From c5c2759ebd9848883d8cd1ffb71090beba567459 Mon Sep 17 00:00:00 2001 From: Sebastian Kupke Date: Tue, 4 Oct 2022 10:51:35 +0200 Subject: [PATCH] Initial commit 2.0 beta 0 --- .eslintrc => .eslintrc.json | 5 +- .prettierrc | 3 +- dist/iwmlib.3rdparty.js | 98959 ++++++++++--------- dist/iwmlib.3rdparty.min.js | 254 +- dist/iwmlib.3rdparty.preload.js | 30 +- dist/iwmlib.3rdparty.preload.min.js | 2 +- dist/iwmlib.js | 740 +- dist/iwmlib.pixi.js | 709 +- gulpfile.js | 4 +- lib/3rdparty/convertPointFromPageToNode.js | 30 +- lib/bootstrap.js | 10 +- lib/bundle.js | 6 +- lib/card/card.js | 173 +- lib/card/highlight.js | 16 +- lib/card/plugin.js | 38 +- lib/card/scatter.js | 12 +- lib/card/theme.js | 2 +- lib/card/wrapper.js | 14 +- lib/doctest.js | 4 +- lib/errors.js | 14 +- lib/events.js | 12 +- lib/flippable.js | 56 +- lib/frames.js | 10 +- lib/imageloader.js | 4 +- lib/index.js | 4 +- lib/interaction.js | 44 +- lib/logging.js | 8 +- lib/pixi/abstractpopup.js | 8 +- lib/pixi/app-fullscreen.html | 2 +- lib/pixi/app-resolution.html | 6 +- lib/pixi/app.html | 30 +- lib/pixi/app.js | 28 +- lib/pixi/application.html | 2 +- lib/pixi/badge.js | 4 +- lib/pixi/blurfilter.js | 4 +- lib/pixi/bundle.js | 4 +- lib/pixi/button.js | 24 +- lib/pixi/buttongroup.js | 32 +- lib/pixi/deepzoom/image.js | 24 +- lib/pixi/deepzoom/loader.js | 6 +- lib/pixi/deepzoom/tileloader.js | 6 +- lib/pixi/deepzoom/tiles.js | 6 +- lib/pixi/flipeffect.js | 22 +- lib/pixi/flippable.js | 22 +- lib/pixi/labeledgraphics.js | 4 +- lib/pixi/list.js | 28 +- lib/pixi/message.js | 2 +- lib/pixi/modal.js | 12 +- lib/pixi/popover.js | 6 +- lib/pixi/popup.js | 8 +- lib/pixi/popupmenu.js | 12 +- lib/pixi/progress.js | 10 +- lib/pixi/scatter.js | 12 +- lib/pixi/scrollbox.js | 13 +- lib/pixi/slider.js | 40 +- lib/pixi/stylus.js | 16 +- lib/pixi/switch.js | 24 +- lib/pixi/test.js | 2 +- lib/pixi/text.js | 24 +- lib/pixi/theme.js | 4 +- lib/pixi/timeline.js | 12 +- lib/pixi/tooltip.js | 12 +- lib/pixi/volatile.js | 4 +- lib/popup.js | 62 +- lib/popupmenu.js | 20 +- lib/scatter.js | 149 +- lib/uitest.js | 68 +- lib/utils.js | 38 +- package-lock.json | 20940 ++-- package.json | 32 +- 70 files changed, 60593 insertions(+), 62354 deletions(-) rename .eslintrc => .eslintrc.json (90%) diff --git a/.eslintrc b/.eslintrc.json similarity index 90% rename from .eslintrc rename to .eslintrc.json index e060e9c..062e6ab 100644 --- a/.eslintrc +++ b/.eslintrc.json @@ -28,5 +28,8 @@ "plugins": [ "prettier" ], - "extends": ["eslint:recommended", "plugin:prettier/recommended"] + "extends": ["eslint:recommended", "plugin:prettier/recommended"], + "rules": { + "comma-dangle": ["error", "never"] + } } diff --git a/.prettierrc b/.prettierrc index 2d84bde..14c8e46 100644 --- a/.prettierrc +++ b/.prettierrc @@ -3,5 +3,6 @@ "jsxSingleQuote": true, "tabWidth": 4, "semi": false, - "printWidth": 120 + "printWidth": 120, + "trailingComma": "none" } diff --git a/dist/iwmlib.3rdparty.js b/dist/iwmlib.3rdparty.js index 12efc1a..350f1f0 100644 --- a/dist/iwmlib.3rdparty.js +++ b/dist/iwmlib.3rdparty.js @@ -4122,22 +4122,12 @@ if (typeof define === 'function' && define.amd) { })(window, document, 'Hammer'); -'use strict'; +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : + typeof define === 'function' && define.amd ? define(factory) : + (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.propagating = factory()); +}(this, (function () { 'use strict'; -(function (factory) { - if (typeof define === 'function' && define.amd) { - // AMD. Register as an anonymous module. - define([], factory); - } else if (typeof exports === 'object') { - // Node. Does not work with strict CommonJS, but - // only CommonJS-like environments that support module.exports, - // like Node. - module.exports = factory(); - } else { - // Browser globals (root is window) - window.propagating = factory(); - } -}(function () { var _firstTarget = null; // singleton, will contain the target element where the touch event started /** @@ -4162,7 +4152,7 @@ if (typeof define === 'function' && define.amd) { * @return {Hammer.Manager} Returns the same hammer instance with extended * functionality */ - return function propagating(hammer, options) { + function propagating(hammer, options) { var _options = options || { preventDefault: false }; @@ -4327,7 +4317,7 @@ if (typeof define === 'function' && define.amd) { event.srcEvent.stopPropagation = function(){ srcStop(); event.stopPropagation(); - } + }; } // attach firstTarget property to the event @@ -4351,41831 +4341,43390 @@ if (typeof define === 'function' && define.amd) { } return wrapper; - }; -})); + } + + return propagating; + +}))); /*! - * pixi.js - v5.3.3 - * Compiled Tue, 04 Aug 2020 16:23:09 UTC + * pixi.js - v6.5.3 + * Compiled Fri, 09 Sep 2022 13:55:20 UTC * * pixi.js is licensed under the MIT License. * http://www.opensource.org/licenses/mit-license */ var PIXI = (function (exports) { - 'use strict'; - - var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; - - function commonjsRequire () { - throw new Error('Dynamic requires are not currently supported by rollup-plugin-commonjs'); - } - - function unwrapExports (x) { - return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; - } - - function createCommonjsModule(fn, module) { - return module = { exports: {} }, fn(module, module.exports), module.exports; - } - - function getCjsExportFromNamespace (n) { - return n && n['default'] || n; - } - - var promise = createCommonjsModule(function (module, exports) { - (function(global){ - - // - // Check for native Promise and it has correct interface - // - - var NativePromise = global['Promise']; - var nativePromiseSupported = - NativePromise && - // Some of these methods are missing from - // Firefox/Chrome experimental implementations - 'resolve' in NativePromise && - 'reject' in NativePromise && - 'all' in NativePromise && - 'race' in NativePromise && - // Older version of the spec had a resolver object - // as the arg rather than a function - (function(){ - var resolve; - new NativePromise(function(r){ resolve = r; }); - return typeof resolve === 'function'; - })(); - - - // - // export if necessary - // - - if ('object' !== 'undefined' && exports) - { - // node.js - exports.Promise = nativePromiseSupported ? NativePromise : Promise; - exports.Polyfill = Promise; - } - else - { - // AMD - if (typeof undefined == 'function' && undefined.amd) - { - undefined(function(){ - return nativePromiseSupported ? NativePromise : Promise; - }); - } - else - { - // in browser add to global - if (!nativePromiseSupported) - { global['Promise'] = Promise; } - } - } - - - // - // Polyfill - // - - var PENDING = 'pending'; - var SEALED = 'sealed'; - var FULFILLED = 'fulfilled'; - var REJECTED = 'rejected'; - var NOOP = function(){}; - - function isArray(value) { - return Object.prototype.toString.call(value) === '[object Array]'; - } - - // async calls - var asyncSetTimer = typeof setImmediate !== 'undefined' ? setImmediate : setTimeout; - var asyncQueue = []; - var asyncTimer; - - function asyncFlush(){ - // run promise callbacks - for (var i = 0; i < asyncQueue.length; i++) - { asyncQueue[i][0](asyncQueue[i][1]); } - - // reset async asyncQueue - asyncQueue = []; - asyncTimer = false; - } - - function asyncCall(callback, arg){ - asyncQueue.push([callback, arg]); - - if (!asyncTimer) - { - asyncTimer = true; - asyncSetTimer(asyncFlush, 0); - } - } - - - function invokeResolver(resolver, promise) { - function resolvePromise(value) { - resolve(promise, value); - } - - function rejectPromise(reason) { - reject(promise, reason); - } - - try { - resolver(resolvePromise, rejectPromise); - } catch(e) { - rejectPromise(e); - } - } - - function invokeCallback(subscriber){ - var owner = subscriber.owner; - var settled = owner.state_; - var value = owner.data_; - var callback = subscriber[settled]; - var promise = subscriber.then; - - if (typeof callback === 'function') - { - settled = FULFILLED; - try { - value = callback(value); - } catch(e) { - reject(promise, e); - } - } - - if (!handleThenable(promise, value)) - { - if (settled === FULFILLED) - { resolve(promise, value); } - - if (settled === REJECTED) - { reject(promise, value); } - } - } - - function handleThenable(promise, value) { - var resolved; - - try { - if (promise === value) - { throw new TypeError('A promises callback cannot return that same promise.'); } - - if (value && (typeof value === 'function' || typeof value === 'object')) - { - var then = value.then; // then should be retrived only once - - if (typeof then === 'function') - { - then.call(value, function(val){ - if (!resolved) - { - resolved = true; - - if (value !== val) - { resolve(promise, val); } - else - { fulfill(promise, val); } - } - }, function(reason){ - if (!resolved) - { - resolved = true; - - reject(promise, reason); - } - }); - - return true; - } - } - } catch (e) { - if (!resolved) - { reject(promise, e); } - - return true; - } - - return false; - } - - function resolve(promise, value){ - if (promise === value || !handleThenable(promise, value)) - { fulfill(promise, value); } - } - - function fulfill(promise, value){ - if (promise.state_ === PENDING) - { - promise.state_ = SEALED; - promise.data_ = value; - - asyncCall(publishFulfillment, promise); - } - } - - function reject(promise, reason){ - if (promise.state_ === PENDING) - { - promise.state_ = SEALED; - promise.data_ = reason; - - asyncCall(publishRejection, promise); - } - } - - function publish(promise) { - var callbacks = promise.then_; - promise.then_ = undefined; - - for (var i = 0; i < callbacks.length; i++) { - invokeCallback(callbacks[i]); - } - } - - function publishFulfillment(promise){ - promise.state_ = FULFILLED; - publish(promise); - } - - function publishRejection(promise){ - promise.state_ = REJECTED; - publish(promise); - } - - /** - * @class - */ - function Promise(resolver){ - if (typeof resolver !== 'function') - { throw new TypeError('Promise constructor takes a function argument'); } - - if (this instanceof Promise === false) - { throw new TypeError('Failed to construct \'Promise\': Please use the \'new\' operator, this object constructor cannot be called as a function.'); } - - this.then_ = []; - - invokeResolver(resolver, this); - } - - Promise.prototype = { - constructor: Promise, - - state_: PENDING, - then_: null, - data_: undefined, - - then: function(onFulfillment, onRejection){ - var subscriber = { - owner: this, - then: new this.constructor(NOOP), - fulfilled: onFulfillment, - rejected: onRejection - }; - - if (this.state_ === FULFILLED || this.state_ === REJECTED) - { - // already resolved, call callback async - asyncCall(invokeCallback, subscriber); - } - else - { - // subscribe - this.then_.push(subscriber); - } - - return subscriber.then; - }, - - 'catch': function(onRejection) { - return this.then(null, onRejection); - } - }; - - Promise.all = function(promises){ - var Class = this; - - if (!isArray(promises)) - { throw new TypeError('You must pass an array to Promise.all().'); } - - return new Class(function(resolve, reject){ - var results = []; - var remaining = 0; - - function resolver(index){ - remaining++; - return function(value){ - results[index] = value; - if (!--remaining) - { resolve(results); } - }; - } - - for (var i = 0, promise; i < promises.length; i++) - { - promise = promises[i]; - - if (promise && typeof promise.then === 'function') - { promise.then(resolver(i), reject); } - else - { results[i] = promise; } - } - - if (!remaining) - { resolve(results); } - }); - }; - - Promise.race = function(promises){ - var Class = this; - - if (!isArray(promises)) - { throw new TypeError('You must pass an array to Promise.race().'); } - - return new Class(function(resolve, reject) { - for (var i = 0, promise; i < promises.length; i++) - { - promise = promises[i]; - - if (promise && typeof promise.then === 'function') - { promise.then(resolve, reject); } - else - { resolve(promise); } - } - }); - }; - - Promise.resolve = function(value){ - var Class = this; - - if (value && typeof value === 'object' && value.constructor === Class) - { return value; } - - return new Class(function(resolve){ - resolve(value); - }); - }; - - Promise.reject = function(reason){ - var Class = this; - - return new Class(function(resolve, reject){ - reject(reason); - }); - }; - - })(typeof window != 'undefined' ? window : typeof commonjsGlobal != 'undefined' ? commonjsGlobal : typeof self != 'undefined' ? self : commonjsGlobal); - }); - var promise_1 = promise.Promise; - var promise_2 = promise.Polyfill; - - /* - object-assign - (c) Sindre Sorhus - @license MIT - */ - - 'use strict'; - /* eslint-disable no-unused-vars */ - var getOwnPropertySymbols = Object.getOwnPropertySymbols; - var hasOwnProperty = Object.prototype.hasOwnProperty; - var propIsEnumerable = Object.prototype.propertyIsEnumerable; - - function toObject(val) { - if (val === null || val === undefined) { - throw new TypeError('Object.assign cannot be called with null or undefined'); - } - - return Object(val); - } - - function shouldUseNative() { - try { - if (!Object.assign) { - return false; - } - - // Detect buggy property enumeration order in older V8 versions. - - // https://bugs.chromium.org/p/v8/issues/detail?id=4118 - var test1 = new String('abc'); // eslint-disable-line no-new-wrappers - test1[5] = 'de'; - if (Object.getOwnPropertyNames(test1)[0] === '5') { - return false; - } - - // https://bugs.chromium.org/p/v8/issues/detail?id=3056 - var test2 = {}; - for (var i = 0; i < 10; i++) { - test2['_' + String.fromCharCode(i)] = i; - } - var order2 = Object.getOwnPropertyNames(test2).map(function (n) { - return test2[n]; - }); - if (order2.join('') !== '0123456789') { - return false; - } - - // https://bugs.chromium.org/p/v8/issues/detail?id=3056 - var test3 = {}; - 'abcdefghijklmnopqrst'.split('').forEach(function (letter) { - test3[letter] = letter; - }); - if (Object.keys(Object.assign({}, test3)).join('') !== - 'abcdefghijklmnopqrst') { - return false; - } - - return true; - } catch (err) { - // We don't expect any of the above to throw, but better to be safe. - return false; - } - } - - var objectAssign = shouldUseNative() ? Object.assign : function (target, source) { - var arguments$1 = arguments; - - var from; - var to = toObject(target); - var symbols; - - for (var s = 1; s < arguments.length; s++) { - from = Object(arguments$1[s]); - - for (var key in from) { - if (hasOwnProperty.call(from, key)) { - to[key] = from[key]; - } - } - - if (getOwnPropertySymbols) { - symbols = getOwnPropertySymbols(from); - for (var i = 0; i < symbols.length; i++) { - if (propIsEnumerable.call(from, symbols[i])) { - to[symbols[i]] = from[symbols[i]]; - } - } - } - } - - return to; - }; - - /*! - * @pixi/polyfill - v5.3.3 - * Compiled Tue, 04 Aug 2020 16:23:09 UTC - * - * @pixi/polyfill is licensed under the MIT License. - * http://www.opensource.org/licenses/mit-license - */ - - // Support for IE 9 - 11 which does not include Promises - if (!window.Promise) { - window.Promise = promise_2; - } - - // References: - if (!Object.assign) { - Object.assign = objectAssign; - } - - // References: - // http://paulirish.com/2011/requestanimationframe-for-smart-animating/ - // https://gist.github.com/1579671 - // http://updates.html5rocks.com/2012/05/requestAnimationFrame-API-now-with-sub-millisecond-precision - // https://gist.github.com/timhall/4078614 - // https://github.com/Financial-Times/polyfill-service/tree/master/polyfills/requestAnimationFrame - // Expected to be used with Browserfiy - // Browserify automatically detects the use of `global` and passes the - // correct reference of `global`, `self`, and finally `window` - var ONE_FRAME_TIME = 16; - // Date.now - if (!(Date.now && Date.prototype.getTime)) { - Date.now = function now() { - return new Date().getTime(); - }; - } - // performance.now - if (!(window.performance && window.performance.now)) { - var startTime_1 = Date.now(); - if (!window.performance) { - window.performance = {}; - } - window.performance.now = function () { return Date.now() - startTime_1; }; - } - // requestAnimationFrame - var lastTime = Date.now(); - var vendors = ['ms', 'moz', 'webkit', 'o']; - for (var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) { - var p = vendors[x]; - window.requestAnimationFrame = window[p + "RequestAnimationFrame"]; - window.cancelAnimationFrame = window[p + "CancelAnimationFrame"] - || window[p + "CancelRequestAnimationFrame"]; - } - if (!window.requestAnimationFrame) { - window.requestAnimationFrame = function (callback) { - if (typeof callback !== 'function') { - throw new TypeError(callback + "is not a function"); - } - var currentTime = Date.now(); - var delay = ONE_FRAME_TIME + lastTime - currentTime; - if (delay < 0) { - delay = 0; - } - lastTime = currentTime; - return window.setTimeout(function () { - lastTime = Date.now(); - callback(performance.now()); - }, delay); - }; - } - if (!window.cancelAnimationFrame) { - window.cancelAnimationFrame = function (id) { return clearTimeout(id); }; - } - - // References: - // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/sign - if (!Math.sign) { - Math.sign = function mathSign(x) { - x = Number(x); - if (x === 0 || isNaN(x)) { - return x; - } - return x > 0 ? 1 : -1; - }; - } - - // References: - // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isInteger - if (!Number.isInteger) { - Number.isInteger = function numberIsInteger(value) { - return typeof value === 'number' && isFinite(value) && Math.floor(value) === value; - }; - } - - if (!window.ArrayBuffer) { - window.ArrayBuffer = Array; - } - if (!window.Float32Array) { - window.Float32Array = Array; - } - if (!window.Uint32Array) { - window.Uint32Array = Array; - } - if (!window.Uint16Array) { - window.Uint16Array = Array; - } - if (!window.Uint8Array) { - window.Uint8Array = Array; - } - if (!window.Int32Array) { - window.Int32Array = Array; - } - - var appleIphone = /iPhone/i; - var appleIpod = /iPod/i; - var appleTablet = /iPad/i; - var appleUniversal = /\biOS-universal(?:.+)Mac\b/i; - var androidPhone = /\bAndroid(?:.+)Mobile\b/i; - var androidTablet = /Android/i; - var amazonPhone = /(?:SD4930UR|\bSilk(?:.+)Mobile\b)/i; - var amazonTablet = /Silk/i; - var windowsPhone = /Windows Phone/i; - var windowsTablet = /\bWindows(?:.+)ARM\b/i; - var otherBlackBerry = /BlackBerry/i; - var otherBlackBerry10 = /BB10/i; - var otherOpera = /Opera Mini/i; - var otherChrome = /\b(CriOS|Chrome)(?:.+)Mobile/i; - var otherFirefox = /Mobile(?:.+)Firefox\b/i; - var isAppleTabletOnIos13 = function (navigator) { - return (typeof navigator !== 'undefined' && - navigator.platform === 'MacIntel' && - typeof navigator.maxTouchPoints === 'number' && - navigator.maxTouchPoints > 1 && - typeof MSStream === 'undefined'); - }; - function createMatch(userAgent) { - return function (regex) { return regex.test(userAgent); }; - } - function isMobile(param) { - var nav = { - userAgent: '', - platform: '', - maxTouchPoints: 0 - }; - if (!param && typeof navigator !== 'undefined') { - nav = { - userAgent: navigator.userAgent, - platform: navigator.platform, - maxTouchPoints: navigator.maxTouchPoints || 0 - }; - } - else if (typeof param === 'string') { - nav.userAgent = param; - } - else if (param && param.userAgent) { - nav = { - userAgent: param.userAgent, - platform: param.platform, - maxTouchPoints: param.maxTouchPoints || 0 - }; - } - var userAgent = nav.userAgent; - var tmp = userAgent.split('[FBAN'); - if (typeof tmp[1] !== 'undefined') { - userAgent = tmp[0]; - } - tmp = userAgent.split('Twitter'); - if (typeof tmp[1] !== 'undefined') { - userAgent = tmp[0]; - } - var match = createMatch(userAgent); - var result = { - apple: { - phone: match(appleIphone) && !match(windowsPhone), - ipod: match(appleIpod), - tablet: !match(appleIphone) && - (match(appleTablet) || isAppleTabletOnIos13(nav)) && - !match(windowsPhone), - universal: match(appleUniversal), - device: (match(appleIphone) || - match(appleIpod) || - match(appleTablet) || - match(appleUniversal) || - isAppleTabletOnIos13(nav)) && - !match(windowsPhone) - }, - amazon: { - phone: match(amazonPhone), - tablet: !match(amazonPhone) && match(amazonTablet), - device: match(amazonPhone) || match(amazonTablet) - }, - android: { - phone: (!match(windowsPhone) && match(amazonPhone)) || - (!match(windowsPhone) && match(androidPhone)), - tablet: !match(windowsPhone) && - !match(amazonPhone) && - !match(androidPhone) && - (match(amazonTablet) || match(androidTablet)), - device: (!match(windowsPhone) && - (match(amazonPhone) || - match(amazonTablet) || - match(androidPhone) || - match(androidTablet))) || - match(/\bokhttp\b/i) - }, - windows: { - phone: match(windowsPhone), - tablet: match(windowsTablet), - device: match(windowsPhone) || match(windowsTablet) - }, - other: { - blackberry: match(otherBlackBerry), - blackberry10: match(otherBlackBerry10), - opera: match(otherOpera), - firefox: match(otherFirefox), - chrome: match(otherChrome), - device: match(otherBlackBerry) || - match(otherBlackBerry10) || - match(otherOpera) || - match(otherFirefox) || - match(otherChrome) - }, - any: false, - phone: false, - tablet: false - }; - result.any = - result.apple.device || - result.android.device || - result.windows.device || - result.other.device; - result.phone = - result.apple.phone || result.android.phone || result.windows.phone; - result.tablet = - result.apple.tablet || result.android.tablet || result.windows.tablet; - return result; - } - - /*! - * @pixi/settings - v5.3.3 - * Compiled Tue, 04 Aug 2020 16:23:09 UTC - * - * @pixi/settings is licensed under the MIT License. - * http://www.opensource.org/licenses/mit-license - */ - - // The ESM/CJS versions of ismobilejs only - var isMobile$1 = isMobile(window.navigator); - - /** - * The maximum recommended texture units to use. - * In theory the bigger the better, and for desktop we'll use as many as we can. - * But some mobile devices slow down if there is to many branches in the shader. - * So in practice there seems to be a sweet spot size that varies depending on the device. - * - * In v4, all mobile devices were limited to 4 texture units because for this. - * In v5, we allow all texture units to be used on modern Apple or Android devices. - * - * @private - * @param {number} max - * @returns {number} - */ - function maxRecommendedTextures(max) { - var allowMax = true; - if (isMobile$1.tablet || isMobile$1.phone) { - if (isMobile$1.apple.device) { - var match = (navigator.userAgent).match(/OS (\d+)_(\d+)?/); - if (match) { - var majorVersion = parseInt(match[1], 10); - // Limit texture units on devices below iOS 11, which will be older hardware - if (majorVersion < 11) { - allowMax = false; - } - } - } - if (isMobile$1.android.device) { - var match = (navigator.userAgent).match(/Android\s([0-9.]*)/); - if (match) { - var majorVersion = parseInt(match[1], 10); - // Limit texture units on devices below Android 7 (Nougat), which will be older hardware - if (majorVersion < 7) { - allowMax = false; - } - } - } - } - return allowMax ? max : 4; - } - - /** - * Uploading the same buffer multiple times in a single frame can cause performance issues. - * Apparent on iOS so only check for that at the moment - * This check may become more complex if this issue pops up elsewhere. - * - * @private - * @returns {boolean} - */ - function canUploadSameBuffer() { - return !isMobile$1.apple.device; - } - - /** - * User's customizable globals for overriding the default PIXI settings, such - * as a renderer's default resolution, framerate, float precision, etc. - * @example - * // Use the native window resolution as the default resolution - * // will support high-density displays when rendering - * PIXI.settings.RESOLUTION = window.devicePixelRatio; - * - * // Disable interpolation when scaling, will make texture be pixelated - * PIXI.settings.SCALE_MODE = PIXI.SCALE_MODES.NEAREST; - * @namespace PIXI.settings - */ - var settings = { - /** - * If set to true WebGL will attempt make textures mimpaped by default. - * Mipmapping will only succeed if the base texture uploaded has power of two dimensions. - * - * @static - * @name MIPMAP_TEXTURES - * @memberof PIXI.settings - * @type {PIXI.MIPMAP_MODES} - * @default PIXI.MIPMAP_MODES.POW2 - */ - MIPMAP_TEXTURES: 1, - /** - * Default anisotropic filtering level of textures. - * Usually from 0 to 16 - * - * @static - * @name ANISOTROPIC_LEVEL - * @memberof PIXI.settings - * @type {number} - * @default 0 - */ - ANISOTROPIC_LEVEL: 0, - /** - * Default resolution / device pixel ratio of the renderer. - * - * @static - * @name RESOLUTION - * @memberof PIXI.settings - * @type {number} - * @default 1 - */ - RESOLUTION: 1, - /** - * Default filter resolution. - * - * @static - * @name FILTER_RESOLUTION - * @memberof PIXI.settings - * @type {number} - * @default 1 - */ - FILTER_RESOLUTION: 1, - /** - * The maximum textures that this device supports. - * - * @static - * @name SPRITE_MAX_TEXTURES - * @memberof PIXI.settings - * @type {number} - * @default 32 - */ - SPRITE_MAX_TEXTURES: maxRecommendedTextures(32), - // TODO: maybe change to SPRITE.BATCH_SIZE: 2000 - // TODO: maybe add PARTICLE.BATCH_SIZE: 15000 - /** - * The default sprite batch size. - * - * The default aims to balance desktop and mobile devices. - * - * @static - * @name SPRITE_BATCH_SIZE - * @memberof PIXI.settings - * @type {number} - * @default 4096 - */ - SPRITE_BATCH_SIZE: 4096, - /** - * The default render options if none are supplied to {@link PIXI.Renderer} - * or {@link PIXI.CanvasRenderer}. - * - * @static - * @name RENDER_OPTIONS - * @memberof PIXI.settings - * @type {object} - * @property {HTMLCanvasElement} view=null - * @property {number} resolution=1 - * @property {boolean} antialias=false - * @property {boolean} autoDensity=false - * @property {boolean} transparent=false - * @property {number} backgroundColor=0x000000 - * @property {boolean} clearBeforeRender=true - * @property {boolean} preserveDrawingBuffer=false - * @property {number} width=800 - * @property {number} height=600 - * @property {boolean} legacy=false - */ - RENDER_OPTIONS: { - view: null, - antialias: false, - autoDensity: false, - transparent: false, - backgroundColor: 0x000000, - clearBeforeRender: true, - preserveDrawingBuffer: false, - width: 800, - height: 600, - legacy: false, - }, - /** - * Default Garbage Collection mode. - * - * @static - * @name GC_MODE - * @memberof PIXI.settings - * @type {PIXI.GC_MODES} - * @default PIXI.GC_MODES.AUTO - */ - GC_MODE: 0, - /** - * Default Garbage Collection max idle. - * - * @static - * @name GC_MAX_IDLE - * @memberof PIXI.settings - * @type {number} - * @default 3600 - */ - GC_MAX_IDLE: 60 * 60, - /** - * Default Garbage Collection maximum check count. - * - * @static - * @name GC_MAX_CHECK_COUNT - * @memberof PIXI.settings - * @type {number} - * @default 600 - */ - GC_MAX_CHECK_COUNT: 60 * 10, - /** - * Default wrap modes that are supported by pixi. - * - * @static - * @name WRAP_MODE - * @memberof PIXI.settings - * @type {PIXI.WRAP_MODES} - * @default PIXI.WRAP_MODES.CLAMP - */ - WRAP_MODE: 33071, - /** - * Default scale mode for textures. - * - * @static - * @name SCALE_MODE - * @memberof PIXI.settings - * @type {PIXI.SCALE_MODES} - * @default PIXI.SCALE_MODES.LINEAR - */ - SCALE_MODE: 1, - /** - * Default specify float precision in vertex shader. - * - * @static - * @name PRECISION_VERTEX - * @memberof PIXI.settings - * @type {PIXI.PRECISION} - * @default PIXI.PRECISION.HIGH - */ - PRECISION_VERTEX: 'highp', - /** - * Default specify float precision in fragment shader. - * iOS is best set at highp due to https://github.com/pixijs/pixi.js/issues/3742 - * - * @static - * @name PRECISION_FRAGMENT - * @memberof PIXI.settings - * @type {PIXI.PRECISION} - * @default PIXI.PRECISION.MEDIUM - */ - PRECISION_FRAGMENT: isMobile$1.apple.device ? 'highp' : 'mediump', - /** - * Can we upload the same buffer in a single frame? - * - * @static - * @name CAN_UPLOAD_SAME_BUFFER - * @memberof PIXI.settings - * @type {boolean} - */ - CAN_UPLOAD_SAME_BUFFER: canUploadSameBuffer(), - /** - * Enables bitmap creation before image load. This feature is experimental. - * - * @static - * @name CREATE_IMAGE_BITMAP - * @memberof PIXI.settings - * @type {boolean} - * @default false - */ - CREATE_IMAGE_BITMAP: false, - /** - * If true PixiJS will Math.floor() x/y values when rendering, stopping pixel interpolation. - * Advantages can include sharper image quality (like text) and faster rendering on canvas. - * The main disadvantage is movement of objects may appear less smooth. - * - * @static - * @constant - * @memberof PIXI.settings - * @type {boolean} - * @default false - */ - ROUND_PIXELS: false, - }; - - var eventemitter3 = createCommonjsModule(function (module) { - 'use strict'; - - var has = Object.prototype.hasOwnProperty - , prefix = '~'; - - /** - * Constructor to create a storage for our `EE` objects. - * An `Events` instance is a plain object whose properties are event names. - * - * @constructor - * @private - */ - function Events() {} - - // - // We try to not inherit from `Object.prototype`. In some engines creating an - // instance in this way is faster than calling `Object.create(null)` directly. - // If `Object.create(null)` is not supported we prefix the event names with a - // character to make sure that the built-in object properties are not - // overridden or used as an attack vector. - // - if (Object.create) { - Events.prototype = Object.create(null); - - // - // This hack is needed because the `__proto__` property is still inherited in - // some old browsers like Android 4, iPhone 5.1, Opera 11 and Safari 5. - // - if (!new Events().__proto__) { prefix = false; } - } - - /** - * Representation of a single event listener. - * - * @param {Function} fn The listener function. - * @param {*} context The context to invoke the listener with. - * @param {Boolean} [once=false] Specify if the listener is a one-time listener. - * @constructor - * @private - */ - function EE(fn, context, once) { - this.fn = fn; - this.context = context; - this.once = once || false; - } - - /** - * Add a listener for a given event. - * - * @param {EventEmitter} emitter Reference to the `EventEmitter` instance. - * @param {(String|Symbol)} event The event name. - * @param {Function} fn The listener function. - * @param {*} context The context to invoke the listener with. - * @param {Boolean} once Specify if the listener is a one-time listener. - * @returns {EventEmitter} - * @private - */ - function addListener(emitter, event, fn, context, once) { - if (typeof fn !== 'function') { - throw new TypeError('The listener must be a function'); - } - - var listener = new EE(fn, context || emitter, once) - , evt = prefix ? prefix + event : event; - - if (!emitter._events[evt]) { emitter._events[evt] = listener, emitter._eventsCount++; } - else if (!emitter._events[evt].fn) { emitter._events[evt].push(listener); } - else { emitter._events[evt] = [emitter._events[evt], listener]; } - - return emitter; - } - - /** - * Clear event by name. - * - * @param {EventEmitter} emitter Reference to the `EventEmitter` instance. - * @param {(String|Symbol)} evt The Event name. - * @private - */ - function clearEvent(emitter, evt) { - if (--emitter._eventsCount === 0) { emitter._events = new Events(); } - else { delete emitter._events[evt]; } - } - - /** - * Minimal `EventEmitter` interface that is molded against the Node.js - * `EventEmitter` interface. - * - * @constructor - * @public - */ - function EventEmitter() { - this._events = new Events(); - this._eventsCount = 0; - } - - /** - * Return an array listing the events for which the emitter has registered - * listeners. - * - * @returns {Array} - * @public - */ - EventEmitter.prototype.eventNames = function eventNames() { - var names = [] - , events - , name; - - if (this._eventsCount === 0) { return names; } - - for (name in (events = this._events)) { - if (has.call(events, name)) { names.push(prefix ? name.slice(1) : name); } - } - - if (Object.getOwnPropertySymbols) { - return names.concat(Object.getOwnPropertySymbols(events)); - } - - return names; - }; - - /** - * Return the listeners registered for a given event. - * - * @param {(String|Symbol)} event The event name. - * @returns {Array} The registered listeners. - * @public - */ - EventEmitter.prototype.listeners = function listeners(event) { - var evt = prefix ? prefix + event : event - , handlers = this._events[evt]; - - if (!handlers) { return []; } - if (handlers.fn) { return [handlers.fn]; } - - for (var i = 0, l = handlers.length, ee = new Array(l); i < l; i++) { - ee[i] = handlers[i].fn; - } - - return ee; - }; - - /** - * Return the number of listeners listening to a given event. - * - * @param {(String|Symbol)} event The event name. - * @returns {Number} The number of listeners. - * @public - */ - EventEmitter.prototype.listenerCount = function listenerCount(event) { - var evt = prefix ? prefix + event : event - , listeners = this._events[evt]; - - if (!listeners) { return 0; } - if (listeners.fn) { return 1; } - return listeners.length; - }; - - /** - * Calls each of the listeners registered for a given event. - * - * @param {(String|Symbol)} event The event name. - * @returns {Boolean} `true` if the event had listeners, else `false`. - * @public - */ - EventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) { - var arguments$1 = arguments; - - var evt = prefix ? prefix + event : event; - - if (!this._events[evt]) { return false; } - - var listeners = this._events[evt] - , len = arguments.length - , args - , i; - - if (listeners.fn) { - if (listeners.once) { this.removeListener(event, listeners.fn, undefined, true); } - - switch (len) { - case 1: return listeners.fn.call(listeners.context), true; - case 2: return listeners.fn.call(listeners.context, a1), true; - case 3: return listeners.fn.call(listeners.context, a1, a2), true; - case 4: return listeners.fn.call(listeners.context, a1, a2, a3), true; - case 5: return listeners.fn.call(listeners.context, a1, a2, a3, a4), true; - case 6: return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true; - } - - for (i = 1, args = new Array(len -1); i < len; i++) { - args[i - 1] = arguments$1[i]; - } - - listeners.fn.apply(listeners.context, args); - } else { - var length = listeners.length - , j; - - for (i = 0; i < length; i++) { - if (listeners[i].once) { this.removeListener(event, listeners[i].fn, undefined, true); } - - switch (len) { - case 1: listeners[i].fn.call(listeners[i].context); break; - case 2: listeners[i].fn.call(listeners[i].context, a1); break; - case 3: listeners[i].fn.call(listeners[i].context, a1, a2); break; - case 4: listeners[i].fn.call(listeners[i].context, a1, a2, a3); break; - default: - if (!args) { for (j = 1, args = new Array(len -1); j < len; j++) { - args[j - 1] = arguments$1[j]; - } } - - listeners[i].fn.apply(listeners[i].context, args); - } - } - } - - return true; - }; - - /** - * Add a listener for a given event. - * - * @param {(String|Symbol)} event The event name. - * @param {Function} fn The listener function. - * @param {*} [context=this] The context to invoke the listener with. - * @returns {EventEmitter} `this`. - * @public - */ - EventEmitter.prototype.on = function on(event, fn, context) { - return addListener(this, event, fn, context, false); - }; - - /** - * Add a one-time listener for a given event. - * - * @param {(String|Symbol)} event The event name. - * @param {Function} fn The listener function. - * @param {*} [context=this] The context to invoke the listener with. - * @returns {EventEmitter} `this`. - * @public - */ - EventEmitter.prototype.once = function once(event, fn, context) { - return addListener(this, event, fn, context, true); - }; - - /** - * Remove the listeners of a given event. - * - * @param {(String|Symbol)} event The event name. - * @param {Function} fn Only remove the listeners that match this function. - * @param {*} context Only remove the listeners that have this context. - * @param {Boolean} once Only remove one-time listeners. - * @returns {EventEmitter} `this`. - * @public - */ - EventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) { - var evt = prefix ? prefix + event : event; - - if (!this._events[evt]) { return this; } - if (!fn) { - clearEvent(this, evt); - return this; - } - - var listeners = this._events[evt]; - - if (listeners.fn) { - if ( - listeners.fn === fn && - (!once || listeners.once) && - (!context || listeners.context === context) - ) { - clearEvent(this, evt); - } - } else { - for (var i = 0, events = [], length = listeners.length; i < length; i++) { - if ( - listeners[i].fn !== fn || - (once && !listeners[i].once) || - (context && listeners[i].context !== context) - ) { - events.push(listeners[i]); - } - } - - // - // Reset the array, or remove it completely if we have no more listeners. - // - if (events.length) { this._events[evt] = events.length === 1 ? events[0] : events; } - else { clearEvent(this, evt); } - } - - return this; - }; - - /** - * Remove all listeners, or those of the specified event. - * - * @param {(String|Symbol)} [event] The event name. - * @returns {EventEmitter} `this`. - * @public - */ - EventEmitter.prototype.removeAllListeners = function removeAllListeners(event) { - var evt; - - if (event) { - evt = prefix ? prefix + event : event; - if (this._events[evt]) { clearEvent(this, evt); } - } else { - this._events = new Events(); - this._eventsCount = 0; - } - - return this; - }; - - // - // Alias methods names because people roll like that. - // - EventEmitter.prototype.off = EventEmitter.prototype.removeListener; - EventEmitter.prototype.addListener = EventEmitter.prototype.on; - - // - // Expose the prefix. - // - EventEmitter.prefixed = prefix; - - // - // Allow `EventEmitter` to be imported as module namespace. - // - EventEmitter.EventEmitter = EventEmitter; - - // - // Expose the module. - // - if ('undefined' !== 'object') { - module.exports = EventEmitter; - } - }); - - 'use strict'; - - var earcut_1 = earcut; - var default_1 = earcut; - - function earcut(data, holeIndices, dim) { - - dim = dim || 2; - - var hasHoles = holeIndices && holeIndices.length, - outerLen = hasHoles ? holeIndices[0] * dim : data.length, - outerNode = linkedList(data, 0, outerLen, dim, true), - triangles = []; - - if (!outerNode || outerNode.next === outerNode.prev) { return triangles; } - - var minX, minY, maxX, maxY, x, y, invSize; - - if (hasHoles) { outerNode = eliminateHoles(data, holeIndices, outerNode, dim); } - - // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox - if (data.length > 80 * dim) { - minX = maxX = data[0]; - minY = maxY = data[1]; - - for (var i = dim; i < outerLen; i += dim) { - x = data[i]; - y = data[i + 1]; - if (x < minX) { minX = x; } - if (y < minY) { minY = y; } - if (x > maxX) { maxX = x; } - if (y > maxY) { maxY = y; } - } - - // minX, minY and invSize are later used to transform coords into integers for z-order calculation - invSize = Math.max(maxX - minX, maxY - minY); - invSize = invSize !== 0 ? 1 / invSize : 0; - } - - earcutLinked(outerNode, triangles, dim, minX, minY, invSize); - - return triangles; - } - - // create a circular doubly linked list from polygon points in the specified winding order - function linkedList(data, start, end, dim, clockwise) { - var i, last; - - if (clockwise === (signedArea(data, start, end, dim) > 0)) { - for (i = start; i < end; i += dim) { last = insertNode(i, data[i], data[i + 1], last); } - } else { - for (i = end - dim; i >= start; i -= dim) { last = insertNode(i, data[i], data[i + 1], last); } - } - - if (last && equals(last, last.next)) { - removeNode(last); - last = last.next; - } - - return last; - } - - // eliminate colinear or duplicate points - function filterPoints(start, end) { - if (!start) { return start; } - if (!end) { end = start; } - - var p = start, - again; - do { - again = false; - - if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) { - removeNode(p); - p = end = p.prev; - if (p === p.next) { break; } - again = true; - - } else { - p = p.next; - } - } while (again || p !== end); - - return end; - } - - // main ear slicing loop which triangulates a polygon (given as a linked list) - function earcutLinked(ear, triangles, dim, minX, minY, invSize, pass) { - if (!ear) { return; } - - // interlink polygon nodes in z-order - if (!pass && invSize) { indexCurve(ear, minX, minY, invSize); } - - var stop = ear, - prev, next; - - // iterate through ears, slicing them one by one - while (ear.prev !== ear.next) { - prev = ear.prev; - next = ear.next; - - if (invSize ? isEarHashed(ear, minX, minY, invSize) : isEar(ear)) { - // cut off the triangle - triangles.push(prev.i / dim); - triangles.push(ear.i / dim); - triangles.push(next.i / dim); - - removeNode(ear); - - // skipping the next vertex leads to less sliver triangles - ear = next.next; - stop = next.next; - - continue; - } - - ear = next; - - // if we looped through the whole remaining polygon and can't find any more ears - if (ear === stop) { - // try filtering points and slicing again - if (!pass) { - earcutLinked(filterPoints(ear), triangles, dim, minX, minY, invSize, 1); - - // if this didn't work, try curing all small self-intersections locally - } else if (pass === 1) { - ear = cureLocalIntersections(filterPoints(ear), triangles, dim); - earcutLinked(ear, triangles, dim, minX, minY, invSize, 2); - - // as a last resort, try splitting the remaining polygon into two - } else if (pass === 2) { - splitEarcut(ear, triangles, dim, minX, minY, invSize); - } - - break; - } - } - } - - // check whether a polygon node forms a valid ear with adjacent nodes - function isEar(ear) { - var a = ear.prev, - b = ear, - c = ear.next; - - if (area(a, b, c) >= 0) { return false; } // reflex, can't be an ear - - // now make sure we don't have other points inside the potential ear - var p = ear.next.next; - - while (p !== ear.prev) { - if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) && - area(p.prev, p, p.next) >= 0) { return false; } - p = p.next; - } - - return true; - } - - function isEarHashed(ear, minX, minY, invSize) { - var a = ear.prev, - b = ear, - c = ear.next; - - if (area(a, b, c) >= 0) { return false; } // reflex, can't be an ear - - // triangle bbox; min & max are calculated like this for speed - var minTX = a.x < b.x ? (a.x < c.x ? a.x : c.x) : (b.x < c.x ? b.x : c.x), - minTY = a.y < b.y ? (a.y < c.y ? a.y : c.y) : (b.y < c.y ? b.y : c.y), - maxTX = a.x > b.x ? (a.x > c.x ? a.x : c.x) : (b.x > c.x ? b.x : c.x), - maxTY = a.y > b.y ? (a.y > c.y ? a.y : c.y) : (b.y > c.y ? b.y : c.y); - - // z-order range for the current triangle bbox; - var minZ = zOrder(minTX, minTY, minX, minY, invSize), - maxZ = zOrder(maxTX, maxTY, minX, minY, invSize); - - var p = ear.prevZ, - n = ear.nextZ; - - // look for points inside the triangle in both directions - while (p && p.z >= minZ && n && n.z <= maxZ) { - if (p !== ear.prev && p !== ear.next && - pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) && - area(p.prev, p, p.next) >= 0) { return false; } - p = p.prevZ; - - if (n !== ear.prev && n !== ear.next && - pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, n.x, n.y) && - area(n.prev, n, n.next) >= 0) { return false; } - n = n.nextZ; - } - - // look for remaining points in decreasing z-order - while (p && p.z >= minZ) { - if (p !== ear.prev && p !== ear.next && - pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) && - area(p.prev, p, p.next) >= 0) { return false; } - p = p.prevZ; - } - - // look for remaining points in increasing z-order - while (n && n.z <= maxZ) { - if (n !== ear.prev && n !== ear.next && - pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, n.x, n.y) && - area(n.prev, n, n.next) >= 0) { return false; } - n = n.nextZ; - } - - return true; - } - - // go through all polygon nodes and cure small local self-intersections - function cureLocalIntersections(start, triangles, dim) { - var p = start; - do { - var a = p.prev, - b = p.next.next; - - if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) { - - triangles.push(a.i / dim); - triangles.push(p.i / dim); - triangles.push(b.i / dim); - - // remove two nodes involved - removeNode(p); - removeNode(p.next); - - p = start = b; - } - p = p.next; - } while (p !== start); - - return filterPoints(p); - } - - // try splitting polygon into two and triangulate them independently - function splitEarcut(start, triangles, dim, minX, minY, invSize) { - // look for a valid diagonal that divides the polygon into two - var a = start; - do { - var b = a.next.next; - while (b !== a.prev) { - if (a.i !== b.i && isValidDiagonal(a, b)) { - // split the polygon in two by the diagonal - var c = splitPolygon(a, b); - - // filter colinear points around the cuts - a = filterPoints(a, a.next); - c = filterPoints(c, c.next); - - // run earcut on each half - earcutLinked(a, triangles, dim, minX, minY, invSize); - earcutLinked(c, triangles, dim, minX, minY, invSize); - return; - } - b = b.next; - } - a = a.next; - } while (a !== start); - } - - // link every hole into the outer loop, producing a single-ring polygon without holes - function eliminateHoles(data, holeIndices, outerNode, dim) { - var queue = [], - i, len, start, end, list; - - for (i = 0, len = holeIndices.length; i < len; i++) { - start = holeIndices[i] * dim; - end = i < len - 1 ? holeIndices[i + 1] * dim : data.length; - list = linkedList(data, start, end, dim, false); - if (list === list.next) { list.steiner = true; } - queue.push(getLeftmost(list)); - } - - queue.sort(compareX); - - // process holes from left to right - for (i = 0; i < queue.length; i++) { - eliminateHole(queue[i], outerNode); - outerNode = filterPoints(outerNode, outerNode.next); - } - - return outerNode; - } - - function compareX(a, b) { - return a.x - b.x; - } - - // find a bridge between vertices that connects hole with an outer ring and and link it - function eliminateHole(hole, outerNode) { - outerNode = findHoleBridge(hole, outerNode); - if (outerNode) { - var b = splitPolygon(outerNode, hole); - - // filter collinear points around the cuts - filterPoints(outerNode, outerNode.next); - filterPoints(b, b.next); - } - } - - // David Eberly's algorithm for finding a bridge between hole and outer polygon - function findHoleBridge(hole, outerNode) { - var p = outerNode, - hx = hole.x, - hy = hole.y, - qx = -Infinity, - m; - - // find a segment intersected by a ray from the hole's leftmost point to the left; - // segment's endpoint with lesser x will be potential connection point - do { - if (hy <= p.y && hy >= p.next.y && p.next.y !== p.y) { - var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y); - if (x <= hx && x > qx) { - qx = x; - if (x === hx) { - if (hy === p.y) { return p; } - if (hy === p.next.y) { return p.next; } - } - m = p.x < p.next.x ? p : p.next; - } - } - p = p.next; - } while (p !== outerNode); - - if (!m) { return null; } - - if (hx === qx) { return m; } // hole touches outer segment; pick leftmost endpoint - - // look for points inside the triangle of hole point, segment intersection and endpoint; - // if there are no points found, we have a valid connection; - // otherwise choose the point of the minimum angle with the ray as connection point - - var stop = m, - mx = m.x, - my = m.y, - tanMin = Infinity, - tan; - - p = m; - - do { - if (hx >= p.x && p.x >= mx && hx !== p.x && - pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) { - - tan = Math.abs(hy - p.y) / (hx - p.x); // tangential - - if (locallyInside(p, hole) && - (tan < tanMin || (tan === tanMin && (p.x > m.x || (p.x === m.x && sectorContainsSector(m, p)))))) { - m = p; - tanMin = tan; - } - } - - p = p.next; - } while (p !== stop); - - return m; - } - - // whether sector in vertex m contains sector in vertex p in the same coordinates - function sectorContainsSector(m, p) { - return area(m.prev, m, p.prev) < 0 && area(p.next, m, m.next) < 0; - } - - // interlink polygon nodes in z-order - function indexCurve(start, minX, minY, invSize) { - var p = start; - do { - if (p.z === null) { p.z = zOrder(p.x, p.y, minX, minY, invSize); } - p.prevZ = p.prev; - p.nextZ = p.next; - p = p.next; - } while (p !== start); - - p.prevZ.nextZ = null; - p.prevZ = null; - - sortLinked(p); - } - - // Simon Tatham's linked list merge sort algorithm - // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html - function sortLinked(list) { - var i, p, q, e, tail, numMerges, pSize, qSize, - inSize = 1; - - do { - p = list; - list = null; - tail = null; - numMerges = 0; - - while (p) { - numMerges++; - q = p; - pSize = 0; - for (i = 0; i < inSize; i++) { - pSize++; - q = q.nextZ; - if (!q) { break; } - } - qSize = inSize; - - while (pSize > 0 || (qSize > 0 && q)) { - - if (pSize !== 0 && (qSize === 0 || !q || p.z <= q.z)) { - e = p; - p = p.nextZ; - pSize--; - } else { - e = q; - q = q.nextZ; - qSize--; - } - - if (tail) { tail.nextZ = e; } - else { list = e; } - - e.prevZ = tail; - tail = e; - } - - p = q; - } - - tail.nextZ = null; - inSize *= 2; - - } while (numMerges > 1); - - return list; - } - - // z-order of a point given coords and inverse of the longer side of data bbox - function zOrder(x, y, minX, minY, invSize) { - // coords are transformed into non-negative 15-bit integer range - x = 32767 * (x - minX) * invSize; - y = 32767 * (y - minY) * invSize; - - x = (x | (x << 8)) & 0x00FF00FF; - x = (x | (x << 4)) & 0x0F0F0F0F; - x = (x | (x << 2)) & 0x33333333; - x = (x | (x << 1)) & 0x55555555; - - y = (y | (y << 8)) & 0x00FF00FF; - y = (y | (y << 4)) & 0x0F0F0F0F; - y = (y | (y << 2)) & 0x33333333; - y = (y | (y << 1)) & 0x55555555; - - return x | (y << 1); - } - - // find the leftmost node of a polygon ring - function getLeftmost(start) { - var p = start, - leftmost = start; - do { - if (p.x < leftmost.x || (p.x === leftmost.x && p.y < leftmost.y)) { leftmost = p; } - p = p.next; - } while (p !== start); - - return leftmost; - } - - // check if a point lies within a convex triangle - function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) { - return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 && - (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 && - (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0; - } - - // check if a diagonal between two polygon nodes is valid (lies in polygon interior) - function isValidDiagonal(a, b) { - return a.next.i !== b.i && a.prev.i !== b.i && !intersectsPolygon(a, b) && // dones't intersect other edges - (locallyInside(a, b) && locallyInside(b, a) && middleInside(a, b) && // locally visible - (area(a.prev, a, b.prev) || area(a, b.prev, b)) || // does not create opposite-facing sectors - equals(a, b) && area(a.prev, a, a.next) > 0 && area(b.prev, b, b.next) > 0); // special zero-length case - } - - // signed area of a triangle - function area(p, q, r) { - return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y); - } - - // check if two points are equal - function equals(p1, p2) { - return p1.x === p2.x && p1.y === p2.y; - } - - // check if two segments intersect - function intersects(p1, q1, p2, q2) { - var o1 = sign(area(p1, q1, p2)); - var o2 = sign(area(p1, q1, q2)); - var o3 = sign(area(p2, q2, p1)); - var o4 = sign(area(p2, q2, q1)); - - if (o1 !== o2 && o3 !== o4) { return true; } // general case - - if (o1 === 0 && onSegment(p1, p2, q1)) { return true; } // p1, q1 and p2 are collinear and p2 lies on p1q1 - if (o2 === 0 && onSegment(p1, q2, q1)) { return true; } // p1, q1 and q2 are collinear and q2 lies on p1q1 - if (o3 === 0 && onSegment(p2, p1, q2)) { return true; } // p2, q2 and p1 are collinear and p1 lies on p2q2 - if (o4 === 0 && onSegment(p2, q1, q2)) { return true; } // p2, q2 and q1 are collinear and q1 lies on p2q2 - - return false; - } - - // for collinear points p, q, r, check if point q lies on segment pr - function onSegment(p, q, r) { - return q.x <= Math.max(p.x, r.x) && q.x >= Math.min(p.x, r.x) && q.y <= Math.max(p.y, r.y) && q.y >= Math.min(p.y, r.y); - } - - function sign(num) { - return num > 0 ? 1 : num < 0 ? -1 : 0; - } - - // check if a polygon diagonal intersects any polygon segments - function intersectsPolygon(a, b) { - var p = a; - do { - if (p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i && - intersects(p, p.next, a, b)) { return true; } - p = p.next; - } while (p !== a); - - return false; - } - - // check if a polygon diagonal is locally inside the polygon - function locallyInside(a, b) { - return area(a.prev, a, a.next) < 0 ? - area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0 : - area(a, b, a.prev) < 0 || area(a, a.next, b) < 0; - } - - // check if the middle point of a polygon diagonal is inside the polygon - function middleInside(a, b) { - var p = a, - inside = false, - px = (a.x + b.x) / 2, - py = (a.y + b.y) / 2; - do { - if (((p.y > py) !== (p.next.y > py)) && p.next.y !== p.y && - (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x)) - { inside = !inside; } - p = p.next; - } while (p !== a); - - return inside; - } - - // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two; - // if one belongs to the outer ring and another to a hole, it merges it into a single ring - function splitPolygon(a, b) { - var a2 = new Node(a.i, a.x, a.y), - b2 = new Node(b.i, b.x, b.y), - an = a.next, - bp = b.prev; - - a.next = b; - b.prev = a; - - a2.next = an; - an.prev = a2; - - b2.next = a2; - a2.prev = b2; - - bp.next = b2; - b2.prev = bp; - - return b2; - } - - // create a node and optionally link it with previous one (in a circular doubly linked list) - function insertNode(i, x, y, last) { - var p = new Node(i, x, y); - - if (!last) { - p.prev = p; - p.next = p; - - } else { - p.next = last.next; - p.prev = last; - last.next.prev = p; - last.next = p; - } - return p; - } - - function removeNode(p) { - p.next.prev = p.prev; - p.prev.next = p.next; - - if (p.prevZ) { p.prevZ.nextZ = p.nextZ; } - if (p.nextZ) { p.nextZ.prevZ = p.prevZ; } - } - - function Node(i, x, y) { - // vertex index in coordinates array - this.i = i; - - // vertex coordinates - this.x = x; - this.y = y; - - // previous and next vertex nodes in a polygon ring - this.prev = null; - this.next = null; - - // z-order curve value - this.z = null; - - // previous and next nodes in z-order - this.prevZ = null; - this.nextZ = null; - - // indicates whether this is a steiner point - this.steiner = false; - } - - // return a percentage difference between the polygon area and its triangulation area; - // used to verify correctness of triangulation - earcut.deviation = function (data, holeIndices, dim, triangles) { - var hasHoles = holeIndices && holeIndices.length; - var outerLen = hasHoles ? holeIndices[0] * dim : data.length; - - var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim)); - if (hasHoles) { - for (var i = 0, len = holeIndices.length; i < len; i++) { - var start = holeIndices[i] * dim; - var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length; - polygonArea -= Math.abs(signedArea(data, start, end, dim)); - } - } - - var trianglesArea = 0; - for (i = 0; i < triangles.length; i += 3) { - var a = triangles[i] * dim; - var b = triangles[i + 1] * dim; - var c = triangles[i + 2] * dim; - trianglesArea += Math.abs( - (data[a] - data[c]) * (data[b + 1] - data[a + 1]) - - (data[a] - data[b]) * (data[c + 1] - data[a + 1])); - } - - return polygonArea === 0 && trianglesArea === 0 ? 0 : - Math.abs((trianglesArea - polygonArea) / polygonArea); - }; - - function signedArea(data, start, end, dim) { - var sum = 0; - for (var i = start, j = end - dim; i < end; i += dim) { - sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]); - j = i; - } - return sum; - } - - // turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts - earcut.flatten = function (data) { - var dim = data[0][0].length, - result = {vertices: [], holes: [], dimensions: dim}, - holeIndex = 0; - - for (var i = 0; i < data.length; i++) { - for (var j = 0; j < data[i].length; j++) { - for (var d = 0; d < dim; d++) { result.vertices.push(data[i][j][d]); } - } - if (i > 0) { - holeIndex += data[i - 1].length; - result.holes.push(holeIndex); - } - } - return result; - }; - earcut_1.default = default_1; - - var punycode = createCommonjsModule(function (module, exports) { - /*! https://mths.be/punycode v1.3.2 by @mathias */ - ;(function(root) { - - /** Detect free variables */ - var freeExports = 'object' == 'object' && exports && - !exports.nodeType && exports; - var freeModule = 'object' == 'object' && module && - !module.nodeType && module; - var freeGlobal = typeof commonjsGlobal == 'object' && commonjsGlobal; - if ( - freeGlobal.global === freeGlobal || - freeGlobal.window === freeGlobal || - freeGlobal.self === freeGlobal - ) { - root = freeGlobal; - } - - /** - * The `punycode` object. - * @name punycode - * @type Object - */ - var punycode, - - /** Highest positive signed 32-bit float value */ - maxInt = 2147483647, // aka. 0x7FFFFFFF or 2^31-1 - - /** Bootstring parameters */ - base = 36, - tMin = 1, - tMax = 26, - skew = 38, - damp = 700, - initialBias = 72, - initialN = 128, // 0x80 - delimiter = '-', // '\x2D' - - /** Regular expressions */ - regexPunycode = /^xn--/, - regexNonASCII = /[^\x20-\x7E]/, // unprintable ASCII chars + non-ASCII chars - regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g, // RFC 3490 separators - - /** Error messages */ - errors = { - 'overflow': 'Overflow: input needs wider integers to process', - 'not-basic': 'Illegal input >= 0x80 (not a basic code point)', - 'invalid-input': 'Invalid input' - }, - - /** Convenience shortcuts */ - baseMinusTMin = base - tMin, - floor = Math.floor, - stringFromCharCode = String.fromCharCode, - - /** Temporary variable */ - key; - - /*--------------------------------------------------------------------------*/ - - /** - * A generic error utility function. - * @private - * @param {String} type The error type. - * @returns {Error} Throws a `RangeError` with the applicable error message. - */ - function error(type) { - throw RangeError(errors[type]); - } - - /** - * A generic `Array#map` utility function. - * @private - * @param {Array} array The array to iterate over. - * @param {Function} callback The function that gets called for every array - * item. - * @returns {Array} A new array of values returned by the callback function. - */ - function map(array, fn) { - var length = array.length; - var result = []; - while (length--) { - result[length] = fn(array[length]); - } - return result; - } - - /** - * A simple `Array#map`-like wrapper to work with domain name strings or email - * addresses. - * @private - * @param {String} domain The domain name or email address. - * @param {Function} callback The function that gets called for every - * character. - * @returns {Array} A new string of characters returned by the callback - * function. - */ - function mapDomain(string, fn) { - var parts = string.split('@'); - var result = ''; - if (parts.length > 1) { - // In email addresses, only the domain name should be punycoded. Leave - // the local part (i.e. everything up to `@`) intact. - result = parts[0] + '@'; - string = parts[1]; - } - // Avoid `split(regex)` for IE8 compatibility. See #17. - string = string.replace(regexSeparators, '\x2E'); - var labels = string.split('.'); - var encoded = map(labels, fn).join('.'); - return result + encoded; - } - - /** - * Creates an array containing the numeric code points of each Unicode - * character in the string. While JavaScript uses UCS-2 internally, - * this function will convert a pair of surrogate halves (each of which - * UCS-2 exposes as separate characters) into a single code point, - * matching UTF-16. - * @see `punycode.ucs2.encode` - * @see - * @memberOf punycode.ucs2 - * @name decode - * @param {String} string The Unicode input string (UCS-2). - * @returns {Array} The new array of code points. - */ - function ucs2decode(string) { - var output = [], - counter = 0, - length = string.length, - value, - extra; - while (counter < length) { - value = string.charCodeAt(counter++); - if (value >= 0xD800 && value <= 0xDBFF && counter < length) { - // high surrogate, and there is a next character - extra = string.charCodeAt(counter++); - if ((extra & 0xFC00) == 0xDC00) { // low surrogate - output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000); - } else { - // unmatched surrogate; only append this code unit, in case the next - // code unit is the high surrogate of a surrogate pair - output.push(value); - counter--; - } - } else { - output.push(value); - } - } - return output; - } - - /** - * Creates a string based on an array of numeric code points. - * @see `punycode.ucs2.decode` - * @memberOf punycode.ucs2 - * @name encode - * @param {Array} codePoints The array of numeric code points. - * @returns {String} The new Unicode string (UCS-2). - */ - function ucs2encode(array) { - return map(array, function(value) { - var output = ''; - if (value > 0xFFFF) { - value -= 0x10000; - output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800); - value = 0xDC00 | value & 0x3FF; - } - output += stringFromCharCode(value); - return output; - }).join(''); - } - - /** - * Converts a basic code point into a digit/integer. - * @see `digitToBasic()` - * @private - * @param {Number} codePoint The basic numeric code point value. - * @returns {Number} The numeric value of a basic code point (for use in - * representing integers) in the range `0` to `base - 1`, or `base` if - * the code point does not represent a value. - */ - function basicToDigit(codePoint) { - if (codePoint - 48 < 10) { - return codePoint - 22; - } - if (codePoint - 65 < 26) { - return codePoint - 65; - } - if (codePoint - 97 < 26) { - return codePoint - 97; - } - return base; - } - - /** - * Converts a digit/integer into a basic code point. - * @see `basicToDigit()` - * @private - * @param {Number} digit The numeric value of a basic code point. - * @returns {Number} The basic code point whose value (when used for - * representing integers) is `digit`, which needs to be in the range - * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is - * used; else, the lowercase form is used. The behavior is undefined - * if `flag` is non-zero and `digit` has no uppercase form. - */ - function digitToBasic(digit, flag) { - // 0..25 map to ASCII a..z or A..Z - // 26..35 map to ASCII 0..9 - return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5); - } - - /** - * Bias adaptation function as per section 3.4 of RFC 3492. - * http://tools.ietf.org/html/rfc3492#section-3.4 - * @private - */ - function adapt(delta, numPoints, firstTime) { - var k = 0; - delta = firstTime ? floor(delta / damp) : delta >> 1; - delta += floor(delta / numPoints); - for (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) { - delta = floor(delta / baseMinusTMin); - } - return floor(k + (baseMinusTMin + 1) * delta / (delta + skew)); - } - - /** - * Converts a Punycode string of ASCII-only symbols to a string of Unicode - * symbols. - * @memberOf punycode - * @param {String} input The Punycode string of ASCII-only symbols. - * @returns {String} The resulting string of Unicode symbols. - */ - function decode(input) { - // Don't use UCS-2 - var output = [], - inputLength = input.length, - out, - i = 0, - n = initialN, - bias = initialBias, - basic, - j, - index, - oldi, - w, - k, - digit, - t, - /** Cached calculation results */ - baseMinusT; - - // Handle the basic code points: let `basic` be the number of input code - // points before the last delimiter, or `0` if there is none, then copy - // the first basic code points to the output. - - basic = input.lastIndexOf(delimiter); - if (basic < 0) { - basic = 0; - } - - for (j = 0; j < basic; ++j) { - // if it's not a basic code point - if (input.charCodeAt(j) >= 0x80) { - error('not-basic'); - } - output.push(input.charCodeAt(j)); - } - - // Main decoding loop: start just after the last delimiter if any basic code - // points were copied; start at the beginning otherwise. - - for (index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) { - - // `index` is the index of the next character to be consumed. - // Decode a generalized variable-length integer into `delta`, - // which gets added to `i`. The overflow checking is easier - // if we increase `i` as we go, then subtract off its starting - // value at the end to obtain `delta`. - for (oldi = i, w = 1, k = base; /* no condition */; k += base) { - - if (index >= inputLength) { - error('invalid-input'); - } - - digit = basicToDigit(input.charCodeAt(index++)); - - if (digit >= base || digit > floor((maxInt - i) / w)) { - error('overflow'); - } - - i += digit * w; - t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); - - if (digit < t) { - break; - } - - baseMinusT = base - t; - if (w > floor(maxInt / baseMinusT)) { - error('overflow'); - } - - w *= baseMinusT; - - } - - out = output.length + 1; - bias = adapt(i - oldi, out, oldi == 0); - - // `i` was supposed to wrap around from `out` to `0`, - // incrementing `n` each time, so we'll fix that now: - if (floor(i / out) > maxInt - n) { - error('overflow'); - } - - n += floor(i / out); - i %= out; - - // Insert `n` at position `i` of the output - output.splice(i++, 0, n); - - } - - return ucs2encode(output); - } - - /** - * Converts a string of Unicode symbols (e.g. a domain name label) to a - * Punycode string of ASCII-only symbols. - * @memberOf punycode - * @param {String} input The string of Unicode symbols. - * @returns {String} The resulting Punycode string of ASCII-only symbols. - */ - function encode(input) { - var n, - delta, - handledCPCount, - basicLength, - bias, - j, - m, - q, - k, - t, - currentValue, - output = [], - /** `inputLength` will hold the number of code points in `input`. */ - inputLength, - /** Cached calculation results */ - handledCPCountPlusOne, - baseMinusT, - qMinusT; - - // Convert the input in UCS-2 to Unicode - input = ucs2decode(input); - - // Cache the length - inputLength = input.length; - - // Initialize the state - n = initialN; - delta = 0; - bias = initialBias; - - // Handle the basic code points - for (j = 0; j < inputLength; ++j) { - currentValue = input[j]; - if (currentValue < 0x80) { - output.push(stringFromCharCode(currentValue)); - } - } - - handledCPCount = basicLength = output.length; - - // `handledCPCount` is the number of code points that have been handled; - // `basicLength` is the number of basic code points. - - // Finish the basic string - if it is not empty - with a delimiter - if (basicLength) { - output.push(delimiter); - } - - // Main encoding loop: - while (handledCPCount < inputLength) { - - // All non-basic code points < n have been handled already. Find the next - // larger one: - for (m = maxInt, j = 0; j < inputLength; ++j) { - currentValue = input[j]; - if (currentValue >= n && currentValue < m) { - m = currentValue; - } - } - - // Increase `delta` enough to advance the decoder's state to , - // but guard against overflow - handledCPCountPlusOne = handledCPCount + 1; - if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) { - error('overflow'); - } - - delta += (m - n) * handledCPCountPlusOne; - n = m; - - for (j = 0; j < inputLength; ++j) { - currentValue = input[j]; - - if (currentValue < n && ++delta > maxInt) { - error('overflow'); - } - - if (currentValue == n) { - // Represent delta as a generalized variable-length integer - for (q = delta, k = base; /* no condition */; k += base) { - t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); - if (q < t) { - break; - } - qMinusT = q - t; - baseMinusT = base - t; - output.push( - stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0)) - ); - q = floor(qMinusT / baseMinusT); - } - - output.push(stringFromCharCode(digitToBasic(q, 0))); - bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength); - delta = 0; - ++handledCPCount; - } - } - - ++delta; - ++n; - - } - return output.join(''); - } - - /** - * Converts a Punycode string representing a domain name or an email address - * to Unicode. Only the Punycoded parts of the input will be converted, i.e. - * it doesn't matter if you call it on a string that has already been - * converted to Unicode. - * @memberOf punycode - * @param {String} input The Punycoded domain name or email address to - * convert to Unicode. - * @returns {String} The Unicode representation of the given Punycode - * string. - */ - function toUnicode(input) { - return mapDomain(input, function(string) { - return regexPunycode.test(string) - ? decode(string.slice(4).toLowerCase()) - : string; - }); - } - - /** - * Converts a Unicode string representing a domain name or an email address to - * Punycode. Only the non-ASCII parts of the domain name will be converted, - * i.e. it doesn't matter if you call it with a domain that's already in - * ASCII. - * @memberOf punycode - * @param {String} input The domain name or email address to convert, as a - * Unicode string. - * @returns {String} The Punycode representation of the given domain name or - * email address. - */ - function toASCII(input) { - return mapDomain(input, function(string) { - return regexNonASCII.test(string) - ? 'xn--' + encode(string) - : string; - }); - } - - /*--------------------------------------------------------------------------*/ - - /** Define the public API */ - punycode = { - /** - * A string representing the current Punycode.js version number. - * @memberOf punycode - * @type String - */ - 'version': '1.3.2', - /** - * An object of methods to convert from JavaScript's internal character - * representation (UCS-2) to Unicode code points, and back. - * @see - * @memberOf punycode - * @type Object - */ - 'ucs2': { - 'decode': ucs2decode, - 'encode': ucs2encode - }, - 'decode': decode, - 'encode': encode, - 'toASCII': toASCII, - 'toUnicode': toUnicode - }; - - /** Expose `punycode` */ - // Some AMD build optimizers, like r.js, check for specific condition patterns - // like the following: - if ( - typeof undefined == 'function' && - typeof undefined.amd == 'object' && - undefined.amd - ) { - undefined('punycode', function() { - return punycode; - }); - } else if (freeExports && freeModule) { - if (module.exports == freeExports) { // in Node.js or RingoJS v0.8.0+ - freeModule.exports = punycode; - } else { // in Narwhal or RingoJS v0.7.0- - for (key in punycode) { - punycode.hasOwnProperty(key) && (freeExports[key] = punycode[key]); - } - } - } else { // in Rhino or a web browser - root.punycode = punycode; - } - - }(commonjsGlobal)); - }); - - 'use strict'; - - var util = { - isString: function(arg) { - return typeof(arg) === 'string'; - }, - isObject: function(arg) { - return typeof(arg) === 'object' && arg !== null; - }, - isNull: function(arg) { - return arg === null; - }, - isNullOrUndefined: function(arg) { - return arg == null; - } - }; - var util_1 = util.isString; - var util_2 = util.isObject; - var util_3 = util.isNull; - var util_4 = util.isNullOrUndefined; - - // Copyright Joyent, Inc. and other Node contributors. - // - // Permission is hereby granted, free of charge, to any person obtaining a - // copy of this software and associated documentation files (the - // "Software"), to deal in the Software without restriction, including - // without limitation the rights to use, copy, modify, merge, publish, - // distribute, sublicense, and/or sell copies of the Software, and to permit - // persons to whom the Software is furnished to do so, subject to the - // following conditions: - // - // The above copyright notice and this permission notice shall be included - // in all copies or substantial portions of the Software. - // - // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS - // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN - // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, - // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR - // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE - // USE OR OTHER DEALINGS IN THE SOFTWARE. - - 'use strict'; - - // If obj.hasOwnProperty has been overridden, then calling - // obj.hasOwnProperty(prop) will break. - // See: https://github.com/joyent/node/issues/1707 - function hasOwnProperty$1(obj, prop) { - return Object.prototype.hasOwnProperty.call(obj, prop); - } - - var decode = function(qs, sep, eq, options) { - sep = sep || '&'; - eq = eq || '='; - var obj = {}; - - if (typeof qs !== 'string' || qs.length === 0) { - return obj; - } - - var regexp = /\+/g; - qs = qs.split(sep); - - var maxKeys = 1000; - if (options && typeof options.maxKeys === 'number') { - maxKeys = options.maxKeys; - } - - var len = qs.length; - // maxKeys <= 0 means that we should not limit keys count - if (maxKeys > 0 && len > maxKeys) { - len = maxKeys; - } - - for (var i = 0; i < len; ++i) { - var x = qs[i].replace(regexp, '%20'), - idx = x.indexOf(eq), - kstr, vstr, k, v; - - if (idx >= 0) { - kstr = x.substr(0, idx); - vstr = x.substr(idx + 1); - } else { - kstr = x; - vstr = ''; - } - - k = decodeURIComponent(kstr); - v = decodeURIComponent(vstr); - - if (!hasOwnProperty$1(obj, k)) { - obj[k] = v; - } else if (Array.isArray(obj[k])) { - obj[k].push(v); - } else { - obj[k] = [obj[k], v]; - } - } - - return obj; - }; - - // Copyright Joyent, Inc. and other Node contributors. - // - // Permission is hereby granted, free of charge, to any person obtaining a - // copy of this software and associated documentation files (the - // "Software"), to deal in the Software without restriction, including - // without limitation the rights to use, copy, modify, merge, publish, - // distribute, sublicense, and/or sell copies of the Software, and to permit - // persons to whom the Software is furnished to do so, subject to the - // following conditions: - // - // The above copyright notice and this permission notice shall be included - // in all copies or substantial portions of the Software. - // - // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS - // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN - // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, - // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR - // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE - // USE OR OTHER DEALINGS IN THE SOFTWARE. - - 'use strict'; - - var stringifyPrimitive = function(v) { - switch (typeof v) { - case 'string': - return v; - - case 'boolean': - return v ? 'true' : 'false'; - - case 'number': - return isFinite(v) ? v : ''; - - default: - return ''; - } - }; - - var encode = function(obj, sep, eq, name) { - sep = sep || '&'; - eq = eq || '='; - if (obj === null) { - obj = undefined; - } - - if (typeof obj === 'object') { - return Object.keys(obj).map(function(k) { - var ks = encodeURIComponent(stringifyPrimitive(k)) + eq; - if (Array.isArray(obj[k])) { - return obj[k].map(function(v) { - return ks + encodeURIComponent(stringifyPrimitive(v)); - }).join(sep); - } else { - return ks + encodeURIComponent(stringifyPrimitive(obj[k])); - } - }).join(sep); - - } - - if (!name) { return ''; } - return encodeURIComponent(stringifyPrimitive(name)) + eq + - encodeURIComponent(stringifyPrimitive(obj)); - }; - - var querystring = createCommonjsModule(function (module, exports) { - 'use strict'; - - exports.decode = exports.parse = decode; - exports.encode = exports.stringify = encode; - }); - var querystring_1 = querystring.decode; - var querystring_2 = querystring.parse; - var querystring_3 = querystring.encode; - var querystring_4 = querystring.stringify; - - // Copyright Joyent, Inc. and other Node contributors. - // - // Permission is hereby granted, free of charge, to any person obtaining a - // copy of this software and associated documentation files (the - // "Software"), to deal in the Software without restriction, including - // without limitation the rights to use, copy, modify, merge, publish, - // distribute, sublicense, and/or sell copies of the Software, and to permit - // persons to whom the Software is furnished to do so, subject to the - // following conditions: - // - // The above copyright notice and this permission notice shall be included - // in all copies or substantial portions of the Software. - // - // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS - // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN - // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, - // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR - // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE - // USE OR OTHER DEALINGS IN THE SOFTWARE. - - 'use strict'; - - - - - var parse = urlParse; - var resolve = urlResolve; - var resolveObject = urlResolveObject; - var format = urlFormat; - - var Url_1 = Url; - - function Url() { - this.protocol = null; - this.slashes = null; - this.auth = null; - this.host = null; - this.port = null; - this.hostname = null; - this.hash = null; - this.search = null; - this.query = null; - this.pathname = null; - this.path = null; - this.href = null; - } - - // Reference: RFC 3986, RFC 1808, RFC 2396 - - // define these here so at least they only have to be - // compiled once on the first module load. - var protocolPattern = /^([a-z0-9.+-]+:)/i, - portPattern = /:[0-9]*$/, - - // Special case for a simple path URL - simplePathPattern = /^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/, - - // RFC 2396: characters reserved for delimiting URLs. - // We actually just auto-escape these. - delims = ['<', '>', '"', '`', ' ', '\r', '\n', '\t'], - - // RFC 2396: characters not allowed for various reasons. - unwise = ['{', '}', '|', '\\', '^', '`'].concat(delims), - - // Allowed by RFCs, but cause of XSS attacks. Always escape these. - autoEscape = ['\''].concat(unwise), - // Characters that are never ever allowed in a hostname. - // Note that any invalid chars are also handled, but these - // are the ones that are *expected* to be seen, so we fast-path - // them. - nonHostChars = ['%', '/', '?', ';', '#'].concat(autoEscape), - hostEndingChars = ['/', '?', '#'], - hostnameMaxLen = 255, - hostnamePartPattern = /^[+a-z0-9A-Z_-]{0,63}$/, - hostnamePartStart = /^([+a-z0-9A-Z_-]{0,63})(.*)$/, - // protocols that can allow "unsafe" and "unwise" chars. - unsafeProtocol = { - 'javascript': true, - 'javascript:': true - }, - // protocols that never have a hostname. - hostlessProtocol = { - 'javascript': true, - 'javascript:': true - }, - // protocols that always contain a // bit. - slashedProtocol = { - 'http': true, - 'https': true, - 'ftp': true, - 'gopher': true, - 'file': true, - 'http:': true, - 'https:': true, - 'ftp:': true, - 'gopher:': true, - 'file:': true - }; - - function urlParse(url, parseQueryString, slashesDenoteHost) { - if (url && util.isObject(url) && url instanceof Url) { return url; } - - var u = new Url; - u.parse(url, parseQueryString, slashesDenoteHost); - return u; - } - - Url.prototype.parse = function(url, parseQueryString, slashesDenoteHost) { - if (!util.isString(url)) { - throw new TypeError("Parameter 'url' must be a string, not " + typeof url); - } - - // Copy chrome, IE, opera backslash-handling behavior. - // Back slashes before the query string get converted to forward slashes - // See: https://code.google.com/p/chromium/issues/detail?id=25916 - var queryIndex = url.indexOf('?'), - splitter = - (queryIndex !== -1 && queryIndex < url.indexOf('#')) ? '?' : '#', - uSplit = url.split(splitter), - slashRegex = /\\/g; - uSplit[0] = uSplit[0].replace(slashRegex, '/'); - url = uSplit.join(splitter); - - var rest = url; - - // trim before proceeding. - // This is to support parse stuff like " http://foo.com \n" - rest = rest.trim(); - - if (!slashesDenoteHost && url.split('#').length === 1) { - // Try fast path regexp - var simplePath = simplePathPattern.exec(rest); - if (simplePath) { - this.path = rest; - this.href = rest; - this.pathname = simplePath[1]; - if (simplePath[2]) { - this.search = simplePath[2]; - if (parseQueryString) { - this.query = querystring.parse(this.search.substr(1)); - } else { - this.query = this.search.substr(1); - } - } else if (parseQueryString) { - this.search = ''; - this.query = {}; - } - return this; - } - } - - var proto = protocolPattern.exec(rest); - if (proto) { - proto = proto[0]; - var lowerProto = proto.toLowerCase(); - this.protocol = lowerProto; - rest = rest.substr(proto.length); - } - - // figure out if it's got a host - // user@server is *always* interpreted as a hostname, and url - // resolution will treat //foo/bar as host=foo,path=bar because that's - // how the browser resolves relative URLs. - if (slashesDenoteHost || proto || rest.match(/^\/\/[^@\/]+@[^@\/]+/)) { - var slashes = rest.substr(0, 2) === '//'; - if (slashes && !(proto && hostlessProtocol[proto])) { - rest = rest.substr(2); - this.slashes = true; - } - } - - if (!hostlessProtocol[proto] && - (slashes || (proto && !slashedProtocol[proto]))) { - - // there's a hostname. - // the first instance of /, ?, ;, or # ends the host. - // - // If there is an @ in the hostname, then non-host chars *are* allowed - // to the left of the last @ sign, unless some host-ending character - // comes *before* the @-sign. - // URLs are obnoxious. - // - // ex: - // http://a@b@c/ => user:a@b host:c - // http://a@b?@c => user:a host:c path:/?@c - - // v0.12 TODO(isaacs): This is not quite how Chrome does things. - // Review our test case against browsers more comprehensively. - - // find the first instance of any hostEndingChars - var hostEnd = -1; - for (var i = 0; i < hostEndingChars.length; i++) { - var hec = rest.indexOf(hostEndingChars[i]); - if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) - { hostEnd = hec; } - } - - // at this point, either we have an explicit point where the - // auth portion cannot go past, or the last @ char is the decider. - var auth, atSign; - if (hostEnd === -1) { - // atSign can be anywhere. - atSign = rest.lastIndexOf('@'); - } else { - // atSign must be in auth portion. - // http://a@b/c@d => host:b auth:a path:/c@d - atSign = rest.lastIndexOf('@', hostEnd); - } - - // Now we have a portion which is definitely the auth. - // Pull that off. - if (atSign !== -1) { - auth = rest.slice(0, atSign); - rest = rest.slice(atSign + 1); - this.auth = decodeURIComponent(auth); - } - - // the host is the remaining to the left of the first non-host char - hostEnd = -1; - for (var i = 0; i < nonHostChars.length; i++) { - var hec = rest.indexOf(nonHostChars[i]); - if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) - { hostEnd = hec; } - } - // if we still have not hit it, then the entire thing is a host. - if (hostEnd === -1) - { hostEnd = rest.length; } - - this.host = rest.slice(0, hostEnd); - rest = rest.slice(hostEnd); - - // pull out port. - this.parseHost(); - - // we've indicated that there is a hostname, - // so even if it's empty, it has to be present. - this.hostname = this.hostname || ''; - - // if hostname begins with [ and ends with ] - // assume that it's an IPv6 address. - var ipv6Hostname = this.hostname[0] === '[' && - this.hostname[this.hostname.length - 1] === ']'; - - // validate a little. - if (!ipv6Hostname) { - var hostparts = this.hostname.split(/\./); - for (var i = 0, l = hostparts.length; i < l; i++) { - var part = hostparts[i]; - if (!part) { continue; } - if (!part.match(hostnamePartPattern)) { - var newpart = ''; - for (var j = 0, k = part.length; j < k; j++) { - if (part.charCodeAt(j) > 127) { - // we replace non-ASCII char with a temporary placeholder - // we need this to make sure size of hostname is not - // broken by replacing non-ASCII by nothing - newpart += 'x'; - } else { - newpart += part[j]; - } - } - // we test again with ASCII char only - if (!newpart.match(hostnamePartPattern)) { - var validParts = hostparts.slice(0, i); - var notHost = hostparts.slice(i + 1); - var bit = part.match(hostnamePartStart); - if (bit) { - validParts.push(bit[1]); - notHost.unshift(bit[2]); - } - if (notHost.length) { - rest = '/' + notHost.join('.') + rest; - } - this.hostname = validParts.join('.'); - break; - } - } - } - } - - if (this.hostname.length > hostnameMaxLen) { - this.hostname = ''; - } else { - // hostnames are always lower case. - this.hostname = this.hostname.toLowerCase(); - } - - if (!ipv6Hostname) { - // IDNA Support: Returns a punycoded representation of "domain". - // It only converts parts of the domain name that - // have non-ASCII characters, i.e. it doesn't matter if - // you call it with a domain that already is ASCII-only. - this.hostname = punycode.toASCII(this.hostname); - } - - var p = this.port ? ':' + this.port : ''; - var h = this.hostname || ''; - this.host = h + p; - this.href += this.host; - - // strip [ and ] from the hostname - // the host field still retains them, though - if (ipv6Hostname) { - this.hostname = this.hostname.substr(1, this.hostname.length - 2); - if (rest[0] !== '/') { - rest = '/' + rest; - } - } - } - - // now rest is set to the post-host stuff. - // chop off any delim chars. - if (!unsafeProtocol[lowerProto]) { - - // First, make 100% sure that any "autoEscape" chars get - // escaped, even if encodeURIComponent doesn't think they - // need to be. - for (var i = 0, l = autoEscape.length; i < l; i++) { - var ae = autoEscape[i]; - if (rest.indexOf(ae) === -1) - { continue; } - var esc = encodeURIComponent(ae); - if (esc === ae) { - esc = escape(ae); - } - rest = rest.split(ae).join(esc); - } - } - - - // chop off from the tail first. - var hash = rest.indexOf('#'); - if (hash !== -1) { - // got a fragment string. - this.hash = rest.substr(hash); - rest = rest.slice(0, hash); - } - var qm = rest.indexOf('?'); - if (qm !== -1) { - this.search = rest.substr(qm); - this.query = rest.substr(qm + 1); - if (parseQueryString) { - this.query = querystring.parse(this.query); - } - rest = rest.slice(0, qm); - } else if (parseQueryString) { - // no query string, but parseQueryString still requested - this.search = ''; - this.query = {}; - } - if (rest) { this.pathname = rest; } - if (slashedProtocol[lowerProto] && - this.hostname && !this.pathname) { - this.pathname = '/'; - } - - //to support http.request - if (this.pathname || this.search) { - var p = this.pathname || ''; - var s = this.search || ''; - this.path = p + s; - } - - // finally, reconstruct the href based on what has been validated. - this.href = this.format(); - return this; - }; - - // format a parsed object into a url string - function urlFormat(obj) { - // ensure it's an object, and not a string url. - // If it's an obj, this is a no-op. - // this way, you can call url_format() on strings - // to clean up potentially wonky urls. - if (util.isString(obj)) { obj = urlParse(obj); } - if (!(obj instanceof Url)) { return Url.prototype.format.call(obj); } - return obj.format(); - } - - Url.prototype.format = function() { - var auth = this.auth || ''; - if (auth) { - auth = encodeURIComponent(auth); - auth = auth.replace(/%3A/i, ':'); - auth += '@'; - } - - var protocol = this.protocol || '', - pathname = this.pathname || '', - hash = this.hash || '', - host = false, - query = ''; - - if (this.host) { - host = auth + this.host; - } else if (this.hostname) { - host = auth + (this.hostname.indexOf(':') === -1 ? - this.hostname : - '[' + this.hostname + ']'); - if (this.port) { - host += ':' + this.port; - } - } - - if (this.query && - util.isObject(this.query) && - Object.keys(this.query).length) { - query = querystring.stringify(this.query); - } - - var search = this.search || (query && ('?' + query)) || ''; - - if (protocol && protocol.substr(-1) !== ':') { protocol += ':'; } - - // only the slashedProtocols get the //. Not mailto:, xmpp:, etc. - // unless they had them to begin with. - if (this.slashes || - (!protocol || slashedProtocol[protocol]) && host !== false) { - host = '//' + (host || ''); - if (pathname && pathname.charAt(0) !== '/') { pathname = '/' + pathname; } - } else if (!host) { - host = ''; - } - - if (hash && hash.charAt(0) !== '#') { hash = '#' + hash; } - if (search && search.charAt(0) !== '?') { search = '?' + search; } - - pathname = pathname.replace(/[?#]/g, function(match) { - return encodeURIComponent(match); - }); - search = search.replace('#', '%23'); - - return protocol + host + pathname + search + hash; - }; - - function urlResolve(source, relative) { - return urlParse(source, false, true).resolve(relative); - } - - Url.prototype.resolve = function(relative) { - return this.resolveObject(urlParse(relative, false, true)).format(); - }; - - function urlResolveObject(source, relative) { - if (!source) { return relative; } - return urlParse(source, false, true).resolveObject(relative); - } - - Url.prototype.resolveObject = function(relative) { - if (util.isString(relative)) { - var rel = new Url(); - rel.parse(relative, false, true); - relative = rel; - } - - var result = new Url(); - var tkeys = Object.keys(this); - for (var tk = 0; tk < tkeys.length; tk++) { - var tkey = tkeys[tk]; - result[tkey] = this[tkey]; - } - - // hash is always overridden, no matter what. - // even href="" will remove it. - result.hash = relative.hash; - - // if the relative url is empty, then there's nothing left to do here. - if (relative.href === '') { - result.href = result.format(); - return result; - } - - // hrefs like //foo/bar always cut to the protocol. - if (relative.slashes && !relative.protocol) { - // take everything except the protocol from relative - var rkeys = Object.keys(relative); - for (var rk = 0; rk < rkeys.length; rk++) { - var rkey = rkeys[rk]; - if (rkey !== 'protocol') - { result[rkey] = relative[rkey]; } - } - - //urlParse appends trailing / to urls like http://www.example.com - if (slashedProtocol[result.protocol] && - result.hostname && !result.pathname) { - result.path = result.pathname = '/'; - } - - result.href = result.format(); - return result; - } - - if (relative.protocol && relative.protocol !== result.protocol) { - // if it's a known url protocol, then changing - // the protocol does weird things - // first, if it's not file:, then we MUST have a host, - // and if there was a path - // to begin with, then we MUST have a path. - // if it is file:, then the host is dropped, - // because that's known to be hostless. - // anything else is assumed to be absolute. - if (!slashedProtocol[relative.protocol]) { - var keys = Object.keys(relative); - for (var v = 0; v < keys.length; v++) { - var k = keys[v]; - result[k] = relative[k]; - } - result.href = result.format(); - return result; - } - - result.protocol = relative.protocol; - if (!relative.host && !hostlessProtocol[relative.protocol]) { - var relPath = (relative.pathname || '').split('/'); - while (relPath.length && !(relative.host = relPath.shift())){ ; } - if (!relative.host) { relative.host = ''; } - if (!relative.hostname) { relative.hostname = ''; } - if (relPath[0] !== '') { relPath.unshift(''); } - if (relPath.length < 2) { relPath.unshift(''); } - result.pathname = relPath.join('/'); - } else { - result.pathname = relative.pathname; - } - result.search = relative.search; - result.query = relative.query; - result.host = relative.host || ''; - result.auth = relative.auth; - result.hostname = relative.hostname || relative.host; - result.port = relative.port; - // to support http.request - if (result.pathname || result.search) { - var p = result.pathname || ''; - var s = result.search || ''; - result.path = p + s; - } - result.slashes = result.slashes || relative.slashes; - result.href = result.format(); - return result; - } - - var isSourceAbs = (result.pathname && result.pathname.charAt(0) === '/'), - isRelAbs = ( - relative.host || - relative.pathname && relative.pathname.charAt(0) === '/' - ), - mustEndAbs = (isRelAbs || isSourceAbs || - (result.host && relative.pathname)), - removeAllDots = mustEndAbs, - srcPath = result.pathname && result.pathname.split('/') || [], - relPath = relative.pathname && relative.pathname.split('/') || [], - psychotic = result.protocol && !slashedProtocol[result.protocol]; - - // if the url is a non-slashed url, then relative - // links like ../.. should be able - // to crawl up to the hostname, as well. This is strange. - // result.protocol has already been set by now. - // Later on, put the first path part into the host field. - if (psychotic) { - result.hostname = ''; - result.port = null; - if (result.host) { - if (srcPath[0] === '') { srcPath[0] = result.host; } - else { srcPath.unshift(result.host); } - } - result.host = ''; - if (relative.protocol) { - relative.hostname = null; - relative.port = null; - if (relative.host) { - if (relPath[0] === '') { relPath[0] = relative.host; } - else { relPath.unshift(relative.host); } - } - relative.host = null; - } - mustEndAbs = mustEndAbs && (relPath[0] === '' || srcPath[0] === ''); - } - - if (isRelAbs) { - // it's absolute. - result.host = (relative.host || relative.host === '') ? - relative.host : result.host; - result.hostname = (relative.hostname || relative.hostname === '') ? - relative.hostname : result.hostname; - result.search = relative.search; - result.query = relative.query; - srcPath = relPath; - // fall through to the dot-handling below. - } else if (relPath.length) { - // it's relative - // throw away the existing file, and take the new path instead. - if (!srcPath) { srcPath = []; } - srcPath.pop(); - srcPath = srcPath.concat(relPath); - result.search = relative.search; - result.query = relative.query; - } else if (!util.isNullOrUndefined(relative.search)) { - // just pull out the search. - // like href='?foo'. - // Put this after the other two cases because it simplifies the booleans - if (psychotic) { - result.hostname = result.host = srcPath.shift(); - //occationaly the auth can get stuck only in host - //this especially happens in cases like - //url.resolveObject('mailto:local1@domain1', 'local2@domain2') - var authInHost = result.host && result.host.indexOf('@') > 0 ? - result.host.split('@') : false; - if (authInHost) { - result.auth = authInHost.shift(); - result.host = result.hostname = authInHost.shift(); - } - } - result.search = relative.search; - result.query = relative.query; - //to support http.request - if (!util.isNull(result.pathname) || !util.isNull(result.search)) { - result.path = (result.pathname ? result.pathname : '') + - (result.search ? result.search : ''); - } - result.href = result.format(); - return result; - } - - if (!srcPath.length) { - // no path at all. easy. - // we've already handled the other stuff above. - result.pathname = null; - //to support http.request - if (result.search) { - result.path = '/' + result.search; - } else { - result.path = null; - } - result.href = result.format(); - return result; - } - - // if a url ENDs in . or .., then it must get a trailing slash. - // however, if it ends in anything else non-slashy, - // then it must NOT get a trailing slash. - var last = srcPath.slice(-1)[0]; - var hasTrailingSlash = ( - (result.host || relative.host || srcPath.length > 1) && - (last === '.' || last === '..') || last === ''); - - // strip single dots, resolve double dots to parent dir - // if the path tries to go above the root, `up` ends up > 0 - var up = 0; - for (var i = srcPath.length; i >= 0; i--) { - last = srcPath[i]; - if (last === '.') { - srcPath.splice(i, 1); - } else if (last === '..') { - srcPath.splice(i, 1); - up++; - } else if (up) { - srcPath.splice(i, 1); - up--; - } - } - - // if the path is allowed to go above the root, restore leading ..s - if (!mustEndAbs && !removeAllDots) { - for (; up--; up) { - srcPath.unshift('..'); - } - } - - if (mustEndAbs && srcPath[0] !== '' && - (!srcPath[0] || srcPath[0].charAt(0) !== '/')) { - srcPath.unshift(''); - } - - if (hasTrailingSlash && (srcPath.join('/').substr(-1) !== '/')) { - srcPath.push(''); - } - - var isAbsolute = srcPath[0] === '' || - (srcPath[0] && srcPath[0].charAt(0) === '/'); - - // put the host back - if (psychotic) { - result.hostname = result.host = isAbsolute ? '' : - srcPath.length ? srcPath.shift() : ''; - //occationaly the auth can get stuck only in host - //this especially happens in cases like - //url.resolveObject('mailto:local1@domain1', 'local2@domain2') - var authInHost = result.host && result.host.indexOf('@') > 0 ? - result.host.split('@') : false; - if (authInHost) { - result.auth = authInHost.shift(); - result.host = result.hostname = authInHost.shift(); - } - } - - mustEndAbs = mustEndAbs || (result.host && srcPath.length); - - if (mustEndAbs && !isAbsolute) { - srcPath.unshift(''); - } - - if (!srcPath.length) { - result.pathname = null; - result.path = null; - } else { - result.pathname = srcPath.join('/'); - } - - //to support request.http - if (!util.isNull(result.pathname) || !util.isNull(result.search)) { - result.path = (result.pathname ? result.pathname : '') + - (result.search ? result.search : ''); - } - result.auth = relative.auth || result.auth; - result.slashes = result.slashes || relative.slashes; - result.href = result.format(); - return result; - }; - - Url.prototype.parseHost = function() { - var host = this.host; - var port = portPattern.exec(host); - if (port) { - port = port[0]; - if (port !== ':') { - this.port = port.substr(1); - } - host = host.substr(0, host.length - port.length); - } - if (host) { this.hostname = host; } - }; - - var url = { - parse: parse, - resolve: resolve, - resolveObject: resolveObject, - format: format, - Url: Url_1 - }; - - /*! - * @pixi/constants - v5.3.3 - * Compiled Tue, 04 Aug 2020 16:23:09 UTC - * - * @pixi/constants is licensed under the MIT License. - * http://www.opensource.org/licenses/mit-license - */ - /** - * Different types of environments for WebGL. - * - * @static - * @memberof PIXI - * @name ENV - * @enum {number} - * @property {number} WEBGL_LEGACY - Used for older v1 WebGL devices. PixiJS will aim to ensure compatibility - * with older / less advanced devices. If you experience unexplained flickering prefer this environment. - * @property {number} WEBGL - Version 1 of WebGL - * @property {number} WEBGL2 - Version 2 of WebGL - */ - - (function (ENV) { - ENV[ENV["WEBGL_LEGACY"] = 0] = "WEBGL_LEGACY"; - ENV[ENV["WEBGL"] = 1] = "WEBGL"; - ENV[ENV["WEBGL2"] = 2] = "WEBGL2"; - })(exports.ENV || (exports.ENV = {})); - /** - * Constant to identify the Renderer Type. - * - * @static - * @memberof PIXI - * @name RENDERER_TYPE - * @enum {number} - * @property {number} UNKNOWN - Unknown render type. - * @property {number} WEBGL - WebGL render type. - * @property {number} CANVAS - Canvas render type. - */ - - (function (RENDERER_TYPE) { - RENDERER_TYPE[RENDERER_TYPE["UNKNOWN"] = 0] = "UNKNOWN"; - RENDERER_TYPE[RENDERER_TYPE["WEBGL"] = 1] = "WEBGL"; - RENDERER_TYPE[RENDERER_TYPE["CANVAS"] = 2] = "CANVAS"; - })(exports.RENDERER_TYPE || (exports.RENDERER_TYPE = {})); - /** - * Bitwise OR of masks that indicate the buffers to be cleared. - * - * @static - * @memberof PIXI - * @name BUFFER_BITS - * @enum {number} - * @property {number} COLOR - Indicates the buffers currently enabled for color writing. - * @property {number} DEPTH - Indicates the depth buffer. - * @property {number} STENCIL - Indicates the stencil buffer. - */ - - (function (BUFFER_BITS) { - BUFFER_BITS[BUFFER_BITS["COLOR"] = 16384] = "COLOR"; - BUFFER_BITS[BUFFER_BITS["DEPTH"] = 256] = "DEPTH"; - BUFFER_BITS[BUFFER_BITS["STENCIL"] = 1024] = "STENCIL"; - })(exports.BUFFER_BITS || (exports.BUFFER_BITS = {})); - /** - * Various blend modes supported by PIXI. - * - * IMPORTANT - The WebGL renderer only supports the NORMAL, ADD, MULTIPLY and SCREEN blend modes. - * Anything else will silently act like NORMAL. - * - * @memberof PIXI - * @name BLEND_MODES - * @enum {number} - * @property {number} NORMAL - * @property {number} ADD - * @property {number} MULTIPLY - * @property {number} SCREEN - * @property {number} OVERLAY - * @property {number} DARKEN - * @property {number} LIGHTEN - * @property {number} COLOR_DODGE - * @property {number} COLOR_BURN - * @property {number} HARD_LIGHT - * @property {number} SOFT_LIGHT - * @property {number} DIFFERENCE - * @property {number} EXCLUSION - * @property {number} HUE - * @property {number} SATURATION - * @property {number} COLOR - * @property {number} LUMINOSITY - * @property {number} NORMAL_NPM - * @property {number} ADD_NPM - * @property {number} SCREEN_NPM - * @property {number} NONE - * @property {number} SRC_IN - * @property {number} SRC_OUT - * @property {number} SRC_ATOP - * @property {number} DST_OVER - * @property {number} DST_IN - * @property {number} DST_OUT - * @property {number} DST_ATOP - * @property {number} SUBTRACT - * @property {number} SRC_OVER - * @property {number} ERASE - * @property {number} XOR - */ - - (function (BLEND_MODES) { - BLEND_MODES[BLEND_MODES["NORMAL"] = 0] = "NORMAL"; - BLEND_MODES[BLEND_MODES["ADD"] = 1] = "ADD"; - BLEND_MODES[BLEND_MODES["MULTIPLY"] = 2] = "MULTIPLY"; - BLEND_MODES[BLEND_MODES["SCREEN"] = 3] = "SCREEN"; - BLEND_MODES[BLEND_MODES["OVERLAY"] = 4] = "OVERLAY"; - BLEND_MODES[BLEND_MODES["DARKEN"] = 5] = "DARKEN"; - BLEND_MODES[BLEND_MODES["LIGHTEN"] = 6] = "LIGHTEN"; - BLEND_MODES[BLEND_MODES["COLOR_DODGE"] = 7] = "COLOR_DODGE"; - BLEND_MODES[BLEND_MODES["COLOR_BURN"] = 8] = "COLOR_BURN"; - BLEND_MODES[BLEND_MODES["HARD_LIGHT"] = 9] = "HARD_LIGHT"; - BLEND_MODES[BLEND_MODES["SOFT_LIGHT"] = 10] = "SOFT_LIGHT"; - BLEND_MODES[BLEND_MODES["DIFFERENCE"] = 11] = "DIFFERENCE"; - BLEND_MODES[BLEND_MODES["EXCLUSION"] = 12] = "EXCLUSION"; - BLEND_MODES[BLEND_MODES["HUE"] = 13] = "HUE"; - BLEND_MODES[BLEND_MODES["SATURATION"] = 14] = "SATURATION"; - BLEND_MODES[BLEND_MODES["COLOR"] = 15] = "COLOR"; - BLEND_MODES[BLEND_MODES["LUMINOSITY"] = 16] = "LUMINOSITY"; - BLEND_MODES[BLEND_MODES["NORMAL_NPM"] = 17] = "NORMAL_NPM"; - BLEND_MODES[BLEND_MODES["ADD_NPM"] = 18] = "ADD_NPM"; - BLEND_MODES[BLEND_MODES["SCREEN_NPM"] = 19] = "SCREEN_NPM"; - BLEND_MODES[BLEND_MODES["NONE"] = 20] = "NONE"; - BLEND_MODES[BLEND_MODES["SRC_OVER"] = 0] = "SRC_OVER"; - BLEND_MODES[BLEND_MODES["SRC_IN"] = 21] = "SRC_IN"; - BLEND_MODES[BLEND_MODES["SRC_OUT"] = 22] = "SRC_OUT"; - BLEND_MODES[BLEND_MODES["SRC_ATOP"] = 23] = "SRC_ATOP"; - BLEND_MODES[BLEND_MODES["DST_OVER"] = 24] = "DST_OVER"; - BLEND_MODES[BLEND_MODES["DST_IN"] = 25] = "DST_IN"; - BLEND_MODES[BLEND_MODES["DST_OUT"] = 26] = "DST_OUT"; - BLEND_MODES[BLEND_MODES["DST_ATOP"] = 27] = "DST_ATOP"; - BLEND_MODES[BLEND_MODES["ERASE"] = 26] = "ERASE"; - BLEND_MODES[BLEND_MODES["SUBTRACT"] = 28] = "SUBTRACT"; - BLEND_MODES[BLEND_MODES["XOR"] = 29] = "XOR"; - })(exports.BLEND_MODES || (exports.BLEND_MODES = {})); - /** - * Various webgl draw modes. These can be used to specify which GL drawMode to use - * under certain situations and renderers. - * - * @memberof PIXI - * @static - * @name DRAW_MODES - * @enum {number} - * @property {number} POINTS - * @property {number} LINES - * @property {number} LINE_LOOP - * @property {number} LINE_STRIP - * @property {number} TRIANGLES - * @property {number} TRIANGLE_STRIP - * @property {number} TRIANGLE_FAN - */ - - (function (DRAW_MODES) { - DRAW_MODES[DRAW_MODES["POINTS"] = 0] = "POINTS"; - DRAW_MODES[DRAW_MODES["LINES"] = 1] = "LINES"; - DRAW_MODES[DRAW_MODES["LINE_LOOP"] = 2] = "LINE_LOOP"; - DRAW_MODES[DRAW_MODES["LINE_STRIP"] = 3] = "LINE_STRIP"; - DRAW_MODES[DRAW_MODES["TRIANGLES"] = 4] = "TRIANGLES"; - DRAW_MODES[DRAW_MODES["TRIANGLE_STRIP"] = 5] = "TRIANGLE_STRIP"; - DRAW_MODES[DRAW_MODES["TRIANGLE_FAN"] = 6] = "TRIANGLE_FAN"; - })(exports.DRAW_MODES || (exports.DRAW_MODES = {})); - /** - * Various GL texture/resources formats. - * - * @memberof PIXI - * @static - * @name FORMATS - * @enum {number} - * @property {number} RGBA=6408 - * @property {number} RGB=6407 - * @property {number} ALPHA=6406 - * @property {number} LUMINANCE=6409 - * @property {number} LUMINANCE_ALPHA=6410 - * @property {number} DEPTH_COMPONENT=6402 - * @property {number} DEPTH_STENCIL=34041 - */ - - (function (FORMATS) { - FORMATS[FORMATS["RGBA"] = 6408] = "RGBA"; - FORMATS[FORMATS["RGB"] = 6407] = "RGB"; - FORMATS[FORMATS["ALPHA"] = 6406] = "ALPHA"; - FORMATS[FORMATS["LUMINANCE"] = 6409] = "LUMINANCE"; - FORMATS[FORMATS["LUMINANCE_ALPHA"] = 6410] = "LUMINANCE_ALPHA"; - FORMATS[FORMATS["DEPTH_COMPONENT"] = 6402] = "DEPTH_COMPONENT"; - FORMATS[FORMATS["DEPTH_STENCIL"] = 34041] = "DEPTH_STENCIL"; - })(exports.FORMATS || (exports.FORMATS = {})); - /** - * Various GL target types. - * - * @memberof PIXI - * @static - * @name TARGETS - * @enum {number} - * @property {number} TEXTURE_2D=3553 - * @property {number} TEXTURE_CUBE_MAP=34067 - * @property {number} TEXTURE_2D_ARRAY=35866 - * @property {number} TEXTURE_CUBE_MAP_POSITIVE_X=34069 - * @property {number} TEXTURE_CUBE_MAP_NEGATIVE_X=34070 - * @property {number} TEXTURE_CUBE_MAP_POSITIVE_Y=34071 - * @property {number} TEXTURE_CUBE_MAP_NEGATIVE_Y=34072 - * @property {number} TEXTURE_CUBE_MAP_POSITIVE_Z=34073 - * @property {number} TEXTURE_CUBE_MAP_NEGATIVE_Z=34074 - */ - - (function (TARGETS) { - TARGETS[TARGETS["TEXTURE_2D"] = 3553] = "TEXTURE_2D"; - TARGETS[TARGETS["TEXTURE_CUBE_MAP"] = 34067] = "TEXTURE_CUBE_MAP"; - TARGETS[TARGETS["TEXTURE_2D_ARRAY"] = 35866] = "TEXTURE_2D_ARRAY"; - TARGETS[TARGETS["TEXTURE_CUBE_MAP_POSITIVE_X"] = 34069] = "TEXTURE_CUBE_MAP_POSITIVE_X"; - TARGETS[TARGETS["TEXTURE_CUBE_MAP_NEGATIVE_X"] = 34070] = "TEXTURE_CUBE_MAP_NEGATIVE_X"; - TARGETS[TARGETS["TEXTURE_CUBE_MAP_POSITIVE_Y"] = 34071] = "TEXTURE_CUBE_MAP_POSITIVE_Y"; - TARGETS[TARGETS["TEXTURE_CUBE_MAP_NEGATIVE_Y"] = 34072] = "TEXTURE_CUBE_MAP_NEGATIVE_Y"; - TARGETS[TARGETS["TEXTURE_CUBE_MAP_POSITIVE_Z"] = 34073] = "TEXTURE_CUBE_MAP_POSITIVE_Z"; - TARGETS[TARGETS["TEXTURE_CUBE_MAP_NEGATIVE_Z"] = 34074] = "TEXTURE_CUBE_MAP_NEGATIVE_Z"; - })(exports.TARGETS || (exports.TARGETS = {})); - /** - * Various GL data format types. - * - * @memberof PIXI - * @static - * @name TYPES - * @enum {number} - * @property {number} UNSIGNED_BYTE=5121 - * @property {number} UNSIGNED_SHORT=5123 - * @property {number} UNSIGNED_SHORT_5_6_5=33635 - * @property {number} UNSIGNED_SHORT_4_4_4_4=32819 - * @property {number} UNSIGNED_SHORT_5_5_5_1=32820 - * @property {number} FLOAT=5126 - * @property {number} HALF_FLOAT=36193 - */ - - (function (TYPES) { - TYPES[TYPES["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE"; - TYPES[TYPES["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT"; - TYPES[TYPES["UNSIGNED_SHORT_5_6_5"] = 33635] = "UNSIGNED_SHORT_5_6_5"; - TYPES[TYPES["UNSIGNED_SHORT_4_4_4_4"] = 32819] = "UNSIGNED_SHORT_4_4_4_4"; - TYPES[TYPES["UNSIGNED_SHORT_5_5_5_1"] = 32820] = "UNSIGNED_SHORT_5_5_5_1"; - TYPES[TYPES["FLOAT"] = 5126] = "FLOAT"; - TYPES[TYPES["HALF_FLOAT"] = 36193] = "HALF_FLOAT"; - })(exports.TYPES || (exports.TYPES = {})); - /** - * The scale modes that are supported by pixi. - * - * The {@link PIXI.settings.SCALE_MODE} scale mode affects the default scaling mode of future operations. - * It can be re-assigned to either LINEAR or NEAREST, depending upon suitability. - * - * @memberof PIXI - * @static - * @name SCALE_MODES - * @enum {number} - * @property {number} LINEAR Smooth scaling - * @property {number} NEAREST Pixelating scaling - */ - - (function (SCALE_MODES) { - SCALE_MODES[SCALE_MODES["NEAREST"] = 0] = "NEAREST"; - SCALE_MODES[SCALE_MODES["LINEAR"] = 1] = "LINEAR"; - })(exports.SCALE_MODES || (exports.SCALE_MODES = {})); - /** - * The wrap modes that are supported by pixi. - * - * The {@link PIXI.settings.WRAP_MODE} wrap mode affects the default wrapping mode of future operations. - * It can be re-assigned to either CLAMP or REPEAT, depending upon suitability. - * If the texture is non power of two then clamp will be used regardless as WebGL can - * only use REPEAT if the texture is po2. - * - * This property only affects WebGL. - * - * @name WRAP_MODES - * @memberof PIXI - * @static - * @enum {number} - * @property {number} CLAMP - The textures uvs are clamped - * @property {number} REPEAT - The texture uvs tile and repeat - * @property {number} MIRRORED_REPEAT - The texture uvs tile and repeat with mirroring - */ - - (function (WRAP_MODES) { - WRAP_MODES[WRAP_MODES["CLAMP"] = 33071] = "CLAMP"; - WRAP_MODES[WRAP_MODES["REPEAT"] = 10497] = "REPEAT"; - WRAP_MODES[WRAP_MODES["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT"; - })(exports.WRAP_MODES || (exports.WRAP_MODES = {})); - /** - * Mipmap filtering modes that are supported by pixi. - * - * The {@link PIXI.settings.MIPMAP_TEXTURES} affects default texture filtering. - * Mipmaps are generated for a baseTexture if its `mipmap` field is `ON`, - * or its `POW2` and texture dimensions are powers of 2. - * Due to platform restriction, `ON` option will work like `POW2` for webgl-1. - * - * This property only affects WebGL. - * - * @name MIPMAP_MODES - * @memberof PIXI - * @static - * @enum {number} - * @property {number} OFF - No mipmaps - * @property {number} POW2 - Generate mipmaps if texture dimensions are pow2 - * @property {number} ON - Always generate mipmaps - */ - - (function (MIPMAP_MODES) { - MIPMAP_MODES[MIPMAP_MODES["OFF"] = 0] = "OFF"; - MIPMAP_MODES[MIPMAP_MODES["POW2"] = 1] = "POW2"; - MIPMAP_MODES[MIPMAP_MODES["ON"] = 2] = "ON"; - })(exports.MIPMAP_MODES || (exports.MIPMAP_MODES = {})); - /** - * How to treat textures with premultiplied alpha - * - * @name ALPHA_MODES - * @memberof PIXI - * @static - * @enum {number} - * @property {number} NO_PREMULTIPLIED_ALPHA - Source is not premultiplied, leave it like that. - * Option for compressed and data textures that are created from typed arrays. - * @property {number} PREMULTIPLY_ON_UPLOAD - Source is not premultiplied, premultiply on upload. - * Default option, used for all loaded images. - * @property {number} PREMULTIPLIED_ALPHA - Source is already premultiplied - * Example: spine atlases with `_pma` suffix. - * @property {number} NPM - Alias for NO_PREMULTIPLIED_ALPHA. - * @property {number} UNPACK - Default option, alias for PREMULTIPLY_ON_UPLOAD. - * @property {number} PMA - Alias for PREMULTIPLIED_ALPHA. - */ - - (function (ALPHA_MODES) { - ALPHA_MODES[ALPHA_MODES["NPM"] = 0] = "NPM"; - ALPHA_MODES[ALPHA_MODES["UNPACK"] = 1] = "UNPACK"; - ALPHA_MODES[ALPHA_MODES["PMA"] = 2] = "PMA"; - ALPHA_MODES[ALPHA_MODES["NO_PREMULTIPLIED_ALPHA"] = 0] = "NO_PREMULTIPLIED_ALPHA"; - ALPHA_MODES[ALPHA_MODES["PREMULTIPLY_ON_UPLOAD"] = 1] = "PREMULTIPLY_ON_UPLOAD"; - ALPHA_MODES[ALPHA_MODES["PREMULTIPLY_ALPHA"] = 2] = "PREMULTIPLY_ALPHA"; - })(exports.ALPHA_MODES || (exports.ALPHA_MODES = {})); - /** - * How to clear renderTextures in filter - * - * @name CLEAR_MODES - * @memberof PIXI - * @static - * @enum {number} - * @property {number} BLEND - Preserve the information in the texture, blend above - * @property {number} CLEAR - Must use `gl.clear` operation - * @property {number} BLIT - Clear or blit it, depends on device and level of paranoia - * @property {number} NO - Alias for BLEND, same as `false` in earlier versions - * @property {number} YES - Alias for CLEAR, same as `true` in earlier versions - * @property {number} AUTO - Alias for BLIT - */ - - (function (CLEAR_MODES) { - CLEAR_MODES[CLEAR_MODES["NO"] = 0] = "NO"; - CLEAR_MODES[CLEAR_MODES["YES"] = 1] = "YES"; - CLEAR_MODES[CLEAR_MODES["AUTO"] = 2] = "AUTO"; - CLEAR_MODES[CLEAR_MODES["BLEND"] = 0] = "BLEND"; - CLEAR_MODES[CLEAR_MODES["CLEAR"] = 1] = "CLEAR"; - CLEAR_MODES[CLEAR_MODES["BLIT"] = 2] = "BLIT"; - })(exports.CLEAR_MODES || (exports.CLEAR_MODES = {})); - /** - * The gc modes that are supported by pixi. - * - * The {@link PIXI.settings.GC_MODE} Garbage Collection mode for PixiJS textures is AUTO - * If set to GC_MODE, the renderer will occasionally check textures usage. If they are not - * used for a specified period of time they will be removed from the GPU. They will of course - * be uploaded again when they are required. This is a silent behind the scenes process that - * should ensure that the GPU does not get filled up. - * - * Handy for mobile devices! - * This property only affects WebGL. - * - * @name GC_MODES - * @enum {number} - * @static - * @memberof PIXI - * @property {number} AUTO - Garbage collection will happen periodically automatically - * @property {number} MANUAL - Garbage collection will need to be called manually - */ - - (function (GC_MODES) { - GC_MODES[GC_MODES["AUTO"] = 0] = "AUTO"; - GC_MODES[GC_MODES["MANUAL"] = 1] = "MANUAL"; - })(exports.GC_MODES || (exports.GC_MODES = {})); - /** - * Constants that specify float precision in shaders. - * - * @name PRECISION - * @memberof PIXI - * @constant - * @static - * @enum {string} - * @property {string} LOW='lowp' - * @property {string} MEDIUM='mediump' - * @property {string} HIGH='highp' - */ - - (function (PRECISION) { - PRECISION["LOW"] = "lowp"; - PRECISION["MEDIUM"] = "mediump"; - PRECISION["HIGH"] = "highp"; - })(exports.PRECISION || (exports.PRECISION = {})); - /** - * Constants for mask implementations. - * We use `type` suffix because it leads to very different behaviours - * - * @name MASK_TYPES - * @memberof PIXI - * @static - * @enum {number} - * @property {number} NONE - Mask is ignored - * @property {number} SCISSOR - Scissor mask, rectangle on screen, cheap - * @property {number} STENCIL - Stencil mask, 1-bit, medium, works only if renderer supports stencil - * @property {number} SPRITE - Mask that uses SpriteMaskFilter, uses temporary RenderTexture - */ - - (function (MASK_TYPES) { - MASK_TYPES[MASK_TYPES["NONE"] = 0] = "NONE"; - MASK_TYPES[MASK_TYPES["SCISSOR"] = 1] = "SCISSOR"; - MASK_TYPES[MASK_TYPES["STENCIL"] = 2] = "STENCIL"; - MASK_TYPES[MASK_TYPES["SPRITE"] = 3] = "SPRITE"; - })(exports.MASK_TYPES || (exports.MASK_TYPES = {})); - /** - * Constants for multi-sampling antialiasing. - * - * @see PIXI.Framebuffer#multisample - * - * @name MSAA_QUALITY - * @memberof PIXI - * @static - * @enum {number} - * @property {number} NONE - No multisampling for this renderTexture - * @property {number} LOW - Try 2 samples - * @property {number} MEDIUM - Try 4 samples - * @property {number} HIGH - Try 8 samples - */ - - (function (MSAA_QUALITY) { - MSAA_QUALITY[MSAA_QUALITY["NONE"] = 0] = "NONE"; - MSAA_QUALITY[MSAA_QUALITY["LOW"] = 2] = "LOW"; - MSAA_QUALITY[MSAA_QUALITY["MEDIUM"] = 4] = "MEDIUM"; - MSAA_QUALITY[MSAA_QUALITY["HIGH"] = 8] = "HIGH"; - })(exports.MSAA_QUALITY || (exports.MSAA_QUALITY = {})); - - /*! - * @pixi/utils - v5.3.3 - * Compiled Tue, 04 Aug 2020 16:23:09 UTC - * - * @pixi/utils is licensed under the MIT License. - * http://www.opensource.org/licenses/mit-license - */ - - /** - * The prefix that denotes a URL is for a retina asset. - * - * @static - * @name RETINA_PREFIX - * @memberof PIXI.settings - * @type {RegExp} - * @default /@([0-9\.]+)x/ - * @example `@2x` - */ - settings.RETINA_PREFIX = /@([0-9\.]+)x/; - /** - * Should the `failIfMajorPerformanceCaveat` flag be enabled as a context option used in the `isWebGLSupported` function. - * For most scenarios this should be left as true, as otherwise the user may have a poor experience. - * However, it can be useful to disable under certain scenarios, such as headless unit tests. - * - * @static - * @name FAIL_IF_MAJOR_PERFORMANCE_CAVEAT - * @memberof PIXI.settings - * @type {boolean} - * @default true - */ - settings.FAIL_IF_MAJOR_PERFORMANCE_CAVEAT = true; - - var saidHello = false; - var VERSION = '5.3.3'; - /** - * Skips the hello message of renderers that are created after this is run. - * - * @function skipHello - * @memberof PIXI.utils - */ - function skipHello() { - saidHello = true; - } - /** - * Logs out the version and renderer information for this running instance of PIXI. - * If you don't want to see this message you can run `PIXI.utils.skipHello()` before - * creating your renderer. Keep in mind that doing that will forever make you a jerk face. - * - * @static - * @function sayHello - * @memberof PIXI.utils - * @param {string} type - The string renderer type to log. - */ - function sayHello(type) { - var _a; - if (saidHello) { - return; - } - if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1) { - var args = [ - "\n %c %c %c PixiJS " + VERSION + " - \u2730 " + type + " \u2730 %c %c http://www.pixijs.com/ %c %c \u2665%c\u2665%c\u2665 \n\n", - 'background: #ff66a5; padding:5px 0;', - 'background: #ff66a5; padding:5px 0;', - 'color: #ff66a5; background: #030307; padding:5px 0;', - 'background: #ff66a5; padding:5px 0;', - 'background: #ffc3dc; padding:5px 0;', - 'background: #ff66a5; padding:5px 0;', - 'color: #ff2424; background: #fff; padding:5px 0;', - 'color: #ff2424; background: #fff; padding:5px 0;', - 'color: #ff2424; background: #fff; padding:5px 0;' ]; - (_a = window.console).log.apply(_a, args); - } - else if (window.console) { - window.console.log("PixiJS " + VERSION + " - " + type + " - http://www.pixijs.com/"); - } - saidHello = true; - } - - var supported; - /** - * Helper for checking for WebGL support. - * - * @memberof PIXI.utils - * @function isWebGLSupported - * @return {boolean} Is WebGL supported. - */ - function isWebGLSupported() { - if (typeof supported === 'undefined') { - supported = (function supported() { - var contextOptions = { - stencil: true, - failIfMajorPerformanceCaveat: settings.FAIL_IF_MAJOR_PERFORMANCE_CAVEAT, - }; - try { - if (!window.WebGLRenderingContext) { - return false; - } - var canvas = document.createElement('canvas'); - var gl = (canvas.getContext('webgl', contextOptions) - || canvas.getContext('experimental-webgl', contextOptions)); - var success = !!(gl && gl.getContextAttributes().stencil); - if (gl) { - var loseContext = gl.getExtension('WEBGL_lose_context'); - if (loseContext) { - loseContext.loseContext(); - } - } - gl = null; - return success; - } - catch (e) { - return false; - } - })(); - } - return supported; - } - - /** - * Converts a hexadecimal color number to an [R, G, B] array of normalized floats (numbers from 0.0 to 1.0). - * - * @example - * PIXI.utils.hex2rgb(0xffffff); // returns [1, 1, 1] - * @memberof PIXI.utils - * @function hex2rgb - * @param {number} hex - The hexadecimal number to convert - * @param {number[]} [out=[]] - If supplied, this array will be used rather than returning a new one - * @return {number[]} An array representing the [R, G, B] of the color where all values are floats. - */ - function hex2rgb(hex, out) { - if (out === void 0) { out = []; } - out[0] = ((hex >> 16) & 0xFF) / 255; - out[1] = ((hex >> 8) & 0xFF) / 255; - out[2] = (hex & 0xFF) / 255; - return out; - } - /** - * Converts a hexadecimal color number to a string. - * - * @example - * PIXI.utils.hex2string(0xffffff); // returns "#ffffff" - * @memberof PIXI.utils - * @function hex2string - * @param {number} hex - Number in hex (e.g., `0xffffff`) - * @return {string} The string color (e.g., `"#ffffff"`). - */ - function hex2string(hex) { - var hexString = hex.toString(16); - hexString = '000000'.substr(0, 6 - hexString.length) + hexString; - return "#" + hexString; - } - /** - * Converts a hexadecimal string to a hexadecimal color number. - * - * @example - * PIXI.utils.string2hex("#ffffff"); // returns 0xffffff - * @memberof PIXI.utils - * @function string2hex - * @param {string} string - The string color (e.g., `"#ffffff"`) - * @return {number} Number in hexadecimal. - */ - function string2hex(string) { - if (typeof string === 'string' && string[0] === '#') { - string = string.substr(1); - } - return parseInt(string, 16); - } - /** - * Converts a color as an [R, G, B] array of normalized floats to a hexadecimal number. - * - * @example - * PIXI.utils.rgb2hex([1, 1, 1]); // returns 0xffffff - * @memberof PIXI.utils - * @function rgb2hex - * @param {number[]} rgb - Array of numbers where all values are normalized floats from 0.0 to 1.0. - * @return {number} Number in hexadecimal. - */ - function rgb2hex(rgb) { - return (((rgb[0] * 255) << 16) + ((rgb[1] * 255) << 8) + (rgb[2] * 255 | 0)); - } - - /** - * Corrects PixiJS blend, takes premultiplied alpha into account - * - * @memberof PIXI.utils - * @function mapPremultipliedBlendModes - * @private - * @return {Array} Mapped modes. - */ - function mapPremultipliedBlendModes() { - var pm = []; - var npm = []; - for (var i = 0; i < 32; i++) { - pm[i] = i; - npm[i] = i; - } - pm[exports.BLEND_MODES.NORMAL_NPM] = exports.BLEND_MODES.NORMAL; - pm[exports.BLEND_MODES.ADD_NPM] = exports.BLEND_MODES.ADD; - pm[exports.BLEND_MODES.SCREEN_NPM] = exports.BLEND_MODES.SCREEN; - npm[exports.BLEND_MODES.NORMAL] = exports.BLEND_MODES.NORMAL_NPM; - npm[exports.BLEND_MODES.ADD] = exports.BLEND_MODES.ADD_NPM; - npm[exports.BLEND_MODES.SCREEN] = exports.BLEND_MODES.SCREEN_NPM; - var array = []; - array.push(npm); - array.push(pm); - return array; - } - /** - * maps premultiply flag and blendMode to adjusted blendMode - * @memberof PIXI.utils - * @const premultiplyBlendMode - * @type {Array} - */ - var premultiplyBlendMode = mapPremultipliedBlendModes(); - /** - * changes blendMode according to texture format - * - * @memberof PIXI.utils - * @function correctBlendMode - * @param {number} blendMode - supposed blend mode - * @param {boolean} premultiplied - whether source is premultiplied - * @returns {number} true blend mode for this texture - */ - function correctBlendMode(blendMode, premultiplied) { - return premultiplyBlendMode[premultiplied ? 1 : 0][blendMode]; - } - /** - * combines rgb and alpha to out array - * - * @memberof PIXI.utils - * @function premultiplyRgba - * @param {Float32Array|number[]} rgb - input rgb - * @param {number} alpha - alpha param - * @param {Float32Array} [out] - output - * @param {boolean} [premultiply=true] - do premultiply it - * @returns {Float32Array} vec4 rgba - */ - function premultiplyRgba(rgb, alpha, out, premultiply) { - out = out || new Float32Array(4); - if (premultiply || premultiply === undefined) { - out[0] = rgb[0] * alpha; - out[1] = rgb[1] * alpha; - out[2] = rgb[2] * alpha; - } - else { - out[0] = rgb[0]; - out[1] = rgb[1]; - out[2] = rgb[2]; - } - out[3] = alpha; - return out; - } - /** - * premultiplies tint - * - * @memberof PIXI.utils - * @function premultiplyTint - * @param {number} tint - integer RGB - * @param {number} alpha - floating point alpha (0.0-1.0) - * @returns {number} tint multiplied by alpha - */ - function premultiplyTint(tint, alpha) { - if (alpha === 1.0) { - return (alpha * 255 << 24) + tint; - } - if (alpha === 0.0) { - return 0; - } - var R = ((tint >> 16) & 0xFF); - var G = ((tint >> 8) & 0xFF); - var B = (tint & 0xFF); - R = ((R * alpha) + 0.5) | 0; - G = ((G * alpha) + 0.5) | 0; - B = ((B * alpha) + 0.5) | 0; - return (alpha * 255 << 24) + (R << 16) + (G << 8) + B; - } - /** - * converts integer tint and float alpha to vec4 form, premultiplies by default - * - * @memberof PIXI.utils - * @function premultiplyTintToRgba - * @param {number} tint - input tint - * @param {number} alpha - alpha param - * @param {Float32Array} [out] output - * @param {boolean} [premultiply=true] - do premultiply it - * @returns {Float32Array} vec4 rgba - */ - function premultiplyTintToRgba(tint, alpha, out, premultiply) { - out = out || new Float32Array(4); - out[0] = ((tint >> 16) & 0xFF) / 255.0; - out[1] = ((tint >> 8) & 0xFF) / 255.0; - out[2] = (tint & 0xFF) / 255.0; - if (premultiply || premultiply === undefined) { - out[0] *= alpha; - out[1] *= alpha; - out[2] *= alpha; - } - out[3] = alpha; - return out; - } - - /** - * Generic Mask Stack data structure - * - * @memberof PIXI.utils - * @function createIndicesForQuads - * @param {number} size - Number of quads - * @param {Uint16Array|Uint32Array} [outBuffer] - Buffer for output, length has to be `6 * size` - * @return {Uint16Array|Uint32Array} - Resulting index buffer - */ - function createIndicesForQuads(size, outBuffer) { - if (outBuffer === void 0) { outBuffer = null; } - // the total number of indices in our array, there are 6 points per quad. - var totalIndices = size * 6; - outBuffer = outBuffer || new Uint16Array(totalIndices); - if (outBuffer.length !== totalIndices) { - throw new Error("Out buffer length is incorrect, got " + outBuffer.length + " and expected " + totalIndices); - } - // fill the indices with the quads to draw - for (var i = 0, j = 0; i < totalIndices; i += 6, j += 4) { - outBuffer[i + 0] = j + 0; - outBuffer[i + 1] = j + 1; - outBuffer[i + 2] = j + 2; - outBuffer[i + 3] = j + 0; - outBuffer[i + 4] = j + 2; - outBuffer[i + 5] = j + 3; - } - return outBuffer; - } - - function getBufferType(array) { - if (array.BYTES_PER_ELEMENT === 4) { - if (array instanceof Float32Array) { - return 'Float32Array'; - } - else if (array instanceof Uint32Array) { - return 'Uint32Array'; - } - return 'Int32Array'; - } - else if (array.BYTES_PER_ELEMENT === 2) { - if (array instanceof Uint16Array) { - return 'Uint16Array'; - } - } - else if (array.BYTES_PER_ELEMENT === 1) { - if (array instanceof Uint8Array) { - return 'Uint8Array'; - } - } - // TODO map out the rest of the array elements! - return null; - } - - /* eslint-disable object-shorthand */ - var map = { Float32Array: Float32Array, Uint32Array: Uint32Array, Int32Array: Int32Array, Uint8Array: Uint8Array }; - function interleaveTypedArrays(arrays, sizes) { - var outSize = 0; - var stride = 0; - var views = {}; - for (var i = 0; i < arrays.length; i++) { - stride += sizes[i]; - outSize += arrays[i].length; - } - var buffer = new ArrayBuffer(outSize * 4); - var out = null; - var littleOffset = 0; - for (var i = 0; i < arrays.length; i++) { - var size = sizes[i]; - var array = arrays[i]; - /* - @todo This is unsafe casting but consistent with how the code worked previously. Should it stay this way - or should and `getBufferTypeUnsafe` function be exposed that throws an Error if unsupported type is passed? - */ - var type = getBufferType(array); - if (!views[type]) { - views[type] = new map[type](buffer); - } - out = views[type]; - for (var j = 0; j < array.length; j++) { - var indexStart = ((j / size | 0) * stride) + littleOffset; - var index = j % size; - out[indexStart + index] = array[j]; - } - littleOffset += size; - } - return new Float32Array(buffer); - } - - // Taken from the bit-twiddle package - /** - * Rounds to next power of two. - * - * @function nextPow2 - * @memberof PIXI.utils - * @param {number} v - input value - * @return {number} - */ - function nextPow2(v) { - v += v === 0 ? 1 : 0; - --v; - v |= v >>> 1; - v |= v >>> 2; - v |= v >>> 4; - v |= v >>> 8; - v |= v >>> 16; - return v + 1; - } - /** - * Checks if a number is a power of two. - * - * @function isPow2 - * @memberof PIXI.utils - * @param {number} v - input value - * @return {boolean} `true` if value is power of two - */ - function isPow2(v) { - return !(v & (v - 1)) && (!!v); - } - /** - * Computes ceil of log base 2 - * - * @function log2 - * @memberof PIXI.utils - * @param {number} v - input value - * @return {number} logarithm base 2 - */ - function log2(v) { - var r = (v > 0xFFFF ? 1 : 0) << 4; - v >>>= r; - var shift = (v > 0xFF ? 1 : 0) << 3; - v >>>= shift; - r |= shift; - shift = (v > 0xF ? 1 : 0) << 2; - v >>>= shift; - r |= shift; - shift = (v > 0x3 ? 1 : 0) << 1; - v >>>= shift; - r |= shift; - return r | (v >> 1); - } - - /** - * Remove items from a javascript array without generating garbage - * - * @function removeItems - * @memberof PIXI.utils - * @param {Array} arr - Array to remove elements from - * @param {number} startIdx - starting index - * @param {number} removeCount - how many to remove - */ - function removeItems(arr, startIdx, removeCount) { - var length = arr.length; - var i; - if (startIdx >= length || removeCount === 0) { - return; - } - removeCount = (startIdx + removeCount > length ? length - startIdx : removeCount); - var len = length - removeCount; - for (i = startIdx; i < len; ++i) { - arr[i] = arr[i + removeCount]; - } - arr.length = len; - } - - /** - * Returns sign of number - * - * @memberof PIXI.utils - * @function sign - * @param {number} n - the number to check the sign of - * @returns {number} 0 if `n` is 0, -1 if `n` is negative, 1 if `n` is positive - */ - function sign$1(n) { - if (n === 0) - { return 0; } - return n < 0 ? -1 : 1; - } - - var nextUid = 0; - /** - * Gets the next unique identifier - * - * @memberof PIXI.utils - * @function uid - * @return {number} The next unique identifier to use. - */ - function uid() { - return ++nextUid; - } - - // A map of warning messages already fired - var warnings = {}; - /** - * Helper for warning developers about deprecated features & settings. - * A stack track for warnings is given; useful for tracking-down where - * deprecated methods/properties/classes are being used within the code. - * - * @memberof PIXI.utils - * @function deprecation - * @param {string} version - The version where the feature became deprecated - * @param {string} message - Message should include what is deprecated, where, and the new solution - * @param {number} [ignoreDepth=3] - The number of steps to ignore at the top of the error stack - * this is mostly to ignore internal deprecation calls. - */ - function deprecation(version, message, ignoreDepth) { - if (ignoreDepth === void 0) { ignoreDepth = 3; } - // Ignore duplicat - if (warnings[message]) { - return; - } - /* eslint-disable no-console */ - var stack = new Error().stack; - // Handle IE < 10 and Safari < 6 - if (typeof stack === 'undefined') { - console.warn('PixiJS Deprecation Warning: ', message + "\nDeprecated since v" + version); - } - else { - // chop off the stack trace which includes PixiJS internal calls - stack = stack.split('\n').splice(ignoreDepth).join('\n'); - if (console.groupCollapsed) { - console.groupCollapsed('%cPixiJS Deprecation Warning: %c%s', 'color:#614108;background:#fffbe6', 'font-weight:normal;color:#614108;background:#fffbe6', message + "\nDeprecated since v" + version); - console.warn(stack); - console.groupEnd(); - } - else { - console.warn('PixiJS Deprecation Warning: ', message + "\nDeprecated since v" + version); - console.warn(stack); - } - } - /* eslint-enable no-console */ - warnings[message] = true; - } - - /** - * @todo Describe property usage - * - * @static - * @name ProgramCache - * @memberof PIXI.utils - * @type {Object} - */ - var ProgramCache = {}; - /** - * @todo Describe property usage - * - * @static - * @name TextureCache - * @memberof PIXI.utils - * @type {Object} - */ - var TextureCache = Object.create(null); - /** - * @todo Describe property usage - * - * @static - * @name BaseTextureCache - * @memberof PIXI.utils - * @type {Object} - */ - var BaseTextureCache = Object.create(null); - /** - * Destroys all texture in the cache - * - * @memberof PIXI.utils - * @function destroyTextureCache - */ - function destroyTextureCache() { - var key; - for (key in TextureCache) { - TextureCache[key].destroy(); - } - for (key in BaseTextureCache) { - BaseTextureCache[key].destroy(); - } - } - /** - * Removes all textures from cache, but does not destroy them - * - * @memberof PIXI.utils - * @function clearTextureCache - */ - function clearTextureCache() { - var key; - for (key in TextureCache) { - delete TextureCache[key]; - } - for (key in BaseTextureCache) { - delete BaseTextureCache[key]; - } - } - - /** - * Creates a Canvas element of the given size to be used as a target for rendering to. - * - * @class - * @memberof PIXI.utils - */ - var CanvasRenderTarget = /** @class */ (function () { - /** - * @param {number} width - the width for the newly created canvas - * @param {number} height - the height for the newly created canvas - * @param {number} [resolution=1] - The resolution / device pixel ratio of the canvas - */ - function CanvasRenderTarget(width, height, resolution) { - /** - * The Canvas object that belongs to this CanvasRenderTarget. - * - * @member {HTMLCanvasElement} - */ - this.canvas = document.createElement('canvas'); - /** - * A CanvasRenderingContext2D object representing a two-dimensional rendering context. - * - * @member {CanvasRenderingContext2D} - */ - this.context = this.canvas.getContext('2d'); - this.resolution = resolution || settings.RESOLUTION; - this.resize(width, height); - } - /** - * Clears the canvas that was created by the CanvasRenderTarget class. - * - * @private - */ - CanvasRenderTarget.prototype.clear = function () { - this.context.setTransform(1, 0, 0, 1, 0, 0); - this.context.clearRect(0, 0, this.canvas.width, this.canvas.height); - }; - /** - * Resizes the canvas to the specified width and height. - * - * @param {number} width - the new width of the canvas - * @param {number} height - the new height of the canvas - */ - CanvasRenderTarget.prototype.resize = function (width, height) { - this.canvas.width = width * this.resolution; - this.canvas.height = height * this.resolution; - }; - /** - * Destroys this canvas. - * - */ - CanvasRenderTarget.prototype.destroy = function () { - this.context = null; - this.canvas = null; - }; - Object.defineProperty(CanvasRenderTarget.prototype, "width", { - /** - * The width of the canvas buffer in pixels. - * - * @member {number} - */ - get: function () { - return this.canvas.width; - }, - set: function (val) { - this.canvas.width = val; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(CanvasRenderTarget.prototype, "height", { - /** - * The height of the canvas buffer in pixels. - * - * @member {number} - */ - get: function () { - return this.canvas.height; - }, - set: function (val) { - this.canvas.height = val; - }, - enumerable: false, - configurable: true - }); - return CanvasRenderTarget; - }()); - - /** - * Trim transparent borders from a canvas - * - * @memberof PIXI.utils - * @function trimCanvas - * @param {HTMLCanvasElement} canvas - the canvas to trim - * @returns {object} Trim data - */ - function trimCanvas(canvas) { - // https://gist.github.com/remy/784508 - var width = canvas.width; - var height = canvas.height; - var context = canvas.getContext('2d'); - var imageData = context.getImageData(0, 0, width, height); - var pixels = imageData.data; - var len = pixels.length; - var bound = { - top: null, - left: null, - right: null, - bottom: null, - }; - var data = null; - var i; - var x; - var y; - for (i = 0; i < len; i += 4) { - if (pixels[i + 3] !== 0) { - x = (i / 4) % width; - y = ~~((i / 4) / width); - if (bound.top === null) { - bound.top = y; - } - if (bound.left === null) { - bound.left = x; - } - else if (x < bound.left) { - bound.left = x; - } - if (bound.right === null) { - bound.right = x + 1; - } - else if (bound.right < x) { - bound.right = x + 1; - } - if (bound.bottom === null) { - bound.bottom = y; - } - else if (bound.bottom < y) { - bound.bottom = y; - } - } - } - if (bound.top !== null) { - width = bound.right - bound.left; - height = bound.bottom - bound.top + 1; - data = context.getImageData(bound.left, bound.top, width, height); - } - return { - height: height, - width: width, - data: data, - }; - } - - /** - * Regexp for data URI. - * Based on: {@link https://github.com/ragingwind/data-uri-regex} - * - * @static - * @constant {RegExp|string} DATA_URI - * @memberof PIXI - * @example data:image/png;base64 - */ - var DATA_URI = /^\s*data:(?:([\w-]+)\/([\w+.-]+))?(?:;charset=([\w-]+))?(?:;(base64))?,(.*)/i; - - /** - * @memberof PIXI.utils - * @interface DecomposedDataUri - */ - /** - * type, eg. `image` - * @memberof PIXI.utils.DecomposedDataUri# - * @member {string} mediaType - */ - /** - * Sub type, eg. `png` - * @memberof PIXI.utils.DecomposedDataUri# - * @member {string} subType - */ - /** - * @memberof PIXI.utils.DecomposedDataUri# - * @member {string} charset - */ - /** - * Data encoding, eg. `base64` - * @memberof PIXI.utils.DecomposedDataUri# - * @member {string} encoding - */ - /** - * The actual data - * @memberof PIXI.utils.DecomposedDataUri# - * @member {string} data - */ - /** - * Split a data URI into components. Returns undefined if - * parameter `dataUri` is not a valid data URI. - * - * @memberof PIXI.utils - * @function decomposeDataUri - * @param {string} dataUri - the data URI to check - * @return {PIXI.utils.DecomposedDataUri|undefined} The decomposed data uri or undefined - */ - function decomposeDataUri(dataUri) { - var dataUriMatch = DATA_URI.exec(dataUri); - if (dataUriMatch) { - return { - mediaType: dataUriMatch[1] ? dataUriMatch[1].toLowerCase() : undefined, - subType: dataUriMatch[2] ? dataUriMatch[2].toLowerCase() : undefined, - charset: dataUriMatch[3] ? dataUriMatch[3].toLowerCase() : undefined, - encoding: dataUriMatch[4] ? dataUriMatch[4].toLowerCase() : undefined, - data: dataUriMatch[5], - }; - } - return undefined; - } - - var tempAnchor; - /** - * Sets the `crossOrigin` property for this resource based on if the url - * for this resource is cross-origin. If crossOrigin was manually set, this - * function does nothing. - * Nipped from the resource loader! - * - * @ignore - * @param {string} url - The url to test. - * @param {object} [loc=window.location] - The location object to test against. - * @return {string} The crossOrigin value to use (or empty string for none). - */ - function determineCrossOrigin(url, loc) { - if (loc === void 0) { loc = window.location; } - // data: and javascript: urls are considered same-origin - if (url.indexOf('data:') === 0) { - return ''; - } - // default is window.location - loc = loc || window.location; - if (!tempAnchor) { - tempAnchor = document.createElement('a'); - } - // let the browser determine the full href for the url of this resource and then - // parse with the node url lib, we can't use the properties of the anchor element - // because they don't work in IE9 :( - tempAnchor.href = url; - var parsedUrl = parse(tempAnchor.href); - var samePort = (!parsedUrl.port && loc.port === '') || (parsedUrl.port === loc.port); - // if cross origin - if (parsedUrl.hostname !== loc.hostname || !samePort || parsedUrl.protocol !== loc.protocol) { - return 'anonymous'; - } - return ''; - } - - /** - * get the resolution / device pixel ratio of an asset by looking for the prefix - * used by spritesheets and image urls - * - * @memberof PIXI.utils - * @function getResolutionOfUrl - * @param {string} url - the image path - * @param {number} [defaultValue=1] - the defaultValue if no filename prefix is set. - * @return {number} resolution / device pixel ratio of an asset - */ - function getResolutionOfUrl(url, defaultValue) { - var resolution = settings.RETINA_PREFIX.exec(url); - if (resolution) { - return parseFloat(resolution[1]); - } - return defaultValue !== undefined ? defaultValue : 1; - } - - var utils_es = ({ - BaseTextureCache: BaseTextureCache, - CanvasRenderTarget: CanvasRenderTarget, - DATA_URI: DATA_URI, - ProgramCache: ProgramCache, - TextureCache: TextureCache, - clearTextureCache: clearTextureCache, - correctBlendMode: correctBlendMode, - createIndicesForQuads: createIndicesForQuads, - decomposeDataUri: decomposeDataUri, - deprecation: deprecation, - destroyTextureCache: destroyTextureCache, - determineCrossOrigin: determineCrossOrigin, - getBufferType: getBufferType, - getResolutionOfUrl: getResolutionOfUrl, - hex2rgb: hex2rgb, - hex2string: hex2string, - interleaveTypedArrays: interleaveTypedArrays, - isPow2: isPow2, - isWebGLSupported: isWebGLSupported, - log2: log2, - nextPow2: nextPow2, - premultiplyBlendMode: premultiplyBlendMode, - premultiplyRgba: premultiplyRgba, - premultiplyTint: premultiplyTint, - premultiplyTintToRgba: premultiplyTintToRgba, - removeItems: removeItems, - rgb2hex: rgb2hex, - sayHello: sayHello, - sign: sign$1, - skipHello: skipHello, - string2hex: string2hex, - trimCanvas: trimCanvas, - uid: uid, - isMobile: isMobile$1, - EventEmitter: eventemitter3, - earcut: earcut_1, - url: url - }); - - /*! - * @pixi/math - v5.3.3 - * Compiled Tue, 04 Aug 2020 16:23:09 UTC - * - * @pixi/math is licensed under the MIT License. - * http://www.opensource.org/licenses/mit-license - */ - /** - * Two Pi. - * - * @static - * @constant {number} PI_2 - * @memberof PIXI - */ - var PI_2 = Math.PI * 2; - /** - * Conversion factor for converting radians to degrees. - * - * @static - * @constant {number} RAD_TO_DEG - * @memberof PIXI - */ - var RAD_TO_DEG = 180 / Math.PI; - /** - * Conversion factor for converting degrees to radians. - * - * @static - * @constant {number} DEG_TO_RAD - * @memberof PIXI - */ - var DEG_TO_RAD = Math.PI / 180; - - (function (SHAPES) { - SHAPES[SHAPES["POLY"] = 0] = "POLY"; - SHAPES[SHAPES["RECT"] = 1] = "RECT"; - SHAPES[SHAPES["CIRC"] = 2] = "CIRC"; - SHAPES[SHAPES["ELIP"] = 3] = "ELIP"; - SHAPES[SHAPES["RREC"] = 4] = "RREC"; - })(exports.SHAPES || (exports.SHAPES = {})); - /** - * Constants that identify shapes, mainly to prevent `instanceof` calls. - * - * @static - * @constant - * @name SHAPES - * @memberof PIXI - * @type {enum} - * @property {number} POLY Polygon - * @property {number} RECT Rectangle - * @property {number} CIRC Circle - * @property {number} ELIP Ellipse - * @property {number} RREC Rounded Rectangle - * @enum {number} - */ - - /** - * Size object, contains width and height - * - * @memberof PIXI - * @typedef {object} ISize - * @property {number} width - Width component - * @property {number} height - Height component - */ - /** - * Rectangle object is an area defined by its position, as indicated by its top-left corner - * point (x, y) and by its width and its height. - * - * @class - * @memberof PIXI - */ - var Rectangle = /** @class */ (function () { - /** - * @param {number} [x=0] - The X coordinate of the upper-left corner of the rectangle - * @param {number} [y=0] - The Y coordinate of the upper-left corner of the rectangle - * @param {number} [width=0] - The overall width of this rectangle - * @param {number} [height=0] - The overall height of this rectangle - */ - function Rectangle(x, y, width, height) { - if (x === void 0) { x = 0; } - if (y === void 0) { y = 0; } - if (width === void 0) { width = 0; } - if (height === void 0) { height = 0; } - /** - * @member {number} - * @default 0 - */ - this.x = Number(x); - /** - * @member {number} - * @default 0 - */ - this.y = Number(y); - /** - * @member {number} - * @default 0 - */ - this.width = Number(width); - /** - * @member {number} - * @default 0 - */ - this.height = Number(height); - /** - * The type of the object, mainly used to avoid `instanceof` checks - * - * @member {number} - * @readOnly - * @default PIXI.SHAPES.RECT - * @see PIXI.SHAPES - */ - this.type = exports.SHAPES.RECT; - } - Object.defineProperty(Rectangle.prototype, "left", { - /** - * returns the left edge of the rectangle - * - * @member {number} - */ - get: function () { - return this.x; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(Rectangle.prototype, "right", { - /** - * returns the right edge of the rectangle - * - * @member {number} - */ - get: function () { - return this.x + this.width; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(Rectangle.prototype, "top", { - /** - * returns the top edge of the rectangle - * - * @member {number} - */ - get: function () { - return this.y; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(Rectangle.prototype, "bottom", { - /** - * returns the bottom edge of the rectangle - * - * @member {number} - */ - get: function () { - return this.y + this.height; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(Rectangle, "EMPTY", { - /** - * A constant empty rectangle. - * - * @static - * @constant - * @member {PIXI.Rectangle} - * @return {PIXI.Rectangle} An empty rectangle - */ - get: function () { - return new Rectangle(0, 0, 0, 0); - }, - enumerable: false, - configurable: true - }); - /** - * Creates a clone of this Rectangle - * - * @return {PIXI.Rectangle} a copy of the rectangle - */ - Rectangle.prototype.clone = function () { - return new Rectangle(this.x, this.y, this.width, this.height); - }; - /** - * Copies another rectangle to this one. - * - * @param {PIXI.Rectangle} rectangle - The rectangle to copy from. - * @return {PIXI.Rectangle} Returns itself. - */ - Rectangle.prototype.copyFrom = function (rectangle) { - this.x = rectangle.x; - this.y = rectangle.y; - this.width = rectangle.width; - this.height = rectangle.height; - return this; - }; - /** - * Copies this rectangle to another one. - * - * @param {PIXI.Rectangle} rectangle - The rectangle to copy to. - * @return {PIXI.Rectangle} Returns given parameter. - */ - Rectangle.prototype.copyTo = function (rectangle) { - rectangle.x = this.x; - rectangle.y = this.y; - rectangle.width = this.width; - rectangle.height = this.height; - return rectangle; - }; - /** - * Checks whether the x and y coordinates given are contained within this Rectangle - * - * @param {number} x - The X coordinate of the point to test - * @param {number} y - The Y coordinate of the point to test - * @return {boolean} Whether the x/y coordinates are within this Rectangle - */ - Rectangle.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { - return false; - } - if (x >= this.x && x < this.x + this.width) { - if (y >= this.y && y < this.y + this.height) { - return true; - } - } - return false; - }; - /** - * Pads the rectangle making it grow in all directions. - * If paddingY is omitted, both paddingX and paddingY will be set to paddingX. - * - * @param {number} [paddingX=0] - The horizontal padding amount. - * @param {number} [paddingY=0] - The vertical padding amount. - * @return {PIXI.Rectangle} Returns itself. - */ - Rectangle.prototype.pad = function (paddingX, paddingY) { - if (paddingX === void 0) { paddingX = 0; } - if (paddingY === void 0) { paddingY = paddingX; } - this.x -= paddingX; - this.y -= paddingY; - this.width += paddingX * 2; - this.height += paddingY * 2; - return this; - }; - /** - * Fits this rectangle around the passed one. - * - * @param {PIXI.Rectangle} rectangle - The rectangle to fit. - * @return {PIXI.Rectangle} Returns itself. - */ - Rectangle.prototype.fit = function (rectangle) { - var x1 = Math.max(this.x, rectangle.x); - var x2 = Math.min(this.x + this.width, rectangle.x + rectangle.width); - var y1 = Math.max(this.y, rectangle.y); - var y2 = Math.min(this.y + this.height, rectangle.y + rectangle.height); - this.x = x1; - this.width = Math.max(x2 - x1, 0); - this.y = y1; - this.height = Math.max(y2 - y1, 0); - return this; - }; - /** - * Enlarges rectangle that way its corners lie on grid - * - * @param {number} [resolution=1] resolution - * @param {number} [eps=0.001] precision - * @return {PIXI.Rectangle} Returns itself. - */ - Rectangle.prototype.ceil = function (resolution, eps) { - if (resolution === void 0) { resolution = 1; } - if (eps === void 0) { eps = 0.001; } - var x2 = Math.ceil((this.x + this.width - eps) * resolution) / resolution; - var y2 = Math.ceil((this.y + this.height - eps) * resolution) / resolution; - this.x = Math.floor((this.x + eps) * resolution) / resolution; - this.y = Math.floor((this.y + eps) * resolution) / resolution; - this.width = x2 - this.x; - this.height = y2 - this.y; - return this; - }; - /** - * Enlarges this rectangle to include the passed rectangle. - * - * @param {PIXI.Rectangle} rectangle - The rectangle to include. - * @return {PIXI.Rectangle} Returns itself. - */ - Rectangle.prototype.enlarge = function (rectangle) { - var x1 = Math.min(this.x, rectangle.x); - var x2 = Math.max(this.x + this.width, rectangle.x + rectangle.width); - var y1 = Math.min(this.y, rectangle.y); - var y2 = Math.max(this.y + this.height, rectangle.y + rectangle.height); - this.x = x1; - this.width = x2 - x1; - this.y = y1; - this.height = y2 - y1; - return this; - }; - return Rectangle; - }()); - - /** - * The Circle object is used to help draw graphics and can also be used to specify a hit area for displayObjects. - * - * @class - * @memberof PIXI - */ - var Circle = /** @class */ (function () { - /** - * @param {number} [x=0] - The X coordinate of the center of this circle - * @param {number} [y=0] - The Y coordinate of the center of this circle - * @param {number} [radius=0] - The radius of the circle - */ - function Circle(x, y, radius) { - if (x === void 0) { x = 0; } - if (y === void 0) { y = 0; } - if (radius === void 0) { radius = 0; } - /** - * @member {number} - * @default 0 - */ - this.x = x; - /** - * @member {number} - * @default 0 - */ - this.y = y; - /** - * @member {number} - * @default 0 - */ - this.radius = radius; - /** - * The type of the object, mainly used to avoid `instanceof` checks - * - * @member {number} - * @readOnly - * @default PIXI.SHAPES.CIRC - * @see PIXI.SHAPES - */ - this.type = exports.SHAPES.CIRC; - } - /** - * Creates a clone of this Circle instance - * - * @return {PIXI.Circle} a copy of the Circle - */ - Circle.prototype.clone = function () { - return new Circle(this.x, this.y, this.radius); - }; - /** - * Checks whether the x and y coordinates given are contained within this circle - * - * @param {number} x - The X coordinate of the point to test - * @param {number} y - The Y coordinate of the point to test - * @return {boolean} Whether the x/y coordinates are within this Circle - */ - Circle.prototype.contains = function (x, y) { - if (this.radius <= 0) { - return false; - } - var r2 = this.radius * this.radius; - var dx = (this.x - x); - var dy = (this.y - y); - dx *= dx; - dy *= dy; - return (dx + dy <= r2); - }; - /** - * Returns the framing rectangle of the circle as a Rectangle object - * - * @return {PIXI.Rectangle} the framing rectangle - */ - Circle.prototype.getBounds = function () { - return new Rectangle(this.x - this.radius, this.y - this.radius, this.radius * 2, this.radius * 2); - }; - return Circle; - }()); - - /** - * The Ellipse object is used to help draw graphics and can also be used to specify a hit area for displayObjects. - * - * @class - * @memberof PIXI - */ - var Ellipse = /** @class */ (function () { - /** - * @param {number} [x=0] - The X coordinate of the center of this ellipse - * @param {number} [y=0] - The Y coordinate of the center of this ellipse - * @param {number} [halfWidth=0] - The half width of this ellipse - * @param {number} [halfHeight=0] - The half height of this ellipse - */ - function Ellipse(x, y, halfWidth, halfHeight) { - if (x === void 0) { x = 0; } - if (y === void 0) { y = 0; } - if (halfWidth === void 0) { halfWidth = 0; } - if (halfHeight === void 0) { halfHeight = 0; } - /** - * @member {number} - * @default 0 - */ - this.x = x; - /** - * @member {number} - * @default 0 - */ - this.y = y; - /** - * @member {number} - * @default 0 - */ - this.width = halfWidth; - /** - * @member {number} - * @default 0 - */ - this.height = halfHeight; - /** - * The type of the object, mainly used to avoid `instanceof` checks - * - * @member {number} - * @readOnly - * @default PIXI.SHAPES.ELIP - * @see PIXI.SHAPES - */ - this.type = exports.SHAPES.ELIP; - } - /** - * Creates a clone of this Ellipse instance - * - * @return {PIXI.Ellipse} a copy of the ellipse - */ - Ellipse.prototype.clone = function () { - return new Ellipse(this.x, this.y, this.width, this.height); - }; - /** - * Checks whether the x and y coordinates given are contained within this ellipse - * - * @param {number} x - The X coordinate of the point to test - * @param {number} y - The Y coordinate of the point to test - * @return {boolean} Whether the x/y coords are within this ellipse - */ - Ellipse.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { - return false; - } - // normalize the coords to an ellipse with center 0,0 - var normx = ((x - this.x) / this.width); - var normy = ((y - this.y) / this.height); - normx *= normx; - normy *= normy; - return (normx + normy <= 1); - }; - /** - * Returns the framing rectangle of the ellipse as a Rectangle object - * - * @return {PIXI.Rectangle} the framing rectangle - */ - Ellipse.prototype.getBounds = function () { - return new Rectangle(this.x - this.width, this.y - this.height, this.width, this.height); - }; - return Ellipse; - }()); - - /** - * A class to define a shape via user defined co-orinates. - * - * @class - * @memberof PIXI - */ - var Polygon = /** @class */ (function () { - /** - * @param {PIXI.IPoint[]|number[]} points - This can be an array of Points - * that form the polygon, a flat array of numbers that will be interpreted as [x,y, x,y, ...], or - * the arguments passed can be all the points of the polygon e.g. - * `new PIXI.Polygon(new PIXI.Point(), new PIXI.Point(), ...)`, or the arguments passed can be flat - * x,y values e.g. `new Polygon(x,y, x,y, x,y, ...)` where `x` and `y` are Numbers. - */ - function Polygon() { - var arguments$1 = arguments; - - var points = []; - for (var _i = 0; _i < arguments.length; _i++) { - points[_i] = arguments$1[_i]; - } - var flat = Array.isArray(points[0]) ? points[0] : points; - // if this is an array of points, convert it to a flat array of numbers - if (typeof flat[0] !== 'number') { - var p = []; - for (var i = 0, il = flat.length; i < il; i++) { - p.push(flat[i].x, flat[i].y); - } - flat = p; - } - /** - * An array of the points of this polygon - * - * @member {number[]} - */ - this.points = flat; - /** - * The type of the object, mainly used to avoid `instanceof` checks - * - * @member {number} - * @readOnly - * @default PIXI.SHAPES.POLY - * @see PIXI.SHAPES - */ - this.type = exports.SHAPES.POLY; - /** - * `false` after moveTo, `true` after `closePath`. In all other cases it is `true`. - * @member {boolean} - * @default true - */ - this.closeStroke = true; - } - /** - * Creates a clone of this polygon - * - * @return {PIXI.Polygon} a copy of the polygon - */ - Polygon.prototype.clone = function () { - var points = this.points.slice(); - var polygon = new Polygon(points); - polygon.closeStroke = this.closeStroke; - return polygon; - }; - /** - * Checks whether the x and y coordinates passed to this function are contained within this polygon - * - * @param {number} x - The X coordinate of the point to test - * @param {number} y - The Y coordinate of the point to test - * @return {boolean} Whether the x/y coordinates are within this polygon - */ - Polygon.prototype.contains = function (x, y) { - var inside = false; - // use some raycasting to test hits - // https://github.com/substack/point-in-polygon/blob/master/index.js - var length = this.points.length / 2; - for (var i = 0, j = length - 1; i < length; j = i++) { - var xi = this.points[i * 2]; - var yi = this.points[(i * 2) + 1]; - var xj = this.points[j * 2]; - var yj = this.points[(j * 2) + 1]; - var intersect = ((yi > y) !== (yj > y)) && (x < ((xj - xi) * ((y - yi) / (yj - yi))) + xi); - if (intersect) { - inside = !inside; - } - } - return inside; - }; - return Polygon; - }()); - - /** - * The Rounded Rectangle object is an area that has nice rounded corners, as indicated by its - * top-left corner point (x, y) and by its width and its height and its radius. - * - * @class - * @memberof PIXI - */ - var RoundedRectangle = /** @class */ (function () { - /** - * @param {number} [x=0] - The X coordinate of the upper-left corner of the rounded rectangle - * @param {number} [y=0] - The Y coordinate of the upper-left corner of the rounded rectangle - * @param {number} [width=0] - The overall width of this rounded rectangle - * @param {number} [height=0] - The overall height of this rounded rectangle - * @param {number} [radius=20] - Controls the radius of the rounded corners - */ - function RoundedRectangle(x, y, width, height, radius) { - if (x === void 0) { x = 0; } - if (y === void 0) { y = 0; } - if (width === void 0) { width = 0; } - if (height === void 0) { height = 0; } - if (radius === void 0) { radius = 20; } - /** - * @member {number} - * @default 0 - */ - this.x = x; - /** - * @member {number} - * @default 0 - */ - this.y = y; - /** - * @member {number} - * @default 0 - */ - this.width = width; - /** - * @member {number} - * @default 0 - */ - this.height = height; - /** - * @member {number} - * @default 20 - */ - this.radius = radius; - /** - * The type of the object, mainly used to avoid `instanceof` checks - * - * @member {number} - * @readonly - * @default PIXI.SHAPES.RREC - * @see PIXI.SHAPES - */ - this.type = exports.SHAPES.RREC; - } - /** - * Creates a clone of this Rounded Rectangle - * - * @return {PIXI.RoundedRectangle} a copy of the rounded rectangle - */ - RoundedRectangle.prototype.clone = function () { - return new RoundedRectangle(this.x, this.y, this.width, this.height, this.radius); - }; - /** - * Checks whether the x and y coordinates given are contained within this Rounded Rectangle - * - * @param {number} x - The X coordinate of the point to test - * @param {number} y - The Y coordinate of the point to test - * @return {boolean} Whether the x/y coordinates are within this Rounded Rectangle - */ - RoundedRectangle.prototype.contains = function (x, y) { - if (this.width <= 0 || this.height <= 0) { - return false; - } - if (x >= this.x && x <= this.x + this.width) { - if (y >= this.y && y <= this.y + this.height) { - if ((y >= this.y + this.radius && y <= this.y + this.height - this.radius) - || (x >= this.x + this.radius && x <= this.x + this.width - this.radius)) { - return true; - } - var dx = x - (this.x + this.radius); - var dy = y - (this.y + this.radius); - var radius2 = this.radius * this.radius; - if ((dx * dx) + (dy * dy) <= radius2) { - return true; - } - dx = x - (this.x + this.width - this.radius); - if ((dx * dx) + (dy * dy) <= radius2) { - return true; - } - dy = y - (this.y + this.height - this.radius); - if ((dx * dx) + (dy * dy) <= radius2) { - return true; - } - dx = x - (this.x + this.radius); - if ((dx * dx) + (dy * dy) <= radius2) { - return true; - } - } - } - return false; - }; - return RoundedRectangle; - }()); - - /** - * Common interface for points. Both Point and ObservablePoint implement it - * @memberof PIXI - * @interface IPointData - */ - /** - * X coord - * @memberof PIXI.IPointData# - * @member {number} x - */ - /** - * Y coord - * @memberof PIXI.IPointData# - * @member {number} y - */ - - /** - * Common interface for points. Both Point and ObservablePoint implement it - * @memberof PIXI - * @interface IPoint - * @extends PIXI.IPointData - */ - /** - * Sets the point to a new x and y position. - * If y is omitted, both x and y will be set to x. - * - * @method set - * @memberof PIXI.IPoint# - * @param {number} [x=0] - position of the point on the x axis - * @param {number} [y=x] - position of the point on the y axis - */ - /** - * Copies x and y from the given point - * @method copyFrom - * @memberof PIXI.IPoint# - * @param {PIXI.IPointData} p - The point to copy from - * @returns {this} Returns itself. - */ - /** - * Copies x and y into the given point - * @method copyTo - * @memberof PIXI.IPoint# - * @param {PIXI.IPoint} p - The point to copy. - * @returns {PIXI.IPoint} Given point with values updated - */ - /** - * Returns true if the given point is equal to this point - * - * @method equals - * @memberof PIXI.IPoint# - * @param {PIXI.IPointData} p - The point to check - * @returns {boolean} Whether the given point equal to this point - */ - - /** - * The Point object represents a location in a two-dimensional coordinate system, where x represents - * the horizontal axis and y represents the vertical axis. - * - * @class - * @memberof PIXI - * @implements IPoint - */ - var Point = /** @class */ (function () { - /** - * @param {number} [x=0] - position of the point on the x axis - * @param {number} [y=0] - position of the point on the y axis - */ - function Point(x, y) { - if (x === void 0) { x = 0; } - if (y === void 0) { y = 0; } - /** - * @member {number} - * @default 0 - */ - this.x = x; - /** - * @member {number} - * @default 0 - */ - this.y = y; - } - /** - * Creates a clone of this point - * - * @return {PIXI.Point} a copy of the point - */ - Point.prototype.clone = function () { - return new Point(this.x, this.y); - }; - /** - * Copies x and y from the given point - * - * @param {PIXI.IPointData} p - The point to copy from - * @returns {this} Returns itself. - */ - Point.prototype.copyFrom = function (p) { - this.set(p.x, p.y); - return this; - }; - /** - * Copies x and y into the given point - * - * @param {PIXI.IPoint} p - The point to copy. - * @returns {PIXI.IPoint} Given point with values updated - */ - Point.prototype.copyTo = function (p) { - p.set(this.x, this.y); - return p; - }; - /** - * Returns true if the given point is equal to this point - * - * @param {PIXI.IPointData} p - The point to check - * @returns {boolean} Whether the given point equal to this point - */ - Point.prototype.equals = function (p) { - return (p.x === this.x) && (p.y === this.y); - }; - /** - * Sets the point to a new x and y position. - * If y is omitted, both x and y will be set to x. - * - * @param {number} [x=0] - position of the point on the x axis - * @param {number} [y=x] - position of the point on the y axis - * @returns {this} Returns itself. - */ - Point.prototype.set = function (x, y) { - if (x === void 0) { x = 0; } - if (y === void 0) { y = x; } - this.x = x; - this.y = y; - return this; - }; - return Point; - }()); - - /** - * The Point object represents a location in a two-dimensional coordinate system, where x represents - * the horizontal axis and y represents the vertical axis. - * - * An ObservablePoint is a point that triggers a callback when the point's position is changed. - * - * @class - * @memberof PIXI - * @implements IPoint - */ - var ObservablePoint = /** @class */ (function () { - /** - * @param {Function} cb - callback when changed - * @param {object} scope - owner of callback - * @param {number} [x=0] - position of the point on the x axis - * @param {number} [y=0] - position of the point on the y axis - */ - function ObservablePoint(cb, scope, x, y) { - if (x === void 0) { x = 0; } - if (y === void 0) { y = 0; } - this._x = x; - this._y = y; - this.cb = cb; - this.scope = scope; - } - /** - * Creates a clone of this point. - * The callback and scope params can be overidden otherwise they will default - * to the clone object's values. - * - * @override - * @param {Function} [cb=null] - callback when changed - * @param {object} [scope=null] - owner of callback - * @return {PIXI.ObservablePoint} a copy of the point - */ - ObservablePoint.prototype.clone = function (cb, scope) { - if (cb === void 0) { cb = this.cb; } - if (scope === void 0) { scope = this.scope; } - return new ObservablePoint(cb, scope, this._x, this._y); - }; - /** - * Sets the point to a new x and y position. - * If y is omitted, both x and y will be set to x. - * - * @param {number} [x=0] - position of the point on the x axis - * @param {number} [y=x] - position of the point on the y axis - * @returns {this} Returns itself. - */ - ObservablePoint.prototype.set = function (x, y) { - if (x === void 0) { x = 0; } - if (y === void 0) { y = x; } - if (this._x !== x || this._y !== y) { - this._x = x; - this._y = y; - this.cb.call(this.scope); - } - return this; - }; - /** - * Copies x and y from the given point - * - * @param {PIXI.IPointData} p - The point to copy from. - * @returns {this} Returns itself. - */ - ObservablePoint.prototype.copyFrom = function (p) { - if (this._x !== p.x || this._y !== p.y) { - this._x = p.x; - this._y = p.y; - this.cb.call(this.scope); - } - return this; - }; - /** - * Copies x and y into the given point - * - * @param {PIXI.IPoint} p - The point to copy. - * @returns {PIXI.IPoint} Given point with values updated - */ - ObservablePoint.prototype.copyTo = function (p) { - p.set(this._x, this._y); - return p; - }; - /** - * Returns true if the given point is equal to this point - * - * @param {PIXI.IPointData} p - The point to check - * @returns {boolean} Whether the given point equal to this point - */ - ObservablePoint.prototype.equals = function (p) { - return (p.x === this._x) && (p.y === this._y); - }; - Object.defineProperty(ObservablePoint.prototype, "x", { - /** - * The position of the displayObject on the x axis relative to the local coordinates of the parent. - * - * @member {number} - */ - get: function () { - return this._x; - }, - set: function (value) { - if (this._x !== value) { - this._x = value; - this.cb.call(this.scope); - } - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(ObservablePoint.prototype, "y", { - /** - * The position of the displayObject on the x axis relative to the local coordinates of the parent. - * - * @member {number} - */ - get: function () { - return this._y; - }, - set: function (value) { - if (this._y !== value) { - this._y = value; - this.cb.call(this.scope); - } - }, - enumerable: false, - configurable: true - }); - return ObservablePoint; - }()); - - /** - * The PixiJS Matrix as a class makes it a lot faster. - * - * Here is a representation of it: - * ```js - * | a | c | tx| - * | b | d | ty| - * | 0 | 0 | 1 | - * ``` - * @class - * @memberof PIXI - */ - var Matrix = /** @class */ (function () { - /** - * @param {number} [a=1] - x scale - * @param {number} [b=0] - x skew - * @param {number} [c=0] - y skew - * @param {number} [d=1] - y scale - * @param {number} [tx=0] - x translation - * @param {number} [ty=0] - y translation - */ - function Matrix(a, b, c, d, tx, ty) { - if (a === void 0) { a = 1; } - if (b === void 0) { b = 0; } - if (c === void 0) { c = 0; } - if (d === void 0) { d = 1; } - if (tx === void 0) { tx = 0; } - if (ty === void 0) { ty = 0; } - this.array = null; - /** - * @member {number} - * @default 1 - */ - this.a = a; - /** - * @member {number} - * @default 0 - */ - this.b = b; - /** - * @member {number} - * @default 0 - */ - this.c = c; - /** - * @member {number} - * @default 1 - */ - this.d = d; - /** - * @member {number} - * @default 0 - */ - this.tx = tx; - /** - * @member {number} - * @default 0 - */ - this.ty = ty; - } - /** - * Creates a Matrix object based on the given array. The Element to Matrix mapping order is as follows: - * - * a = array[0] - * b = array[1] - * c = array[3] - * d = array[4] - * tx = array[2] - * ty = array[5] - * - * @param {number[]} array - The array that the matrix will be populated from. - */ - Matrix.prototype.fromArray = function (array) { - this.a = array[0]; - this.b = array[1]; - this.c = array[3]; - this.d = array[4]; - this.tx = array[2]; - this.ty = array[5]; - }; - /** - * sets the matrix properties - * - * @param {number} a - Matrix component - * @param {number} b - Matrix component - * @param {number} c - Matrix component - * @param {number} d - Matrix component - * @param {number} tx - Matrix component - * @param {number} ty - Matrix component - * - * @return {PIXI.Matrix} This matrix. Good for chaining method calls. - */ - Matrix.prototype.set = function (a, b, c, d, tx, ty) { - this.a = a; - this.b = b; - this.c = c; - this.d = d; - this.tx = tx; - this.ty = ty; - return this; - }; - /** - * Creates an array from the current Matrix object. - * - * @param {boolean} transpose - Whether we need to transpose the matrix or not - * @param {Float32Array} [out=new Float32Array(9)] - If provided the array will be assigned to out - * @return {number[]} the newly created array which contains the matrix - */ - Matrix.prototype.toArray = function (transpose, out) { - if (!this.array) { - this.array = new Float32Array(9); - } - var array = out || this.array; - if (transpose) { - array[0] = this.a; - array[1] = this.b; - array[2] = 0; - array[3] = this.c; - array[4] = this.d; - array[5] = 0; - array[6] = this.tx; - array[7] = this.ty; - array[8] = 1; - } - else { - array[0] = this.a; - array[1] = this.c; - array[2] = this.tx; - array[3] = this.b; - array[4] = this.d; - array[5] = this.ty; - array[6] = 0; - array[7] = 0; - array[8] = 1; - } - return array; - }; - /** - * Get a new position with the current transformation applied. - * Can be used to go from a child's coordinate space to the world coordinate space. (e.g. rendering) - * - * @param {PIXI.IPointData} pos - The origin - * @param {PIXI.Point} [newPos] - The point that the new position is assigned to (allowed to be same as input) - * @return {PIXI.Point} The new point, transformed through this matrix - */ - Matrix.prototype.apply = function (pos, newPos) { - newPos = (newPos || new Point()); - var x = pos.x; - var y = pos.y; - newPos.x = (this.a * x) + (this.c * y) + this.tx; - newPos.y = (this.b * x) + (this.d * y) + this.ty; - return newPos; - }; - /** - * Get a new position with the inverse of the current transformation applied. - * Can be used to go from the world coordinate space to a child's coordinate space. (e.g. input) - * - * @param {PIXI.IPointData} pos - The origin - * @param {PIXI.Point} [newPos] - The point that the new position is assigned to (allowed to be same as input) - * @return {PIXI.Point} The new point, inverse-transformed through this matrix - */ - Matrix.prototype.applyInverse = function (pos, newPos) { - newPos = (newPos || new Point()); - var id = 1 / ((this.a * this.d) + (this.c * -this.b)); - var x = pos.x; - var y = pos.y; - newPos.x = (this.d * id * x) + (-this.c * id * y) + (((this.ty * this.c) - (this.tx * this.d)) * id); - newPos.y = (this.a * id * y) + (-this.b * id * x) + (((-this.ty * this.a) + (this.tx * this.b)) * id); - return newPos; - }; - /** - * Translates the matrix on the x and y. - * - * @param {number} x - How much to translate x by - * @param {number} y - How much to translate y by - * @return {PIXI.Matrix} This matrix. Good for chaining method calls. - */ - Matrix.prototype.translate = function (x, y) { - this.tx += x; - this.ty += y; - return this; - }; - /** - * Applies a scale transformation to the matrix. - * - * @param {number} x - The amount to scale horizontally - * @param {number} y - The amount to scale vertically - * @return {PIXI.Matrix} This matrix. Good for chaining method calls. - */ - Matrix.prototype.scale = function (x, y) { - this.a *= x; - this.d *= y; - this.c *= x; - this.b *= y; - this.tx *= x; - this.ty *= y; - return this; - }; - /** - * Applies a rotation transformation to the matrix. - * - * @param {number} angle - The angle in radians. - * @return {PIXI.Matrix} This matrix. Good for chaining method calls. - */ - Matrix.prototype.rotate = function (angle) { - var cos = Math.cos(angle); - var sin = Math.sin(angle); - var a1 = this.a; - var c1 = this.c; - var tx1 = this.tx; - this.a = (a1 * cos) - (this.b * sin); - this.b = (a1 * sin) + (this.b * cos); - this.c = (c1 * cos) - (this.d * sin); - this.d = (c1 * sin) + (this.d * cos); - this.tx = (tx1 * cos) - (this.ty * sin); - this.ty = (tx1 * sin) + (this.ty * cos); - return this; - }; - /** - * Appends the given Matrix to this Matrix. - * - * @param {PIXI.Matrix} matrix - The matrix to append. - * @return {PIXI.Matrix} This matrix. Good for chaining method calls. - */ - Matrix.prototype.append = function (matrix) { - var a1 = this.a; - var b1 = this.b; - var c1 = this.c; - var d1 = this.d; - this.a = (matrix.a * a1) + (matrix.b * c1); - this.b = (matrix.a * b1) + (matrix.b * d1); - this.c = (matrix.c * a1) + (matrix.d * c1); - this.d = (matrix.c * b1) + (matrix.d * d1); - this.tx = (matrix.tx * a1) + (matrix.ty * c1) + this.tx; - this.ty = (matrix.tx * b1) + (matrix.ty * d1) + this.ty; - return this; - }; - /** - * Sets the matrix based on all the available properties - * - * @param {number} x - Position on the x axis - * @param {number} y - Position on the y axis - * @param {number} pivotX - Pivot on the x axis - * @param {number} pivotY - Pivot on the y axis - * @param {number} scaleX - Scale on the x axis - * @param {number} scaleY - Scale on the y axis - * @param {number} rotation - Rotation in radians - * @param {number} skewX - Skew on the x axis - * @param {number} skewY - Skew on the y axis - * @return {PIXI.Matrix} This matrix. Good for chaining method calls. - */ - Matrix.prototype.setTransform = function (x, y, pivotX, pivotY, scaleX, scaleY, rotation, skewX, skewY) { - this.a = Math.cos(rotation + skewY) * scaleX; - this.b = Math.sin(rotation + skewY) * scaleX; - this.c = -Math.sin(rotation - skewX) * scaleY; - this.d = Math.cos(rotation - skewX) * scaleY; - this.tx = x - ((pivotX * this.a) + (pivotY * this.c)); - this.ty = y - ((pivotX * this.b) + (pivotY * this.d)); - return this; - }; - /** - * Prepends the given Matrix to this Matrix. - * - * @param {PIXI.Matrix} matrix - The matrix to prepend - * @return {PIXI.Matrix} This matrix. Good for chaining method calls. - */ - Matrix.prototype.prepend = function (matrix) { - var tx1 = this.tx; - if (matrix.a !== 1 || matrix.b !== 0 || matrix.c !== 0 || matrix.d !== 1) { - var a1 = this.a; - var c1 = this.c; - this.a = (a1 * matrix.a) + (this.b * matrix.c); - this.b = (a1 * matrix.b) + (this.b * matrix.d); - this.c = (c1 * matrix.a) + (this.d * matrix.c); - this.d = (c1 * matrix.b) + (this.d * matrix.d); - } - this.tx = (tx1 * matrix.a) + (this.ty * matrix.c) + matrix.tx; - this.ty = (tx1 * matrix.b) + (this.ty * matrix.d) + matrix.ty; - return this; - }; - /** - * Decomposes the matrix (x, y, scaleX, scaleY, and rotation) and sets the properties on to a transform. - * - * @param {PIXI.Transform} transform - The transform to apply the properties to. - * @return {PIXI.Transform} The transform with the newly applied properties - */ - Matrix.prototype.decompose = function (transform) { - // sort out rotation / skew.. - var a = this.a; - var b = this.b; - var c = this.c; - var d = this.d; - var skewX = -Math.atan2(-c, d); - var skewY = Math.atan2(b, a); - var delta = Math.abs(skewX + skewY); - if (delta < 0.00001 || Math.abs(PI_2 - delta) < 0.00001) { - transform.rotation = skewY; - transform.skew.x = transform.skew.y = 0; - } - else { - transform.rotation = 0; - transform.skew.x = skewX; - transform.skew.y = skewY; - } - // next set scale - transform.scale.x = Math.sqrt((a * a) + (b * b)); - transform.scale.y = Math.sqrt((c * c) + (d * d)); - // next set position - transform.position.x = this.tx; - transform.position.y = this.ty; - return transform; - }; - /** - * Inverts this matrix - * - * @return {PIXI.Matrix} This matrix. Good for chaining method calls. - */ - Matrix.prototype.invert = function () { - var a1 = this.a; - var b1 = this.b; - var c1 = this.c; - var d1 = this.d; - var tx1 = this.tx; - var n = (a1 * d1) - (b1 * c1); - this.a = d1 / n; - this.b = -b1 / n; - this.c = -c1 / n; - this.d = a1 / n; - this.tx = ((c1 * this.ty) - (d1 * tx1)) / n; - this.ty = -((a1 * this.ty) - (b1 * tx1)) / n; - return this; - }; - /** - * Resets this Matrix to an identity (default) matrix. - * - * @return {PIXI.Matrix} This matrix. Good for chaining method calls. - */ - Matrix.prototype.identity = function () { - this.a = 1; - this.b = 0; - this.c = 0; - this.d = 1; - this.tx = 0; - this.ty = 0; - return this; - }; - /** - * Creates a new Matrix object with the same values as this one. - * - * @return {PIXI.Matrix} A copy of this matrix. Good for chaining method calls. - */ - Matrix.prototype.clone = function () { - var matrix = new Matrix(); - matrix.a = this.a; - matrix.b = this.b; - matrix.c = this.c; - matrix.d = this.d; - matrix.tx = this.tx; - matrix.ty = this.ty; - return matrix; - }; - /** - * Changes the values of the given matrix to be the same as the ones in this matrix - * - * @param {PIXI.Matrix} matrix - The matrix to copy to. - * @return {PIXI.Matrix} The matrix given in parameter with its values updated. - */ - Matrix.prototype.copyTo = function (matrix) { - matrix.a = this.a; - matrix.b = this.b; - matrix.c = this.c; - matrix.d = this.d; - matrix.tx = this.tx; - matrix.ty = this.ty; - return matrix; - }; - /** - * Changes the values of the matrix to be the same as the ones in given matrix - * - * @param {PIXI.Matrix} matrix - The matrix to copy from. - * @return {PIXI.Matrix} this - */ - Matrix.prototype.copyFrom = function (matrix) { - this.a = matrix.a; - this.b = matrix.b; - this.c = matrix.c; - this.d = matrix.d; - this.tx = matrix.tx; - this.ty = matrix.ty; - return this; - }; - Object.defineProperty(Matrix, "IDENTITY", { - /** - * A default (identity) matrix - * - * @static - * @const - * @member {PIXI.Matrix} - */ - get: function () { - return new Matrix(); - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(Matrix, "TEMP_MATRIX", { - /** - * A temp matrix - * - * @static - * @const - * @member {PIXI.Matrix} - */ - get: function () { - return new Matrix(); - }, - enumerable: false, - configurable: true - }); - return Matrix; - }()); - - // Your friendly neighbour https://en.wikipedia.org/wiki/Dihedral_group - /* - * Transform matrix for operation n is: - * | ux | vx | - * | uy | vy | - */ - var ux = [1, 1, 0, -1, -1, -1, 0, 1, 1, 1, 0, -1, -1, -1, 0, 1]; - var uy = [0, 1, 1, 1, 0, -1, -1, -1, 0, 1, 1, 1, 0, -1, -1, -1]; - var vx = [0, -1, -1, -1, 0, 1, 1, 1, 0, 1, 1, 1, 0, -1, -1, -1]; - var vy = [1, 1, 0, -1, -1, -1, 0, 1, -1, -1, 0, 1, 1, 1, 0, -1]; - /** - * [Cayley Table]{@link https://en.wikipedia.org/wiki/Cayley_table} - * for the composition of each rotation in the dihederal group D8. - * - * @type number[][] - * @private - */ - var rotationCayley = []; - /** - * Matrices for each `GD8Symmetry` rotation. - * - * @type Matrix[] - * @private - */ - var rotationMatrices = []; - /* - * Alias for {@code Math.sign}. - */ - var signum = Math.sign; - /* - * Initializes `rotationCayley` and `rotationMatrices`. It is called - * only once below. - */ - function init() { - for (var i = 0; i < 16; i++) { - var row = []; - rotationCayley.push(row); - for (var j = 0; j < 16; j++) { - /* Multiplies rotation matrices i and j. */ - var _ux = signum((ux[i] * ux[j]) + (vx[i] * uy[j])); - var _uy = signum((uy[i] * ux[j]) + (vy[i] * uy[j])); - var _vx = signum((ux[i] * vx[j]) + (vx[i] * vy[j])); - var _vy = signum((uy[i] * vx[j]) + (vy[i] * vy[j])); - /* Finds rotation matrix matching the product and pushes it. */ - for (var k = 0; k < 16; k++) { - if (ux[k] === _ux && uy[k] === _uy - && vx[k] === _vx && vy[k] === _vy) { - row.push(k); - break; - } - } - } - } - for (var i = 0; i < 16; i++) { - var mat = new Matrix(); - mat.set(ux[i], uy[i], vx[i], vy[i], 0, 0); - rotationMatrices.push(mat); - } - } - init(); - /** - * @memberof PIXI - * @typedef {number} GD8Symmetry - * @see PIXI.groupD8 - */ - /** - * Implements the dihedral group D8, which is similar to - * [group D4]{@link http://mathworld.wolfram.com/DihedralGroupD4.html}; - * D8 is the same but with diagonals, and it is used for texture - * rotations. - * - * The directions the U- and V- axes after rotation - * of an angle of `a: GD8Constant` are the vectors `(uX(a), uY(a))` - * and `(vX(a), vY(a))`. These aren't necessarily unit vectors. - * - * **Origin:**
- * This is the small part of gameofbombs.com portal system. It works. - * - * @see PIXI.groupD8.E - * @see PIXI.groupD8.SE - * @see PIXI.groupD8.S - * @see PIXI.groupD8.SW - * @see PIXI.groupD8.W - * @see PIXI.groupD8.NW - * @see PIXI.groupD8.N - * @see PIXI.groupD8.NE - * @author Ivan @ivanpopelyshev - * @namespace PIXI.groupD8 - * @memberof PIXI - */ - var groupD8 = { - /** - * | Rotation | Direction | - * |----------|-----------| - * | 0° | East | - * - * @memberof PIXI.groupD8 - * @constant {PIXI.GD8Symmetry} - */ - E: 0, - /** - * | Rotation | Direction | - * |----------|-----------| - * | 45°↻ | Southeast | - * - * @memberof PIXI.groupD8 - * @constant {PIXI.GD8Symmetry} - */ - SE: 1, - /** - * | Rotation | Direction | - * |----------|-----------| - * | 90°↻ | South | - * - * @memberof PIXI.groupD8 - * @constant {PIXI.GD8Symmetry} - */ - S: 2, - /** - * | Rotation | Direction | - * |----------|-----------| - * | 135°↻ | Southwest | - * - * @memberof PIXI.groupD8 - * @constant {PIXI.GD8Symmetry} - */ - SW: 3, - /** - * | Rotation | Direction | - * |----------|-----------| - * | 180° | West | - * - * @memberof PIXI.groupD8 - * @constant {PIXI.GD8Symmetry} - */ - W: 4, - /** - * | Rotation | Direction | - * |-------------|--------------| - * | -135°/225°↻ | Northwest | - * - * @memberof PIXI.groupD8 - * @constant {PIXI.GD8Symmetry} - */ - NW: 5, - /** - * | Rotation | Direction | - * |-------------|--------------| - * | -90°/270°↻ | North | - * - * @memberof PIXI.groupD8 - * @constant {PIXI.GD8Symmetry} - */ - N: 6, - /** - * | Rotation | Direction | - * |-------------|--------------| - * | -45°/315°↻ | Northeast | - * - * @memberof PIXI.groupD8 - * @constant {PIXI.GD8Symmetry} - */ - NE: 7, - /** - * Reflection about Y-axis. - * - * @memberof PIXI.groupD8 - * @constant {PIXI.GD8Symmetry} - */ - MIRROR_VERTICAL: 8, - /** - * Reflection about the main diagonal. - * - * @memberof PIXI.groupD8 - * @constant {PIXI.GD8Symmetry} - */ - MAIN_DIAGONAL: 10, - /** - * Reflection about X-axis. - * - * @memberof PIXI.groupD8 - * @constant {PIXI.GD8Symmetry} - */ - MIRROR_HORIZONTAL: 12, - /** - * Reflection about reverse diagonal. - * - * @memberof PIXI.groupD8 - * @constant {PIXI.GD8Symmetry} - */ - REVERSE_DIAGONAL: 14, - /** - * @memberof PIXI.groupD8 - * @param {PIXI.GD8Symmetry} ind - sprite rotation angle. - * @return {PIXI.GD8Symmetry} The X-component of the U-axis - * after rotating the axes. - */ - uX: function (ind) { return ux[ind]; }, - /** - * @memberof PIXI.groupD8 - * @param {PIXI.GD8Symmetry} ind - sprite rotation angle. - * @return {PIXI.GD8Symmetry} The Y-component of the U-axis - * after rotating the axes. - */ - uY: function (ind) { return uy[ind]; }, - /** - * @memberof PIXI.groupD8 - * @param {PIXI.GD8Symmetry} ind - sprite rotation angle. - * @return {PIXI.GD8Symmetry} The X-component of the V-axis - * after rotating the axes. - */ - vX: function (ind) { return vx[ind]; }, - /** - * @memberof PIXI.groupD8 - * @param {PIXI.GD8Symmetry} ind - sprite rotation angle. - * @return {PIXI.GD8Symmetry} The Y-component of the V-axis - * after rotating the axes. - */ - vY: function (ind) { return vy[ind]; }, - /** - * @memberof PIXI.groupD8 - * @param {PIXI.GD8Symmetry} rotation - symmetry whose opposite - * is needed. Only rotations have opposite symmetries while - * reflections don't. - * @return {PIXI.GD8Symmetry} The opposite symmetry of `rotation` - */ - inv: function (rotation) { - if (rotation & 8) // true only if between 8 & 15 (reflections) - { - return rotation & 15; // or rotation % 16 - } - return (-rotation) & 7; // or (8 - rotation) % 8 - }, - /** - * Composes the two D8 operations. - * - * Taking `^` as reflection: - * - * | | E=0 | S=2 | W=4 | N=6 | E^=8 | S^=10 | W^=12 | N^=14 | - * |-------|-----|-----|-----|-----|------|-------|-------|-------| - * | E=0 | E | S | W | N | E^ | S^ | W^ | N^ | - * | S=2 | S | W | N | E | S^ | W^ | N^ | E^ | - * | W=4 | W | N | E | S | W^ | N^ | E^ | S^ | - * | N=6 | N | E | S | W | N^ | E^ | S^ | W^ | - * | E^=8 | E^ | N^ | W^ | S^ | E | N | W | S | - * | S^=10 | S^ | E^ | N^ | W^ | S | E | N | W | - * | W^=12 | W^ | S^ | E^ | N^ | W | S | E | N | - * | N^=14 | N^ | W^ | S^ | E^ | N | W | S | E | - * - * [This is a Cayley table]{@link https://en.wikipedia.org/wiki/Cayley_table} - * @memberof PIXI.groupD8 - * @param {PIXI.GD8Symmetry} rotationSecond - Second operation, which - * is the row in the above cayley table. - * @param {PIXI.GD8Symmetry} rotationFirst - First operation, which - * is the column in the above cayley table. - * @return {PIXI.GD8Symmetry} Composed operation - */ - add: function (rotationSecond, rotationFirst) { return (rotationCayley[rotationSecond][rotationFirst]); }, - /** - * Reverse of `add`. - * - * @memberof PIXI.groupD8 - * @param {PIXI.GD8Symmetry} rotationSecond - Second operation - * @param {PIXI.GD8Symmetry} rotationFirst - First operation - * @return {PIXI.GD8Symmetry} Result - */ - sub: function (rotationSecond, rotationFirst) { return (rotationCayley[rotationSecond][groupD8.inv(rotationFirst)]); }, - /** - * Adds 180 degrees to rotation, which is a commutative - * operation. - * - * @memberof PIXI.groupD8 - * @param {number} rotation - The number to rotate. - * @returns {number} Rotated number - */ - rotate180: function (rotation) { return rotation ^ 4; }, - /** - * Checks if the rotation angle is vertical, i.e. south - * or north. It doesn't work for reflections. - * - * @memberof PIXI.groupD8 - * @param {PIXI.GD8Symmetry} rotation - The number to check. - * @returns {boolean} Whether or not the direction is vertical - */ - isVertical: function (rotation) { return (rotation & 3) === 2; }, - /** - * Approximates the vector `V(dx,dy)` into one of the - * eight directions provided by `groupD8`. - * - * @memberof PIXI.groupD8 - * @param {number} dx - X-component of the vector - * @param {number} dy - Y-component of the vector - * @return {PIXI.GD8Symmetry} Approximation of the vector into - * one of the eight symmetries. - */ - byDirection: function (dx, dy) { - if (Math.abs(dx) * 2 <= Math.abs(dy)) { - if (dy >= 0) { - return groupD8.S; - } - return groupD8.N; - } - else if (Math.abs(dy) * 2 <= Math.abs(dx)) { - if (dx > 0) { - return groupD8.E; - } - return groupD8.W; - } - else if (dy > 0) { - if (dx > 0) { - return groupD8.SE; - } - return groupD8.SW; - } - else if (dx > 0) { - return groupD8.NE; - } - return groupD8.NW; - }, - /** - * Helps sprite to compensate texture packer rotation. - * - * @memberof PIXI.groupD8 - * @param {PIXI.Matrix} matrix - sprite world matrix - * @param {PIXI.GD8Symmetry} rotation - The rotation factor to use. - * @param {number} tx - sprite anchoring - * @param {number} ty - sprite anchoring - */ - matrixAppendRotationInv: function (matrix, rotation, tx, ty) { - if (tx === void 0) { tx = 0; } - if (ty === void 0) { ty = 0; } - // Packer used "rotation", we use "inv(rotation)" - var mat = rotationMatrices[groupD8.inv(rotation)]; - mat.tx = tx; - mat.ty = ty; - matrix.append(mat); - }, - }; - - /** - * Transform that takes care about its versions - * - * @class - * @memberof PIXI - */ - var Transform = /** @class */ (function () { - function Transform() { - /** - * The world transformation matrix. - * - * @member {PIXI.Matrix} - */ - this.worldTransform = new Matrix(); - /** - * The local transformation matrix. - * - * @member {PIXI.Matrix} - */ - this.localTransform = new Matrix(); - /** - * The coordinate of the object relative to the local coordinates of the parent. - * - * @member {PIXI.ObservablePoint} - */ - this.position = new ObservablePoint(this.onChange, this, 0, 0); - /** - * The scale factor of the object. - * - * @member {PIXI.ObservablePoint} - */ - this.scale = new ObservablePoint(this.onChange, this, 1, 1); - /** - * The pivot point of the displayObject that it rotates around. - * - * @member {PIXI.ObservablePoint} - */ - this.pivot = new ObservablePoint(this.onChange, this, 0, 0); - /** - * The skew amount, on the x and y axis. - * - * @member {PIXI.ObservablePoint} - */ - this.skew = new ObservablePoint(this.updateSkew, this, 0, 0); - /** - * The rotation amount. - * - * @protected - * @member {number} - */ - this._rotation = 0; - /** - * The X-coordinate value of the normalized local X axis, - * the first column of the local transformation matrix without a scale. - * - * @protected - * @member {number} - */ - this._cx = 1; - /** - * The Y-coordinate value of the normalized local X axis, - * the first column of the local transformation matrix without a scale. - * - * @protected - * @member {number} - */ - this._sx = 0; - /** - * The X-coordinate value of the normalized local Y axis, - * the second column of the local transformation matrix without a scale. - * - * @protected - * @member {number} - */ - this._cy = 0; - /** - * The Y-coordinate value of the normalized local Y axis, - * the second column of the local transformation matrix without a scale. - * - * @protected - * @member {number} - */ - this._sy = 1; - /** - * The locally unique ID of the local transform. - * - * @protected - * @member {number} - */ - this._localID = 0; - /** - * The locally unique ID of the local transform - * used to calculate the current local transformation matrix. - * - * @protected - * @member {number} - */ - this._currentLocalID = 0; - /** - * The locally unique ID of the world transform. - * - * @protected - * @member {number} - */ - this._worldID = 0; - /** - * The locally unique ID of the parent's world transform - * used to calculate the current world transformation matrix. - * - * @protected - * @member {number} - */ - this._parentID = 0; - } - /** - * Called when a value changes. - * - * @protected - */ - Transform.prototype.onChange = function () { - this._localID++; - }; - /** - * Called when the skew or the rotation changes. - * - * @protected - */ - Transform.prototype.updateSkew = function () { - this._cx = Math.cos(this._rotation + this.skew.y); - this._sx = Math.sin(this._rotation + this.skew.y); - this._cy = -Math.sin(this._rotation - this.skew.x); // cos, added PI/2 - this._sy = Math.cos(this._rotation - this.skew.x); // sin, added PI/2 - this._localID++; - }; - /** - * Updates the local transformation matrix. - */ - Transform.prototype.updateLocalTransform = function () { - var lt = this.localTransform; - if (this._localID !== this._currentLocalID) { - // get the matrix values of the displayobject based on its transform properties.. - lt.a = this._cx * this.scale.x; - lt.b = this._sx * this.scale.x; - lt.c = this._cy * this.scale.y; - lt.d = this._sy * this.scale.y; - lt.tx = this.position.x - ((this.pivot.x * lt.a) + (this.pivot.y * lt.c)); - lt.ty = this.position.y - ((this.pivot.x * lt.b) + (this.pivot.y * lt.d)); - this._currentLocalID = this._localID; - // force an update.. - this._parentID = -1; - } - }; - /** - * Updates the local and the world transformation matrices. - * - * @param {PIXI.Transform} parentTransform - The parent transform - */ - Transform.prototype.updateTransform = function (parentTransform) { - var lt = this.localTransform; - if (this._localID !== this._currentLocalID) { - // get the matrix values of the displayobject based on its transform properties.. - lt.a = this._cx * this.scale.x; - lt.b = this._sx * this.scale.x; - lt.c = this._cy * this.scale.y; - lt.d = this._sy * this.scale.y; - lt.tx = this.position.x - ((this.pivot.x * lt.a) + (this.pivot.y * lt.c)); - lt.ty = this.position.y - ((this.pivot.x * lt.b) + (this.pivot.y * lt.d)); - this._currentLocalID = this._localID; - // force an update.. - this._parentID = -1; - } - if (this._parentID !== parentTransform._worldID) { - // concat the parent matrix with the objects transform. - var pt = parentTransform.worldTransform; - var wt = this.worldTransform; - wt.a = (lt.a * pt.a) + (lt.b * pt.c); - wt.b = (lt.a * pt.b) + (lt.b * pt.d); - wt.c = (lt.c * pt.a) + (lt.d * pt.c); - wt.d = (lt.c * pt.b) + (lt.d * pt.d); - wt.tx = (lt.tx * pt.a) + (lt.ty * pt.c) + pt.tx; - wt.ty = (lt.tx * pt.b) + (lt.ty * pt.d) + pt.ty; - this._parentID = parentTransform._worldID; - // update the id of the transform.. - this._worldID++; - } - }; - /** - * Decomposes a matrix and sets the transforms properties based on it. - * - * @param {PIXI.Matrix} matrix - The matrix to decompose - */ - Transform.prototype.setFromMatrix = function (matrix) { - matrix.decompose(this); - this._localID++; - }; - Object.defineProperty(Transform.prototype, "rotation", { - /** - * The rotation of the object in radians. - * - * @member {number} - */ - get: function () { - return this._rotation; - }, - set: function (value) { - if (this._rotation !== value) { - this._rotation = value; - this.updateSkew(); - } - }, - enumerable: false, - configurable: true - }); - /** - * A default (identity) transform - * - * @static - * @constant - * @member {PIXI.Transform} - */ - Transform.IDENTITY = new Transform(); - return Transform; - }()); - - /*! - * @pixi/display - v5.3.3 - * Compiled Tue, 04 Aug 2020 16:23:09 UTC - * - * @pixi/display is licensed under the MIT License. - * http://www.opensource.org/licenses/mit-license - */ - - /** - * Sets the default value for the container property 'sortableChildren'. - * If set to true, the container will sort its children by zIndex value - * when updateTransform() is called, or manually if sortChildren() is called. - * - * This actually changes the order of elements in the array, so should be treated - * as a basic solution that is not performant compared to other solutions, - * such as @link https://github.com/pixijs/pixi-display - * - * Also be aware of that this may not work nicely with the addChildAt() function, - * as the zIndex sorting may cause the child to automatically sorted to another position. - * - * @static - * @constant - * @name SORTABLE_CHILDREN - * @memberof PIXI.settings - * @type {boolean} - * @default false - */ - settings.SORTABLE_CHILDREN = false; - - /** - * 'Builder' pattern for bounds rectangles. - * - * This could be called an Axis-Aligned Bounding Box. - * It is not an actual shape. It is a mutable thing; no 'EMPTY' or those kind of problems. - * - * @class - * @memberof PIXI - */ - var Bounds = /** @class */ (function () { - function Bounds() { - /** - * @member {number} - * @default 0 - */ - this.minX = Infinity; - /** - * @member {number} - * @default 0 - */ - this.minY = Infinity; - /** - * @member {number} - * @default 0 - */ - this.maxX = -Infinity; - /** - * @member {number} - * @default 0 - */ - this.maxY = -Infinity; - this.rect = null; - /** - * It is updated to _boundsID of corresponding object to keep bounds in sync with content. - * Updated from outside, thus public modifier. - * - * @member {number} - * @public - */ - this.updateID = -1; - } - /** - * Checks if bounds are empty. - * - * @return {boolean} True if empty. - */ - Bounds.prototype.isEmpty = function () { - return this.minX > this.maxX || this.minY > this.maxY; - }; - /** - * Clears the bounds and resets. - * - */ - Bounds.prototype.clear = function () { - this.minX = Infinity; - this.minY = Infinity; - this.maxX = -Infinity; - this.maxY = -Infinity; - }; - /** - * Can return Rectangle.EMPTY constant, either construct new rectangle, either use your rectangle - * It is not guaranteed that it will return tempRect - * - * @param {PIXI.Rectangle} rect - temporary object will be used if AABB is not empty - * @returns {PIXI.Rectangle} A rectangle of the bounds - */ - Bounds.prototype.getRectangle = function (rect) { - if (this.minX > this.maxX || this.minY > this.maxY) { - return Rectangle.EMPTY; - } - rect = rect || new Rectangle(0, 0, 1, 1); - rect.x = this.minX; - rect.y = this.minY; - rect.width = this.maxX - this.minX; - rect.height = this.maxY - this.minY; - return rect; - }; - /** - * This function should be inlined when its possible. - * - * @param {PIXI.IPointData} point - The point to add. - */ - Bounds.prototype.addPoint = function (point) { - this.minX = Math.min(this.minX, point.x); - this.maxX = Math.max(this.maxX, point.x); - this.minY = Math.min(this.minY, point.y); - this.maxY = Math.max(this.maxY, point.y); - }; - /** - * Adds a quad, not transformed - * - * @param {Float32Array} vertices - The verts to add. - */ - Bounds.prototype.addQuad = function (vertices) { - var minX = this.minX; - var minY = this.minY; - var maxX = this.maxX; - var maxY = this.maxY; - var x = vertices[0]; - var y = vertices[1]; - minX = x < minX ? x : minX; - minY = y < minY ? y : minY; - maxX = x > maxX ? x : maxX; - maxY = y > maxY ? y : maxY; - x = vertices[2]; - y = vertices[3]; - minX = x < minX ? x : minX; - minY = y < minY ? y : minY; - maxX = x > maxX ? x : maxX; - maxY = y > maxY ? y : maxY; - x = vertices[4]; - y = vertices[5]; - minX = x < minX ? x : minX; - minY = y < minY ? y : minY; - maxX = x > maxX ? x : maxX; - maxY = y > maxY ? y : maxY; - x = vertices[6]; - y = vertices[7]; - minX = x < minX ? x : minX; - minY = y < minY ? y : minY; - maxX = x > maxX ? x : maxX; - maxY = y > maxY ? y : maxY; - this.minX = minX; - this.minY = minY; - this.maxX = maxX; - this.maxY = maxY; - }; - /** - * Adds sprite frame, transformed. - * - * @param {PIXI.Transform} transform - transform to apply - * @param {number} x0 - left X of frame - * @param {number} y0 - top Y of frame - * @param {number} x1 - right X of frame - * @param {number} y1 - bottom Y of frame - */ - Bounds.prototype.addFrame = function (transform, x0, y0, x1, y1) { - this.addFrameMatrix(transform.worldTransform, x0, y0, x1, y1); - }; - /** - * Adds sprite frame, multiplied by matrix - * - * @param {PIXI.Matrix} matrix - matrix to apply - * @param {number} x0 - left X of frame - * @param {number} y0 - top Y of frame - * @param {number} x1 - right X of frame - * @param {number} y1 - bottom Y of frame - */ - Bounds.prototype.addFrameMatrix = function (matrix, x0, y0, x1, y1) { - var a = matrix.a; - var b = matrix.b; - var c = matrix.c; - var d = matrix.d; - var tx = matrix.tx; - var ty = matrix.ty; - var minX = this.minX; - var minY = this.minY; - var maxX = this.maxX; - var maxY = this.maxY; - var x = (a * x0) + (c * y0) + tx; - var y = (b * x0) + (d * y0) + ty; - minX = x < minX ? x : minX; - minY = y < minY ? y : minY; - maxX = x > maxX ? x : maxX; - maxY = y > maxY ? y : maxY; - x = (a * x1) + (c * y0) + tx; - y = (b * x1) + (d * y0) + ty; - minX = x < minX ? x : minX; - minY = y < minY ? y : minY; - maxX = x > maxX ? x : maxX; - maxY = y > maxY ? y : maxY; - x = (a * x0) + (c * y1) + tx; - y = (b * x0) + (d * y1) + ty; - minX = x < minX ? x : minX; - minY = y < minY ? y : minY; - maxX = x > maxX ? x : maxX; - maxY = y > maxY ? y : maxY; - x = (a * x1) + (c * y1) + tx; - y = (b * x1) + (d * y1) + ty; - minX = x < minX ? x : minX; - minY = y < minY ? y : minY; - maxX = x > maxX ? x : maxX; - maxY = y > maxY ? y : maxY; - this.minX = minX; - this.minY = minY; - this.maxX = maxX; - this.maxY = maxY; - }; - /** - * Adds screen vertices from array - * - * @param {Float32Array} vertexData - calculated vertices - * @param {number} beginOffset - begin offset - * @param {number} endOffset - end offset, excluded - */ - Bounds.prototype.addVertexData = function (vertexData, beginOffset, endOffset) { - var minX = this.minX; - var minY = this.minY; - var maxX = this.maxX; - var maxY = this.maxY; - for (var i = beginOffset; i < endOffset; i += 2) { - var x = vertexData[i]; - var y = vertexData[i + 1]; - minX = x < minX ? x : minX; - minY = y < minY ? y : minY; - maxX = x > maxX ? x : maxX; - maxY = y > maxY ? y : maxY; - } - this.minX = minX; - this.minY = minY; - this.maxX = maxX; - this.maxY = maxY; - }; - /** - * Add an array of mesh vertices - * - * @param {PIXI.Transform} transform - mesh transform - * @param {Float32Array} vertices - mesh coordinates in array - * @param {number} beginOffset - begin offset - * @param {number} endOffset - end offset, excluded - */ - Bounds.prototype.addVertices = function (transform, vertices, beginOffset, endOffset) { - this.addVerticesMatrix(transform.worldTransform, vertices, beginOffset, endOffset); - }; - /** - * Add an array of mesh vertices. - * - * @param {PIXI.Matrix} matrix - mesh matrix - * @param {Float32Array} vertices - mesh coordinates in array - * @param {number} beginOffset - begin offset - * @param {number} endOffset - end offset, excluded - * @param {number} [padX=0] - x padding - * @param {number} [padY=0] - y padding - */ - Bounds.prototype.addVerticesMatrix = function (matrix, vertices, beginOffset, endOffset, padX, padY) { - if (padX === void 0) { padX = 0; } - if (padY === void 0) { padY = padX; } - var a = matrix.a; - var b = matrix.b; - var c = matrix.c; - var d = matrix.d; - var tx = matrix.tx; - var ty = matrix.ty; - var minX = this.minX; - var minY = this.minY; - var maxX = this.maxX; - var maxY = this.maxY; - for (var i = beginOffset; i < endOffset; i += 2) { - var rawX = vertices[i]; - var rawY = vertices[i + 1]; - var x = (a * rawX) + (c * rawY) + tx; - var y = (d * rawY) + (b * rawX) + ty; - minX = Math.min(minX, x - padX); - maxX = Math.max(maxX, x + padX); - minY = Math.min(minY, y - padY); - maxY = Math.max(maxY, y + padY); - } - this.minX = minX; - this.minY = minY; - this.maxX = maxX; - this.maxY = maxY; - }; - /** - * Adds other Bounds. - * - * @param {PIXI.Bounds} bounds - The Bounds to be added - */ - Bounds.prototype.addBounds = function (bounds) { - var minX = this.minX; - var minY = this.minY; - var maxX = this.maxX; - var maxY = this.maxY; - this.minX = bounds.minX < minX ? bounds.minX : minX; - this.minY = bounds.minY < minY ? bounds.minY : minY; - this.maxX = bounds.maxX > maxX ? bounds.maxX : maxX; - this.maxY = bounds.maxY > maxY ? bounds.maxY : maxY; - }; - /** - * Adds other Bounds, masked with Bounds. - * - * @param {PIXI.Bounds} bounds - The Bounds to be added. - * @param {PIXI.Bounds} mask - TODO - */ - Bounds.prototype.addBoundsMask = function (bounds, mask) { - var _minX = bounds.minX > mask.minX ? bounds.minX : mask.minX; - var _minY = bounds.minY > mask.minY ? bounds.minY : mask.minY; - var _maxX = bounds.maxX < mask.maxX ? bounds.maxX : mask.maxX; - var _maxY = bounds.maxY < mask.maxY ? bounds.maxY : mask.maxY; - if (_minX <= _maxX && _minY <= _maxY) { - var minX = this.minX; - var minY = this.minY; - var maxX = this.maxX; - var maxY = this.maxY; - this.minX = _minX < minX ? _minX : minX; - this.minY = _minY < minY ? _minY : minY; - this.maxX = _maxX > maxX ? _maxX : maxX; - this.maxY = _maxY > maxY ? _maxY : maxY; - } - }; - /** - * Adds other Bounds, multiplied by matrix. Bounds shouldn't be empty. - * - * @param {PIXI.Bounds} bounds - other bounds - * @param {PIXI.Matrix} matrix - multiplicator - */ - Bounds.prototype.addBoundsMatrix = function (bounds, matrix) { - this.addFrameMatrix(matrix, bounds.minX, bounds.minY, bounds.maxX, bounds.maxY); - }; - /** - * Adds other Bounds, masked with Rectangle. - * - * @param {PIXI.Bounds} bounds - TODO - * @param {PIXI.Rectangle} area - TODO - */ - Bounds.prototype.addBoundsArea = function (bounds, area) { - var _minX = bounds.minX > area.x ? bounds.minX : area.x; - var _minY = bounds.minY > area.y ? bounds.minY : area.y; - var _maxX = bounds.maxX < area.x + area.width ? bounds.maxX : (area.x + area.width); - var _maxY = bounds.maxY < area.y + area.height ? bounds.maxY : (area.y + area.height); - if (_minX <= _maxX && _minY <= _maxY) { - var minX = this.minX; - var minY = this.minY; - var maxX = this.maxX; - var maxY = this.maxY; - this.minX = _minX < minX ? _minX : minX; - this.minY = _minY < minY ? _minY : minY; - this.maxX = _maxX > maxX ? _maxX : maxX; - this.maxY = _maxY > maxY ? _maxY : maxY; - } - }; - /** - * Pads bounds object, making it grow in all directions. - * If paddingY is omitted, both paddingX and paddingY will be set to paddingX. - * - * @param {number} [paddingX=0] - The horizontal padding amount. - * @param {number} [paddingY=0] - The vertical padding amount. - */ - Bounds.prototype.pad = function (paddingX, paddingY) { - if (paddingX === void 0) { paddingX = 0; } - if (paddingY === void 0) { paddingY = paddingX; } - if (!this.isEmpty()) { - this.minX -= paddingX; - this.maxX += paddingX; - this.minY -= paddingY; - this.maxY += paddingY; - } - }; - /** - * Adds padded frame. (x0, y0) should be strictly less than (x1, y1) - * - * @param {number} x0 - left X of frame - * @param {number} y0 - top Y of frame - * @param {number} x1 - right X of frame - * @param {number} y1 - bottom Y of frame - * @param {number} padX - padding X - * @param {number} padY - padding Y - */ - Bounds.prototype.addFramePad = function (x0, y0, x1, y1, padX, padY) { - x0 -= padX; - y0 -= padY; - x1 += padX; - y1 += padY; - this.minX = this.minX < x0 ? this.minX : x0; - this.maxX = this.maxX > x1 ? this.maxX : x1; - this.minY = this.minY < y0 ? this.minY : y0; - this.maxY = this.maxY > y1 ? this.maxY : y1; - }; - return Bounds; - }()); - - /*! ***************************************************************************** - Copyright (c) Microsoft Corporation. All rights reserved. - Licensed under the Apache License, Version 2.0 (the "License"); you may not use - this file except in compliance with the License. You may obtain a copy of the - License at http://www.apache.org/licenses/LICENSE-2.0 + 'use strict'; + + /** + * @this {Promise} + */ + function finallyConstructor(callback) { + var constructor = this.constructor; + return this.then( + function(value) { + // @ts-ignore + return constructor.resolve(callback()).then(function() { + return value; + }); + }, + function(reason) { + // @ts-ignore + return constructor.resolve(callback()).then(function() { + // @ts-ignore + return constructor.reject(reason); + }); + } + ); + } + + function allSettled(arr) { + var P = this; + return new P(function(resolve, reject) { + if (!(arr && typeof arr.length !== 'undefined')) { + return reject( + new TypeError( + typeof arr + + ' ' + + arr + + ' is not iterable(cannot read property Symbol(Symbol.iterator))' + ) + ); + } + var args = Array.prototype.slice.call(arr); + if (args.length === 0) { return resolve([]); } + var remaining = args.length; + + function res(i, val) { + if (val && (typeof val === 'object' || typeof val === 'function')) { + var then = val.then; + if (typeof then === 'function') { + then.call( + val, + function(val) { + res(i, val); + }, + function(e) { + args[i] = { status: 'rejected', reason: e }; + if (--remaining === 0) { + resolve(args); + } + } + ); + return; + } + } + args[i] = { status: 'fulfilled', value: val }; + if (--remaining === 0) { + resolve(args); + } + } + + for (var i = 0; i < args.length; i++) { + res(i, args[i]); + } + }); + } + + // Store setTimeout reference so promise-polyfill will be unaffected by + // other code modifying setTimeout (like sinon.useFakeTimers()) + var setTimeoutFunc = setTimeout; + + function isArray(x) { + return Boolean(x && typeof x.length !== 'undefined'); + } + + function noop() {} + + // Polyfill for Function.prototype.bind + function bind(fn, thisArg) { + return function() { + fn.apply(thisArg, arguments); + }; + } + + /** + * @constructor + * @param {Function} fn + */ + function Promise$1(fn) { + if (!(this instanceof Promise$1)) + { throw new TypeError('Promises must be constructed via new'); } + if (typeof fn !== 'function') { throw new TypeError('not a function'); } + /** @type {!number} */ + this._state = 0; + /** @type {!boolean} */ + this._handled = false; + /** @type {Promise|undefined} */ + this._value = undefined; + /** @type {!Array} */ + this._deferreds = []; + + doResolve(fn, this); + } + + function handle(self, deferred) { + while (self._state === 3) { + self = self._value; + } + if (self._state === 0) { + self._deferreds.push(deferred); + return; + } + self._handled = true; + Promise$1._immediateFn(function() { + var cb = self._state === 1 ? deferred.onFulfilled : deferred.onRejected; + if (cb === null) { + (self._state === 1 ? resolve$1 : reject)(deferred.promise, self._value); + return; + } + var ret; + try { + ret = cb(self._value); + } catch (e) { + reject(deferred.promise, e); + return; + } + resolve$1(deferred.promise, ret); + }); + } + + function resolve$1(self, newValue) { + try { + // Promise Resolution Procedure: https://github.com/promises-aplus/promises-spec#the-promise-resolution-procedure + if (newValue === self) + { throw new TypeError('A promise cannot be resolved with itself.'); } + if ( + newValue && + (typeof newValue === 'object' || typeof newValue === 'function') + ) { + var then = newValue.then; + if (newValue instanceof Promise$1) { + self._state = 3; + self._value = newValue; + finale(self); + return; + } else if (typeof then === 'function') { + doResolve(bind(then, newValue), self); + return; + } + } + self._state = 1; + self._value = newValue; + finale(self); + } catch (e) { + reject(self, e); + } + } + + function reject(self, newValue) { + self._state = 2; + self._value = newValue; + finale(self); + } + + function finale(self) { + if (self._state === 2 && self._deferreds.length === 0) { + Promise$1._immediateFn(function() { + if (!self._handled) { + Promise$1._unhandledRejectionFn(self._value); + } + }); + } + + for (var i = 0, len = self._deferreds.length; i < len; i++) { + handle(self, self._deferreds[i]); + } + self._deferreds = null; + } + + /** + * @constructor + */ + function Handler(onFulfilled, onRejected, promise) { + this.onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : null; + this.onRejected = typeof onRejected === 'function' ? onRejected : null; + this.promise = promise; + } + + /** + * Take a potentially misbehaving resolver function and make sure + * onFulfilled and onRejected are only called once. + * + * Makes no guarantees about asynchrony. + */ + function doResolve(fn, self) { + var done = false; + try { + fn( + function(value) { + if (done) { return; } + done = true; + resolve$1(self, value); + }, + function(reason) { + if (done) { return; } + done = true; + reject(self, reason); + } + ); + } catch (ex) { + if (done) { return; } + done = true; + reject(self, ex); + } + } + + Promise$1.prototype['catch'] = function(onRejected) { + return this.then(null, onRejected); + }; + + Promise$1.prototype.then = function(onFulfilled, onRejected) { + // @ts-ignore + var prom = new this.constructor(noop); + + handle(this, new Handler(onFulfilled, onRejected, prom)); + return prom; + }; + + Promise$1.prototype['finally'] = finallyConstructor; + + Promise$1.all = function(arr) { + return new Promise$1(function(resolve, reject) { + if (!isArray(arr)) { + return reject(new TypeError('Promise.all accepts an array')); + } + + var args = Array.prototype.slice.call(arr); + if (args.length === 0) { return resolve([]); } + var remaining = args.length; + + function res(i, val) { + try { + if (val && (typeof val === 'object' || typeof val === 'function')) { + var then = val.then; + if (typeof then === 'function') { + then.call( + val, + function(val) { + res(i, val); + }, + reject + ); + return; + } + } + args[i] = val; + if (--remaining === 0) { + resolve(args); + } + } catch (ex) { + reject(ex); + } + } + + for (var i = 0; i < args.length; i++) { + res(i, args[i]); + } + }); + }; + + Promise$1.allSettled = allSettled; + + Promise$1.resolve = function(value) { + if (value && typeof value === 'object' && value.constructor === Promise$1) { + return value; + } + + return new Promise$1(function(resolve) { + resolve(value); + }); + }; + + Promise$1.reject = function(value) { + return new Promise$1(function(resolve, reject) { + reject(value); + }); + }; + + Promise$1.race = function(arr) { + return new Promise$1(function(resolve, reject) { + if (!isArray(arr)) { + return reject(new TypeError('Promise.race accepts an array')); + } + + for (var i = 0, len = arr.length; i < len; i++) { + Promise$1.resolve(arr[i]).then(resolve, reject); + } + }); + }; + + // Use polyfill for setImmediate for performance gains + Promise$1._immediateFn = + // @ts-ignore + (typeof setImmediate === 'function' && + function(fn) { + // @ts-ignore + setImmediate(fn); + }) || + function(fn) { + setTimeoutFunc(fn, 0); + }; + + Promise$1._unhandledRejectionFn = function _unhandledRejectionFn(err) { + if (typeof console !== 'undefined' && console) { + console.warn('Possible Unhandled Promise Rejection:', err); // eslint-disable-line no-console + } + }; + + /* + object-assign + (c) Sindre Sorhus + @license MIT + */ + + 'use strict'; + /* eslint-disable no-unused-vars */ + var getOwnPropertySymbols = Object.getOwnPropertySymbols; + var hasOwnProperty$2 = Object.prototype.hasOwnProperty; + var propIsEnumerable = Object.prototype.propertyIsEnumerable; + + function toObject(val) { + if (val === null || val === undefined) { + throw new TypeError('Object.assign cannot be called with null or undefined'); + } + + return Object(val); + } + + function shouldUseNative() { + try { + if (!Object.assign) { + return false; + } + + // Detect buggy property enumeration order in older V8 versions. + + // https://bugs.chromium.org/p/v8/issues/detail?id=4118 + var test1 = new String('abc'); // eslint-disable-line no-new-wrappers + test1[5] = 'de'; + if (Object.getOwnPropertyNames(test1)[0] === '5') { + return false; + } + + // https://bugs.chromium.org/p/v8/issues/detail?id=3056 + var test2 = {}; + for (var i = 0; i < 10; i++) { + test2['_' + String.fromCharCode(i)] = i; + } + var order2 = Object.getOwnPropertyNames(test2).map(function (n) { + return test2[n]; + }); + if (order2.join('') !== '0123456789') { + return false; + } + + // https://bugs.chromium.org/p/v8/issues/detail?id=3056 + var test3 = {}; + 'abcdefghijklmnopqrst'.split('').forEach(function (letter) { + test3[letter] = letter; + }); + if (Object.keys(Object.assign({}, test3)).join('') !== + 'abcdefghijklmnopqrst') { + return false; + } + + return true; + } catch (err) { + // We don't expect any of the above to throw, but better to be safe. + return false; + } + } + + var objectAssign = shouldUseNative() ? Object.assign : function (target, source) { + var arguments$1 = arguments; + + var from; + var to = toObject(target); + var symbols; + + for (var s = 1; s < arguments.length; s++) { + from = Object(arguments$1[s]); + + for (var key in from) { + if (hasOwnProperty$2.call(from, key)) { + to[key] = from[key]; + } + } + + if (getOwnPropertySymbols) { + symbols = getOwnPropertySymbols(from); + for (var i = 0; i < symbols.length; i++) { + if (propIsEnumerable.call(from, symbols[i])) { + to[symbols[i]] = from[symbols[i]]; + } + } + } + } + + return to; + }; + + /*! + * @pixi/polyfill - v6.5.3 + * Compiled Fri, 09 Sep 2022 13:55:20 UTC + * + * @pixi/polyfill is licensed under the MIT License. + * http://www.opensource.org/licenses/mit-license + */ + + if (typeof globalThis === 'undefined') { + if (typeof self !== 'undefined') { + // covers browsers + // @ts-expect-error not-writable ts(2540) error only on node + self.globalThis = self; + } + else if (typeof global !== 'undefined') { + // covers versions of Node < 12 + // @ts-expect-error not-writable ts(2540) error only on node + global.globalThis = global; + } + } + + // Support for IE 9 - 11 which does not include Promises + if (!globalThis.Promise) { + globalThis.Promise = Promise$1; + } + + // References: + if (!Object.assign) { + Object.assign = objectAssign; + } + + // References: + // http://paulirish.com/2011/requestanimationframe-for-smart-animating/ + // https://gist.github.com/1579671 + // http://updates.html5rocks.com/2012/05/requestAnimationFrame-API-now-with-sub-millisecond-precision + // https://gist.github.com/timhall/4078614 + // https://github.com/Financial-Times/polyfill-service/tree/master/polyfills/requestAnimationFrame + // Expected to be used with Browserfiy + // Browserify automatically detects the use of `global` and passes the + // correct reference of `global`, `globalThis`, and finally `window` + var ONE_FRAME_TIME = 16; + // Date.now + if (!(Date.now && Date.prototype.getTime)) { + Date.now = function now() { + return new Date().getTime(); + }; + } + // performance.now + if (!(globalThis.performance && globalThis.performance.now)) { + var startTime_1 = Date.now(); + if (!globalThis.performance) { + globalThis.performance = {}; + } + globalThis.performance.now = function () { return Date.now() - startTime_1; }; + } + // requestAnimationFrame + var lastTime = Date.now(); + var vendors = ['ms', 'moz', 'webkit', 'o']; + for (var x = 0; x < vendors.length && !globalThis.requestAnimationFrame; ++x) { + var p = vendors[x]; + globalThis.requestAnimationFrame = globalThis[p + "RequestAnimationFrame"]; + globalThis.cancelAnimationFrame = globalThis[p + "CancelAnimationFrame"] + || globalThis[p + "CancelRequestAnimationFrame"]; + } + if (!globalThis.requestAnimationFrame) { + globalThis.requestAnimationFrame = function (callback) { + if (typeof callback !== 'function') { + throw new TypeError(callback + "is not a function"); + } + var currentTime = Date.now(); + var delay = ONE_FRAME_TIME + lastTime - currentTime; + if (delay < 0) { + delay = 0; + } + lastTime = currentTime; + return globalThis.self.setTimeout(function () { + lastTime = Date.now(); + callback(performance.now()); + }, delay); + }; + } + if (!globalThis.cancelAnimationFrame) { + globalThis.cancelAnimationFrame = function (id) { return clearTimeout(id); }; + } + + // References: + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/sign + if (!Math.sign) { + Math.sign = function mathSign(x) { + x = Number(x); + if (x === 0 || isNaN(x)) { + return x; + } + return x > 0 ? 1 : -1; + }; + } + + // References: + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isInteger + if (!Number.isInteger) { + Number.isInteger = function numberIsInteger(value) { + return typeof value === 'number' && isFinite(value) && Math.floor(value) === value; + }; + } + + if (!globalThis.ArrayBuffer) { + globalThis.ArrayBuffer = Array; + } + if (!globalThis.Float32Array) { + globalThis.Float32Array = Array; + } + if (!globalThis.Uint32Array) { + globalThis.Uint32Array = Array; + } + if (!globalThis.Uint16Array) { + globalThis.Uint16Array = Array; + } + if (!globalThis.Uint8Array) { + globalThis.Uint8Array = Array; + } + if (!globalThis.Int32Array) { + globalThis.Int32Array = Array; + } + + /*! + * @pixi/settings - v6.5.3 + * Compiled Fri, 09 Sep 2022 13:55:20 UTC + * + * @pixi/settings is licensed under the MIT License. + * http://www.opensource.org/licenses/mit-license + */ + /*! + * @pixi/constants - v6.5.3 + * Compiled Fri, 09 Sep 2022 13:55:20 UTC + * + * @pixi/constants is licensed under the MIT License. + * http://www.opensource.org/licenses/mit-license + */ + /** + * Different types of environments for WebGL. + * @static + * @memberof PIXI + * @name ENV + * @enum {number} + * @property {number} WEBGL_LEGACY - Used for older v1 WebGL devices. PixiJS will aim to ensure compatibility + * with older / less advanced devices. If you experience unexplained flickering prefer this environment. + * @property {number} WEBGL - Version 1 of WebGL + * @property {number} WEBGL2 - Version 2 of WebGL + */ + var ENV$5; + (function (ENV) { + ENV[ENV["WEBGL_LEGACY"] = 0] = "WEBGL_LEGACY"; + ENV[ENV["WEBGL"] = 1] = "WEBGL"; + ENV[ENV["WEBGL2"] = 2] = "WEBGL2"; + })(ENV$5 || (ENV$5 = {})); + /** + * Constant to identify the Renderer Type. + * @static + * @memberof PIXI + * @name RENDERER_TYPE + * @enum {number} + * @property {number} UNKNOWN - Unknown render type. + * @property {number} WEBGL - WebGL render type. + * @property {number} CANVAS - Canvas render type. + */ + var RENDERER_TYPE$5; + (function (RENDERER_TYPE) { + RENDERER_TYPE[RENDERER_TYPE["UNKNOWN"] = 0] = "UNKNOWN"; + RENDERER_TYPE[RENDERER_TYPE["WEBGL"] = 1] = "WEBGL"; + RENDERER_TYPE[RENDERER_TYPE["CANVAS"] = 2] = "CANVAS"; + })(RENDERER_TYPE$5 || (RENDERER_TYPE$5 = {})); + /** + * Bitwise OR of masks that indicate the buffers to be cleared. + * @static + * @memberof PIXI + * @name BUFFER_BITS + * @enum {number} + * @property {number} COLOR - Indicates the buffers currently enabled for color writing. + * @property {number} DEPTH - Indicates the depth buffer. + * @property {number} STENCIL - Indicates the stencil buffer. + */ + var BUFFER_BITS$5; + (function (BUFFER_BITS) { + BUFFER_BITS[BUFFER_BITS["COLOR"] = 16384] = "COLOR"; + BUFFER_BITS[BUFFER_BITS["DEPTH"] = 256] = "DEPTH"; + BUFFER_BITS[BUFFER_BITS["STENCIL"] = 1024] = "STENCIL"; + })(BUFFER_BITS$5 || (BUFFER_BITS$5 = {})); + /** + * Various blend modes supported by PIXI. + * + * IMPORTANT - The WebGL renderer only supports the NORMAL, ADD, MULTIPLY and SCREEN blend modes. + * Anything else will silently act like NORMAL. + * @memberof PIXI + * @name BLEND_MODES + * @enum {number} + * @property {number} NORMAL - + * @property {number} ADD - + * @property {number} MULTIPLY - + * @property {number} SCREEN - + * @property {number} OVERLAY - + * @property {number} DARKEN - + * @property {number} LIGHTEN - + * @property {number} COLOR_DODGE - + * @property {number} COLOR_BURN - + * @property {number} HARD_LIGHT - + * @property {number} SOFT_LIGHT - + * @property {number} DIFFERENCE - + * @property {number} EXCLUSION - + * @property {number} HUE - + * @property {number} SATURATION - + * @property {number} COLOR - + * @property {number} LUMINOSITY - + * @property {number} NORMAL_NPM - + * @property {number} ADD_NPM - + * @property {number} SCREEN_NPM - + * @property {number} NONE - + * @property {number} SRC_IN - + * @property {number} SRC_OUT - + * @property {number} SRC_ATOP - + * @property {number} DST_OVER - + * @property {number} DST_IN - + * @property {number} DST_OUT - + * @property {number} DST_ATOP - + * @property {number} SUBTRACT - + * @property {number} SRC_OVER - + * @property {number} ERASE - + * @property {number} XOR - + */ + var BLEND_MODES$5; + (function (BLEND_MODES) { + BLEND_MODES[BLEND_MODES["NORMAL"] = 0] = "NORMAL"; + BLEND_MODES[BLEND_MODES["ADD"] = 1] = "ADD"; + BLEND_MODES[BLEND_MODES["MULTIPLY"] = 2] = "MULTIPLY"; + BLEND_MODES[BLEND_MODES["SCREEN"] = 3] = "SCREEN"; + BLEND_MODES[BLEND_MODES["OVERLAY"] = 4] = "OVERLAY"; + BLEND_MODES[BLEND_MODES["DARKEN"] = 5] = "DARKEN"; + BLEND_MODES[BLEND_MODES["LIGHTEN"] = 6] = "LIGHTEN"; + BLEND_MODES[BLEND_MODES["COLOR_DODGE"] = 7] = "COLOR_DODGE"; + BLEND_MODES[BLEND_MODES["COLOR_BURN"] = 8] = "COLOR_BURN"; + BLEND_MODES[BLEND_MODES["HARD_LIGHT"] = 9] = "HARD_LIGHT"; + BLEND_MODES[BLEND_MODES["SOFT_LIGHT"] = 10] = "SOFT_LIGHT"; + BLEND_MODES[BLEND_MODES["DIFFERENCE"] = 11] = "DIFFERENCE"; + BLEND_MODES[BLEND_MODES["EXCLUSION"] = 12] = "EXCLUSION"; + BLEND_MODES[BLEND_MODES["HUE"] = 13] = "HUE"; + BLEND_MODES[BLEND_MODES["SATURATION"] = 14] = "SATURATION"; + BLEND_MODES[BLEND_MODES["COLOR"] = 15] = "COLOR"; + BLEND_MODES[BLEND_MODES["LUMINOSITY"] = 16] = "LUMINOSITY"; + BLEND_MODES[BLEND_MODES["NORMAL_NPM"] = 17] = "NORMAL_NPM"; + BLEND_MODES[BLEND_MODES["ADD_NPM"] = 18] = "ADD_NPM"; + BLEND_MODES[BLEND_MODES["SCREEN_NPM"] = 19] = "SCREEN_NPM"; + BLEND_MODES[BLEND_MODES["NONE"] = 20] = "NONE"; + BLEND_MODES[BLEND_MODES["SRC_OVER"] = 0] = "SRC_OVER"; + BLEND_MODES[BLEND_MODES["SRC_IN"] = 21] = "SRC_IN"; + BLEND_MODES[BLEND_MODES["SRC_OUT"] = 22] = "SRC_OUT"; + BLEND_MODES[BLEND_MODES["SRC_ATOP"] = 23] = "SRC_ATOP"; + BLEND_MODES[BLEND_MODES["DST_OVER"] = 24] = "DST_OVER"; + BLEND_MODES[BLEND_MODES["DST_IN"] = 25] = "DST_IN"; + BLEND_MODES[BLEND_MODES["DST_OUT"] = 26] = "DST_OUT"; + BLEND_MODES[BLEND_MODES["DST_ATOP"] = 27] = "DST_ATOP"; + BLEND_MODES[BLEND_MODES["ERASE"] = 26] = "ERASE"; + BLEND_MODES[BLEND_MODES["SUBTRACT"] = 28] = "SUBTRACT"; + BLEND_MODES[BLEND_MODES["XOR"] = 29] = "XOR"; + })(BLEND_MODES$5 || (BLEND_MODES$5 = {})); + /** + * Various webgl draw modes. These can be used to specify which GL drawMode to use + * under certain situations and renderers. + * @memberof PIXI + * @static + * @name DRAW_MODES + * @enum {number} + * @property {number} POINTS - + * @property {number} LINES - + * @property {number} LINE_LOOP - + * @property {number} LINE_STRIP - + * @property {number} TRIANGLES - + * @property {number} TRIANGLE_STRIP - + * @property {number} TRIANGLE_FAN - + */ + var DRAW_MODES$5; + (function (DRAW_MODES) { + DRAW_MODES[DRAW_MODES["POINTS"] = 0] = "POINTS"; + DRAW_MODES[DRAW_MODES["LINES"] = 1] = "LINES"; + DRAW_MODES[DRAW_MODES["LINE_LOOP"] = 2] = "LINE_LOOP"; + DRAW_MODES[DRAW_MODES["LINE_STRIP"] = 3] = "LINE_STRIP"; + DRAW_MODES[DRAW_MODES["TRIANGLES"] = 4] = "TRIANGLES"; + DRAW_MODES[DRAW_MODES["TRIANGLE_STRIP"] = 5] = "TRIANGLE_STRIP"; + DRAW_MODES[DRAW_MODES["TRIANGLE_FAN"] = 6] = "TRIANGLE_FAN"; + })(DRAW_MODES$5 || (DRAW_MODES$5 = {})); + /** + * Various GL texture/resources formats. + * @memberof PIXI + * @static + * @name FORMATS + * @enum {number} + * @property {number} [RGBA=6408] - + * @property {number} [RGB=6407] - + * @property {number} [RG=33319] - + * @property {number} [RED=6403] - + * @property {number} [RGBA_INTEGER=36249] - + * @property {number} [RGB_INTEGER=36248] - + * @property {number} [RG_INTEGER=33320] - + * @property {number} [RED_INTEGER=36244] - + * @property {number} [ALPHA=6406] - + * @property {number} [LUMINANCE=6409] - + * @property {number} [LUMINANCE_ALPHA=6410] - + * @property {number} [DEPTH_COMPONENT=6402] - + * @property {number} [DEPTH_STENCIL=34041] - + */ + var FORMATS$5; + (function (FORMATS) { + FORMATS[FORMATS["RGBA"] = 6408] = "RGBA"; + FORMATS[FORMATS["RGB"] = 6407] = "RGB"; + FORMATS[FORMATS["RG"] = 33319] = "RG"; + FORMATS[FORMATS["RED"] = 6403] = "RED"; + FORMATS[FORMATS["RGBA_INTEGER"] = 36249] = "RGBA_INTEGER"; + FORMATS[FORMATS["RGB_INTEGER"] = 36248] = "RGB_INTEGER"; + FORMATS[FORMATS["RG_INTEGER"] = 33320] = "RG_INTEGER"; + FORMATS[FORMATS["RED_INTEGER"] = 36244] = "RED_INTEGER"; + FORMATS[FORMATS["ALPHA"] = 6406] = "ALPHA"; + FORMATS[FORMATS["LUMINANCE"] = 6409] = "LUMINANCE"; + FORMATS[FORMATS["LUMINANCE_ALPHA"] = 6410] = "LUMINANCE_ALPHA"; + FORMATS[FORMATS["DEPTH_COMPONENT"] = 6402] = "DEPTH_COMPONENT"; + FORMATS[FORMATS["DEPTH_STENCIL"] = 34041] = "DEPTH_STENCIL"; + })(FORMATS$5 || (FORMATS$5 = {})); + /** + * Various GL target types. + * @memberof PIXI + * @static + * @name TARGETS + * @enum {number} + * @property {number} [TEXTURE_2D=3553] - + * @property {number} [TEXTURE_CUBE_MAP=34067] - + * @property {number} [TEXTURE_2D_ARRAY=35866] - + * @property {number} [TEXTURE_CUBE_MAP_POSITIVE_X=34069] - + * @property {number} [TEXTURE_CUBE_MAP_NEGATIVE_X=34070] - + * @property {number} [TEXTURE_CUBE_MAP_POSITIVE_Y=34071] - + * @property {number} [TEXTURE_CUBE_MAP_NEGATIVE_Y=34072] - + * @property {number} [TEXTURE_CUBE_MAP_POSITIVE_Z=34073] - + * @property {number} [TEXTURE_CUBE_MAP_NEGATIVE_Z=34074] - + */ + var TARGETS$5; + (function (TARGETS) { + TARGETS[TARGETS["TEXTURE_2D"] = 3553] = "TEXTURE_2D"; + TARGETS[TARGETS["TEXTURE_CUBE_MAP"] = 34067] = "TEXTURE_CUBE_MAP"; + TARGETS[TARGETS["TEXTURE_2D_ARRAY"] = 35866] = "TEXTURE_2D_ARRAY"; + TARGETS[TARGETS["TEXTURE_CUBE_MAP_POSITIVE_X"] = 34069] = "TEXTURE_CUBE_MAP_POSITIVE_X"; + TARGETS[TARGETS["TEXTURE_CUBE_MAP_NEGATIVE_X"] = 34070] = "TEXTURE_CUBE_MAP_NEGATIVE_X"; + TARGETS[TARGETS["TEXTURE_CUBE_MAP_POSITIVE_Y"] = 34071] = "TEXTURE_CUBE_MAP_POSITIVE_Y"; + TARGETS[TARGETS["TEXTURE_CUBE_MAP_NEGATIVE_Y"] = 34072] = "TEXTURE_CUBE_MAP_NEGATIVE_Y"; + TARGETS[TARGETS["TEXTURE_CUBE_MAP_POSITIVE_Z"] = 34073] = "TEXTURE_CUBE_MAP_POSITIVE_Z"; + TARGETS[TARGETS["TEXTURE_CUBE_MAP_NEGATIVE_Z"] = 34074] = "TEXTURE_CUBE_MAP_NEGATIVE_Z"; + })(TARGETS$5 || (TARGETS$5 = {})); + /** + * Various GL data format types. + * @memberof PIXI + * @static + * @name TYPES + * @enum {number} + * @property {number} [UNSIGNED_BYTE=5121] - + * @property {number} [UNSIGNED_SHORT=5123] - + * @property {number} [UNSIGNED_SHORT_5_6_5=33635] - + * @property {number} [UNSIGNED_SHORT_4_4_4_4=32819] - + * @property {number} [UNSIGNED_SHORT_5_5_5_1=32820] - + * @property {number} [UNSIGNED_INT=5125] - + * @property {number} [UNSIGNED_INT_10F_11F_11F_REV=35899] - + * @property {number} [UNSIGNED_INT_2_10_10_10_REV=33640] - + * @property {number} [UNSIGNED_INT_24_8=34042] - + * @property {number} [UNSIGNED_INT_5_9_9_9_REV=35902] - + * @property {number} [BYTE=5120] - + * @property {number} [SHORT=5122] - + * @property {number} [INT=5124] - + * @property {number} [FLOAT=5126] - + * @property {number} [FLOAT_32_UNSIGNED_INT_24_8_REV=36269] - + * @property {number} [HALF_FLOAT=36193] - + */ + var TYPES$5; + (function (TYPES) { + TYPES[TYPES["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE"; + TYPES[TYPES["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT"; + TYPES[TYPES["UNSIGNED_SHORT_5_6_5"] = 33635] = "UNSIGNED_SHORT_5_6_5"; + TYPES[TYPES["UNSIGNED_SHORT_4_4_4_4"] = 32819] = "UNSIGNED_SHORT_4_4_4_4"; + TYPES[TYPES["UNSIGNED_SHORT_5_5_5_1"] = 32820] = "UNSIGNED_SHORT_5_5_5_1"; + TYPES[TYPES["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT"; + TYPES[TYPES["UNSIGNED_INT_10F_11F_11F_REV"] = 35899] = "UNSIGNED_INT_10F_11F_11F_REV"; + TYPES[TYPES["UNSIGNED_INT_2_10_10_10_REV"] = 33640] = "UNSIGNED_INT_2_10_10_10_REV"; + TYPES[TYPES["UNSIGNED_INT_24_8"] = 34042] = "UNSIGNED_INT_24_8"; + TYPES[TYPES["UNSIGNED_INT_5_9_9_9_REV"] = 35902] = "UNSIGNED_INT_5_9_9_9_REV"; + TYPES[TYPES["BYTE"] = 5120] = "BYTE"; + TYPES[TYPES["SHORT"] = 5122] = "SHORT"; + TYPES[TYPES["INT"] = 5124] = "INT"; + TYPES[TYPES["FLOAT"] = 5126] = "FLOAT"; + TYPES[TYPES["FLOAT_32_UNSIGNED_INT_24_8_REV"] = 36269] = "FLOAT_32_UNSIGNED_INT_24_8_REV"; + TYPES[TYPES["HALF_FLOAT"] = 36193] = "HALF_FLOAT"; + })(TYPES$5 || (TYPES$5 = {})); + /** + * Various sampler types. Correspond to `sampler`, `isampler`, `usampler` GLSL types respectively. + * WebGL1 works only with FLOAT. + * @memberof PIXI + * @static + * @name SAMPLER_TYPES + * @enum {number} + * @property {number} [FLOAT=0] - + * @property {number} [INT=1] - + * @property {number} [UINT=2] - + */ + var SAMPLER_TYPES$5; + (function (SAMPLER_TYPES) { + SAMPLER_TYPES[SAMPLER_TYPES["FLOAT"] = 0] = "FLOAT"; + SAMPLER_TYPES[SAMPLER_TYPES["INT"] = 1] = "INT"; + SAMPLER_TYPES[SAMPLER_TYPES["UINT"] = 2] = "UINT"; + })(SAMPLER_TYPES$5 || (SAMPLER_TYPES$5 = {})); + /** + * The scale modes that are supported by pixi. + * + * The {@link PIXI.settings.SCALE_MODE} scale mode affects the default scaling mode of future operations. + * It can be re-assigned to either LINEAR or NEAREST, depending upon suitability. + * @memberof PIXI + * @static + * @name SCALE_MODES + * @enum {number} + * @property {number} LINEAR Smooth scaling + * @property {number} NEAREST Pixelating scaling + */ + var SCALE_MODES$5; + (function (SCALE_MODES) { + SCALE_MODES[SCALE_MODES["NEAREST"] = 0] = "NEAREST"; + SCALE_MODES[SCALE_MODES["LINEAR"] = 1] = "LINEAR"; + })(SCALE_MODES$5 || (SCALE_MODES$5 = {})); + /** + * The wrap modes that are supported by pixi. + * + * The {@link PIXI.settings.WRAP_MODE} wrap mode affects the default wrapping mode of future operations. + * It can be re-assigned to either CLAMP or REPEAT, depending upon suitability. + * If the texture is non power of two then clamp will be used regardless as WebGL can + * only use REPEAT if the texture is po2. + * + * This property only affects WebGL. + * @name WRAP_MODES + * @memberof PIXI + * @static + * @enum {number} + * @property {number} CLAMP - The textures uvs are clamped + * @property {number} REPEAT - The texture uvs tile and repeat + * @property {number} MIRRORED_REPEAT - The texture uvs tile and repeat with mirroring + */ + var WRAP_MODES$5; + (function (WRAP_MODES) { + WRAP_MODES[WRAP_MODES["CLAMP"] = 33071] = "CLAMP"; + WRAP_MODES[WRAP_MODES["REPEAT"] = 10497] = "REPEAT"; + WRAP_MODES[WRAP_MODES["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT"; + })(WRAP_MODES$5 || (WRAP_MODES$5 = {})); + /** + * Mipmap filtering modes that are supported by pixi. + * + * The {@link PIXI.settings.MIPMAP_TEXTURES} affects default texture filtering. + * Mipmaps are generated for a baseTexture if its `mipmap` field is `ON`, + * or its `POW2` and texture dimensions are powers of 2. + * Due to platform restriction, `ON` option will work like `POW2` for webgl-1. + * + * This property only affects WebGL. + * @name MIPMAP_MODES + * @memberof PIXI + * @static + * @enum {number} + * @property {number} OFF - No mipmaps + * @property {number} POW2 - Generate mipmaps if texture dimensions are pow2 + * @property {number} ON - Always generate mipmaps + * @property {number} ON_MANUAL - Use mipmaps, but do not auto-generate them; this is used with a resource + * that supports buffering each level-of-detail. + */ + var MIPMAP_MODES$5; + (function (MIPMAP_MODES) { + MIPMAP_MODES[MIPMAP_MODES["OFF"] = 0] = "OFF"; + MIPMAP_MODES[MIPMAP_MODES["POW2"] = 1] = "POW2"; + MIPMAP_MODES[MIPMAP_MODES["ON"] = 2] = "ON"; + MIPMAP_MODES[MIPMAP_MODES["ON_MANUAL"] = 3] = "ON_MANUAL"; + })(MIPMAP_MODES$5 || (MIPMAP_MODES$5 = {})); + /** + * How to treat textures with premultiplied alpha + * @name ALPHA_MODES + * @memberof PIXI + * @static + * @enum {number} + * @property {number} NO_PREMULTIPLIED_ALPHA - Source is not premultiplied, leave it like that. + * Option for compressed and data textures that are created from typed arrays. + * @property {number} PREMULTIPLY_ON_UPLOAD - Source is not premultiplied, premultiply on upload. + * Default option, used for all loaded images. + * @property {number} PREMULTIPLIED_ALPHA - Source is already premultiplied + * Example: spine atlases with `_pma` suffix. + * @property {number} NPM - Alias for NO_PREMULTIPLIED_ALPHA. + * @property {number} UNPACK - Default option, alias for PREMULTIPLY_ON_UPLOAD. + * @property {number} PMA - Alias for PREMULTIPLIED_ALPHA. + */ + var ALPHA_MODES$5; + (function (ALPHA_MODES) { + ALPHA_MODES[ALPHA_MODES["NPM"] = 0] = "NPM"; + ALPHA_MODES[ALPHA_MODES["UNPACK"] = 1] = "UNPACK"; + ALPHA_MODES[ALPHA_MODES["PMA"] = 2] = "PMA"; + ALPHA_MODES[ALPHA_MODES["NO_PREMULTIPLIED_ALPHA"] = 0] = "NO_PREMULTIPLIED_ALPHA"; + ALPHA_MODES[ALPHA_MODES["PREMULTIPLY_ON_UPLOAD"] = 1] = "PREMULTIPLY_ON_UPLOAD"; + ALPHA_MODES[ALPHA_MODES["PREMULTIPLY_ALPHA"] = 2] = "PREMULTIPLY_ALPHA"; + ALPHA_MODES[ALPHA_MODES["PREMULTIPLIED_ALPHA"] = 2] = "PREMULTIPLIED_ALPHA"; + })(ALPHA_MODES$5 || (ALPHA_MODES$5 = {})); + /** + * Configure whether filter textures are cleared after binding. + * + * Filter textures need not be cleared if the filter does not use pixel blending. {@link CLEAR_MODES.BLIT} will detect + * this and skip clearing as an optimization. + * @name CLEAR_MODES + * @memberof PIXI + * @static + * @enum {number} + * @property {number} BLEND - Do not clear the filter texture. The filter's output will blend on top of the output texture. + * @property {number} CLEAR - Always clear the filter texture. + * @property {number} BLIT - Clear only if {@link FilterSystem.forceClear} is set or if the filter uses pixel blending. + * @property {number} NO - Alias for BLEND, same as `false` in earlier versions + * @property {number} YES - Alias for CLEAR, same as `true` in earlier versions + * @property {number} AUTO - Alias for BLIT + */ + var CLEAR_MODES$5; + (function (CLEAR_MODES) { + CLEAR_MODES[CLEAR_MODES["NO"] = 0] = "NO"; + CLEAR_MODES[CLEAR_MODES["YES"] = 1] = "YES"; + CLEAR_MODES[CLEAR_MODES["AUTO"] = 2] = "AUTO"; + CLEAR_MODES[CLEAR_MODES["BLEND"] = 0] = "BLEND"; + CLEAR_MODES[CLEAR_MODES["CLEAR"] = 1] = "CLEAR"; + CLEAR_MODES[CLEAR_MODES["BLIT"] = 2] = "BLIT"; + })(CLEAR_MODES$5 || (CLEAR_MODES$5 = {})); + /** + * The gc modes that are supported by pixi. + * + * The {@link PIXI.settings.GC_MODE} Garbage Collection mode for PixiJS textures is AUTO + * If set to GC_MODE, the renderer will occasionally check textures usage. If they are not + * used for a specified period of time they will be removed from the GPU. They will of course + * be uploaded again when they are required. This is a silent behind the scenes process that + * should ensure that the GPU does not get filled up. + * + * Handy for mobile devices! + * This property only affects WebGL. + * @name GC_MODES + * @enum {number} + * @static + * @memberof PIXI + * @property {number} AUTO - Garbage collection will happen periodically automatically + * @property {number} MANUAL - Garbage collection will need to be called manually + */ + var GC_MODES$5; + (function (GC_MODES) { + GC_MODES[GC_MODES["AUTO"] = 0] = "AUTO"; + GC_MODES[GC_MODES["MANUAL"] = 1] = "MANUAL"; + })(GC_MODES$5 || (GC_MODES$5 = {})); + /** + * Constants that specify float precision in shaders. + * @name PRECISION + * @memberof PIXI + * @constant + * @static + * @enum {string} + * @property {string} [LOW='lowp'] - + * @property {string} [MEDIUM='mediump'] - + * @property {string} [HIGH='highp'] - + */ + var PRECISION$5; + (function (PRECISION) { + PRECISION["LOW"] = "lowp"; + PRECISION["MEDIUM"] = "mediump"; + PRECISION["HIGH"] = "highp"; + })(PRECISION$5 || (PRECISION$5 = {})); + /** + * Constants for mask implementations. + * We use `type` suffix because it leads to very different behaviours + * @name MASK_TYPES + * @memberof PIXI + * @static + * @enum {number} + * @property {number} NONE - Mask is ignored + * @property {number} SCISSOR - Scissor mask, rectangle on screen, cheap + * @property {number} STENCIL - Stencil mask, 1-bit, medium, works only if renderer supports stencil + * @property {number} SPRITE - Mask that uses SpriteMaskFilter, uses temporary RenderTexture + * @property {number} COLOR - Color mask (RGBA) + */ + var MASK_TYPES$5; + (function (MASK_TYPES) { + MASK_TYPES[MASK_TYPES["NONE"] = 0] = "NONE"; + MASK_TYPES[MASK_TYPES["SCISSOR"] = 1] = "SCISSOR"; + MASK_TYPES[MASK_TYPES["STENCIL"] = 2] = "STENCIL"; + MASK_TYPES[MASK_TYPES["SPRITE"] = 3] = "SPRITE"; + MASK_TYPES[MASK_TYPES["COLOR"] = 4] = "COLOR"; + })(MASK_TYPES$5 || (MASK_TYPES$5 = {})); + /** + * Bitwise OR of masks that indicate the color channels that are rendered to. + * @static + * @memberof PIXI + * @name COLOR_MASK_BITS + * @enum {number} + * @property {number} RED - Red channel. + * @property {number} GREEN - Green channel + * @property {number} BLUE - Blue channel. + * @property {number} ALPHA - Alpha channel. + */ + var COLOR_MASK_BITS$5; + (function (COLOR_MASK_BITS) { + COLOR_MASK_BITS[COLOR_MASK_BITS["RED"] = 1] = "RED"; + COLOR_MASK_BITS[COLOR_MASK_BITS["GREEN"] = 2] = "GREEN"; + COLOR_MASK_BITS[COLOR_MASK_BITS["BLUE"] = 4] = "BLUE"; + COLOR_MASK_BITS[COLOR_MASK_BITS["ALPHA"] = 8] = "ALPHA"; + })(COLOR_MASK_BITS$5 || (COLOR_MASK_BITS$5 = {})); + /** + * Constants for multi-sampling antialiasing. + * @see PIXI.Framebuffer#multisample + * @name MSAA_QUALITY + * @memberof PIXI + * @static + * @enum {number} + * @property {number} NONE - No multisampling for this renderTexture + * @property {number} LOW - Try 2 samples + * @property {number} MEDIUM - Try 4 samples + * @property {number} HIGH - Try 8 samples + */ + var MSAA_QUALITY$5; + (function (MSAA_QUALITY) { + MSAA_QUALITY[MSAA_QUALITY["NONE"] = 0] = "NONE"; + MSAA_QUALITY[MSAA_QUALITY["LOW"] = 2] = "LOW"; + MSAA_QUALITY[MSAA_QUALITY["MEDIUM"] = 4] = "MEDIUM"; + MSAA_QUALITY[MSAA_QUALITY["HIGH"] = 8] = "HIGH"; + })(MSAA_QUALITY$5 || (MSAA_QUALITY$5 = {})); + /** + * Constants for various buffer types in Pixi + * @see PIXI.BUFFER_TYPE + * @name BUFFER_TYPE + * @memberof PIXI + * @static + * @enum {number} + * @property {number} ELEMENT_ARRAY_BUFFER - buffer type for using as an index buffer + * @property {number} ARRAY_BUFFER - buffer type for using attribute data + * @property {number} UNIFORM_BUFFER - the buffer type is for uniform buffer objects + */ + var BUFFER_TYPE$5; + (function (BUFFER_TYPE) { + BUFFER_TYPE[BUFFER_TYPE["ELEMENT_ARRAY_BUFFER"] = 34963] = "ELEMENT_ARRAY_BUFFER"; + BUFFER_TYPE[BUFFER_TYPE["ARRAY_BUFFER"] = 34962] = "ARRAY_BUFFER"; + // NOT YET SUPPORTED + BUFFER_TYPE[BUFFER_TYPE["UNIFORM_BUFFER"] = 35345] = "UNIFORM_BUFFER"; + })(BUFFER_TYPE$5 || (BUFFER_TYPE$5 = {})); + + var BrowserAdapter$1 = { + /** + * Creates a canvas element of the given size. + * This canvas is created using the browser's native canvas element. + * @param width - width of the canvas + * @param height - height of the canvas + */ + createCanvas: function (width, height) { + var canvas = document.createElement('canvas'); + canvas.width = width; + canvas.height = height; + return canvas; + }, + getWebGLRenderingContext: function () { return WebGLRenderingContext; }, + getNavigator: function () { return navigator; }, + getBaseUrl: function () { var _a; return ((_a = document.baseURI) !== null && _a !== void 0 ? _a : window.location.href); }, + fetch: function (url, options) { return fetch(url, options); }, + }; + + var appleIphone$1 = /iPhone/i; + var appleIpod$1 = /iPod/i; + var appleTablet$1 = /iPad/i; + var appleUniversal$1 = /\biOS-universal(?:.+)Mac\b/i; + var androidPhone$1 = /\bAndroid(?:.+)Mobile\b/i; + var androidTablet$1 = /Android/i; + var amazonPhone$1 = /(?:SD4930UR|\bSilk(?:.+)Mobile\b)/i; + var amazonTablet$1 = /Silk/i; + var windowsPhone$1 = /Windows Phone/i; + var windowsTablet$1 = /\bWindows(?:.+)ARM\b/i; + var otherBlackBerry$1 = /BlackBerry/i; + var otherBlackBerry10$1 = /BB10/i; + var otherOpera$1 = /Opera Mini/i; + var otherChrome$1 = /\b(CriOS|Chrome)(?:.+)Mobile/i; + var otherFirefox$1 = /Mobile(?:.+)Firefox\b/i; + var isAppleTabletOnIos13$1 = function (navigator) { + return (typeof navigator !== 'undefined' && + navigator.platform === 'MacIntel' && + typeof navigator.maxTouchPoints === 'number' && + navigator.maxTouchPoints > 1 && + typeof MSStream === 'undefined'); + }; + function createMatch$1(userAgent) { + return function (regex) { return regex.test(userAgent); }; + } + function isMobile$1$1(param) { + var nav = { + userAgent: '', + platform: '', + maxTouchPoints: 0 + }; + if (!param && typeof navigator !== 'undefined') { + nav = { + userAgent: navigator.userAgent, + platform: navigator.platform, + maxTouchPoints: navigator.maxTouchPoints || 0 + }; + } + else if (typeof param === 'string') { + nav.userAgent = param; + } + else if (param && param.userAgent) { + nav = { + userAgent: param.userAgent, + platform: param.platform, + maxTouchPoints: param.maxTouchPoints || 0 + }; + } + var userAgent = nav.userAgent; + var tmp = userAgent.split('[FBAN'); + if (typeof tmp[1] !== 'undefined') { + userAgent = tmp[0]; + } + tmp = userAgent.split('Twitter'); + if (typeof tmp[1] !== 'undefined') { + userAgent = tmp[0]; + } + var match = createMatch$1(userAgent); + var result = { + apple: { + phone: match(appleIphone$1) && !match(windowsPhone$1), + ipod: match(appleIpod$1), + tablet: !match(appleIphone$1) && + (match(appleTablet$1) || isAppleTabletOnIos13$1(nav)) && + !match(windowsPhone$1), + universal: match(appleUniversal$1), + device: (match(appleIphone$1) || + match(appleIpod$1) || + match(appleTablet$1) || + match(appleUniversal$1) || + isAppleTabletOnIos13$1(nav)) && + !match(windowsPhone$1) + }, + amazon: { + phone: match(amazonPhone$1), + tablet: !match(amazonPhone$1) && match(amazonTablet$1), + device: match(amazonPhone$1) || match(amazonTablet$1) + }, + android: { + phone: (!match(windowsPhone$1) && match(amazonPhone$1)) || + (!match(windowsPhone$1) && match(androidPhone$1)), + tablet: !match(windowsPhone$1) && + !match(amazonPhone$1) && + !match(androidPhone$1) && + (match(amazonTablet$1) || match(androidTablet$1)), + device: (!match(windowsPhone$1) && + (match(amazonPhone$1) || + match(amazonTablet$1) || + match(androidPhone$1) || + match(androidTablet$1))) || + match(/\bokhttp\b/i) + }, + windows: { + phone: match(windowsPhone$1), + tablet: match(windowsTablet$1), + device: match(windowsPhone$1) || match(windowsTablet$1) + }, + other: { + blackberry: match(otherBlackBerry$1), + blackberry10: match(otherBlackBerry10$1), + opera: match(otherOpera$1), + firefox: match(otherFirefox$1), + chrome: match(otherChrome$1), + device: match(otherBlackBerry$1) || + match(otherBlackBerry10$1) || + match(otherOpera$1) || + match(otherFirefox$1) || + match(otherChrome$1) + }, + any: false, + phone: false, + tablet: false + }; + result.any = + result.apple.device || + result.android.device || + result.windows.device || + result.other.device; + result.phone = + result.apple.phone || result.android.phone || result.windows.phone; + result.tablet = + result.apple.tablet || result.android.tablet || result.windows.tablet; + return result; + } + + var isMobile$2 = isMobile$1$1(globalThis.navigator); + + /** + * Uploading the same buffer multiple times in a single frame can cause performance issues. + * Apparent on iOS so only check for that at the moment + * This check may become more complex if this issue pops up elsewhere. + * @private + * @returns {boolean} `true` if the same buffer may be uploaded more than once. + */ + function canUploadSameBuffer$1() { + return !isMobile$2.apple.device; + } + + /** + * The maximum recommended texture units to use. + * In theory the bigger the better, and for desktop we'll use as many as we can. + * But some mobile devices slow down if there is to many branches in the shader. + * So in practice there seems to be a sweet spot size that varies depending on the device. + * + * In v4, all mobile devices were limited to 4 texture units because for this. + * In v5, we allow all texture units to be used on modern Apple or Android devices. + * @private + * @param {number} max + * @returns {number} The maximum recommended texture units to use. + */ + function maxRecommendedTextures$1(max) { + var allowMax = true; + if (isMobile$2.tablet || isMobile$2.phone) { + if (isMobile$2.apple.device) { + var match = (navigator.userAgent).match(/OS (\d+)_(\d+)?/); + if (match) { + var majorVersion = parseInt(match[1], 10); + // Limit texture units on devices below iOS 11, which will be older hardware + if (majorVersion < 11) { + allowMax = false; + } + } + } + if (isMobile$2.android.device) { + var match = (navigator.userAgent).match(/Android\s([0-9.]*)/); + if (match) { + var majorVersion = parseInt(match[1], 10); + // Limit texture units on devices below Android 7 (Nougat), which will be older hardware + if (majorVersion < 7) { + allowMax = false; + } + } + } + } + return allowMax ? max : 4; + } + + /** + * User's customizable globals for overriding the default PIXI settings, such + * as a renderer's default resolution, framerate, float precision, etc. + * @example + * // Use the native window resolution as the default resolution + * // will support high-density displays when rendering + * PIXI.settings.RESOLUTION = window.devicePixelRatio; + * + * // Disable interpolation when scaling, will make texture be pixelated + * PIXI.settings.SCALE_MODE = PIXI.SCALE_MODES.NEAREST; + * @namespace PIXI.settings + */ + var settings$1 = { + /** + * This adapter is used to call methods that are platform dependent. + * For example `document.createElement` only runs on the web but fails in node environments. + * This allows us to support more platforms by abstracting away specific implementations per platform. + * + * By default the adapter is set to work in the browser. However you can create your own + * by implementing the `IAdapter` interface. See `IAdapter` for more information. + * @name ADAPTER + * @memberof PIXI.settings + * @type {PIXI.IAdapter} + * @default PIXI.BrowserAdapter + */ + ADAPTER: BrowserAdapter$1, + /** + * If set to true WebGL will attempt make textures mimpaped by default. + * Mipmapping will only succeed if the base texture uploaded has power of two dimensions. + * @static + * @name MIPMAP_TEXTURES + * @memberof PIXI.settings + * @type {PIXI.MIPMAP_MODES} + * @default PIXI.MIPMAP_MODES.POW2 + */ + MIPMAP_TEXTURES: MIPMAP_MODES$5.POW2, + /** + * Default anisotropic filtering level of textures. + * Usually from 0 to 16 + * @static + * @name ANISOTROPIC_LEVEL + * @memberof PIXI.settings + * @type {number} + * @default 0 + */ + ANISOTROPIC_LEVEL: 0, + /** + * Default resolution / device pixel ratio of the renderer. + * @static + * @name RESOLUTION + * @memberof PIXI.settings + * @type {number} + * @default 1 + */ + RESOLUTION: 1, + /** + * Default filter resolution. + * @static + * @name FILTER_RESOLUTION + * @memberof PIXI.settings + * @type {number} + * @default 1 + */ + FILTER_RESOLUTION: 1, + /** + * Default filter samples. + * @static + * @name FILTER_MULTISAMPLE + * @memberof PIXI.settings + * @type {PIXI.MSAA_QUALITY} + * @default PIXI.MSAA_QUALITY.NONE + */ + FILTER_MULTISAMPLE: MSAA_QUALITY$5.NONE, + /** + * The maximum textures that this device supports. + * @static + * @name SPRITE_MAX_TEXTURES + * @memberof PIXI.settings + * @type {number} + * @default 32 + */ + SPRITE_MAX_TEXTURES: maxRecommendedTextures$1(32), + // TODO: maybe change to SPRITE.BATCH_SIZE: 2000 + // TODO: maybe add PARTICLE.BATCH_SIZE: 15000 + /** + * The default sprite batch size. + * + * The default aims to balance desktop and mobile devices. + * @static + * @name SPRITE_BATCH_SIZE + * @memberof PIXI.settings + * @type {number} + * @default 4096 + */ + SPRITE_BATCH_SIZE: 4096, + /** + * The default render options if none are supplied to {@link PIXI.Renderer} + * or {@link PIXI.CanvasRenderer}. + * @static + * @name RENDER_OPTIONS + * @memberof PIXI.settings + * @type {object} + * @property {HTMLCanvasElement} [view=null] - + * @property {boolean} [antialias=false] - + * @property {boolean} [autoDensity=false] - + * @property {boolean} [useContextAlpha=true] - + * @property {number} [backgroundColor=0x000000] - + * @property {number} [backgroundAlpha=1] - + * @property {boolean} [clearBeforeRender=true] - + * @property {boolean} [preserveDrawingBuffer=false] - + * @property {number} [width=800] - + * @property {number} [height=600] - + * @property {boolean} [legacy=false] - + */ + RENDER_OPTIONS: { + view: null, + antialias: false, + autoDensity: false, + backgroundColor: 0x000000, + backgroundAlpha: 1, + useContextAlpha: true, + clearBeforeRender: true, + preserveDrawingBuffer: false, + width: 800, + height: 600, + legacy: false, + }, + /** + * Default Garbage Collection mode. + * @static + * @name GC_MODE + * @memberof PIXI.settings + * @type {PIXI.GC_MODES} + * @default PIXI.GC_MODES.AUTO + */ + GC_MODE: GC_MODES$5.AUTO, + /** + * Default Garbage Collection max idle. + * @static + * @name GC_MAX_IDLE + * @memberof PIXI.settings + * @type {number} + * @default 3600 + */ + GC_MAX_IDLE: 60 * 60, + /** + * Default Garbage Collection maximum check count. + * @static + * @name GC_MAX_CHECK_COUNT + * @memberof PIXI.settings + * @type {number} + * @default 600 + */ + GC_MAX_CHECK_COUNT: 60 * 10, + /** + * Default wrap modes that are supported by pixi. + * @static + * @name WRAP_MODE + * @memberof PIXI.settings + * @type {PIXI.WRAP_MODES} + * @default PIXI.WRAP_MODES.CLAMP + */ + WRAP_MODE: WRAP_MODES$5.CLAMP, + /** + * Default scale mode for textures. + * @static + * @name SCALE_MODE + * @memberof PIXI.settings + * @type {PIXI.SCALE_MODES} + * @default PIXI.SCALE_MODES.LINEAR + */ + SCALE_MODE: SCALE_MODES$5.LINEAR, + /** + * Default specify float precision in vertex shader. + * @static + * @name PRECISION_VERTEX + * @memberof PIXI.settings + * @type {PIXI.PRECISION} + * @default PIXI.PRECISION.HIGH + */ + PRECISION_VERTEX: PRECISION$5.HIGH, + /** + * Default specify float precision in fragment shader. + * iOS is best set at highp due to https://github.com/pixijs/pixi.js/issues/3742 + * @static + * @name PRECISION_FRAGMENT + * @memberof PIXI.settings + * @type {PIXI.PRECISION} + * @default PIXI.PRECISION.MEDIUM + */ + PRECISION_FRAGMENT: isMobile$2.apple.device ? PRECISION$5.HIGH : PRECISION$5.MEDIUM, + /** + * Can we upload the same buffer in a single frame? + * @static + * @name CAN_UPLOAD_SAME_BUFFER + * @memberof PIXI.settings + * @type {boolean} + */ + CAN_UPLOAD_SAME_BUFFER: canUploadSameBuffer$1(), + /** + * Enables bitmap creation before image load. This feature is experimental. + * @static + * @name CREATE_IMAGE_BITMAP + * @memberof PIXI.settings + * @type {boolean} + * @default false + */ + CREATE_IMAGE_BITMAP: false, + /** + * If true PixiJS will Math.floor() x/y values when rendering, stopping pixel interpolation. + * Advantages can include sharper image quality (like text) and faster rendering on canvas. + * The main disadvantage is movement of objects may appear less smooth. + * @static + * @constant + * @memberof PIXI.settings + * @type {boolean} + * @default false + */ + ROUND_PIXELS: false, + }; + + var commonjsGlobal$1 = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; + + function getDefaultExportFromCjs (x) { + return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; + } + + function createCommonjsModule$1(fn, basedir, module) { + return module = { + path: basedir, + exports: {}, + require: function (path, base) { + return commonjsRequire$1(path, (base === undefined || base === null) ? module.path : base); + } + }, fn(module, module.exports), module.exports; + } + + function getDefaultExportFromNamespaceIfPresent (n) { + return n && Object.prototype.hasOwnProperty.call(n, 'default') ? n['default'] : n; + } + + function getDefaultExportFromNamespaceIfNotNamed (n) { + return n && Object.prototype.hasOwnProperty.call(n, 'default') && Object.keys(n).length === 1 ? n['default'] : n; + } + + function getAugmentedNamespace(n) { + if (n.__esModule) return n; + var a = Object.defineProperty({}, '__esModule', {value: true}); + Object.keys(n).forEach(function (k) { + var d = Object.getOwnPropertyDescriptor(n, k); + Object.defineProperty(a, k, d.get ? d : { + enumerable: true, + get: function () { + return n[k]; + } + }); + }); + return a; + } + + function commonjsRequire$1 () { + throw new Error('Dynamic requires are not currently supported by @rollup/plugin-commonjs'); + } + + var eventemitter3 = createCommonjsModule$1(function (module) { + 'use strict'; + + var has = Object.prototype.hasOwnProperty + , prefix = '~'; + + /** + * Constructor to create a storage for our `EE` objects. + * An `Events` instance is a plain object whose properties are event names. + * + * @constructor + * @private + */ + function Events() {} + + // + // We try to not inherit from `Object.prototype`. In some engines creating an + // instance in this way is faster than calling `Object.create(null)` directly. + // If `Object.create(null)` is not supported we prefix the event names with a + // character to make sure that the built-in object properties are not + // overridden or used as an attack vector. + // + if (Object.create) { + Events.prototype = Object.create(null); + + // + // This hack is needed because the `__proto__` property is still inherited in + // some old browsers like Android 4, iPhone 5.1, Opera 11 and Safari 5. + // + if (!new Events().__proto__) { prefix = false; } + } + + /** + * Representation of a single event listener. + * + * @param {Function} fn The listener function. + * @param {*} context The context to invoke the listener with. + * @param {Boolean} [once=false] Specify if the listener is a one-time listener. + * @constructor + * @private + */ + function EE(fn, context, once) { + this.fn = fn; + this.context = context; + this.once = once || false; + } + + /** + * Add a listener for a given event. + * + * @param {EventEmitter} emitter Reference to the `EventEmitter` instance. + * @param {(String|Symbol)} event The event name. + * @param {Function} fn The listener function. + * @param {*} context The context to invoke the listener with. + * @param {Boolean} once Specify if the listener is a one-time listener. + * @returns {EventEmitter} + * @private + */ + function addListener(emitter, event, fn, context, once) { + if (typeof fn !== 'function') { + throw new TypeError('The listener must be a function'); + } + + var listener = new EE(fn, context || emitter, once) + , evt = prefix ? prefix + event : event; + + if (!emitter._events[evt]) { emitter._events[evt] = listener, emitter._eventsCount++; } + else if (!emitter._events[evt].fn) { emitter._events[evt].push(listener); } + else { emitter._events[evt] = [emitter._events[evt], listener]; } + + return emitter; + } + + /** + * Clear event by name. + * + * @param {EventEmitter} emitter Reference to the `EventEmitter` instance. + * @param {(String|Symbol)} evt The Event name. + * @private + */ + function clearEvent(emitter, evt) { + if (--emitter._eventsCount === 0) { emitter._events = new Events(); } + else { delete emitter._events[evt]; } + } + + /** + * Minimal `EventEmitter` interface that is molded against the Node.js + * `EventEmitter` interface. + * + * @constructor + * @public + */ + function EventEmitter() { + this._events = new Events(); + this._eventsCount = 0; + } + + /** + * Return an array listing the events for which the emitter has registered + * listeners. + * + * @returns {Array} + * @public + */ + EventEmitter.prototype.eventNames = function eventNames() { + var names = [] + , events + , name; + + if (this._eventsCount === 0) { return names; } + + for (name in (events = this._events)) { + if (has.call(events, name)) { names.push(prefix ? name.slice(1) : name); } + } + + if (Object.getOwnPropertySymbols) { + return names.concat(Object.getOwnPropertySymbols(events)); + } + + return names; + }; + + /** + * Return the listeners registered for a given event. + * + * @param {(String|Symbol)} event The event name. + * @returns {Array} The registered listeners. + * @public + */ + EventEmitter.prototype.listeners = function listeners(event) { + var evt = prefix ? prefix + event : event + , handlers = this._events[evt]; + + if (!handlers) { return []; } + if (handlers.fn) { return [handlers.fn]; } + + for (var i = 0, l = handlers.length, ee = new Array(l); i < l; i++) { + ee[i] = handlers[i].fn; + } + + return ee; + }; + + /** + * Return the number of listeners listening to a given event. + * + * @param {(String|Symbol)} event The event name. + * @returns {Number} The number of listeners. + * @public + */ + EventEmitter.prototype.listenerCount = function listenerCount(event) { + var evt = prefix ? prefix + event : event + , listeners = this._events[evt]; + + if (!listeners) { return 0; } + if (listeners.fn) { return 1; } + return listeners.length; + }; + + /** + * Calls each of the listeners registered for a given event. + * + * @param {(String|Symbol)} event The event name. + * @returns {Boolean} `true` if the event had listeners, else `false`. + * @public + */ + EventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) { + var arguments$1 = arguments; + + var evt = prefix ? prefix + event : event; + + if (!this._events[evt]) { return false; } + + var listeners = this._events[evt] + , len = arguments.length + , args + , i; + + if (listeners.fn) { + if (listeners.once) { this.removeListener(event, listeners.fn, undefined, true); } + + switch (len) { + case 1: return listeners.fn.call(listeners.context), true; + case 2: return listeners.fn.call(listeners.context, a1), true; + case 3: return listeners.fn.call(listeners.context, a1, a2), true; + case 4: return listeners.fn.call(listeners.context, a1, a2, a3), true; + case 5: return listeners.fn.call(listeners.context, a1, a2, a3, a4), true; + case 6: return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true; + } + + for (i = 1, args = new Array(len -1); i < len; i++) { + args[i - 1] = arguments$1[i]; + } + + listeners.fn.apply(listeners.context, args); + } else { + var length = listeners.length + , j; + + for (i = 0; i < length; i++) { + if (listeners[i].once) { this.removeListener(event, listeners[i].fn, undefined, true); } + + switch (len) { + case 1: listeners[i].fn.call(listeners[i].context); break; + case 2: listeners[i].fn.call(listeners[i].context, a1); break; + case 3: listeners[i].fn.call(listeners[i].context, a1, a2); break; + case 4: listeners[i].fn.call(listeners[i].context, a1, a2, a3); break; + default: + if (!args) { for (j = 1, args = new Array(len -1); j < len; j++) { + args[j - 1] = arguments$1[j]; + } } + + listeners[i].fn.apply(listeners[i].context, args); + } + } + } + + return true; + }; + + /** + * Add a listener for a given event. + * + * @param {(String|Symbol)} event The event name. + * @param {Function} fn The listener function. + * @param {*} [context=this] The context to invoke the listener with. + * @returns {EventEmitter} `this`. + * @public + */ + EventEmitter.prototype.on = function on(event, fn, context) { + return addListener(this, event, fn, context, false); + }; + + /** + * Add a one-time listener for a given event. + * + * @param {(String|Symbol)} event The event name. + * @param {Function} fn The listener function. + * @param {*} [context=this] The context to invoke the listener with. + * @returns {EventEmitter} `this`. + * @public + */ + EventEmitter.prototype.once = function once(event, fn, context) { + return addListener(this, event, fn, context, true); + }; + + /** + * Remove the listeners of a given event. + * + * @param {(String|Symbol)} event The event name. + * @param {Function} fn Only remove the listeners that match this function. + * @param {*} context Only remove the listeners that have this context. + * @param {Boolean} once Only remove one-time listeners. + * @returns {EventEmitter} `this`. + * @public + */ + EventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) { + var evt = prefix ? prefix + event : event; + + if (!this._events[evt]) { return this; } + if (!fn) { + clearEvent(this, evt); + return this; + } + + var listeners = this._events[evt]; + + if (listeners.fn) { + if ( + listeners.fn === fn && + (!once || listeners.once) && + (!context || listeners.context === context) + ) { + clearEvent(this, evt); + } + } else { + for (var i = 0, events = [], length = listeners.length; i < length; i++) { + if ( + listeners[i].fn !== fn || + (once && !listeners[i].once) || + (context && listeners[i].context !== context) + ) { + events.push(listeners[i]); + } + } + + // + // Reset the array, or remove it completely if we have no more listeners. + // + if (events.length) { this._events[evt] = events.length === 1 ? events[0] : events; } + else { clearEvent(this, evt); } + } + + return this; + }; + + /** + * Remove all listeners, or those of the specified event. + * + * @param {(String|Symbol)} [event] The event name. + * @returns {EventEmitter} `this`. + * @public + */ + EventEmitter.prototype.removeAllListeners = function removeAllListeners(event) { + var evt; + + if (event) { + evt = prefix ? prefix + event : event; + if (this._events[evt]) { clearEvent(this, evt); } + } else { + this._events = new Events(); + this._eventsCount = 0; + } + + return this; + }; + + // + // Alias methods names because people roll like that. + // + EventEmitter.prototype.off = EventEmitter.prototype.removeListener; + EventEmitter.prototype.addListener = EventEmitter.prototype.on; + + // + // Expose the prefix. + // + EventEmitter.prefixed = prefix; + + // + // Allow `EventEmitter` to be imported as module namespace. + // + EventEmitter.EventEmitter = EventEmitter; + + // + // Expose the module. + // + if ('undefined' !== 'object') { + module.exports = EventEmitter; + } + }); + + 'use strict'; + + var earcut_1 = earcut; + var _default = earcut; + + function earcut(data, holeIndices, dim) { + + dim = dim || 2; + + var hasHoles = holeIndices && holeIndices.length, + outerLen = hasHoles ? holeIndices[0] * dim : data.length, + outerNode = linkedList(data, 0, outerLen, dim, true), + triangles = []; + + if (!outerNode || outerNode.next === outerNode.prev) { return triangles; } + + var minX, minY, maxX, maxY, x, y, invSize; + + if (hasHoles) { outerNode = eliminateHoles(data, holeIndices, outerNode, dim); } + + // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox + if (data.length > 80 * dim) { + minX = maxX = data[0]; + minY = maxY = data[1]; + + for (var i = dim; i < outerLen; i += dim) { + x = data[i]; + y = data[i + 1]; + if (x < minX) { minX = x; } + if (y < minY) { minY = y; } + if (x > maxX) { maxX = x; } + if (y > maxY) { maxY = y; } + } + + // minX, minY and invSize are later used to transform coords into integers for z-order calculation + invSize = Math.max(maxX - minX, maxY - minY); + invSize = invSize !== 0 ? 32767 / invSize : 0; + } + + earcutLinked(outerNode, triangles, dim, minX, minY, invSize, 0); + + return triangles; + } + + // create a circular doubly linked list from polygon points in the specified winding order + function linkedList(data, start, end, dim, clockwise) { + var i, last; + + if (clockwise === (signedArea(data, start, end, dim) > 0)) { + for (i = start; i < end; i += dim) { last = insertNode(i, data[i], data[i + 1], last); } + } else { + for (i = end - dim; i >= start; i -= dim) { last = insertNode(i, data[i], data[i + 1], last); } + } + + if (last && equals(last, last.next)) { + removeNode(last); + last = last.next; + } + + return last; + } + + // eliminate colinear or duplicate points + function filterPoints(start, end) { + if (!start) { return start; } + if (!end) { end = start; } + + var p = start, + again; + do { + again = false; + + if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) { + removeNode(p); + p = end = p.prev; + if (p === p.next) { break; } + again = true; + + } else { + p = p.next; + } + } while (again || p !== end); + + return end; + } + + // main ear slicing loop which triangulates a polygon (given as a linked list) + function earcutLinked(ear, triangles, dim, minX, minY, invSize, pass) { + if (!ear) { return; } + + // interlink polygon nodes in z-order + if (!pass && invSize) { indexCurve(ear, minX, minY, invSize); } + + var stop = ear, + prev, next; + + // iterate through ears, slicing them one by one + while (ear.prev !== ear.next) { + prev = ear.prev; + next = ear.next; + + if (invSize ? isEarHashed(ear, minX, minY, invSize) : isEar(ear)) { + // cut off the triangle + triangles.push(prev.i / dim | 0); + triangles.push(ear.i / dim | 0); + triangles.push(next.i / dim | 0); + + removeNode(ear); + + // skipping the next vertex leads to less sliver triangles + ear = next.next; + stop = next.next; + + continue; + } + + ear = next; + + // if we looped through the whole remaining polygon and can't find any more ears + if (ear === stop) { + // try filtering points and slicing again + if (!pass) { + earcutLinked(filterPoints(ear), triangles, dim, minX, minY, invSize, 1); + + // if this didn't work, try curing all small self-intersections locally + } else if (pass === 1) { + ear = cureLocalIntersections(filterPoints(ear), triangles, dim); + earcutLinked(ear, triangles, dim, minX, minY, invSize, 2); + + // as a last resort, try splitting the remaining polygon into two + } else if (pass === 2) { + splitEarcut(ear, triangles, dim, minX, minY, invSize); + } + + break; + } + } + } + + // check whether a polygon node forms a valid ear with adjacent nodes + function isEar(ear) { + var a = ear.prev, + b = ear, + c = ear.next; + + if (area(a, b, c) >= 0) { return false; } // reflex, can't be an ear + + // now make sure we don't have other points inside the potential ear + var ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y; + + // triangle bbox; min & max are calculated like this for speed + var x0 = ax < bx ? (ax < cx ? ax : cx) : (bx < cx ? bx : cx), + y0 = ay < by ? (ay < cy ? ay : cy) : (by < cy ? by : cy), + x1 = ax > bx ? (ax > cx ? ax : cx) : (bx > cx ? bx : cx), + y1 = ay > by ? (ay > cy ? ay : cy) : (by > cy ? by : cy); + + var p = c.next; + while (p !== a) { + if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && + pointInTriangle(ax, ay, bx, by, cx, cy, p.x, p.y) && + area(p.prev, p, p.next) >= 0) { return false; } + p = p.next; + } + + return true; + } + + function isEarHashed(ear, minX, minY, invSize) { + var a = ear.prev, + b = ear, + c = ear.next; + + if (area(a, b, c) >= 0) { return false; } // reflex, can't be an ear + + var ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y; + + // triangle bbox; min & max are calculated like this for speed + var x0 = ax < bx ? (ax < cx ? ax : cx) : (bx < cx ? bx : cx), + y0 = ay < by ? (ay < cy ? ay : cy) : (by < cy ? by : cy), + x1 = ax > bx ? (ax > cx ? ax : cx) : (bx > cx ? bx : cx), + y1 = ay > by ? (ay > cy ? ay : cy) : (by > cy ? by : cy); + + // z-order range for the current triangle bbox; + var minZ = zOrder(x0, y0, minX, minY, invSize), + maxZ = zOrder(x1, y1, minX, minY, invSize); + + var p = ear.prevZ, + n = ear.nextZ; + + // look for points inside the triangle in both directions + while (p && p.z >= minZ && n && n.z <= maxZ) { + if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c && + pointInTriangle(ax, ay, bx, by, cx, cy, p.x, p.y) && area(p.prev, p, p.next) >= 0) { return false; } + p = p.prevZ; + + if (n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c && + pointInTriangle(ax, ay, bx, by, cx, cy, n.x, n.y) && area(n.prev, n, n.next) >= 0) { return false; } + n = n.nextZ; + } + + // look for remaining points in decreasing z-order + while (p && p.z >= minZ) { + if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c && + pointInTriangle(ax, ay, bx, by, cx, cy, p.x, p.y) && area(p.prev, p, p.next) >= 0) { return false; } + p = p.prevZ; + } + + // look for remaining points in increasing z-order + while (n && n.z <= maxZ) { + if (n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c && + pointInTriangle(ax, ay, bx, by, cx, cy, n.x, n.y) && area(n.prev, n, n.next) >= 0) { return false; } + n = n.nextZ; + } + + return true; + } + + // go through all polygon nodes and cure small local self-intersections + function cureLocalIntersections(start, triangles, dim) { + var p = start; + do { + var a = p.prev, + b = p.next.next; + + if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) { + + triangles.push(a.i / dim | 0); + triangles.push(p.i / dim | 0); + triangles.push(b.i / dim | 0); + + // remove two nodes involved + removeNode(p); + removeNode(p.next); + + p = start = b; + } + p = p.next; + } while (p !== start); + + return filterPoints(p); + } + + // try splitting polygon into two and triangulate them independently + function splitEarcut(start, triangles, dim, minX, minY, invSize) { + // look for a valid diagonal that divides the polygon into two + var a = start; + do { + var b = a.next.next; + while (b !== a.prev) { + if (a.i !== b.i && isValidDiagonal(a, b)) { + // split the polygon in two by the diagonal + var c = splitPolygon(a, b); + + // filter colinear points around the cuts + a = filterPoints(a, a.next); + c = filterPoints(c, c.next); + + // run earcut on each half + earcutLinked(a, triangles, dim, minX, minY, invSize, 0); + earcutLinked(c, triangles, dim, minX, minY, invSize, 0); + return; + } + b = b.next; + } + a = a.next; + } while (a !== start); + } + + // link every hole into the outer loop, producing a single-ring polygon without holes + function eliminateHoles(data, holeIndices, outerNode, dim) { + var queue = [], + i, len, start, end, list; + + for (i = 0, len = holeIndices.length; i < len; i++) { + start = holeIndices[i] * dim; + end = i < len - 1 ? holeIndices[i + 1] * dim : data.length; + list = linkedList(data, start, end, dim, false); + if (list === list.next) { list.steiner = true; } + queue.push(getLeftmost(list)); + } + + queue.sort(compareX); + + // process holes from left to right + for (i = 0; i < queue.length; i++) { + outerNode = eliminateHole(queue[i], outerNode); + } + + return outerNode; + } + + function compareX(a, b) { + return a.x - b.x; + } + + // find a bridge between vertices that connects hole with an outer ring and and link it + function eliminateHole(hole, outerNode) { + var bridge = findHoleBridge(hole, outerNode); + if (!bridge) { + return outerNode; + } + + var bridgeReverse = splitPolygon(bridge, hole); + + // filter collinear points around the cuts + filterPoints(bridgeReverse, bridgeReverse.next); + return filterPoints(bridge, bridge.next); + } + + // David Eberly's algorithm for finding a bridge between hole and outer polygon + function findHoleBridge(hole, outerNode) { + var p = outerNode, + hx = hole.x, + hy = hole.y, + qx = -Infinity, + m; + + // find a segment intersected by a ray from the hole's leftmost point to the left; + // segment's endpoint with lesser x will be potential connection point + do { + if (hy <= p.y && hy >= p.next.y && p.next.y !== p.y) { + var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y); + if (x <= hx && x > qx) { + qx = x; + m = p.x < p.next.x ? p : p.next; + if (x === hx) { return m; } // hole touches outer segment; pick leftmost endpoint + } + } + p = p.next; + } while (p !== outerNode); + + if (!m) { return null; } + + // look for points inside the triangle of hole point, segment intersection and endpoint; + // if there are no points found, we have a valid connection; + // otherwise choose the point of the minimum angle with the ray as connection point + + var stop = m, + mx = m.x, + my = m.y, + tanMin = Infinity, + tan; + + p = m; + + do { + if (hx >= p.x && p.x >= mx && hx !== p.x && + pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) { + + tan = Math.abs(hy - p.y) / (hx - p.x); // tangential + + if (locallyInside(p, hole) && + (tan < tanMin || (tan === tanMin && (p.x > m.x || (p.x === m.x && sectorContainsSector(m, p)))))) { + m = p; + tanMin = tan; + } + } + + p = p.next; + } while (p !== stop); + + return m; + } + + // whether sector in vertex m contains sector in vertex p in the same coordinates + function sectorContainsSector(m, p) { + return area(m.prev, m, p.prev) < 0 && area(p.next, m, m.next) < 0; + } + + // interlink polygon nodes in z-order + function indexCurve(start, minX, minY, invSize) { + var p = start; + do { + if (p.z === 0) { p.z = zOrder(p.x, p.y, minX, minY, invSize); } + p.prevZ = p.prev; + p.nextZ = p.next; + p = p.next; + } while (p !== start); + + p.prevZ.nextZ = null; + p.prevZ = null; + + sortLinked(p); + } + + // Simon Tatham's linked list merge sort algorithm + // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html + function sortLinked(list) { + var i, p, q, e, tail, numMerges, pSize, qSize, + inSize = 1; + + do { + p = list; + list = null; + tail = null; + numMerges = 0; + + while (p) { + numMerges++; + q = p; + pSize = 0; + for (i = 0; i < inSize; i++) { + pSize++; + q = q.nextZ; + if (!q) { break; } + } + qSize = inSize; + + while (pSize > 0 || (qSize > 0 && q)) { + + if (pSize !== 0 && (qSize === 0 || !q || p.z <= q.z)) { + e = p; + p = p.nextZ; + pSize--; + } else { + e = q; + q = q.nextZ; + qSize--; + } + + if (tail) { tail.nextZ = e; } + else { list = e; } + + e.prevZ = tail; + tail = e; + } + + p = q; + } + + tail.nextZ = null; + inSize *= 2; + + } while (numMerges > 1); + + return list; + } + + // z-order of a point given coords and inverse of the longer side of data bbox + function zOrder(x, y, minX, minY, invSize) { + // coords are transformed into non-negative 15-bit integer range + x = (x - minX) * invSize | 0; + y = (y - minY) * invSize | 0; + + x = (x | (x << 8)) & 0x00FF00FF; + x = (x | (x << 4)) & 0x0F0F0F0F; + x = (x | (x << 2)) & 0x33333333; + x = (x | (x << 1)) & 0x55555555; + + y = (y | (y << 8)) & 0x00FF00FF; + y = (y | (y << 4)) & 0x0F0F0F0F; + y = (y | (y << 2)) & 0x33333333; + y = (y | (y << 1)) & 0x55555555; + + return x | (y << 1); + } + + // find the leftmost node of a polygon ring + function getLeftmost(start) { + var p = start, + leftmost = start; + do { + if (p.x < leftmost.x || (p.x === leftmost.x && p.y < leftmost.y)) { leftmost = p; } + p = p.next; + } while (p !== start); + + return leftmost; + } + + // check if a point lies within a convex triangle + function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) { + return (cx - px) * (ay - py) >= (ax - px) * (cy - py) && + (ax - px) * (by - py) >= (bx - px) * (ay - py) && + (bx - px) * (cy - py) >= (cx - px) * (by - py); + } + + // check if a diagonal between two polygon nodes is valid (lies in polygon interior) + function isValidDiagonal(a, b) { + return a.next.i !== b.i && a.prev.i !== b.i && !intersectsPolygon(a, b) && // dones't intersect other edges + (locallyInside(a, b) && locallyInside(b, a) && middleInside(a, b) && // locally visible + (area(a.prev, a, b.prev) || area(a, b.prev, b)) || // does not create opposite-facing sectors + equals(a, b) && area(a.prev, a, a.next) > 0 && area(b.prev, b, b.next) > 0); // special zero-length case + } + + // signed area of a triangle + function area(p, q, r) { + return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y); + } + + // check if two points are equal + function equals(p1, p2) { + return p1.x === p2.x && p1.y === p2.y; + } + + // check if two segments intersect + function intersects(p1, q1, p2, q2) { + var o1 = sign$1(area(p1, q1, p2)); + var o2 = sign$1(area(p1, q1, q2)); + var o3 = sign$1(area(p2, q2, p1)); + var o4 = sign$1(area(p2, q2, q1)); + + if (o1 !== o2 && o3 !== o4) { return true; } // general case + + if (o1 === 0 && onSegment(p1, p2, q1)) { return true; } // p1, q1 and p2 are collinear and p2 lies on p1q1 + if (o2 === 0 && onSegment(p1, q2, q1)) { return true; } // p1, q1 and q2 are collinear and q2 lies on p1q1 + if (o3 === 0 && onSegment(p2, p1, q2)) { return true; } // p2, q2 and p1 are collinear and p1 lies on p2q2 + if (o4 === 0 && onSegment(p2, q1, q2)) { return true; } // p2, q2 and q1 are collinear and q1 lies on p2q2 + + return false; + } + + // for collinear points p, q, r, check if point q lies on segment pr + function onSegment(p, q, r) { + return q.x <= Math.max(p.x, r.x) && q.x >= Math.min(p.x, r.x) && q.y <= Math.max(p.y, r.y) && q.y >= Math.min(p.y, r.y); + } + + function sign$1(num) { + return num > 0 ? 1 : num < 0 ? -1 : 0; + } + + // check if a polygon diagonal intersects any polygon segments + function intersectsPolygon(a, b) { + var p = a; + do { + if (p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i && + intersects(p, p.next, a, b)) { return true; } + p = p.next; + } while (p !== a); + + return false; + } + + // check if a polygon diagonal is locally inside the polygon + function locallyInside(a, b) { + return area(a.prev, a, a.next) < 0 ? + area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0 : + area(a, b, a.prev) < 0 || area(a, a.next, b) < 0; + } + + // check if the middle point of a polygon diagonal is inside the polygon + function middleInside(a, b) { + var p = a, + inside = false, + px = (a.x + b.x) / 2, + py = (a.y + b.y) / 2; + do { + if (((p.y > py) !== (p.next.y > py)) && p.next.y !== p.y && + (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x)) + { inside = !inside; } + p = p.next; + } while (p !== a); + + return inside; + } + + // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two; + // if one belongs to the outer ring and another to a hole, it merges it into a single ring + function splitPolygon(a, b) { + var a2 = new Node(a.i, a.x, a.y), + b2 = new Node(b.i, b.x, b.y), + an = a.next, + bp = b.prev; + + a.next = b; + b.prev = a; + + a2.next = an; + an.prev = a2; + + b2.next = a2; + a2.prev = b2; + + bp.next = b2; + b2.prev = bp; + + return b2; + } + + // create a node and optionally link it with previous one (in a circular doubly linked list) + function insertNode(i, x, y, last) { + var p = new Node(i, x, y); + + if (!last) { + p.prev = p; + p.next = p; + + } else { + p.next = last.next; + p.prev = last; + last.next.prev = p; + last.next = p; + } + return p; + } + + function removeNode(p) { + p.next.prev = p.prev; + p.prev.next = p.next; + + if (p.prevZ) { p.prevZ.nextZ = p.nextZ; } + if (p.nextZ) { p.nextZ.prevZ = p.prevZ; } + } + + function Node(i, x, y) { + // vertex index in coordinates array + this.i = i; + + // vertex coordinates + this.x = x; + this.y = y; + + // previous and next vertex nodes in a polygon ring + this.prev = null; + this.next = null; + + // z-order curve value + this.z = 0; + + // previous and next nodes in z-order + this.prevZ = null; + this.nextZ = null; + + // indicates whether this is a steiner point + this.steiner = false; + } + + // return a percentage difference between the polygon area and its triangulation area; + // used to verify correctness of triangulation + earcut.deviation = function (data, holeIndices, dim, triangles) { + var hasHoles = holeIndices && holeIndices.length; + var outerLen = hasHoles ? holeIndices[0] * dim : data.length; + + var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim)); + if (hasHoles) { + for (var i = 0, len = holeIndices.length; i < len; i++) { + var start = holeIndices[i] * dim; + var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length; + polygonArea -= Math.abs(signedArea(data, start, end, dim)); + } + } + + var trianglesArea = 0; + for (i = 0; i < triangles.length; i += 3) { + var a = triangles[i] * dim; + var b = triangles[i + 1] * dim; + var c = triangles[i + 2] * dim; + trianglesArea += Math.abs( + (data[a] - data[c]) * (data[b + 1] - data[a + 1]) - + (data[a] - data[b]) * (data[c + 1] - data[a + 1])); + } + + return polygonArea === 0 && trianglesArea === 0 ? 0 : + Math.abs((trianglesArea - polygonArea) / polygonArea); + }; + + function signedArea(data, start, end, dim) { + var sum = 0; + for (var i = start, j = end - dim; i < end; i += dim) { + sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]); + j = i; + } + return sum; + } + + // turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts + earcut.flatten = function (data) { + var dim = data[0][0].length, + result = {vertices: [], holes: [], dimensions: dim}, + holeIndex = 0; + + for (var i = 0; i < data.length; i++) { + for (var j = 0; j < data[i].length; j++) { + for (var d = 0; d < dim; d++) { result.vertices.push(data[i][j][d]); } + } + if (i > 0) { + holeIndex += data[i - 1].length; + result.holes.push(holeIndex); + } + } + return result; + }; + earcut_1.default = _default; + + var punycode = createCommonjsModule$1(function (module, exports) { + /*! https://mths.be/punycode v1.3.2 by @mathias */ + ;(function(root) { + + /** Detect free variables */ + var freeExports = 'object' == 'object' && exports && + !exports.nodeType && exports; + var freeModule = 'object' == 'object' && module && + !module.nodeType && module; + var freeGlobal = typeof commonjsGlobal$1 == 'object' && commonjsGlobal$1; + if ( + freeGlobal.global === freeGlobal || + freeGlobal.window === freeGlobal || + freeGlobal.self === freeGlobal + ) { + root = freeGlobal; + } + + /** + * The `punycode` object. + * @name punycode + * @type Object + */ + var punycode, + + /** Highest positive signed 32-bit float value */ + maxInt = 2147483647, // aka. 0x7FFFFFFF or 2^31-1 + + /** Bootstring parameters */ + base = 36, + tMin = 1, + tMax = 26, + skew = 38, + damp = 700, + initialBias = 72, + initialN = 128, // 0x80 + delimiter = '-', // '\x2D' + + /** Regular expressions */ + regexPunycode = /^xn--/, + regexNonASCII = /[^\x20-\x7E]/, // unprintable ASCII chars + non-ASCII chars + regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g, // RFC 3490 separators + + /** Error messages */ + errors = { + 'overflow': 'Overflow: input needs wider integers to process', + 'not-basic': 'Illegal input >= 0x80 (not a basic code point)', + 'invalid-input': 'Invalid input' + }, + + /** Convenience shortcuts */ + baseMinusTMin = base - tMin, + floor = Math.floor, + stringFromCharCode = String.fromCharCode, + + /** Temporary variable */ + key; + + /*--------------------------------------------------------------------------*/ + + /** + * A generic error utility function. + * @private + * @param {String} type The error type. + * @returns {Error} Throws a `RangeError` with the applicable error message. + */ + function error(type) { + throw RangeError(errors[type]); + } + + /** + * A generic `Array#map` utility function. + * @private + * @param {Array} array The array to iterate over. + * @param {Function} callback The function that gets called for every array + * item. + * @returns {Array} A new array of values returned by the callback function. + */ + function map(array, fn) { + var length = array.length; + var result = []; + while (length--) { + result[length] = fn(array[length]); + } + return result; + } + + /** + * A simple `Array#map`-like wrapper to work with domain name strings or email + * addresses. + * @private + * @param {String} domain The domain name or email address. + * @param {Function} callback The function that gets called for every + * character. + * @returns {Array} A new string of characters returned by the callback + * function. + */ + function mapDomain(string, fn) { + var parts = string.split('@'); + var result = ''; + if (parts.length > 1) { + // In email addresses, only the domain name should be punycoded. Leave + // the local part (i.e. everything up to `@`) intact. + result = parts[0] + '@'; + string = parts[1]; + } + // Avoid `split(regex)` for IE8 compatibility. See #17. + string = string.replace(regexSeparators, '\x2E'); + var labels = string.split('.'); + var encoded = map(labels, fn).join('.'); + return result + encoded; + } + + /** + * Creates an array containing the numeric code points of each Unicode + * character in the string. While JavaScript uses UCS-2 internally, + * this function will convert a pair of surrogate halves (each of which + * UCS-2 exposes as separate characters) into a single code point, + * matching UTF-16. + * @see `punycode.ucs2.encode` + * @see + * @memberOf punycode.ucs2 + * @name decode + * @param {String} string The Unicode input string (UCS-2). + * @returns {Array} The new array of code points. + */ + function ucs2decode(string) { + var output = [], + counter = 0, + length = string.length, + value, + extra; + while (counter < length) { + value = string.charCodeAt(counter++); + if (value >= 0xD800 && value <= 0xDBFF && counter < length) { + // high surrogate, and there is a next character + extra = string.charCodeAt(counter++); + if ((extra & 0xFC00) == 0xDC00) { // low surrogate + output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000); + } else { + // unmatched surrogate; only append this code unit, in case the next + // code unit is the high surrogate of a surrogate pair + output.push(value); + counter--; + } + } else { + output.push(value); + } + } + return output; + } + + /** + * Creates a string based on an array of numeric code points. + * @see `punycode.ucs2.decode` + * @memberOf punycode.ucs2 + * @name encode + * @param {Array} codePoints The array of numeric code points. + * @returns {String} The new Unicode string (UCS-2). + */ + function ucs2encode(array) { + return map(array, function(value) { + var output = ''; + if (value > 0xFFFF) { + value -= 0x10000; + output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800); + value = 0xDC00 | value & 0x3FF; + } + output += stringFromCharCode(value); + return output; + }).join(''); + } + + /** + * Converts a basic code point into a digit/integer. + * @see `digitToBasic()` + * @private + * @param {Number} codePoint The basic numeric code point value. + * @returns {Number} The numeric value of a basic code point (for use in + * representing integers) in the range `0` to `base - 1`, or `base` if + * the code point does not represent a value. + */ + function basicToDigit(codePoint) { + if (codePoint - 48 < 10) { + return codePoint - 22; + } + if (codePoint - 65 < 26) { + return codePoint - 65; + } + if (codePoint - 97 < 26) { + return codePoint - 97; + } + return base; + } + + /** + * Converts a digit/integer into a basic code point. + * @see `basicToDigit()` + * @private + * @param {Number} digit The numeric value of a basic code point. + * @returns {Number} The basic code point whose value (when used for + * representing integers) is `digit`, which needs to be in the range + * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is + * used; else, the lowercase form is used. The behavior is undefined + * if `flag` is non-zero and `digit` has no uppercase form. + */ + function digitToBasic(digit, flag) { + // 0..25 map to ASCII a..z or A..Z + // 26..35 map to ASCII 0..9 + return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5); + } + + /** + * Bias adaptation function as per section 3.4 of RFC 3492. + * http://tools.ietf.org/html/rfc3492#section-3.4 + * @private + */ + function adapt(delta, numPoints, firstTime) { + var k = 0; + delta = firstTime ? floor(delta / damp) : delta >> 1; + delta += floor(delta / numPoints); + for (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) { + delta = floor(delta / baseMinusTMin); + } + return floor(k + (baseMinusTMin + 1) * delta / (delta + skew)); + } + + /** + * Converts a Punycode string of ASCII-only symbols to a string of Unicode + * symbols. + * @memberOf punycode + * @param {String} input The Punycode string of ASCII-only symbols. + * @returns {String} The resulting string of Unicode symbols. + */ + function decode(input) { + // Don't use UCS-2 + var output = [], + inputLength = input.length, + out, + i = 0, + n = initialN, + bias = initialBias, + basic, + j, + index, + oldi, + w, + k, + digit, + t, + /** Cached calculation results */ + baseMinusT; + + // Handle the basic code points: let `basic` be the number of input code + // points before the last delimiter, or `0` if there is none, then copy + // the first basic code points to the output. + + basic = input.lastIndexOf(delimiter); + if (basic < 0) { + basic = 0; + } + + for (j = 0; j < basic; ++j) { + // if it's not a basic code point + if (input.charCodeAt(j) >= 0x80) { + error('not-basic'); + } + output.push(input.charCodeAt(j)); + } + + // Main decoding loop: start just after the last delimiter if any basic code + // points were copied; start at the beginning otherwise. + + for (index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) { + + // `index` is the index of the next character to be consumed. + // Decode a generalized variable-length integer into `delta`, + // which gets added to `i`. The overflow checking is easier + // if we increase `i` as we go, then subtract off its starting + // value at the end to obtain `delta`. + for (oldi = i, w = 1, k = base; /* no condition */; k += base) { + + if (index >= inputLength) { + error('invalid-input'); + } + + digit = basicToDigit(input.charCodeAt(index++)); + + if (digit >= base || digit > floor((maxInt - i) / w)) { + error('overflow'); + } + + i += digit * w; + t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); + + if (digit < t) { + break; + } + + baseMinusT = base - t; + if (w > floor(maxInt / baseMinusT)) { + error('overflow'); + } + + w *= baseMinusT; + + } + + out = output.length + 1; + bias = adapt(i - oldi, out, oldi == 0); + + // `i` was supposed to wrap around from `out` to `0`, + // incrementing `n` each time, so we'll fix that now: + if (floor(i / out) > maxInt - n) { + error('overflow'); + } + + n += floor(i / out); + i %= out; + + // Insert `n` at position `i` of the output + output.splice(i++, 0, n); + + } + + return ucs2encode(output); + } + + /** + * Converts a string of Unicode symbols (e.g. a domain name label) to a + * Punycode string of ASCII-only symbols. + * @memberOf punycode + * @param {String} input The string of Unicode symbols. + * @returns {String} The resulting Punycode string of ASCII-only symbols. + */ + function encode(input) { + var n, + delta, + handledCPCount, + basicLength, + bias, + j, + m, + q, + k, + t, + currentValue, + output = [], + /** `inputLength` will hold the number of code points in `input`. */ + inputLength, + /** Cached calculation results */ + handledCPCountPlusOne, + baseMinusT, + qMinusT; + + // Convert the input in UCS-2 to Unicode + input = ucs2decode(input); + + // Cache the length + inputLength = input.length; + + // Initialize the state + n = initialN; + delta = 0; + bias = initialBias; + + // Handle the basic code points + for (j = 0; j < inputLength; ++j) { + currentValue = input[j]; + if (currentValue < 0x80) { + output.push(stringFromCharCode(currentValue)); + } + } + + handledCPCount = basicLength = output.length; + + // `handledCPCount` is the number of code points that have been handled; + // `basicLength` is the number of basic code points. + + // Finish the basic string - if it is not empty - with a delimiter + if (basicLength) { + output.push(delimiter); + } + + // Main encoding loop: + while (handledCPCount < inputLength) { + + // All non-basic code points < n have been handled already. Find the next + // larger one: + for (m = maxInt, j = 0; j < inputLength; ++j) { + currentValue = input[j]; + if (currentValue >= n && currentValue < m) { + m = currentValue; + } + } + + // Increase `delta` enough to advance the decoder's state to , + // but guard against overflow + handledCPCountPlusOne = handledCPCount + 1; + if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) { + error('overflow'); + } + + delta += (m - n) * handledCPCountPlusOne; + n = m; + + for (j = 0; j < inputLength; ++j) { + currentValue = input[j]; + + if (currentValue < n && ++delta > maxInt) { + error('overflow'); + } + + if (currentValue == n) { + // Represent delta as a generalized variable-length integer + for (q = delta, k = base; /* no condition */; k += base) { + t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); + if (q < t) { + break; + } + qMinusT = q - t; + baseMinusT = base - t; + output.push( + stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0)) + ); + q = floor(qMinusT / baseMinusT); + } + + output.push(stringFromCharCode(digitToBasic(q, 0))); + bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength); + delta = 0; + ++handledCPCount; + } + } + + ++delta; + ++n; + + } + return output.join(''); + } + + /** + * Converts a Punycode string representing a domain name or an email address + * to Unicode. Only the Punycoded parts of the input will be converted, i.e. + * it doesn't matter if you call it on a string that has already been + * converted to Unicode. + * @memberOf punycode + * @param {String} input The Punycoded domain name or email address to + * convert to Unicode. + * @returns {String} The Unicode representation of the given Punycode + * string. + */ + function toUnicode(input) { + return mapDomain(input, function(string) { + return regexPunycode.test(string) + ? decode(string.slice(4).toLowerCase()) + : string; + }); + } + + /** + * Converts a Unicode string representing a domain name or an email address to + * Punycode. Only the non-ASCII parts of the domain name will be converted, + * i.e. it doesn't matter if you call it with a domain that's already in + * ASCII. + * @memberOf punycode + * @param {String} input The domain name or email address to convert, as a + * Unicode string. + * @returns {String} The Punycode representation of the given domain name or + * email address. + */ + function toASCII(input) { + return mapDomain(input, function(string) { + return regexNonASCII.test(string) + ? 'xn--' + encode(string) + : string; + }); + } + + /*--------------------------------------------------------------------------*/ + + /** Define the public API */ + punycode = { + /** + * A string representing the current Punycode.js version number. + * @memberOf punycode + * @type String + */ + 'version': '1.3.2', + /** + * An object of methods to convert from JavaScript's internal character + * representation (UCS-2) to Unicode code points, and back. + * @see + * @memberOf punycode + * @type Object + */ + 'ucs2': { + 'decode': ucs2decode, + 'encode': ucs2encode + }, + 'decode': decode, + 'encode': encode, + 'toASCII': toASCII, + 'toUnicode': toUnicode + }; + + /** Expose `punycode` */ + // Some AMD build optimizers, like r.js, check for specific condition patterns + // like the following: + if ( + typeof undefined == 'function' && + typeof undefined.amd == 'object' && + undefined.amd + ) { + undefined('punycode', function() { + return punycode; + }); + } else if (freeExports && freeModule) { + if (module.exports == freeExports) { // in Node.js or RingoJS v0.8.0+ + freeModule.exports = punycode; + } else { // in Narwhal or RingoJS v0.7.0- + for (key in punycode) { + punycode.hasOwnProperty(key) && (freeExports[key] = punycode[key]); + } + } + } else { // in Rhino or a web browser + root.punycode = punycode; + } + + }(commonjsGlobal$1)); + }); + + 'use strict'; + + var util = { + isString: function(arg) { + return typeof(arg) === 'string'; + }, + isObject: function(arg) { + return typeof(arg) === 'object' && arg !== null; + }, + isNull: function(arg) { + return arg === null; + }, + isNullOrUndefined: function(arg) { + return arg == null; + } + }; + + // Copyright Joyent, Inc. and other Node contributors. + // + // Permission is hereby granted, free of charge, to any person obtaining a + // copy of this software and associated documentation files (the + // "Software"), to deal in the Software without restriction, including + // without limitation the rights to use, copy, modify, merge, publish, + // distribute, sublicense, and/or sell copies of the Software, and to permit + // persons to whom the Software is furnished to do so, subject to the + // following conditions: + // + // The above copyright notice and this permission notice shall be included + // in all copies or substantial portions of the Software. + // + // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN + // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR + // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE + // USE OR OTHER DEALINGS IN THE SOFTWARE. + + 'use strict'; + + // If obj.hasOwnProperty has been overridden, then calling + // obj.hasOwnProperty(prop) will break. + // See: https://github.com/joyent/node/issues/1707 + function hasOwnProperty$1(obj, prop) { + return Object.prototype.hasOwnProperty.call(obj, prop); + } + + var decode$1 = function(qs, sep, eq, options) { + sep = sep || '&'; + eq = eq || '='; + var obj = {}; + + if (typeof qs !== 'string' || qs.length === 0) { + return obj; + } + + var regexp = /\+/g; + qs = qs.split(sep); + + var maxKeys = 1000; + if (options && typeof options.maxKeys === 'number') { + maxKeys = options.maxKeys; + } + + var len = qs.length; + // maxKeys <= 0 means that we should not limit keys count + if (maxKeys > 0 && len > maxKeys) { + len = maxKeys; + } + + for (var i = 0; i < len; ++i) { + var x = qs[i].replace(regexp, '%20'), + idx = x.indexOf(eq), + kstr, vstr, k, v; + + if (idx >= 0) { + kstr = x.substr(0, idx); + vstr = x.substr(idx + 1); + } else { + kstr = x; + vstr = ''; + } + + k = decodeURIComponent(kstr); + v = decodeURIComponent(vstr); + + if (!hasOwnProperty$1(obj, k)) { + obj[k] = v; + } else if (Array.isArray(obj[k])) { + obj[k].push(v); + } else { + obj[k] = [obj[k], v]; + } + } + + return obj; + }; + + // Copyright Joyent, Inc. and other Node contributors. + // + // Permission is hereby granted, free of charge, to any person obtaining a + // copy of this software and associated documentation files (the + // "Software"), to deal in the Software without restriction, including + // without limitation the rights to use, copy, modify, merge, publish, + // distribute, sublicense, and/or sell copies of the Software, and to permit + // persons to whom the Software is furnished to do so, subject to the + // following conditions: + // + // The above copyright notice and this permission notice shall be included + // in all copies or substantial portions of the Software. + // + // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN + // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR + // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE + // USE OR OTHER DEALINGS IN THE SOFTWARE. + + 'use strict'; + + var stringifyPrimitive$1 = function(v) { + switch (typeof v) { + case 'string': + return v; + + case 'boolean': + return v ? 'true' : 'false'; + + case 'number': + return isFinite(v) ? v : ''; + + default: + return ''; + } + }; + + var encode$1 = function(obj, sep, eq, name) { + sep = sep || '&'; + eq = eq || '='; + if (obj === null) { + obj = undefined; + } + + if (typeof obj === 'object') { + return Object.keys(obj).map(function(k) { + var ks = encodeURIComponent(stringifyPrimitive$1(k)) + eq; + if (Array.isArray(obj[k])) { + return obj[k].map(function(v) { + return ks + encodeURIComponent(stringifyPrimitive$1(v)); + }).join(sep); + } else { + return ks + encodeURIComponent(stringifyPrimitive$1(obj[k])); + } + }).join(sep); + + } + + if (!name) { return ''; } + return encodeURIComponent(stringifyPrimitive$1(name)) + eq + + encodeURIComponent(stringifyPrimitive$1(obj)); + }; + + var querystring = createCommonjsModule$1(function (module, exports) { + 'use strict'; + + exports.decode = exports.parse = decode$1; + exports.encode = exports.stringify = encode$1; + }); + + // Copyright Joyent, Inc. and other Node contributors. + // + // Permission is hereby granted, free of charge, to any person obtaining a + // copy of this software and associated documentation files (the + // "Software"), to deal in the Software without restriction, including + // without limitation the rights to use, copy, modify, merge, publish, + // distribute, sublicense, and/or sell copies of the Software, and to permit + // persons to whom the Software is furnished to do so, subject to the + // following conditions: + // + // The above copyright notice and this permission notice shall be included + // in all copies or substantial portions of the Software. + // + // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN + // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR + // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE + // USE OR OTHER DEALINGS IN THE SOFTWARE. + + 'use strict'; + + + + + var parse = urlParse; + var resolve = urlResolve; + var resolveObject = urlResolveObject; + var format = urlFormat; + + var Url_1 = Url; + + function Url() { + this.protocol = null; + this.slashes = null; + this.auth = null; + this.host = null; + this.port = null; + this.hostname = null; + this.hash = null; + this.search = null; + this.query = null; + this.pathname = null; + this.path = null; + this.href = null; + } + + // Reference: RFC 3986, RFC 1808, RFC 2396 + + // define these here so at least they only have to be + // compiled once on the first module load. + var protocolPattern = /^([a-z0-9.+-]+:)/i, + portPattern = /:[0-9]*$/, + + // Special case for a simple path URL + simplePathPattern = /^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/, + + // RFC 2396: characters reserved for delimiting URLs. + // We actually just auto-escape these. + delims = ['<', '>', '"', '`', ' ', '\r', '\n', '\t'], + + // RFC 2396: characters not allowed for various reasons. + unwise = ['{', '}', '|', '\\', '^', '`'].concat(delims), + + // Allowed by RFCs, but cause of XSS attacks. Always escape these. + autoEscape = ['\''].concat(unwise), + // Characters that are never ever allowed in a hostname. + // Note that any invalid chars are also handled, but these + // are the ones that are *expected* to be seen, so we fast-path + // them. + nonHostChars = ['%', '/', '?', ';', '#'].concat(autoEscape), + hostEndingChars = ['/', '?', '#'], + hostnameMaxLen = 255, + hostnamePartPattern = /^[+a-z0-9A-Z_-]{0,63}$/, + hostnamePartStart = /^([+a-z0-9A-Z_-]{0,63})(.*)$/, + // protocols that can allow "unsafe" and "unwise" chars. + unsafeProtocol = { + 'javascript': true, + 'javascript:': true + }, + // protocols that never have a hostname. + hostlessProtocol = { + 'javascript': true, + 'javascript:': true + }, + // protocols that always contain a // bit. + slashedProtocol = { + 'http': true, + 'https': true, + 'ftp': true, + 'gopher': true, + 'file': true, + 'http:': true, + 'https:': true, + 'ftp:': true, + 'gopher:': true, + 'file:': true + }; + + function urlParse(url, parseQueryString, slashesDenoteHost) { + if (url && util.isObject(url) && url instanceof Url) { return url; } + + var u = new Url; + u.parse(url, parseQueryString, slashesDenoteHost); + return u; + } + + Url.prototype.parse = function(url, parseQueryString, slashesDenoteHost) { + if (!util.isString(url)) { + throw new TypeError("Parameter 'url' must be a string, not " + typeof url); + } + + // Copy chrome, IE, opera backslash-handling behavior. + // Back slashes before the query string get converted to forward slashes + // See: https://code.google.com/p/chromium/issues/detail?id=25916 + var queryIndex = url.indexOf('?'), + splitter = + (queryIndex !== -1 && queryIndex < url.indexOf('#')) ? '?' : '#', + uSplit = url.split(splitter), + slashRegex = /\\/g; + uSplit[0] = uSplit[0].replace(slashRegex, '/'); + url = uSplit.join(splitter); + + var rest = url; + + // trim before proceeding. + // This is to support parse stuff like " http://foo.com \n" + rest = rest.trim(); + + if (!slashesDenoteHost && url.split('#').length === 1) { + // Try fast path regexp + var simplePath = simplePathPattern.exec(rest); + if (simplePath) { + this.path = rest; + this.href = rest; + this.pathname = simplePath[1]; + if (simplePath[2]) { + this.search = simplePath[2]; + if (parseQueryString) { + this.query = querystring.parse(this.search.substr(1)); + } else { + this.query = this.search.substr(1); + } + } else if (parseQueryString) { + this.search = ''; + this.query = {}; + } + return this; + } + } + + var proto = protocolPattern.exec(rest); + if (proto) { + proto = proto[0]; + var lowerProto = proto.toLowerCase(); + this.protocol = lowerProto; + rest = rest.substr(proto.length); + } + + // figure out if it's got a host + // user@server is *always* interpreted as a hostname, and url + // resolution will treat //foo/bar as host=foo,path=bar because that's + // how the browser resolves relative URLs. + if (slashesDenoteHost || proto || rest.match(/^\/\/[^@\/]+@[^@\/]+/)) { + var slashes = rest.substr(0, 2) === '//'; + if (slashes && !(proto && hostlessProtocol[proto])) { + rest = rest.substr(2); + this.slashes = true; + } + } + + if (!hostlessProtocol[proto] && + (slashes || (proto && !slashedProtocol[proto]))) { + + // there's a hostname. + // the first instance of /, ?, ;, or # ends the host. + // + // If there is an @ in the hostname, then non-host chars *are* allowed + // to the left of the last @ sign, unless some host-ending character + // comes *before* the @-sign. + // URLs are obnoxious. + // + // ex: + // http://a@b@c/ => user:a@b host:c + // http://a@b?@c => user:a host:c path:/?@c + + // v0.12 TODO(isaacs): This is not quite how Chrome does things. + // Review our test case against browsers more comprehensively. + + // find the first instance of any hostEndingChars + var hostEnd = -1; + for (var i = 0; i < hostEndingChars.length; i++) { + var hec = rest.indexOf(hostEndingChars[i]); + if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) + { hostEnd = hec; } + } + + // at this point, either we have an explicit point where the + // auth portion cannot go past, or the last @ char is the decider. + var auth, atSign; + if (hostEnd === -1) { + // atSign can be anywhere. + atSign = rest.lastIndexOf('@'); + } else { + // atSign must be in auth portion. + // http://a@b/c@d => host:b auth:a path:/c@d + atSign = rest.lastIndexOf('@', hostEnd); + } + + // Now we have a portion which is definitely the auth. + // Pull that off. + if (atSign !== -1) { + auth = rest.slice(0, atSign); + rest = rest.slice(atSign + 1); + this.auth = decodeURIComponent(auth); + } + + // the host is the remaining to the left of the first non-host char + hostEnd = -1; + for (var i = 0; i < nonHostChars.length; i++) { + var hec = rest.indexOf(nonHostChars[i]); + if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) + { hostEnd = hec; } + } + // if we still have not hit it, then the entire thing is a host. + if (hostEnd === -1) + { hostEnd = rest.length; } + + this.host = rest.slice(0, hostEnd); + rest = rest.slice(hostEnd); + + // pull out port. + this.parseHost(); + + // we've indicated that there is a hostname, + // so even if it's empty, it has to be present. + this.hostname = this.hostname || ''; + + // if hostname begins with [ and ends with ] + // assume that it's an IPv6 address. + var ipv6Hostname = this.hostname[0] === '[' && + this.hostname[this.hostname.length - 1] === ']'; + + // validate a little. + if (!ipv6Hostname) { + var hostparts = this.hostname.split(/\./); + for (var i = 0, l = hostparts.length; i < l; i++) { + var part = hostparts[i]; + if (!part) { continue; } + if (!part.match(hostnamePartPattern)) { + var newpart = ''; + for (var j = 0, k = part.length; j < k; j++) { + if (part.charCodeAt(j) > 127) { + // we replace non-ASCII char with a temporary placeholder + // we need this to make sure size of hostname is not + // broken by replacing non-ASCII by nothing + newpart += 'x'; + } else { + newpart += part[j]; + } + } + // we test again with ASCII char only + if (!newpart.match(hostnamePartPattern)) { + var validParts = hostparts.slice(0, i); + var notHost = hostparts.slice(i + 1); + var bit = part.match(hostnamePartStart); + if (bit) { + validParts.push(bit[1]); + notHost.unshift(bit[2]); + } + if (notHost.length) { + rest = '/' + notHost.join('.') + rest; + } + this.hostname = validParts.join('.'); + break; + } + } + } + } + + if (this.hostname.length > hostnameMaxLen) { + this.hostname = ''; + } else { + // hostnames are always lower case. + this.hostname = this.hostname.toLowerCase(); + } + + if (!ipv6Hostname) { + // IDNA Support: Returns a punycoded representation of "domain". + // It only converts parts of the domain name that + // have non-ASCII characters, i.e. it doesn't matter if + // you call it with a domain that already is ASCII-only. + this.hostname = punycode.toASCII(this.hostname); + } + + var p = this.port ? ':' + this.port : ''; + var h = this.hostname || ''; + this.host = h + p; + this.href += this.host; + + // strip [ and ] from the hostname + // the host field still retains them, though + if (ipv6Hostname) { + this.hostname = this.hostname.substr(1, this.hostname.length - 2); + if (rest[0] !== '/') { + rest = '/' + rest; + } + } + } + + // now rest is set to the post-host stuff. + // chop off any delim chars. + if (!unsafeProtocol[lowerProto]) { + + // First, make 100% sure that any "autoEscape" chars get + // escaped, even if encodeURIComponent doesn't think they + // need to be. + for (var i = 0, l = autoEscape.length; i < l; i++) { + var ae = autoEscape[i]; + if (rest.indexOf(ae) === -1) + { continue; } + var esc = encodeURIComponent(ae); + if (esc === ae) { + esc = escape(ae); + } + rest = rest.split(ae).join(esc); + } + } + + + // chop off from the tail first. + var hash = rest.indexOf('#'); + if (hash !== -1) { + // got a fragment string. + this.hash = rest.substr(hash); + rest = rest.slice(0, hash); + } + var qm = rest.indexOf('?'); + if (qm !== -1) { + this.search = rest.substr(qm); + this.query = rest.substr(qm + 1); + if (parseQueryString) { + this.query = querystring.parse(this.query); + } + rest = rest.slice(0, qm); + } else if (parseQueryString) { + // no query string, but parseQueryString still requested + this.search = ''; + this.query = {}; + } + if (rest) { this.pathname = rest; } + if (slashedProtocol[lowerProto] && + this.hostname && !this.pathname) { + this.pathname = '/'; + } + + //to support http.request + if (this.pathname || this.search) { + var p = this.pathname || ''; + var s = this.search || ''; + this.path = p + s; + } + + // finally, reconstruct the href based on what has been validated. + this.href = this.format(); + return this; + }; + + // format a parsed object into a url string + function urlFormat(obj) { + // ensure it's an object, and not a string url. + // If it's an obj, this is a no-op. + // this way, you can call url_format() on strings + // to clean up potentially wonky urls. + if (util.isString(obj)) { obj = urlParse(obj); } + if (!(obj instanceof Url)) { return Url.prototype.format.call(obj); } + return obj.format(); + } + + Url.prototype.format = function() { + var auth = this.auth || ''; + if (auth) { + auth = encodeURIComponent(auth); + auth = auth.replace(/%3A/i, ':'); + auth += '@'; + } + + var protocol = this.protocol || '', + pathname = this.pathname || '', + hash = this.hash || '', + host = false, + query = ''; + + if (this.host) { + host = auth + this.host; + } else if (this.hostname) { + host = auth + (this.hostname.indexOf(':') === -1 ? + this.hostname : + '[' + this.hostname + ']'); + if (this.port) { + host += ':' + this.port; + } + } + + if (this.query && + util.isObject(this.query) && + Object.keys(this.query).length) { + query = querystring.stringify(this.query); + } + + var search = this.search || (query && ('?' + query)) || ''; + + if (protocol && protocol.substr(-1) !== ':') { protocol += ':'; } + + // only the slashedProtocols get the //. Not mailto:, xmpp:, etc. + // unless they had them to begin with. + if (this.slashes || + (!protocol || slashedProtocol[protocol]) && host !== false) { + host = '//' + (host || ''); + if (pathname && pathname.charAt(0) !== '/') { pathname = '/' + pathname; } + } else if (!host) { + host = ''; + } + + if (hash && hash.charAt(0) !== '#') { hash = '#' + hash; } + if (search && search.charAt(0) !== '?') { search = '?' + search; } + + pathname = pathname.replace(/[?#]/g, function(match) { + return encodeURIComponent(match); + }); + search = search.replace('#', '%23'); + + return protocol + host + pathname + search + hash; + }; + + function urlResolve(source, relative) { + return urlParse(source, false, true).resolve(relative); + } + + Url.prototype.resolve = function(relative) { + return this.resolveObject(urlParse(relative, false, true)).format(); + }; + + function urlResolveObject(source, relative) { + if (!source) { return relative; } + return urlParse(source, false, true).resolveObject(relative); + } + + Url.prototype.resolveObject = function(relative) { + if (util.isString(relative)) { + var rel = new Url(); + rel.parse(relative, false, true); + relative = rel; + } + + var result = new Url(); + var tkeys = Object.keys(this); + for (var tk = 0; tk < tkeys.length; tk++) { + var tkey = tkeys[tk]; + result[tkey] = this[tkey]; + } + + // hash is always overridden, no matter what. + // even href="" will remove it. + result.hash = relative.hash; + + // if the relative url is empty, then there's nothing left to do here. + if (relative.href === '') { + result.href = result.format(); + return result; + } + + // hrefs like //foo/bar always cut to the protocol. + if (relative.slashes && !relative.protocol) { + // take everything except the protocol from relative + var rkeys = Object.keys(relative); + for (var rk = 0; rk < rkeys.length; rk++) { + var rkey = rkeys[rk]; + if (rkey !== 'protocol') + { result[rkey] = relative[rkey]; } + } + + //urlParse appends trailing / to urls like http://www.example.com + if (slashedProtocol[result.protocol] && + result.hostname && !result.pathname) { + result.path = result.pathname = '/'; + } + + result.href = result.format(); + return result; + } + + if (relative.protocol && relative.protocol !== result.protocol) { + // if it's a known url protocol, then changing + // the protocol does weird things + // first, if it's not file:, then we MUST have a host, + // and if there was a path + // to begin with, then we MUST have a path. + // if it is file:, then the host is dropped, + // because that's known to be hostless. + // anything else is assumed to be absolute. + if (!slashedProtocol[relative.protocol]) { + var keys = Object.keys(relative); + for (var v = 0; v < keys.length; v++) { + var k = keys[v]; + result[k] = relative[k]; + } + result.href = result.format(); + return result; + } + + result.protocol = relative.protocol; + if (!relative.host && !hostlessProtocol[relative.protocol]) { + var relPath = (relative.pathname || '').split('/'); + while (relPath.length && !(relative.host = relPath.shift())){ ; } + if (!relative.host) { relative.host = ''; } + if (!relative.hostname) { relative.hostname = ''; } + if (relPath[0] !== '') { relPath.unshift(''); } + if (relPath.length < 2) { relPath.unshift(''); } + result.pathname = relPath.join('/'); + } else { + result.pathname = relative.pathname; + } + result.search = relative.search; + result.query = relative.query; + result.host = relative.host || ''; + result.auth = relative.auth; + result.hostname = relative.hostname || relative.host; + result.port = relative.port; + // to support http.request + if (result.pathname || result.search) { + var p = result.pathname || ''; + var s = result.search || ''; + result.path = p + s; + } + result.slashes = result.slashes || relative.slashes; + result.href = result.format(); + return result; + } + + var isSourceAbs = (result.pathname && result.pathname.charAt(0) === '/'), + isRelAbs = ( + relative.host || + relative.pathname && relative.pathname.charAt(0) === '/' + ), + mustEndAbs = (isRelAbs || isSourceAbs || + (result.host && relative.pathname)), + removeAllDots = mustEndAbs, + srcPath = result.pathname && result.pathname.split('/') || [], + relPath = relative.pathname && relative.pathname.split('/') || [], + psychotic = result.protocol && !slashedProtocol[result.protocol]; + + // if the url is a non-slashed url, then relative + // links like ../.. should be able + // to crawl up to the hostname, as well. This is strange. + // result.protocol has already been set by now. + // Later on, put the first path part into the host field. + if (psychotic) { + result.hostname = ''; + result.port = null; + if (result.host) { + if (srcPath[0] === '') { srcPath[0] = result.host; } + else { srcPath.unshift(result.host); } + } + result.host = ''; + if (relative.protocol) { + relative.hostname = null; + relative.port = null; + if (relative.host) { + if (relPath[0] === '') { relPath[0] = relative.host; } + else { relPath.unshift(relative.host); } + } + relative.host = null; + } + mustEndAbs = mustEndAbs && (relPath[0] === '' || srcPath[0] === ''); + } + + if (isRelAbs) { + // it's absolute. + result.host = (relative.host || relative.host === '') ? + relative.host : result.host; + result.hostname = (relative.hostname || relative.hostname === '') ? + relative.hostname : result.hostname; + result.search = relative.search; + result.query = relative.query; + srcPath = relPath; + // fall through to the dot-handling below. + } else if (relPath.length) { + // it's relative + // throw away the existing file, and take the new path instead. + if (!srcPath) { srcPath = []; } + srcPath.pop(); + srcPath = srcPath.concat(relPath); + result.search = relative.search; + result.query = relative.query; + } else if (!util.isNullOrUndefined(relative.search)) { + // just pull out the search. + // like href='?foo'. + // Put this after the other two cases because it simplifies the booleans + if (psychotic) { + result.hostname = result.host = srcPath.shift(); + //occationaly the auth can get stuck only in host + //this especially happens in cases like + //url.resolveObject('mailto:local1@domain1', 'local2@domain2') + var authInHost = result.host && result.host.indexOf('@') > 0 ? + result.host.split('@') : false; + if (authInHost) { + result.auth = authInHost.shift(); + result.host = result.hostname = authInHost.shift(); + } + } + result.search = relative.search; + result.query = relative.query; + //to support http.request + if (!util.isNull(result.pathname) || !util.isNull(result.search)) { + result.path = (result.pathname ? result.pathname : '') + + (result.search ? result.search : ''); + } + result.href = result.format(); + return result; + } + + if (!srcPath.length) { + // no path at all. easy. + // we've already handled the other stuff above. + result.pathname = null; + //to support http.request + if (result.search) { + result.path = '/' + result.search; + } else { + result.path = null; + } + result.href = result.format(); + return result; + } + + // if a url ENDs in . or .., then it must get a trailing slash. + // however, if it ends in anything else non-slashy, + // then it must NOT get a trailing slash. + var last = srcPath.slice(-1)[0]; + var hasTrailingSlash = ( + (result.host || relative.host || srcPath.length > 1) && + (last === '.' || last === '..') || last === ''); + + // strip single dots, resolve double dots to parent dir + // if the path tries to go above the root, `up` ends up > 0 + var up = 0; + for (var i = srcPath.length; i >= 0; i--) { + last = srcPath[i]; + if (last === '.') { + srcPath.splice(i, 1); + } else if (last === '..') { + srcPath.splice(i, 1); + up++; + } else if (up) { + srcPath.splice(i, 1); + up--; + } + } + + // if the path is allowed to go above the root, restore leading ..s + if (!mustEndAbs && !removeAllDots) { + for (; up--; up) { + srcPath.unshift('..'); + } + } + + if (mustEndAbs && srcPath[0] !== '' && + (!srcPath[0] || srcPath[0].charAt(0) !== '/')) { + srcPath.unshift(''); + } + + if (hasTrailingSlash && (srcPath.join('/').substr(-1) !== '/')) { + srcPath.push(''); + } + + var isAbsolute = srcPath[0] === '' || + (srcPath[0] && srcPath[0].charAt(0) === '/'); + + // put the host back + if (psychotic) { + result.hostname = result.host = isAbsolute ? '' : + srcPath.length ? srcPath.shift() : ''; + //occationaly the auth can get stuck only in host + //this especially happens in cases like + //url.resolveObject('mailto:local1@domain1', 'local2@domain2') + var authInHost = result.host && result.host.indexOf('@') > 0 ? + result.host.split('@') : false; + if (authInHost) { + result.auth = authInHost.shift(); + result.host = result.hostname = authInHost.shift(); + } + } + + mustEndAbs = mustEndAbs || (result.host && srcPath.length); + + if (mustEndAbs && !isAbsolute) { + srcPath.unshift(''); + } + + if (!srcPath.length) { + result.pathname = null; + result.path = null; + } else { + result.pathname = srcPath.join('/'); + } + + //to support request.http + if (!util.isNull(result.pathname) || !util.isNull(result.search)) { + result.path = (result.pathname ? result.pathname : '') + + (result.search ? result.search : ''); + } + result.auth = relative.auth || result.auth; + result.slashes = result.slashes || relative.slashes; + result.href = result.format(); + return result; + }; + + Url.prototype.parseHost = function() { + var host = this.host; + var port = portPattern.exec(host); + if (port) { + port = port[0]; + if (port !== ':') { + this.port = port.substr(1); + } + host = host.substr(0, host.length - port.length); + } + if (host) { this.hostname = host; } + }; + + var url$1 = { + parse: parse, + resolve: resolve, + resolveObject: resolveObject, + format: format, + Url: Url_1 + }; + + /*! + * @pixi/constants - v6.5.3 + * Compiled Fri, 09 Sep 2022 13:55:20 UTC + * + * @pixi/constants is licensed under the MIT License. + * http://www.opensource.org/licenses/mit-license + */ + /** + * Different types of environments for WebGL. + * @static + * @memberof PIXI + * @name ENV + * @enum {number} + * @property {number} WEBGL_LEGACY - Used for older v1 WebGL devices. PixiJS will aim to ensure compatibility + * with older / less advanced devices. If you experience unexplained flickering prefer this environment. + * @property {number} WEBGL - Version 1 of WebGL + * @property {number} WEBGL2 - Version 2 of WebGL + */ + exports.ENV = void 0; + (function (ENV) { + ENV[ENV["WEBGL_LEGACY"] = 0] = "WEBGL_LEGACY"; + ENV[ENV["WEBGL"] = 1] = "WEBGL"; + ENV[ENV["WEBGL2"] = 2] = "WEBGL2"; + })(exports.ENV || (exports.ENV = {})); + /** + * Constant to identify the Renderer Type. + * @static + * @memberof PIXI + * @name RENDERER_TYPE + * @enum {number} + * @property {number} UNKNOWN - Unknown render type. + * @property {number} WEBGL - WebGL render type. + * @property {number} CANVAS - Canvas render type. + */ + exports.RENDERER_TYPE = void 0; + (function (RENDERER_TYPE) { + RENDERER_TYPE[RENDERER_TYPE["UNKNOWN"] = 0] = "UNKNOWN"; + RENDERER_TYPE[RENDERER_TYPE["WEBGL"] = 1] = "WEBGL"; + RENDERER_TYPE[RENDERER_TYPE["CANVAS"] = 2] = "CANVAS"; + })(exports.RENDERER_TYPE || (exports.RENDERER_TYPE = {})); + /** + * Bitwise OR of masks that indicate the buffers to be cleared. + * @static + * @memberof PIXI + * @name BUFFER_BITS + * @enum {number} + * @property {number} COLOR - Indicates the buffers currently enabled for color writing. + * @property {number} DEPTH - Indicates the depth buffer. + * @property {number} STENCIL - Indicates the stencil buffer. + */ + exports.BUFFER_BITS = void 0; + (function (BUFFER_BITS) { + BUFFER_BITS[BUFFER_BITS["COLOR"] = 16384] = "COLOR"; + BUFFER_BITS[BUFFER_BITS["DEPTH"] = 256] = "DEPTH"; + BUFFER_BITS[BUFFER_BITS["STENCIL"] = 1024] = "STENCIL"; + })(exports.BUFFER_BITS || (exports.BUFFER_BITS = {})); + /** + * Various blend modes supported by PIXI. + * + * IMPORTANT - The WebGL renderer only supports the NORMAL, ADD, MULTIPLY and SCREEN blend modes. + * Anything else will silently act like NORMAL. + * @memberof PIXI + * @name BLEND_MODES + * @enum {number} + * @property {number} NORMAL - + * @property {number} ADD - + * @property {number} MULTIPLY - + * @property {number} SCREEN - + * @property {number} OVERLAY - + * @property {number} DARKEN - + * @property {number} LIGHTEN - + * @property {number} COLOR_DODGE - + * @property {number} COLOR_BURN - + * @property {number} HARD_LIGHT - + * @property {number} SOFT_LIGHT - + * @property {number} DIFFERENCE - + * @property {number} EXCLUSION - + * @property {number} HUE - + * @property {number} SATURATION - + * @property {number} COLOR - + * @property {number} LUMINOSITY - + * @property {number} NORMAL_NPM - + * @property {number} ADD_NPM - + * @property {number} SCREEN_NPM - + * @property {number} NONE - + * @property {number} SRC_IN - + * @property {number} SRC_OUT - + * @property {number} SRC_ATOP - + * @property {number} DST_OVER - + * @property {number} DST_IN - + * @property {number} DST_OUT - + * @property {number} DST_ATOP - + * @property {number} SUBTRACT - + * @property {number} SRC_OVER - + * @property {number} ERASE - + * @property {number} XOR - + */ + exports.BLEND_MODES = void 0; + (function (BLEND_MODES) { + BLEND_MODES[BLEND_MODES["NORMAL"] = 0] = "NORMAL"; + BLEND_MODES[BLEND_MODES["ADD"] = 1] = "ADD"; + BLEND_MODES[BLEND_MODES["MULTIPLY"] = 2] = "MULTIPLY"; + BLEND_MODES[BLEND_MODES["SCREEN"] = 3] = "SCREEN"; + BLEND_MODES[BLEND_MODES["OVERLAY"] = 4] = "OVERLAY"; + BLEND_MODES[BLEND_MODES["DARKEN"] = 5] = "DARKEN"; + BLEND_MODES[BLEND_MODES["LIGHTEN"] = 6] = "LIGHTEN"; + BLEND_MODES[BLEND_MODES["COLOR_DODGE"] = 7] = "COLOR_DODGE"; + BLEND_MODES[BLEND_MODES["COLOR_BURN"] = 8] = "COLOR_BURN"; + BLEND_MODES[BLEND_MODES["HARD_LIGHT"] = 9] = "HARD_LIGHT"; + BLEND_MODES[BLEND_MODES["SOFT_LIGHT"] = 10] = "SOFT_LIGHT"; + BLEND_MODES[BLEND_MODES["DIFFERENCE"] = 11] = "DIFFERENCE"; + BLEND_MODES[BLEND_MODES["EXCLUSION"] = 12] = "EXCLUSION"; + BLEND_MODES[BLEND_MODES["HUE"] = 13] = "HUE"; + BLEND_MODES[BLEND_MODES["SATURATION"] = 14] = "SATURATION"; + BLEND_MODES[BLEND_MODES["COLOR"] = 15] = "COLOR"; + BLEND_MODES[BLEND_MODES["LUMINOSITY"] = 16] = "LUMINOSITY"; + BLEND_MODES[BLEND_MODES["NORMAL_NPM"] = 17] = "NORMAL_NPM"; + BLEND_MODES[BLEND_MODES["ADD_NPM"] = 18] = "ADD_NPM"; + BLEND_MODES[BLEND_MODES["SCREEN_NPM"] = 19] = "SCREEN_NPM"; + BLEND_MODES[BLEND_MODES["NONE"] = 20] = "NONE"; + BLEND_MODES[BLEND_MODES["SRC_OVER"] = 0] = "SRC_OVER"; + BLEND_MODES[BLEND_MODES["SRC_IN"] = 21] = "SRC_IN"; + BLEND_MODES[BLEND_MODES["SRC_OUT"] = 22] = "SRC_OUT"; + BLEND_MODES[BLEND_MODES["SRC_ATOP"] = 23] = "SRC_ATOP"; + BLEND_MODES[BLEND_MODES["DST_OVER"] = 24] = "DST_OVER"; + BLEND_MODES[BLEND_MODES["DST_IN"] = 25] = "DST_IN"; + BLEND_MODES[BLEND_MODES["DST_OUT"] = 26] = "DST_OUT"; + BLEND_MODES[BLEND_MODES["DST_ATOP"] = 27] = "DST_ATOP"; + BLEND_MODES[BLEND_MODES["ERASE"] = 26] = "ERASE"; + BLEND_MODES[BLEND_MODES["SUBTRACT"] = 28] = "SUBTRACT"; + BLEND_MODES[BLEND_MODES["XOR"] = 29] = "XOR"; + })(exports.BLEND_MODES || (exports.BLEND_MODES = {})); + /** + * Various webgl draw modes. These can be used to specify which GL drawMode to use + * under certain situations and renderers. + * @memberof PIXI + * @static + * @name DRAW_MODES + * @enum {number} + * @property {number} POINTS - + * @property {number} LINES - + * @property {number} LINE_LOOP - + * @property {number} LINE_STRIP - + * @property {number} TRIANGLES - + * @property {number} TRIANGLE_STRIP - + * @property {number} TRIANGLE_FAN - + */ + exports.DRAW_MODES = void 0; + (function (DRAW_MODES) { + DRAW_MODES[DRAW_MODES["POINTS"] = 0] = "POINTS"; + DRAW_MODES[DRAW_MODES["LINES"] = 1] = "LINES"; + DRAW_MODES[DRAW_MODES["LINE_LOOP"] = 2] = "LINE_LOOP"; + DRAW_MODES[DRAW_MODES["LINE_STRIP"] = 3] = "LINE_STRIP"; + DRAW_MODES[DRAW_MODES["TRIANGLES"] = 4] = "TRIANGLES"; + DRAW_MODES[DRAW_MODES["TRIANGLE_STRIP"] = 5] = "TRIANGLE_STRIP"; + DRAW_MODES[DRAW_MODES["TRIANGLE_FAN"] = 6] = "TRIANGLE_FAN"; + })(exports.DRAW_MODES || (exports.DRAW_MODES = {})); + /** + * Various GL texture/resources formats. + * @memberof PIXI + * @static + * @name FORMATS + * @enum {number} + * @property {number} [RGBA=6408] - + * @property {number} [RGB=6407] - + * @property {number} [RG=33319] - + * @property {number} [RED=6403] - + * @property {number} [RGBA_INTEGER=36249] - + * @property {number} [RGB_INTEGER=36248] - + * @property {number} [RG_INTEGER=33320] - + * @property {number} [RED_INTEGER=36244] - + * @property {number} [ALPHA=6406] - + * @property {number} [LUMINANCE=6409] - + * @property {number} [LUMINANCE_ALPHA=6410] - + * @property {number} [DEPTH_COMPONENT=6402] - + * @property {number} [DEPTH_STENCIL=34041] - + */ + exports.FORMATS = void 0; + (function (FORMATS) { + FORMATS[FORMATS["RGBA"] = 6408] = "RGBA"; + FORMATS[FORMATS["RGB"] = 6407] = "RGB"; + FORMATS[FORMATS["RG"] = 33319] = "RG"; + FORMATS[FORMATS["RED"] = 6403] = "RED"; + FORMATS[FORMATS["RGBA_INTEGER"] = 36249] = "RGBA_INTEGER"; + FORMATS[FORMATS["RGB_INTEGER"] = 36248] = "RGB_INTEGER"; + FORMATS[FORMATS["RG_INTEGER"] = 33320] = "RG_INTEGER"; + FORMATS[FORMATS["RED_INTEGER"] = 36244] = "RED_INTEGER"; + FORMATS[FORMATS["ALPHA"] = 6406] = "ALPHA"; + FORMATS[FORMATS["LUMINANCE"] = 6409] = "LUMINANCE"; + FORMATS[FORMATS["LUMINANCE_ALPHA"] = 6410] = "LUMINANCE_ALPHA"; + FORMATS[FORMATS["DEPTH_COMPONENT"] = 6402] = "DEPTH_COMPONENT"; + FORMATS[FORMATS["DEPTH_STENCIL"] = 34041] = "DEPTH_STENCIL"; + })(exports.FORMATS || (exports.FORMATS = {})); + /** + * Various GL target types. + * @memberof PIXI + * @static + * @name TARGETS + * @enum {number} + * @property {number} [TEXTURE_2D=3553] - + * @property {number} [TEXTURE_CUBE_MAP=34067] - + * @property {number} [TEXTURE_2D_ARRAY=35866] - + * @property {number} [TEXTURE_CUBE_MAP_POSITIVE_X=34069] - + * @property {number} [TEXTURE_CUBE_MAP_NEGATIVE_X=34070] - + * @property {number} [TEXTURE_CUBE_MAP_POSITIVE_Y=34071] - + * @property {number} [TEXTURE_CUBE_MAP_NEGATIVE_Y=34072] - + * @property {number} [TEXTURE_CUBE_MAP_POSITIVE_Z=34073] - + * @property {number} [TEXTURE_CUBE_MAP_NEGATIVE_Z=34074] - + */ + exports.TARGETS = void 0; + (function (TARGETS) { + TARGETS[TARGETS["TEXTURE_2D"] = 3553] = "TEXTURE_2D"; + TARGETS[TARGETS["TEXTURE_CUBE_MAP"] = 34067] = "TEXTURE_CUBE_MAP"; + TARGETS[TARGETS["TEXTURE_2D_ARRAY"] = 35866] = "TEXTURE_2D_ARRAY"; + TARGETS[TARGETS["TEXTURE_CUBE_MAP_POSITIVE_X"] = 34069] = "TEXTURE_CUBE_MAP_POSITIVE_X"; + TARGETS[TARGETS["TEXTURE_CUBE_MAP_NEGATIVE_X"] = 34070] = "TEXTURE_CUBE_MAP_NEGATIVE_X"; + TARGETS[TARGETS["TEXTURE_CUBE_MAP_POSITIVE_Y"] = 34071] = "TEXTURE_CUBE_MAP_POSITIVE_Y"; + TARGETS[TARGETS["TEXTURE_CUBE_MAP_NEGATIVE_Y"] = 34072] = "TEXTURE_CUBE_MAP_NEGATIVE_Y"; + TARGETS[TARGETS["TEXTURE_CUBE_MAP_POSITIVE_Z"] = 34073] = "TEXTURE_CUBE_MAP_POSITIVE_Z"; + TARGETS[TARGETS["TEXTURE_CUBE_MAP_NEGATIVE_Z"] = 34074] = "TEXTURE_CUBE_MAP_NEGATIVE_Z"; + })(exports.TARGETS || (exports.TARGETS = {})); + /** + * Various GL data format types. + * @memberof PIXI + * @static + * @name TYPES + * @enum {number} + * @property {number} [UNSIGNED_BYTE=5121] - + * @property {number} [UNSIGNED_SHORT=5123] - + * @property {number} [UNSIGNED_SHORT_5_6_5=33635] - + * @property {number} [UNSIGNED_SHORT_4_4_4_4=32819] - + * @property {number} [UNSIGNED_SHORT_5_5_5_1=32820] - + * @property {number} [UNSIGNED_INT=5125] - + * @property {number} [UNSIGNED_INT_10F_11F_11F_REV=35899] - + * @property {number} [UNSIGNED_INT_2_10_10_10_REV=33640] - + * @property {number} [UNSIGNED_INT_24_8=34042] - + * @property {number} [UNSIGNED_INT_5_9_9_9_REV=35902] - + * @property {number} [BYTE=5120] - + * @property {number} [SHORT=5122] - + * @property {number} [INT=5124] - + * @property {number} [FLOAT=5126] - + * @property {number} [FLOAT_32_UNSIGNED_INT_24_8_REV=36269] - + * @property {number} [HALF_FLOAT=36193] - + */ + exports.TYPES = void 0; + (function (TYPES) { + TYPES[TYPES["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE"; + TYPES[TYPES["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT"; + TYPES[TYPES["UNSIGNED_SHORT_5_6_5"] = 33635] = "UNSIGNED_SHORT_5_6_5"; + TYPES[TYPES["UNSIGNED_SHORT_4_4_4_4"] = 32819] = "UNSIGNED_SHORT_4_4_4_4"; + TYPES[TYPES["UNSIGNED_SHORT_5_5_5_1"] = 32820] = "UNSIGNED_SHORT_5_5_5_1"; + TYPES[TYPES["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT"; + TYPES[TYPES["UNSIGNED_INT_10F_11F_11F_REV"] = 35899] = "UNSIGNED_INT_10F_11F_11F_REV"; + TYPES[TYPES["UNSIGNED_INT_2_10_10_10_REV"] = 33640] = "UNSIGNED_INT_2_10_10_10_REV"; + TYPES[TYPES["UNSIGNED_INT_24_8"] = 34042] = "UNSIGNED_INT_24_8"; + TYPES[TYPES["UNSIGNED_INT_5_9_9_9_REV"] = 35902] = "UNSIGNED_INT_5_9_9_9_REV"; + TYPES[TYPES["BYTE"] = 5120] = "BYTE"; + TYPES[TYPES["SHORT"] = 5122] = "SHORT"; + TYPES[TYPES["INT"] = 5124] = "INT"; + TYPES[TYPES["FLOAT"] = 5126] = "FLOAT"; + TYPES[TYPES["FLOAT_32_UNSIGNED_INT_24_8_REV"] = 36269] = "FLOAT_32_UNSIGNED_INT_24_8_REV"; + TYPES[TYPES["HALF_FLOAT"] = 36193] = "HALF_FLOAT"; + })(exports.TYPES || (exports.TYPES = {})); + /** + * Various sampler types. Correspond to `sampler`, `isampler`, `usampler` GLSL types respectively. + * WebGL1 works only with FLOAT. + * @memberof PIXI + * @static + * @name SAMPLER_TYPES + * @enum {number} + * @property {number} [FLOAT=0] - + * @property {number} [INT=1] - + * @property {number} [UINT=2] - + */ + exports.SAMPLER_TYPES = void 0; + (function (SAMPLER_TYPES) { + SAMPLER_TYPES[SAMPLER_TYPES["FLOAT"] = 0] = "FLOAT"; + SAMPLER_TYPES[SAMPLER_TYPES["INT"] = 1] = "INT"; + SAMPLER_TYPES[SAMPLER_TYPES["UINT"] = 2] = "UINT"; + })(exports.SAMPLER_TYPES || (exports.SAMPLER_TYPES = {})); + /** + * The scale modes that are supported by pixi. + * + * The {@link PIXI.settings.SCALE_MODE} scale mode affects the default scaling mode of future operations. + * It can be re-assigned to either LINEAR or NEAREST, depending upon suitability. + * @memberof PIXI + * @static + * @name SCALE_MODES + * @enum {number} + * @property {number} LINEAR Smooth scaling + * @property {number} NEAREST Pixelating scaling + */ + exports.SCALE_MODES = void 0; + (function (SCALE_MODES) { + SCALE_MODES[SCALE_MODES["NEAREST"] = 0] = "NEAREST"; + SCALE_MODES[SCALE_MODES["LINEAR"] = 1] = "LINEAR"; + })(exports.SCALE_MODES || (exports.SCALE_MODES = {})); + /** + * The wrap modes that are supported by pixi. + * + * The {@link PIXI.settings.WRAP_MODE} wrap mode affects the default wrapping mode of future operations. + * It can be re-assigned to either CLAMP or REPEAT, depending upon suitability. + * If the texture is non power of two then clamp will be used regardless as WebGL can + * only use REPEAT if the texture is po2. + * + * This property only affects WebGL. + * @name WRAP_MODES + * @memberof PIXI + * @static + * @enum {number} + * @property {number} CLAMP - The textures uvs are clamped + * @property {number} REPEAT - The texture uvs tile and repeat + * @property {number} MIRRORED_REPEAT - The texture uvs tile and repeat with mirroring + */ + exports.WRAP_MODES = void 0; + (function (WRAP_MODES) { + WRAP_MODES[WRAP_MODES["CLAMP"] = 33071] = "CLAMP"; + WRAP_MODES[WRAP_MODES["REPEAT"] = 10497] = "REPEAT"; + WRAP_MODES[WRAP_MODES["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT"; + })(exports.WRAP_MODES || (exports.WRAP_MODES = {})); + /** + * Mipmap filtering modes that are supported by pixi. + * + * The {@link PIXI.settings.MIPMAP_TEXTURES} affects default texture filtering. + * Mipmaps are generated for a baseTexture if its `mipmap` field is `ON`, + * or its `POW2` and texture dimensions are powers of 2. + * Due to platform restriction, `ON` option will work like `POW2` for webgl-1. + * + * This property only affects WebGL. + * @name MIPMAP_MODES + * @memberof PIXI + * @static + * @enum {number} + * @property {number} OFF - No mipmaps + * @property {number} POW2 - Generate mipmaps if texture dimensions are pow2 + * @property {number} ON - Always generate mipmaps + * @property {number} ON_MANUAL - Use mipmaps, but do not auto-generate them; this is used with a resource + * that supports buffering each level-of-detail. + */ + exports.MIPMAP_MODES = void 0; + (function (MIPMAP_MODES) { + MIPMAP_MODES[MIPMAP_MODES["OFF"] = 0] = "OFF"; + MIPMAP_MODES[MIPMAP_MODES["POW2"] = 1] = "POW2"; + MIPMAP_MODES[MIPMAP_MODES["ON"] = 2] = "ON"; + MIPMAP_MODES[MIPMAP_MODES["ON_MANUAL"] = 3] = "ON_MANUAL"; + })(exports.MIPMAP_MODES || (exports.MIPMAP_MODES = {})); + /** + * How to treat textures with premultiplied alpha + * @name ALPHA_MODES + * @memberof PIXI + * @static + * @enum {number} + * @property {number} NO_PREMULTIPLIED_ALPHA - Source is not premultiplied, leave it like that. + * Option for compressed and data textures that are created from typed arrays. + * @property {number} PREMULTIPLY_ON_UPLOAD - Source is not premultiplied, premultiply on upload. + * Default option, used for all loaded images. + * @property {number} PREMULTIPLIED_ALPHA - Source is already premultiplied + * Example: spine atlases with `_pma` suffix. + * @property {number} NPM - Alias for NO_PREMULTIPLIED_ALPHA. + * @property {number} UNPACK - Default option, alias for PREMULTIPLY_ON_UPLOAD. + * @property {number} PMA - Alias for PREMULTIPLIED_ALPHA. + */ + exports.ALPHA_MODES = void 0; + (function (ALPHA_MODES) { + ALPHA_MODES[ALPHA_MODES["NPM"] = 0] = "NPM"; + ALPHA_MODES[ALPHA_MODES["UNPACK"] = 1] = "UNPACK"; + ALPHA_MODES[ALPHA_MODES["PMA"] = 2] = "PMA"; + ALPHA_MODES[ALPHA_MODES["NO_PREMULTIPLIED_ALPHA"] = 0] = "NO_PREMULTIPLIED_ALPHA"; + ALPHA_MODES[ALPHA_MODES["PREMULTIPLY_ON_UPLOAD"] = 1] = "PREMULTIPLY_ON_UPLOAD"; + ALPHA_MODES[ALPHA_MODES["PREMULTIPLY_ALPHA"] = 2] = "PREMULTIPLY_ALPHA"; + ALPHA_MODES[ALPHA_MODES["PREMULTIPLIED_ALPHA"] = 2] = "PREMULTIPLIED_ALPHA"; + })(exports.ALPHA_MODES || (exports.ALPHA_MODES = {})); + /** + * Configure whether filter textures are cleared after binding. + * + * Filter textures need not be cleared if the filter does not use pixel blending. {@link CLEAR_MODES.BLIT} will detect + * this and skip clearing as an optimization. + * @name CLEAR_MODES + * @memberof PIXI + * @static + * @enum {number} + * @property {number} BLEND - Do not clear the filter texture. The filter's output will blend on top of the output texture. + * @property {number} CLEAR - Always clear the filter texture. + * @property {number} BLIT - Clear only if {@link FilterSystem.forceClear} is set or if the filter uses pixel blending. + * @property {number} NO - Alias for BLEND, same as `false` in earlier versions + * @property {number} YES - Alias for CLEAR, same as `true` in earlier versions + * @property {number} AUTO - Alias for BLIT + */ + exports.CLEAR_MODES = void 0; + (function (CLEAR_MODES) { + CLEAR_MODES[CLEAR_MODES["NO"] = 0] = "NO"; + CLEAR_MODES[CLEAR_MODES["YES"] = 1] = "YES"; + CLEAR_MODES[CLEAR_MODES["AUTO"] = 2] = "AUTO"; + CLEAR_MODES[CLEAR_MODES["BLEND"] = 0] = "BLEND"; + CLEAR_MODES[CLEAR_MODES["CLEAR"] = 1] = "CLEAR"; + CLEAR_MODES[CLEAR_MODES["BLIT"] = 2] = "BLIT"; + })(exports.CLEAR_MODES || (exports.CLEAR_MODES = {})); + /** + * The gc modes that are supported by pixi. + * + * The {@link PIXI.settings.GC_MODE} Garbage Collection mode for PixiJS textures is AUTO + * If set to GC_MODE, the renderer will occasionally check textures usage. If they are not + * used for a specified period of time they will be removed from the GPU. They will of course + * be uploaded again when they are required. This is a silent behind the scenes process that + * should ensure that the GPU does not get filled up. + * + * Handy for mobile devices! + * This property only affects WebGL. + * @name GC_MODES + * @enum {number} + * @static + * @memberof PIXI + * @property {number} AUTO - Garbage collection will happen periodically automatically + * @property {number} MANUAL - Garbage collection will need to be called manually + */ + exports.GC_MODES = void 0; + (function (GC_MODES) { + GC_MODES[GC_MODES["AUTO"] = 0] = "AUTO"; + GC_MODES[GC_MODES["MANUAL"] = 1] = "MANUAL"; + })(exports.GC_MODES || (exports.GC_MODES = {})); + /** + * Constants that specify float precision in shaders. + * @name PRECISION + * @memberof PIXI + * @constant + * @static + * @enum {string} + * @property {string} [LOW='lowp'] - + * @property {string} [MEDIUM='mediump'] - + * @property {string} [HIGH='highp'] - + */ + exports.PRECISION = void 0; + (function (PRECISION) { + PRECISION["LOW"] = "lowp"; + PRECISION["MEDIUM"] = "mediump"; + PRECISION["HIGH"] = "highp"; + })(exports.PRECISION || (exports.PRECISION = {})); + /** + * Constants for mask implementations. + * We use `type` suffix because it leads to very different behaviours + * @name MASK_TYPES + * @memberof PIXI + * @static + * @enum {number} + * @property {number} NONE - Mask is ignored + * @property {number} SCISSOR - Scissor mask, rectangle on screen, cheap + * @property {number} STENCIL - Stencil mask, 1-bit, medium, works only if renderer supports stencil + * @property {number} SPRITE - Mask that uses SpriteMaskFilter, uses temporary RenderTexture + * @property {number} COLOR - Color mask (RGBA) + */ + exports.MASK_TYPES = void 0; + (function (MASK_TYPES) { + MASK_TYPES[MASK_TYPES["NONE"] = 0] = "NONE"; + MASK_TYPES[MASK_TYPES["SCISSOR"] = 1] = "SCISSOR"; + MASK_TYPES[MASK_TYPES["STENCIL"] = 2] = "STENCIL"; + MASK_TYPES[MASK_TYPES["SPRITE"] = 3] = "SPRITE"; + MASK_TYPES[MASK_TYPES["COLOR"] = 4] = "COLOR"; + })(exports.MASK_TYPES || (exports.MASK_TYPES = {})); + /** + * Bitwise OR of masks that indicate the color channels that are rendered to. + * @static + * @memberof PIXI + * @name COLOR_MASK_BITS + * @enum {number} + * @property {number} RED - Red channel. + * @property {number} GREEN - Green channel + * @property {number} BLUE - Blue channel. + * @property {number} ALPHA - Alpha channel. + */ + exports.COLOR_MASK_BITS = void 0; + (function (COLOR_MASK_BITS) { + COLOR_MASK_BITS[COLOR_MASK_BITS["RED"] = 1] = "RED"; + COLOR_MASK_BITS[COLOR_MASK_BITS["GREEN"] = 2] = "GREEN"; + COLOR_MASK_BITS[COLOR_MASK_BITS["BLUE"] = 4] = "BLUE"; + COLOR_MASK_BITS[COLOR_MASK_BITS["ALPHA"] = 8] = "ALPHA"; + })(exports.COLOR_MASK_BITS || (exports.COLOR_MASK_BITS = {})); + /** + * Constants for multi-sampling antialiasing. + * @see PIXI.Framebuffer#multisample + * @name MSAA_QUALITY + * @memberof PIXI + * @static + * @enum {number} + * @property {number} NONE - No multisampling for this renderTexture + * @property {number} LOW - Try 2 samples + * @property {number} MEDIUM - Try 4 samples + * @property {number} HIGH - Try 8 samples + */ + exports.MSAA_QUALITY = void 0; + (function (MSAA_QUALITY) { + MSAA_QUALITY[MSAA_QUALITY["NONE"] = 0] = "NONE"; + MSAA_QUALITY[MSAA_QUALITY["LOW"] = 2] = "LOW"; + MSAA_QUALITY[MSAA_QUALITY["MEDIUM"] = 4] = "MEDIUM"; + MSAA_QUALITY[MSAA_QUALITY["HIGH"] = 8] = "HIGH"; + })(exports.MSAA_QUALITY || (exports.MSAA_QUALITY = {})); + /** + * Constants for various buffer types in Pixi + * @see PIXI.BUFFER_TYPE + * @name BUFFER_TYPE + * @memberof PIXI + * @static + * @enum {number} + * @property {number} ELEMENT_ARRAY_BUFFER - buffer type for using as an index buffer + * @property {number} ARRAY_BUFFER - buffer type for using attribute data + * @property {number} UNIFORM_BUFFER - the buffer type is for uniform buffer objects + */ + exports.BUFFER_TYPE = void 0; + (function (BUFFER_TYPE) { + BUFFER_TYPE[BUFFER_TYPE["ELEMENT_ARRAY_BUFFER"] = 34963] = "ELEMENT_ARRAY_BUFFER"; + BUFFER_TYPE[BUFFER_TYPE["ARRAY_BUFFER"] = 34962] = "ARRAY_BUFFER"; + // NOT YET SUPPORTED + BUFFER_TYPE[BUFFER_TYPE["UNIFORM_BUFFER"] = 35345] = "UNIFORM_BUFFER"; + })(exports.BUFFER_TYPE || (exports.BUFFER_TYPE = {})); + + /*! + * @pixi/utils - v6.5.3 + * Compiled Fri, 09 Sep 2022 13:55:20 UTC + * + * @pixi/utils is licensed under the MIT License. + * http://www.opensource.org/licenses/mit-license + */ + + /** + * This file contains redeclared types for Node `url` and `querystring` modules. These modules + * don't provide their own typings but instead are a part of the full Node typings. The purpose of + * this file is to redeclare the required types to avoid having the whole Node types as a + * dependency. + */ + var url = { + parse: parse, + format: format, + resolve: resolve, + }; + + function assertPath(path) { + if (typeof path !== 'string') { + throw new TypeError("Path must be a string. Received " + JSON.stringify(path)); + } + } + function removeUrlParams(url) { + var re = url.split('?')[0]; + return re.split('#')[0]; + } + function escapeRegExp(string) { + return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string + } + function replaceAll(str, find, replace) { + return str.replace(new RegExp(escapeRegExp(find), 'g'), replace); + } + // Resolves . and .. elements in a path with directory names + function normalizeStringPosix(path, allowAboveRoot) { + var res = ''; + var lastSegmentLength = 0; + var lastSlash = -1; + var dots = 0; + var code; + for (var i = 0; i <= path.length; ++i) { + if (i < path.length) { + code = path.charCodeAt(i); + } + else if (code === 47) { + break; + } + else { + code = 47; + } + if (code === 47) { + if (lastSlash === i - 1 || dots === 1) { ; } + else if (lastSlash !== i - 1 && dots === 2) { + if (res.length < 2 + || lastSegmentLength !== 2 + || res.charCodeAt(res.length - 1) !== 46 + || res.charCodeAt(res.length - 2) !== 46) { + if (res.length > 2) { + var lastSlashIndex = res.lastIndexOf('/'); + if (lastSlashIndex !== res.length - 1) { + if (lastSlashIndex === -1) { + res = ''; + lastSegmentLength = 0; + } + else { + res = res.slice(0, lastSlashIndex); + lastSegmentLength = res.length - 1 - res.lastIndexOf('/'); + } + lastSlash = i; + dots = 0; + continue; + } + } + else if (res.length === 2 || res.length === 1) { + res = ''; + lastSegmentLength = 0; + lastSlash = i; + dots = 0; + continue; + } + } + if (allowAboveRoot) { + if (res.length > 0) { + res += '/..'; + } + else { + res = '..'; + } + lastSegmentLength = 2; + } + } + else { + if (res.length > 0) { + res += "/" + path.slice(lastSlash + 1, i); + } + else { + res = path.slice(lastSlash + 1, i); + } + lastSegmentLength = i - lastSlash - 1; + } + lastSlash = i; + dots = 0; + } + else if (code === 46 && dots !== -1) { + ++dots; + } + else { + dots = -1; + } + } + return res; + } + var path = { + /** + * Converts a path to posix format. + * @param path - The path to convert to posix + */ + toPosix: function (path) { return replaceAll(path, '\\', '/'); }, + /** + * Checks if the path is a URL + * @param path - The path to check + */ + isUrl: function (path) { return (/^https?:/).test(this.toPosix(path)); }, + /** + * Checks if the path is a data URL + * @param path - The path to check + */ + isDataUrl: function (path) { + // eslint-disable-next-line max-len + return (/^data:([a-z]+\/[a-z0-9-+.]+(;[a-z0-9-.!#$%*+.{}|~`]+=[a-z0-9-.!#$%*+.{}()_|~`]+)*)?(;base64)?,([a-z0-9!$&',()*+;=\-._~:@\/?%\s<>]*?)$/i) + .test(path); + }, + /** + * Checks if the path has a protocol e.g. http:// + * This will return true for windows file paths + * @param path - The path to check + */ + hasProtocol: function (path) { return (/^[^/:]+:\//).test(this.toPosix(path)); }, + /** + * Returns the protocol of the path e.g. http://, C:/, file:/// + * @param path - The path to get the protocol from + */ + getProtocol: function (path) { + assertPath(path); + path = this.toPosix(path); + var protocol = ''; + var isFile = (/^file:\/\/\//).exec(path); + var isHttp = (/^[^/:]+:\/\//).exec(path); + var isWindows = (/^[^/:]+:\//).exec(path); + if (isFile || isHttp || isWindows) { + var arr = (isFile === null || isFile === void 0 ? void 0 : isFile[0]) || (isHttp === null || isHttp === void 0 ? void 0 : isHttp[0]) || (isWindows === null || isWindows === void 0 ? void 0 : isWindows[0]); + protocol = arr; + path = path.slice(arr.length); + } + return protocol; + }, + /** + * Converts URL to an absolute path. + * When loading from a Web Worker, we must use absolute paths. + * If the URL is already absolute we return it as is + * If it's not, we convert it + * @param url - The URL to test + * @param customBaseUrl - The base URL to use + * @param customRootUrl - The root URL to use + */ + toAbsolute: function (url, customBaseUrl, customRootUrl) { + if (this.isDataUrl(url)) + { return url; } + var baseUrl = removeUrlParams(this.toPosix(customBaseUrl !== null && customBaseUrl !== void 0 ? customBaseUrl : settings$1.ADAPTER.getBaseUrl())); + var rootUrl = removeUrlParams(this.toPosix(customRootUrl !== null && customRootUrl !== void 0 ? customRootUrl : this.rootname(baseUrl))); + assertPath(url); + url = this.toPosix(url); + // root relative url + if (url.startsWith('/')) { + return path.join(rootUrl, url.slice(1)); + } + var absolutePath = this.isAbsolute(url) ? url : this.join(baseUrl, url); + return absolutePath; + }, + /** + * Normalizes the given path, resolving '..' and '.' segments + * @param path - The path to normalize + */ + normalize: function (path) { + path = this.toPosix(path); + assertPath(path); + if (path.length === 0) + { return '.'; } + var protocol = ''; + var isAbsolute = path.startsWith('/'); + if (this.hasProtocol(path)) { + protocol = this.rootname(path); + path = path.slice(protocol.length); + } + var trailingSeparator = path.endsWith('/'); + // Normalize the path + path = normalizeStringPosix(path, false); + if (path.length > 0 && trailingSeparator) + { path += '/'; } + if (isAbsolute) + { return "/" + path; } + return protocol + path; + }, + /** + * Determines if path is an absolute path. + * Absolute paths can be urls, data urls, or paths on disk + * @param path - The path to test + */ + isAbsolute: function (path) { + assertPath(path); + path = this.toPosix(path); + if (this.hasProtocol(path)) + { return true; } + return path.startsWith('/'); + }, + /** + * Joins all given path segments together using the platform-specific separator as a delimiter, + * then normalizes the resulting path + * @param segments - The segments of the path to join + */ + join: function () { + var arguments$1 = arguments; + + var _a; + var segments = []; + for (var _i = 0; _i < arguments.length; _i++) { + segments[_i] = arguments$1[_i]; + } + if (segments.length === 0) { + return '.'; + } + var joined; + for (var i = 0; i < segments.length; ++i) { + var arg = segments[i]; + assertPath(arg); + if (arg.length > 0) { + if (joined === undefined) + { joined = arg; } + else { + var prevArg = (_a = segments[i - 1]) !== null && _a !== void 0 ? _a : ''; + if (this.extname(prevArg)) { + joined += "/../" + arg; + } + else { + joined += "/" + arg; + } + } + } + } + if (joined === undefined) { + return '.'; + } + return this.normalize(joined); + }, + /** + * Returns the directory name of a path + * @param path - The path to parse + */ + dirname: function (path) { + assertPath(path); + if (path.length === 0) + { return '.'; } + path = this.toPosix(path); + var code = path.charCodeAt(0); + var hasRoot = code === 47; + var end = -1; + var matchedSlash = true; + var proto = this.getProtocol(path); + var origpath = path; + path = path.slice(proto.length); + for (var i = path.length - 1; i >= 1; --i) { + code = path.charCodeAt(i); + if (code === 47) { + if (!matchedSlash) { + end = i; + break; + } + } + else { + // We saw the first non-path separator + matchedSlash = false; + } + } + // if end is -1 and its a url then we need to add the path back + // eslint-disable-next-line no-nested-ternary + if (end === -1) + { return hasRoot ? '/' : this.isUrl(origpath) ? proto + path : proto; } + if (hasRoot && end === 1) + { return '//'; } + return proto + path.slice(0, end); + }, + /** + * Returns the root of the path e.g. /, C:/, file:///, http://domain.com/ + * @param path - The path to parse + */ + rootname: function (path) { + assertPath(path); + path = this.toPosix(path); + var root = ''; + if (path.startsWith('/')) + { root = '/'; } + else { + root = this.getProtocol(path); + } + if (this.isUrl(path)) { + // need to find the first path separator + var index = path.indexOf('/', root.length); + if (index !== -1) { + root = path.slice(0, index); + } + else + { root = path; } + if (!root.endsWith('/')) + { root += '/'; } + } + return root; + }, + /** + * Returns the last portion of a path + * @param path - The path to test + * @param ext - Optional extension to remove + */ + basename: function (path, ext) { + assertPath(path); + if (ext) + { assertPath(ext); } + path = this.toPosix(path); + var start = 0; + var end = -1; + var matchedSlash = true; + var i; + if (ext !== undefined && ext.length > 0 && ext.length <= path.length) { + if (ext.length === path.length && ext === path) + { return ''; } + var extIdx = ext.length - 1; + var firstNonSlashEnd = -1; + for (i = path.length - 1; i >= 0; --i) { + var code = path.charCodeAt(i); + if (code === 47) { + // If we reached a path separator that was not part of a set of path + // separators at the end of the string, stop now + if (!matchedSlash) { + start = i + 1; + break; + } + } + else { + if (firstNonSlashEnd === -1) { + // We saw the first non-path separator, remember this index in case + // we need it if the extension ends up not matching + matchedSlash = false; + firstNonSlashEnd = i + 1; + } + if (extIdx >= 0) { + // Try to match the explicit extension + if (code === ext.charCodeAt(extIdx)) { + if (--extIdx === -1) { + // We matched the extension, so mark this as the end of our path + // component + end = i; + } + } + else { + // Extension does not match, so our result is the entire path + // component + extIdx = -1; + end = firstNonSlashEnd; + } + } + } + } + if (start === end) + { end = firstNonSlashEnd; } + else if (end === -1) + { end = path.length; } + return path.slice(start, end); + } + for (i = path.length - 1; i >= 0; --i) { + if (path.charCodeAt(i) === 47) { + // If we reached a path separator that was not part of a set of path + // separators at the end of the string, stop now + if (!matchedSlash) { + start = i + 1; + break; + } + } + else if (end === -1) { + // We saw the first non-path separator, mark this as the end of our + // path component + matchedSlash = false; + end = i + 1; + } + } + if (end === -1) + { return ''; } + return path.slice(start, end); + }, + /** + * Returns the extension of the path, from the last occurrence of the . (period) character to end of string in the last + * portion of the path. If there is no . in the last portion of the path, or if there are no . characters other than + * the first character of the basename of path, an empty string is returned. + * @param path - The path to parse + */ + extname: function (path) { + assertPath(path); + path = this.toPosix(path); + var startDot = -1; + var startPart = 0; + var end = -1; + var matchedSlash = true; + // Track the state of characters (if any) we see before our first dot and + // after any path separator we find + var preDotState = 0; + for (var i = path.length - 1; i >= 0; --i) { + var code = path.charCodeAt(i); + if (code === 47) { + // If we reached a path separator that was not part of a set of path + // separators at the end of the string, stop now + if (!matchedSlash) { + startPart = i + 1; + break; + } + continue; + } + if (end === -1) { + // We saw the first non-path separator, mark this as the end of our + // extension + matchedSlash = false; + end = i + 1; + } + if (code === 46) { + // If this is our first dot, mark it as the start of our extension + if (startDot === -1) + { startDot = i; } + else if (preDotState !== 1) + { preDotState = 1; } + } + else if (startDot !== -1) { + // We saw a non-dot and non-path separator before our dot, so we should + // have a good chance at having a non-empty extension + preDotState = -1; + } + } + if (startDot === -1 || end === -1 + // We saw a non-dot character immediately before the dot + || preDotState === 0 + // The (right-most) trimmed path component is exactly '..' + // eslint-disable-next-line no-mixed-operators + || preDotState === 1 && startDot === end - 1 && startDot === startPart + 1) { + return ''; + } + return path.slice(startDot, end); + }, + /** + * Parses a path into an object containing the 'root', `dir`, `base`, `ext`, and `name` properties. + * @param path - The path to parse + */ + parse: function (path) { + assertPath(path); + var ret = { root: '', dir: '', base: '', ext: '', name: '' }; + if (path.length === 0) + { return ret; } + path = this.toPosix(path); + var code = path.charCodeAt(0); + var isAbsolute = this.isAbsolute(path); + var start; + ret.root = this.rootname(path); + if (isAbsolute || this.hasProtocol(path)) { + start = 1; + } + else { + start = 0; + } + var startDot = -1; + var startPart = 0; + var end = -1; + var matchedSlash = true; + var i = path.length - 1; + // Track the state of characters (if any) we see before our first dot and + // after any path separator we find + var preDotState = 0; + // Get non-dir info + for (; i >= start; --i) { + code = path.charCodeAt(i); + if (code === 47) { + // If we reached a path separator that was not part of a set of path + // separators at the end of the string, stop now + if (!matchedSlash) { + startPart = i + 1; + break; + } + continue; + } + if (end === -1) { + // We saw the first non-path separator, mark this as the end of our + // extension + matchedSlash = false; + end = i + 1; + } + if (code === 46) { + // If this is our first dot, mark it as the start of our extension + if (startDot === -1) + { startDot = i; } + else if (preDotState !== 1) + { preDotState = 1; } + } + else if (startDot !== -1) { + // We saw a non-dot and non-path separator before our dot, so we should + // have a good chance at having a non-empty extension + preDotState = -1; + } + } + if (startDot === -1 || end === -1 + // We saw a non-dot character immediately before the dot + || preDotState === 0 + // The (right-most) trimmed path component is exactly '..' + // eslint-disable-next-line no-mixed-operators + || preDotState === 1 && startDot === end - 1 && startDot === startPart + 1) { + if (end !== -1) { + if (startPart === 0 && isAbsolute) + { ret.base = ret.name = path.slice(1, end); } + else + { ret.base = ret.name = path.slice(startPart, end); } + } + } + else { + if (startPart === 0 && isAbsolute) { + ret.name = path.slice(1, startDot); + ret.base = path.slice(1, end); + } + else { + ret.name = path.slice(startPart, startDot); + ret.base = path.slice(startPart, end); + } + ret.ext = path.slice(startDot, end); + } + ret.dir = this.dirname(path); + return ret; + }, + sep: '/', + delimiter: ':' + }; + + /** + * The prefix that denotes a URL is for a retina asset. + * @static + * @name RETINA_PREFIX + * @memberof PIXI.settings + * @type {RegExp} + * @default /@([0-9\.]+)x/ + * @example `@2x` + */ + settings$1.RETINA_PREFIX = /@([0-9\.]+)x/; + /** + * Should the `failIfMajorPerformanceCaveat` flag be enabled as a context option used in the `isWebGLSupported` function. + * If set to true, a WebGL renderer can fail to be created if the browser thinks there could be performance issues when + * using WebGL. + * + * In PixiJS v6 this has changed from true to false by default, to allow WebGL to work in as many scenarios as possible. + * However, some users may have a poor experience, for example, if a user has a gpu or driver version blacklisted by the + * browser. + * + * If your application requires high performance rendering, you may wish to set this to false. + * We recommend one of two options if you decide to set this flag to false: + * + * 1: Use the `pixi.js-legacy` package, which includes a Canvas renderer as a fallback in case high performance WebGL is + * not supported. + * + * 2: Call `isWebGLSupported` (which if found in the PIXI.utils package) in your code before attempting to create a PixiJS + * renderer, and show an error message to the user if the function returns false, explaining that their device & browser + * combination does not support high performance WebGL. + * This is a much better strategy than trying to create a PixiJS renderer and finding it then fails. + * @static + * @name FAIL_IF_MAJOR_PERFORMANCE_CAVEAT + * @memberof PIXI.settings + * @type {boolean} + * @default false + */ + settings$1.FAIL_IF_MAJOR_PERFORMANCE_CAVEAT = false; + + var saidHello = false; + var VERSION$1 = '6.5.3'; + /** + * Skips the hello message of renderers that are created after this is run. + * @function skipHello + * @memberof PIXI.utils + */ + function skipHello() { + saidHello = true; + } + /** + * Logs out the version and renderer information for this running instance of PIXI. + * If you don't want to see this message you can run `PIXI.utils.skipHello()` before + * creating your renderer. Keep in mind that doing that will forever make you a jerk face. + * @static + * @function sayHello + * @memberof PIXI.utils + * @param {string} type - The string renderer type to log. + */ + function sayHello(type) { + var _a; + if (saidHello) { + return; + } + if (settings$1.ADAPTER.getNavigator().userAgent.toLowerCase().indexOf('chrome') > -1) { + var args = [ + "\n %c %c %c PixiJS " + VERSION$1 + " - \u2730 " + type + " \u2730 %c %c http://www.pixijs.com/ %c %c \u2665%c\u2665%c\u2665 \n\n", + 'background: #ff66a5; padding:5px 0;', + 'background: #ff66a5; padding:5px 0;', + 'color: #ff66a5; background: #030307; padding:5px 0;', + 'background: #ff66a5; padding:5px 0;', + 'background: #ffc3dc; padding:5px 0;', + 'background: #ff66a5; padding:5px 0;', + 'color: #ff2424; background: #fff; padding:5px 0;', + 'color: #ff2424; background: #fff; padding:5px 0;', + 'color: #ff2424; background: #fff; padding:5px 0;' ]; + (_a = globalThis.console).log.apply(_a, args); + } + else if (globalThis.console) { + globalThis.console.log("PixiJS " + VERSION$1 + " - " + type + " - http://www.pixijs.com/"); + } + saidHello = true; + } + + var supported; + /** + * Helper for checking for WebGL support. + * @memberof PIXI.utils + * @function isWebGLSupported + * @returns {boolean} Is WebGL supported. + */ + function isWebGLSupported() { + if (typeof supported === 'undefined') { + supported = (function supported() { + var contextOptions = { + stencil: true, + failIfMajorPerformanceCaveat: settings$1.FAIL_IF_MAJOR_PERFORMANCE_CAVEAT, + }; + try { + if (!settings$1.ADAPTER.getWebGLRenderingContext()) { + return false; + } + var canvas = settings$1.ADAPTER.createCanvas(); + var gl = (canvas.getContext('webgl', contextOptions) + || canvas.getContext('experimental-webgl', contextOptions)); + var success = !!(gl && gl.getContextAttributes().stencil); + if (gl) { + var loseContext = gl.getExtension('WEBGL_lose_context'); + if (loseContext) { + loseContext.loseContext(); + } + } + gl = null; + return success; + } + catch (e) { + return false; + } + })(); + } + return supported; + } + + var aliceblue = "#f0f8ff"; + var antiquewhite = "#faebd7"; + var aqua = "#00ffff"; + var aquamarine = "#7fffd4"; + var azure = "#f0ffff"; + var beige = "#f5f5dc"; + var bisque = "#ffe4c4"; + var black = "#000000"; + var blanchedalmond = "#ffebcd"; + var blue = "#0000ff"; + var blueviolet = "#8a2be2"; + var brown = "#a52a2a"; + var burlywood = "#deb887"; + var cadetblue = "#5f9ea0"; + var chartreuse = "#7fff00"; + var chocolate = "#d2691e"; + var coral = "#ff7f50"; + var cornflowerblue = "#6495ed"; + var cornsilk = "#fff8dc"; + var crimson = "#dc143c"; + var cyan = "#00ffff"; + var darkblue = "#00008b"; + var darkcyan = "#008b8b"; + var darkgoldenrod = "#b8860b"; + var darkgray = "#a9a9a9"; + var darkgreen = "#006400"; + var darkgrey = "#a9a9a9"; + var darkkhaki = "#bdb76b"; + var darkmagenta = "#8b008b"; + var darkolivegreen = "#556b2f"; + var darkorange = "#ff8c00"; + var darkorchid = "#9932cc"; + var darkred = "#8b0000"; + var darksalmon = "#e9967a"; + var darkseagreen = "#8fbc8f"; + var darkslateblue = "#483d8b"; + var darkslategray = "#2f4f4f"; + var darkslategrey = "#2f4f4f"; + var darkturquoise = "#00ced1"; + var darkviolet = "#9400d3"; + var deeppink = "#ff1493"; + var deepskyblue = "#00bfff"; + var dimgray = "#696969"; + var dimgrey = "#696969"; + var dodgerblue = "#1e90ff"; + var firebrick = "#b22222"; + var floralwhite = "#fffaf0"; + var forestgreen = "#228b22"; + var fuchsia = "#ff00ff"; + var gainsboro = "#dcdcdc"; + var ghostwhite = "#f8f8ff"; + var goldenrod = "#daa520"; + var gold = "#ffd700"; + var gray = "#808080"; + var green = "#008000"; + var greenyellow = "#adff2f"; + var grey = "#808080"; + var honeydew = "#f0fff0"; + var hotpink = "#ff69b4"; + var indianred = "#cd5c5c"; + var indigo = "#4b0082"; + var ivory = "#fffff0"; + var khaki = "#f0e68c"; + var lavenderblush = "#fff0f5"; + var lavender = "#e6e6fa"; + var lawngreen = "#7cfc00"; + var lemonchiffon = "#fffacd"; + var lightblue = "#add8e6"; + var lightcoral = "#f08080"; + var lightcyan = "#e0ffff"; + var lightgoldenrodyellow = "#fafad2"; + var lightgray = "#d3d3d3"; + var lightgreen = "#90ee90"; + var lightgrey = "#d3d3d3"; + var lightpink = "#ffb6c1"; + var lightsalmon = "#ffa07a"; + var lightseagreen = "#20b2aa"; + var lightskyblue = "#87cefa"; + var lightslategray = "#778899"; + var lightslategrey = "#778899"; + var lightsteelblue = "#b0c4de"; + var lightyellow = "#ffffe0"; + var lime = "#00ff00"; + var limegreen = "#32cd32"; + var linen = "#faf0e6"; + var magenta = "#ff00ff"; + var maroon = "#800000"; + var mediumaquamarine = "#66cdaa"; + var mediumblue = "#0000cd"; + var mediumorchid = "#ba55d3"; + var mediumpurple = "#9370db"; + var mediumseagreen = "#3cb371"; + var mediumslateblue = "#7b68ee"; + var mediumspringgreen = "#00fa9a"; + var mediumturquoise = "#48d1cc"; + var mediumvioletred = "#c71585"; + var midnightblue = "#191970"; + var mintcream = "#f5fffa"; + var mistyrose = "#ffe4e1"; + var moccasin = "#ffe4b5"; + var navajowhite = "#ffdead"; + var navy = "#000080"; + var oldlace = "#fdf5e6"; + var olive = "#808000"; + var olivedrab = "#6b8e23"; + var orange = "#ffa500"; + var orangered = "#ff4500"; + var orchid = "#da70d6"; + var palegoldenrod = "#eee8aa"; + var palegreen = "#98fb98"; + var paleturquoise = "#afeeee"; + var palevioletred = "#db7093"; + var papayawhip = "#ffefd5"; + var peachpuff = "#ffdab9"; + var peru = "#cd853f"; + var pink = "#ffc0cb"; + var plum = "#dda0dd"; + var powderblue = "#b0e0e6"; + var purple = "#800080"; + var rebeccapurple = "#663399"; + var red = "#ff0000"; + var rosybrown = "#bc8f8f"; + var royalblue = "#4169e1"; + var saddlebrown = "#8b4513"; + var salmon = "#fa8072"; + var sandybrown = "#f4a460"; + var seagreen = "#2e8b57"; + var seashell = "#fff5ee"; + var sienna = "#a0522d"; + var silver = "#c0c0c0"; + var skyblue = "#87ceeb"; + var slateblue = "#6a5acd"; + var slategray = "#708090"; + var slategrey = "#708090"; + var snow = "#fffafa"; + var springgreen = "#00ff7f"; + var steelblue = "#4682b4"; + var tan = "#d2b48c"; + var teal = "#008080"; + var thistle = "#d8bfd8"; + var tomato = "#ff6347"; + var turquoise = "#40e0d0"; + var violet = "#ee82ee"; + var wheat = "#f5deb3"; + var white = "#ffffff"; + var whitesmoke = "#f5f5f5"; + var yellow = "#ffff00"; + var yellowgreen = "#9acd32"; + var cssColorNames = { + aliceblue: aliceblue, + antiquewhite: antiquewhite, + aqua: aqua, + aquamarine: aquamarine, + azure: azure, + beige: beige, + bisque: bisque, + black: black, + blanchedalmond: blanchedalmond, + blue: blue, + blueviolet: blueviolet, + brown: brown, + burlywood: burlywood, + cadetblue: cadetblue, + chartreuse: chartreuse, + chocolate: chocolate, + coral: coral, + cornflowerblue: cornflowerblue, + cornsilk: cornsilk, + crimson: crimson, + cyan: cyan, + darkblue: darkblue, + darkcyan: darkcyan, + darkgoldenrod: darkgoldenrod, + darkgray: darkgray, + darkgreen: darkgreen, + darkgrey: darkgrey, + darkkhaki: darkkhaki, + darkmagenta: darkmagenta, + darkolivegreen: darkolivegreen, + darkorange: darkorange, + darkorchid: darkorchid, + darkred: darkred, + darksalmon: darksalmon, + darkseagreen: darkseagreen, + darkslateblue: darkslateblue, + darkslategray: darkslategray, + darkslategrey: darkslategrey, + darkturquoise: darkturquoise, + darkviolet: darkviolet, + deeppink: deeppink, + deepskyblue: deepskyblue, + dimgray: dimgray, + dimgrey: dimgrey, + dodgerblue: dodgerblue, + firebrick: firebrick, + floralwhite: floralwhite, + forestgreen: forestgreen, + fuchsia: fuchsia, + gainsboro: gainsboro, + ghostwhite: ghostwhite, + goldenrod: goldenrod, + gold: gold, + gray: gray, + green: green, + greenyellow: greenyellow, + grey: grey, + honeydew: honeydew, + hotpink: hotpink, + indianred: indianred, + indigo: indigo, + ivory: ivory, + khaki: khaki, + lavenderblush: lavenderblush, + lavender: lavender, + lawngreen: lawngreen, + lemonchiffon: lemonchiffon, + lightblue: lightblue, + lightcoral: lightcoral, + lightcyan: lightcyan, + lightgoldenrodyellow: lightgoldenrodyellow, + lightgray: lightgray, + lightgreen: lightgreen, + lightgrey: lightgrey, + lightpink: lightpink, + lightsalmon: lightsalmon, + lightseagreen: lightseagreen, + lightskyblue: lightskyblue, + lightslategray: lightslategray, + lightslategrey: lightslategrey, + lightsteelblue: lightsteelblue, + lightyellow: lightyellow, + lime: lime, + limegreen: limegreen, + linen: linen, + magenta: magenta, + maroon: maroon, + mediumaquamarine: mediumaquamarine, + mediumblue: mediumblue, + mediumorchid: mediumorchid, + mediumpurple: mediumpurple, + mediumseagreen: mediumseagreen, + mediumslateblue: mediumslateblue, + mediumspringgreen: mediumspringgreen, + mediumturquoise: mediumturquoise, + mediumvioletred: mediumvioletred, + midnightblue: midnightblue, + mintcream: mintcream, + mistyrose: mistyrose, + moccasin: moccasin, + navajowhite: navajowhite, + navy: navy, + oldlace: oldlace, + olive: olive, + olivedrab: olivedrab, + orange: orange, + orangered: orangered, + orchid: orchid, + palegoldenrod: palegoldenrod, + palegreen: palegreen, + paleturquoise: paleturquoise, + palevioletred: palevioletred, + papayawhip: papayawhip, + peachpuff: peachpuff, + peru: peru, + pink: pink, + plum: plum, + powderblue: powderblue, + purple: purple, + rebeccapurple: rebeccapurple, + red: red, + rosybrown: rosybrown, + royalblue: royalblue, + saddlebrown: saddlebrown, + salmon: salmon, + sandybrown: sandybrown, + seagreen: seagreen, + seashell: seashell, + sienna: sienna, + silver: silver, + skyblue: skyblue, + slateblue: slateblue, + slategray: slategray, + slategrey: slategrey, + snow: snow, + springgreen: springgreen, + steelblue: steelblue, + tan: tan, + teal: teal, + thistle: thistle, + tomato: tomato, + turquoise: turquoise, + violet: violet, + wheat: wheat, + white: white, + whitesmoke: whitesmoke, + yellow: yellow, + yellowgreen: yellowgreen + }; + + /** + * Converts a hexadecimal color number to an [R, G, B] array of normalized floats (numbers from 0.0 to 1.0). + * @example + * PIXI.utils.hex2rgb(0xffffff); // returns [1, 1, 1] + * @memberof PIXI.utils + * @function hex2rgb + * @param {number} hex - The hexadecimal number to convert + * @param {number[]} [out=[]] - If supplied, this array will be used rather than returning a new one + * @returns {number[]} An array representing the [R, G, B] of the color where all values are floats. + */ + function hex2rgb(hex, out) { + if (out === void 0) { out = []; } + out[0] = ((hex >> 16) & 0xFF) / 255; + out[1] = ((hex >> 8) & 0xFF) / 255; + out[2] = (hex & 0xFF) / 255; + return out; + } + /** + * Converts a hexadecimal color number to a string. + * @example + * PIXI.utils.hex2string(0xffffff); // returns "#ffffff" + * @memberof PIXI.utils + * @function hex2string + * @param {number} hex - Number in hex (e.g., `0xffffff`) + * @returns {string} The string color (e.g., `"#ffffff"`). + */ + function hex2string(hex) { + var hexString = hex.toString(16); + hexString = '000000'.substring(0, 6 - hexString.length) + hexString; + return "#" + hexString; + } + /** + * Converts a string to a hexadecimal color number. + * It can handle: + * hex strings starting with #: "#ffffff" + * hex strings starting with 0x: "0xffffff" + * hex strings without prefix: "ffffff" + * css colors: "black" + * @example + * PIXI.utils.string2hex("#ffffff"); // returns 0xffffff + * @memberof PIXI.utils + * @function string2hex + * @param {string} string - The string color (e.g., `"#ffffff"`) + * @returns {number} Number in hexadecimal. + */ + function string2hex(string) { + if (typeof string === 'string') { + string = cssColorNames[string.toLowerCase()] || string; + if (string[0] === '#') { + string = string.slice(1); + } + } + return parseInt(string, 16); + } + /** + * Converts a color as an [R, G, B] array of normalized floats to a hexadecimal number. + * @example + * PIXI.utils.rgb2hex([1, 1, 1]); // returns 0xffffff + * @memberof PIXI.utils + * @function rgb2hex + * @param {number[]} rgb - Array of numbers where all values are normalized floats from 0.0 to 1.0. + * @returns {number} Number in hexadecimal. + */ + function rgb2hex(rgb) { + return (((rgb[0] * 255) << 16) + ((rgb[1] * 255) << 8) + (rgb[2] * 255 | 0)); + } + + /** + * Corrects PixiJS blend, takes premultiplied alpha into account + * @memberof PIXI.utils + * @function mapPremultipliedBlendModes + * @private + * @returns {Array} Mapped modes. + */ + function mapPremultipliedBlendModes$1() { + var pm = []; + var npm = []; + for (var i = 0; i < 32; i++) { + pm[i] = i; + npm[i] = i; + } + pm[exports.BLEND_MODES.NORMAL_NPM] = exports.BLEND_MODES.NORMAL; + pm[exports.BLEND_MODES.ADD_NPM] = exports.BLEND_MODES.ADD; + pm[exports.BLEND_MODES.SCREEN_NPM] = exports.BLEND_MODES.SCREEN; + npm[exports.BLEND_MODES.NORMAL] = exports.BLEND_MODES.NORMAL_NPM; + npm[exports.BLEND_MODES.ADD] = exports.BLEND_MODES.ADD_NPM; + npm[exports.BLEND_MODES.SCREEN] = exports.BLEND_MODES.SCREEN_NPM; + var array = []; + array.push(npm); + array.push(pm); + return array; + } + /** + * maps premultiply flag and blendMode to adjusted blendMode + * @memberof PIXI.utils + * @constant premultiplyBlendMode + * @type {Array} + */ + var premultiplyBlendMode = mapPremultipliedBlendModes$1(); + /** + * changes blendMode according to texture format + * @memberof PIXI.utils + * @function correctBlendMode + * @param {number} blendMode - supposed blend mode + * @param {boolean} premultiplied - whether source is premultiplied + * @returns {number} true blend mode for this texture + */ + function correctBlendMode(blendMode, premultiplied) { + return premultiplyBlendMode[premultiplied ? 1 : 0][blendMode]; + } + /** + * combines rgb and alpha to out array + * @memberof PIXI.utils + * @function premultiplyRgba + * @param {Float32Array|number[]} rgb - input rgb + * @param {number} alpha - alpha param + * @param {Float32Array} [out] - output + * @param {boolean} [premultiply=true] - do premultiply it + * @returns {Float32Array} vec4 rgba + */ + function premultiplyRgba(rgb, alpha, out, premultiply) { + out = out || new Float32Array(4); + if (premultiply || premultiply === undefined) { + out[0] = rgb[0] * alpha; + out[1] = rgb[1] * alpha; + out[2] = rgb[2] * alpha; + } + else { + out[0] = rgb[0]; + out[1] = rgb[1]; + out[2] = rgb[2]; + } + out[3] = alpha; + return out; + } + /** + * premultiplies tint + * @memberof PIXI.utils + * @function premultiplyTint + * @param {number} tint - integer RGB + * @param {number} alpha - floating point alpha (0.0-1.0) + * @returns {number} tint multiplied by alpha + */ + function premultiplyTint(tint, alpha) { + if (alpha === 1.0) { + return (alpha * 255 << 24) + tint; + } + if (alpha === 0.0) { + return 0; + } + var R = ((tint >> 16) & 0xFF); + var G = ((tint >> 8) & 0xFF); + var B = (tint & 0xFF); + R = ((R * alpha) + 0.5) | 0; + G = ((G * alpha) + 0.5) | 0; + B = ((B * alpha) + 0.5) | 0; + return (alpha * 255 << 24) + (R << 16) + (G << 8) + B; + } + /** + * converts integer tint and float alpha to vec4 form, premultiplies by default + * @memberof PIXI.utils + * @function premultiplyTintToRgba + * @param {number} tint - input tint + * @param {number} alpha - alpha param + * @param {Float32Array} [out] - output + * @param {boolean} [premultiply=true] - do premultiply it + * @returns {Float32Array} vec4 rgba + */ + function premultiplyTintToRgba(tint, alpha, out, premultiply) { + out = out || new Float32Array(4); + out[0] = ((tint >> 16) & 0xFF) / 255.0; + out[1] = ((tint >> 8) & 0xFF) / 255.0; + out[2] = (tint & 0xFF) / 255.0; + if (premultiply || premultiply === undefined) { + out[0] *= alpha; + out[1] *= alpha; + out[2] *= alpha; + } + out[3] = alpha; + return out; + } + + /** + * Generic Mask Stack data structure + * @memberof PIXI.utils + * @function createIndicesForQuads + * @param {number} size - Number of quads + * @param {Uint16Array|Uint32Array} [outBuffer] - Buffer for output, length has to be `6 * size` + * @returns {Uint16Array|Uint32Array} - Resulting index buffer + */ + function createIndicesForQuads(size, outBuffer) { + if (outBuffer === void 0) { outBuffer = null; } + // the total number of indices in our array, there are 6 points per quad. + var totalIndices = size * 6; + outBuffer = outBuffer || new Uint16Array(totalIndices); + if (outBuffer.length !== totalIndices) { + throw new Error("Out buffer length is incorrect, got " + outBuffer.length + " and expected " + totalIndices); + } + // fill the indices with the quads to draw + for (var i = 0, j = 0; i < totalIndices; i += 6, j += 4) { + outBuffer[i + 0] = j + 0; + outBuffer[i + 1] = j + 1; + outBuffer[i + 2] = j + 2; + outBuffer[i + 3] = j + 0; + outBuffer[i + 4] = j + 2; + outBuffer[i + 5] = j + 3; + } + return outBuffer; + } + + function getBufferType(array) { + if (array.BYTES_PER_ELEMENT === 4) { + if (array instanceof Float32Array) { + return 'Float32Array'; + } + else if (array instanceof Uint32Array) { + return 'Uint32Array'; + } + return 'Int32Array'; + } + else if (array.BYTES_PER_ELEMENT === 2) { + if (array instanceof Uint16Array) { + return 'Uint16Array'; + } + } + else if (array.BYTES_PER_ELEMENT === 1) { + if (array instanceof Uint8Array) { + return 'Uint8Array'; + } + } + // TODO map out the rest of the array elements! + return null; + } + + /* eslint-disable object-shorthand */ + var map$2 = { Float32Array: Float32Array, Uint32Array: Uint32Array, Int32Array: Int32Array, Uint8Array: Uint8Array }; + function interleaveTypedArrays$1(arrays, sizes) { + var outSize = 0; + var stride = 0; + var views = {}; + for (var i = 0; i < arrays.length; i++) { + stride += sizes[i]; + outSize += arrays[i].length; + } + var buffer = new ArrayBuffer(outSize * 4); + var out = null; + var littleOffset = 0; + for (var i = 0; i < arrays.length; i++) { + var size = sizes[i]; + var array = arrays[i]; + /* + @todo This is unsafe casting but consistent with how the code worked previously. Should it stay this way + or should and `getBufferTypeUnsafe` function be exposed that throws an Error if unsupported type is passed? + */ + var type = getBufferType(array); + if (!views[type]) { + views[type] = new map$2[type](buffer); + } + out = views[type]; + for (var j = 0; j < array.length; j++) { + var indexStart = ((j / size | 0) * stride) + littleOffset; + var index = j % size; + out[indexStart + index] = array[j]; + } + littleOffset += size; + } + return new Float32Array(buffer); + } + + // Taken from the bit-twiddle package + /** + * Rounds to next power of two. + * @function nextPow2 + * @memberof PIXI.utils + * @param {number} v - input value + * @returns {number} - next rounded power of two + */ + function nextPow2(v) { + v += v === 0 ? 1 : 0; + --v; + v |= v >>> 1; + v |= v >>> 2; + v |= v >>> 4; + v |= v >>> 8; + v |= v >>> 16; + return v + 1; + } + /** + * Checks if a number is a power of two. + * @function isPow2 + * @memberof PIXI.utils + * @param {number} v - input value + * @returns {boolean} `true` if value is power of two + */ + function isPow2(v) { + return !(v & (v - 1)) && (!!v); + } + /** + * Computes ceil of log base 2 + * @function log2 + * @memberof PIXI.utils + * @param {number} v - input value + * @returns {number} logarithm base 2 + */ + function log2(v) { + var r = (v > 0xFFFF ? 1 : 0) << 4; + v >>>= r; + var shift = (v > 0xFF ? 1 : 0) << 3; + v >>>= shift; + r |= shift; + shift = (v > 0xF ? 1 : 0) << 2; + v >>>= shift; + r |= shift; + shift = (v > 0x3 ? 1 : 0) << 1; + v >>>= shift; + r |= shift; + return r | (v >> 1); + } + + /** + * Remove items from a javascript array without generating garbage + * @function removeItems + * @memberof PIXI.utils + * @param {Array} arr - Array to remove elements from + * @param {number} startIdx - starting index + * @param {number} removeCount - how many to remove + */ + function removeItems(arr, startIdx, removeCount) { + var length = arr.length; + var i; + if (startIdx >= length || removeCount === 0) { + return; + } + removeCount = (startIdx + removeCount > length ? length - startIdx : removeCount); + var len = length - removeCount; + for (i = startIdx; i < len; ++i) { + arr[i] = arr[i + removeCount]; + } + arr.length = len; + } + + /** + * Returns sign of number + * @memberof PIXI.utils + * @function sign + * @param {number} n - the number to check the sign of + * @returns {number} 0 if `n` is 0, -1 if `n` is negative, 1 if `n` is positive + */ + function sign(n) { + if (n === 0) + { return 0; } + return n < 0 ? -1 : 1; + } + + var nextUid = 0; + /** + * Gets the next unique identifier + * @memberof PIXI.utils + * @function uid + * @returns {number} The next unique identifier to use. + */ + function uid() { + return ++nextUid; + } + + // A map of warning messages already fired + var warnings$1 = {}; + /** + * Helper for warning developers about deprecated features & settings. + * A stack track for warnings is given; useful for tracking-down where + * deprecated methods/properties/classes are being used within the code. + * @memberof PIXI.utils + * @function deprecation + * @param {string} version - The version where the feature became deprecated + * @param {string} message - Message should include what is deprecated, where, and the new solution + * @param {number} [ignoreDepth=3] - The number of steps to ignore at the top of the error stack + * this is mostly to ignore internal deprecation calls. + */ + function deprecation$1(version, message, ignoreDepth) { + if (ignoreDepth === void 0) { ignoreDepth = 3; } + // Ignore duplicat + if (warnings$1[message]) { + return; + } + /* eslint-disable no-console */ + var stack = new Error().stack; + // Handle IE < 10 and Safari < 6 + if (typeof stack === 'undefined') { + console.warn('PixiJS Deprecation Warning: ', message + "\nDeprecated since v" + version); + } + else { + // chop off the stack trace which includes PixiJS internal calls + stack = stack.split('\n').splice(ignoreDepth).join('\n'); + if (console.groupCollapsed) { + console.groupCollapsed('%cPixiJS Deprecation Warning: %c%s', 'color:#614108;background:#fffbe6', 'font-weight:normal;color:#614108;background:#fffbe6', message + "\nDeprecated since v" + version); + console.warn(stack); + console.groupEnd(); + } + else { + console.warn('PixiJS Deprecation Warning: ', message + "\nDeprecated since v" + version); + console.warn(stack); + } + } + /* eslint-enable no-console */ + warnings$1[message] = true; + } + + /** + * @todo Describe property usage + * @static + * @name ProgramCache + * @memberof PIXI.utils + * @type {object} + */ + var ProgramCache = {}; + /** + * @todo Describe property usage + * @static + * @name TextureCache + * @memberof PIXI.utils + * @type {object} + */ + var TextureCache = Object.create(null); + /** + * @todo Describe property usage + * @static + * @name BaseTextureCache + * @memberof PIXI.utils + * @type {object} + */ + var BaseTextureCache = Object.create(null); + /** + * Destroys all texture in the cache + * @memberof PIXI.utils + * @function destroyTextureCache + */ + function destroyTextureCache() { + var key; + for (key in TextureCache) { + TextureCache[key].destroy(); + } + for (key in BaseTextureCache) { + BaseTextureCache[key].destroy(); + } + } + /** + * Removes all textures from cache, but does not destroy them + * @memberof PIXI.utils + * @function clearTextureCache + */ + function clearTextureCache() { + var key; + for (key in TextureCache) { + delete TextureCache[key]; + } + for (key in BaseTextureCache) { + delete BaseTextureCache[key]; + } + } + + /** + * Creates a Canvas element of the given size to be used as a target for rendering to. + * @class + * @memberof PIXI.utils + */ + var CanvasRenderTarget = /** @class */ (function () { + /** + * @param width - the width for the newly created canvas + * @param height - the height for the newly created canvas + * @param {number} [resolution=PIXI.settings.RESOLUTION] - The resolution / device pixel ratio of the canvas + */ + function CanvasRenderTarget(width, height, resolution) { + this.canvas = settings$1.ADAPTER.createCanvas(); + this.context = this.canvas.getContext('2d'); + this.resolution = resolution || settings$1.RESOLUTION; + this.resize(width, height); + } + /** + * Clears the canvas that was created by the CanvasRenderTarget class. + * @private + */ + CanvasRenderTarget.prototype.clear = function () { + this.context.setTransform(1, 0, 0, 1, 0, 0); + this.context.clearRect(0, 0, this.canvas.width, this.canvas.height); + }; + /** + * Resizes the canvas to the specified width and height. + * @param desiredWidth - the desired width of the canvas + * @param desiredHeight - the desired height of the canvas + */ + CanvasRenderTarget.prototype.resize = function (desiredWidth, desiredHeight) { + this.canvas.width = Math.round(desiredWidth * this.resolution); + this.canvas.height = Math.round(desiredHeight * this.resolution); + }; + /** Destroys this canvas. */ + CanvasRenderTarget.prototype.destroy = function () { + this.context = null; + this.canvas = null; + }; + Object.defineProperty(CanvasRenderTarget.prototype, "width", { + /** + * The width of the canvas buffer in pixels. + * @member {number} + */ + get: function () { + return this.canvas.width; + }, + set: function (val) { + this.canvas.width = Math.round(val); + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(CanvasRenderTarget.prototype, "height", { + /** + * The height of the canvas buffer in pixels. + * @member {number} + */ + get: function () { + return this.canvas.height; + }, + set: function (val) { + this.canvas.height = Math.round(val); + }, + enumerable: false, + configurable: true + }); + return CanvasRenderTarget; + }()); + + /** + * Trim transparent borders from a canvas + * @memberof PIXI.utils + * @function trimCanvas + * @param {HTMLCanvasElement} canvas - the canvas to trim + * @returns {object} Trim data + */ + function trimCanvas(canvas) { + // https://gist.github.com/remy/784508 + var width = canvas.width; + var height = canvas.height; + var context = canvas.getContext('2d'); + var imageData = context.getImageData(0, 0, width, height); + var pixels = imageData.data; + var len = pixels.length; + var bound = { + top: null, + left: null, + right: null, + bottom: null, + }; + var data = null; + var i; + var x; + var y; + for (i = 0; i < len; i += 4) { + if (pixels[i + 3] !== 0) { + x = (i / 4) % width; + y = ~~((i / 4) / width); + if (bound.top === null) { + bound.top = y; + } + if (bound.left === null) { + bound.left = x; + } + else if (x < bound.left) { + bound.left = x; + } + if (bound.right === null) { + bound.right = x + 1; + } + else if (bound.right < x) { + bound.right = x + 1; + } + if (bound.bottom === null) { + bound.bottom = y; + } + else if (bound.bottom < y) { + bound.bottom = y; + } + } + } + if (bound.top !== null) { + width = bound.right - bound.left; + height = bound.bottom - bound.top + 1; + data = context.getImageData(bound.left, bound.top, width, height); + } + return { + height: height, + width: width, + data: data, + }; + } + + /** + * Regexp for data URI. + * Based on: {@link https://github.com/ragingwind/data-uri-regex} + * @static + * @constant {RegExp|string} DATA_URI + * @memberof PIXI + * @example data:image/png;base64 + */ + var DATA_URI = /^\s*data:(?:([\w-]+)\/([\w+.-]+))?(?:;charset=([\w-]+))?(?:;(base64))?,(.*)/i; + + /** + * @memberof PIXI.utils + * @interface DecomposedDataUri + */ + /** + * type, eg. `image` + * @memberof PIXI.utils.DecomposedDataUri# + * @member {string} mediaType + */ + /** + * Sub type, eg. `png` + * @memberof PIXI.utils.DecomposedDataUri# + * @member {string} subType + */ + /** + * @memberof PIXI.utils.DecomposedDataUri# + * @member {string} charset + */ + /** + * Data encoding, eg. `base64` + * @memberof PIXI.utils.DecomposedDataUri# + * @member {string} encoding + */ + /** + * The actual data + * @memberof PIXI.utils.DecomposedDataUri# + * @member {string} data + */ + /** + * Split a data URI into components. Returns undefined if + * parameter `dataUri` is not a valid data URI. + * @memberof PIXI.utils + * @function decomposeDataUri + * @param {string} dataUri - the data URI to check + * @returns {PIXI.utils.DecomposedDataUri|undefined} The decomposed data uri or undefined + */ + function decomposeDataUri(dataUri) { + var dataUriMatch = DATA_URI.exec(dataUri); + if (dataUriMatch) { + return { + mediaType: dataUriMatch[1] ? dataUriMatch[1].toLowerCase() : undefined, + subType: dataUriMatch[2] ? dataUriMatch[2].toLowerCase() : undefined, + charset: dataUriMatch[3] ? dataUriMatch[3].toLowerCase() : undefined, + encoding: dataUriMatch[4] ? dataUriMatch[4].toLowerCase() : undefined, + data: dataUriMatch[5], + }; + } + return undefined; + } + + var tempAnchor$1; + /** + * Sets the `crossOrigin` property for this resource based on if the url + * for this resource is cross-origin. If crossOrigin was manually set, this + * function does nothing. + * Nipped from the resource loader! + * @ignore + * @param {string} url - The url to test. + * @param {object} [loc=window.location] - The location object to test against. + * @returns {string} The crossOrigin value to use (or empty string for none). + */ + function determineCrossOrigin(url$1, loc) { + if (loc === void 0) { loc = globalThis.location; } + // data: and javascript: urls are considered same-origin + if (url$1.indexOf('data:') === 0) { + return ''; + } + // default is window.location + loc = loc || globalThis.location; + if (!tempAnchor$1) { + tempAnchor$1 = document.createElement('a'); + } + // let the browser determine the full href for the url of this resource and then + // parse with the node url lib, we can't use the properties of the anchor element + // because they don't work in IE9 :( + tempAnchor$1.href = url$1; + var parsedUrl = url.parse(tempAnchor$1.href); + var samePort = (!parsedUrl.port && loc.port === '') || (parsedUrl.port === loc.port); + // if cross origin + if (parsedUrl.hostname !== loc.hostname || !samePort || parsedUrl.protocol !== loc.protocol) { + return 'anonymous'; + } + return ''; + } + + /** + * get the resolution / device pixel ratio of an asset by looking for the prefix + * used by spritesheets and image urls + * @memberof PIXI.utils + * @function getResolutionOfUrl + * @param {string} url - the image path + * @param {number} [defaultValue=1] - the defaultValue if no filename prefix is set. + * @returns {number} resolution / device pixel ratio of an asset + */ + function getResolutionOfUrl(url, defaultValue) { + var resolution = settings$1.RETINA_PREFIX.exec(url); + if (resolution) { + return parseFloat(resolution[1]); + } + return defaultValue !== undefined ? defaultValue : 1; + } + + var utils = { + __proto__: null, + BaseTextureCache: BaseTextureCache, + CanvasRenderTarget: CanvasRenderTarget, + DATA_URI: DATA_URI, + ProgramCache: ProgramCache, + TextureCache: TextureCache, + clearTextureCache: clearTextureCache, + correctBlendMode: correctBlendMode, + createIndicesForQuads: createIndicesForQuads, + decomposeDataUri: decomposeDataUri, + deprecation: deprecation$1, + destroyTextureCache: destroyTextureCache, + determineCrossOrigin: determineCrossOrigin, + getBufferType: getBufferType, + getResolutionOfUrl: getResolutionOfUrl, + hex2rgb: hex2rgb, + hex2string: hex2string, + interleaveTypedArrays: interleaveTypedArrays$1, + isPow2: isPow2, + isWebGLSupported: isWebGLSupported, + log2: log2, + nextPow2: nextPow2, + path: path, + premultiplyBlendMode: premultiplyBlendMode, + premultiplyRgba: premultiplyRgba, + premultiplyTint: premultiplyTint, + premultiplyTintToRgba: premultiplyTintToRgba, + removeItems: removeItems, + rgb2hex: rgb2hex, + sayHello: sayHello, + sign: sign, + skipHello: skipHello, + string2hex: string2hex, + trimCanvas: trimCanvas, + uid: uid, + url: url, + isMobile: isMobile$2, + EventEmitter: eventemitter3, + earcut: earcut_1 + }; + + /*! + * @pixi/math - v6.5.3 + * Compiled Fri, 09 Sep 2022 13:55:20 UTC + * + * @pixi/math is licensed under the MIT License. + * http://www.opensource.org/licenses/mit-license + */ + /** + * Two Pi. + * @static + * @member {number} + * @memberof PIXI + */ + var PI_2 = Math.PI * 2; + /** + * Conversion factor for converting radians to degrees. + * @static + * @member {number} RAD_TO_DEG + * @memberof PIXI + */ + var RAD_TO_DEG = 180 / Math.PI; + /** + * Conversion factor for converting degrees to radians. + * @static + * @member {number} + * @memberof PIXI + */ + var DEG_TO_RAD = Math.PI / 180; + /** + * Constants that identify shapes, mainly to prevent `instanceof` calls. + * @static + * @memberof PIXI + * @enum {number} + * @property {number} POLY Polygon + * @property {number} RECT Rectangle + * @property {number} CIRC Circle + * @property {number} ELIP Ellipse + * @property {number} RREC Rounded Rectangle + */ + exports.SHAPES = void 0; + (function (SHAPES) { + SHAPES[SHAPES["POLY"] = 0] = "POLY"; + SHAPES[SHAPES["RECT"] = 1] = "RECT"; + SHAPES[SHAPES["CIRC"] = 2] = "CIRC"; + SHAPES[SHAPES["ELIP"] = 3] = "ELIP"; + SHAPES[SHAPES["RREC"] = 4] = "RREC"; + })(exports.SHAPES || (exports.SHAPES = {})); + + /** + * The Point object represents a location in a two-dimensional coordinate system, where `x` represents + * the position on the horizontal axis and `y` represents the position on the vertical axis + * @class + * @memberof PIXI + * @implements {IPoint} + */ + var Point = /** @class */ (function () { + /** + * Creates a new `Point` + * @param {number} [x=0] - position of the point on the x axis + * @param {number} [y=0] - position of the point on the y axis + */ + function Point(x, y) { + if (x === void 0) { x = 0; } + if (y === void 0) { y = 0; } + /** Position of the point on the x axis */ + this.x = 0; + /** Position of the point on the y axis */ + this.y = 0; + this.x = x; + this.y = y; + } + /** + * Creates a clone of this point + * @returns A clone of this point + */ + Point.prototype.clone = function () { + return new Point(this.x, this.y); + }; + /** + * Copies `x` and `y` from the given point into this point + * @param p - The point to copy from + * @returns The point instance itself + */ + Point.prototype.copyFrom = function (p) { + this.set(p.x, p.y); + return this; + }; + /** + * Copies this point's x and y into the given point (`p`). + * @param p - The point to copy to. Can be any of type that is or extends `IPointData` + * @returns The point (`p`) with values updated + */ + Point.prototype.copyTo = function (p) { + p.set(this.x, this.y); + return p; + }; + /** + * Accepts another point (`p`) and returns `true` if the given point is equal to this point + * @param p - The point to check + * @returns Returns `true` if both `x` and `y` are equal + */ + Point.prototype.equals = function (p) { + return (p.x === this.x) && (p.y === this.y); + }; + /** + * Sets the point to a new `x` and `y` position. + * If `y` is omitted, both `x` and `y` will be set to `x`. + * @param {number} [x=0] - position of the point on the `x` axis + * @param {number} [y=x] - position of the point on the `y` axis + * @returns The point instance itself + */ + Point.prototype.set = function (x, y) { + if (x === void 0) { x = 0; } + if (y === void 0) { y = x; } + this.x = x; + this.y = y; + return this; + }; + Point.prototype.toString = function () { + return "[@pixi/math:Point x=" + this.x + " y=" + this.y + "]"; + }; + return Point; + }()); + + var tempPoints$1 = [new Point(), new Point(), new Point(), new Point()]; + /** + * Size object, contains width and height + * @memberof PIXI + * @typedef {object} ISize + * @property {number} width - Width component + * @property {number} height - Height component + */ + /** + * Rectangle object is an area defined by its position, as indicated by its top-left corner + * point (x, y) and by its width and its height. + * @memberof PIXI + */ + var Rectangle = /** @class */ (function () { + /** + * @param x - The X coordinate of the upper-left corner of the rectangle + * @param y - The Y coordinate of the upper-left corner of the rectangle + * @param width - The overall width of the rectangle + * @param height - The overall height of the rectangle + */ + function Rectangle(x, y, width, height) { + if (x === void 0) { x = 0; } + if (y === void 0) { y = 0; } + if (width === void 0) { width = 0; } + if (height === void 0) { height = 0; } + this.x = Number(x); + this.y = Number(y); + this.width = Number(width); + this.height = Number(height); + this.type = exports.SHAPES.RECT; + } + Object.defineProperty(Rectangle.prototype, "left", { + /** Returns the left edge of the rectangle. */ + get: function () { + return this.x; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(Rectangle.prototype, "right", { + /** Returns the right edge of the rectangle. */ + get: function () { + return this.x + this.width; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(Rectangle.prototype, "top", { + /** Returns the top edge of the rectangle. */ + get: function () { + return this.y; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(Rectangle.prototype, "bottom", { + /** Returns the bottom edge of the rectangle. */ + get: function () { + return this.y + this.height; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(Rectangle, "EMPTY", { + /** A constant empty rectangle. */ + get: function () { + return new Rectangle(0, 0, 0, 0); + }, + enumerable: false, + configurable: true + }); + /** + * Creates a clone of this Rectangle + * @returns a copy of the rectangle + */ + Rectangle.prototype.clone = function () { + return new Rectangle(this.x, this.y, this.width, this.height); + }; + /** + * Copies another rectangle to this one. + * @param rectangle - The rectangle to copy from. + * @returns Returns itself. + */ + Rectangle.prototype.copyFrom = function (rectangle) { + this.x = rectangle.x; + this.y = rectangle.y; + this.width = rectangle.width; + this.height = rectangle.height; + return this; + }; + /** + * Copies this rectangle to another one. + * @param rectangle - The rectangle to copy to. + * @returns Returns given parameter. + */ + Rectangle.prototype.copyTo = function (rectangle) { + rectangle.x = this.x; + rectangle.y = this.y; + rectangle.width = this.width; + rectangle.height = this.height; + return rectangle; + }; + /** + * Checks whether the x and y coordinates given are contained within this Rectangle + * @param x - The X coordinate of the point to test + * @param y - The Y coordinate of the point to test + * @returns Whether the x/y coordinates are within this Rectangle + */ + Rectangle.prototype.contains = function (x, y) { + if (this.width <= 0 || this.height <= 0) { + return false; + } + if (x >= this.x && x < this.x + this.width) { + if (y >= this.y && y < this.y + this.height) { + return true; + } + } + return false; + }; + /** + * Determines whether the `other` Rectangle transformed by `transform` intersects with `this` Rectangle object. + * Returns true only if the area of the intersection is >0, this means that Rectangles + * sharing a side are not overlapping. Another side effect is that an arealess rectangle + * (width or height equal to zero) can't intersect any other rectangle. + * @param {Rectangle} other - The Rectangle to intersect with `this`. + * @param {Matrix} transform - The transformation matrix of `other`. + * @returns {boolean} A value of `true` if the transformed `other` Rectangle intersects with `this`; otherwise `false`. + */ + Rectangle.prototype.intersects = function (other, transform) { + if (!transform) { + var x0_1 = this.x < other.x ? other.x : this.x; + var x1_1 = this.right > other.right ? other.right : this.right; + if (x1_1 <= x0_1) { + return false; + } + var y0_1 = this.y < other.y ? other.y : this.y; + var y1_1 = this.bottom > other.bottom ? other.bottom : this.bottom; + return y1_1 > y0_1; + } + var x0 = this.left; + var x1 = this.right; + var y0 = this.top; + var y1 = this.bottom; + if (x1 <= x0 || y1 <= y0) { + return false; + } + var lt = tempPoints$1[0].set(other.left, other.top); + var lb = tempPoints$1[1].set(other.left, other.bottom); + var rt = tempPoints$1[2].set(other.right, other.top); + var rb = tempPoints$1[3].set(other.right, other.bottom); + if (rt.x <= lt.x || lb.y <= lt.y) { + return false; + } + var s = Math.sign((transform.a * transform.d) - (transform.b * transform.c)); + if (s === 0) { + return false; + } + transform.apply(lt, lt); + transform.apply(lb, lb); + transform.apply(rt, rt); + transform.apply(rb, rb); + if (Math.max(lt.x, lb.x, rt.x, rb.x) <= x0 + || Math.min(lt.x, lb.x, rt.x, rb.x) >= x1 + || Math.max(lt.y, lb.y, rt.y, rb.y) <= y0 + || Math.min(lt.y, lb.y, rt.y, rb.y) >= y1) { + return false; + } + var nx = s * (lb.y - lt.y); + var ny = s * (lt.x - lb.x); + var n00 = (nx * x0) + (ny * y0); + var n10 = (nx * x1) + (ny * y0); + var n01 = (nx * x0) + (ny * y1); + var n11 = (nx * x1) + (ny * y1); + if (Math.max(n00, n10, n01, n11) <= (nx * lt.x) + (ny * lt.y) + || Math.min(n00, n10, n01, n11) >= (nx * rb.x) + (ny * rb.y)) { + return false; + } + var mx = s * (lt.y - rt.y); + var my = s * (rt.x - lt.x); + var m00 = (mx * x0) + (my * y0); + var m10 = (mx * x1) + (my * y0); + var m01 = (mx * x0) + (my * y1); + var m11 = (mx * x1) + (my * y1); + if (Math.max(m00, m10, m01, m11) <= (mx * lt.x) + (my * lt.y) + || Math.min(m00, m10, m01, m11) >= (mx * rb.x) + (my * rb.y)) { + return false; + } + return true; + }; + /** + * Pads the rectangle making it grow in all directions. + * If paddingY is omitted, both paddingX and paddingY will be set to paddingX. + * @param paddingX - The horizontal padding amount. + * @param paddingY - The vertical padding amount. + * @returns Returns itself. + */ + Rectangle.prototype.pad = function (paddingX, paddingY) { + if (paddingX === void 0) { paddingX = 0; } + if (paddingY === void 0) { paddingY = paddingX; } + this.x -= paddingX; + this.y -= paddingY; + this.width += paddingX * 2; + this.height += paddingY * 2; + return this; + }; + /** + * Fits this rectangle around the passed one. + * @param rectangle - The rectangle to fit. + * @returns Returns itself. + */ + Rectangle.prototype.fit = function (rectangle) { + var x1 = Math.max(this.x, rectangle.x); + var x2 = Math.min(this.x + this.width, rectangle.x + rectangle.width); + var y1 = Math.max(this.y, rectangle.y); + var y2 = Math.min(this.y + this.height, rectangle.y + rectangle.height); + this.x = x1; + this.width = Math.max(x2 - x1, 0); + this.y = y1; + this.height = Math.max(y2 - y1, 0); + return this; + }; + /** + * Enlarges rectangle that way its corners lie on grid + * @param resolution - resolution + * @param eps - precision + * @returns Returns itself. + */ + Rectangle.prototype.ceil = function (resolution, eps) { + if (resolution === void 0) { resolution = 1; } + if (eps === void 0) { eps = 0.001; } + var x2 = Math.ceil((this.x + this.width - eps) * resolution) / resolution; + var y2 = Math.ceil((this.y + this.height - eps) * resolution) / resolution; + this.x = Math.floor((this.x + eps) * resolution) / resolution; + this.y = Math.floor((this.y + eps) * resolution) / resolution; + this.width = x2 - this.x; + this.height = y2 - this.y; + return this; + }; + /** + * Enlarges this rectangle to include the passed rectangle. + * @param rectangle - The rectangle to include. + * @returns Returns itself. + */ + Rectangle.prototype.enlarge = function (rectangle) { + var x1 = Math.min(this.x, rectangle.x); + var x2 = Math.max(this.x + this.width, rectangle.x + rectangle.width); + var y1 = Math.min(this.y, rectangle.y); + var y2 = Math.max(this.y + this.height, rectangle.y + rectangle.height); + this.x = x1; + this.width = x2 - x1; + this.y = y1; + this.height = y2 - y1; + return this; + }; + Rectangle.prototype.toString = function () { + return "[@pixi/math:Rectangle x=" + this.x + " y=" + this.y + " width=" + this.width + " height=" + this.height + "]"; + }; + return Rectangle; + }()); + + /** + * The Circle object is used to help draw graphics and can also be used to specify a hit area for displayObjects. + * @memberof PIXI + */ + var Circle = /** @class */ (function () { + /** + * @param x - The X coordinate of the center of this circle + * @param y - The Y coordinate of the center of this circle + * @param radius - The radius of the circle + */ + function Circle(x, y, radius) { + if (x === void 0) { x = 0; } + if (y === void 0) { y = 0; } + if (radius === void 0) { radius = 0; } + this.x = x; + this.y = y; + this.radius = radius; + this.type = exports.SHAPES.CIRC; + } + /** + * Creates a clone of this Circle instance + * @returns A copy of the Circle + */ + Circle.prototype.clone = function () { + return new Circle(this.x, this.y, this.radius); + }; + /** + * Checks whether the x and y coordinates given are contained within this circle + * @param x - The X coordinate of the point to test + * @param y - The Y coordinate of the point to test + * @returns Whether the x/y coordinates are within this Circle + */ + Circle.prototype.contains = function (x, y) { + if (this.radius <= 0) { + return false; + } + var r2 = this.radius * this.radius; + var dx = (this.x - x); + var dy = (this.y - y); + dx *= dx; + dy *= dy; + return (dx + dy <= r2); + }; + /** + * Returns the framing rectangle of the circle as a Rectangle object + * @returns The framing rectangle + */ + Circle.prototype.getBounds = function () { + return new Rectangle(this.x - this.radius, this.y - this.radius, this.radius * 2, this.radius * 2); + }; + Circle.prototype.toString = function () { + return "[@pixi/math:Circle x=" + this.x + " y=" + this.y + " radius=" + this.radius + "]"; + }; + return Circle; + }()); + + /** + * The Ellipse object is used to help draw graphics and can also be used to specify a hit area for displayObjects. + * @memberof PIXI + */ + var Ellipse = /** @class */ (function () { + /** + * @param x - The X coordinate of the center of this ellipse + * @param y - The Y coordinate of the center of this ellipse + * @param halfWidth - The half width of this ellipse + * @param halfHeight - The half height of this ellipse + */ + function Ellipse(x, y, halfWidth, halfHeight) { + if (x === void 0) { x = 0; } + if (y === void 0) { y = 0; } + if (halfWidth === void 0) { halfWidth = 0; } + if (halfHeight === void 0) { halfHeight = 0; } + this.x = x; + this.y = y; + this.width = halfWidth; + this.height = halfHeight; + this.type = exports.SHAPES.ELIP; + } + /** + * Creates a clone of this Ellipse instance + * @returns {PIXI.Ellipse} A copy of the ellipse + */ + Ellipse.prototype.clone = function () { + return new Ellipse(this.x, this.y, this.width, this.height); + }; + /** + * Checks whether the x and y coordinates given are contained within this ellipse + * @param x - The X coordinate of the point to test + * @param y - The Y coordinate of the point to test + * @returns Whether the x/y coords are within this ellipse + */ + Ellipse.prototype.contains = function (x, y) { + if (this.width <= 0 || this.height <= 0) { + return false; + } + // normalize the coords to an ellipse with center 0,0 + var normx = ((x - this.x) / this.width); + var normy = ((y - this.y) / this.height); + normx *= normx; + normy *= normy; + return (normx + normy <= 1); + }; + /** + * Returns the framing rectangle of the ellipse as a Rectangle object + * @returns The framing rectangle + */ + Ellipse.prototype.getBounds = function () { + return new Rectangle(this.x - this.width, this.y - this.height, this.width, this.height); + }; + Ellipse.prototype.toString = function () { + return "[@pixi/math:Ellipse x=" + this.x + " y=" + this.y + " width=" + this.width + " height=" + this.height + "]"; + }; + return Ellipse; + }()); + + /** + * A class to define a shape via user defined coordinates. + * @memberof PIXI + */ + var Polygon = /** @class */ (function () { + /** + * @param {PIXI.IPointData[]|number[]} points - This can be an array of Points + * that form the polygon, a flat array of numbers that will be interpreted as [x,y, x,y, ...], or + * the arguments passed can be all the points of the polygon e.g. + * `new PIXI.Polygon(new PIXI.Point(), new PIXI.Point(), ...)`, or the arguments passed can be flat + * x,y values e.g. `new Polygon(x,y, x,y, x,y, ...)` where `x` and `y` are Numbers. + */ + function Polygon() { + var arguments$1 = arguments; + + var points = []; + for (var _i = 0; _i < arguments.length; _i++) { + points[_i] = arguments$1[_i]; + } + var flat = Array.isArray(points[0]) ? points[0] : points; + // if this is an array of points, convert it to a flat array of numbers + if (typeof flat[0] !== 'number') { + var p = []; + for (var i = 0, il = flat.length; i < il; i++) { + p.push(flat[i].x, flat[i].y); + } + flat = p; + } + this.points = flat; + this.type = exports.SHAPES.POLY; + this.closeStroke = true; + } + /** + * Creates a clone of this polygon. + * @returns - A copy of the polygon. + */ + Polygon.prototype.clone = function () { + var points = this.points.slice(); + var polygon = new Polygon(points); + polygon.closeStroke = this.closeStroke; + return polygon; + }; + /** + * Checks whether the x and y coordinates passed to this function are contained within this polygon. + * @param x - The X coordinate of the point to test. + * @param y - The Y coordinate of the point to test. + * @returns - Whether the x/y coordinates are within this polygon. + */ + Polygon.prototype.contains = function (x, y) { + var inside = false; + // use some raycasting to test hits + // https://github.com/substack/point-in-polygon/blob/master/index.js + var length = this.points.length / 2; + for (var i = 0, j = length - 1; i < length; j = i++) { + var xi = this.points[i * 2]; + var yi = this.points[(i * 2) + 1]; + var xj = this.points[j * 2]; + var yj = this.points[(j * 2) + 1]; + var intersect = ((yi > y) !== (yj > y)) && (x < ((xj - xi) * ((y - yi) / (yj - yi))) + xi); + if (intersect) { + inside = !inside; + } + } + return inside; + }; + Polygon.prototype.toString = function () { + return "[@pixi/math:Polygon" + + ("closeStroke=" + this.closeStroke) + + ("points=" + this.points.reduce(function (pointsDesc, currentPoint) { return pointsDesc + ", " + currentPoint; }, '') + "]"); + }; + return Polygon; + }()); + + /** + * The Rounded Rectangle object is an area that has nice rounded corners, as indicated by its + * top-left corner point (x, y) and by its width and its height and its radius. + * @memberof PIXI + */ + var RoundedRectangle = /** @class */ (function () { + /** + * @param x - The X coordinate of the upper-left corner of the rounded rectangle + * @param y - The Y coordinate of the upper-left corner of the rounded rectangle + * @param width - The overall width of this rounded rectangle + * @param height - The overall height of this rounded rectangle + * @param radius - Controls the radius of the rounded corners + */ + function RoundedRectangle(x, y, width, height, radius) { + if (x === void 0) { x = 0; } + if (y === void 0) { y = 0; } + if (width === void 0) { width = 0; } + if (height === void 0) { height = 0; } + if (radius === void 0) { radius = 20; } + this.x = x; + this.y = y; + this.width = width; + this.height = height; + this.radius = radius; + this.type = exports.SHAPES.RREC; + } + /** + * Creates a clone of this Rounded Rectangle. + * @returns - A copy of the rounded rectangle. + */ + RoundedRectangle.prototype.clone = function () { + return new RoundedRectangle(this.x, this.y, this.width, this.height, this.radius); + }; + /** + * Checks whether the x and y coordinates given are contained within this Rounded Rectangle + * @param x - The X coordinate of the point to test. + * @param y - The Y coordinate of the point to test. + * @returns - Whether the x/y coordinates are within this Rounded Rectangle. + */ + RoundedRectangle.prototype.contains = function (x, y) { + if (this.width <= 0 || this.height <= 0) { + return false; + } + if (x >= this.x && x <= this.x + this.width) { + if (y >= this.y && y <= this.y + this.height) { + var radius = Math.max(0, Math.min(this.radius, Math.min(this.width, this.height) / 2)); + if ((y >= this.y + radius && y <= this.y + this.height - radius) + || (x >= this.x + radius && x <= this.x + this.width - radius)) { + return true; + } + var dx = x - (this.x + radius); + var dy = y - (this.y + radius); + var radius2 = radius * radius; + if ((dx * dx) + (dy * dy) <= radius2) { + return true; + } + dx = x - (this.x + this.width - radius); + if ((dx * dx) + (dy * dy) <= radius2) { + return true; + } + dy = y - (this.y + this.height - radius); + if ((dx * dx) + (dy * dy) <= radius2) { + return true; + } + dx = x - (this.x + radius); + if ((dx * dx) + (dy * dy) <= radius2) { + return true; + } + } + } + return false; + }; + RoundedRectangle.prototype.toString = function () { + return "[@pixi/math:RoundedRectangle x=" + this.x + " y=" + this.y + + ("width=" + this.width + " height=" + this.height + " radius=" + this.radius + "]"); + }; + return RoundedRectangle; + }()); + + /** + * The ObservablePoint object represents a location in a two-dimensional coordinate system, where `x` represents + * the position on the horizontal axis and `y` represents the position on the vertical axis. + * + * An `ObservablePoint` is a point that triggers a callback when the point's position is changed. + * @memberof PIXI + */ + var ObservablePoint = /** @class */ (function () { + /** + * Creates a new `ObservablePoint` + * @param cb - callback function triggered when `x` and/or `y` are changed + * @param scope - owner of callback + * @param {number} [x=0] - position of the point on the x axis + * @param {number} [y=0] - position of the point on the y axis + */ + function ObservablePoint(cb, scope, x, y) { + if (x === void 0) { x = 0; } + if (y === void 0) { y = 0; } + this._x = x; + this._y = y; + this.cb = cb; + this.scope = scope; + } + /** + * Creates a clone of this point. + * The callback and scope params can be overridden otherwise they will default + * to the clone object's values. + * @override + * @param cb - The callback function triggered when `x` and/or `y` are changed + * @param scope - The owner of the callback + * @returns a copy of this observable point + */ + ObservablePoint.prototype.clone = function (cb, scope) { + if (cb === void 0) { cb = this.cb; } + if (scope === void 0) { scope = this.scope; } + return new ObservablePoint(cb, scope, this._x, this._y); + }; + /** + * Sets the point to a new `x` and `y` position. + * If `y` is omitted, both `x` and `y` will be set to `x`. + * @param {number} [x=0] - position of the point on the x axis + * @param {number} [y=x] - position of the point on the y axis + * @returns The observable point instance itself + */ + ObservablePoint.prototype.set = function (x, y) { + if (x === void 0) { x = 0; } + if (y === void 0) { y = x; } + if (this._x !== x || this._y !== y) { + this._x = x; + this._y = y; + this.cb.call(this.scope); + } + return this; + }; + /** + * Copies x and y from the given point (`p`) + * @param p - The point to copy from. Can be any of type that is or extends `IPointData` + * @returns The observable point instance itself + */ + ObservablePoint.prototype.copyFrom = function (p) { + if (this._x !== p.x || this._y !== p.y) { + this._x = p.x; + this._y = p.y; + this.cb.call(this.scope); + } + return this; + }; + /** + * Copies this point's x and y into that of the given point (`p`) + * @param p - The point to copy to. Can be any of type that is or extends `IPointData` + * @returns The point (`p`) with values updated + */ + ObservablePoint.prototype.copyTo = function (p) { + p.set(this._x, this._y); + return p; + }; + /** + * Accepts another point (`p`) and returns `true` if the given point is equal to this point + * @param p - The point to check + * @returns Returns `true` if both `x` and `y` are equal + */ + ObservablePoint.prototype.equals = function (p) { + return (p.x === this._x) && (p.y === this._y); + }; + ObservablePoint.prototype.toString = function () { + return "[@pixi/math:ObservablePoint x=" + 0 + " y=" + 0 + " scope=" + this.scope + "]"; + }; + Object.defineProperty(ObservablePoint.prototype, "x", { + /** Position of the observable point on the x axis. */ + get: function () { + return this._x; + }, + set: function (value) { + if (this._x !== value) { + this._x = value; + this.cb.call(this.scope); + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(ObservablePoint.prototype, "y", { + /** Position of the observable point on the y axis. */ + get: function () { + return this._y; + }, + set: function (value) { + if (this._y !== value) { + this._y = value; + this.cb.call(this.scope); + } + }, + enumerable: false, + configurable: true + }); + return ObservablePoint; + }()); + + /** + * The PixiJS Matrix as a class makes it a lot faster. + * + * Here is a representation of it: + * ```js + * | a | c | tx| + * | b | d | ty| + * | 0 | 0 | 1 | + * ``` + * @memberof PIXI + */ + var Matrix = /** @class */ (function () { + /** + * @param a - x scale + * @param b - y skew + * @param c - x skew + * @param d - y scale + * @param tx - x translation + * @param ty - y translation + */ + function Matrix(a, b, c, d, tx, ty) { + if (a === void 0) { a = 1; } + if (b === void 0) { b = 0; } + if (c === void 0) { c = 0; } + if (d === void 0) { d = 1; } + if (tx === void 0) { tx = 0; } + if (ty === void 0) { ty = 0; } + this.array = null; + this.a = a; + this.b = b; + this.c = c; + this.d = d; + this.tx = tx; + this.ty = ty; + } + /** + * Creates a Matrix object based on the given array. The Element to Matrix mapping order is as follows: + * + * a = array[0] + * b = array[1] + * c = array[3] + * d = array[4] + * tx = array[2] + * ty = array[5] + * @param array - The array that the matrix will be populated from. + */ + Matrix.prototype.fromArray = function (array) { + this.a = array[0]; + this.b = array[1]; + this.c = array[3]; + this.d = array[4]; + this.tx = array[2]; + this.ty = array[5]; + }; + /** + * Sets the matrix properties. + * @param a - Matrix component + * @param b - Matrix component + * @param c - Matrix component + * @param d - Matrix component + * @param tx - Matrix component + * @param ty - Matrix component + * @returns This matrix. Good for chaining method calls. + */ + Matrix.prototype.set = function (a, b, c, d, tx, ty) { + this.a = a; + this.b = b; + this.c = c; + this.d = d; + this.tx = tx; + this.ty = ty; + return this; + }; + /** + * Creates an array from the current Matrix object. + * @param transpose - Whether we need to transpose the matrix or not + * @param [out=new Float32Array(9)] - If provided the array will be assigned to out + * @returns The newly created array which contains the matrix + */ + Matrix.prototype.toArray = function (transpose, out) { + if (!this.array) { + this.array = new Float32Array(9); + } + var array = out || this.array; + if (transpose) { + array[0] = this.a; + array[1] = this.b; + array[2] = 0; + array[3] = this.c; + array[4] = this.d; + array[5] = 0; + array[6] = this.tx; + array[7] = this.ty; + array[8] = 1; + } + else { + array[0] = this.a; + array[1] = this.c; + array[2] = this.tx; + array[3] = this.b; + array[4] = this.d; + array[5] = this.ty; + array[6] = 0; + array[7] = 0; + array[8] = 1; + } + return array; + }; + /** + * Get a new position with the current transformation applied. + * Can be used to go from a child's coordinate space to the world coordinate space. (e.g. rendering) + * @param pos - The origin + * @param {PIXI.Point} [newPos] - The point that the new position is assigned to (allowed to be same as input) + * @returns {PIXI.Point} The new point, transformed through this matrix + */ + Matrix.prototype.apply = function (pos, newPos) { + newPos = (newPos || new Point()); + var x = pos.x; + var y = pos.y; + newPos.x = (this.a * x) + (this.c * y) + this.tx; + newPos.y = (this.b * x) + (this.d * y) + this.ty; + return newPos; + }; + /** + * Get a new position with the inverse of the current transformation applied. + * Can be used to go from the world coordinate space to a child's coordinate space. (e.g. input) + * @param pos - The origin + * @param {PIXI.Point} [newPos] - The point that the new position is assigned to (allowed to be same as input) + * @returns {PIXI.Point} The new point, inverse-transformed through this matrix + */ + Matrix.prototype.applyInverse = function (pos, newPos) { + newPos = (newPos || new Point()); + var id = 1 / ((this.a * this.d) + (this.c * -this.b)); + var x = pos.x; + var y = pos.y; + newPos.x = (this.d * id * x) + (-this.c * id * y) + (((this.ty * this.c) - (this.tx * this.d)) * id); + newPos.y = (this.a * id * y) + (-this.b * id * x) + (((-this.ty * this.a) + (this.tx * this.b)) * id); + return newPos; + }; + /** + * Translates the matrix on the x and y. + * @param x - How much to translate x by + * @param y - How much to translate y by + * @returns This matrix. Good for chaining method calls. + */ + Matrix.prototype.translate = function (x, y) { + this.tx += x; + this.ty += y; + return this; + }; + /** + * Applies a scale transformation to the matrix. + * @param x - The amount to scale horizontally + * @param y - The amount to scale vertically + * @returns This matrix. Good for chaining method calls. + */ + Matrix.prototype.scale = function (x, y) { + this.a *= x; + this.d *= y; + this.c *= x; + this.b *= y; + this.tx *= x; + this.ty *= y; + return this; + }; + /** + * Applies a rotation transformation to the matrix. + * @param angle - The angle in radians. + * @returns This matrix. Good for chaining method calls. + */ + Matrix.prototype.rotate = function (angle) { + var cos = Math.cos(angle); + var sin = Math.sin(angle); + var a1 = this.a; + var c1 = this.c; + var tx1 = this.tx; + this.a = (a1 * cos) - (this.b * sin); + this.b = (a1 * sin) + (this.b * cos); + this.c = (c1 * cos) - (this.d * sin); + this.d = (c1 * sin) + (this.d * cos); + this.tx = (tx1 * cos) - (this.ty * sin); + this.ty = (tx1 * sin) + (this.ty * cos); + return this; + }; + /** + * Appends the given Matrix to this Matrix. + * @param matrix - The matrix to append. + * @returns This matrix. Good for chaining method calls. + */ + Matrix.prototype.append = function (matrix) { + var a1 = this.a; + var b1 = this.b; + var c1 = this.c; + var d1 = this.d; + this.a = (matrix.a * a1) + (matrix.b * c1); + this.b = (matrix.a * b1) + (matrix.b * d1); + this.c = (matrix.c * a1) + (matrix.d * c1); + this.d = (matrix.c * b1) + (matrix.d * d1); + this.tx = (matrix.tx * a1) + (matrix.ty * c1) + this.tx; + this.ty = (matrix.tx * b1) + (matrix.ty * d1) + this.ty; + return this; + }; + /** + * Sets the matrix based on all the available properties + * @param x - Position on the x axis + * @param y - Position on the y axis + * @param pivotX - Pivot on the x axis + * @param pivotY - Pivot on the y axis + * @param scaleX - Scale on the x axis + * @param scaleY - Scale on the y axis + * @param rotation - Rotation in radians + * @param skewX - Skew on the x axis + * @param skewY - Skew on the y axis + * @returns This matrix. Good for chaining method calls. + */ + Matrix.prototype.setTransform = function (x, y, pivotX, pivotY, scaleX, scaleY, rotation, skewX, skewY) { + this.a = Math.cos(rotation + skewY) * scaleX; + this.b = Math.sin(rotation + skewY) * scaleX; + this.c = -Math.sin(rotation - skewX) * scaleY; + this.d = Math.cos(rotation - skewX) * scaleY; + this.tx = x - ((pivotX * this.a) + (pivotY * this.c)); + this.ty = y - ((pivotX * this.b) + (pivotY * this.d)); + return this; + }; + /** + * Prepends the given Matrix to this Matrix. + * @param matrix - The matrix to prepend + * @returns This matrix. Good for chaining method calls. + */ + Matrix.prototype.prepend = function (matrix) { + var tx1 = this.tx; + if (matrix.a !== 1 || matrix.b !== 0 || matrix.c !== 0 || matrix.d !== 1) { + var a1 = this.a; + var c1 = this.c; + this.a = (a1 * matrix.a) + (this.b * matrix.c); + this.b = (a1 * matrix.b) + (this.b * matrix.d); + this.c = (c1 * matrix.a) + (this.d * matrix.c); + this.d = (c1 * matrix.b) + (this.d * matrix.d); + } + this.tx = (tx1 * matrix.a) + (this.ty * matrix.c) + matrix.tx; + this.ty = (tx1 * matrix.b) + (this.ty * matrix.d) + matrix.ty; + return this; + }; + /** + * Decomposes the matrix (x, y, scaleX, scaleY, and rotation) and sets the properties on to a transform. + * @param transform - The transform to apply the properties to. + * @returns The transform with the newly applied properties + */ + Matrix.prototype.decompose = function (transform) { + // sort out rotation / skew.. + var a = this.a; + var b = this.b; + var c = this.c; + var d = this.d; + var pivot = transform.pivot; + var skewX = -Math.atan2(-c, d); + var skewY = Math.atan2(b, a); + var delta = Math.abs(skewX + skewY); + if (delta < 0.00001 || Math.abs(PI_2 - delta) < 0.00001) { + transform.rotation = skewY; + transform.skew.x = transform.skew.y = 0; + } + else { + transform.rotation = 0; + transform.skew.x = skewX; + transform.skew.y = skewY; + } + // next set scale + transform.scale.x = Math.sqrt((a * a) + (b * b)); + transform.scale.y = Math.sqrt((c * c) + (d * d)); + // next set position + transform.position.x = this.tx + ((pivot.x * a) + (pivot.y * c)); + transform.position.y = this.ty + ((pivot.x * b) + (pivot.y * d)); + return transform; + }; + /** + * Inverts this matrix + * @returns This matrix. Good for chaining method calls. + */ + Matrix.prototype.invert = function () { + var a1 = this.a; + var b1 = this.b; + var c1 = this.c; + var d1 = this.d; + var tx1 = this.tx; + var n = (a1 * d1) - (b1 * c1); + this.a = d1 / n; + this.b = -b1 / n; + this.c = -c1 / n; + this.d = a1 / n; + this.tx = ((c1 * this.ty) - (d1 * tx1)) / n; + this.ty = -((a1 * this.ty) - (b1 * tx1)) / n; + return this; + }; + /** + * Resets this Matrix to an identity (default) matrix. + * @returns This matrix. Good for chaining method calls. + */ + Matrix.prototype.identity = function () { + this.a = 1; + this.b = 0; + this.c = 0; + this.d = 1; + this.tx = 0; + this.ty = 0; + return this; + }; + /** + * Creates a new Matrix object with the same values as this one. + * @returns A copy of this matrix. Good for chaining method calls. + */ + Matrix.prototype.clone = function () { + var matrix = new Matrix(); + matrix.a = this.a; + matrix.b = this.b; + matrix.c = this.c; + matrix.d = this.d; + matrix.tx = this.tx; + matrix.ty = this.ty; + return matrix; + }; + /** + * Changes the values of the given matrix to be the same as the ones in this matrix + * @param matrix - The matrix to copy to. + * @returns The matrix given in parameter with its values updated. + */ + Matrix.prototype.copyTo = function (matrix) { + matrix.a = this.a; + matrix.b = this.b; + matrix.c = this.c; + matrix.d = this.d; + matrix.tx = this.tx; + matrix.ty = this.ty; + return matrix; + }; + /** + * Changes the values of the matrix to be the same as the ones in given matrix + * @param {PIXI.Matrix} matrix - The matrix to copy from. + * @returns {PIXI.Matrix} this + */ + Matrix.prototype.copyFrom = function (matrix) { + this.a = matrix.a; + this.b = matrix.b; + this.c = matrix.c; + this.d = matrix.d; + this.tx = matrix.tx; + this.ty = matrix.ty; + return this; + }; + Matrix.prototype.toString = function () { + return "[@pixi/math:Matrix a=" + this.a + " b=" + this.b + " c=" + this.c + " d=" + this.d + " tx=" + this.tx + " ty=" + this.ty + "]"; + }; + Object.defineProperty(Matrix, "IDENTITY", { + /** + * A default (identity) matrix + * @readonly + */ + get: function () { + return new Matrix(); + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(Matrix, "TEMP_MATRIX", { + /** + * A temp matrix + * @readonly + */ + get: function () { + return new Matrix(); + }, + enumerable: false, + configurable: true + }); + return Matrix; + }()); + + // Your friendly neighbour https://en.wikipedia.org/wiki/Dihedral_group + /* + * Transform matrix for operation n is: + * | ux | vx | + * | uy | vy | + */ + var ux = [1, 1, 0, -1, -1, -1, 0, 1, 1, 1, 0, -1, -1, -1, 0, 1]; + var uy = [0, 1, 1, 1, 0, -1, -1, -1, 0, 1, 1, 1, 0, -1, -1, -1]; + var vx = [0, -1, -1, -1, 0, 1, 1, 1, 0, 1, 1, 1, 0, -1, -1, -1]; + var vy = [1, 1, 0, -1, -1, -1, 0, 1, -1, -1, 0, 1, 1, 1, 0, -1]; + /** + * [Cayley Table]{@link https://en.wikipedia.org/wiki/Cayley_table} + * for the composition of each rotation in the dihederal group D8. + * @type {number[][]} + * @private + */ + var rotationCayley = []; + /** + * Matrices for each `GD8Symmetry` rotation. + * @type {PIXI.Matrix[]} + * @private + */ + var rotationMatrices = []; + /* + * Alias for {@code Math.sign}. + */ + var signum = Math.sign; + /* + * Initializes `rotationCayley` and `rotationMatrices`. It is called + * only once below. + */ + function init() { + for (var i = 0; i < 16; i++) { + var row = []; + rotationCayley.push(row); + for (var j = 0; j < 16; j++) { + /* Multiplies rotation matrices i and j. */ + var _ux = signum((ux[i] * ux[j]) + (vx[i] * uy[j])); + var _uy = signum((uy[i] * ux[j]) + (vy[i] * uy[j])); + var _vx = signum((ux[i] * vx[j]) + (vx[i] * vy[j])); + var _vy = signum((uy[i] * vx[j]) + (vy[i] * vy[j])); + /* Finds rotation matrix matching the product and pushes it. */ + for (var k = 0; k < 16; k++) { + if (ux[k] === _ux && uy[k] === _uy + && vx[k] === _vx && vy[k] === _vy) { + row.push(k); + break; + } + } + } + } + for (var i = 0; i < 16; i++) { + var mat = new Matrix(); + mat.set(ux[i], uy[i], vx[i], vy[i], 0, 0); + rotationMatrices.push(mat); + } + } + init(); + /** + * @memberof PIXI + * @typedef {number} GD8Symmetry + * @see PIXI.groupD8 + */ + /** + * Implements the dihedral group D8, which is similar to + * [group D4]{@link http://mathworld.wolfram.com/DihedralGroupD4.html}; + * D8 is the same but with diagonals, and it is used for texture + * rotations. + * + * The directions the U- and V- axes after rotation + * of an angle of `a: GD8Constant` are the vectors `(uX(a), uY(a))` + * and `(vX(a), vY(a))`. These aren't necessarily unit vectors. + * + * **Origin:**
+ * This is the small part of gameofbombs.com portal system. It works. + * @see PIXI.groupD8.E + * @see PIXI.groupD8.SE + * @see PIXI.groupD8.S + * @see PIXI.groupD8.SW + * @see PIXI.groupD8.W + * @see PIXI.groupD8.NW + * @see PIXI.groupD8.N + * @see PIXI.groupD8.NE + * @author Ivan @ivanpopelyshev + * @namespace PIXI.groupD8 + * @memberof PIXI + */ + var groupD8 = { + /** + * | Rotation | Direction | + * |----------|-----------| + * | 0° | East | + * @memberof PIXI.groupD8 + * @constant {PIXI.GD8Symmetry} + */ + E: 0, + /** + * | Rotation | Direction | + * |----------|-----------| + * | 45°↻ | Southeast | + * @memberof PIXI.groupD8 + * @constant {PIXI.GD8Symmetry} + */ + SE: 1, + /** + * | Rotation | Direction | + * |----------|-----------| + * | 90°↻ | South | + * @memberof PIXI.groupD8 + * @constant {PIXI.GD8Symmetry} + */ + S: 2, + /** + * | Rotation | Direction | + * |----------|-----------| + * | 135°↻ | Southwest | + * @memberof PIXI.groupD8 + * @constant {PIXI.GD8Symmetry} + */ + SW: 3, + /** + * | Rotation | Direction | + * |----------|-----------| + * | 180° | West | + * @memberof PIXI.groupD8 + * @constant {PIXI.GD8Symmetry} + */ + W: 4, + /** + * | Rotation | Direction | + * |-------------|--------------| + * | -135°/225°↻ | Northwest | + * @memberof PIXI.groupD8 + * @constant {PIXI.GD8Symmetry} + */ + NW: 5, + /** + * | Rotation | Direction | + * |-------------|--------------| + * | -90°/270°↻ | North | + * @memberof PIXI.groupD8 + * @constant {PIXI.GD8Symmetry} + */ + N: 6, + /** + * | Rotation | Direction | + * |-------------|--------------| + * | -45°/315°↻ | Northeast | + * @memberof PIXI.groupD8 + * @constant {PIXI.GD8Symmetry} + */ + NE: 7, + /** + * Reflection about Y-axis. + * @memberof PIXI.groupD8 + * @constant {PIXI.GD8Symmetry} + */ + MIRROR_VERTICAL: 8, + /** + * Reflection about the main diagonal. + * @memberof PIXI.groupD8 + * @constant {PIXI.GD8Symmetry} + */ + MAIN_DIAGONAL: 10, + /** + * Reflection about X-axis. + * @memberof PIXI.groupD8 + * @constant {PIXI.GD8Symmetry} + */ + MIRROR_HORIZONTAL: 12, + /** + * Reflection about reverse diagonal. + * @memberof PIXI.groupD8 + * @constant {PIXI.GD8Symmetry} + */ + REVERSE_DIAGONAL: 14, + /** + * @memberof PIXI.groupD8 + * @param {PIXI.GD8Symmetry} ind - sprite rotation angle. + * @returns {PIXI.GD8Symmetry} The X-component of the U-axis + * after rotating the axes. + */ + uX: function (ind) { return ux[ind]; }, + /** + * @memberof PIXI.groupD8 + * @param {PIXI.GD8Symmetry} ind - sprite rotation angle. + * @returns {PIXI.GD8Symmetry} The Y-component of the U-axis + * after rotating the axes. + */ + uY: function (ind) { return uy[ind]; }, + /** + * @memberof PIXI.groupD8 + * @param {PIXI.GD8Symmetry} ind - sprite rotation angle. + * @returns {PIXI.GD8Symmetry} The X-component of the V-axis + * after rotating the axes. + */ + vX: function (ind) { return vx[ind]; }, + /** + * @memberof PIXI.groupD8 + * @param {PIXI.GD8Symmetry} ind - sprite rotation angle. + * @returns {PIXI.GD8Symmetry} The Y-component of the V-axis + * after rotating the axes. + */ + vY: function (ind) { return vy[ind]; }, + /** + * @memberof PIXI.groupD8 + * @param {PIXI.GD8Symmetry} rotation - symmetry whose opposite + * is needed. Only rotations have opposite symmetries while + * reflections don't. + * @returns {PIXI.GD8Symmetry} The opposite symmetry of `rotation` + */ + inv: function (rotation) { + if (rotation & 8) // true only if between 8 & 15 (reflections) + { + return rotation & 15; // or rotation % 16 + } + return (-rotation) & 7; // or (8 - rotation) % 8 + }, + /** + * Composes the two D8 operations. + * + * Taking `^` as reflection: + * + * | | E=0 | S=2 | W=4 | N=6 | E^=8 | S^=10 | W^=12 | N^=14 | + * |-------|-----|-----|-----|-----|------|-------|-------|-------| + * | E=0 | E | S | W | N | E^ | S^ | W^ | N^ | + * | S=2 | S | W | N | E | S^ | W^ | N^ | E^ | + * | W=4 | W | N | E | S | W^ | N^ | E^ | S^ | + * | N=6 | N | E | S | W | N^ | E^ | S^ | W^ | + * | E^=8 | E^ | N^ | W^ | S^ | E | N | W | S | + * | S^=10 | S^ | E^ | N^ | W^ | S | E | N | W | + * | W^=12 | W^ | S^ | E^ | N^ | W | S | E | N | + * | N^=14 | N^ | W^ | S^ | E^ | N | W | S | E | + * + * [This is a Cayley table]{@link https://en.wikipedia.org/wiki/Cayley_table} + * @memberof PIXI.groupD8 + * @param {PIXI.GD8Symmetry} rotationSecond - Second operation, which + * is the row in the above cayley table. + * @param {PIXI.GD8Symmetry} rotationFirst - First operation, which + * is the column in the above cayley table. + * @returns {PIXI.GD8Symmetry} Composed operation + */ + add: function (rotationSecond, rotationFirst) { return (rotationCayley[rotationSecond][rotationFirst]); }, + /** + * Reverse of `add`. + * @memberof PIXI.groupD8 + * @param {PIXI.GD8Symmetry} rotationSecond - Second operation + * @param {PIXI.GD8Symmetry} rotationFirst - First operation + * @returns {PIXI.GD8Symmetry} Result + */ + sub: function (rotationSecond, rotationFirst) { return (rotationCayley[rotationSecond][groupD8.inv(rotationFirst)]); }, + /** + * Adds 180 degrees to rotation, which is a commutative + * operation. + * @memberof PIXI.groupD8 + * @param {number} rotation - The number to rotate. + * @returns {number} Rotated number + */ + rotate180: function (rotation) { return rotation ^ 4; }, + /** + * Checks if the rotation angle is vertical, i.e. south + * or north. It doesn't work for reflections. + * @memberof PIXI.groupD8 + * @param {PIXI.GD8Symmetry} rotation - The number to check. + * @returns {boolean} Whether or not the direction is vertical + */ + isVertical: function (rotation) { return (rotation & 3) === 2; }, + /** + * Approximates the vector `V(dx,dy)` into one of the + * eight directions provided by `groupD8`. + * @memberof PIXI.groupD8 + * @param {number} dx - X-component of the vector + * @param {number} dy - Y-component of the vector + * @returns {PIXI.GD8Symmetry} Approximation of the vector into + * one of the eight symmetries. + */ + byDirection: function (dx, dy) { + if (Math.abs(dx) * 2 <= Math.abs(dy)) { + if (dy >= 0) { + return groupD8.S; + } + return groupD8.N; + } + else if (Math.abs(dy) * 2 <= Math.abs(dx)) { + if (dx > 0) { + return groupD8.E; + } + return groupD8.W; + } + else if (dy > 0) { + if (dx > 0) { + return groupD8.SE; + } + return groupD8.SW; + } + else if (dx > 0) { + return groupD8.NE; + } + return groupD8.NW; + }, + /** + * Helps sprite to compensate texture packer rotation. + * @memberof PIXI.groupD8 + * @param {PIXI.Matrix} matrix - sprite world matrix + * @param {PIXI.GD8Symmetry} rotation - The rotation factor to use. + * @param {number} tx - sprite anchoring + * @param {number} ty - sprite anchoring + */ + matrixAppendRotationInv: function (matrix, rotation, tx, ty) { + if (tx === void 0) { tx = 0; } + if (ty === void 0) { ty = 0; } + // Packer used "rotation", we use "inv(rotation)" + var mat = rotationMatrices[groupD8.inv(rotation)]; + mat.tx = tx; + mat.ty = ty; + matrix.append(mat); + }, + }; + + /** + * Transform that takes care about its versions. + * @memberof PIXI + */ + var Transform = /** @class */ (function () { + function Transform() { + this.worldTransform = new Matrix(); + this.localTransform = new Matrix(); + this.position = new ObservablePoint(this.onChange, this, 0, 0); + this.scale = new ObservablePoint(this.onChange, this, 1, 1); + this.pivot = new ObservablePoint(this.onChange, this, 0, 0); + this.skew = new ObservablePoint(this.updateSkew, this, 0, 0); + this._rotation = 0; + this._cx = 1; + this._sx = 0; + this._cy = 0; + this._sy = 1; + this._localID = 0; + this._currentLocalID = 0; + this._worldID = 0; + this._parentID = 0; + } + /** Called when a value changes. */ + Transform.prototype.onChange = function () { + this._localID++; + }; + /** Called when the skew or the rotation changes. */ + Transform.prototype.updateSkew = function () { + this._cx = Math.cos(this._rotation + this.skew.y); + this._sx = Math.sin(this._rotation + this.skew.y); + this._cy = -Math.sin(this._rotation - this.skew.x); // cos, added PI/2 + this._sy = Math.cos(this._rotation - this.skew.x); // sin, added PI/2 + this._localID++; + }; + Transform.prototype.toString = function () { + return "[@pixi/math:Transform " + + ("position=(" + this.position.x + ", " + this.position.y + ") ") + + ("rotation=" + this.rotation + " ") + + ("scale=(" + this.scale.x + ", " + this.scale.y + ") ") + + ("skew=(" + this.skew.x + ", " + this.skew.y + ") ") + + "]"; + }; + /** Updates the local transformation matrix. */ + Transform.prototype.updateLocalTransform = function () { + var lt = this.localTransform; + if (this._localID !== this._currentLocalID) { + // get the matrix values of the displayobject based on its transform properties.. + lt.a = this._cx * this.scale.x; + lt.b = this._sx * this.scale.x; + lt.c = this._cy * this.scale.y; + lt.d = this._sy * this.scale.y; + lt.tx = this.position.x - ((this.pivot.x * lt.a) + (this.pivot.y * lt.c)); + lt.ty = this.position.y - ((this.pivot.x * lt.b) + (this.pivot.y * lt.d)); + this._currentLocalID = this._localID; + // force an update.. + this._parentID = -1; + } + }; + /** + * Updates the local and the world transformation matrices. + * @param parentTransform - The parent transform + */ + Transform.prototype.updateTransform = function (parentTransform) { + var lt = this.localTransform; + if (this._localID !== this._currentLocalID) { + // get the matrix values of the displayobject based on its transform properties.. + lt.a = this._cx * this.scale.x; + lt.b = this._sx * this.scale.x; + lt.c = this._cy * this.scale.y; + lt.d = this._sy * this.scale.y; + lt.tx = this.position.x - ((this.pivot.x * lt.a) + (this.pivot.y * lt.c)); + lt.ty = this.position.y - ((this.pivot.x * lt.b) + (this.pivot.y * lt.d)); + this._currentLocalID = this._localID; + // force an update.. + this._parentID = -1; + } + if (this._parentID !== parentTransform._worldID) { + // concat the parent matrix with the objects transform. + var pt = parentTransform.worldTransform; + var wt = this.worldTransform; + wt.a = (lt.a * pt.a) + (lt.b * pt.c); + wt.b = (lt.a * pt.b) + (lt.b * pt.d); + wt.c = (lt.c * pt.a) + (lt.d * pt.c); + wt.d = (lt.c * pt.b) + (lt.d * pt.d); + wt.tx = (lt.tx * pt.a) + (lt.ty * pt.c) + pt.tx; + wt.ty = (lt.tx * pt.b) + (lt.ty * pt.d) + pt.ty; + this._parentID = parentTransform._worldID; + // update the id of the transform.. + this._worldID++; + } + }; + /** + * Decomposes a matrix and sets the transforms properties based on it. + * @param matrix - The matrix to decompose + */ + Transform.prototype.setFromMatrix = function (matrix) { + matrix.decompose(this); + this._localID++; + }; + Object.defineProperty(Transform.prototype, "rotation", { + /** The rotation of the object in radians. */ + get: function () { + return this._rotation; + }, + set: function (value) { + if (this._rotation !== value) { + this._rotation = value; + this.updateSkew(); + } + }, + enumerable: false, + configurable: true + }); + /** A default (identity) transform. */ + Transform.IDENTITY = new Transform(); + return Transform; + }()); + + /*! + * @pixi/display - v6.5.3 + * Compiled Fri, 09 Sep 2022 13:55:20 UTC + * + * @pixi/display is licensed under the MIT License. + * http://www.opensource.org/licenses/mit-license + */ + + /** + * Sets the default value for the container property 'sortableChildren'. + * If set to true, the container will sort its children by zIndex value + * when updateTransform() is called, or manually if sortChildren() is called. + * + * This actually changes the order of elements in the array, so should be treated + * as a basic solution that is not performant compared to other solutions, + * such as @link https://github.com/pixijs/pixi-display + * + * Also be aware of that this may not work nicely with the addChildAt() function, + * as the zIndex sorting may cause the child to automatically sorted to another position. + * @static + * @constant + * @name SORTABLE_CHILDREN + * @memberof PIXI.settings + * @type {boolean} + * @default false + */ + settings$1.SORTABLE_CHILDREN = false; + + /** + * 'Builder' pattern for bounds rectangles. + * + * This could be called an Axis-Aligned Bounding Box. + * It is not an actual shape. It is a mutable thing; no 'EMPTY' or those kind of problems. + * @memberof PIXI + */ + var Bounds = /** @class */ (function () { + function Bounds() { + this.minX = Infinity; + this.minY = Infinity; + this.maxX = -Infinity; + this.maxY = -Infinity; + this.rect = null; + this.updateID = -1; + } + /** + * Checks if bounds are empty. + * @returns - True if empty. + */ + Bounds.prototype.isEmpty = function () { + return this.minX > this.maxX || this.minY > this.maxY; + }; + /** Clears the bounds and resets. */ + Bounds.prototype.clear = function () { + this.minX = Infinity; + this.minY = Infinity; + this.maxX = -Infinity; + this.maxY = -Infinity; + }; + /** + * Can return Rectangle.EMPTY constant, either construct new rectangle, either use your rectangle + * It is not guaranteed that it will return tempRect + * @param rect - Temporary object will be used if AABB is not empty + * @returns - A rectangle of the bounds + */ + Bounds.prototype.getRectangle = function (rect) { + if (this.minX > this.maxX || this.minY > this.maxY) { + return Rectangle.EMPTY; + } + rect = rect || new Rectangle(0, 0, 1, 1); + rect.x = this.minX; + rect.y = this.minY; + rect.width = this.maxX - this.minX; + rect.height = this.maxY - this.minY; + return rect; + }; + /** + * This function should be inlined when its possible. + * @param point - The point to add. + */ + Bounds.prototype.addPoint = function (point) { + this.minX = Math.min(this.minX, point.x); + this.maxX = Math.max(this.maxX, point.x); + this.minY = Math.min(this.minY, point.y); + this.maxY = Math.max(this.maxY, point.y); + }; + /** + * Adds a point, after transformed. This should be inlined when its possible. + * @param matrix + * @param point + */ + Bounds.prototype.addPointMatrix = function (matrix, point) { + var a = matrix.a, b = matrix.b, c = matrix.c, d = matrix.d, tx = matrix.tx, ty = matrix.ty; + var x = (a * point.x) + (c * point.y) + tx; + var y = (b * point.x) + (d * point.y) + ty; + this.minX = Math.min(this.minX, x); + this.maxX = Math.max(this.maxX, x); + this.minY = Math.min(this.minY, y); + this.maxY = Math.max(this.maxY, y); + }; + /** + * Adds a quad, not transformed + * @param vertices - The verts to add. + */ + Bounds.prototype.addQuad = function (vertices) { + var minX = this.minX; + var minY = this.minY; + var maxX = this.maxX; + var maxY = this.maxY; + var x = vertices[0]; + var y = vertices[1]; + minX = x < minX ? x : minX; + minY = y < minY ? y : minY; + maxX = x > maxX ? x : maxX; + maxY = y > maxY ? y : maxY; + x = vertices[2]; + y = vertices[3]; + minX = x < minX ? x : minX; + minY = y < minY ? y : minY; + maxX = x > maxX ? x : maxX; + maxY = y > maxY ? y : maxY; + x = vertices[4]; + y = vertices[5]; + minX = x < minX ? x : minX; + minY = y < minY ? y : minY; + maxX = x > maxX ? x : maxX; + maxY = y > maxY ? y : maxY; + x = vertices[6]; + y = vertices[7]; + minX = x < minX ? x : minX; + minY = y < minY ? y : minY; + maxX = x > maxX ? x : maxX; + maxY = y > maxY ? y : maxY; + this.minX = minX; + this.minY = minY; + this.maxX = maxX; + this.maxY = maxY; + }; + /** + * Adds sprite frame, transformed. + * @param transform - transform to apply + * @param x0 - left X of frame + * @param y0 - top Y of frame + * @param x1 - right X of frame + * @param y1 - bottom Y of frame + */ + Bounds.prototype.addFrame = function (transform, x0, y0, x1, y1) { + this.addFrameMatrix(transform.worldTransform, x0, y0, x1, y1); + }; + /** + * Adds sprite frame, multiplied by matrix + * @param matrix - matrix to apply + * @param x0 - left X of frame + * @param y0 - top Y of frame + * @param x1 - right X of frame + * @param y1 - bottom Y of frame + */ + Bounds.prototype.addFrameMatrix = function (matrix, x0, y0, x1, y1) { + var a = matrix.a; + var b = matrix.b; + var c = matrix.c; + var d = matrix.d; + var tx = matrix.tx; + var ty = matrix.ty; + var minX = this.minX; + var minY = this.minY; + var maxX = this.maxX; + var maxY = this.maxY; + var x = (a * x0) + (c * y0) + tx; + var y = (b * x0) + (d * y0) + ty; + minX = x < minX ? x : minX; + minY = y < minY ? y : minY; + maxX = x > maxX ? x : maxX; + maxY = y > maxY ? y : maxY; + x = (a * x1) + (c * y0) + tx; + y = (b * x1) + (d * y0) + ty; + minX = x < minX ? x : minX; + minY = y < minY ? y : minY; + maxX = x > maxX ? x : maxX; + maxY = y > maxY ? y : maxY; + x = (a * x0) + (c * y1) + tx; + y = (b * x0) + (d * y1) + ty; + minX = x < minX ? x : minX; + minY = y < minY ? y : minY; + maxX = x > maxX ? x : maxX; + maxY = y > maxY ? y : maxY; + x = (a * x1) + (c * y1) + tx; + y = (b * x1) + (d * y1) + ty; + minX = x < minX ? x : minX; + minY = y < minY ? y : minY; + maxX = x > maxX ? x : maxX; + maxY = y > maxY ? y : maxY; + this.minX = minX; + this.minY = minY; + this.maxX = maxX; + this.maxY = maxY; + }; + /** + * Adds screen vertices from array + * @param vertexData - calculated vertices + * @param beginOffset - begin offset + * @param endOffset - end offset, excluded + */ + Bounds.prototype.addVertexData = function (vertexData, beginOffset, endOffset) { + var minX = this.minX; + var minY = this.minY; + var maxX = this.maxX; + var maxY = this.maxY; + for (var i = beginOffset; i < endOffset; i += 2) { + var x = vertexData[i]; + var y = vertexData[i + 1]; + minX = x < minX ? x : minX; + minY = y < minY ? y : minY; + maxX = x > maxX ? x : maxX; + maxY = y > maxY ? y : maxY; + } + this.minX = minX; + this.minY = minY; + this.maxX = maxX; + this.maxY = maxY; + }; + /** + * Add an array of mesh vertices + * @param transform - mesh transform + * @param vertices - mesh coordinates in array + * @param beginOffset - begin offset + * @param endOffset - end offset, excluded + */ + Bounds.prototype.addVertices = function (transform, vertices, beginOffset, endOffset) { + this.addVerticesMatrix(transform.worldTransform, vertices, beginOffset, endOffset); + }; + /** + * Add an array of mesh vertices. + * @param matrix - mesh matrix + * @param vertices - mesh coordinates in array + * @param beginOffset - begin offset + * @param endOffset - end offset, excluded + * @param padX - x padding + * @param padY - y padding + */ + Bounds.prototype.addVerticesMatrix = function (matrix, vertices, beginOffset, endOffset, padX, padY) { + if (padX === void 0) { padX = 0; } + if (padY === void 0) { padY = padX; } + var a = matrix.a; + var b = matrix.b; + var c = matrix.c; + var d = matrix.d; + var tx = matrix.tx; + var ty = matrix.ty; + var minX = this.minX; + var minY = this.minY; + var maxX = this.maxX; + var maxY = this.maxY; + for (var i = beginOffset; i < endOffset; i += 2) { + var rawX = vertices[i]; + var rawY = vertices[i + 1]; + var x = (a * rawX) + (c * rawY) + tx; + var y = (d * rawY) + (b * rawX) + ty; + minX = Math.min(minX, x - padX); + maxX = Math.max(maxX, x + padX); + minY = Math.min(minY, y - padY); + maxY = Math.max(maxY, y + padY); + } + this.minX = minX; + this.minY = minY; + this.maxX = maxX; + this.maxY = maxY; + }; + /** + * Adds other {@link Bounds}. + * @param bounds - The Bounds to be added + */ + Bounds.prototype.addBounds = function (bounds) { + var minX = this.minX; + var minY = this.minY; + var maxX = this.maxX; + var maxY = this.maxY; + this.minX = bounds.minX < minX ? bounds.minX : minX; + this.minY = bounds.minY < minY ? bounds.minY : minY; + this.maxX = bounds.maxX > maxX ? bounds.maxX : maxX; + this.maxY = bounds.maxY > maxY ? bounds.maxY : maxY; + }; + /** + * Adds other Bounds, masked with Bounds. + * @param bounds - The Bounds to be added. + * @param mask - TODO + */ + Bounds.prototype.addBoundsMask = function (bounds, mask) { + var _minX = bounds.minX > mask.minX ? bounds.minX : mask.minX; + var _minY = bounds.minY > mask.minY ? bounds.minY : mask.minY; + var _maxX = bounds.maxX < mask.maxX ? bounds.maxX : mask.maxX; + var _maxY = bounds.maxY < mask.maxY ? bounds.maxY : mask.maxY; + if (_minX <= _maxX && _minY <= _maxY) { + var minX = this.minX; + var minY = this.minY; + var maxX = this.maxX; + var maxY = this.maxY; + this.minX = _minX < minX ? _minX : minX; + this.minY = _minY < minY ? _minY : minY; + this.maxX = _maxX > maxX ? _maxX : maxX; + this.maxY = _maxY > maxY ? _maxY : maxY; + } + }; + /** + * Adds other Bounds, multiplied by matrix. Bounds shouldn't be empty. + * @param bounds - other bounds + * @param matrix - multiplicator + */ + Bounds.prototype.addBoundsMatrix = function (bounds, matrix) { + this.addFrameMatrix(matrix, bounds.minX, bounds.minY, bounds.maxX, bounds.maxY); + }; + /** + * Adds other Bounds, masked with Rectangle. + * @param bounds - TODO + * @param area - TODO + */ + Bounds.prototype.addBoundsArea = function (bounds, area) { + var _minX = bounds.minX > area.x ? bounds.minX : area.x; + var _minY = bounds.minY > area.y ? bounds.minY : area.y; + var _maxX = bounds.maxX < area.x + area.width ? bounds.maxX : (area.x + area.width); + var _maxY = bounds.maxY < area.y + area.height ? bounds.maxY : (area.y + area.height); + if (_minX <= _maxX && _minY <= _maxY) { + var minX = this.minX; + var minY = this.minY; + var maxX = this.maxX; + var maxY = this.maxY; + this.minX = _minX < minX ? _minX : minX; + this.minY = _minY < minY ? _minY : minY; + this.maxX = _maxX > maxX ? _maxX : maxX; + this.maxY = _maxY > maxY ? _maxY : maxY; + } + }; + /** + * Pads bounds object, making it grow in all directions. + * If paddingY is omitted, both paddingX and paddingY will be set to paddingX. + * @param paddingX - The horizontal padding amount. + * @param paddingY - The vertical padding amount. + */ + Bounds.prototype.pad = function (paddingX, paddingY) { + if (paddingX === void 0) { paddingX = 0; } + if (paddingY === void 0) { paddingY = paddingX; } + if (!this.isEmpty()) { + this.minX -= paddingX; + this.maxX += paddingX; + this.minY -= paddingY; + this.maxY += paddingY; + } + }; + /** + * Adds padded frame. (x0, y0) should be strictly less than (x1, y1) + * @param x0 - left X of frame + * @param y0 - top Y of frame + * @param x1 - right X of frame + * @param y1 - bottom Y of frame + * @param padX - padding X + * @param padY - padding Y + */ + Bounds.prototype.addFramePad = function (x0, y0, x1, y1, padX, padY) { + x0 -= padX; + y0 -= padY; + x1 += padX; + y1 += padY; + this.minX = this.minX < x0 ? this.minX : x0; + this.maxX = this.maxX > x1 ? this.maxX : x1; + this.minY = this.minY < y0 ? this.minY : y0; + this.maxY = this.maxY > y1 ? this.maxY : y1; + }; + return Bounds; + }()); + + /*! ***************************************************************************** + Copyright (c) Microsoft Corporation. - THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED - WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, - MERCHANTABLITY OR NON-INFRINGEMENT. + Permission to use, copy, modify, and/or distribute this software for any + purpose with or without fee is hereby granted. - See the Apache Version 2.0 License for specific language governing permissions - and limitations under the License. - ***************************************************************************** */ - /* global Reflect, Promise */ + THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH + REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY + AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, + INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM + LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR + OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR + PERFORMANCE OF THIS SOFTWARE. + ***************************************************************************** */ + /* global Reflect, Promise */ - var extendStatics = function(d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) { if (b.hasOwnProperty(p)) { d[p] = b[p]; } } }; - return extendStatics(d, b); - }; + var extendStatics$j = function(d, b) { + extendStatics$j = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) { if (b.hasOwnProperty(p)) { d[p] = b[p]; } } }; + return extendStatics$j(d, b); + }; - function __extends(d, b) { - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - } - - /** - * The base class for all objects that are rendered on the screen. - * - * This is an abstract class and should not be used on its own; rather it should b e extended. - * - * @class - * @extends PIXI.utils.EventEmitter - * @memberof PIXI - */ - var DisplayObject = /** @class */ (function (_super) { - __extends(DisplayObject, _super); - function DisplayObject() { - var _this = _super.call(this) || this; - _this.tempDisplayObjectParent = null; - // TODO: need to create Transform from factory - /** - * World transform and local transform of this object. - * This will become read-only later, please do not assign anything there unless you know what are you doing. - * - * @member {PIXI.Transform} - */ - _this.transform = new Transform(); - /** - * The opacity of the object. - * - * @member {number} - */ - _this.alpha = 1; - /** - * The visibility of the object. If false the object will not be drawn, and - * the updateTransform function will not be called. - * - * Only affects recursive calls from parent. You can ask for bounds or call updateTransform manually. - * - * @member {boolean} - */ - _this.visible = true; - /** - * Can this object be rendered, if false the object will not be drawn but the updateTransform - * methods will still be called. - * - * Only affects recursive calls from parent. You can ask for bounds manually. - * - * @member {boolean} - */ - _this.renderable = true; - /** - * The display object container that contains this display object. - * - * @member {PIXI.Container} - */ - _this.parent = null; - /** - * The multiplied alpha of the displayObject. - * - * @member {number} - * @readonly - */ - _this.worldAlpha = 1; - /** - * Which index in the children array the display component was before the previous zIndex sort. - * Used by containers to help sort objects with the same zIndex, by using previous array index as the decider. - * - * @member {number} - * @protected - */ - _this._lastSortedIndex = 0; - /** - * The zIndex of the displayObject. - * A higher value will mean it will be rendered on top of other displayObjects within the same container. - * - * @member {number} - * @protected - */ - _this._zIndex = 0; - /** - * The area the filter is applied to. This is used as more of an optimization - * rather than figuring out the dimensions of the displayObject each frame you can set this rectangle. - * - * Also works as an interaction mask. - * - * @member {?PIXI.Rectangle} - */ - _this.filterArea = null; - /** - * Sets the filters for the displayObject. - * * IMPORTANT: This is a WebGL only feature and will be ignored by the canvas renderer. - * To remove filters simply set this property to `'null'`. - * - * @member {?PIXI.Filter[]} - */ - _this.filters = null; - /** - * Currently enabled filters - * @member {PIXI.Filter[]} - * @protected - */ - _this._enabledFilters = null; - /** - * The bounds object, this is used to calculate and store the bounds of the displayObject. - * - * @member {PIXI.Bounds} - */ - _this._bounds = new Bounds(); - /** - * Local bounds object, swapped with `_bounds` when using `getLocalBounds()`. - * - * @member {PIXI.Bounds} - */ - _this._localBounds = null; - /** - * Flags the cached bounds as dirty. - * - * @member {number} - * @protected - */ - _this._boundsID = 0; - /** - * Cache of this display-object's bounds-rectangle. - * - * @member {PIXI.Bounds} - * @protected - */ - _this._boundsRect = null; - /** - * Cache of this display-object's local-bounds rectangle. - * - * @member {PIXI.Bounds} - * @protected - */ - _this._localBoundsRect = null; - /** - * The original, cached mask of the object. - * - * @member {PIXI.Container|PIXI.MaskData|null} - * @protected - */ - _this._mask = null; - /** - * Fired when this DisplayObject is added to a Container. - * - * @event PIXI.DisplayObject#added - * @param {PIXI.Container} container - The container added to. - */ - /** - * Fired when this DisplayObject is removed from a Container. - * - * @event PIXI.DisplayObject#removed - * @param {PIXI.Container} container - The container removed from. - */ - /** - * If the object has been destroyed via destroy(). If true, it should not be used. - * - * @member {boolean} - * @protected - */ - _this._destroyed = false; - /** - * used to fast check if a sprite is.. a sprite! - * @member {boolean} - */ - _this.isSprite = false; - /** - * Does any other displayObject use this object as a mask? - * @member {boolean} - */ - _this.isMask = false; - return _this; - } - /** - * Mixes all enumerable properties and methods from a source object to DisplayObject. - * - * @param {object} source - The source of properties and methods to mix in. - */ - DisplayObject.mixin = function (source) { - // in ES8/ES2017, this would be really easy: - // Object.defineProperties(DisplayObject.prototype, Object.getOwnPropertyDescriptors(source)); - // get all the enumerable property keys - var keys = Object.keys(source); - // loop through properties - for (var i = 0; i < keys.length; ++i) { - var propertyName = keys[i]; - // Set the property using the property descriptor - this works for accessors and normal value properties - Object.defineProperty(DisplayObject.prototype, propertyName, Object.getOwnPropertyDescriptor(source, propertyName)); - } - }; - /** - * Recursively updates transform of all objects from the root to this one - * internal function for toLocal() - */ - DisplayObject.prototype._recursivePostUpdateTransform = function () { - if (this.parent) { - this.parent._recursivePostUpdateTransform(); - this.transform.updateTransform(this.parent.transform); - } - else { - this.transform.updateTransform(this._tempDisplayObjectParent.transform); - } - }; - /** - * Updates the object transform for rendering. - * - * TODO - Optimization pass! - */ - DisplayObject.prototype.updateTransform = function () { - this._boundsID++; - this.transform.updateTransform(this.parent.transform); - // multiply the alphas.. - this.worldAlpha = this.alpha * this.parent.worldAlpha; - }; - /** - * Retrieves the bounds of the displayObject as a rectangle object. - * - * @param {boolean} [skipUpdate] - Setting to `true` will stop the transforms of the scene graph from - * being updated. This means the calculation returned MAY be out of date BUT will give you a - * nice performance boost. - * @param {PIXI.Rectangle} [rect] - Optional rectangle to store the result of the bounds calculation. - * @return {PIXI.Rectangle} The rectangular bounding area. - */ - DisplayObject.prototype.getBounds = function (skipUpdate, rect) { - if (!skipUpdate) { - if (!this.parent) { - this.parent = this._tempDisplayObjectParent; - this.updateTransform(); - this.parent = null; - } - else { - this._recursivePostUpdateTransform(); - this.updateTransform(); - } - } - if (this._bounds.updateID !== this._boundsID) { - this.calculateBounds(); - this._bounds.updateID = this._boundsID; - } - if (!rect) { - if (!this._boundsRect) { - this._boundsRect = new Rectangle(); - } - rect = this._boundsRect; - } - return this._bounds.getRectangle(rect); - }; - /** - * Retrieves the local bounds of the displayObject as a rectangle object. - * - * @param {PIXI.Rectangle} [rect] - Optional rectangle to store the result of the bounds calculation. - * @return {PIXI.Rectangle} The rectangular bounding area. - */ - DisplayObject.prototype.getLocalBounds = function (rect) { - if (!rect) { - if (!this._localBoundsRect) { - this._localBoundsRect = new Rectangle(); - } - rect = this._localBoundsRect; - } - if (!this._localBounds) { - this._localBounds = new Bounds(); - } - var transformRef = this.transform; - var parentRef = this.parent; - this.parent = null; - this.transform = this._tempDisplayObjectParent.transform; - var worldBounds = this._bounds; - var worldBoundsID = this._boundsID; - this._bounds = this._localBounds; - var bounds = this.getBounds(false, rect); - this.parent = parentRef; - this.transform = transformRef; - this._bounds = worldBounds; - this._bounds.updateID += this._boundsID - worldBoundsID; // reflect side-effects - return bounds; - }; - /** - * Calculates the global position of the display object. - * - * @param {PIXI.IPointData} position - The world origin to calculate from. - * @param {PIXI.Point} [point] - A Point object in which to store the value, optional - * (otherwise will create a new Point). - * @param {boolean} [skipUpdate=false] - Should we skip the update transform. - * @return {PIXI.Point} A point object representing the position of this object. - */ - DisplayObject.prototype.toGlobal = function (position, point, skipUpdate) { - if (skipUpdate === void 0) { skipUpdate = false; } - if (!skipUpdate) { - this._recursivePostUpdateTransform(); - // this parent check is for just in case the item is a root object. - // If it is we need to give it a temporary parent so that displayObjectUpdateTransform works correctly - // this is mainly to avoid a parent check in the main loop. Every little helps for performance :) - if (!this.parent) { - this.parent = this._tempDisplayObjectParent; - this.displayObjectUpdateTransform(); - this.parent = null; - } - else { - this.displayObjectUpdateTransform(); - } - } - // don't need to update the lot - return this.worldTransform.apply(position, point); - }; - /** - * Calculates the local position of the display object relative to another point. - * - * @param {PIXI.IPointData} position - The world origin to calculate from. - * @param {PIXI.DisplayObject} [from] - The DisplayObject to calculate the global position from. - * @param {PIXI.Point} [point] - A Point object in which to store the value, optional - * (otherwise will create a new Point). - * @param {boolean} [skipUpdate=false] - Should we skip the update transform - * @return {PIXI.Point} A point object representing the position of this object - */ - DisplayObject.prototype.toLocal = function (position, from, point, skipUpdate) { - if (from) { - position = from.toGlobal(position, point, skipUpdate); - } - if (!skipUpdate) { - this._recursivePostUpdateTransform(); - // this parent check is for just in case the item is a root object. - // If it is we need to give it a temporary parent so that displayObjectUpdateTransform works correctly - // this is mainly to avoid a parent check in the main loop. Every little helps for performance :) - if (!this.parent) { - this.parent = this._tempDisplayObjectParent; - this.displayObjectUpdateTransform(); - this.parent = null; - } - else { - this.displayObjectUpdateTransform(); - } - } - // simply apply the matrix.. - return this.worldTransform.applyInverse(position, point); - }; - /** - * Set the parent Container of this DisplayObject. - * - * @param {PIXI.Container} container - The Container to add this DisplayObject to. - * @return {PIXI.Container} The Container that this DisplayObject was added to. - */ - DisplayObject.prototype.setParent = function (container) { - if (!container || !container.addChild) { - throw new Error('setParent: Argument must be a Container'); - } - container.addChild(this); - return container; - }; - /** - * Convenience function to set the position, scale, skew and pivot at once. - * - * @param {number} [x=0] - The X position - * @param {number} [y=0] - The Y position - * @param {number} [scaleX=1] - The X scale value - * @param {number} [scaleY=1] - The Y scale value - * @param {number} [rotation=0] - The rotation - * @param {number} [skewX=0] - The X skew value - * @param {number} [skewY=0] - The Y skew value - * @param {number} [pivotX=0] - The X pivot value - * @param {number} [pivotY=0] - The Y pivot value - * @return {PIXI.DisplayObject} The DisplayObject instance - */ - DisplayObject.prototype.setTransform = function (x, y, scaleX, scaleY, rotation, skewX, skewY, pivotX, pivotY) { - if (x === void 0) { x = 0; } - if (y === void 0) { y = 0; } - if (scaleX === void 0) { scaleX = 1; } - if (scaleY === void 0) { scaleY = 1; } - if (rotation === void 0) { rotation = 0; } - if (skewX === void 0) { skewX = 0; } - if (skewY === void 0) { skewY = 0; } - if (pivotX === void 0) { pivotX = 0; } - if (pivotY === void 0) { pivotY = 0; } - this.position.x = x; - this.position.y = y; - this.scale.x = !scaleX ? 1 : scaleX; - this.scale.y = !scaleY ? 1 : scaleY; - this.rotation = rotation; - this.skew.x = skewX; - this.skew.y = skewY; - this.pivot.x = pivotX; - this.pivot.y = pivotY; - return this; - }; - /** - * Base destroy method for generic display objects. This will automatically - * remove the display object from its parent Container as well as remove - * all current event listeners and internal references. Do not use a DisplayObject - * after calling `destroy()`. - * - */ - DisplayObject.prototype.destroy = function (_options) { - if (this.parent) { - this.parent.removeChild(this); - } - this.removeAllListeners(); - this.transform = null; - this.parent = null; - this._bounds = null; - this._mask = null; - this.filters = null; - this.filterArea = null; - this.hitArea = null; - this.interactive = false; - this.interactiveChildren = false; - this._destroyed = true; - }; - Object.defineProperty(DisplayObject.prototype, "_tempDisplayObjectParent", { - /** - * @protected - * @member {PIXI.Container} - */ - get: function () { - if (this.tempDisplayObjectParent === null) { - // eslint-disable-next-line no-use-before-define - this.tempDisplayObjectParent = new TemporaryDisplayObject(); - } - return this.tempDisplayObjectParent; - }, - enumerable: false, - configurable: true - }); - /** - * Used in Renderer, cacheAsBitmap and other places where you call an `updateTransform` on root - * - * ``` - * const cacheParent = elem.enableTempParent(); - * elem.updateTransform(); - * elem.disableTempParent(cacheParent); - * ``` - * - * @returns {PIXI.DisplayObject} current parent - */ - DisplayObject.prototype.enableTempParent = function () { - var myParent = this.parent; - this.parent = this._tempDisplayObjectParent; - return myParent; - }; - /** - * Pair method for `enableTempParent` - * @param {PIXI.DisplayObject} cacheParent actual parent of element - */ - DisplayObject.prototype.disableTempParent = function (cacheParent) { - this.parent = cacheParent; - }; - Object.defineProperty(DisplayObject.prototype, "x", { - /** - * The position of the displayObject on the x axis relative to the local coordinates of the parent. - * An alias to position.x - * - * @member {number} - */ - get: function () { - return this.position.x; - }, - set: function (value) { - this.transform.position.x = value; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(DisplayObject.prototype, "y", { - /** - * The position of the displayObject on the y axis relative to the local coordinates of the parent. - * An alias to position.y - * - * @member {number} - */ - get: function () { - return this.position.y; - }, - set: function (value) { - this.transform.position.y = value; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(DisplayObject.prototype, "worldTransform", { - /** - * Current transform of the object based on world (parent) factors. - * - * @member {PIXI.Matrix} - * @readonly - */ - get: function () { - return this.transform.worldTransform; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(DisplayObject.prototype, "localTransform", { - /** - * Current transform of the object based on local factors: position, scale, other stuff. - * - * @member {PIXI.Matrix} - * @readonly - */ - get: function () { - return this.transform.localTransform; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(DisplayObject.prototype, "position", { - /** - * The coordinate of the object relative to the local coordinates of the parent. - * Assignment by value since pixi-v4. - * - * @member {PIXI.ObservablePoint} - */ - get: function () { - return this.transform.position; - }, - set: function (value) { - this.transform.position.copyFrom(value); - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(DisplayObject.prototype, "scale", { - /** - * The scale factor of the object. - * Assignment by value since pixi-v4. - * - * @member {PIXI.ObservablePoint} - */ - get: function () { - return this.transform.scale; - }, - set: function (value) { - this.transform.scale.copyFrom(value); - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(DisplayObject.prototype, "pivot", { - /** - * The pivot point of the displayObject that it rotates around. - * Assignment by value since pixi-v4. - * - * @member {PIXI.ObservablePoint} - */ - get: function () { - return this.transform.pivot; - }, - set: function (value) { - this.transform.pivot.copyFrom(value); - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(DisplayObject.prototype, "skew", { - /** - * The skew factor for the object in radians. - * Assignment by value since pixi-v4. - * - * @member {PIXI.ObservablePoint} - */ - get: function () { - return this.transform.skew; - }, - set: function (value) { - this.transform.skew.copyFrom(value); - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(DisplayObject.prototype, "rotation", { - /** - * The rotation of the object in radians. - * 'rotation' and 'angle' have the same effect on a display object; rotation is in radians, angle is in degrees. - * - * @member {number} - */ - get: function () { - return this.transform.rotation; - }, - set: function (value) { - this.transform.rotation = value; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(DisplayObject.prototype, "angle", { - /** - * The angle of the object in degrees. - * 'rotation' and 'angle' have the same effect on a display object; rotation is in radians, angle is in degrees. - * - * @member {number} - */ - get: function () { - return this.transform.rotation * RAD_TO_DEG; - }, - set: function (value) { - this.transform.rotation = value * DEG_TO_RAD; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(DisplayObject.prototype, "zIndex", { - /** - * The zIndex of the displayObject. - * If a container has the sortableChildren property set to true, children will be automatically - * sorted by zIndex value; a higher value will mean it will be moved towards the end of the array, - * and thus rendered on top of other displayObjects within the same container. - * - * @member {number} - */ - get: function () { - return this._zIndex; - }, - set: function (value) { - this._zIndex = value; - if (this.parent) { - this.parent.sortDirty = true; - } - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(DisplayObject.prototype, "worldVisible", { - /** - * Indicates if the object is globally visible. - * - * @member {boolean} - * @readonly - */ - get: function () { - var item = this; - do { - if (!item.visible) { - return false; - } - item = item.parent; - } while (item); - return true; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(DisplayObject.prototype, "mask", { - /** - * Sets a mask for the displayObject. A mask is an object that limits the visibility of an - * object to the shape of the mask applied to it. In PixiJS a regular mask must be a - * {@link PIXI.Graphics} or a {@link PIXI.Sprite} object. This allows for much faster masking in canvas as it - * utilities shape clipping. To remove a mask, set this property to `null`. - * - * For sprite mask both alpha and red channel are used. Black mask is the same as transparent mask. - * @example - * const graphics = new PIXI.Graphics(); - * graphics.beginFill(0xFF3300); - * graphics.drawRect(50, 250, 100, 100); - * graphics.endFill(); - * - * const sprite = new PIXI.Sprite(texture); - * sprite.mask = graphics; - * @todo At the moment, PIXI.CanvasRenderer doesn't support PIXI.Sprite as mask. - * - * @member {PIXI.Container|PIXI.MaskData|null} - */ - get: function () { - return this._mask; - }, - set: function (value) { - if (this._mask) { - var maskObject = (this._mask.maskObject || this._mask); - maskObject.renderable = true; - maskObject.isMask = false; - } - this._mask = value; - if (this._mask) { - var maskObject = (this._mask.maskObject || this._mask); - maskObject.renderable = false; - maskObject.isMask = true; - } - }, - enumerable: false, - configurable: true - }); - return DisplayObject; - }(eventemitter3)); - var TemporaryDisplayObject = /** @class */ (function (_super) { - __extends(TemporaryDisplayObject, _super); - function TemporaryDisplayObject() { - var _this = _super !== null && _super.apply(this, arguments) || this; - _this.sortDirty = null; - return _this; - } - return TemporaryDisplayObject; - }(DisplayObject)); - /** - * DisplayObject default updateTransform, does not update children of container. - * Will crash if there's no parent element. - * - * @memberof PIXI.DisplayObject# - * @function displayObjectUpdateTransform - */ - DisplayObject.prototype.displayObjectUpdateTransform = DisplayObject.prototype.updateTransform; - - function sortChildren(a, b) { - if (a.zIndex === b.zIndex) { - return a._lastSortedIndex - b._lastSortedIndex; - } - return a.zIndex - b.zIndex; - } - /** - * A Container represents a collection of display objects. - * - * It is the base class of all display objects that act as a container for other objects (like Sprites). - * - *```js - * let container = new PIXI.Container(); - * container.addChild(sprite); - * ``` - * - * @class - * @extends PIXI.DisplayObject - * @memberof PIXI - */ - var Container = /** @class */ (function (_super) { - __extends(Container, _super); - function Container() { - var _this = _super.call(this) || this; - /** - * The array of children of this container. - * - * @member {PIXI.DisplayObject[]} - * @readonly - */ - _this.children = []; - /** - * If set to true, the container will sort its children by zIndex value - * when updateTransform() is called, or manually if sortChildren() is called. - * - * This actually changes the order of elements in the array, so should be treated - * as a basic solution that is not performant compared to other solutions, - * such as @link https://github.com/pixijs/pixi-display - * - * Also be aware of that this may not work nicely with the addChildAt() function, - * as the zIndex sorting may cause the child to automatically sorted to another position. - * - * @see PIXI.settings.SORTABLE_CHILDREN - * - * @member {boolean} - */ - _this.sortableChildren = settings.SORTABLE_CHILDREN; - /** - * Should children be sorted by zIndex at the next updateTransform call. - * Will get automatically set to true if a new child is added, or if a child's zIndex changes. - * - * @member {boolean} - */ - _this.sortDirty = false; - return _this; - /** - * Fired when a DisplayObject is added to this Container. - * - * @event PIXI.Container#childAdded - * @param {PIXI.DisplayObject} child - The child added to the Container. - * @param {PIXI.Container} container - The container that added the child. - * @param {number} index - The children's index of the added child. - */ - /** - * Fired when a DisplayObject is removed from this Container. - * - * @event PIXI.DisplayObject#removedFrom - * @param {PIXI.DisplayObject} child - The child removed from the Container. - * @param {PIXI.Container} container - The container that removed removed the child. - * @param {number} index - The former children's index of the removed child - */ - } - /** - * Overridable method that can be used by Container subclasses whenever the children array is modified - * - * @protected - */ - Container.prototype.onChildrenChange = function (_length) { - /* empty */ - }; - /** - * Adds one or more children to the container. - * - * Multiple items can be added like so: `myContainer.addChild(thingOne, thingTwo, thingThree)` - * - * @param {...PIXI.DisplayObject} children - The DisplayObject(s) to add to the container - * @return {PIXI.DisplayObject} The first child that was added. - */ - Container.prototype.addChild = function () { - var arguments$1 = arguments; - - var children = []; - for (var _i = 0; _i < arguments.length; _i++) { - children[_i] = arguments$1[_i]; - } - // if there is only one argument we can bypass looping through the them - if (children.length > 1) { - // loop through the array and add all children - for (var i = 0; i < children.length; i++) { - // eslint-disable-next-line prefer-rest-params - this.addChild(children[i]); - } - } - else { - var child = children[0]; - // if the child has a parent then lets remove it as PixiJS objects can only exist in one place - if (child.parent) { - child.parent.removeChild(child); - } - child.parent = this; - this.sortDirty = true; - // ensure child transform will be recalculated - child.transform._parentID = -1; - this.children.push(child); - // ensure bounds will be recalculated - this._boundsID++; - // TODO - lets either do all callbacks or all events.. not both! - this.onChildrenChange(this.children.length - 1); - this.emit('childAdded', child, this, this.children.length - 1); - child.emit('added', this); - } - return children[0]; - }; - /** - * Adds a child to the container at a specified index. If the index is out of bounds an error will be thrown - * - * @param {PIXI.DisplayObject} child - The child to add - * @param {number} index - The index to place the child in - * @return {PIXI.DisplayObject} The child that was added. - */ - Container.prototype.addChildAt = function (child, index) { - if (index < 0 || index > this.children.length) { - throw new Error(child + "addChildAt: The index " + index + " supplied is out of bounds " + this.children.length); - } - if (child.parent) { - child.parent.removeChild(child); - } - child.parent = this; - this.sortDirty = true; - // ensure child transform will be recalculated - child.transform._parentID = -1; - this.children.splice(index, 0, child); - // ensure bounds will be recalculated - this._boundsID++; - // TODO - lets either do all callbacks or all events.. not both! - this.onChildrenChange(index); - child.emit('added', this); - this.emit('childAdded', child, this, index); - return child; - }; - /** - * Swaps the position of 2 Display Objects within this container. - * - * @param {PIXI.DisplayObject} child - First display object to swap - * @param {PIXI.DisplayObject} child2 - Second display object to swap - */ - Container.prototype.swapChildren = function (child, child2) { - if (child === child2) { - return; - } - var index1 = this.getChildIndex(child); - var index2 = this.getChildIndex(child2); - this.children[index1] = child2; - this.children[index2] = child; - this.onChildrenChange(index1 < index2 ? index1 : index2); - }; - /** - * Returns the index position of a child DisplayObject instance - * - * @param {PIXI.DisplayObject} child - The DisplayObject instance to identify - * @return {number} The index position of the child display object to identify - */ - Container.prototype.getChildIndex = function (child) { - var index = this.children.indexOf(child); - if (index === -1) { - throw new Error('The supplied DisplayObject must be a child of the caller'); - } - return index; - }; - /** - * Changes the position of an existing child in the display object container - * - * @param {PIXI.DisplayObject} child - The child DisplayObject instance for which you want to change the index number - * @param {number} index - The resulting index number for the child display object - */ - Container.prototype.setChildIndex = function (child, index) { - if (index < 0 || index >= this.children.length) { - throw new Error("The index " + index + " supplied is out of bounds " + this.children.length); - } - var currentIndex = this.getChildIndex(child); - removeItems(this.children, currentIndex, 1); // remove from old position - this.children.splice(index, 0, child); // add at new position - this.onChildrenChange(index); - }; - /** - * Returns the child at the specified index - * - * @param {number} index - The index to get the child at - * @return {PIXI.DisplayObject} The child at the given index, if any. - */ - Container.prototype.getChildAt = function (index) { - if (index < 0 || index >= this.children.length) { - throw new Error("getChildAt: Index (" + index + ") does not exist."); - } - return this.children[index]; - }; - /** - * Removes one or more children from the container. - * - * @param {...PIXI.DisplayObject} children - The DisplayObject(s) to remove - * @return {PIXI.DisplayObject} The first child that was removed. - */ - Container.prototype.removeChild = function () { - var arguments$1 = arguments; - - var children = []; - for (var _i = 0; _i < arguments.length; _i++) { - children[_i] = arguments$1[_i]; - } - // if there is only one argument we can bypass looping through the them - if (children.length > 1) { - // loop through the arguments property and remove all children - for (var i = 0; i < children.length; i++) { - this.removeChild(children[i]); - } - } - else { - var child = children[0]; - var index = this.children.indexOf(child); - if (index === -1) - { return null; } - child.parent = null; - // ensure child transform will be recalculated - child.transform._parentID = -1; - removeItems(this.children, index, 1); - // ensure bounds will be recalculated - this._boundsID++; - // TODO - lets either do all callbacks or all events.. not both! - this.onChildrenChange(index); - child.emit('removed', this); - this.emit('childRemoved', child, this, index); - } - return children[0]; - }; - /** - * Removes a child from the specified index position. - * - * @param {number} index - The index to get the child from - * @return {PIXI.DisplayObject} The child that was removed. - */ - Container.prototype.removeChildAt = function (index) { - var child = this.getChildAt(index); - // ensure child transform will be recalculated.. - child.parent = null; - child.transform._parentID = -1; - removeItems(this.children, index, 1); - // ensure bounds will be recalculated - this._boundsID++; - // TODO - lets either do all callbacks or all events.. not both! - this.onChildrenChange(index); - child.emit('removed', this); - this.emit('childRemoved', child, this, index); - return child; - }; - /** - * Removes all children from this container that are within the begin and end indexes. - * - * @param {number} [beginIndex=0] - The beginning position. - * @param {number} [endIndex=this.children.length] - The ending position. Default value is size of the container. - * @returns {PIXI.DisplayObject[]} List of removed children - */ - Container.prototype.removeChildren = function (beginIndex, endIndex) { - if (beginIndex === void 0) { beginIndex = 0; } - if (endIndex === void 0) { endIndex = this.children.length; } - var begin = beginIndex; - var end = endIndex; - var range = end - begin; - var removed; - if (range > 0 && range <= end) { - removed = this.children.splice(begin, range); - for (var i = 0; i < removed.length; ++i) { - removed[i].parent = null; - if (removed[i].transform) { - removed[i].transform._parentID = -1; - } - } - this._boundsID++; - this.onChildrenChange(beginIndex); - for (var i = 0; i < removed.length; ++i) { - removed[i].emit('removed', this); - this.emit('childRemoved', removed[i], this, i); - } - return removed; - } - else if (range === 0 && this.children.length === 0) { - return []; - } - throw new RangeError('removeChildren: numeric values are outside the acceptable range.'); - }; - /** - * Sorts children by zIndex. Previous order is mantained for 2 children with the same zIndex. - */ - Container.prototype.sortChildren = function () { - var sortRequired = false; - for (var i = 0, j = this.children.length; i < j; ++i) { - var child = this.children[i]; - child._lastSortedIndex = i; - if (!sortRequired && child.zIndex !== 0) { - sortRequired = true; - } - } - if (sortRequired && this.children.length > 1) { - this.children.sort(sortChildren); - } - this.sortDirty = false; - }; - /** - * Updates the transform on all children of this container for rendering - */ - Container.prototype.updateTransform = function () { - if (this.sortableChildren && this.sortDirty) { - this.sortChildren(); - } - this._boundsID++; - this.transform.updateTransform(this.parent.transform); - // TODO: check render flags, how to process stuff here - this.worldAlpha = this.alpha * this.parent.worldAlpha; - for (var i = 0, j = this.children.length; i < j; ++i) { - var child = this.children[i]; - if (child.visible) { - child.updateTransform(); - } - } - }; - /** - * Recalculates the bounds of the container. - * - */ - Container.prototype.calculateBounds = function () { - this._bounds.clear(); - this._calculateBounds(); - for (var i = 0; i < this.children.length; i++) { - var child = this.children[i]; - if (!child.visible || !child.renderable) { - continue; - } - child.calculateBounds(); - // TODO: filter+mask, need to mask both somehow - if (child._mask) { - var maskObject = (child._mask.maskObject || child._mask); - maskObject.calculateBounds(); - this._bounds.addBoundsMask(child._bounds, maskObject._bounds); - } - else if (child.filterArea) { - this._bounds.addBoundsArea(child._bounds, child.filterArea); - } - else { - this._bounds.addBounds(child._bounds); - } - } - this._bounds.updateID = this._boundsID; - }; - /** - * Retrieves the local bounds of the displayObject as a rectangle object. - * - * @param {PIXI.Rectangle} [rect] - Optional rectangle to store the result of the bounds calculation. - * @param {boolean} [skipChildrenUpdate=false] - Setting to `true` will stop re-calculation of children transforms, - * it was default behaviour of pixi 4.0-5.2 and caused many problems to users. - * @return {PIXI.Rectangle} The rectangular bounding area. - */ - Container.prototype.getLocalBounds = function (rect, skipChildrenUpdate) { - if (skipChildrenUpdate === void 0) { skipChildrenUpdate = false; } - var result = _super.prototype.getLocalBounds.call(this, rect); - if (!skipChildrenUpdate) { - for (var i = 0, j = this.children.length; i < j; ++i) { - var child = this.children[i]; - if (child.visible) { - child.updateTransform(); - } - } - } - return result; - }; - /** - * Recalculates the bounds of the object. Override this to - * calculate the bounds of the specific object (not including children). - * - * @protected - */ - Container.prototype._calculateBounds = function () { - // FILL IN// - }; - /** - * Renders the object using the WebGL renderer - * - * @param {PIXI.Renderer} renderer - The renderer - */ - Container.prototype.render = function (renderer) { - // if the object is not visible or the alpha is 0 then no need to render this element - if (!this.visible || this.worldAlpha <= 0 || !this.renderable) { - return; - } - // do a quick check to see if this element has a mask or a filter. - if (this._mask || (this.filters && this.filters.length)) { - this.renderAdvanced(renderer); - } - else { - this._render(renderer); - // simple render children! - for (var i = 0, j = this.children.length; i < j; ++i) { - this.children[i].render(renderer); - } - } - }; - /** - * Render the object using the WebGL renderer and advanced features. - * - * @protected - * @param {PIXI.Renderer} renderer - The renderer - */ - Container.prototype.renderAdvanced = function (renderer) { - renderer.batch.flush(); - var filters = this.filters; - var mask = this._mask; - // push filter first as we need to ensure the stencil buffer is correct for any masking - if (filters) { - if (!this._enabledFilters) { - this._enabledFilters = []; - } - this._enabledFilters.length = 0; - for (var i = 0; i < filters.length; i++) { - if (filters[i].enabled) { - this._enabledFilters.push(filters[i]); - } - } - if (this._enabledFilters.length) { - renderer.filter.push(this, this._enabledFilters); - } - } - if (mask) { - renderer.mask.push(this, this._mask); - } - // add this object to the batch, only rendered if it has a texture. - this._render(renderer); - // now loop through the children and make sure they get rendered - for (var i = 0, j = this.children.length; i < j; i++) { - this.children[i].render(renderer); - } - renderer.batch.flush(); - if (mask) { - renderer.mask.pop(this); - } - if (filters && this._enabledFilters && this._enabledFilters.length) { - renderer.filter.pop(); - } - }; - /** - * To be overridden by the subclasses. - * - * @protected - * @param {PIXI.Renderer} renderer - The renderer - */ - Container.prototype._render = function (_renderer) { - // this is where content itself gets rendered... - }; - /** - * Removes all internal references and listeners as well as removes children from the display list. - * Do not use a Container after calling `destroy`. - * - * @param {object|boolean} [options] - Options parameter. A boolean will act as if all options - * have been set to that value - * @param {boolean} [options.children=false] - if set to true, all the children will have their destroy - * method called as well. 'options' will be passed on to those calls. - * @param {boolean} [options.texture=false] - Only used for child Sprites if options.children is set to true - * Should it destroy the texture of the child sprite - * @param {boolean} [options.baseTexture=false] - Only used for child Sprites if options.children is set to true - * Should it destroy the base texture of the child sprite - */ - Container.prototype.destroy = function (options) { - _super.prototype.destroy.call(this); - this.sortDirty = false; - var destroyChildren = typeof options === 'boolean' ? options : options && options.children; - var oldChildren = this.removeChildren(0, this.children.length); - if (destroyChildren) { - for (var i = 0; i < oldChildren.length; ++i) { - oldChildren[i].destroy(options); - } - } - }; - Object.defineProperty(Container.prototype, "width", { - /** - * The width of the Container, setting this will actually modify the scale to achieve the value set - * - * @member {number} - */ - get: function () { - return this.scale.x * this.getLocalBounds().width; - }, - set: function (value) { - var width = this.getLocalBounds().width; - if (width !== 0) { - this.scale.x = value / width; - } - else { - this.scale.x = 1; - } - this._width = value; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(Container.prototype, "height", { - /** - * The height of the Container, setting this will actually modify the scale to achieve the value set - * - * @member {number} - */ - get: function () { - return this.scale.y * this.getLocalBounds().height; - }, - set: function (value) { - var height = this.getLocalBounds().height; - if (height !== 0) { - this.scale.y = value / height; - } - else { - this.scale.y = 1; - } - this._height = value; - }, - enumerable: false, - configurable: true - }); - return Container; - }(DisplayObject)); - /** - * Container default updateTransform, does update children of container. - * Will crash if there's no parent element. - * - * @memberof PIXI.Container# - * @function containerUpdateTransform - */ - Container.prototype.containerUpdateTransform = Container.prototype.updateTransform; - - /*! - * @pixi/accessibility - v5.3.3 - * Compiled Tue, 04 Aug 2020 16:23:09 UTC - * - * @pixi/accessibility is licensed under the MIT License. - * http://www.opensource.org/licenses/mit-license - */ - - /** - * Default property values of accessible objects - * used by {@link PIXI.AccessibilityManager}. - * - * @private - * @function accessibleTarget - * @memberof PIXI - * @type {Object} - * @example - * function MyObject() {} - * - * Object.assign( - * MyObject.prototype, - * PIXI.accessibleTarget - * ); - */ - var accessibleTarget = { - /** - * Flag for if the object is accessible. If true AccessibilityManager will overlay a - * shadow div with attributes set - * - * @member {boolean} - * @memberof PIXI.DisplayObject# - */ - accessible: false, - /** - * Sets the title attribute of the shadow div - * If accessibleTitle AND accessibleHint has not been this will default to 'displayObject [tabIndex]' - * - * @member {?string} - * @memberof PIXI.DisplayObject# - */ - accessibleTitle: null, - /** - * Sets the aria-label attribute of the shadow div - * - * @member {string} - * @memberof PIXI.DisplayObject# - */ - accessibleHint: null, - /** - * @member {number} - * @memberof PIXI.DisplayObject# - * @private - * @todo Needs docs. - */ - tabIndex: 0, - /** - * @member {boolean} - * @memberof PIXI.DisplayObject# - * @todo Needs docs. - */ - _accessibleActive: false, - /** - * @member {boolean} - * @memberof PIXI.DisplayObject# - * @todo Needs docs. - */ - _accessibleDiv: null, - /** - * Specify the type of div the accessible layer is. Screen readers treat the element differently - * depending on this type. Defaults to button. - * - * @member {string} - * @memberof PIXI.DisplayObject# - * @default 'button' - */ - accessibleType: 'button', - /** - * Specify the pointer-events the accessible div will use - * Defaults to auto. - * - * @member {string} - * @memberof PIXI.DisplayObject# - * @default 'auto' - */ - accessiblePointerEvents: 'auto', - /** - * Setting to false will prevent any children inside this container to - * be accessible. Defaults to true. - * - * @member {boolean} - * @memberof PIXI.DisplayObject# - * @default true - */ - accessibleChildren: true, - renderId: -1, - }; - - // add some extra variables to the container.. - DisplayObject.mixin(accessibleTarget); - var KEY_CODE_TAB = 9; - var DIV_TOUCH_SIZE = 100; - var DIV_TOUCH_POS_X = 0; - var DIV_TOUCH_POS_Y = 0; - var DIV_TOUCH_ZINDEX = 2; - var DIV_HOOK_SIZE = 1; - var DIV_HOOK_POS_X = -1000; - var DIV_HOOK_POS_Y = -1000; - var DIV_HOOK_ZINDEX = 2; - /** - * The Accessibility manager recreates the ability to tab and have content read by screen readers. - * This is very important as it can possibly help people with disabilities access PixiJS content. - * - * A DisplayObject can be made accessible just like it can be made interactive. This manager will map the - * events as if the mouse was being used, minimizing the effort required to implement. - * - * An instance of this class is automatically created by default, and can be found at `renderer.plugins.accessibility` - * - * @class - * @memberof PIXI - */ - var AccessibilityManager = /** @class */ (function () { - /** - * @param {PIXI.CanvasRenderer|PIXI.Renderer} renderer - A reference to the current renderer - */ - function AccessibilityManager(renderer) { - /** - * @type {?HTMLElement} - * @private - */ - this._hookDiv = null; - if (isMobile$1.tablet || isMobile$1.phone) { - this.createTouchHook(); - } - // first we create a div that will sit over the PixiJS element. This is where the div overlays will go. - var div = document.createElement('div'); - div.style.width = DIV_TOUCH_SIZE + "px"; - div.style.height = DIV_TOUCH_SIZE + "px"; - div.style.position = 'absolute'; - div.style.top = DIV_TOUCH_POS_X + "px"; - div.style.left = DIV_TOUCH_POS_Y + "px"; - div.style.zIndex = DIV_TOUCH_ZINDEX.toString(); - /** - * This is the dom element that will sit over the PixiJS element. This is where the div overlays will go. - * - * @type {HTMLElement} - * @private - */ - this.div = div; - /** - * A simple pool for storing divs. - * - * @type {*} - * @private - */ - this.pool = []; - /** - * This is a tick used to check if an object is no longer being rendered. - * - * @type {Number} - * @private - */ - this.renderId = 0; - /** - * Setting this to true will visually show the divs. - * - * @type {boolean} - */ - this.debug = false; - /** - * The renderer this accessibility manager works for. - * - * @member {PIXI.AbstractRenderer} - */ - this.renderer = renderer; - /** - * The array of currently active accessible items. - * - * @member {Array<*>} - * @private - */ - this.children = []; - /** - * pre-bind the functions - * - * @type {Function} - * @private - */ - this._onKeyDown = this._onKeyDown.bind(this); - /** - * pre-bind the functions - * - * @type {Function} - * @private - */ - this._onMouseMove = this._onMouseMove.bind(this); - this._isActive = false; - this._isMobileAccessibility = false; - /** - * count to throttle div updates on android devices - * @type number - * @private - */ - this.androidUpdateCount = 0; - /** - * the frequency to update the div elements () - * @private - */ - this.androidUpdateFrequency = 500; // 2fps - // let listen for tab.. once pressed we can fire up and show the accessibility layer - window.addEventListener('keydown', this._onKeyDown, false); - } - Object.defineProperty(AccessibilityManager.prototype, "isActive", { - /** - * A flag - * @member {boolean} - * @readonly - */ - get: function () { - return this._isActive; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(AccessibilityManager.prototype, "isMobileAccessibility", { - /** - * A flag - * @member {boolean} - * @readonly - */ - get: function () { - return this._isMobileAccessibility; - }, - enumerable: false, - configurable: true - }); - /** - * Creates the touch hooks. - * - * @private - */ - AccessibilityManager.prototype.createTouchHook = function () { - var _this = this; - var hookDiv = document.createElement('button'); - hookDiv.style.width = DIV_HOOK_SIZE + "px"; - hookDiv.style.height = DIV_HOOK_SIZE + "px"; - hookDiv.style.position = 'absolute'; - hookDiv.style.top = DIV_HOOK_POS_X + "px"; - hookDiv.style.left = DIV_HOOK_POS_Y + "px"; - hookDiv.style.zIndex = DIV_HOOK_ZINDEX.toString(); - hookDiv.style.backgroundColor = '#FF0000'; - hookDiv.title = 'select to enable accessability for this content'; - hookDiv.addEventListener('focus', function () { - _this._isMobileAccessibility = true; - _this.activate(); - _this.destroyTouchHook(); - }); - document.body.appendChild(hookDiv); - this._hookDiv = hookDiv; - }; - /** - * Destroys the touch hooks. - * - * @private - */ - AccessibilityManager.prototype.destroyTouchHook = function () { - if (!this._hookDiv) { - return; - } - document.body.removeChild(this._hookDiv); - this._hookDiv = null; - }; - /** - * Activating will cause the Accessibility layer to be shown. - * This is called when a user presses the tab key. - * - * @private - */ - AccessibilityManager.prototype.activate = function () { - if (this._isActive) { - return; - } - this._isActive = true; - window.document.addEventListener('mousemove', this._onMouseMove, true); - window.removeEventListener('keydown', this._onKeyDown, false); - // TODO: Remove casting when CanvasRenderer is converted - this.renderer.on('postrender', this.update, this); - if (this.renderer.view.parentNode) { - this.renderer.view.parentNode.appendChild(this.div); - } - }; - /** - * Deactivating will cause the Accessibility layer to be hidden. - * This is called when a user moves the mouse. - * - * @private - */ - AccessibilityManager.prototype.deactivate = function () { - if (!this._isActive || this._isMobileAccessibility) { - return; - } - this._isActive = false; - window.document.removeEventListener('mousemove', this._onMouseMove, true); - window.addEventListener('keydown', this._onKeyDown, false); - // TODO: Remove casting when CanvasRenderer is converted - this.renderer.off('postrender', this.update); - if (this.div.parentNode) { - this.div.parentNode.removeChild(this.div); - } - }; - /** - * This recursive function will run through the scene graph and add any new accessible objects to the DOM layer. - * - * @private - * @param {PIXI.Container} displayObject - The DisplayObject to check. - */ - AccessibilityManager.prototype.updateAccessibleObjects = function (displayObject) { - if (!displayObject.visible || !displayObject.accessibleChildren) { - return; - } - if (displayObject.accessible && displayObject.interactive) { - if (!displayObject._accessibleActive) { - this.addChild(displayObject); - } - displayObject.renderId = this.renderId; - } - var children = displayObject.children; - for (var i = 0; i < children.length; i++) { - this.updateAccessibleObjects(children[i]); - } - }; - /** - * Before each render this function will ensure that all divs are mapped correctly to their DisplayObjects. - * - * @private - */ - AccessibilityManager.prototype.update = function () { - /* On Android default web browser, tab order seems to be calculated by position rather than tabIndex, - * moving buttons can cause focus to flicker between two buttons making it hard/impossible to navigate, - * so I am just running update every half a second, seems to fix it. - */ - var now = performance.now(); - if (isMobile$1.android.device && now < this.androidUpdateCount) { - return; - } - this.androidUpdateCount = now + this.androidUpdateFrequency; - if (!this.renderer.renderingToScreen) { - return; - } - // update children... - if (this.renderer._lastObjectRendered) { - this.updateAccessibleObjects(this.renderer._lastObjectRendered); - } - // TODO: Remove casting when CanvasRenderer is converted - var rect = this.renderer.view.getBoundingClientRect(); - var resolution = this.renderer.resolution; - var sx = (rect.width / this.renderer.width) * resolution; - var sy = (rect.height / this.renderer.height) * resolution; - var div = this.div; - div.style.left = rect.left + "px"; - div.style.top = rect.top + "px"; - div.style.width = this.renderer.width + "px"; - div.style.height = this.renderer.height + "px"; - for (var i = 0; i < this.children.length; i++) { - var child = this.children[i]; - if (child.renderId !== this.renderId) { - child._accessibleActive = false; - removeItems(this.children, i, 1); - this.div.removeChild(child._accessibleDiv); - this.pool.push(child._accessibleDiv); - child._accessibleDiv = null; - i--; - } - else { - // map div to display.. - div = child._accessibleDiv; - var hitArea = child.hitArea; - var wt = child.worldTransform; - if (child.hitArea) { - div.style.left = (wt.tx + (hitArea.x * wt.a)) * sx + "px"; - div.style.top = (wt.ty + (hitArea.y * wt.d)) * sy + "px"; - div.style.width = hitArea.width * wt.a * sx + "px"; - div.style.height = hitArea.height * wt.d * sy + "px"; - } - else { - hitArea = child.getBounds(); - this.capHitArea(hitArea); - div.style.left = hitArea.x * sx + "px"; - div.style.top = hitArea.y * sy + "px"; - div.style.width = hitArea.width * sx + "px"; - div.style.height = hitArea.height * sy + "px"; - // update button titles and hints if they exist and they've changed - if (div.title !== child.accessibleTitle && child.accessibleTitle !== null) { - div.title = child.accessibleTitle; - } - if (div.getAttribute('aria-label') !== child.accessibleHint - && child.accessibleHint !== null) { - div.setAttribute('aria-label', child.accessibleHint); - } - } - // the title or index may have changed, if so lets update it! - if (child.accessibleTitle !== div.title || child.tabIndex !== div.tabIndex) { - div.title = child.accessibleTitle; - div.tabIndex = child.tabIndex; - if (this.debug) - { this.updateDebugHTML(div); } - } - } - } - // increment the render id.. - this.renderId++; - }; - /** - * private function that will visually add the information to the - * accessability div - * - * @param {HTMLElement} div - */ - AccessibilityManager.prototype.updateDebugHTML = function (div) { - div.innerHTML = "type: " + div.type + "
title : " + div.title + "
tabIndex: " + div.tabIndex; - }; - /** - * Adjust the hit area based on the bounds of a display object - * - * @param {PIXI.Rectangle} hitArea - Bounds of the child - */ - AccessibilityManager.prototype.capHitArea = function (hitArea) { - if (hitArea.x < 0) { - hitArea.width += hitArea.x; - hitArea.x = 0; - } - if (hitArea.y < 0) { - hitArea.height += hitArea.y; - hitArea.y = 0; - } - // TODO: Remove casting when CanvasRenderer is converted - if (hitArea.x + hitArea.width > this.renderer.width) { - hitArea.width = this.renderer.width - hitArea.x; - } - if (hitArea.y + hitArea.height > this.renderer.height) { - hitArea.height = this.renderer.height - hitArea.y; - } - }; - /** - * Adds a DisplayObject to the accessibility manager - * - * @private - * @param {PIXI.DisplayObject} displayObject - The child to make accessible. - */ - AccessibilityManager.prototype.addChild = function (displayObject) { - // this.activate(); - var div = this.pool.pop(); - if (!div) { - div = document.createElement('button'); - div.style.width = DIV_TOUCH_SIZE + "px"; - div.style.height = DIV_TOUCH_SIZE + "px"; - div.style.backgroundColor = this.debug ? 'rgba(255,255,255,0.5)' : 'transparent'; - div.style.position = 'absolute'; - div.style.zIndex = DIV_TOUCH_ZINDEX.toString(); - div.style.borderStyle = 'none'; - // ARIA attributes ensure that button title and hint updates are announced properly - if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1) { - // Chrome doesn't need aria-live to work as intended; in fact it just gets more confused. - div.setAttribute('aria-live', 'off'); - } - else { - div.setAttribute('aria-live', 'polite'); - } - if (navigator.userAgent.match(/rv:.*Gecko\//)) { - // FireFox needs this to announce only the new button name - div.setAttribute('aria-relevant', 'additions'); - } - else { - // required by IE, other browsers don't much care - div.setAttribute('aria-relevant', 'text'); - } - div.addEventListener('click', this._onClick.bind(this)); - div.addEventListener('focus', this._onFocus.bind(this)); - div.addEventListener('focusout', this._onFocusOut.bind(this)); - } - // set pointer events - div.style.pointerEvents = displayObject.accessiblePointerEvents; - // set the type, this defaults to button! - div.type = displayObject.accessibleType; - if (displayObject.accessibleTitle && displayObject.accessibleTitle !== null) { - div.title = displayObject.accessibleTitle; - } - else if (!displayObject.accessibleHint - || displayObject.accessibleHint === null) { - div.title = "displayObject " + displayObject.tabIndex; - } - if (displayObject.accessibleHint - && displayObject.accessibleHint !== null) { - div.setAttribute('aria-label', displayObject.accessibleHint); - } - if (this.debug) - { this.updateDebugHTML(div); } - displayObject._accessibleActive = true; - displayObject._accessibleDiv = div; - div.displayObject = displayObject; - this.children.push(displayObject); - this.div.appendChild(displayObject._accessibleDiv); - displayObject._accessibleDiv.tabIndex = displayObject.tabIndex; - }; - /** - * Maps the div button press to pixi's InteractionManager (click) - * - * @private - * @param {MouseEvent} e - The click event. - */ - AccessibilityManager.prototype._onClick = function (e) { - // TODO: Remove casting when CanvasRenderer is converted - var interactionManager = this.renderer.plugins.interaction; - interactionManager.dispatchEvent(e.target.displayObject, 'click', interactionManager.eventData); - interactionManager.dispatchEvent(e.target.displayObject, 'pointertap', interactionManager.eventData); - interactionManager.dispatchEvent(e.target.displayObject, 'tap', interactionManager.eventData); - }; - /** - * Maps the div focus events to pixi's InteractionManager (mouseover) - * - * @private - * @param {FocusEvent} e - The focus event. - */ - AccessibilityManager.prototype._onFocus = function (e) { - if (!e.target.getAttribute('aria-live')) { - e.target.setAttribute('aria-live', 'assertive'); - } - // TODO: Remove casting when CanvasRenderer is converted - var interactionManager = this.renderer.plugins.interaction; - interactionManager.dispatchEvent(e.target.displayObject, 'mouseover', interactionManager.eventData); - }; - /** - * Maps the div focus events to pixi's InteractionManager (mouseout) - * - * @private - * @param {FocusEvent} e - The focusout event. - */ - AccessibilityManager.prototype._onFocusOut = function (e) { - if (!e.target.getAttribute('aria-live')) { - e.target.setAttribute('aria-live', 'polite'); - } - // TODO: Remove casting when CanvasRenderer is converted - var interactionManager = this.renderer.plugins.interaction; - interactionManager.dispatchEvent(e.target.displayObject, 'mouseout', interactionManager.eventData); - }; - /** - * Is called when a key is pressed - * - * @private - * @param {KeyboardEvent} e - The keydown event. - */ - AccessibilityManager.prototype._onKeyDown = function (e) { - if (e.keyCode !== KEY_CODE_TAB) { - return; - } - this.activate(); - }; - /** - * Is called when the mouse moves across the renderer element - * - * @private - * @param {MouseEvent} e - The mouse event. - */ - AccessibilityManager.prototype._onMouseMove = function (e) { - if (e.movementX === 0 && e.movementY === 0) { - return; - } - this.deactivate(); - }; - /** - * Destroys the accessibility manager - * - */ - AccessibilityManager.prototype.destroy = function () { - this.destroyTouchHook(); - this.div = null; - window.document.removeEventListener('mousemove', this._onMouseMove, true); - window.removeEventListener('keydown', this._onKeyDown); - this.pool = null; - this.children = null; - this.renderer = null; - }; - return AccessibilityManager; - }()); - - /*! - * @pixi/ticker - v5.3.3 - * Compiled Tue, 04 Aug 2020 16:23:09 UTC - * - * @pixi/ticker is licensed under the MIT License. - * http://www.opensource.org/licenses/mit-license - */ - - /** - * Target frames per millisecond. - * - * @static - * @name TARGET_FPMS - * @memberof PIXI.settings - * @type {number} - * @default 0.06 - */ - settings.TARGET_FPMS = 0.06; - - /** - * Represents the update priorities used by internal PIXI classes when registered with - * the {@link PIXI.Ticker} object. Higher priority items are updated first and lower - * priority items, such as render, should go later. - * - * @static - * @constant - * @name UPDATE_PRIORITY - * @memberof PIXI - * @enum {number} - * @property {number} INTERACTION=50 Highest priority, used for {@link PIXI.InteractionManager} - * @property {number} HIGH=25 High priority updating, {@link PIXI.VideoBaseTexture} and {@link PIXI.AnimatedSprite} - * @property {number} NORMAL=0 Default priority for ticker events, see {@link PIXI.Ticker#add}. - * @property {number} LOW=-25 Low priority used for {@link PIXI.Application} rendering. - * @property {number} UTILITY=-50 Lowest priority used for {@link PIXI.BasePrepare} utility. - */ - - (function (UPDATE_PRIORITY) { - UPDATE_PRIORITY[UPDATE_PRIORITY["INTERACTION"] = 50] = "INTERACTION"; - UPDATE_PRIORITY[UPDATE_PRIORITY["HIGH"] = 25] = "HIGH"; - UPDATE_PRIORITY[UPDATE_PRIORITY["NORMAL"] = 0] = "NORMAL"; - UPDATE_PRIORITY[UPDATE_PRIORITY["LOW"] = -25] = "LOW"; - UPDATE_PRIORITY[UPDATE_PRIORITY["UTILITY"] = -50] = "UTILITY"; - })(exports.UPDATE_PRIORITY || (exports.UPDATE_PRIORITY = {})); - - /** - * Internal class for handling the priority sorting of ticker handlers. - * - * @private - * @class - * @memberof PIXI - */ - var TickerListener = /** @class */ (function () { - /** - * Constructor - * @private - * @param {Function} fn - The listener function to be added for one update - * @param {*} [context=null] - The listener context - * @param {number} [priority=0] - The priority for emitting - * @param {boolean} [once=false] - If the handler should fire once - */ - function TickerListener(fn, context, priority, once) { - if (context === void 0) { context = null; } - if (priority === void 0) { priority = 0; } - if (once === void 0) { once = false; } - /** - * The handler function to execute. - * @private - * @member {Function} - */ - this.fn = fn; - /** - * The calling to execute. - * @private - * @member {*} - */ - this.context = context; - /** - * The current priority. - * @private - * @member {number} - */ - this.priority = priority; - /** - * If this should only execute once. - * @private - * @member {boolean} - */ - this.once = once; - /** - * The next item in chain. - * @private - * @member {TickerListener} - */ - this.next = null; - /** - * The previous item in chain. - * @private - * @member {TickerListener} - */ - this.previous = null; - /** - * `true` if this listener has been destroyed already. - * @member {boolean} - * @private - */ - this._destroyed = false; - } - /** - * Simple compare function to figure out if a function and context match. - * @private - * @param {Function} fn - The listener function to be added for one update - * @param {any} [context] - The listener context - * @return {boolean} `true` if the listener match the arguments - */ - TickerListener.prototype.match = function (fn, context) { - if (context === void 0) { context = null; } - return this.fn === fn && this.context === context; - }; - /** - * Emit by calling the current function. - * @private - * @param {number} deltaTime - time since the last emit. - * @return {TickerListener} Next ticker - */ - TickerListener.prototype.emit = function (deltaTime) { - if (this.fn) { - if (this.context) { - this.fn.call(this.context, deltaTime); - } - else { - this.fn(deltaTime); - } - } - var redirect = this.next; - if (this.once) { - this.destroy(true); - } - // Soft-destroying should remove - // the next reference - if (this._destroyed) { - this.next = null; - } - return redirect; - }; - /** - * Connect to the list. - * @private - * @param {TickerListener} previous - Input node, previous listener - */ - TickerListener.prototype.connect = function (previous) { - this.previous = previous; - if (previous.next) { - previous.next.previous = this; - } - this.next = previous.next; - previous.next = this; - }; - /** - * Destroy and don't use after this. - * @private - * @param {boolean} [hard = false] `true` to remove the `next` reference, this - * is considered a hard destroy. Soft destroy maintains the next reference. - * @return {TickerListener} The listener to redirect while emitting or removing. - */ - TickerListener.prototype.destroy = function (hard) { - if (hard === void 0) { hard = false; } - this._destroyed = true; - this.fn = null; - this.context = null; - // Disconnect, hook up next and previous - if (this.previous) { - this.previous.next = this.next; - } - if (this.next) { - this.next.previous = this.previous; - } - // Redirect to the next item - var redirect = this.next; - // Remove references - this.next = hard ? null : redirect; - this.previous = null; - return redirect; - }; - return TickerListener; - }()); - - /** - * A Ticker class that runs an update loop that other objects listen to. - * - * This class is composed around listeners meant for execution on the next requested animation frame. - * Animation frames are requested only when necessary, e.g. When the ticker is started and the emitter has listeners. - * - * @class - * @memberof PIXI - */ - var Ticker = /** @class */ (function () { - function Ticker() { - var _this = this; - /** - * The first listener. All new listeners added are chained on this. - * @private - * @type {TickerListener} - */ - this._head = new TickerListener(null, null, Infinity); - /** - * Internal current frame request ID - * @type {?number} - * @private - */ - this._requestId = null; - /** - * Internal value managed by minFPS property setter and getter. - * This is the maximum allowed milliseconds between updates. - * @type {number} - * @private - */ - this._maxElapsedMS = 100; - /** - * Internal value managed by maxFPS property setter and getter. - * This is the minimum allowed milliseconds between updates. - * @type {number} - * @private - */ - this._minElapsedMS = 0; - /** - * Whether or not this ticker should invoke the method - * {@link PIXI.Ticker#start} automatically - * when a listener is added. - * - * @member {boolean} - * @default false - */ - this.autoStart = false; - /** - * Scalar time value from last frame to this frame. - * This value is capped by setting {@link PIXI.Ticker#minFPS} - * and is scaled with {@link PIXI.Ticker#speed}. - * **Note:** The cap may be exceeded by scaling. - * - * @member {number} - * @default 1 - */ - this.deltaTime = 1; - /** - * Scaler time elapsed in milliseconds from last frame to this frame. - * This value is capped by setting {@link PIXI.Ticker#minFPS} - * and is scaled with {@link PIXI.Ticker#speed}. - * **Note:** The cap may be exceeded by scaling. - * If the platform supports DOMHighResTimeStamp, - * this value will have a precision of 1 µs. - * Defaults to target frame time - * - * @member {number} - * @default 16.66 - */ - this.deltaMS = 1 / settings.TARGET_FPMS; - /** - * Time elapsed in milliseconds from last frame to this frame. - * Opposed to what the scalar {@link PIXI.Ticker#deltaTime} - * is based, this value is neither capped nor scaled. - * If the platform supports DOMHighResTimeStamp, - * this value will have a precision of 1 µs. - * Defaults to target frame time - * - * @member {number} - * @default 16.66 - */ - this.elapsedMS = 1 / settings.TARGET_FPMS; - /** - * The last time {@link PIXI.Ticker#update} was invoked. - * This value is also reset internally outside of invoking - * update, but only when a new animation frame is requested. - * If the platform supports DOMHighResTimeStamp, - * this value will have a precision of 1 µs. - * - * @member {number} - * @default -1 - */ - this.lastTime = -1; - /** - * Factor of current {@link PIXI.Ticker#deltaTime}. - * @example - * // Scales ticker.deltaTime to what would be - * // the equivalent of approximately 120 FPS - * ticker.speed = 2; - * - * @member {number} - * @default 1 - */ - this.speed = 1; - /** - * Whether or not this ticker has been started. - * `true` if {@link PIXI.Ticker#start} has been called. - * `false` if {@link PIXI.Ticker#stop} has been called. - * While `false`, this value may change to `true` in the - * event of {@link PIXI.Ticker#autoStart} being `true` - * and a listener is added. - * - * @member {boolean} - * @default false - */ - this.started = false; - /** - * If enabled, deleting is disabled. - * @member {boolean} - * @default false - * @private - */ - this._protected = false; - /** - * The last time keyframe was executed. - * Maintains a relatively fixed interval with the previous value. - * @member {number} - * @default -1 - * @private - */ - this._lastFrame = -1; - /** - * Internal tick method bound to ticker instance. - * This is because in early 2015, Function.bind - * is still 60% slower in high performance scenarios. - * Also separating frame requests from update method - * so listeners may be called at any time and with - * any animation API, just invoke ticker.update(time). - * - * @private - * @param {number} time - Time since last tick. - */ - this._tick = function (time) { - _this._requestId = null; - if (_this.started) { - // Invoke listeners now - _this.update(time); - // Listener side effects may have modified ticker state. - if (_this.started && _this._requestId === null && _this._head.next) { - _this._requestId = requestAnimationFrame(_this._tick); - } - } - }; - } - /** - * Conditionally requests a new animation frame. - * If a frame has not already been requested, and if the internal - * emitter has listeners, a new frame is requested. - * - * @private - */ - Ticker.prototype._requestIfNeeded = function () { - if (this._requestId === null && this._head.next) { - // ensure callbacks get correct delta - this.lastTime = performance.now(); - this._lastFrame = this.lastTime; - this._requestId = requestAnimationFrame(this._tick); - } - }; - /** - * Conditionally cancels a pending animation frame. - * - * @private - */ - Ticker.prototype._cancelIfNeeded = function () { - if (this._requestId !== null) { - cancelAnimationFrame(this._requestId); - this._requestId = null; - } - }; - /** - * Conditionally requests a new animation frame. - * If the ticker has been started it checks if a frame has not already - * been requested, and if the internal emitter has listeners. If these - * conditions are met, a new frame is requested. If the ticker has not - * been started, but autoStart is `true`, then the ticker starts now, - * and continues with the previous conditions to request a new frame. - * - * @private - */ - Ticker.prototype._startIfPossible = function () { - if (this.started) { - this._requestIfNeeded(); - } - else if (this.autoStart) { - this.start(); - } - }; - /** - * Register a handler for tick events. Calls continuously unless - * it is removed or the ticker is stopped. - * - * @param {Function} fn - The listener function to be added for updates - * @param {*} [context] - The listener context - * @param {number} [priority=PIXI.UPDATE_PRIORITY.NORMAL] - The priority for emitting - * @returns {PIXI.Ticker} This instance of a ticker - */ - Ticker.prototype.add = function (fn, context, priority) { - if (priority === void 0) { priority = exports.UPDATE_PRIORITY.NORMAL; } - return this._addListener(new TickerListener(fn, context, priority)); - }; - /** - * Add a handler for the tick event which is only execute once. - * - * @param {Function} fn - The listener function to be added for one update - * @param {*} [context] - The listener context - * @param {number} [priority=PIXI.UPDATE_PRIORITY.NORMAL] - The priority for emitting - * @returns {PIXI.Ticker} This instance of a ticker - */ - Ticker.prototype.addOnce = function (fn, context, priority) { - if (priority === void 0) { priority = exports.UPDATE_PRIORITY.NORMAL; } - return this._addListener(new TickerListener(fn, context, priority, true)); - }; - /** - * Internally adds the event handler so that it can be sorted by priority. - * Priority allows certain handler (user, AnimatedSprite, Interaction) to be run - * before the rendering. - * - * @private - * @param {TickerListener} listener - Current listener being added. - * @returns {PIXI.Ticker} This instance of a ticker - */ - Ticker.prototype._addListener = function (listener) { - // For attaching to head - var current = this._head.next; - var previous = this._head; - // Add the first item - if (!current) { - listener.connect(previous); - } - else { - // Go from highest to lowest priority - while (current) { - if (listener.priority > current.priority) { - listener.connect(previous); - break; - } - previous = current; - current = current.next; - } - // Not yet connected - if (!listener.previous) { - listener.connect(previous); - } - } - this._startIfPossible(); - return this; - }; - /** - * Removes any handlers matching the function and context parameters. - * If no handlers are left after removing, then it cancels the animation frame. - * - * @param {Function} fn - The listener function to be removed - * @param {*} [context] - The listener context to be removed - * @returns {PIXI.Ticker} This instance of a ticker - */ - Ticker.prototype.remove = function (fn, context) { - var listener = this._head.next; - while (listener) { - // We found a match, lets remove it - // no break to delete all possible matches - // incase a listener was added 2+ times - if (listener.match(fn, context)) { - listener = listener.destroy(); - } - else { - listener = listener.next; - } - } - if (!this._head.next) { - this._cancelIfNeeded(); - } - return this; - }; - Object.defineProperty(Ticker.prototype, "count", { - /** - * The number of listeners on this ticker, calculated by walking through linked list - * - * @readonly - * @member {number} - */ - get: function () { - if (!this._head) { - return 0; - } - var count = 0; - var current = this._head; - while ((current = current.next)) { - count++; - } - return count; - }, - enumerable: false, - configurable: true - }); - /** - * Starts the ticker. If the ticker has listeners - * a new animation frame is requested at this point. - */ - Ticker.prototype.start = function () { - if (!this.started) { - this.started = true; - this._requestIfNeeded(); - } - }; - /** - * Stops the ticker. If the ticker has requested - * an animation frame it is canceled at this point. - */ - Ticker.prototype.stop = function () { - if (this.started) { - this.started = false; - this._cancelIfNeeded(); - } - }; - /** - * Destroy the ticker and don't use after this. Calling - * this method removes all references to internal events. - */ - Ticker.prototype.destroy = function () { - if (!this._protected) { - this.stop(); - var listener = this._head.next; - while (listener) { - listener = listener.destroy(true); - } - this._head.destroy(); - this._head = null; - } - }; - /** - * Triggers an update. An update entails setting the - * current {@link PIXI.Ticker#elapsedMS}, - * the current {@link PIXI.Ticker#deltaTime}, - * invoking all listeners with current deltaTime, - * and then finally setting {@link PIXI.Ticker#lastTime} - * with the value of currentTime that was provided. - * This method will be called automatically by animation - * frame callbacks if the ticker instance has been started - * and listeners are added. - * - * @param {number} [currentTime=performance.now()] - the current time of execution - */ - Ticker.prototype.update = function (currentTime) { - if (currentTime === void 0) { currentTime = performance.now(); } - var elapsedMS; - // If the difference in time is zero or negative, we ignore most of the work done here. - // If there is no valid difference, then should be no reason to let anyone know about it. - // A zero delta, is exactly that, nothing should update. - // - // The difference in time can be negative, and no this does not mean time traveling. - // This can be the result of a race condition between when an animation frame is requested - // on the current JavaScript engine event loop, and when the ticker's start method is invoked - // (which invokes the internal _requestIfNeeded method). If a frame is requested before - // _requestIfNeeded is invoked, then the callback for the animation frame the ticker requests, - // can receive a time argument that can be less than the lastTime value that was set within - // _requestIfNeeded. This difference is in microseconds, but this is enough to cause problems. - // - // This check covers this browser engine timing issue, as well as if consumers pass an invalid - // currentTime value. This may happen if consumers opt-out of the autoStart, and update themselves. - if (currentTime > this.lastTime) { - // Save uncapped elapsedMS for measurement - elapsedMS = this.elapsedMS = currentTime - this.lastTime; - // cap the milliseconds elapsed used for deltaTime - if (elapsedMS > this._maxElapsedMS) { - elapsedMS = this._maxElapsedMS; - } - elapsedMS *= this.speed; - // If not enough time has passed, exit the function. - // Get ready for next frame by setting _lastFrame, but based on _minElapsedMS - // adjustment to ensure a relatively stable interval. - if (this._minElapsedMS) { - var delta = currentTime - this._lastFrame | 0; - if (delta < this._minElapsedMS) { - return; - } - this._lastFrame = currentTime - (delta % this._minElapsedMS); - } - this.deltaMS = elapsedMS; - this.deltaTime = this.deltaMS * settings.TARGET_FPMS; - // Cache a local reference, in-case ticker is destroyed - // during the emit, we can still check for head.next - var head = this._head; - // Invoke listeners added to internal emitter - var listener = head.next; - while (listener) { - listener = listener.emit(this.deltaTime); - } - if (!head.next) { - this._cancelIfNeeded(); - } - } - else { - this.deltaTime = this.deltaMS = this.elapsedMS = 0; - } - this.lastTime = currentTime; - }; - Object.defineProperty(Ticker.prototype, "FPS", { - /** - * The frames per second at which this ticker is running. - * The default is approximately 60 in most modern browsers. - * **Note:** This does not factor in the value of - * {@link PIXI.Ticker#speed}, which is specific - * to scaling {@link PIXI.Ticker#deltaTime}. - * - * @member {number} - * @readonly - */ - get: function () { - return 1000 / this.elapsedMS; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(Ticker.prototype, "minFPS", { - /** - * Manages the maximum amount of milliseconds allowed to - * elapse between invoking {@link PIXI.Ticker#update}. - * This value is used to cap {@link PIXI.Ticker#deltaTime}, - * but does not effect the measured value of {@link PIXI.Ticker#FPS}. - * When setting this property it is clamped to a value between - * `0` and `PIXI.settings.TARGET_FPMS * 1000`. - * - * @member {number} - * @default 10 - */ - get: function () { - return 1000 / this._maxElapsedMS; - }, - set: function (fps) { - // Minimum must be below the maxFPS - var minFPS = Math.min(this.maxFPS, fps); - // Must be at least 0, but below 1 / settings.TARGET_FPMS - var minFPMS = Math.min(Math.max(0, minFPS) / 1000, settings.TARGET_FPMS); - this._maxElapsedMS = 1 / minFPMS; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(Ticker.prototype, "maxFPS", { - /** - * Manages the minimum amount of milliseconds required to - * elapse between invoking {@link PIXI.Ticker#update}. - * This will effect the measured value of {@link PIXI.Ticker#FPS}. - * If it is set to `0`, then there is no limit; PixiJS will render as many frames as it can. - * Otherwise it will be at least `minFPS` - * - * @member {number} - * @default 0 - */ - get: function () { - if (this._minElapsedMS) { - return Math.round(1000 / this._minElapsedMS); - } - return 0; - }, - set: function (fps) { - if (fps === 0) { - this._minElapsedMS = 0; - } - else { - // Max must be at least the minFPS - var maxFPS = Math.max(this.minFPS, fps); - this._minElapsedMS = 1 / (maxFPS / 1000); - } - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(Ticker, "shared", { - /** - * The shared ticker instance used by {@link PIXI.AnimatedSprite} and by - * {@link PIXI.VideoResource} to update animation frames / video textures. - * - * It may also be used by {@link PIXI.Application} if created with the `sharedTicker` option property set to true. - * - * The property {@link PIXI.Ticker#autoStart} is set to `true` for this instance. - * Please follow the examples for usage, including how to opt-out of auto-starting the shared ticker. - * - * @example - * let ticker = PIXI.Ticker.shared; - * // Set this to prevent starting this ticker when listeners are added. - * // By default this is true only for the PIXI.Ticker.shared instance. - * ticker.autoStart = false; - * // FYI, call this to ensure the ticker is stopped. It should be stopped - * // if you have not attempted to render anything yet. - * ticker.stop(); - * // Call this when you are ready for a running shared ticker. - * ticker.start(); - * - * @example - * // You may use the shared ticker to render... - * let renderer = PIXI.autoDetectRenderer(); - * let stage = new PIXI.Container(); - * document.body.appendChild(renderer.view); - * ticker.add(function (time) { - * renderer.render(stage); - * }); - * - * @example - * // Or you can just update it manually. - * ticker.autoStart = false; - * ticker.stop(); - * function animate(time) { - * ticker.update(time); - * renderer.render(stage); - * requestAnimationFrame(animate); - * } - * animate(performance.now()); - * - * @member {PIXI.Ticker} - * @static - */ - get: function () { - if (!Ticker._shared) { - var shared = Ticker._shared = new Ticker(); - shared.autoStart = true; - shared._protected = true; - } - return Ticker._shared; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(Ticker, "system", { - /** - * The system ticker instance used by {@link PIXI.InteractionManager} and by - * {@link PIXI.BasePrepare} for core timing functionality that shouldn't usually need to be paused, - * unlike the `shared` ticker which drives visual animations and rendering which may want to be paused. - * - * The property {@link PIXI.Ticker#autoStart} is set to `true` for this instance. - * - * @member {PIXI.Ticker} - * @static - */ - get: function () { - if (!Ticker._system) { - var system = Ticker._system = new Ticker(); - system.autoStart = true; - system._protected = true; - } - return Ticker._system; - }, - enumerable: false, - configurable: true - }); - return Ticker; - }()); - - /** - * Middleware for for Application Ticker. - * - * @example - * import {TickerPlugin} from '@pixi/ticker'; - * import {Application} from '@pixi/app'; - * Application.registerPlugin(TickerPlugin); - * - * @class - * @memberof PIXI - */ - var TickerPlugin = /** @class */ (function () { - function TickerPlugin() { - } - /** - * Initialize the plugin with scope of application instance - * - * @static - * @private - * @param {object} [options] - See application options - */ - TickerPlugin.init = function (options) { - var _this = this; - // Set default - options = Object.assign({ - autoStart: true, - sharedTicker: false, - }, options); - // Create ticker setter - Object.defineProperty(this, 'ticker', { - set: function (ticker) { - if (this._ticker) { - this._ticker.remove(this.render, this); - } - this._ticker = ticker; - if (ticker) { - ticker.add(this.render, this, exports.UPDATE_PRIORITY.LOW); - } - }, - get: function () { - return this._ticker; - }, - }); - /** - * Convenience method for stopping the render. - * - * @method PIXI.Application#stop - */ - this.stop = function () { - _this._ticker.stop(); - }; - /** - * Convenience method for starting the render. - * - * @method PIXI.Application#start - */ - this.start = function () { - _this._ticker.start(); - }; - /** - * Internal reference to the ticker. - * - * @type {PIXI.Ticker} - * @name _ticker - * @memberof PIXI.Application# - * @private - */ - this._ticker = null; - /** - * Ticker for doing render updates. - * - * @type {PIXI.Ticker} - * @name ticker - * @memberof PIXI.Application# - * @default PIXI.Ticker.shared - */ - this.ticker = options.sharedTicker ? Ticker.shared : new Ticker(); - // Start the rendering - if (options.autoStart) { - this.start(); - } - }; - /** - * Clean up the ticker, scoped to application. - * - * @static - * @private - */ - TickerPlugin.destroy = function () { - if (this._ticker) { - var oldTicker = this._ticker; - this.ticker = null; - oldTicker.destroy(); - } - }; - return TickerPlugin; - }()); - - /*! - * @pixi/interaction - v5.3.3 - * Compiled Tue, 04 Aug 2020 16:23:09 UTC - * - * @pixi/interaction is licensed under the MIT License. - * http://www.opensource.org/licenses/mit-license - */ - - /** - * Holds all information related to an Interaction event - * - * @class - * @memberof PIXI - */ - var InteractionData = /** @class */ (function () { - function InteractionData() { - this.pressure = 0; - this.rotationAngle = 0; - this.twist = 0; - this.tangentialPressure = 0; - /** - * This point stores the global coords of where the touch/mouse event happened - * - * @member {PIXI.Point} - */ - this.global = new Point(); - /** - * The target Sprite that was interacted with - * - * @member {PIXI.Sprite} - */ - this.target = null; - /** - * When passed to an event handler, this will be the original DOM Event that was captured - * - * @see https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent - * @see https://developer.mozilla.org/en-US/docs/Web/API/TouchEvent - * @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent - * @member {MouseEvent|TouchEvent|PointerEvent} - */ - this.originalEvent = null; - /** - * Unique identifier for this interaction - * - * @member {number} - */ - this.identifier = null; - /** - * Indicates whether or not the pointer device that created the event is the primary pointer. - * @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/isPrimary - * @type {Boolean} - */ - this.isPrimary = false; - /** - * Indicates which button was pressed on the mouse or pointer device to trigger the event. - * @see https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/button - * @type {number} - */ - this.button = 0; - /** - * Indicates which buttons are pressed on the mouse or pointer device when the event is triggered. - * @see https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/buttons - * @type {number} - */ - this.buttons = 0; - /** - * The width of the pointer's contact along the x-axis, measured in CSS pixels. - * radiusX of TouchEvents will be represented by this value. - * @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/width - * @type {number} - */ - this.width = 0; - /** - * The height of the pointer's contact along the y-axis, measured in CSS pixels. - * radiusY of TouchEvents will be represented by this value. - * @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/height - * @type {number} - */ - this.height = 0; - /** - * The angle, in degrees, between the pointer device and the screen. - * @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/tiltX - * @type {number} - */ - this.tiltX = 0; - /** - * The angle, in degrees, between the pointer device and the screen. - * @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/tiltY - * @type {number} - */ - this.tiltY = 0; - /** - * The type of pointer that triggered the event. - * @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/pointerType - * @type {string} - */ - this.pointerType = null; - /** - * Pressure applied by the pointing device during the event. A Touch's force property - * will be represented by this value. - * @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/pressure - * @type {number} - */ - this.pressure = 0; - /** - * From TouchEvents (not PointerEvents triggered by touches), the rotationAngle of the Touch. - * @see https://developer.mozilla.org/en-US/docs/Web/API/Touch/rotationAngle - * @type {number} - */ - this.rotationAngle = 0; - /** - * Twist of a stylus pointer. - * @see https://w3c.github.io/pointerevents/#pointerevent-interface - * @type {number} - */ - this.twist = 0; - /** - * Barrel pressure on a stylus pointer. - * @see https://w3c.github.io/pointerevents/#pointerevent-interface - * @type {number} - */ - this.tangentialPressure = 0; - } - Object.defineProperty(InteractionData.prototype, "pointerId", { - /** - * The unique identifier of the pointer. It will be the same as `identifier`. - * @readonly - * @member {number} - * @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/pointerId - */ - get: function () { - return this.identifier; - }, - enumerable: false, - configurable: true - }); - /** - * This will return the local coordinates of the specified displayObject for this InteractionData - * - * @param {PIXI.DisplayObject} displayObject - The DisplayObject that you would like the local - * coords off - * @param {PIXI.Point} [point] - A Point object in which to store the value, optional (otherwise - * will create a new point) - * @param {PIXI.Point} [globalPos] - A Point object containing your custom global coords, optional - * (otherwise will use the current global coords) - * @return {PIXI.Point} A point containing the coordinates of the InteractionData position relative - * to the DisplayObject - */ - InteractionData.prototype.getLocalPosition = function (displayObject, point, globalPos) { - return displayObject.worldTransform.applyInverse(globalPos || this.global, point); - }; - /** - * Copies properties from normalized event data. - * - * @param {Touch|MouseEvent|PointerEvent} event - The normalized event data - */ - InteractionData.prototype.copyEvent = function (event) { - // isPrimary should only change on touchstart/pointerdown, so we don't want to overwrite - // it with "false" on later events when our shim for it on touch events might not be - // accurate - if ('isPrimary' in event && event.isPrimary) { - this.isPrimary = true; - } - this.button = 'button' in event && event.button; - // event.buttons is not available in all browsers (ie. Safari), but it does have a non-standard - // event.which property instead, which conveys the same information. - var buttons = 'buttons' in event && event.buttons; - this.buttons = Number.isInteger(buttons) ? buttons : 'which' in event && event.which; - this.width = 'width' in event && event.width; - this.height = 'height' in event && event.height; - this.tiltX = 'tiltX' in event && event.tiltX; - this.tiltY = 'tiltY' in event && event.tiltY; - this.pointerType = 'pointerType' in event && event.pointerType; - this.pressure = 'pressure' in event && event.pressure; - this.rotationAngle = 'rotationAngle' in event && event.rotationAngle; - this.twist = ('twist' in event && event.twist) || 0; - this.tangentialPressure = ('tangentialPressure' in event && event.tangentialPressure) || 0; - }; - /** - * Resets the data for pooling. - */ - InteractionData.prototype.reset = function () { - // isPrimary is the only property that we really need to reset - everything else is - // guaranteed to be overwritten - this.isPrimary = false; - }; - return InteractionData; - }()); - - /*! ***************************************************************************** - Copyright (c) Microsoft Corporation. All rights reserved. - Licensed under the Apache License, Version 2.0 (the "License"); you may not use - this file except in compliance with the License. You may obtain a copy of the - License at http://www.apache.org/licenses/LICENSE-2.0 + function __extends$j(d, b) { + extendStatics$j(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + } + + /** + * The base class for all objects that are rendered on the screen. + * + * This is an abstract class and can not be used on its own; rather it should be extended. + * + * ## Display objects implemented in PixiJS + * + * | Display Object | Description | + * | ------------------------------- | --------------------------------------------------------------------- | + * | {@link PIXI.Container} | Adds support for `children` to DisplayObject | + * | {@link PIXI.Graphics} | Shape-drawing display object similar to the Canvas API | + * | {@link PIXI.Sprite} | Draws textures (i.e. images) | + * | {@link PIXI.Text} | Draws text using the Canvas API internally | + * | {@link PIXI.BitmapText} | More scaleable solution for text rendering, reusing glyph textures | + * | {@link PIXI.TilingSprite} | Draws textures/images in a tiled fashion | + * | {@link PIXI.AnimatedSprite} | Draws an animation of multiple images | + * | {@link PIXI.Mesh} | Provides a lower-level API for drawing meshes with custom data | + * | {@link PIXI.NineSlicePlane} | Mesh-related | + * | {@link PIXI.SimpleMesh} | v4-compatible mesh | + * | {@link PIXI.SimplePlane} | Mesh-related | + * | {@link PIXI.SimpleRope} | Mesh-related | + * + * ## Transforms + * + * The [transform]{@link DisplayObject#transform} of a display object describes the projection from its + * local coordinate space to its parent's local coordinate space. The following properties are derived + * from the transform: + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
PropertyDescription
[pivot]{@link PIXI.DisplayObject#pivot} + * Invariant under rotation, scaling, and skewing. The projection of into the parent's space of the pivot + * is equal to position, regardless of the other three transformations. In other words, It is the center of + * rotation, scaling, and skewing. + *
[position]{@link PIXI.DisplayObject#position} + * Translation. This is the position of the [pivot]{@link PIXI.DisplayObject#pivot} in the parent's local + * space. The default value of the pivot is the origin (0,0). If the top-left corner of your display object + * is (0,0) in its local space, then the position will be its top-left corner in the parent's local space. + *
[scale]{@link PIXI.DisplayObject#scale} + * Scaling. This will stretch (or compress) the display object's projection. The scale factors are along the + * local coordinate axes. In other words, the display object is scaled before rotated or skewed. The center + * of scaling is the [pivot]{@link PIXI.DisplayObject#pivot}. + *
[rotation]{@link PIXI.DisplayObject#rotation} + * Rotation. This will rotate the display object's projection by this angle (in radians). + *
[skew]{@link PIXI.DisplayObject#skew} + *

Skewing. This can be used to deform a rectangular display object into a parallelogram.

+ *

+ * In PixiJS, skew has a slightly different behaviour than the conventional meaning. It can be + * thought of the net rotation applied to the coordinate axes (separately). For example, if "skew.x" is + * ⍺ and "skew.y" is β, then the line x = 0 will be rotated by ⍺ (y = -x*cot⍺) and the line y = 0 will be + * rotated by β (y = x*tanβ). A line y = x*tanϴ (i.e. a line at angle ϴ to the x-axis in local-space) will + * be rotated by an angle between ⍺ and β. + *

+ *

+ * It can be observed that if skew is applied equally to both axes, then it will be equivalent to applying + * a rotation. Indeed, if "skew.x" = -ϴ and "skew.y" = ϴ, it will produce an equivalent of "rotation" = ϴ. + *

+ *

+ * Another quite interesting observation is that "skew.x", "skew.y", rotation are communtative operations. Indeed, + * because rotation is essentially a careful combination of the two. + *

+ *
angleRotation. This is an alias for [rotation]{@link PIXI.DisplayObject#rotation}, but in degrees.
xTranslation. This is an alias for position.x!
yTranslation. This is an alias for position.y!
width + * Implemented in [Container]{@link PIXI.Container}. Scaling. The width property calculates scale.x by dividing + * the "requested" width by the local bounding box width. It is indirectly an abstraction over scale.x, and there + * is no concept of user-defined width. + *
height + * Implemented in [Container]{@link PIXI.Container}. Scaling. The height property calculates scale.y by dividing + * the "requested" height by the local bounding box height. It is indirectly an abstraction over scale.y, and there + * is no concept of user-defined height. + *
+ * + * ## Bounds + * + * The bounds of a display object is defined by the minimum axis-aligned rectangle in world space that can fit + * around it. The abstract `calculateBounds` method is responsible for providing it (and it should use the + * `worldTransform` to calculate in world space). + * + * There are a few additional types of bounding boxes: + * + * | Bounds | Description | + * | --------------------- | ---------------------------------------------------------------------------------------- | + * | World Bounds | This is synonymous is the regular bounds described above. See `getBounds()`. | + * | Local Bounds | This the axis-aligned bounding box in the parent's local space. See `getLocalBounds()`. | + * | Render Bounds | The bounds, but including extra rendering effects like filter padding. | + * | Projected Bounds | The bounds of the projected display object onto the screen. Usually equals world bounds. | + * | Relative Bounds | The bounds of a display object when projected onto a ancestor's (or parent's) space. | + * | Natural Bounds | The bounds of an object in its own local space (not parent's space, like in local bounds)| + * | Content Bounds | The natural bounds when excluding all children of a `Container`. | + * + * ### calculateBounds + * + * [Container]{@link Container} already implements `calculateBounds` in a manner that includes children. + * + * But for a non-Container display object, the `calculateBounds` method must be overridden in order for `getBounds` and + * `getLocalBounds` to work. This method must write the bounds into `this._bounds`. + * + * Generally, the following technique works for most simple cases: take the list of points + * forming the "hull" of the object (i.e. outline of the object's shape), and then add them + * using {@link PIXI.Bounds#addPointMatrix}. + * + * ```js + * calculateBounds(): void + * { + * const points = [...]; + * + * for (let i = 0, j = points.length; i < j; i++) + * { + * this._bounds.addPointMatrix(this.worldTransform, points[i]); + * } + * } + * ``` + * + * You can optimize this for a large number of points by using {@link PIXI.Bounds#addVerticesMatrix} to pass them + * in one array together. + * + * ## Alpha + * + * This alpha sets a display object's **relative opacity** w.r.t its parent. For example, if the alpha of a display + * object is 0.5 and its parent's alpha is 0.5, then it will be rendered with 25% opacity (assuming alpha is not + * applied on any ancestor further up the chain). + * + * The alpha with which the display object will be rendered is called the [worldAlpha]{@link PIXI.DisplayObject#worldAlpha}. + * + * ## Renderable vs Visible + * + * The `renderable` and `visible` properties can be used to prevent a display object from being rendered to the + * screen. However, there is a subtle difference between the two. When using `renderable`, the transforms of the display + * object (and its children subtree) will continue to be calculated. When using `visible`, the transforms will not + * be calculated. + * + * It is recommended that applications use the `renderable` property for culling. See + * [@pixi-essentials/cull]{@link https://www.npmjs.com/package/@pixi-essentials/cull} or + * [pixi-cull]{@link https://www.npmjs.com/package/pixi-cull} for more details. + * + * Otherwise, to prevent an object from rendering in the general-purpose sense - `visible` is the property to use. This + * one is also better in terms of performance. + * @memberof PIXI + */ + var DisplayObject = /** @class */ (function (_super) { + __extends$j(DisplayObject, _super); + function DisplayObject() { + var _this = _super.call(this) || this; + _this.tempDisplayObjectParent = null; + // TODO: need to create Transform from factory + _this.transform = new Transform(); + _this.alpha = 1; + _this.visible = true; + _this.renderable = true; + _this.cullable = false; + _this.cullArea = null; + _this.parent = null; + _this.worldAlpha = 1; + _this._lastSortedIndex = 0; + _this._zIndex = 0; + _this.filterArea = null; + _this.filters = null; + _this._enabledFilters = null; + _this._bounds = new Bounds(); + _this._localBounds = null; + _this._boundsID = 0; + _this._boundsRect = null; + _this._localBoundsRect = null; + _this._mask = null; + _this._maskRefCount = 0; + _this._destroyed = false; + _this.isSprite = false; + _this.isMask = false; + return _this; + } + /** + * Mixes all enumerable properties and methods from a source object to DisplayObject. + * @param source - The source of properties and methods to mix in. + */ + DisplayObject.mixin = function (source) { + // in ES8/ES2017, this would be really easy: + // Object.defineProperties(DisplayObject.prototype, Object.getOwnPropertyDescriptors(source)); + // get all the enumerable property keys + var keys = Object.keys(source); + // loop through properties + for (var i = 0; i < keys.length; ++i) { + var propertyName = keys[i]; + // Set the property using the property descriptor - this works for accessors and normal value properties + Object.defineProperty(DisplayObject.prototype, propertyName, Object.getOwnPropertyDescriptor(source, propertyName)); + } + }; + Object.defineProperty(DisplayObject.prototype, "destroyed", { + /** + * Fired when this DisplayObject is added to a Container. + * @instance + * @event added + * @param {PIXI.Container} container - The container added to. + */ + /** + * Fired when this DisplayObject is removed from a Container. + * @instance + * @event removed + * @param {PIXI.Container} container - The container removed from. + */ + /** + * Fired when this DisplayObject is destroyed. This event is emitted once + * destroy is finished. + * @instance + * @event destroyed + */ + /** Readonly flag for destroyed display objects. */ + get: function () { + return this._destroyed; + }, + enumerable: false, + configurable: true + }); + /** Recursively updates transform of all objects from the root to this one internal function for toLocal() */ + DisplayObject.prototype._recursivePostUpdateTransform = function () { + if (this.parent) { + this.parent._recursivePostUpdateTransform(); + this.transform.updateTransform(this.parent.transform); + } + else { + this.transform.updateTransform(this._tempDisplayObjectParent.transform); + } + }; + /** Updates the object transform for rendering. TODO - Optimization pass! */ + DisplayObject.prototype.updateTransform = function () { + this._boundsID++; + this.transform.updateTransform(this.parent.transform); + // multiply the alphas.. + this.worldAlpha = this.alpha * this.parent.worldAlpha; + }; + /** + * Calculates and returns the (world) bounds of the display object as a [Rectangle]{@link PIXI.Rectangle}. + * + * This method is expensive on containers with a large subtree (like the stage). This is because the bounds + * of a container depend on its children's bounds, which recursively causes all bounds in the subtree to + * be recalculated. The upside, however, is that calling `getBounds` once on a container will indeed update + * the bounds of all children (the whole subtree, in fact). This side effect should be exploited by using + * `displayObject._bounds.getRectangle()` when traversing through all the bounds in a scene graph. Otherwise, + * calling `getBounds` on each object in a subtree will cause the total cost to increase quadratically as + * its height increases. + * + * The transforms of all objects in a container's **subtree** and of all **ancestors** are updated. + * The world bounds of all display objects in a container's **subtree** will also be recalculated. + * + * The `_bounds` object stores the last calculation of the bounds. You can use to entirely skip bounds + * calculation if needed. + * + * ```js + * const lastCalculatedBounds = displayObject._bounds.getRectangle(optionalRect); + * ``` + * + * Do know that usage of `getLocalBounds` can corrupt the `_bounds` of children (the whole subtree, actually). This + * is a known issue that has not been solved. See [getLocalBounds]{@link PIXI.DisplayObject#getLocalBounds} for more + * details. + * + * `getBounds` should be called with `skipUpdate` equal to `true` in a render() call. This is because the transforms + * are guaranteed to be update-to-date. In fact, recalculating inside a render() call may cause corruption in certain + * cases. + * @param skipUpdate - Setting to `true` will stop the transforms of the scene graph from + * being updated. This means the calculation returned MAY be out of date BUT will give you a + * nice performance boost. + * @param rect - Optional rectangle to store the result of the bounds calculation. + * @returns - The minimum axis-aligned rectangle in world space that fits around this object. + */ + DisplayObject.prototype.getBounds = function (skipUpdate, rect) { + if (!skipUpdate) { + if (!this.parent) { + this.parent = this._tempDisplayObjectParent; + this.updateTransform(); + this.parent = null; + } + else { + this._recursivePostUpdateTransform(); + this.updateTransform(); + } + } + if (this._bounds.updateID !== this._boundsID) { + this.calculateBounds(); + this._bounds.updateID = this._boundsID; + } + if (!rect) { + if (!this._boundsRect) { + this._boundsRect = new Rectangle(); + } + rect = this._boundsRect; + } + return this._bounds.getRectangle(rect); + }; + /** + * Retrieves the local bounds of the displayObject as a rectangle object. + * @param rect - Optional rectangle to store the result of the bounds calculation. + * @returns - The rectangular bounding area. + */ + DisplayObject.prototype.getLocalBounds = function (rect) { + if (!rect) { + if (!this._localBoundsRect) { + this._localBoundsRect = new Rectangle(); + } + rect = this._localBoundsRect; + } + if (!this._localBounds) { + this._localBounds = new Bounds(); + } + var transformRef = this.transform; + var parentRef = this.parent; + this.parent = null; + this.transform = this._tempDisplayObjectParent.transform; + var worldBounds = this._bounds; + var worldBoundsID = this._boundsID; + this._bounds = this._localBounds; + var bounds = this.getBounds(false, rect); + this.parent = parentRef; + this.transform = transformRef; + this._bounds = worldBounds; + this._bounds.updateID += this._boundsID - worldBoundsID; // reflect side-effects + return bounds; + }; + /** + * Calculates the global position of the display object. + * @param position - The world origin to calculate from. + * @param point - A Point object in which to store the value, optional + * (otherwise will create a new Point). + * @param skipUpdate - Should we skip the update transform. + * @returns - A point object representing the position of this object. + */ + DisplayObject.prototype.toGlobal = function (position, point, skipUpdate) { + if (skipUpdate === void 0) { skipUpdate = false; } + if (!skipUpdate) { + this._recursivePostUpdateTransform(); + // this parent check is for just in case the item is a root object. + // If it is we need to give it a temporary parent so that displayObjectUpdateTransform works correctly + // this is mainly to avoid a parent check in the main loop. Every little helps for performance :) + if (!this.parent) { + this.parent = this._tempDisplayObjectParent; + this.displayObjectUpdateTransform(); + this.parent = null; + } + else { + this.displayObjectUpdateTransform(); + } + } + // don't need to update the lot + return this.worldTransform.apply(position, point); + }; + /** + * Calculates the local position of the display object relative to another point. + * @param position - The world origin to calculate from. + * @param from - The DisplayObject to calculate the global position from. + * @param point - A Point object in which to store the value, optional + * (otherwise will create a new Point). + * @param skipUpdate - Should we skip the update transform + * @returns - A point object representing the position of this object + */ + DisplayObject.prototype.toLocal = function (position, from, point, skipUpdate) { + if (from) { + position = from.toGlobal(position, point, skipUpdate); + } + if (!skipUpdate) { + this._recursivePostUpdateTransform(); + // this parent check is for just in case the item is a root object. + // If it is we need to give it a temporary parent so that displayObjectUpdateTransform works correctly + // this is mainly to avoid a parent check in the main loop. Every little helps for performance :) + if (!this.parent) { + this.parent = this._tempDisplayObjectParent; + this.displayObjectUpdateTransform(); + this.parent = null; + } + else { + this.displayObjectUpdateTransform(); + } + } + // simply apply the matrix.. + return this.worldTransform.applyInverse(position, point); + }; + /** + * Set the parent Container of this DisplayObject. + * @param container - The Container to add this DisplayObject to. + * @returns - The Container that this DisplayObject was added to. + */ + DisplayObject.prototype.setParent = function (container) { + if (!container || !container.addChild) { + throw new Error('setParent: Argument must be a Container'); + } + container.addChild(this); + return container; + }; + /** + * Convenience function to set the position, scale, skew and pivot at once. + * @param x - The X position + * @param y - The Y position + * @param scaleX - The X scale value + * @param scaleY - The Y scale value + * @param rotation - The rotation + * @param skewX - The X skew value + * @param skewY - The Y skew value + * @param pivotX - The X pivot value + * @param pivotY - The Y pivot value + * @returns - The DisplayObject instance + */ + DisplayObject.prototype.setTransform = function (x, y, scaleX, scaleY, rotation, skewX, skewY, pivotX, pivotY) { + if (x === void 0) { x = 0; } + if (y === void 0) { y = 0; } + if (scaleX === void 0) { scaleX = 1; } + if (scaleY === void 0) { scaleY = 1; } + if (rotation === void 0) { rotation = 0; } + if (skewX === void 0) { skewX = 0; } + if (skewY === void 0) { skewY = 0; } + if (pivotX === void 0) { pivotX = 0; } + if (pivotY === void 0) { pivotY = 0; } + this.position.x = x; + this.position.y = y; + this.scale.x = !scaleX ? 1 : scaleX; + this.scale.y = !scaleY ? 1 : scaleY; + this.rotation = rotation; + this.skew.x = skewX; + this.skew.y = skewY; + this.pivot.x = pivotX; + this.pivot.y = pivotY; + return this; + }; + /** + * Base destroy method for generic display objects. This will automatically + * remove the display object from its parent Container as well as remove + * all current event listeners and internal references. Do not use a DisplayObject + * after calling `destroy()`. + * @param _options + */ + DisplayObject.prototype.destroy = function (_options) { + if (this.parent) { + this.parent.removeChild(this); + } + this._destroyed = true; + this.transform = null; + this.parent = null; + this._bounds = null; + this.mask = null; + this.cullArea = null; + this.filters = null; + this.filterArea = null; + this.hitArea = null; + this.interactive = false; + this.interactiveChildren = false; + this.emit('destroyed'); + this.removeAllListeners(); + }; + Object.defineProperty(DisplayObject.prototype, "_tempDisplayObjectParent", { + /** + * @protected + * @member {PIXI.Container} + */ + get: function () { + if (this.tempDisplayObjectParent === null) { + // eslint-disable-next-line @typescript-eslint/no-use-before-define + this.tempDisplayObjectParent = new TemporaryDisplayObject(); + } + return this.tempDisplayObjectParent; + }, + enumerable: false, + configurable: true + }); + /** + * Used in Renderer, cacheAsBitmap and other places where you call an `updateTransform` on root + * + * ``` + * const cacheParent = elem.enableTempParent(); + * elem.updateTransform(); + * elem.disableTempParent(cacheParent); + * ``` + * @returns - current parent + */ + DisplayObject.prototype.enableTempParent = function () { + var myParent = this.parent; + this.parent = this._tempDisplayObjectParent; + return myParent; + }; + /** + * Pair method for `enableTempParent` + * @param cacheParent - Actual parent of element + */ + DisplayObject.prototype.disableTempParent = function (cacheParent) { + this.parent = cacheParent; + }; + Object.defineProperty(DisplayObject.prototype, "x", { + /** + * The position of the displayObject on the x axis relative to the local coordinates of the parent. + * An alias to position.x + */ + get: function () { + return this.position.x; + }, + set: function (value) { + this.transform.position.x = value; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(DisplayObject.prototype, "y", { + /** + * The position of the displayObject on the y axis relative to the local coordinates of the parent. + * An alias to position.y + */ + get: function () { + return this.position.y; + }, + set: function (value) { + this.transform.position.y = value; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(DisplayObject.prototype, "worldTransform", { + /** + * Current transform of the object based on world (parent) factors. + * @readonly + */ + get: function () { + return this.transform.worldTransform; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(DisplayObject.prototype, "localTransform", { + /** + * Current transform of the object based on local factors: position, scale, other stuff. + * @readonly + */ + get: function () { + return this.transform.localTransform; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(DisplayObject.prototype, "position", { + /** + * The coordinate of the object relative to the local coordinates of the parent. + * @since 4.0.0 + */ + get: function () { + return this.transform.position; + }, + set: function (value) { + this.transform.position.copyFrom(value); + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(DisplayObject.prototype, "scale", { + /** + * The scale factors of this object along the local coordinate axes. + * + * The default scale is (1, 1). + * @since 4.0.0 + */ + get: function () { + return this.transform.scale; + }, + set: function (value) { + this.transform.scale.copyFrom(value); + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(DisplayObject.prototype, "pivot", { + /** + * The center of rotation, scaling, and skewing for this display object in its local space. The `position` + * is the projection of `pivot` in the parent's local space. + * + * By default, the pivot is the origin (0, 0). + * @since 4.0.0 + */ + get: function () { + return this.transform.pivot; + }, + set: function (value) { + this.transform.pivot.copyFrom(value); + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(DisplayObject.prototype, "skew", { + /** + * The skew factor for the object in radians. + * @since 4.0.0 + */ + get: function () { + return this.transform.skew; + }, + set: function (value) { + this.transform.skew.copyFrom(value); + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(DisplayObject.prototype, "rotation", { + /** + * The rotation of the object in radians. + * 'rotation' and 'angle' have the same effect on a display object; rotation is in radians, angle is in degrees. + */ + get: function () { + return this.transform.rotation; + }, + set: function (value) { + this.transform.rotation = value; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(DisplayObject.prototype, "angle", { + /** + * The angle of the object in degrees. + * 'rotation' and 'angle' have the same effect on a display object; rotation is in radians, angle is in degrees. + */ + get: function () { + return this.transform.rotation * RAD_TO_DEG; + }, + set: function (value) { + this.transform.rotation = value * DEG_TO_RAD; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(DisplayObject.prototype, "zIndex", { + /** + * The zIndex of the displayObject. + * + * If a container has the sortableChildren property set to true, children will be automatically + * sorted by zIndex value; a higher value will mean it will be moved towards the end of the array, + * and thus rendered on top of other display objects within the same container. + * @see PIXI.Container#sortableChildren + */ + get: function () { + return this._zIndex; + }, + set: function (value) { + this._zIndex = value; + if (this.parent) { + this.parent.sortDirty = true; + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(DisplayObject.prototype, "worldVisible", { + /** + * Indicates if the object is globally visible. + * @readonly + */ + get: function () { + var item = this; + do { + if (!item.visible) { + return false; + } + item = item.parent; + } while (item); + return true; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(DisplayObject.prototype, "mask", { + /** + * Sets a mask for the displayObject. A mask is an object that limits the visibility of an + * object to the shape of the mask applied to it. In PixiJS a regular mask must be a + * {@link PIXI.Graphics} or a {@link PIXI.Sprite} object. This allows for much faster masking in canvas as it + * utilities shape clipping. Furthermore, a mask of an object must be in the subtree of its parent. + * Otherwise, `getLocalBounds` may calculate incorrect bounds, which makes the container's width and height wrong. + * To remove a mask, set this property to `null`. + * + * For sprite mask both alpha and red channel are used. Black mask is the same as transparent mask. + * @example + * const graphics = new PIXI.Graphics(); + * graphics.beginFill(0xFF3300); + * graphics.drawRect(50, 250, 100, 100); + * graphics.endFill(); + * + * const sprite = new PIXI.Sprite(texture); + * sprite.mask = graphics; + * @todo At the moment, PIXI.CanvasRenderer doesn't support PIXI.Sprite as mask. + */ + get: function () { + return this._mask; + }, + set: function (value) { + if (this._mask === value) { + return; + } + if (this._mask) { + var maskObject = (this._mask.isMaskData + ? this._mask.maskObject : this._mask); + if (maskObject) { + maskObject._maskRefCount--; + if (maskObject._maskRefCount === 0) { + maskObject.renderable = true; + maskObject.isMask = false; + } + } + } + this._mask = value; + if (this._mask) { + var maskObject = (this._mask.isMaskData + ? this._mask.maskObject : this._mask); + if (maskObject) { + if (maskObject._maskRefCount === 0) { + maskObject.renderable = false; + maskObject.isMask = true; + } + maskObject._maskRefCount++; + } + } + }, + enumerable: false, + configurable: true + }); + return DisplayObject; + }(eventemitter3)); + /** + * @private + */ + var TemporaryDisplayObject = /** @class */ (function (_super) { + __extends$j(TemporaryDisplayObject, _super); + function TemporaryDisplayObject() { + var _this = _super !== null && _super.apply(this, arguments) || this; + _this.sortDirty = null; + return _this; + } + return TemporaryDisplayObject; + }(DisplayObject)); + /** + * DisplayObject default updateTransform, does not update children of container. + * Will crash if there's no parent element. + * @memberof PIXI.DisplayObject# + * @method displayObjectUpdateTransform + */ + DisplayObject.prototype.displayObjectUpdateTransform = DisplayObject.prototype.updateTransform; + + /*! + * @pixi/constants - v6.5.3 + * Compiled Fri, 09 Sep 2022 13:55:20 UTC + * + * @pixi/constants is licensed under the MIT License. + * http://www.opensource.org/licenses/mit-license + */ + /** + * Different types of environments for WebGL. + * @static + * @memberof PIXI + * @name ENV + * @enum {number} + * @property {number} WEBGL_LEGACY - Used for older v1 WebGL devices. PixiJS will aim to ensure compatibility + * with older / less advanced devices. If you experience unexplained flickering prefer this environment. + * @property {number} WEBGL - Version 1 of WebGL + * @property {number} WEBGL2 - Version 2 of WebGL + */ + var ENV$4; + (function (ENV) { + ENV[ENV["WEBGL_LEGACY"] = 0] = "WEBGL_LEGACY"; + ENV[ENV["WEBGL"] = 1] = "WEBGL"; + ENV[ENV["WEBGL2"] = 2] = "WEBGL2"; + })(ENV$4 || (ENV$4 = {})); + /** + * Constant to identify the Renderer Type. + * @static + * @memberof PIXI + * @name RENDERER_TYPE + * @enum {number} + * @property {number} UNKNOWN - Unknown render type. + * @property {number} WEBGL - WebGL render type. + * @property {number} CANVAS - Canvas render type. + */ + var RENDERER_TYPE$4; + (function (RENDERER_TYPE) { + RENDERER_TYPE[RENDERER_TYPE["UNKNOWN"] = 0] = "UNKNOWN"; + RENDERER_TYPE[RENDERER_TYPE["WEBGL"] = 1] = "WEBGL"; + RENDERER_TYPE[RENDERER_TYPE["CANVAS"] = 2] = "CANVAS"; + })(RENDERER_TYPE$4 || (RENDERER_TYPE$4 = {})); + /** + * Bitwise OR of masks that indicate the buffers to be cleared. + * @static + * @memberof PIXI + * @name BUFFER_BITS + * @enum {number} + * @property {number} COLOR - Indicates the buffers currently enabled for color writing. + * @property {number} DEPTH - Indicates the depth buffer. + * @property {number} STENCIL - Indicates the stencil buffer. + */ + var BUFFER_BITS$4; + (function (BUFFER_BITS) { + BUFFER_BITS[BUFFER_BITS["COLOR"] = 16384] = "COLOR"; + BUFFER_BITS[BUFFER_BITS["DEPTH"] = 256] = "DEPTH"; + BUFFER_BITS[BUFFER_BITS["STENCIL"] = 1024] = "STENCIL"; + })(BUFFER_BITS$4 || (BUFFER_BITS$4 = {})); + /** + * Various blend modes supported by PIXI. + * + * IMPORTANT - The WebGL renderer only supports the NORMAL, ADD, MULTIPLY and SCREEN blend modes. + * Anything else will silently act like NORMAL. + * @memberof PIXI + * @name BLEND_MODES + * @enum {number} + * @property {number} NORMAL - + * @property {number} ADD - + * @property {number} MULTIPLY - + * @property {number} SCREEN - + * @property {number} OVERLAY - + * @property {number} DARKEN - + * @property {number} LIGHTEN - + * @property {number} COLOR_DODGE - + * @property {number} COLOR_BURN - + * @property {number} HARD_LIGHT - + * @property {number} SOFT_LIGHT - + * @property {number} DIFFERENCE - + * @property {number} EXCLUSION - + * @property {number} HUE - + * @property {number} SATURATION - + * @property {number} COLOR - + * @property {number} LUMINOSITY - + * @property {number} NORMAL_NPM - + * @property {number} ADD_NPM - + * @property {number} SCREEN_NPM - + * @property {number} NONE - + * @property {number} SRC_IN - + * @property {number} SRC_OUT - + * @property {number} SRC_ATOP - + * @property {number} DST_OVER - + * @property {number} DST_IN - + * @property {number} DST_OUT - + * @property {number} DST_ATOP - + * @property {number} SUBTRACT - + * @property {number} SRC_OVER - + * @property {number} ERASE - + * @property {number} XOR - + */ + var BLEND_MODES$4; + (function (BLEND_MODES) { + BLEND_MODES[BLEND_MODES["NORMAL"] = 0] = "NORMAL"; + BLEND_MODES[BLEND_MODES["ADD"] = 1] = "ADD"; + BLEND_MODES[BLEND_MODES["MULTIPLY"] = 2] = "MULTIPLY"; + BLEND_MODES[BLEND_MODES["SCREEN"] = 3] = "SCREEN"; + BLEND_MODES[BLEND_MODES["OVERLAY"] = 4] = "OVERLAY"; + BLEND_MODES[BLEND_MODES["DARKEN"] = 5] = "DARKEN"; + BLEND_MODES[BLEND_MODES["LIGHTEN"] = 6] = "LIGHTEN"; + BLEND_MODES[BLEND_MODES["COLOR_DODGE"] = 7] = "COLOR_DODGE"; + BLEND_MODES[BLEND_MODES["COLOR_BURN"] = 8] = "COLOR_BURN"; + BLEND_MODES[BLEND_MODES["HARD_LIGHT"] = 9] = "HARD_LIGHT"; + BLEND_MODES[BLEND_MODES["SOFT_LIGHT"] = 10] = "SOFT_LIGHT"; + BLEND_MODES[BLEND_MODES["DIFFERENCE"] = 11] = "DIFFERENCE"; + BLEND_MODES[BLEND_MODES["EXCLUSION"] = 12] = "EXCLUSION"; + BLEND_MODES[BLEND_MODES["HUE"] = 13] = "HUE"; + BLEND_MODES[BLEND_MODES["SATURATION"] = 14] = "SATURATION"; + BLEND_MODES[BLEND_MODES["COLOR"] = 15] = "COLOR"; + BLEND_MODES[BLEND_MODES["LUMINOSITY"] = 16] = "LUMINOSITY"; + BLEND_MODES[BLEND_MODES["NORMAL_NPM"] = 17] = "NORMAL_NPM"; + BLEND_MODES[BLEND_MODES["ADD_NPM"] = 18] = "ADD_NPM"; + BLEND_MODES[BLEND_MODES["SCREEN_NPM"] = 19] = "SCREEN_NPM"; + BLEND_MODES[BLEND_MODES["NONE"] = 20] = "NONE"; + BLEND_MODES[BLEND_MODES["SRC_OVER"] = 0] = "SRC_OVER"; + BLEND_MODES[BLEND_MODES["SRC_IN"] = 21] = "SRC_IN"; + BLEND_MODES[BLEND_MODES["SRC_OUT"] = 22] = "SRC_OUT"; + BLEND_MODES[BLEND_MODES["SRC_ATOP"] = 23] = "SRC_ATOP"; + BLEND_MODES[BLEND_MODES["DST_OVER"] = 24] = "DST_OVER"; + BLEND_MODES[BLEND_MODES["DST_IN"] = 25] = "DST_IN"; + BLEND_MODES[BLEND_MODES["DST_OUT"] = 26] = "DST_OUT"; + BLEND_MODES[BLEND_MODES["DST_ATOP"] = 27] = "DST_ATOP"; + BLEND_MODES[BLEND_MODES["ERASE"] = 26] = "ERASE"; + BLEND_MODES[BLEND_MODES["SUBTRACT"] = 28] = "SUBTRACT"; + BLEND_MODES[BLEND_MODES["XOR"] = 29] = "XOR"; + })(BLEND_MODES$4 || (BLEND_MODES$4 = {})); + /** + * Various webgl draw modes. These can be used to specify which GL drawMode to use + * under certain situations and renderers. + * @memberof PIXI + * @static + * @name DRAW_MODES + * @enum {number} + * @property {number} POINTS - + * @property {number} LINES - + * @property {number} LINE_LOOP - + * @property {number} LINE_STRIP - + * @property {number} TRIANGLES - + * @property {number} TRIANGLE_STRIP - + * @property {number} TRIANGLE_FAN - + */ + var DRAW_MODES$4; + (function (DRAW_MODES) { + DRAW_MODES[DRAW_MODES["POINTS"] = 0] = "POINTS"; + DRAW_MODES[DRAW_MODES["LINES"] = 1] = "LINES"; + DRAW_MODES[DRAW_MODES["LINE_LOOP"] = 2] = "LINE_LOOP"; + DRAW_MODES[DRAW_MODES["LINE_STRIP"] = 3] = "LINE_STRIP"; + DRAW_MODES[DRAW_MODES["TRIANGLES"] = 4] = "TRIANGLES"; + DRAW_MODES[DRAW_MODES["TRIANGLE_STRIP"] = 5] = "TRIANGLE_STRIP"; + DRAW_MODES[DRAW_MODES["TRIANGLE_FAN"] = 6] = "TRIANGLE_FAN"; + })(DRAW_MODES$4 || (DRAW_MODES$4 = {})); + /** + * Various GL texture/resources formats. + * @memberof PIXI + * @static + * @name FORMATS + * @enum {number} + * @property {number} [RGBA=6408] - + * @property {number} [RGB=6407] - + * @property {number} [RG=33319] - + * @property {number} [RED=6403] - + * @property {number} [RGBA_INTEGER=36249] - + * @property {number} [RGB_INTEGER=36248] - + * @property {number} [RG_INTEGER=33320] - + * @property {number} [RED_INTEGER=36244] - + * @property {number} [ALPHA=6406] - + * @property {number} [LUMINANCE=6409] - + * @property {number} [LUMINANCE_ALPHA=6410] - + * @property {number} [DEPTH_COMPONENT=6402] - + * @property {number} [DEPTH_STENCIL=34041] - + */ + var FORMATS$4; + (function (FORMATS) { + FORMATS[FORMATS["RGBA"] = 6408] = "RGBA"; + FORMATS[FORMATS["RGB"] = 6407] = "RGB"; + FORMATS[FORMATS["RG"] = 33319] = "RG"; + FORMATS[FORMATS["RED"] = 6403] = "RED"; + FORMATS[FORMATS["RGBA_INTEGER"] = 36249] = "RGBA_INTEGER"; + FORMATS[FORMATS["RGB_INTEGER"] = 36248] = "RGB_INTEGER"; + FORMATS[FORMATS["RG_INTEGER"] = 33320] = "RG_INTEGER"; + FORMATS[FORMATS["RED_INTEGER"] = 36244] = "RED_INTEGER"; + FORMATS[FORMATS["ALPHA"] = 6406] = "ALPHA"; + FORMATS[FORMATS["LUMINANCE"] = 6409] = "LUMINANCE"; + FORMATS[FORMATS["LUMINANCE_ALPHA"] = 6410] = "LUMINANCE_ALPHA"; + FORMATS[FORMATS["DEPTH_COMPONENT"] = 6402] = "DEPTH_COMPONENT"; + FORMATS[FORMATS["DEPTH_STENCIL"] = 34041] = "DEPTH_STENCIL"; + })(FORMATS$4 || (FORMATS$4 = {})); + /** + * Various GL target types. + * @memberof PIXI + * @static + * @name TARGETS + * @enum {number} + * @property {number} [TEXTURE_2D=3553] - + * @property {number} [TEXTURE_CUBE_MAP=34067] - + * @property {number} [TEXTURE_2D_ARRAY=35866] - + * @property {number} [TEXTURE_CUBE_MAP_POSITIVE_X=34069] - + * @property {number} [TEXTURE_CUBE_MAP_NEGATIVE_X=34070] - + * @property {number} [TEXTURE_CUBE_MAP_POSITIVE_Y=34071] - + * @property {number} [TEXTURE_CUBE_MAP_NEGATIVE_Y=34072] - + * @property {number} [TEXTURE_CUBE_MAP_POSITIVE_Z=34073] - + * @property {number} [TEXTURE_CUBE_MAP_NEGATIVE_Z=34074] - + */ + var TARGETS$4; + (function (TARGETS) { + TARGETS[TARGETS["TEXTURE_2D"] = 3553] = "TEXTURE_2D"; + TARGETS[TARGETS["TEXTURE_CUBE_MAP"] = 34067] = "TEXTURE_CUBE_MAP"; + TARGETS[TARGETS["TEXTURE_2D_ARRAY"] = 35866] = "TEXTURE_2D_ARRAY"; + TARGETS[TARGETS["TEXTURE_CUBE_MAP_POSITIVE_X"] = 34069] = "TEXTURE_CUBE_MAP_POSITIVE_X"; + TARGETS[TARGETS["TEXTURE_CUBE_MAP_NEGATIVE_X"] = 34070] = "TEXTURE_CUBE_MAP_NEGATIVE_X"; + TARGETS[TARGETS["TEXTURE_CUBE_MAP_POSITIVE_Y"] = 34071] = "TEXTURE_CUBE_MAP_POSITIVE_Y"; + TARGETS[TARGETS["TEXTURE_CUBE_MAP_NEGATIVE_Y"] = 34072] = "TEXTURE_CUBE_MAP_NEGATIVE_Y"; + TARGETS[TARGETS["TEXTURE_CUBE_MAP_POSITIVE_Z"] = 34073] = "TEXTURE_CUBE_MAP_POSITIVE_Z"; + TARGETS[TARGETS["TEXTURE_CUBE_MAP_NEGATIVE_Z"] = 34074] = "TEXTURE_CUBE_MAP_NEGATIVE_Z"; + })(TARGETS$4 || (TARGETS$4 = {})); + /** + * Various GL data format types. + * @memberof PIXI + * @static + * @name TYPES + * @enum {number} + * @property {number} [UNSIGNED_BYTE=5121] - + * @property {number} [UNSIGNED_SHORT=5123] - + * @property {number} [UNSIGNED_SHORT_5_6_5=33635] - + * @property {number} [UNSIGNED_SHORT_4_4_4_4=32819] - + * @property {number} [UNSIGNED_SHORT_5_5_5_1=32820] - + * @property {number} [UNSIGNED_INT=5125] - + * @property {number} [UNSIGNED_INT_10F_11F_11F_REV=35899] - + * @property {number} [UNSIGNED_INT_2_10_10_10_REV=33640] - + * @property {number} [UNSIGNED_INT_24_8=34042] - + * @property {number} [UNSIGNED_INT_5_9_9_9_REV=35902] - + * @property {number} [BYTE=5120] - + * @property {number} [SHORT=5122] - + * @property {number} [INT=5124] - + * @property {number} [FLOAT=5126] - + * @property {number} [FLOAT_32_UNSIGNED_INT_24_8_REV=36269] - + * @property {number} [HALF_FLOAT=36193] - + */ + var TYPES$4; + (function (TYPES) { + TYPES[TYPES["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE"; + TYPES[TYPES["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT"; + TYPES[TYPES["UNSIGNED_SHORT_5_6_5"] = 33635] = "UNSIGNED_SHORT_5_6_5"; + TYPES[TYPES["UNSIGNED_SHORT_4_4_4_4"] = 32819] = "UNSIGNED_SHORT_4_4_4_4"; + TYPES[TYPES["UNSIGNED_SHORT_5_5_5_1"] = 32820] = "UNSIGNED_SHORT_5_5_5_1"; + TYPES[TYPES["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT"; + TYPES[TYPES["UNSIGNED_INT_10F_11F_11F_REV"] = 35899] = "UNSIGNED_INT_10F_11F_11F_REV"; + TYPES[TYPES["UNSIGNED_INT_2_10_10_10_REV"] = 33640] = "UNSIGNED_INT_2_10_10_10_REV"; + TYPES[TYPES["UNSIGNED_INT_24_8"] = 34042] = "UNSIGNED_INT_24_8"; + TYPES[TYPES["UNSIGNED_INT_5_9_9_9_REV"] = 35902] = "UNSIGNED_INT_5_9_9_9_REV"; + TYPES[TYPES["BYTE"] = 5120] = "BYTE"; + TYPES[TYPES["SHORT"] = 5122] = "SHORT"; + TYPES[TYPES["INT"] = 5124] = "INT"; + TYPES[TYPES["FLOAT"] = 5126] = "FLOAT"; + TYPES[TYPES["FLOAT_32_UNSIGNED_INT_24_8_REV"] = 36269] = "FLOAT_32_UNSIGNED_INT_24_8_REV"; + TYPES[TYPES["HALF_FLOAT"] = 36193] = "HALF_FLOAT"; + })(TYPES$4 || (TYPES$4 = {})); + /** + * Various sampler types. Correspond to `sampler`, `isampler`, `usampler` GLSL types respectively. + * WebGL1 works only with FLOAT. + * @memberof PIXI + * @static + * @name SAMPLER_TYPES + * @enum {number} + * @property {number} [FLOAT=0] - + * @property {number} [INT=1] - + * @property {number} [UINT=2] - + */ + var SAMPLER_TYPES$4; + (function (SAMPLER_TYPES) { + SAMPLER_TYPES[SAMPLER_TYPES["FLOAT"] = 0] = "FLOAT"; + SAMPLER_TYPES[SAMPLER_TYPES["INT"] = 1] = "INT"; + SAMPLER_TYPES[SAMPLER_TYPES["UINT"] = 2] = "UINT"; + })(SAMPLER_TYPES$4 || (SAMPLER_TYPES$4 = {})); + /** + * The scale modes that are supported by pixi. + * + * The {@link PIXI.settings.SCALE_MODE} scale mode affects the default scaling mode of future operations. + * It can be re-assigned to either LINEAR or NEAREST, depending upon suitability. + * @memberof PIXI + * @static + * @name SCALE_MODES + * @enum {number} + * @property {number} LINEAR Smooth scaling + * @property {number} NEAREST Pixelating scaling + */ + var SCALE_MODES$4; + (function (SCALE_MODES) { + SCALE_MODES[SCALE_MODES["NEAREST"] = 0] = "NEAREST"; + SCALE_MODES[SCALE_MODES["LINEAR"] = 1] = "LINEAR"; + })(SCALE_MODES$4 || (SCALE_MODES$4 = {})); + /** + * The wrap modes that are supported by pixi. + * + * The {@link PIXI.settings.WRAP_MODE} wrap mode affects the default wrapping mode of future operations. + * It can be re-assigned to either CLAMP or REPEAT, depending upon suitability. + * If the texture is non power of two then clamp will be used regardless as WebGL can + * only use REPEAT if the texture is po2. + * + * This property only affects WebGL. + * @name WRAP_MODES + * @memberof PIXI + * @static + * @enum {number} + * @property {number} CLAMP - The textures uvs are clamped + * @property {number} REPEAT - The texture uvs tile and repeat + * @property {number} MIRRORED_REPEAT - The texture uvs tile and repeat with mirroring + */ + var WRAP_MODES$4; + (function (WRAP_MODES) { + WRAP_MODES[WRAP_MODES["CLAMP"] = 33071] = "CLAMP"; + WRAP_MODES[WRAP_MODES["REPEAT"] = 10497] = "REPEAT"; + WRAP_MODES[WRAP_MODES["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT"; + })(WRAP_MODES$4 || (WRAP_MODES$4 = {})); + /** + * Mipmap filtering modes that are supported by pixi. + * + * The {@link PIXI.settings.MIPMAP_TEXTURES} affects default texture filtering. + * Mipmaps are generated for a baseTexture if its `mipmap` field is `ON`, + * or its `POW2` and texture dimensions are powers of 2. + * Due to platform restriction, `ON` option will work like `POW2` for webgl-1. + * + * This property only affects WebGL. + * @name MIPMAP_MODES + * @memberof PIXI + * @static + * @enum {number} + * @property {number} OFF - No mipmaps + * @property {number} POW2 - Generate mipmaps if texture dimensions are pow2 + * @property {number} ON - Always generate mipmaps + * @property {number} ON_MANUAL - Use mipmaps, but do not auto-generate them; this is used with a resource + * that supports buffering each level-of-detail. + */ + var MIPMAP_MODES$4; + (function (MIPMAP_MODES) { + MIPMAP_MODES[MIPMAP_MODES["OFF"] = 0] = "OFF"; + MIPMAP_MODES[MIPMAP_MODES["POW2"] = 1] = "POW2"; + MIPMAP_MODES[MIPMAP_MODES["ON"] = 2] = "ON"; + MIPMAP_MODES[MIPMAP_MODES["ON_MANUAL"] = 3] = "ON_MANUAL"; + })(MIPMAP_MODES$4 || (MIPMAP_MODES$4 = {})); + /** + * How to treat textures with premultiplied alpha + * @name ALPHA_MODES + * @memberof PIXI + * @static + * @enum {number} + * @property {number} NO_PREMULTIPLIED_ALPHA - Source is not premultiplied, leave it like that. + * Option for compressed and data textures that are created from typed arrays. + * @property {number} PREMULTIPLY_ON_UPLOAD - Source is not premultiplied, premultiply on upload. + * Default option, used for all loaded images. + * @property {number} PREMULTIPLIED_ALPHA - Source is already premultiplied + * Example: spine atlases with `_pma` suffix. + * @property {number} NPM - Alias for NO_PREMULTIPLIED_ALPHA. + * @property {number} UNPACK - Default option, alias for PREMULTIPLY_ON_UPLOAD. + * @property {number} PMA - Alias for PREMULTIPLIED_ALPHA. + */ + var ALPHA_MODES$4; + (function (ALPHA_MODES) { + ALPHA_MODES[ALPHA_MODES["NPM"] = 0] = "NPM"; + ALPHA_MODES[ALPHA_MODES["UNPACK"] = 1] = "UNPACK"; + ALPHA_MODES[ALPHA_MODES["PMA"] = 2] = "PMA"; + ALPHA_MODES[ALPHA_MODES["NO_PREMULTIPLIED_ALPHA"] = 0] = "NO_PREMULTIPLIED_ALPHA"; + ALPHA_MODES[ALPHA_MODES["PREMULTIPLY_ON_UPLOAD"] = 1] = "PREMULTIPLY_ON_UPLOAD"; + ALPHA_MODES[ALPHA_MODES["PREMULTIPLY_ALPHA"] = 2] = "PREMULTIPLY_ALPHA"; + ALPHA_MODES[ALPHA_MODES["PREMULTIPLIED_ALPHA"] = 2] = "PREMULTIPLIED_ALPHA"; + })(ALPHA_MODES$4 || (ALPHA_MODES$4 = {})); + /** + * Configure whether filter textures are cleared after binding. + * + * Filter textures need not be cleared if the filter does not use pixel blending. {@link CLEAR_MODES.BLIT} will detect + * this and skip clearing as an optimization. + * @name CLEAR_MODES + * @memberof PIXI + * @static + * @enum {number} + * @property {number} BLEND - Do not clear the filter texture. The filter's output will blend on top of the output texture. + * @property {number} CLEAR - Always clear the filter texture. + * @property {number} BLIT - Clear only if {@link FilterSystem.forceClear} is set or if the filter uses pixel blending. + * @property {number} NO - Alias for BLEND, same as `false` in earlier versions + * @property {number} YES - Alias for CLEAR, same as `true` in earlier versions + * @property {number} AUTO - Alias for BLIT + */ + var CLEAR_MODES$4; + (function (CLEAR_MODES) { + CLEAR_MODES[CLEAR_MODES["NO"] = 0] = "NO"; + CLEAR_MODES[CLEAR_MODES["YES"] = 1] = "YES"; + CLEAR_MODES[CLEAR_MODES["AUTO"] = 2] = "AUTO"; + CLEAR_MODES[CLEAR_MODES["BLEND"] = 0] = "BLEND"; + CLEAR_MODES[CLEAR_MODES["CLEAR"] = 1] = "CLEAR"; + CLEAR_MODES[CLEAR_MODES["BLIT"] = 2] = "BLIT"; + })(CLEAR_MODES$4 || (CLEAR_MODES$4 = {})); + /** + * The gc modes that are supported by pixi. + * + * The {@link PIXI.settings.GC_MODE} Garbage Collection mode for PixiJS textures is AUTO + * If set to GC_MODE, the renderer will occasionally check textures usage. If they are not + * used for a specified period of time they will be removed from the GPU. They will of course + * be uploaded again when they are required. This is a silent behind the scenes process that + * should ensure that the GPU does not get filled up. + * + * Handy for mobile devices! + * This property only affects WebGL. + * @name GC_MODES + * @enum {number} + * @static + * @memberof PIXI + * @property {number} AUTO - Garbage collection will happen periodically automatically + * @property {number} MANUAL - Garbage collection will need to be called manually + */ + var GC_MODES$4; + (function (GC_MODES) { + GC_MODES[GC_MODES["AUTO"] = 0] = "AUTO"; + GC_MODES[GC_MODES["MANUAL"] = 1] = "MANUAL"; + })(GC_MODES$4 || (GC_MODES$4 = {})); + /** + * Constants that specify float precision in shaders. + * @name PRECISION + * @memberof PIXI + * @constant + * @static + * @enum {string} + * @property {string} [LOW='lowp'] - + * @property {string} [MEDIUM='mediump'] - + * @property {string} [HIGH='highp'] - + */ + var PRECISION$4; + (function (PRECISION) { + PRECISION["LOW"] = "lowp"; + PRECISION["MEDIUM"] = "mediump"; + PRECISION["HIGH"] = "highp"; + })(PRECISION$4 || (PRECISION$4 = {})); + /** + * Constants for mask implementations. + * We use `type` suffix because it leads to very different behaviours + * @name MASK_TYPES + * @memberof PIXI + * @static + * @enum {number} + * @property {number} NONE - Mask is ignored + * @property {number} SCISSOR - Scissor mask, rectangle on screen, cheap + * @property {number} STENCIL - Stencil mask, 1-bit, medium, works only if renderer supports stencil + * @property {number} SPRITE - Mask that uses SpriteMaskFilter, uses temporary RenderTexture + * @property {number} COLOR - Color mask (RGBA) + */ + var MASK_TYPES$4; + (function (MASK_TYPES) { + MASK_TYPES[MASK_TYPES["NONE"] = 0] = "NONE"; + MASK_TYPES[MASK_TYPES["SCISSOR"] = 1] = "SCISSOR"; + MASK_TYPES[MASK_TYPES["STENCIL"] = 2] = "STENCIL"; + MASK_TYPES[MASK_TYPES["SPRITE"] = 3] = "SPRITE"; + MASK_TYPES[MASK_TYPES["COLOR"] = 4] = "COLOR"; + })(MASK_TYPES$4 || (MASK_TYPES$4 = {})); + /** + * Bitwise OR of masks that indicate the color channels that are rendered to. + * @static + * @memberof PIXI + * @name COLOR_MASK_BITS + * @enum {number} + * @property {number} RED - Red channel. + * @property {number} GREEN - Green channel + * @property {number} BLUE - Blue channel. + * @property {number} ALPHA - Alpha channel. + */ + var COLOR_MASK_BITS$4; + (function (COLOR_MASK_BITS) { + COLOR_MASK_BITS[COLOR_MASK_BITS["RED"] = 1] = "RED"; + COLOR_MASK_BITS[COLOR_MASK_BITS["GREEN"] = 2] = "GREEN"; + COLOR_MASK_BITS[COLOR_MASK_BITS["BLUE"] = 4] = "BLUE"; + COLOR_MASK_BITS[COLOR_MASK_BITS["ALPHA"] = 8] = "ALPHA"; + })(COLOR_MASK_BITS$4 || (COLOR_MASK_BITS$4 = {})); + /** + * Constants for multi-sampling antialiasing. + * @see PIXI.Framebuffer#multisample + * @name MSAA_QUALITY + * @memberof PIXI + * @static + * @enum {number} + * @property {number} NONE - No multisampling for this renderTexture + * @property {number} LOW - Try 2 samples + * @property {number} MEDIUM - Try 4 samples + * @property {number} HIGH - Try 8 samples + */ + var MSAA_QUALITY$4; + (function (MSAA_QUALITY) { + MSAA_QUALITY[MSAA_QUALITY["NONE"] = 0] = "NONE"; + MSAA_QUALITY[MSAA_QUALITY["LOW"] = 2] = "LOW"; + MSAA_QUALITY[MSAA_QUALITY["MEDIUM"] = 4] = "MEDIUM"; + MSAA_QUALITY[MSAA_QUALITY["HIGH"] = 8] = "HIGH"; + })(MSAA_QUALITY$4 || (MSAA_QUALITY$4 = {})); + /** + * Constants for various buffer types in Pixi + * @see PIXI.BUFFER_TYPE + * @name BUFFER_TYPE + * @memberof PIXI + * @static + * @enum {number} + * @property {number} ELEMENT_ARRAY_BUFFER - buffer type for using as an index buffer + * @property {number} ARRAY_BUFFER - buffer type for using attribute data + * @property {number} UNIFORM_BUFFER - the buffer type is for uniform buffer objects + */ + var BUFFER_TYPE$4; + (function (BUFFER_TYPE) { + BUFFER_TYPE[BUFFER_TYPE["ELEMENT_ARRAY_BUFFER"] = 34963] = "ELEMENT_ARRAY_BUFFER"; + BUFFER_TYPE[BUFFER_TYPE["ARRAY_BUFFER"] = 34962] = "ARRAY_BUFFER"; + // NOT YET SUPPORTED + BUFFER_TYPE[BUFFER_TYPE["UNIFORM_BUFFER"] = 35345] = "UNIFORM_BUFFER"; + })(BUFFER_TYPE$4 || (BUFFER_TYPE$4 = {})); + + function sortChildren(a, b) { + if (a.zIndex === b.zIndex) { + return a._lastSortedIndex - b._lastSortedIndex; + } + return a.zIndex - b.zIndex; + } + /** + * Container is a general-purpose display object that holds children. It also adds built-in support for advanced + * rendering features like masking and filtering. + * + * It is the base class of all display objects that act as a container for other objects, including Graphics + * and Sprite. + * + * ```js + * import { BlurFilter } from '@pixi/filter-blur'; + * import { Container } from '@pixi/display'; + * import { Graphics } from '@pixi/graphics'; + * import { Sprite } from '@pixi/sprite'; + * + * let container = new Container(); + * let sprite = Sprite.from("https://s3-us-west-2.amazonaws.com/s.cdpn.io/693612/IaUrttj.png"); + * + * sprite.width = 512; + * sprite.height = 512; + * + * // Adds a sprite as a child to this container. As a result, the sprite will be rendered whenever the container + * // is rendered. + * container.addChild(sprite); + * + * // Blurs whatever is rendered by the container + * container.filters = [new BlurFilter()]; + * + * // Only the contents within a circle at the center should be rendered onto the screen. + * container.mask = new Graphics() + * .beginFill(0xffffff) + * .drawCircle(sprite.width / 2, sprite.height / 2, Math.min(sprite.width, sprite.height) / 2) + * .endFill(); + * ``` + * @memberof PIXI + */ + var Container = /** @class */ (function (_super) { + __extends$j(Container, _super); + function Container() { + var _this = _super.call(this) || this; + _this.children = []; + _this.sortableChildren = settings$1.SORTABLE_CHILDREN; + _this.sortDirty = false; + return _this; + /** + * Fired when a DisplayObject is added to this Container. + * @event PIXI.Container#childAdded + * @param {PIXI.DisplayObject} child - The child added to the Container. + * @param {PIXI.Container} container - The container that added the child. + * @param {number} index - The children's index of the added child. + */ + /** + * Fired when a DisplayObject is removed from this Container. + * @event PIXI.DisplayObject#childRemoved + * @param {PIXI.DisplayObject} child - The child removed from the Container. + * @param {PIXI.Container} container - The container that removed the child. + * @param {number} index - The former children's index of the removed child + */ + } + /** + * Overridable method that can be used by Container subclasses whenever the children array is modified. + * @param _length + */ + Container.prototype.onChildrenChange = function (_length) { + /* empty */ + }; + /** + * Adds one or more children to the container. + * + * Multiple items can be added like so: `myContainer.addChild(thingOne, thingTwo, thingThree)` + * @param {...PIXI.DisplayObject} children - The DisplayObject(s) to add to the container + * @returns {PIXI.DisplayObject} - The first child that was added. + */ + Container.prototype.addChild = function () { + var arguments$1 = arguments; + + var children = []; + for (var _i = 0; _i < arguments.length; _i++) { + children[_i] = arguments$1[_i]; + } + // if there is only one argument we can bypass looping through the them + if (children.length > 1) { + // loop through the array and add all children + for (var i = 0; i < children.length; i++) { + // eslint-disable-next-line prefer-rest-params + this.addChild(children[i]); + } + } + else { + var child = children[0]; + // if the child has a parent then lets remove it as PixiJS objects can only exist in one place + if (child.parent) { + child.parent.removeChild(child); + } + child.parent = this; + this.sortDirty = true; + // ensure child transform will be recalculated + child.transform._parentID = -1; + this.children.push(child); + // ensure bounds will be recalculated + this._boundsID++; + // TODO - lets either do all callbacks or all events.. not both! + this.onChildrenChange(this.children.length - 1); + this.emit('childAdded', child, this, this.children.length - 1); + child.emit('added', this); + } + return children[0]; + }; + /** + * Adds a child to the container at a specified index. If the index is out of bounds an error will be thrown + * @param {PIXI.DisplayObject} child - The child to add + * @param {number} index - The index to place the child in + * @returns {PIXI.DisplayObject} The child that was added. + */ + Container.prototype.addChildAt = function (child, index) { + if (index < 0 || index > this.children.length) { + throw new Error(child + "addChildAt: The index " + index + " supplied is out of bounds " + this.children.length); + } + if (child.parent) { + child.parent.removeChild(child); + } + child.parent = this; + this.sortDirty = true; + // ensure child transform will be recalculated + child.transform._parentID = -1; + this.children.splice(index, 0, child); + // ensure bounds will be recalculated + this._boundsID++; + // TODO - lets either do all callbacks or all events.. not both! + this.onChildrenChange(index); + child.emit('added', this); + this.emit('childAdded', child, this, index); + return child; + }; + /** + * Swaps the position of 2 Display Objects within this container. + * @param child - First display object to swap + * @param child2 - Second display object to swap + */ + Container.prototype.swapChildren = function (child, child2) { + if (child === child2) { + return; + } + var index1 = this.getChildIndex(child); + var index2 = this.getChildIndex(child2); + this.children[index1] = child2; + this.children[index2] = child; + this.onChildrenChange(index1 < index2 ? index1 : index2); + }; + /** + * Returns the index position of a child DisplayObject instance + * @param child - The DisplayObject instance to identify + * @returns - The index position of the child display object to identify + */ + Container.prototype.getChildIndex = function (child) { + var index = this.children.indexOf(child); + if (index === -1) { + throw new Error('The supplied DisplayObject must be a child of the caller'); + } + return index; + }; + /** + * Changes the position of an existing child in the display object container + * @param child - The child DisplayObject instance for which you want to change the index number + * @param index - The resulting index number for the child display object + */ + Container.prototype.setChildIndex = function (child, index) { + if (index < 0 || index >= this.children.length) { + throw new Error("The index " + index + " supplied is out of bounds " + this.children.length); + } + var currentIndex = this.getChildIndex(child); + removeItems(this.children, currentIndex, 1); // remove from old position + this.children.splice(index, 0, child); // add at new position + this.onChildrenChange(index); + }; + /** + * Returns the child at the specified index + * @param index - The index to get the child at + * @returns - The child at the given index, if any. + */ + Container.prototype.getChildAt = function (index) { + if (index < 0 || index >= this.children.length) { + throw new Error("getChildAt: Index (" + index + ") does not exist."); + } + return this.children[index]; + }; + /** + * Removes one or more children from the container. + * @param {...PIXI.DisplayObject} children - The DisplayObject(s) to remove + * @returns {PIXI.DisplayObject} The first child that was removed. + */ + Container.prototype.removeChild = function () { + var arguments$1 = arguments; + + var children = []; + for (var _i = 0; _i < arguments.length; _i++) { + children[_i] = arguments$1[_i]; + } + // if there is only one argument we can bypass looping through the them + if (children.length > 1) { + // loop through the arguments property and remove all children + for (var i = 0; i < children.length; i++) { + this.removeChild(children[i]); + } + } + else { + var child = children[0]; + var index = this.children.indexOf(child); + if (index === -1) + { return null; } + child.parent = null; + // ensure child transform will be recalculated + child.transform._parentID = -1; + removeItems(this.children, index, 1); + // ensure bounds will be recalculated + this._boundsID++; + // TODO - lets either do all callbacks or all events.. not both! + this.onChildrenChange(index); + child.emit('removed', this); + this.emit('childRemoved', child, this, index); + } + return children[0]; + }; + /** + * Removes a child from the specified index position. + * @param index - The index to get the child from + * @returns The child that was removed. + */ + Container.prototype.removeChildAt = function (index) { + var child = this.getChildAt(index); + // ensure child transform will be recalculated.. + child.parent = null; + child.transform._parentID = -1; + removeItems(this.children, index, 1); + // ensure bounds will be recalculated + this._boundsID++; + // TODO - lets either do all callbacks or all events.. not both! + this.onChildrenChange(index); + child.emit('removed', this); + this.emit('childRemoved', child, this, index); + return child; + }; + /** + * Removes all children from this container that are within the begin and end indexes. + * @param beginIndex - The beginning position. + * @param endIndex - The ending position. Default value is size of the container. + * @returns - List of removed children + */ + Container.prototype.removeChildren = function (beginIndex, endIndex) { + if (beginIndex === void 0) { beginIndex = 0; } + if (endIndex === void 0) { endIndex = this.children.length; } + var begin = beginIndex; + var end = endIndex; + var range = end - begin; + var removed; + if (range > 0 && range <= end) { + removed = this.children.splice(begin, range); + for (var i = 0; i < removed.length; ++i) { + removed[i].parent = null; + if (removed[i].transform) { + removed[i].transform._parentID = -1; + } + } + this._boundsID++; + this.onChildrenChange(beginIndex); + for (var i = 0; i < removed.length; ++i) { + removed[i].emit('removed', this); + this.emit('childRemoved', removed[i], this, i); + } + return removed; + } + else if (range === 0 && this.children.length === 0) { + return []; + } + throw new RangeError('removeChildren: numeric values are outside the acceptable range.'); + }; + /** Sorts children by zIndex. Previous order is maintained for 2 children with the same zIndex. */ + Container.prototype.sortChildren = function () { + var sortRequired = false; + for (var i = 0, j = this.children.length; i < j; ++i) { + var child = this.children[i]; + child._lastSortedIndex = i; + if (!sortRequired && child.zIndex !== 0) { + sortRequired = true; + } + } + if (sortRequired && this.children.length > 1) { + this.children.sort(sortChildren); + } + this.sortDirty = false; + }; + /** Updates the transform on all children of this container for rendering. */ + Container.prototype.updateTransform = function () { + if (this.sortableChildren && this.sortDirty) { + this.sortChildren(); + } + this._boundsID++; + this.transform.updateTransform(this.parent.transform); + // TODO: check render flags, how to process stuff here + this.worldAlpha = this.alpha * this.parent.worldAlpha; + for (var i = 0, j = this.children.length; i < j; ++i) { + var child = this.children[i]; + if (child.visible) { + child.updateTransform(); + } + } + }; + /** + * Recalculates the bounds of the container. + * + * This implementation will automatically fit the children's bounds into the calculation. Each child's bounds + * is limited to its mask's bounds or filterArea, if any is applied. + */ + Container.prototype.calculateBounds = function () { + this._bounds.clear(); + this._calculateBounds(); + for (var i = 0; i < this.children.length; i++) { + var child = this.children[i]; + if (!child.visible || !child.renderable) { + continue; + } + child.calculateBounds(); + // TODO: filter+mask, need to mask both somehow + if (child._mask) { + var maskObject = (child._mask.isMaskData + ? child._mask.maskObject : child._mask); + if (maskObject) { + maskObject.calculateBounds(); + this._bounds.addBoundsMask(child._bounds, maskObject._bounds); + } + else { + this._bounds.addBounds(child._bounds); + } + } + else if (child.filterArea) { + this._bounds.addBoundsArea(child._bounds, child.filterArea); + } + else { + this._bounds.addBounds(child._bounds); + } + } + this._bounds.updateID = this._boundsID; + }; + /** + * Retrieves the local bounds of the displayObject as a rectangle object. + * + * Calling `getLocalBounds` may invalidate the `_bounds` of the whole subtree below. If using it inside a render() + * call, it is advised to call `getBounds()` immediately after to recalculate the world bounds of the subtree. + * @param rect - Optional rectangle to store the result of the bounds calculation. + * @param skipChildrenUpdate - Setting to `true` will stop re-calculation of children transforms, + * it was default behaviour of pixi 4.0-5.2 and caused many problems to users. + * @returns - The rectangular bounding area. + */ + Container.prototype.getLocalBounds = function (rect, skipChildrenUpdate) { + if (skipChildrenUpdate === void 0) { skipChildrenUpdate = false; } + var result = _super.prototype.getLocalBounds.call(this, rect); + if (!skipChildrenUpdate) { + for (var i = 0, j = this.children.length; i < j; ++i) { + var child = this.children[i]; + if (child.visible) { + child.updateTransform(); + } + } + } + return result; + }; + /** + * Recalculates the content bounds of this object. This should be overriden to + * calculate the bounds of this specific object (not including children). + * @protected + */ + Container.prototype._calculateBounds = function () { + // FILL IN// + }; + /** + * Renders this object and its children with culling. + * @protected + * @param {PIXI.Renderer} renderer - The renderer + */ + Container.prototype._renderWithCulling = function (renderer) { + var sourceFrame = renderer.renderTexture.sourceFrame; + // If the source frame is empty, stop rendering. + if (!(sourceFrame.width > 0 && sourceFrame.height > 0)) { + return; + } + // Render the content of the container only if its bounds intersect with the source frame. + // All filters are on the stack at this point, and the filter source frame is bound: + // therefore, even if the bounds to non intersect the filter frame, the filter + // is still applied and any filter padding that is in the frame is rendered correctly. + var bounds; + var transform; + // If cullArea is set, we use this rectangle instead of the bounds of the object. The cullArea + // rectangle must completely contain the container and its children including filter padding. + if (this.cullArea) { + bounds = this.cullArea; + transform = this.worldTransform; + } + // If the container doesn't override _render, we can skip the bounds calculation and intersection test. + else if (this._render !== Container.prototype._render) { + bounds = this.getBounds(true); + } + // Render the container if the source frame intersects the bounds. + if (bounds && sourceFrame.intersects(bounds, transform)) { + this._render(renderer); + } + // If the bounds are defined by cullArea and do not intersect with the source frame, stop rendering. + else if (this.cullArea) { + return; + } + // Unless cullArea is set, we cannot skip the children if the bounds of the container do not intersect + // the source frame, because the children might have filters with nonzero padding, which may intersect + // with the source frame while the bounds do not: filter padding is not included in the bounds. + // If cullArea is not set, render the children with culling temporarily enabled so that they are not rendered + // if they are out of frame; otherwise, render the children normally. + for (var i = 0, j = this.children.length; i < j; ++i) { + var child = this.children[i]; + var childCullable = child.cullable; + child.cullable = childCullable || !this.cullArea; + child.render(renderer); + child.cullable = childCullable; + } + }; + /** + * Renders the object using the WebGL renderer. + * + * The [_render]{@link PIXI.Container#_render} method is be overriden for rendering the contents of the + * container itself. This `render` method will invoke it, and also invoke the `render` methods of all + * children afterward. + * + * If `renderable` or `visible` is false or if `worldAlpha` is not positive or if `cullable` is true and + * the bounds of this object are out of frame, this implementation will entirely skip rendering. + * See {@link PIXI.DisplayObject} for choosing between `renderable` or `visible`. Generally, + * setting alpha to zero is not recommended for purely skipping rendering. + * + * When your scene becomes large (especially when it is larger than can be viewed in a single screen), it is + * advised to employ **culling** to automatically skip rendering objects outside of the current screen. + * See [cullable]{@link PIXI.DisplayObject#cullable} and [cullArea]{@link PIXI.DisplayObject#cullArea}. + * Other culling methods might be better suited for a large number static objects; see + * [@pixi-essentials/cull]{@link https://www.npmjs.com/package/@pixi-essentials/cull} and + * [pixi-cull]{@link https://www.npmjs.com/package/pixi-cull}. + * + * The [renderAdvanced]{@link PIXI.Container#renderAdvanced} method is internally used when when masking or + * filtering is applied on a container. This does, however, break batching and can affect performance when + * masking and filtering is applied extensively throughout the scene graph. + * @param renderer - The renderer + */ + Container.prototype.render = function (renderer) { + // if the object is not visible or the alpha is 0 then no need to render this element + if (!this.visible || this.worldAlpha <= 0 || !this.renderable) { + return; + } + // do a quick check to see if this element has a mask or a filter. + if (this._mask || (this.filters && this.filters.length)) { + this.renderAdvanced(renderer); + } + else if (this.cullable) { + this._renderWithCulling(renderer); + } + else { + this._render(renderer); + for (var i = 0, j = this.children.length; i < j; ++i) { + this.children[i].render(renderer); + } + } + }; + /** + * Render the object using the WebGL renderer and advanced features. + * @param renderer - The renderer + */ + Container.prototype.renderAdvanced = function (renderer) { + var filters = this.filters; + var mask = this._mask; + // push filter first as we need to ensure the stencil buffer is correct for any masking + if (filters) { + if (!this._enabledFilters) { + this._enabledFilters = []; + } + this._enabledFilters.length = 0; + for (var i = 0; i < filters.length; i++) { + if (filters[i].enabled) { + this._enabledFilters.push(filters[i]); + } + } + } + var flush = (filters && this._enabledFilters && this._enabledFilters.length) + || (mask && (!mask.isMaskData + || (mask.enabled && (mask.autoDetect || mask.type !== MASK_TYPES$4.NONE)))); + if (flush) { + renderer.batch.flush(); + } + if (filters && this._enabledFilters && this._enabledFilters.length) { + renderer.filter.push(this, this._enabledFilters); + } + if (mask) { + renderer.mask.push(this, this._mask); + } + if (this.cullable) { + this._renderWithCulling(renderer); + } + else { + this._render(renderer); + for (var i = 0, j = this.children.length; i < j; ++i) { + this.children[i].render(renderer); + } + } + if (flush) { + renderer.batch.flush(); + } + if (mask) { + renderer.mask.pop(this); + } + if (filters && this._enabledFilters && this._enabledFilters.length) { + renderer.filter.pop(); + } + }; + /** + * To be overridden by the subclasses. + * @param _renderer - The renderer + */ + Container.prototype._render = function (_renderer) { + // this is where content itself gets rendered... + }; + /** + * Removes all internal references and listeners as well as removes children from the display list. + * Do not use a Container after calling `destroy`. + * @param options - Options parameter. A boolean will act as if all options + * have been set to that value + * @param {boolean} [options.children=false] - if set to true, all the children will have their destroy + * method called as well. 'options' will be passed on to those calls. + * @param {boolean} [options.texture=false] - Only used for child Sprites if options.children is set to true + * Should it destroy the texture of the child sprite + * @param {boolean} [options.baseTexture=false] - Only used for child Sprites if options.children is set to true + * Should it destroy the base texture of the child sprite + */ + Container.prototype.destroy = function (options) { + _super.prototype.destroy.call(this); + this.sortDirty = false; + var destroyChildren = typeof options === 'boolean' ? options : options && options.children; + var oldChildren = this.removeChildren(0, this.children.length); + if (destroyChildren) { + for (var i = 0; i < oldChildren.length; ++i) { + oldChildren[i].destroy(options); + } + } + }; + Object.defineProperty(Container.prototype, "width", { + /** The width of the Container, setting this will actually modify the scale to achieve the value set. */ + get: function () { + return this.scale.x * this.getLocalBounds().width; + }, + set: function (value) { + var width = this.getLocalBounds().width; + if (width !== 0) { + this.scale.x = value / width; + } + else { + this.scale.x = 1; + } + this._width = value; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(Container.prototype, "height", { + /** The height of the Container, setting this will actually modify the scale to achieve the value set. */ + get: function () { + return this.scale.y * this.getLocalBounds().height; + }, + set: function (value) { + var height = this.getLocalBounds().height; + if (height !== 0) { + this.scale.y = value / height; + } + else { + this.scale.y = 1; + } + this._height = value; + }, + enumerable: false, + configurable: true + }); + return Container; + }(DisplayObject)); + /** + * Container default updateTransform, does update children of container. + * Will crash if there's no parent element. + * @memberof PIXI.Container# + * @method containerUpdateTransform + */ + Container.prototype.containerUpdateTransform = Container.prototype.updateTransform; + + /*! + * @pixi/extensions - v6.5.3 + * Compiled Fri, 09 Sep 2022 13:55:20 UTC + * + * @pixi/extensions is licensed under the MIT License. + * http://www.opensource.org/licenses/mit-license + */ + /*! ***************************************************************************** + Copyright (c) Microsoft Corporation. - THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED - WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, - MERCHANTABLITY OR NON-INFRINGEMENT. + Permission to use, copy, modify, and/or distribute this software for any + purpose with or without fee is hereby granted. - See the Apache Version 2.0 License for specific language governing permissions - and limitations under the License. - ***************************************************************************** */ - /* global Reflect, Promise */ + THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH + REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY + AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, + INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM + LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR + OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR + PERFORMANCE OF THIS SOFTWARE. + ***************************************************************************** */ - var extendStatics$1 = function(d, b) { - extendStatics$1 = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) { if (b.hasOwnProperty(p)) { d[p] = b[p]; } } }; - return extendStatics$1(d, b); - }; + var __assign$1 = function() { + __assign$1 = Object.assign || function __assign(t) { + var arguments$1 = arguments; - function __extends$1(d, b) { - extendStatics$1(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - } - - /** - * Event class that mimics native DOM events. - * - * @class - * @memberof PIXI - */ - var InteractionEvent = /** @class */ (function () { - function InteractionEvent() { - /** - * Whether this event will continue propagating in the tree. - * - * Remaining events for the {@link stopsPropagatingAt} object - * will still be dispatched. - * - * @member {boolean} - */ - this.stopped = false; - /** - * At which object this event stops propagating. - * - * @private - * @member {PIXI.DisplayObject} - */ - this.stopsPropagatingAt = null; - /** - * Whether we already reached the element we want to - * stop propagating at. This is important for delayed events, - * where we start over deeper in the tree again. - * - * @private - * @member {boolean} - */ - this.stopPropagationHint = false; - /** - * The object which caused this event to be dispatched. - * For listener callback see {@link PIXI.InteractionEvent.currentTarget}. - * - * @member {PIXI.DisplayObject} - */ - this.target = null; - /** - * The object whose event listener’s callback is currently being invoked. - * - * @member {PIXI.DisplayObject} - */ - this.currentTarget = null; - /** - * Type of the event - * - * @member {string} - */ - this.type = null; - /** - * InteractionData related to this event - * - * @member {PIXI.InteractionData} - */ - this.data = null; - } - /** - * Prevents event from reaching any objects other than the current object. - * - */ - InteractionEvent.prototype.stopPropagation = function () { - this.stopped = true; - this.stopPropagationHint = true; - this.stopsPropagatingAt = this.currentTarget; - }; - /** - * Resets the event. - */ - InteractionEvent.prototype.reset = function () { - this.stopped = false; - this.stopsPropagatingAt = null; - this.stopPropagationHint = false; - this.currentTarget = null; - this.target = null; - }; - return InteractionEvent; - }()); - - /** - * DisplayObjects with the {@link PIXI.interactiveTarget} mixin use this class to track interactions - * - * @class - * @private - * @memberof PIXI - */ - var InteractionTrackingData = /** @class */ (function () { - /** - * @param {number} pointerId - Unique pointer id of the event - * @private - */ - function InteractionTrackingData(pointerId) { - this._pointerId = pointerId; - this._flags = InteractionTrackingData.FLAGS.NONE; - } - /** - * - * @private - * @param {number} flag - The interaction flag to set - * @param {boolean} yn - Should the flag be set or unset - */ - InteractionTrackingData.prototype._doSet = function (flag, yn) { - if (yn) { - this._flags = this._flags | flag; - } - else { - this._flags = this._flags & (~flag); - } - }; - Object.defineProperty(InteractionTrackingData.prototype, "pointerId", { - /** - * Unique pointer id of the event - * - * @readonly - * @private - * @member {number} - */ - get: function () { - return this._pointerId; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(InteractionTrackingData.prototype, "flags", { - /** - * State of the tracking data, expressed as bit flags - * - * @private - * @member {number} - */ - get: function () { - return this._flags; - }, - set: function (flags) { - this._flags = flags; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(InteractionTrackingData.prototype, "none", { - /** - * Is the tracked event inactive (not over or down)? - * - * @private - * @member {number} - */ - get: function () { - return this._flags === InteractionTrackingData.FLAGS.NONE; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(InteractionTrackingData.prototype, "over", { - /** - * Is the tracked event over the DisplayObject? - * - * @private - * @member {boolean} - */ - get: function () { - return (this._flags & InteractionTrackingData.FLAGS.OVER) !== 0; - }, - set: function (yn) { - this._doSet(InteractionTrackingData.FLAGS.OVER, yn); - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(InteractionTrackingData.prototype, "rightDown", { - /** - * Did the right mouse button come down in the DisplayObject? - * - * @private - * @member {boolean} - */ - get: function () { - return (this._flags & InteractionTrackingData.FLAGS.RIGHT_DOWN) !== 0; - }, - set: function (yn) { - this._doSet(InteractionTrackingData.FLAGS.RIGHT_DOWN, yn); - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(InteractionTrackingData.prototype, "leftDown", { - /** - * Did the left mouse button come down in the DisplayObject? - * - * @private - * @member {boolean} - */ - get: function () { - return (this._flags & InteractionTrackingData.FLAGS.LEFT_DOWN) !== 0; - }, - set: function (yn) { - this._doSet(InteractionTrackingData.FLAGS.LEFT_DOWN, yn); - }, - enumerable: false, - configurable: true - }); - InteractionTrackingData.FLAGS = Object.freeze({ - NONE: 0, - OVER: 1 << 0, - LEFT_DOWN: 1 << 1, - RIGHT_DOWN: 1 << 2, - }); - return InteractionTrackingData; - }()); - - /** - * Strategy how to search through stage tree for interactive objects - * - * @private - * @class - * @memberof PIXI - */ - var TreeSearch = /** @class */ (function () { - function TreeSearch() { - this._tempPoint = new Point(); - } - /** - * Recursive implementation for findHit - * - * @private - * @param {PIXI.InteractionEvent} interactionEvent - event containing the point that - * is tested for collision - * @param {PIXI.Container|PIXI.Sprite|PIXI.TilingSprite} displayObject - the displayObject - * that will be hit test (recursively crawls its children) - * @param {Function} [func] - the function that will be called on each interactive object. The - * interactionEvent, displayObject and hit will be passed to the function - * @param {boolean} [hitTest] - this indicates if the objects inside should be hit test against the point - * @param {boolean} [interactive] - Whether the displayObject is interactive - * @return {boolean} returns true if the displayObject hit the point - */ - TreeSearch.prototype.recursiveFindHit = function (interactionEvent, displayObject, func, hitTest, interactive) { - if (!displayObject || !displayObject.visible) { - return false; - } - var point = interactionEvent.data.global; - // Took a little while to rework this function correctly! But now it is done and nice and optimized! ^_^ - // - // This function will now loop through all objects and then only hit test the objects it HAS - // to, not all of them. MUCH faster.. - // An object will be hit test if the following is true: - // - // 1: It is interactive. - // 2: It belongs to a parent that is interactive AND one of the parents children have not already been hit. - // - // As another little optimization once an interactive object has been hit we can carry on - // through the scenegraph, but we know that there will be no more hits! So we can avoid extra hit tests - // A final optimization is that an object is not hit test directly if a child has already been hit. - interactive = displayObject.interactive || interactive; - var hit = false; - var interactiveParent = interactive; - // Flag here can set to false if the event is outside the parents hitArea or mask - var hitTestChildren = true; - // If there is a hitArea, no need to test against anything else if the pointer is not within the hitArea - // There is also no longer a need to hitTest children. - if (displayObject.hitArea) { - if (hitTest) { - displayObject.worldTransform.applyInverse(point, this._tempPoint); - if (!displayObject.hitArea.contains(this._tempPoint.x, this._tempPoint.y)) { - hitTest = false; - hitTestChildren = false; - } - else { - hit = true; - } - } - interactiveParent = false; - } - // If there is a mask, no need to hitTest against anything else if the pointer is not within the mask. - // We still want to hitTestChildren, however, to ensure a mouseout can still be generated. - // https://github.com/pixijs/pixi.js/issues/5135 - else if (displayObject._mask) { - if (hitTest) { - if (!(displayObject._mask.containsPoint && displayObject._mask.containsPoint(point))) { - hitTest = false; - } - } - } - // ** FREE TIP **! If an object is not interactive or has no buttons in it - // (such as a game scene!) set interactiveChildren to false for that displayObject. - // This will allow PixiJS to completely ignore and bypass checking the displayObjects children. - if (hitTestChildren && displayObject.interactiveChildren && displayObject.children) { - var children = displayObject.children; - for (var i = children.length - 1; i >= 0; i--) { - var child = children[i]; - // time to get recursive.. if this function will return if something is hit.. - var childHit = this.recursiveFindHit(interactionEvent, child, func, hitTest, interactiveParent); - if (childHit) { - // its a good idea to check if a child has lost its parent. - // this means it has been removed whilst looping so its best - if (!child.parent) { - continue; - } - // we no longer need to hit test any more objects in this container as we we - // now know the parent has been hit - interactiveParent = false; - // If the child is interactive , that means that the object hit was actually - // interactive and not just the child of an interactive object. - // This means we no longer need to hit test anything else. We still need to run - // through all objects, but we don't need to perform any hit tests. - if (childHit) { - if (interactionEvent.target) { - hitTest = false; - } - hit = true; - } - } - } - } - // no point running this if the item is not interactive or does not have an interactive parent. - if (interactive) { - // if we are hit testing (as in we have no hit any objects yet) - // We also don't need to worry about hit testing if once of the displayObjects children - // has already been hit - but only if it was interactive, otherwise we need to keep - // looking for an interactive child, just in case we hit one - if (hitTest && !interactionEvent.target) { - // already tested against hitArea if it is defined - if (!displayObject.hitArea && displayObject.containsPoint) { - if (displayObject.containsPoint(point)) { - hit = true; - } - } - } - if (displayObject.interactive) { - if (hit && !interactionEvent.target) { - interactionEvent.target = displayObject; - } - if (func) { - func(interactionEvent, displayObject, !!hit); - } - } - } - return hit; - }; - /** - * This function is provides a neat way of crawling through the scene graph and running a - * specified function on all interactive objects it finds. It will also take care of hit - * testing the interactive objects and passes the hit across in the function. - * - * @private - * @param {PIXI.InteractionEvent} interactionEvent - event containing the point that - * is tested for collision - * @param {PIXI.Container|PIXI.Sprite|PIXI.TilingSprite} displayObject - the displayObject - * that will be hit test (recursively crawls its children) - * @param {Function} [func] - the function that will be called on each interactive object. The - * interactionEvent, displayObject and hit will be passed to the function - * @param {boolean} [hitTest] - this indicates if the objects inside should be hit test against the point - * @return {boolean} returns true if the displayObject hit the point - */ - TreeSearch.prototype.findHit = function (interactionEvent, displayObject, func, hitTest) { - this.recursiveFindHit(interactionEvent, displayObject, func, hitTest, false); - }; - return TreeSearch; - }()); - - /** - * Interface for classes that represent a hit area. - * - * It is implemented by the following classes: - * - {@link PIXI.Circle} - * - {@link PIXI.Ellipse} - * - {@link PIXI.Polygon} - * - {@link PIXI.RoundedRectangle} - * - * @interface IHitArea - * @memberof PIXI - */ - /** - * Checks whether the x and y coordinates given are contained within this area - * - * @method - * @name contains - * @memberof PIXI.IHitArea# - * @param {number} x - The X coordinate of the point to test - * @param {number} y - The Y coordinate of the point to test - * @return {boolean} Whether the x/y coordinates are within this area - */ - /** - * Default property values of interactive objects - * Used by {@link PIXI.InteractionManager} to automatically give all DisplayObjects these properties - * - * @private - * @name interactiveTarget - * @type {Object} - * @memberof PIXI - * @example - * function MyObject() {} - * - * Object.assign( - * DisplayObject.prototype, - * PIXI.interactiveTarget - * ); - */ - var interactiveTarget = { - /** - * Enable interaction events for the DisplayObject. Touch, pointer and mouse - * events will not be emitted unless `interactive` is set to `true`. - * - * @example - * const sprite = new PIXI.Sprite(texture); - * sprite.interactive = true; - * sprite.on('tap', (event) => { - * //handle event - * }); - * @member {boolean} - * @memberof PIXI.DisplayObject# - */ - interactive: false, - /** - * Determines if the children to the displayObject can be clicked/touched - * Setting this to false allows PixiJS to bypass a recursive `hitTest` function - * - * @member {boolean} - * @memberof PIXI.Container# - */ - interactiveChildren: true, - /** - * Interaction shape. Children will be hit first, then this shape will be checked. - * Setting this will cause this shape to be checked in hit tests rather than the displayObject's bounds. - * - * @example - * const sprite = new PIXI.Sprite(texture); - * sprite.interactive = true; - * sprite.hitArea = new PIXI.Rectangle(0, 0, 100, 100); - * @member {PIXI.IHitArea} - * @memberof PIXI.DisplayObject# - */ - hitArea: null, - /** - * If enabled, the mouse cursor use the pointer behavior when hovered over the displayObject if it is interactive - * Setting this changes the 'cursor' property to `'pointer'`. - * - * @example - * const sprite = new PIXI.Sprite(texture); - * sprite.interactive = true; - * sprite.buttonMode = true; - * @member {boolean} - * @memberof PIXI.DisplayObject# - */ - get buttonMode() { - return this.cursor === 'pointer'; - }, - set buttonMode(value) { - if (value) { - this.cursor = 'pointer'; - } - else if (this.cursor === 'pointer') { - this.cursor = null; - } - }, - /** - * This defines what cursor mode is used when the mouse cursor - * is hovered over the displayObject. - * - * @example - * const sprite = new PIXI.Sprite(texture); - * sprite.interactive = true; - * sprite.cursor = 'wait'; - * @see https://developer.mozilla.org/en/docs/Web/CSS/cursor - * - * @member {string} - * @memberof PIXI.DisplayObject# - */ - cursor: null, - /** - * Internal set of all active pointers, by identifier - * - * @member {Map} - * @memberof PIXI.DisplayObject# - * @private - */ - get trackedPointers() { - if (this._trackedPointers === undefined) - { this._trackedPointers = {}; } - return this._trackedPointers; - }, - /** - * Map of all tracked pointers, by identifier. Use trackedPointers to access. - * - * @private - * @type {Map} - */ - _trackedPointers: undefined, - }; - - // Mix interactiveTarget into DisplayObject.prototype, - // after deprecation has been handled - DisplayObject.mixin(interactiveTarget); - var MOUSE_POINTER_ID = 1; - // helpers for hitTest() - only used inside hitTest() - var hitTestEvent = { - target: null, - data: { - global: null, - }, - }; - /** - * The interaction manager deals with mouse, touch and pointer events. - * - * Any DisplayObject can be interactive if its `interactive` property is set to true. - * - * This manager also supports multitouch. - * - * An instance of this class is automatically created by default, and can be found at `renderer.plugins.interaction` - * - * @class - * @extends PIXI.utils.EventEmitter - * @memberof PIXI - */ - var InteractionManager = /** @class */ (function (_super) { - __extends$1(InteractionManager, _super); - /** - * @param {PIXI.CanvasRenderer|PIXI.Renderer} renderer - A reference to the current renderer - * @param {object} [options] - The options for the manager. - * @param {boolean} [options.autoPreventDefault=true] - Should the manager automatically prevent default browser actions. - * @param {number} [options.interactionFrequency=10] - Maximum requency (ms) at pointer over/out states will be checked. - * @param {number} [options.useSystemTicker=true] - Whether to add {@link tickerUpdate} to {@link PIXI.Ticker.system}. - */ - function InteractionManager(renderer, options) { - var _this = _super.call(this) || this; - options = options || {}; - /** - * The renderer this interaction manager works for. - * - * @member {PIXI.AbstractRenderer} - */ - _this.renderer = renderer; - /** - * Should default browser actions automatically be prevented. - * Does not apply to pointer events for backwards compatibility - * preventDefault on pointer events stops mouse events from firing - * Thus, for every pointer event, there will always be either a mouse of touch event alongside it. - * - * @member {boolean} - * @default true - */ - _this.autoPreventDefault = options.autoPreventDefault !== undefined ? options.autoPreventDefault : true; - /** - * Maximum requency in milliseconds at which pointer over/out states will be checked by {@link tickerUpdate}. - * - * @member {number} - * @default 10 - */ - _this.interactionFrequency = options.interactionFrequency || 10; - /** - * The mouse data - * - * @member {PIXI.InteractionData} - */ - _this.mouse = new InteractionData(); - _this.mouse.identifier = MOUSE_POINTER_ID; - // setting the mouse to start off far off screen will mean that mouse over does - // not get called before we even move the mouse. - _this.mouse.global.set(-999999); - /** - * Actively tracked InteractionData - * - * @private - * @member {Object.} - */ - _this.activeInteractionData = {}; - _this.activeInteractionData[MOUSE_POINTER_ID] = _this.mouse; - /** - * Pool of unused InteractionData - * - * @private - * @member {PIXI.InteractionData[]} - */ - _this.interactionDataPool = []; - /** - * An event data object to handle all the event tracking/dispatching - * - * @member {object} - */ - _this.eventData = new InteractionEvent(); - /** - * The DOM element to bind to. - * - * @protected - * @member {HTMLElement} - */ - _this.interactionDOMElement = null; - /** - * This property determines if mousemove and touchmove events are fired only when the cursor - * is over the object. - * Setting to true will make things work more in line with how the DOM version works. - * Setting to false can make things easier for things like dragging - * It is currently set to false as this is how PixiJS used to work. This will be set to true in - * future versions of pixi. - * - * @member {boolean} - * @default false - */ - _this.moveWhenInside = false; - /** - * Have events been attached to the dom element? - * - * @protected - * @member {boolean} - */ - _this.eventsAdded = false; - /** - * Has the system ticker been added? - * - * @protected - * @member {boolean} - */ - _this.tickerAdded = false; - /** - * Is the mouse hovering over the renderer? - * - * @protected - * @member {boolean} - */ - _this.mouseOverRenderer = false; - /** - * Does the device support touch events - * https://www.w3.org/TR/touch-events/ - * - * @readonly - * @member {boolean} - */ - _this.supportsTouchEvents = 'ontouchstart' in window; - /** - * Does the device support pointer events - * https://www.w3.org/Submission/pointer-events/ - * - * @readonly - * @member {boolean} - */ - _this.supportsPointerEvents = !!window.PointerEvent; - // this will make it so that you don't have to call bind all the time - /** - * @private - * @member {Function} - */ - _this.onPointerUp = _this.onPointerUp.bind(_this); - _this.processPointerUp = _this.processPointerUp.bind(_this); - /** - * @private - * @member {Function} - */ - _this.onPointerCancel = _this.onPointerCancel.bind(_this); - _this.processPointerCancel = _this.processPointerCancel.bind(_this); - /** - * @private - * @member {Function} - */ - _this.onPointerDown = _this.onPointerDown.bind(_this); - _this.processPointerDown = _this.processPointerDown.bind(_this); - /** - * @private - * @member {Function} - */ - _this.onPointerMove = _this.onPointerMove.bind(_this); - _this.processPointerMove = _this.processPointerMove.bind(_this); - /** - * @private - * @member {Function} - */ - _this.onPointerOut = _this.onPointerOut.bind(_this); - _this.processPointerOverOut = _this.processPointerOverOut.bind(_this); - /** - * @private - * @member {Function} - */ - _this.onPointerOver = _this.onPointerOver.bind(_this); - /** - * Dictionary of how different cursor modes are handled. Strings are handled as CSS cursor - * values, objects are handled as dictionaries of CSS values for interactionDOMElement, - * and functions are called instead of changing the CSS. - * Default CSS cursor values are provided for 'default' and 'pointer' modes. - * @member {Object.} - */ - _this.cursorStyles = { - default: 'inherit', - pointer: 'pointer', - }; - /** - * The mode of the cursor that is being used. - * The value of this is a key from the cursorStyles dictionary. - * - * @member {string} - */ - _this.currentCursorMode = null; - /** - * Internal cached let. - * - * @private - * @member {string} - */ - _this.cursor = null; - /** - * The current resolution / device pixel ratio. - * - * @member {number} - * @default 1 - */ - _this.resolution = 1; - /** - * Delayed pointer events. Used to guarantee correct ordering of over/out events. - * - * @private - * @member {Array} - */ - _this.delayedEvents = []; - /** - * TreeSearch component that is used to hitTest stage tree - * - * @private - * @member {PIXI.TreeSearch} - */ - _this.search = new TreeSearch(); - /** - * Used as a last rendered object in case renderer doesnt have _lastObjectRendered - * @member {DisplayObject} - * @private - */ - _this._tempDisplayObject = new TemporaryDisplayObject(); - /** - * Fired when a pointer device button (usually a mouse left-button) is pressed on the display - * object. - * - * @event PIXI.InteractionManager#mousedown - * @param {PIXI.InteractionEvent} event - Interaction event - */ - /** - * Fired when a pointer device secondary button (usually a mouse right-button) is pressed - * on the display object. - * - * @event PIXI.InteractionManager#rightdown - * @param {PIXI.InteractionEvent} event - Interaction event - */ - /** - * Fired when a pointer device button (usually a mouse left-button) is released over the display - * object. - * - * @event PIXI.InteractionManager#mouseup - * @param {PIXI.InteractionEvent} event - Interaction event - */ - /** - * Fired when a pointer device secondary button (usually a mouse right-button) is released - * over the display object. - * - * @event PIXI.InteractionManager#rightup - * @param {PIXI.InteractionEvent} event - Interaction event - */ - /** - * Fired when a pointer device button (usually a mouse left-button) is pressed and released on - * the display object. - * - * @event PIXI.InteractionManager#click - * @param {PIXI.InteractionEvent} event - Interaction event - */ - /** - * Fired when a pointer device secondary button (usually a mouse right-button) is pressed - * and released on the display object. - * - * @event PIXI.InteractionManager#rightclick - * @param {PIXI.InteractionEvent} event - Interaction event - */ - /** - * Fired when a pointer device button (usually a mouse left-button) is released outside the - * display object that initially registered a - * [mousedown]{@link PIXI.InteractionManager#event:mousedown}. - * - * @event PIXI.InteractionManager#mouseupoutside - * @param {PIXI.InteractionEvent} event - Interaction event - */ - /** - * Fired when a pointer device secondary button (usually a mouse right-button) is released - * outside the display object that initially registered a - * [rightdown]{@link PIXI.InteractionManager#event:rightdown}. - * - * @event PIXI.InteractionManager#rightupoutside - * @param {PIXI.InteractionEvent} event - Interaction event - */ - /** - * Fired when a pointer device (usually a mouse) is moved while over the display object - * - * @event PIXI.InteractionManager#mousemove - * @param {PIXI.InteractionEvent} event - Interaction event - */ - /** - * Fired when a pointer device (usually a mouse) is moved onto the display object - * - * @event PIXI.InteractionManager#mouseover - * @param {PIXI.InteractionEvent} event - Interaction event - */ - /** - * Fired when a pointer device (usually a mouse) is moved off the display object - * - * @event PIXI.InteractionManager#mouseout - * @param {PIXI.InteractionEvent} event - Interaction event - */ - /** - * Fired when a pointer device button is pressed on the display object. - * - * @event PIXI.InteractionManager#pointerdown - * @param {PIXI.InteractionEvent} event - Interaction event - */ - /** - * Fired when a pointer device button is released over the display object. - * Not always fired when some buttons are held down while others are released. In those cases, - * use [mousedown]{@link PIXI.InteractionManager#event:mousedown} and - * [mouseup]{@link PIXI.InteractionManager#event:mouseup} instead. - * - * @event PIXI.InteractionManager#pointerup - * @param {PIXI.InteractionEvent} event - Interaction event - */ - /** - * Fired when the operating system cancels a pointer event - * - * @event PIXI.InteractionManager#pointercancel - * @param {PIXI.InteractionEvent} event - Interaction event - */ - /** - * Fired when a pointer device button is pressed and released on the display object. - * - * @event PIXI.InteractionManager#pointertap - * @param {PIXI.InteractionEvent} event - Interaction event - */ - /** - * Fired when a pointer device button is released outside the display object that initially - * registered a [pointerdown]{@link PIXI.InteractionManager#event:pointerdown}. - * - * @event PIXI.InteractionManager#pointerupoutside - * @param {PIXI.InteractionEvent} event - Interaction event - */ - /** - * Fired when a pointer device is moved while over the display object - * - * @event PIXI.InteractionManager#pointermove - * @param {PIXI.InteractionEvent} event - Interaction event - */ - /** - * Fired when a pointer device is moved onto the display object - * - * @event PIXI.InteractionManager#pointerover - * @param {PIXI.InteractionEvent} event - Interaction event - */ - /** - * Fired when a pointer device is moved off the display object - * - * @event PIXI.InteractionManager#pointerout - * @param {PIXI.InteractionEvent} event - Interaction event - */ - /** - * Fired when a touch point is placed on the display object. - * - * @event PIXI.InteractionManager#touchstart - * @param {PIXI.InteractionEvent} event - Interaction event - */ - /** - * Fired when a touch point is removed from the display object. - * - * @event PIXI.InteractionManager#touchend - * @param {PIXI.InteractionEvent} event - Interaction event - */ - /** - * Fired when the operating system cancels a touch - * - * @event PIXI.InteractionManager#touchcancel - * @param {PIXI.InteractionEvent} event - Interaction event - */ - /** - * Fired when a touch point is placed and removed from the display object. - * - * @event PIXI.InteractionManager#tap - * @param {PIXI.InteractionEvent} event - Interaction event - */ - /** - * Fired when a touch point is removed outside of the display object that initially - * registered a [touchstart]{@link PIXI.InteractionManager#event:touchstart}. - * - * @event PIXI.InteractionManager#touchendoutside - * @param {PIXI.InteractionEvent} event - Interaction event - */ - /** - * Fired when a touch point is moved along the display object. - * - * @event PIXI.InteractionManager#touchmove - * @param {PIXI.InteractionEvent} event - Interaction event - */ - /** - * Fired when a pointer device button (usually a mouse left-button) is pressed on the display. - * object. DisplayObject's `interactive` property must be set to `true` to fire event. - * - * @event PIXI.DisplayObject#mousedown - * @param {PIXI.InteractionEvent} event - Interaction event - */ - /** - * Fired when a pointer device secondary button (usually a mouse right-button) is pressed - * on the display object. DisplayObject's `interactive` property must be set to `true` to fire event. - * - * @event PIXI.DisplayObject#rightdown - * @param {PIXI.InteractionEvent} event - Interaction event - */ - /** - * Fired when a pointer device button (usually a mouse left-button) is released over the display - * object. DisplayObject's `interactive` property must be set to `true` to fire event. - * - * @event PIXI.DisplayObject#mouseup - * @param {PIXI.InteractionEvent} event - Interaction event - */ - /** - * Fired when a pointer device secondary button (usually a mouse right-button) is released - * over the display object. DisplayObject's `interactive` property must be set to `true` to fire event. - * - * @event PIXI.DisplayObject#rightup - * @param {PIXI.InteractionEvent} event - Interaction event - */ - /** - * Fired when a pointer device button (usually a mouse left-button) is pressed and released on - * the display object. DisplayObject's `interactive` property must be set to `true` to fire event. - * - * @event PIXI.DisplayObject#click - * @param {PIXI.InteractionEvent} event - Interaction event - */ - /** - * Fired when a pointer device secondary button (usually a mouse right-button) is pressed - * and released on the display object. DisplayObject's `interactive` property must be set to `true` to fire event. - * - * @event PIXI.DisplayObject#rightclick - * @param {PIXI.InteractionEvent} event - Interaction event - */ - /** - * Fired when a pointer device button (usually a mouse left-button) is released outside the - * display object that initially registered a - * [mousedown]{@link PIXI.DisplayObject#event:mousedown}. - * DisplayObject's `interactive` property must be set to `true` to fire event. - * - * @event PIXI.DisplayObject#mouseupoutside - * @param {PIXI.InteractionEvent} event - Interaction event - */ - /** - * Fired when a pointer device secondary button (usually a mouse right-button) is released - * outside the display object that initially registered a - * [rightdown]{@link PIXI.DisplayObject#event:rightdown}. - * DisplayObject's `interactive` property must be set to `true` to fire event. - * - * @event PIXI.DisplayObject#rightupoutside - * @param {PIXI.InteractionEvent} event - Interaction event - */ - /** - * Fired when a pointer device (usually a mouse) is moved while over the display object. - * DisplayObject's `interactive` property must be set to `true` to fire event. - * - * @event PIXI.DisplayObject#mousemove - * @param {PIXI.InteractionEvent} event - Interaction event - */ - /** - * Fired when a pointer device (usually a mouse) is moved onto the display object. - * DisplayObject's `interactive` property must be set to `true` to fire event. - * - * @event PIXI.DisplayObject#mouseover - * @param {PIXI.InteractionEvent} event - Interaction event - */ - /** - * Fired when a pointer device (usually a mouse) is moved off the display object. - * DisplayObject's `interactive` property must be set to `true` to fire event. - * - * @event PIXI.DisplayObject#mouseout - * @param {PIXI.InteractionEvent} event - Interaction event - */ - /** - * Fired when a pointer device button is pressed on the display object. - * DisplayObject's `interactive` property must be set to `true` to fire event. - * - * @event PIXI.DisplayObject#pointerdown - * @param {PIXI.InteractionEvent} event - Interaction event - */ - /** - * Fired when a pointer device button is released over the display object. - * DisplayObject's `interactive` property must be set to `true` to fire event. - * - * @event PIXI.DisplayObject#pointerup - * @param {PIXI.InteractionEvent} event - Interaction event - */ - /** - * Fired when the operating system cancels a pointer event. - * DisplayObject's `interactive` property must be set to `true` to fire event. - * - * @event PIXI.DisplayObject#pointercancel - * @param {PIXI.InteractionEvent} event - Interaction event - */ - /** - * Fired when a pointer device button is pressed and released on the display object. - * DisplayObject's `interactive` property must be set to `true` to fire event. - * - * @event PIXI.DisplayObject#pointertap - * @param {PIXI.InteractionEvent} event - Interaction event - */ - /** - * Fired when a pointer device button is released outside the display object that initially - * registered a [pointerdown]{@link PIXI.DisplayObject#event:pointerdown}. - * DisplayObject's `interactive` property must be set to `true` to fire event. - * - * @event PIXI.DisplayObject#pointerupoutside - * @param {PIXI.InteractionEvent} event - Interaction event - */ - /** - * Fired when a pointer device is moved while over the display object. - * DisplayObject's `interactive` property must be set to `true` to fire event. - * - * @event PIXI.DisplayObject#pointermove - * @param {PIXI.InteractionEvent} event - Interaction event - */ - /** - * Fired when a pointer device is moved onto the display object. - * DisplayObject's `interactive` property must be set to `true` to fire event. - * - * @event PIXI.DisplayObject#pointerover - * @param {PIXI.InteractionEvent} event - Interaction event - */ - /** - * Fired when a pointer device is moved off the display object. - * DisplayObject's `interactive` property must be set to `true` to fire event. - * - * @event PIXI.DisplayObject#pointerout - * @param {PIXI.InteractionEvent} event - Interaction event - */ - /** - * Fired when a touch point is placed on the display object. - * DisplayObject's `interactive` property must be set to `true` to fire event. - * - * @event PIXI.DisplayObject#touchstart - * @param {PIXI.InteractionEvent} event - Interaction event - */ - /** - * Fired when a touch point is removed from the display object. - * DisplayObject's `interactive` property must be set to `true` to fire event. - * - * @event PIXI.DisplayObject#touchend - * @param {PIXI.InteractionEvent} event - Interaction event - */ - /** - * Fired when the operating system cancels a touch. - * DisplayObject's `interactive` property must be set to `true` to fire event. - * - * @event PIXI.DisplayObject#touchcancel - * @param {PIXI.InteractionEvent} event - Interaction event - */ - /** - * Fired when a touch point is placed and removed from the display object. - * DisplayObject's `interactive` property must be set to `true` to fire event. - * - * @event PIXI.DisplayObject#tap - * @param {PIXI.InteractionEvent} event - Interaction event - */ - /** - * Fired when a touch point is removed outside of the display object that initially - * registered a [touchstart]{@link PIXI.DisplayObject#event:touchstart}. - * DisplayObject's `interactive` property must be set to `true` to fire event. - * - * @event PIXI.DisplayObject#touchendoutside - * @param {PIXI.InteractionEvent} event - Interaction event - */ - /** - * Fired when a touch point is moved along the display object. - * DisplayObject's `interactive` property must be set to `true` to fire event. - * - * @event PIXI.DisplayObject#touchmove - * @param {PIXI.InteractionEvent} event - Interaction event - */ - _this._useSystemTicker = options.useSystemTicker !== undefined ? options.useSystemTicker : true; - _this.setTargetElement(_this.renderer.view, _this.renderer.resolution); - return _this; - } - Object.defineProperty(InteractionManager.prototype, "useSystemTicker", { - /** - * Should the InteractionManager automatically add {@link tickerUpdate} to {@link PIXI.Ticker.system}. - * - * @member {boolean} - * @default true - */ - get: function () { - return this._useSystemTicker; - }, - set: function (useSystemTicker) { - this._useSystemTicker = useSystemTicker; - if (useSystemTicker) { - this.addTickerListener(); - } - else { - this.removeTickerListener(); - } - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(InteractionManager.prototype, "lastObjectRendered", { - /** - * Last rendered object or temp object - * @readonly - * @protected - * @member {PIXI.DisplayObject} - */ - get: function () { - return this.renderer._lastObjectRendered || this._tempDisplayObject; - }, - enumerable: false, - configurable: true - }); - /** - * Hit tests a point against the display tree, returning the first interactive object that is hit. - * - * @param {PIXI.Point} globalPoint - A point to hit test with, in global space. - * @param {PIXI.Container} [root] - The root display object to start from. If omitted, defaults - * to the last rendered root of the associated renderer. - * @return {PIXI.DisplayObject} The hit display object, if any. - */ - InteractionManager.prototype.hitTest = function (globalPoint, root) { - // clear the target for our hit test - hitTestEvent.target = null; - // assign the global point - hitTestEvent.data.global = globalPoint; - // ensure safety of the root - if (!root) { - root = this.lastObjectRendered; - } - // run the hit test - this.processInteractive(hitTestEvent, root, null, true); - // return our found object - it'll be null if we didn't hit anything - return hitTestEvent.target; - }; - /** - * Sets the DOM element which will receive mouse/touch events. This is useful for when you have - * other DOM elements on top of the renderers Canvas element. With this you'll be bale to delegate - * another DOM element to receive those events. - * - * @param {HTMLElement} element - the DOM element which will receive mouse and touch events. - * @param {number} [resolution=1] - The resolution / device pixel ratio of the new element (relative to the canvas). - */ - InteractionManager.prototype.setTargetElement = function (element, resolution) { - if (resolution === void 0) { resolution = 1; } - this.removeTickerListener(); - this.removeEvents(); - this.interactionDOMElement = element; - this.resolution = resolution; - this.addEvents(); - this.addTickerListener(); - }; - /** - * Add the ticker listener - * - * @private - */ - InteractionManager.prototype.addTickerListener = function () { - if (this.tickerAdded || !this.interactionDOMElement || !this._useSystemTicker) { - return; - } - Ticker.system.add(this.tickerUpdate, this, exports.UPDATE_PRIORITY.INTERACTION); - this.tickerAdded = true; - }; - /** - * Remove the ticker listener - * - * @private - */ - InteractionManager.prototype.removeTickerListener = function () { - if (!this.tickerAdded) { - return; - } - Ticker.system.remove(this.tickerUpdate, this); - this.tickerAdded = false; - }; - /** - * Registers all the DOM events - * - * @private - */ - InteractionManager.prototype.addEvents = function () { - if (this.eventsAdded || !this.interactionDOMElement) { - return; - } - var style = this.interactionDOMElement.style; - if (window.navigator.msPointerEnabled) { - style.msContentZooming = 'none'; - style.msTouchAction = 'none'; - } - else if (this.supportsPointerEvents) { - style.touchAction = 'none'; - } - /** - * These events are added first, so that if pointer events are normalized, they are fired - * in the same order as non-normalized events. ie. pointer event 1st, mouse / touch 2nd - */ - if (this.supportsPointerEvents) { - window.document.addEventListener('pointermove', this.onPointerMove, true); - this.interactionDOMElement.addEventListener('pointerdown', this.onPointerDown, true); - // pointerout is fired in addition to pointerup (for touch events) and pointercancel - // we already handle those, so for the purposes of what we do in onPointerOut, we only - // care about the pointerleave event - this.interactionDOMElement.addEventListener('pointerleave', this.onPointerOut, true); - this.interactionDOMElement.addEventListener('pointerover', this.onPointerOver, true); - window.addEventListener('pointercancel', this.onPointerCancel, true); - window.addEventListener('pointerup', this.onPointerUp, true); - } - else { - window.document.addEventListener('mousemove', this.onPointerMove, true); - this.interactionDOMElement.addEventListener('mousedown', this.onPointerDown, true); - this.interactionDOMElement.addEventListener('mouseout', this.onPointerOut, true); - this.interactionDOMElement.addEventListener('mouseover', this.onPointerOver, true); - window.addEventListener('mouseup', this.onPointerUp, true); - } - // always look directly for touch events so that we can provide original data - // In a future version we should change this to being just a fallback and rely solely on - // PointerEvents whenever available - if (this.supportsTouchEvents) { - this.interactionDOMElement.addEventListener('touchstart', this.onPointerDown, true); - this.interactionDOMElement.addEventListener('touchcancel', this.onPointerCancel, true); - this.interactionDOMElement.addEventListener('touchend', this.onPointerUp, true); - this.interactionDOMElement.addEventListener('touchmove', this.onPointerMove, true); - } - this.eventsAdded = true; - }; - /** - * Removes all the DOM events that were previously registered - * - * @private - */ - InteractionManager.prototype.removeEvents = function () { - if (!this.eventsAdded || !this.interactionDOMElement) { - return; - } - var style = this.interactionDOMElement.style; - if (window.navigator.msPointerEnabled) { - style.msContentZooming = ''; - style.msTouchAction = ''; - } - else if (this.supportsPointerEvents) { - style.touchAction = ''; - } - if (this.supportsPointerEvents) { - window.document.removeEventListener('pointermove', this.onPointerMove, true); - this.interactionDOMElement.removeEventListener('pointerdown', this.onPointerDown, true); - this.interactionDOMElement.removeEventListener('pointerleave', this.onPointerOut, true); - this.interactionDOMElement.removeEventListener('pointerover', this.onPointerOver, true); - window.removeEventListener('pointercancel', this.onPointerCancel, true); - window.removeEventListener('pointerup', this.onPointerUp, true); - } - else { - window.document.removeEventListener('mousemove', this.onPointerMove, true); - this.interactionDOMElement.removeEventListener('mousedown', this.onPointerDown, true); - this.interactionDOMElement.removeEventListener('mouseout', this.onPointerOut, true); - this.interactionDOMElement.removeEventListener('mouseover', this.onPointerOver, true); - window.removeEventListener('mouseup', this.onPointerUp, true); - } - if (this.supportsTouchEvents) { - this.interactionDOMElement.removeEventListener('touchstart', this.onPointerDown, true); - this.interactionDOMElement.removeEventListener('touchcancel', this.onPointerCancel, true); - this.interactionDOMElement.removeEventListener('touchend', this.onPointerUp, true); - this.interactionDOMElement.removeEventListener('touchmove', this.onPointerMove, true); - } - this.interactionDOMElement = null; - this.eventsAdded = false; - }; - /** - * Updates the state of interactive objects if at least {@link interactionFrequency} - * milliseconds have passed since the last invocation. - * - * Invoked by a throttled ticker update from {@link PIXI.Ticker.system}. - * - * @param {number} deltaTime - time delta since the last call - */ - InteractionManager.prototype.tickerUpdate = function (deltaTime) { - this._deltaTime += deltaTime; - if (this._deltaTime < this.interactionFrequency) { - return; - } - this._deltaTime = 0; - this.update(); - }; - /** - * Updates the state of interactive objects. - */ - InteractionManager.prototype.update = function () { - if (!this.interactionDOMElement) { - return; - } - // if the user move the mouse this check has already been done using the mouse move! - if (this._didMove) { - this._didMove = false; - return; - } - this.cursor = null; - // Resets the flag as set by a stopPropagation call. This flag is usually reset by a user interaction of any kind, - // but there was a scenario of a display object moving under a static mouse cursor. - // In this case, mouseover and mouseevents would not pass the flag test in dispatchEvent function - for (var k in this.activeInteractionData) { - // eslint-disable-next-line no-prototype-builtins - if (this.activeInteractionData.hasOwnProperty(k)) { - var interactionData = this.activeInteractionData[k]; - if (interactionData.originalEvent && interactionData.pointerType !== 'touch') { - var interactionEvent = this.configureInteractionEventForDOMEvent(this.eventData, interactionData.originalEvent, interactionData); - this.processInteractive(interactionEvent, this.lastObjectRendered, this.processPointerOverOut, true); - } - } - } - this.setCursorMode(this.cursor); - }; - /** - * Sets the current cursor mode, handling any callbacks or CSS style changes. - * - * @param {string} mode - cursor mode, a key from the cursorStyles dictionary - */ - InteractionManager.prototype.setCursorMode = function (mode) { - mode = mode || 'default'; - // if the mode didn't actually change, bail early - if (this.currentCursorMode === mode) { - return; - } - this.currentCursorMode = mode; - var style = this.cursorStyles[mode]; - // only do things if there is a cursor style for it - if (style) { - switch (typeof style) { - case 'string': - // string styles are handled as cursor CSS - this.interactionDOMElement.style.cursor = style; - break; - case 'function': - // functions are just called, and passed the cursor mode - style(mode); - break; - case 'object': - // if it is an object, assume that it is a dictionary of CSS styles, - // apply it to the interactionDOMElement - Object.assign(this.interactionDOMElement.style, style); - break; - } - } - else if (typeof mode === 'string' && !Object.prototype.hasOwnProperty.call(this.cursorStyles, mode)) { - // if it mode is a string (not a Symbol) and cursorStyles doesn't have any entry - // for the mode, then assume that the dev wants it to be CSS for the cursor. - this.interactionDOMElement.style.cursor = mode; - } - }; - /** - * Dispatches an event on the display object that was interacted with - * - * @param {PIXI.Container|PIXI.Sprite|PIXI.TilingSprite} displayObject - the display object in question - * @param {string} eventString - the name of the event (e.g, mousedown) - * @param {PIXI.InteractionEvent} eventData - the event data object - * @private - */ - InteractionManager.prototype.dispatchEvent = function (displayObject, eventString, eventData) { - // Even if the event was stopped, at least dispatch any remaining events - // for the same display object. - if (!eventData.stopPropagationHint || displayObject === eventData.stopsPropagatingAt) { - eventData.currentTarget = displayObject; - eventData.type = eventString; - displayObject.emit(eventString, eventData); - if (displayObject[eventString]) { - displayObject[eventString](eventData); - } - } - }; - /** - * Puts a event on a queue to be dispatched later. This is used to guarantee correct - * ordering of over/out events. - * - * @param {PIXI.Container|PIXI.Sprite|PIXI.TilingSprite} displayObject - the display object in question - * @param {string} eventString - the name of the event (e.g, mousedown) - * @param {object} eventData - the event data object - * @private - */ - InteractionManager.prototype.delayDispatchEvent = function (displayObject, eventString, eventData) { - this.delayedEvents.push({ displayObject: displayObject, eventString: eventString, eventData: eventData }); - }; - /** - * Maps x and y coords from a DOM object and maps them correctly to the PixiJS view. The - * resulting value is stored in the point. This takes into account the fact that the DOM - * element could be scaled and positioned anywhere on the screen. - * - * @param {PIXI.IPointData} point - the point that the result will be stored in - * @param {number} x - the x coord of the position to map - * @param {number} y - the y coord of the position to map - */ - InteractionManager.prototype.mapPositionToPoint = function (point, x, y) { - var rect; - // IE 11 fix - if (!this.interactionDOMElement.parentElement) { - rect = { x: 0, y: 0, width: 0, height: 0 }; - } - else { - rect = this.interactionDOMElement.getBoundingClientRect(); - } - var resolutionMultiplier = 1.0 / this.resolution; - point.x = ((x - rect.left) * (this.interactionDOMElement.width / rect.width)) * resolutionMultiplier; - point.y = ((y - rect.top) * (this.interactionDOMElement.height / rect.height)) * resolutionMultiplier; - }; - /** - * This function is provides a neat way of crawling through the scene graph and running a - * specified function on all interactive objects it finds. It will also take care of hit - * testing the interactive objects and passes the hit across in the function. - * - * @protected - * @param {PIXI.InteractionEvent} interactionEvent - event containing the point that - * is tested for collision - * @param {PIXI.Container|PIXI.Sprite|PIXI.TilingSprite} displayObject - the displayObject - * that will be hit test (recursively crawls its children) - * @param {Function} [func] - the function that will be called on each interactive object. The - * interactionEvent, displayObject and hit will be passed to the function - * @param {boolean} [hitTest] - indicates whether we want to calculate hits - * or just iterate through all interactive objects - */ - InteractionManager.prototype.processInteractive = function (interactionEvent, displayObject, func, hitTest) { - var hit = this.search.findHit(interactionEvent, displayObject, func, hitTest); - var delayedEvents = this.delayedEvents; - if (!delayedEvents.length) { - return hit; - } - // Reset the propagation hint, because we start deeper in the tree again. - interactionEvent.stopPropagationHint = false; - var delayedLen = delayedEvents.length; - this.delayedEvents = []; - for (var i = 0; i < delayedLen; i++) { - var _a = delayedEvents[i], displayObject_1 = _a.displayObject, eventString = _a.eventString, eventData = _a.eventData; - // When we reach the object we wanted to stop propagating at, - // set the propagation hint. - if (eventData.stopsPropagatingAt === displayObject_1) { - eventData.stopPropagationHint = true; - } - this.dispatchEvent(displayObject_1, eventString, eventData); - } - return hit; - }; - /** - * Is called when the pointer button is pressed down on the renderer element - * - * @private - * @param {PointerEvent} originalEvent - The DOM event of a pointer button being pressed down - */ - InteractionManager.prototype.onPointerDown = function (originalEvent) { - // if we support touch events, then only use those for touch events, not pointer events - if (this.supportsTouchEvents && originalEvent.pointerType === 'touch') - { return; } - var events = this.normalizeToPointerData(originalEvent); - /** - * No need to prevent default on natural pointer events, as there are no side effects - * Normalized events, however, may have the double mousedown/touchstart issue on the native android browser, - * so still need to be prevented. - */ - // Guaranteed that there will be at least one event in events, and all events must have the same pointer type - if (this.autoPreventDefault && events[0].isNormalized) { - var cancelable = originalEvent.cancelable || !('cancelable' in originalEvent); - if (cancelable) { - originalEvent.preventDefault(); - } - } - var eventLen = events.length; - for (var i = 0; i < eventLen; i++) { - var event = events[i]; - var interactionData = this.getInteractionDataForPointerId(event); - var interactionEvent = this.configureInteractionEventForDOMEvent(this.eventData, event, interactionData); - interactionEvent.data.originalEvent = originalEvent; - this.processInteractive(interactionEvent, this.lastObjectRendered, this.processPointerDown, true); - this.emit('pointerdown', interactionEvent); - if (event.pointerType === 'touch') { - this.emit('touchstart', interactionEvent); - } - // emit a mouse event for "pen" pointers, the way a browser would emit a fallback event - else if (event.pointerType === 'mouse' || event.pointerType === 'pen') { - var isRightButton = event.button === 2; - this.emit(isRightButton ? 'rightdown' : 'mousedown', this.eventData); - } - } - }; - /** - * Processes the result of the pointer down check and dispatches the event if need be - * - * @private - * @param {PIXI.InteractionEvent} interactionEvent - The interaction event wrapping the DOM event - * @param {PIXI.Container|PIXI.Sprite|PIXI.TilingSprite} displayObject - The display object that was tested - * @param {boolean} hit - the result of the hit test on the display object - */ - InteractionManager.prototype.processPointerDown = function (interactionEvent, displayObject, hit) { - var data = interactionEvent.data; - var id = interactionEvent.data.identifier; - if (hit) { - if (!displayObject.trackedPointers[id]) { - displayObject.trackedPointers[id] = new InteractionTrackingData(id); - } - this.dispatchEvent(displayObject, 'pointerdown', interactionEvent); - if (data.pointerType === 'touch') { - this.dispatchEvent(displayObject, 'touchstart', interactionEvent); - } - else if (data.pointerType === 'mouse' || data.pointerType === 'pen') { - var isRightButton = data.button === 2; - if (isRightButton) { - displayObject.trackedPointers[id].rightDown = true; - } - else { - displayObject.trackedPointers[id].leftDown = true; - } - this.dispatchEvent(displayObject, isRightButton ? 'rightdown' : 'mousedown', interactionEvent); - } - } - }; - /** - * Is called when the pointer button is released on the renderer element - * - * @private - * @param {PointerEvent} originalEvent - The DOM event of a pointer button being released - * @param {boolean} cancelled - true if the pointer is cancelled - * @param {Function} func - Function passed to {@link processInteractive} - */ - InteractionManager.prototype.onPointerComplete = function (originalEvent, cancelled, func) { - var events = this.normalizeToPointerData(originalEvent); - var eventLen = events.length; - // if the event wasn't targeting our canvas, then consider it to be pointerupoutside - // in all cases (unless it was a pointercancel) - var eventAppend = originalEvent.target !== this.interactionDOMElement ? 'outside' : ''; - for (var i = 0; i < eventLen; i++) { - var event = events[i]; - var interactionData = this.getInteractionDataForPointerId(event); - var interactionEvent = this.configureInteractionEventForDOMEvent(this.eventData, event, interactionData); - interactionEvent.data.originalEvent = originalEvent; - // perform hit testing for events targeting our canvas or cancel events - this.processInteractive(interactionEvent, this.lastObjectRendered, func, cancelled || !eventAppend); - this.emit(cancelled ? 'pointercancel' : "pointerup" + eventAppend, interactionEvent); - if (event.pointerType === 'mouse' || event.pointerType === 'pen') { - var isRightButton = event.button === 2; - this.emit(isRightButton ? "rightup" + eventAppend : "mouseup" + eventAppend, interactionEvent); - } - else if (event.pointerType === 'touch') { - this.emit(cancelled ? 'touchcancel' : "touchend" + eventAppend, interactionEvent); - this.releaseInteractionDataForPointerId(event.pointerId); - } - } - }; - /** - * Is called when the pointer button is cancelled - * - * @private - * @param {PointerEvent} event - The DOM event of a pointer button being released - */ - InteractionManager.prototype.onPointerCancel = function (event) { - // if we support touch events, then only use those for touch events, not pointer events - if (this.supportsTouchEvents && event.pointerType === 'touch') - { return; } - this.onPointerComplete(event, true, this.processPointerCancel); - }; - /** - * Processes the result of the pointer cancel check and dispatches the event if need be - * - * @private - * @param {PIXI.InteractionEvent} interactionEvent - The interaction event wrapping the DOM event - * @param {PIXI.Container|PIXI.Sprite|PIXI.TilingSprite} displayObject - The display object that was tested - */ - InteractionManager.prototype.processPointerCancel = function (interactionEvent, displayObject) { - var data = interactionEvent.data; - var id = interactionEvent.data.identifier; - if (displayObject.trackedPointers[id] !== undefined) { - delete displayObject.trackedPointers[id]; - this.dispatchEvent(displayObject, 'pointercancel', interactionEvent); - if (data.pointerType === 'touch') { - this.dispatchEvent(displayObject, 'touchcancel', interactionEvent); - } - } - }; - /** - * Is called when the pointer button is released on the renderer element - * - * @private - * @param {PointerEvent} event - The DOM event of a pointer button being released - */ - InteractionManager.prototype.onPointerUp = function (event) { - // if we support touch events, then only use those for touch events, not pointer events - if (this.supportsTouchEvents && event.pointerType === 'touch') - { return; } - this.onPointerComplete(event, false, this.processPointerUp); - }; - /** - * Processes the result of the pointer up check and dispatches the event if need be - * - * @private - * @param {PIXI.InteractionEvent} interactionEvent - The interaction event wrapping the DOM event - * @param {PIXI.Container|PIXI.Sprite|PIXI.TilingSprite} displayObject - The display object that was tested - * @param {boolean} hit - the result of the hit test on the display object - */ - InteractionManager.prototype.processPointerUp = function (interactionEvent, displayObject, hit) { - var data = interactionEvent.data; - var id = interactionEvent.data.identifier; - var trackingData = displayObject.trackedPointers[id]; - var isTouch = data.pointerType === 'touch'; - var isMouse = (data.pointerType === 'mouse' || data.pointerType === 'pen'); - // need to track mouse down status in the mouse block so that we can emit - // event in a later block - var isMouseTap = false; - // Mouse only - if (isMouse) { - var isRightButton = data.button === 2; - var flags = InteractionTrackingData.FLAGS; - var test = isRightButton ? flags.RIGHT_DOWN : flags.LEFT_DOWN; - var isDown = trackingData !== undefined && (trackingData.flags & test); - if (hit) { - this.dispatchEvent(displayObject, isRightButton ? 'rightup' : 'mouseup', interactionEvent); - if (isDown) { - this.dispatchEvent(displayObject, isRightButton ? 'rightclick' : 'click', interactionEvent); - // because we can confirm that the mousedown happened on this object, flag for later emit of pointertap - isMouseTap = true; - } - } - else if (isDown) { - this.dispatchEvent(displayObject, isRightButton ? 'rightupoutside' : 'mouseupoutside', interactionEvent); - } - // update the down state of the tracking data - if (trackingData) { - if (isRightButton) { - trackingData.rightDown = false; - } - else { - trackingData.leftDown = false; - } - } - } - // Pointers and Touches, and Mouse - if (hit) { - this.dispatchEvent(displayObject, 'pointerup', interactionEvent); - if (isTouch) - { this.dispatchEvent(displayObject, 'touchend', interactionEvent); } - if (trackingData) { - // emit pointertap if not a mouse, or if the mouse block decided it was a tap - if (!isMouse || isMouseTap) { - this.dispatchEvent(displayObject, 'pointertap', interactionEvent); - } - if (isTouch) { - this.dispatchEvent(displayObject, 'tap', interactionEvent); - // touches are no longer over (if they ever were) when we get the touchend - // so we should ensure that we don't keep pretending that they are - trackingData.over = false; - } - } - } - else if (trackingData) { - this.dispatchEvent(displayObject, 'pointerupoutside', interactionEvent); - if (isTouch) - { this.dispatchEvent(displayObject, 'touchendoutside', interactionEvent); } - } - // Only remove the tracking data if there is no over/down state still associated with it - if (trackingData && trackingData.none) { - delete displayObject.trackedPointers[id]; - } - }; - /** - * Is called when the pointer moves across the renderer element - * - * @private - * @param {PointerEvent} originalEvent - The DOM event of a pointer moving - */ - InteractionManager.prototype.onPointerMove = function (originalEvent) { - // if we support touch events, then only use those for touch events, not pointer events - if (this.supportsTouchEvents && originalEvent.pointerType === 'touch') - { return; } - var events = this.normalizeToPointerData(originalEvent); - if (events[0].pointerType === 'mouse' || events[0].pointerType === 'pen') { - this._didMove = true; - this.cursor = null; - } - var eventLen = events.length; - for (var i = 0; i < eventLen; i++) { - var event = events[i]; - var interactionData = this.getInteractionDataForPointerId(event); - var interactionEvent = this.configureInteractionEventForDOMEvent(this.eventData, event, interactionData); - interactionEvent.data.originalEvent = originalEvent; - this.processInteractive(interactionEvent, this.lastObjectRendered, this.processPointerMove, true); - this.emit('pointermove', interactionEvent); - if (event.pointerType === 'touch') - { this.emit('touchmove', interactionEvent); } - if (event.pointerType === 'mouse' || event.pointerType === 'pen') - { this.emit('mousemove', interactionEvent); } - } - if (events[0].pointerType === 'mouse') { - this.setCursorMode(this.cursor); - // TODO BUG for parents interactive object (border order issue) - } - }; - /** - * Processes the result of the pointer move check and dispatches the event if need be - * - * @private - * @param {PIXI.InteractionEvent} interactionEvent - The interaction event wrapping the DOM event - * @param {PIXI.Container|PIXI.Sprite|PIXI.TilingSprite} displayObject - The display object that was tested - * @param {boolean} hit - the result of the hit test on the display object - */ - InteractionManager.prototype.processPointerMove = function (interactionEvent, displayObject, hit) { - var data = interactionEvent.data; - var isTouch = data.pointerType === 'touch'; - var isMouse = (data.pointerType === 'mouse' || data.pointerType === 'pen'); - if (isMouse) { - this.processPointerOverOut(interactionEvent, displayObject, hit); - } - if (!this.moveWhenInside || hit) { - this.dispatchEvent(displayObject, 'pointermove', interactionEvent); - if (isTouch) - { this.dispatchEvent(displayObject, 'touchmove', interactionEvent); } - if (isMouse) - { this.dispatchEvent(displayObject, 'mousemove', interactionEvent); } - } - }; - /** - * Is called when the pointer is moved out of the renderer element - * - * @private - * @param {PointerEvent} originalEvent - The DOM event of a pointer being moved out - */ - InteractionManager.prototype.onPointerOut = function (originalEvent) { - // if we support touch events, then only use those for touch events, not pointer events - if (this.supportsTouchEvents && originalEvent.pointerType === 'touch') - { return; } - var events = this.normalizeToPointerData(originalEvent); - // Only mouse and pointer can call onPointerOut, so events will always be length 1 - var event = events[0]; - if (event.pointerType === 'mouse') { - this.mouseOverRenderer = false; - this.setCursorMode(null); - } - var interactionData = this.getInteractionDataForPointerId(event); - var interactionEvent = this.configureInteractionEventForDOMEvent(this.eventData, event, interactionData); - interactionEvent.data.originalEvent = event; - this.processInteractive(interactionEvent, this.lastObjectRendered, this.processPointerOverOut, false); - this.emit('pointerout', interactionEvent); - if (event.pointerType === 'mouse' || event.pointerType === 'pen') { - this.emit('mouseout', interactionEvent); - } - else { - // we can get touchleave events after touchend, so we want to make sure we don't - // introduce memory leaks - this.releaseInteractionDataForPointerId(interactionData.identifier); - } - }; - /** - * Processes the result of the pointer over/out check and dispatches the event if need be - * - * @private - * @param {PIXI.InteractionEvent} interactionEvent - The interaction event wrapping the DOM event - * @param {PIXI.Container|PIXI.Sprite|PIXI.TilingSprite} displayObject - The display object that was tested - * @param {boolean} hit - the result of the hit test on the display object - */ - InteractionManager.prototype.processPointerOverOut = function (interactionEvent, displayObject, hit) { - var data = interactionEvent.data; - var id = interactionEvent.data.identifier; - var isMouse = (data.pointerType === 'mouse' || data.pointerType === 'pen'); - var trackingData = displayObject.trackedPointers[id]; - // if we just moused over the display object, then we need to track that state - if (hit && !trackingData) { - trackingData = displayObject.trackedPointers[id] = new InteractionTrackingData(id); - } - if (trackingData === undefined) - { return; } - if (hit && this.mouseOverRenderer) { - if (!trackingData.over) { - trackingData.over = true; - this.delayDispatchEvent(displayObject, 'pointerover', interactionEvent); - if (isMouse) { - this.delayDispatchEvent(displayObject, 'mouseover', interactionEvent); - } - } - // only change the cursor if it has not already been changed (by something deeper in the - // display tree) - if (isMouse && this.cursor === null) { - this.cursor = displayObject.cursor; - } - } - else if (trackingData.over) { - trackingData.over = false; - this.dispatchEvent(displayObject, 'pointerout', this.eventData); - if (isMouse) { - this.dispatchEvent(displayObject, 'mouseout', interactionEvent); - } - // if there is no mouse down information for the pointer, then it is safe to delete - if (trackingData.none) { - delete displayObject.trackedPointers[id]; - } - } - }; - /** - * Is called when the pointer is moved into the renderer element - * - * @private - * @param {PointerEvent} originalEvent - The DOM event of a pointer button being moved into the renderer view - */ - InteractionManager.prototype.onPointerOver = function (originalEvent) { - var events = this.normalizeToPointerData(originalEvent); - // Only mouse and pointer can call onPointerOver, so events will always be length 1 - var event = events[0]; - var interactionData = this.getInteractionDataForPointerId(event); - var interactionEvent = this.configureInteractionEventForDOMEvent(this.eventData, event, interactionData); - interactionEvent.data.originalEvent = event; - if (event.pointerType === 'mouse') { - this.mouseOverRenderer = true; - } - this.emit('pointerover', interactionEvent); - if (event.pointerType === 'mouse' || event.pointerType === 'pen') { - this.emit('mouseover', interactionEvent); - } - }; - /** - * Get InteractionData for a given pointerId. Store that data as well - * - * @private - * @param {PointerEvent} event - Normalized pointer event, output from normalizeToPointerData - * @return {PIXI.InteractionData} - Interaction data for the given pointer identifier - */ - InteractionManager.prototype.getInteractionDataForPointerId = function (event) { - var pointerId = event.pointerId; - var interactionData; - if (pointerId === MOUSE_POINTER_ID || event.pointerType === 'mouse') { - interactionData = this.mouse; - } - else if (this.activeInteractionData[pointerId]) { - interactionData = this.activeInteractionData[pointerId]; - } - else { - interactionData = this.interactionDataPool.pop() || new InteractionData(); - interactionData.identifier = pointerId; - this.activeInteractionData[pointerId] = interactionData; - } - // copy properties from the event, so that we can make sure that touch/pointer specific - // data is available - interactionData.copyEvent(event); - return interactionData; - }; - /** - * Return unused InteractionData to the pool, for a given pointerId - * - * @private - * @param {number} pointerId - Identifier from a pointer event - */ - InteractionManager.prototype.releaseInteractionDataForPointerId = function (pointerId) { - var interactionData = this.activeInteractionData[pointerId]; - if (interactionData) { - delete this.activeInteractionData[pointerId]; - interactionData.reset(); - this.interactionDataPool.push(interactionData); - } - }; - /** - * Configure an InteractionEvent to wrap a DOM PointerEvent and InteractionData - * - * @private - * @param {PIXI.InteractionEvent} interactionEvent - The event to be configured - * @param {PointerEvent} pointerEvent - The DOM event that will be paired with the InteractionEvent - * @param {PIXI.InteractionData} interactionData - The InteractionData that will be paired - * with the InteractionEvent - * @return {PIXI.InteractionEvent} the interaction event that was passed in - */ - InteractionManager.prototype.configureInteractionEventForDOMEvent = function (interactionEvent, pointerEvent, interactionData) { - interactionEvent.data = interactionData; - this.mapPositionToPoint(interactionData.global, pointerEvent.clientX, pointerEvent.clientY); - // Not really sure why this is happening, but it's how a previous version handled things - if (pointerEvent.pointerType === 'touch') { - pointerEvent.globalX = interactionData.global.x; - pointerEvent.globalY = interactionData.global.y; - } - interactionData.originalEvent = pointerEvent; - interactionEvent.reset(); - return interactionEvent; - }; - /** - * Ensures that the original event object contains all data that a regular pointer event would have - * - * @private - * @param {TouchEvent|MouseEvent|PointerEvent} event - The original event data from a touch or mouse event - * @return {PointerEvent[]} An array containing a single normalized pointer event, in the case of a pointer - * or mouse event, or a multiple normalized pointer events if there are multiple changed touches - */ - InteractionManager.prototype.normalizeToPointerData = function (event) { - var normalizedEvents = []; - if (this.supportsTouchEvents && event instanceof TouchEvent) { - for (var i = 0, li = event.changedTouches.length; i < li; i++) { - var touch = event.changedTouches[i]; - if (typeof touch.button === 'undefined') - { touch.button = event.touches.length ? 1 : 0; } - if (typeof touch.buttons === 'undefined') - { touch.buttons = event.touches.length ? 1 : 0; } - if (typeof touch.isPrimary === 'undefined') { - touch.isPrimary = event.touches.length === 1 && event.type === 'touchstart'; - } - if (typeof touch.width === 'undefined') - { touch.width = touch.radiusX || 1; } - if (typeof touch.height === 'undefined') - { touch.height = touch.radiusY || 1; } - if (typeof touch.tiltX === 'undefined') - { touch.tiltX = 0; } - if (typeof touch.tiltY === 'undefined') - { touch.tiltY = 0; } - if (typeof touch.pointerType === 'undefined') - { touch.pointerType = 'touch'; } - if (typeof touch.pointerId === 'undefined') - { touch.pointerId = touch.identifier || 0; } - if (typeof touch.pressure === 'undefined') - { touch.pressure = touch.force || 0.5; } - if (typeof touch.twist === 'undefined') - { touch.twist = 0; } - if (typeof touch.tangentialPressure === 'undefined') - { touch.tangentialPressure = 0; } - // TODO: Remove these, as layerX/Y is not a standard, is deprecated, has uneven - // support, and the fill ins are not quite the same - // offsetX/Y might be okay, but is not the same as clientX/Y when the canvas's top - // left is not 0,0 on the page - if (typeof touch.layerX === 'undefined') - { touch.layerX = touch.offsetX = touch.clientX; } - if (typeof touch.layerY === 'undefined') - { touch.layerY = touch.offsetY = touch.clientY; } - // mark the touch as normalized, just so that we know we did it - touch.isNormalized = true; - normalizedEvents.push(touch); - } - } - // apparently PointerEvent subclasses MouseEvent, so yay - else if (event instanceof MouseEvent && (!this.supportsPointerEvents || !(event instanceof window.PointerEvent))) { - var tempEvent = event; - if (typeof tempEvent.isPrimary === 'undefined') - { tempEvent.isPrimary = true; } - if (typeof tempEvent.width === 'undefined') - { tempEvent.width = 1; } - if (typeof tempEvent.height === 'undefined') - { tempEvent.height = 1; } - if (typeof tempEvent.tiltX === 'undefined') - { tempEvent.tiltX = 0; } - if (typeof tempEvent.tiltY === 'undefined') - { tempEvent.tiltY = 0; } - if (typeof tempEvent.pointerType === 'undefined') - { tempEvent.pointerType = 'mouse'; } - if (typeof tempEvent.pointerId === 'undefined') - { tempEvent.pointerId = MOUSE_POINTER_ID; } - if (typeof tempEvent.pressure === 'undefined') - { tempEvent.pressure = 0.5; } - if (typeof tempEvent.twist === 'undefined') - { tempEvent.twist = 0; } - if (typeof tempEvent.tangentialPressure === 'undefined') - { tempEvent.tangentialPressure = 0; } - // mark the mouse event as normalized, just so that we know we did it - tempEvent.isNormalized = true; - normalizedEvents.push(tempEvent); - } - else { - normalizedEvents.push(event); - } - return normalizedEvents; - }; - /** - * Destroys the interaction manager - * - */ - InteractionManager.prototype.destroy = function () { - this.removeEvents(); - this.removeTickerListener(); - this.removeAllListeners(); - this.renderer = null; - this.mouse = null; - this.eventData = null; - this.interactionDOMElement = null; - this.onPointerDown = null; - this.processPointerDown = null; - this.onPointerUp = null; - this.processPointerUp = null; - this.onPointerCancel = null; - this.processPointerCancel = null; - this.onPointerMove = null; - this.processPointerMove = null; - this.onPointerOut = null; - this.processPointerOverOut = null; - this.onPointerOver = null; - this.search = null; - }; - return InteractionManager; - }(eventemitter3)); - - /*! - * @pixi/runner - v5.3.3 - * Compiled Tue, 04 Aug 2020 16:23:09 UTC - * - * @pixi/runner is licensed under the MIT License. - * http://www.opensource.org/licenses/mit-license - */ - /** - * A Runner is a highly performant and simple alternative to signals. Best used in situations - * where events are dispatched to many objects at high frequency (say every frame!) - * - * - * like a signal.. - * ``` - * import { Runner } from '@pixi/runner'; - * - * const myObject = { - * loaded: new Runner('loaded') - * } - * - * const listener = { - * loaded: function(){ - * // thin - * } - * } - * - * myObject.update.add(listener); - * - * myObject.loaded.emit(); - * ``` - * - * Or for handling calling the same function on many items - * ``` - * import { Runner } from '@pixi/runner'; - * - * const myGame = { - * update: new Runner('update') - * } - * - * const gameObject = { - * update: function(time){ - * // update my gamey state - * } - * } - * - * myGame.update.add(gameObject1); - * - * myGame.update.emit(time); - * ``` - * @class - * @memberof PIXI - */ - var Runner = /** @class */ (function () { - /** - * @param {string} name - the function name that will be executed on the listeners added to this Runner. - */ - function Runner(name) { - this.items = []; - this._name = name; - this._aliasCount = 0; - } - /** - * Dispatch/Broadcast Runner to all listeners added to the queue. - * @param {...any} params - optional parameters to pass to each listener - * @return {PIXI.Runner} - */ - Runner.prototype.emit = function (a0, a1, a2, a3, a4, a5, a6, a7) { - if (arguments.length > 8) { - throw new Error('max arguments reached'); - } - var _a = this, name = _a.name, items = _a.items; - this._aliasCount++; - for (var i = 0, len = items.length; i < len; i++) { - items[i][name](a0, a1, a2, a3, a4, a5, a6, a7); - } - if (items === this.items) { - this._aliasCount--; - } - return this; - }; - Runner.prototype.ensureNonAliasedItems = function () { - if (this._aliasCount > 0 && this.items.length > 1) { - this._aliasCount = 0; - this.items = this.items.slice(0); - } - }; - /** - * Add a listener to the Runner - * - * Runners do not need to have scope or functions passed to them. - * All that is required is to pass the listening object and ensure that it has contains a function that has the same name - * as the name provided to the Runner when it was created. - * - * Eg A listener passed to this Runner will require a 'complete' function. - * - * ``` - * import { Runner } from '@pixi/runner'; - * - * const complete = new Runner('complete'); - * ``` - * - * The scope used will be the object itself. - * - * @param {any} item - The object that will be listening. - * @return {PIXI.Runner} - */ - Runner.prototype.add = function (item) { - if (item[this._name]) { - this.ensureNonAliasedItems(); - this.remove(item); - this.items.push(item); - } - return this; - }; - /** - * Remove a single listener from the dispatch queue. - * @param {any} item - The listenr that you would like to remove. - * @return {PIXI.Runner} - */ - Runner.prototype.remove = function (item) { - var index = this.items.indexOf(item); - if (index !== -1) { - this.ensureNonAliasedItems(); - this.items.splice(index, 1); - } - return this; - }; - /** - * Check to see if the listener is already in the Runner - * @param {any} item - The listener that you would like to check. - */ - Runner.prototype.contains = function (item) { - return this.items.indexOf(item) !== -1; - }; - /** - * Remove all listeners from the Runner - * @return {PIXI.Runner} - */ - Runner.prototype.removeAll = function () { - this.ensureNonAliasedItems(); - this.items.length = 0; - return this; - }; - /** - * Remove all references, don't use after this. - */ - Runner.prototype.destroy = function () { - this.removeAll(); - this.items = null; - this._name = null; - }; - Object.defineProperty(Runner.prototype, "empty", { - /** - * `true` if there are no this Runner contains no listeners - * - * @member {boolean} - * @readonly - */ - get: function () { - return this.items.length === 0; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(Runner.prototype, "name", { - /** - * The name of the runner. - * - * @member {string} - * @readonly - */ - get: function () { - return this._name; - }, - enumerable: false, - configurable: true - }); - return Runner; - }()); - Object.defineProperties(Runner.prototype, { - /** - * Alias for `emit` - * @memberof PIXI.Runner# - * @method dispatch - * @see PIXI.Runner#emit - */ - dispatch: { value: Runner.prototype.emit }, - /** - * Alias for `emit` - * @memberof PIXI.Runner# - * @method run - * @see PIXI.Runner#emit - */ - run: { value: Runner.prototype.emit }, - }); - - /*! - * @pixi/core - v5.3.3 - * Compiled Tue, 04 Aug 2020 16:23:09 UTC - * - * @pixi/core is licensed under the MIT License. - * http://www.opensource.org/licenses/mit-license - */ - - /** - * The maximum support for using WebGL. If a device does not - * support WebGL version, for instance WebGL 2, it will still - * attempt to fallback support to WebGL 1. If you want to - * explicitly remove feature support to target a more stable - * baseline, prefer a lower environment. - * - * Due to {@link https://bugs.chromium.org/p/chromium/issues/detail?id=934823|bug in chromium} - * we disable webgl2 by default for all non-apple mobile devices. - * - * @static - * @name PREFER_ENV - * @memberof PIXI.settings - * @type {number} - * @default PIXI.ENV.WEBGL2 - */ - settings.PREFER_ENV = isMobile$1.any ? exports.ENV.WEBGL : exports.ENV.WEBGL2; - /** - * If set to `true`, *only* Textures and BaseTexture objects stored - * in the caches ({@link PIXI.utils.TextureCache TextureCache} and - * {@link PIXI.utils.BaseTextureCache BaseTextureCache}) can be - * used when calling {@link PIXI.Texture.from Texture.from} or - * {@link PIXI.BaseTexture.from BaseTexture.from}. - * Otherwise, these `from` calls throw an exception. Using this property - * can be useful if you want to enforce preloading all assets with - * {@link PIXI.Loader Loader}. - * - * @static - * @name STRICT_TEXTURE_CACHE - * @memberof PIXI.settings - * @type {boolean} - * @default false - */ - settings.STRICT_TEXTURE_CACHE = false; - - /** - * Collection of installed resource types, class must extend {@link PIXI.resources.Resource}. - * @example - * class CustomResource extends PIXI.resources.Resource { - * // MUST have source, options constructor signature - * // for auto-detected resources to be created. - * constructor(source, options) { - * super(); - * } - * upload(renderer, baseTexture, glTexture) { - * // upload with GL - * return true; - * } - * // used to auto-detect resource - * static test(source, extension) { - * return extension === 'xyz'|| source instanceof SomeClass; - * } - * } - * // Install the new resource type - * PIXI.resources.INSTALLED.push(CustomResource); - * - * @name PIXI.resources.INSTALLED - * @type {Array<*>} - * @static - * @readonly - */ - var INSTALLED = []; - /** - * Create a resource element from a single source element. This - * auto-detects which type of resource to create. All resources that - * are auto-detectable must have a static `test` method and a constructor - * with the arguments `(source, options?)`. Currently, the supported - * resources for auto-detection include: - * - {@link PIXI.resources.ImageResource} - * - {@link PIXI.resources.CanvasResource} - * - {@link PIXI.resources.VideoResource} - * - {@link PIXI.resources.SVGResource} - * - {@link PIXI.resources.BufferResource} - * @static - * @function PIXI.resources.autoDetectResource - * @param {string|*} source - Resource source, this can be the URL to the resource, - * a typed-array (for BufferResource), HTMLVideoElement, SVG data-uri - * or any other resource that can be auto-detected. If not resource is - * detected, it's assumed to be an ImageResource. - * @param {object} [options] - Pass-through options to use for Resource - * @param {number} [options.width] - Width of BufferResource or SVG rasterization - * @param {number} [options.height] - Height of BufferResource or SVG rasterization - * @param {boolean} [options.autoLoad=true] - Image, SVG and Video flag to start loading - * @param {number} [options.scale=1] - SVG source scale. Overridden by width, height - * @param {boolean} [options.createBitmap=PIXI.settings.CREATE_IMAGE_BITMAP] - Image option to create Bitmap object - * @param {boolean} [options.crossorigin=true] - Image and Video option to set crossOrigin - * @param {boolean} [options.autoPlay=true] - Video option to start playing video immediately - * @param {number} [options.updateFPS=0] - Video option to update how many times a second the - * texture should be updated from the video. Leave at 0 to update at every render - * @return {PIXI.resources.Resource} The created resource. - */ - function autoDetectResource(source, options) { - if (!source) { - return null; - } - var extension = ''; - if (typeof source === 'string') { - // search for file extension: period, 3-4 chars, then ?, # or EOL - var result = (/\.(\w{3,4})(?:$|\?|#)/i).exec(source); - if (result) { - extension = result[1].toLowerCase(); - } - } - for (var i = INSTALLED.length - 1; i >= 0; --i) { - var ResourcePlugin = INSTALLED[i]; - if (ResourcePlugin.test && ResourcePlugin.test(source, extension)) { - return new ResourcePlugin(source, options); - } - } - throw new Error('Unrecognized source type to auto-detect Resource'); - } - - /*! ***************************************************************************** - Copyright (c) Microsoft Corporation. All rights reserved. - Licensed under the Apache License, Version 2.0 (the "License"); you may not use - this file except in compliance with the License. You may obtain a copy of the - License at http://www.apache.org/licenses/LICENSE-2.0 + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments$1[i]; + for (var p in s) { if (Object.prototype.hasOwnProperty.call(s, p)) { t[p] = s[p]; } } + } + return t; + }; + return __assign$1.apply(this, arguments); + }; + + /** + * Collection of valid extension types. + * @memberof PIXI + * @property {string} Application - Application plugins + * @property {string} RendererPlugin - Plugins for Renderer + * @property {string} CanvasRendererPlugin - Plugins for CanvasRenderer + * @property {string} Loader - Plugins to use with Loader + * @property {string} LoadParser - Parsers for Assets loader. + * @property {string} ResolveParser - Parsers for Assets resolvers. + * @property {string} CacheParser - Parsers for Assets cache. + */ + exports.ExtensionType = void 0; + (function (ExtensionType) { + ExtensionType["Application"] = "application"; + ExtensionType["RendererPlugin"] = "renderer-webgl-plugin"; + ExtensionType["CanvasRendererPlugin"] = "renderer-canvas-plugin"; + ExtensionType["Loader"] = "loader"; + ExtensionType["LoadParser"] = "load-parser"; + ExtensionType["ResolveParser"] = "resolve-parser"; + ExtensionType["CacheParser"] = "cache-parser"; + ExtensionType["DetectionParser"] = "detection-parser"; + })(exports.ExtensionType || (exports.ExtensionType = {})); + /** + * Convert input into extension format data. + * @ignore + */ + var normalizeExtension = function (ext) { + // Class/Object submission, use extension object + if (typeof ext === 'function' || (typeof ext === 'object' && ext.extension)) { + if (!ext.extension) { + throw new Error('Extension class must have an extension object'); + } + var metadata = (typeof ext.extension !== 'object') + ? { type: ext.extension } + : ext.extension; + ext = __assign$1(__assign$1({}, metadata), { ref: ext }); + } + if (typeof ext === 'object') { + ext = __assign$1({}, ext); + } + else { + throw new Error('Invalid extension type'); + } + if (typeof ext.type === 'string') { + ext.type = [ext.type]; + } + return ext; + }; + /** + * Global registration of all PixiJS extensions. One-stop-shop for extensibility. + * @memberof PIXI + * @namespace extensions + */ + var extensions = { + /** @ignore */ + _addHandlers: null, + /** @ignore */ + _removeHandlers: null, + /** @ignore */ + _queue: {}, + /** + * Remove extensions from PixiJS. + * @param extensions - Extensions to be removed. + * @returns {PIXI.extensions} For chaining. + */ + remove: function () { + var arguments$1 = arguments; + + var _this = this; + var extensions = []; + for (var _i = 0; _i < arguments.length; _i++) { + extensions[_i] = arguments$1[_i]; + } + extensions.map(normalizeExtension).forEach(function (ext) { + ext.type.forEach(function (type) { var _a, _b; return (_b = (_a = _this._removeHandlers)[type]) === null || _b === void 0 ? void 0 : _b.call(_a, ext); }); + }); + return this; + }, + /** + * Register new extensions with PixiJS. + * @param extensions - The spread of extensions to add to PixiJS. + * @returns {PIXI.extensions} For chaining. + */ + add: function () { + var arguments$1 = arguments; + + var _this = this; + var extensions = []; + for (var _i = 0; _i < arguments.length; _i++) { + extensions[_i] = arguments$1[_i]; + } + // Handle any extensions either passed as class w/ data or as data + extensions.map(normalizeExtension).forEach(function (ext) { + ext.type.forEach(function (type) { + var handlers = _this._addHandlers; + var queue = _this._queue; + if (!handlers[type]) { + queue[type] = queue[type] || []; + queue[type].push(ext); + } + else { + handlers[type](ext); + } + }); + }); + return this; + }, + /** + * Internal method to handle extensions by name. + * @param type - The extension type. + * @param onAdd - Function for handling when extensions are added/registered passes {@link PIXI.ExtensionFormat}. + * @param onRemove - Function for handling when extensions are removed/unregistered passes {@link PIXI.ExtensionFormat}. + * @returns {PIXI.extensions} For chaining. + */ + handle: function (type, onAdd, onRemove) { + var addHandlers = this._addHandlers = this._addHandlers || {}; + var removeHandlers = this._removeHandlers = this._removeHandlers || {}; + if (addHandlers[type] || removeHandlers[type]) { + throw new Error("Extension type " + type + " already has a handler"); + } + addHandlers[type] = onAdd; + removeHandlers[type] = onRemove; + // Process the queue + var queue = this._queue; + // Process any plugins that have been registered before the handler + if (queue[type]) { + queue[type].forEach(function (ext) { return onAdd(ext); }); + delete queue[type]; + } + return this; + }, + /** + * Handle a type, but using a map by `name` property. + * @param type - Type of extension to handle. + * @param map - The object map of named extensions. + * @returns {PIXI.extensions} For chaining. + */ + handleByMap: function (type, map) { + return this.handle(type, function (extension) { + map[extension.name] = extension.ref; + }, function (extension) { + delete map[extension.name]; + }); + }, + /** + * Handle a type, but using a list of extensions. + * @param type - Type of extension to handle. + * @param list - The list of extensions. + * @returns {PIXI.extensions} For chaining. + */ + handleByList: function (type, list) { + return this.handle(type, function (extension) { + var _a, _b; + list.push(extension.ref); + // TODO: remove me later, only added for @pixi/loaders + if (type === exports.ExtensionType.Loader) { + (_b = (_a = extension.ref).add) === null || _b === void 0 ? void 0 : _b.call(_a); + } + }, function (extension) { + var index = list.indexOf(extension.ref); + if (index !== -1) { + list.splice(index, 1); + } + }); + }, + }; + + /*! + * @pixi/runner - v6.5.3 + * Compiled Fri, 09 Sep 2022 13:55:20 UTC + * + * @pixi/runner is licensed under the MIT License. + * http://www.opensource.org/licenses/mit-license + */ + /** + * A Runner is a highly performant and simple alternative to signals. Best used in situations + * where events are dispatched to many objects at high frequency (say every frame!) + * + * + * like a signal.. + * ``` + * import { Runner } from '@pixi/runner'; + * + * const myObject = { + * loaded: new Runner('loaded') + * } + * + * const listener = { + * loaded: function(){ + * // thin + * } + * } + * + * myObject.loaded.add(listener); + * + * myObject.loaded.emit(); + * ``` + * + * Or for handling calling the same function on many items + * ``` + * import { Runner } from '@pixi/runner'; + * + * const myGame = { + * update: new Runner('update') + * } + * + * const gameObject = { + * update: function(time){ + * // update my gamey state + * } + * } + * + * myGame.update.add(gameObject); + * + * myGame.update.emit(time); + * ``` + * @memberof PIXI + */ + var Runner = /** @class */ (function () { + /** + * @param name - The function name that will be executed on the listeners added to this Runner. + */ + function Runner(name) { + this.items = []; + this._name = name; + this._aliasCount = 0; + } + /* eslint-disable jsdoc/require-param, jsdoc/check-param-names */ + /** + * Dispatch/Broadcast Runner to all listeners added to the queue. + * @param {...any} params - (optional) parameters to pass to each listener + */ + /* eslint-enable jsdoc/require-param, jsdoc/check-param-names */ + Runner.prototype.emit = function (a0, a1, a2, a3, a4, a5, a6, a7) { + if (arguments.length > 8) { + throw new Error('max arguments reached'); + } + var _a = this, name = _a.name, items = _a.items; + this._aliasCount++; + for (var i = 0, len = items.length; i < len; i++) { + items[i][name](a0, a1, a2, a3, a4, a5, a6, a7); + } + if (items === this.items) { + this._aliasCount--; + } + return this; + }; + Runner.prototype.ensureNonAliasedItems = function () { + if (this._aliasCount > 0 && this.items.length > 1) { + this._aliasCount = 0; + this.items = this.items.slice(0); + } + }; + /** + * Add a listener to the Runner + * + * Runners do not need to have scope or functions passed to them. + * All that is required is to pass the listening object and ensure that it has contains a function that has the same name + * as the name provided to the Runner when it was created. + * + * Eg A listener passed to this Runner will require a 'complete' function. + * + * ``` + * import { Runner } from '@pixi/runner'; + * + * const complete = new Runner('complete'); + * ``` + * + * The scope used will be the object itself. + * @param {any} item - The object that will be listening. + */ + Runner.prototype.add = function (item) { + if (item[this._name]) { + this.ensureNonAliasedItems(); + this.remove(item); + this.items.push(item); + } + return this; + }; + /** + * Remove a single listener from the dispatch queue. + * @param {any} item - The listener that you would like to remove. + */ + Runner.prototype.remove = function (item) { + var index = this.items.indexOf(item); + if (index !== -1) { + this.ensureNonAliasedItems(); + this.items.splice(index, 1); + } + return this; + }; + /** + * Check to see if the listener is already in the Runner + * @param {any} item - The listener that you would like to check. + */ + Runner.prototype.contains = function (item) { + return this.items.indexOf(item) !== -1; + }; + /** Remove all listeners from the Runner */ + Runner.prototype.removeAll = function () { + this.ensureNonAliasedItems(); + this.items.length = 0; + return this; + }; + /** Remove all references, don't use after this. */ + Runner.prototype.destroy = function () { + this.removeAll(); + this.items = null; + this._name = null; + }; + Object.defineProperty(Runner.prototype, "empty", { + /** + * `true` if there are no this Runner contains no listeners + * @readonly + */ + get: function () { + return this.items.length === 0; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(Runner.prototype, "name", { + /** + * The name of the runner. + * @readonly + */ + get: function () { + return this._name; + }, + enumerable: false, + configurable: true + }); + return Runner; + }()); + Object.defineProperties(Runner.prototype, { + /** + * Alias for `emit` + * @memberof PIXI.Runner# + * @method dispatch + * @see PIXI.Runner#emit + */ + dispatch: { value: Runner.prototype.emit }, + /** + * Alias for `emit` + * @memberof PIXI.Runner# + * @method run + * @see PIXI.Runner#emit + */ + run: { value: Runner.prototype.emit }, + }); + + /*! + * @pixi/ticker - v6.5.3 + * Compiled Fri, 09 Sep 2022 13:55:20 UTC + * + * @pixi/ticker is licensed under the MIT License. + * http://www.opensource.org/licenses/mit-license + */ + + /** + * Target frames per millisecond. + * @static + * @name TARGET_FPMS + * @memberof PIXI.settings + * @type {number} + * @default 0.06 + */ + settings$1.TARGET_FPMS = 0.06; + + /** + * Represents the update priorities used by internal PIXI classes when registered with + * the {@link PIXI.Ticker} object. Higher priority items are updated first and lower + * priority items, such as render, should go later. + * @static + * @constant + * @name UPDATE_PRIORITY + * @memberof PIXI + * @enum {number} + * @property {number} [INTERACTION=50] Highest priority, used for {@link PIXI.InteractionManager} + * @property {number} [HIGH=25] High priority updating, {@link PIXI.VideoBaseTexture} and {@link PIXI.AnimatedSprite} + * @property {number} [NORMAL=0] Default priority for ticker events, see {@link PIXI.Ticker#add}. + * @property {number} [LOW=-25] Low priority used for {@link PIXI.Application} rendering. + * @property {number} [UTILITY=-50] Lowest priority used for {@link PIXI.BasePrepare} utility. + */ + exports.UPDATE_PRIORITY = void 0; + (function (UPDATE_PRIORITY) { + UPDATE_PRIORITY[UPDATE_PRIORITY["INTERACTION"] = 50] = "INTERACTION"; + UPDATE_PRIORITY[UPDATE_PRIORITY["HIGH"] = 25] = "HIGH"; + UPDATE_PRIORITY[UPDATE_PRIORITY["NORMAL"] = 0] = "NORMAL"; + UPDATE_PRIORITY[UPDATE_PRIORITY["LOW"] = -25] = "LOW"; + UPDATE_PRIORITY[UPDATE_PRIORITY["UTILITY"] = -50] = "UTILITY"; + })(exports.UPDATE_PRIORITY || (exports.UPDATE_PRIORITY = {})); + + /** + * Internal class for handling the priority sorting of ticker handlers. + * @private + * @class + * @memberof PIXI + */ + var TickerListener = /** @class */ (function () { + /** + * Constructor + * @private + * @param fn - The listener function to be added for one update + * @param context - The listener context + * @param priority - The priority for emitting + * @param once - If the handler should fire once + */ + function TickerListener(fn, context, priority, once) { + if (context === void 0) { context = null; } + if (priority === void 0) { priority = 0; } + if (once === void 0) { once = false; } + /** The next item in chain. */ + this.next = null; + /** The previous item in chain. */ + this.previous = null; + /** `true` if this listener has been destroyed already. */ + this._destroyed = false; + this.fn = fn; + this.context = context; + this.priority = priority; + this.once = once; + } + /** + * Simple compare function to figure out if a function and context match. + * @private + * @param fn - The listener function to be added for one update + * @param context - The listener context + * @returns `true` if the listener match the arguments + */ + TickerListener.prototype.match = function (fn, context) { + if (context === void 0) { context = null; } + return this.fn === fn && this.context === context; + }; + /** + * Emit by calling the current function. + * @private + * @param deltaTime - time since the last emit. + * @returns Next ticker + */ + TickerListener.prototype.emit = function (deltaTime) { + if (this.fn) { + if (this.context) { + this.fn.call(this.context, deltaTime); + } + else { + this.fn(deltaTime); + } + } + var redirect = this.next; + if (this.once) { + this.destroy(true); + } + // Soft-destroying should remove + // the next reference + if (this._destroyed) { + this.next = null; + } + return redirect; + }; + /** + * Connect to the list. + * @private + * @param previous - Input node, previous listener + */ + TickerListener.prototype.connect = function (previous) { + this.previous = previous; + if (previous.next) { + previous.next.previous = this; + } + this.next = previous.next; + previous.next = this; + }; + /** + * Destroy and don't use after this. + * @private + * @param hard - `true` to remove the `next` reference, this + * is considered a hard destroy. Soft destroy maintains the next reference. + * @returns The listener to redirect while emitting or removing. + */ + TickerListener.prototype.destroy = function (hard) { + if (hard === void 0) { hard = false; } + this._destroyed = true; + this.fn = null; + this.context = null; + // Disconnect, hook up next and previous + if (this.previous) { + this.previous.next = this.next; + } + if (this.next) { + this.next.previous = this.previous; + } + // Redirect to the next item + var redirect = this.next; + // Remove references + this.next = hard ? null : redirect; + this.previous = null; + return redirect; + }; + return TickerListener; + }()); + + /** + * A Ticker class that runs an update loop that other objects listen to. + * + * This class is composed around listeners meant for execution on the next requested animation frame. + * Animation frames are requested only when necessary, e.g. When the ticker is started and the emitter has listeners. + * @class + * @memberof PIXI + */ + var Ticker = /** @class */ (function () { + function Ticker() { + var _this = this; + /** + * Whether or not this ticker should invoke the method + * {@link PIXI.Ticker#start} automatically + * when a listener is added. + */ + this.autoStart = false; + /** + * Scalar time value from last frame to this frame. + * This value is capped by setting {@link PIXI.Ticker#minFPS} + * and is scaled with {@link PIXI.Ticker#speed}. + * **Note:** The cap may be exceeded by scaling. + */ + this.deltaTime = 1; + /** + * The last time {@link PIXI.Ticker#update} was invoked. + * This value is also reset internally outside of invoking + * update, but only when a new animation frame is requested. + * If the platform supports DOMHighResTimeStamp, + * this value will have a precision of 1 µs. + */ + this.lastTime = -1; + /** + * Factor of current {@link PIXI.Ticker#deltaTime}. + * @example + * // Scales ticker.deltaTime to what would be + * // the equivalent of approximately 120 FPS + * ticker.speed = 2; + */ + this.speed = 1; + /** + * Whether or not this ticker has been started. + * `true` if {@link PIXI.Ticker#start} has been called. + * `false` if {@link PIXI.Ticker#stop} has been called. + * While `false`, this value may change to `true` in the + * event of {@link PIXI.Ticker#autoStart} being `true` + * and a listener is added. + */ + this.started = false; + /** Internal current frame request ID */ + this._requestId = null; + /** + * Internal value managed by minFPS property setter and getter. + * This is the maximum allowed milliseconds between updates. + */ + this._maxElapsedMS = 100; + /** + * Internal value managed by minFPS property setter and getter. + * This is the minimum allowed milliseconds between updates. + */ + this._minElapsedMS = 0; + /** If enabled, deleting is disabled.*/ + this._protected = false; + /** The last time keyframe was executed. Maintains a relatively fixed interval with the previous value. */ + this._lastFrame = -1; + this._head = new TickerListener(null, null, Infinity); + this.deltaMS = 1 / settings$1.TARGET_FPMS; + this.elapsedMS = 1 / settings$1.TARGET_FPMS; + this._tick = function (time) { + _this._requestId = null; + if (_this.started) { + // Invoke listeners now + _this.update(time); + // Listener side effects may have modified ticker state. + if (_this.started && _this._requestId === null && _this._head.next) { + _this._requestId = requestAnimationFrame(_this._tick); + } + } + }; + } + /** + * Conditionally requests a new animation frame. + * If a frame has not already been requested, and if the internal + * emitter has listeners, a new frame is requested. + * @private + */ + Ticker.prototype._requestIfNeeded = function () { + if (this._requestId === null && this._head.next) { + // ensure callbacks get correct delta + this.lastTime = performance.now(); + this._lastFrame = this.lastTime; + this._requestId = requestAnimationFrame(this._tick); + } + }; + /** + * Conditionally cancels a pending animation frame. + * @private + */ + Ticker.prototype._cancelIfNeeded = function () { + if (this._requestId !== null) { + cancelAnimationFrame(this._requestId); + this._requestId = null; + } + }; + /** + * Conditionally requests a new animation frame. + * If the ticker has been started it checks if a frame has not already + * been requested, and if the internal emitter has listeners. If these + * conditions are met, a new frame is requested. If the ticker has not + * been started, but autoStart is `true`, then the ticker starts now, + * and continues with the previous conditions to request a new frame. + * @private + */ + Ticker.prototype._startIfPossible = function () { + if (this.started) { + this._requestIfNeeded(); + } + else if (this.autoStart) { + this.start(); + } + }; + /** + * Register a handler for tick events. Calls continuously unless + * it is removed or the ticker is stopped. + * @param fn - The listener function to be added for updates + * @param context - The listener context + * @param {number} [priority=PIXI.UPDATE_PRIORITY.NORMAL] - The priority for emitting + * @returns This instance of a ticker + */ + Ticker.prototype.add = function (fn, context, priority) { + if (priority === void 0) { priority = exports.UPDATE_PRIORITY.NORMAL; } + return this._addListener(new TickerListener(fn, context, priority)); + }; + /** + * Add a handler for the tick event which is only execute once. + * @param fn - The listener function to be added for one update + * @param context - The listener context + * @param {number} [priority=PIXI.UPDATE_PRIORITY.NORMAL] - The priority for emitting + * @returns This instance of a ticker + */ + Ticker.prototype.addOnce = function (fn, context, priority) { + if (priority === void 0) { priority = exports.UPDATE_PRIORITY.NORMAL; } + return this._addListener(new TickerListener(fn, context, priority, true)); + }; + /** + * Internally adds the event handler so that it can be sorted by priority. + * Priority allows certain handler (user, AnimatedSprite, Interaction) to be run + * before the rendering. + * @private + * @param listener - Current listener being added. + * @returns This instance of a ticker + */ + Ticker.prototype._addListener = function (listener) { + // For attaching to head + var current = this._head.next; + var previous = this._head; + // Add the first item + if (!current) { + listener.connect(previous); + } + else { + // Go from highest to lowest priority + while (current) { + if (listener.priority > current.priority) { + listener.connect(previous); + break; + } + previous = current; + current = current.next; + } + // Not yet connected + if (!listener.previous) { + listener.connect(previous); + } + } + this._startIfPossible(); + return this; + }; + /** + * Removes any handlers matching the function and context parameters. + * If no handlers are left after removing, then it cancels the animation frame. + * @param fn - The listener function to be removed + * @param context - The listener context to be removed + * @returns This instance of a ticker + */ + Ticker.prototype.remove = function (fn, context) { + var listener = this._head.next; + while (listener) { + // We found a match, lets remove it + // no break to delete all possible matches + // incase a listener was added 2+ times + if (listener.match(fn, context)) { + listener = listener.destroy(); + } + else { + listener = listener.next; + } + } + if (!this._head.next) { + this._cancelIfNeeded(); + } + return this; + }; + Object.defineProperty(Ticker.prototype, "count", { + /** + * The number of listeners on this ticker, calculated by walking through linked list + * @readonly + * @member {number} + */ + get: function () { + if (!this._head) { + return 0; + } + var count = 0; + var current = this._head; + while ((current = current.next)) { + count++; + } + return count; + }, + enumerable: false, + configurable: true + }); + /** Starts the ticker. If the ticker has listeners a new animation frame is requested at this point. */ + Ticker.prototype.start = function () { + if (!this.started) { + this.started = true; + this._requestIfNeeded(); + } + }; + /** Stops the ticker. If the ticker has requested an animation frame it is canceled at this point. */ + Ticker.prototype.stop = function () { + if (this.started) { + this.started = false; + this._cancelIfNeeded(); + } + }; + /** Destroy the ticker and don't use after this. Calling this method removes all references to internal events. */ + Ticker.prototype.destroy = function () { + if (!this._protected) { + this.stop(); + var listener = this._head.next; + while (listener) { + listener = listener.destroy(true); + } + this._head.destroy(); + this._head = null; + } + }; + /** + * Triggers an update. An update entails setting the + * current {@link PIXI.Ticker#elapsedMS}, + * the current {@link PIXI.Ticker#deltaTime}, + * invoking all listeners with current deltaTime, + * and then finally setting {@link PIXI.Ticker#lastTime} + * with the value of currentTime that was provided. + * This method will be called automatically by animation + * frame callbacks if the ticker instance has been started + * and listeners are added. + * @param {number} [currentTime=performance.now()] - the current time of execution + */ + Ticker.prototype.update = function (currentTime) { + if (currentTime === void 0) { currentTime = performance.now(); } + var elapsedMS; + // If the difference in time is zero or negative, we ignore most of the work done here. + // If there is no valid difference, then should be no reason to let anyone know about it. + // A zero delta, is exactly that, nothing should update. + // + // The difference in time can be negative, and no this does not mean time traveling. + // This can be the result of a race condition between when an animation frame is requested + // on the current JavaScript engine event loop, and when the ticker's start method is invoked + // (which invokes the internal _requestIfNeeded method). If a frame is requested before + // _requestIfNeeded is invoked, then the callback for the animation frame the ticker requests, + // can receive a time argument that can be less than the lastTime value that was set within + // _requestIfNeeded. This difference is in microseconds, but this is enough to cause problems. + // + // This check covers this browser engine timing issue, as well as if consumers pass an invalid + // currentTime value. This may happen if consumers opt-out of the autoStart, and update themselves. + if (currentTime > this.lastTime) { + // Save uncapped elapsedMS for measurement + elapsedMS = this.elapsedMS = currentTime - this.lastTime; + // cap the milliseconds elapsed used for deltaTime + if (elapsedMS > this._maxElapsedMS) { + elapsedMS = this._maxElapsedMS; + } + elapsedMS *= this.speed; + // If not enough time has passed, exit the function. + // Get ready for next frame by setting _lastFrame, but based on _minElapsedMS + // adjustment to ensure a relatively stable interval. + if (this._minElapsedMS) { + var delta = currentTime - this._lastFrame | 0; + if (delta < this._minElapsedMS) { + return; + } + this._lastFrame = currentTime - (delta % this._minElapsedMS); + } + this.deltaMS = elapsedMS; + this.deltaTime = this.deltaMS * settings$1.TARGET_FPMS; + // Cache a local reference, in-case ticker is destroyed + // during the emit, we can still check for head.next + var head = this._head; + // Invoke listeners added to internal emitter + var listener = head.next; + while (listener) { + listener = listener.emit(this.deltaTime); + } + if (!head.next) { + this._cancelIfNeeded(); + } + } + else { + this.deltaTime = this.deltaMS = this.elapsedMS = 0; + } + this.lastTime = currentTime; + }; + Object.defineProperty(Ticker.prototype, "FPS", { + /** + * The frames per second at which this ticker is running. + * The default is approximately 60 in most modern browsers. + * **Note:** This does not factor in the value of + * {@link PIXI.Ticker#speed}, which is specific + * to scaling {@link PIXI.Ticker#deltaTime}. + * @member {number} + * @readonly + */ + get: function () { + return 1000 / this.elapsedMS; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(Ticker.prototype, "minFPS", { + /** + * Manages the maximum amount of milliseconds allowed to + * elapse between invoking {@link PIXI.Ticker#update}. + * This value is used to cap {@link PIXI.Ticker#deltaTime}, + * but does not effect the measured value of {@link PIXI.Ticker#FPS}. + * When setting this property it is clamped to a value between + * `0` and `PIXI.settings.TARGET_FPMS * 1000`. + * @member {number} + * @default 10 + */ + get: function () { + return 1000 / this._maxElapsedMS; + }, + set: function (fps) { + // Minimum must be below the maxFPS + var minFPS = Math.min(this.maxFPS, fps); + // Must be at least 0, but below 1 / settings.TARGET_FPMS + var minFPMS = Math.min(Math.max(0, minFPS) / 1000, settings$1.TARGET_FPMS); + this._maxElapsedMS = 1 / minFPMS; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(Ticker.prototype, "maxFPS", { + /** + * Manages the minimum amount of milliseconds required to + * elapse between invoking {@link PIXI.Ticker#update}. + * This will effect the measured value of {@link PIXI.Ticker#FPS}. + * If it is set to `0`, then there is no limit; PixiJS will render as many frames as it can. + * Otherwise it will be at least `minFPS` + * @member {number} + * @default 0 + */ + get: function () { + if (this._minElapsedMS) { + return Math.round(1000 / this._minElapsedMS); + } + return 0; + }, + set: function (fps) { + if (fps === 0) { + this._minElapsedMS = 0; + } + else { + // Max must be at least the minFPS + var maxFPS = Math.max(this.minFPS, fps); + this._minElapsedMS = 1 / (maxFPS / 1000); + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(Ticker, "shared", { + /** + * The shared ticker instance used by {@link PIXI.AnimatedSprite} and by + * {@link PIXI.VideoResource} to update animation frames / video textures. + * + * It may also be used by {@link PIXI.Application} if created with the `sharedTicker` option property set to true. + * + * The property {@link PIXI.Ticker#autoStart} is set to `true` for this instance. + * Please follow the examples for usage, including how to opt-out of auto-starting the shared ticker. + * @example + * let ticker = PIXI.Ticker.shared; + * // Set this to prevent starting this ticker when listeners are added. + * // By default this is true only for the PIXI.Ticker.shared instance. + * ticker.autoStart = false; + * // FYI, call this to ensure the ticker is stopped. It should be stopped + * // if you have not attempted to render anything yet. + * ticker.stop(); + * // Call this when you are ready for a running shared ticker. + * ticker.start(); + * @example + * // You may use the shared ticker to render... + * let renderer = PIXI.autoDetectRenderer(); + * let stage = new PIXI.Container(); + * document.body.appendChild(renderer.view); + * ticker.add(function (time) { + * renderer.render(stage); + * }); + * @example + * // Or you can just update it manually. + * ticker.autoStart = false; + * ticker.stop(); + * function animate(time) { + * ticker.update(time); + * renderer.render(stage); + * requestAnimationFrame(animate); + * } + * animate(performance.now()); + * @member {PIXI.Ticker} + * @static + */ + get: function () { + if (!Ticker._shared) { + var shared = Ticker._shared = new Ticker(); + shared.autoStart = true; + shared._protected = true; + } + return Ticker._shared; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(Ticker, "system", { + /** + * The system ticker instance used by {@link PIXI.InteractionManager} and by + * {@link PIXI.BasePrepare} for core timing functionality that shouldn't usually need to be paused, + * unlike the `shared` ticker which drives visual animations and rendering which may want to be paused. + * + * The property {@link PIXI.Ticker#autoStart} is set to `true` for this instance. + * @member {PIXI.Ticker} + * @static + */ + get: function () { + if (!Ticker._system) { + var system = Ticker._system = new Ticker(); + system.autoStart = true; + system._protected = true; + } + return Ticker._system; + }, + enumerable: false, + configurable: true + }); + return Ticker; + }()); + + /** + * Middleware for for Application Ticker. + * @example + * import {TickerPlugin} from '@pixi/ticker'; + * import {Application} from '@pixi/app'; + * import {extensions} from '@pixi/extensions'; + * extensions.add(TickerPlugin); + * @class + * @memberof PIXI + */ + var TickerPlugin = /** @class */ (function () { + function TickerPlugin() { + } + /** + * Initialize the plugin with scope of application instance + * @static + * @private + * @param {object} [options] - See application options + */ + TickerPlugin.init = function (options) { + var _this = this; + // Set default + options = Object.assign({ + autoStart: true, + sharedTicker: false, + }, options); + // Create ticker setter + Object.defineProperty(this, 'ticker', { + set: function (ticker) { + if (this._ticker) { + this._ticker.remove(this.render, this); + } + this._ticker = ticker; + if (ticker) { + ticker.add(this.render, this, exports.UPDATE_PRIORITY.LOW); + } + }, + get: function () { + return this._ticker; + }, + }); + /** + * Convenience method for stopping the render. + * @method + * @memberof PIXI.Application + * @instance + */ + this.stop = function () { + _this._ticker.stop(); + }; + /** + * Convenience method for starting the render. + * @method + * @memberof PIXI.Application + * @instance + */ + this.start = function () { + _this._ticker.start(); + }; + /** + * Internal reference to the ticker. + * @type {PIXI.Ticker} + * @name _ticker + * @memberof PIXI.Application# + * @private + */ + this._ticker = null; + /** + * Ticker for doing render updates. + * @type {PIXI.Ticker} + * @name ticker + * @memberof PIXI.Application# + * @default PIXI.Ticker.shared + */ + this.ticker = options.sharedTicker ? Ticker.shared : new Ticker(); + // Start the rendering + if (options.autoStart) { + this.start(); + } + }; + /** + * Clean up the ticker, scoped to application. + * @static + * @private + */ + TickerPlugin.destroy = function () { + if (this._ticker) { + var oldTicker = this._ticker; + this.ticker = null; + oldTicker.destroy(); + } + }; + /** @ignore */ + TickerPlugin.extension = exports.ExtensionType.Application; + return TickerPlugin; + }()); + + /*! + * @pixi/core - v6.5.3 + * Compiled Fri, 09 Sep 2022 13:55:20 UTC + * + * @pixi/core is licensed under the MIT License. + * http://www.opensource.org/licenses/mit-license + */ + + /** + * The maximum support for using WebGL. If a device does not + * support WebGL version, for instance WebGL 2, it will still + * attempt to fallback support to WebGL 1. If you want to + * explicitly remove feature support to target a more stable + * baseline, prefer a lower environment. + * + * Due to {@link https://bugs.chromium.org/p/chromium/issues/detail?id=934823|bug in chromium} + * we disable webgl2 by default for all non-apple mobile devices. + * @static + * @name PREFER_ENV + * @memberof PIXI.settings + * @type {number} + * @default PIXI.ENV.WEBGL2 + */ + settings$1.PREFER_ENV = isMobile$2.any ? exports.ENV.WEBGL : exports.ENV.WEBGL2; + /** + * If set to `true`, *only* Textures and BaseTexture objects stored + * in the caches ({@link PIXI.utils.TextureCache TextureCache} and + * {@link PIXI.utils.BaseTextureCache BaseTextureCache}) can be + * used when calling {@link PIXI.Texture.from Texture.from} or + * {@link PIXI.BaseTexture.from BaseTexture.from}. + * Otherwise, these `from` calls throw an exception. Using this property + * can be useful if you want to enforce preloading all assets with + * {@link PIXI.Loader Loader}. + * @static + * @name STRICT_TEXTURE_CACHE + * @memberof PIXI.settings + * @type {boolean} + * @default false + */ + settings$1.STRICT_TEXTURE_CACHE = false; + + /** + * Collection of installed resource types, class must extend {@link PIXI.Resource}. + * @example + * class CustomResource extends PIXI.Resource { + * // MUST have source, options constructor signature + * // for auto-detected resources to be created. + * constructor(source, options) { + * super(); + * } + * upload(renderer, baseTexture, glTexture) { + * // upload with GL + * return true; + * } + * // used to auto-detect resource + * static test(source, extension) { + * return extension === 'xyz'|| source instanceof SomeClass; + * } + * } + * // Install the new resource type + * PIXI.INSTALLED.push(CustomResource); + * @memberof PIXI + * @type {Array} + * @static + * @readonly + */ + var INSTALLED = []; + /** + * Create a resource element from a single source element. This + * auto-detects which type of resource to create. All resources that + * are auto-detectable must have a static `test` method and a constructor + * with the arguments `(source, options?)`. Currently, the supported + * resources for auto-detection include: + * - {@link PIXI.ImageResource} + * - {@link PIXI.CanvasResource} + * - {@link PIXI.VideoResource} + * - {@link PIXI.SVGResource} + * - {@link PIXI.BufferResource} + * @static + * @memberof PIXI + * @function autoDetectResource + * @param {string|*} source - Resource source, this can be the URL to the resource, + * a typed-array (for BufferResource), HTMLVideoElement, SVG data-uri + * or any other resource that can be auto-detected. If not resource is + * detected, it's assumed to be an ImageResource. + * @param {object} [options] - Pass-through options to use for Resource + * @param {number} [options.width] - Width of BufferResource or SVG rasterization + * @param {number} [options.height] - Height of BufferResource or SVG rasterization + * @param {boolean} [options.autoLoad=true] - Image, SVG and Video flag to start loading + * @param {number} [options.scale=1] - SVG source scale. Overridden by width, height + * @param {boolean} [options.createBitmap=PIXI.settings.CREATE_IMAGE_BITMAP] - Image option to create Bitmap object + * @param {boolean} [options.crossorigin=true] - Image and Video option to set crossOrigin + * @param {boolean} [options.autoPlay=true] - Video option to start playing video immediately + * @param {number} [options.updateFPS=0] - Video option to update how many times a second the + * texture should be updated from the video. Leave at 0 to update at every render + * @returns {PIXI.Resource} The created resource. + */ + function autoDetectResource(source, options) { + if (!source) { + return null; + } + var extension = ''; + if (typeof source === 'string') { + // search for file extension: period, 3-4 chars, then ?, # or EOL + var result = (/\.(\w{3,4})(?:$|\?|#)/i).exec(source); + if (result) { + extension = result[1].toLowerCase(); + } + } + for (var i = INSTALLED.length - 1; i >= 0; --i) { + var ResourcePlugin = INSTALLED[i]; + if (ResourcePlugin.test && ResourcePlugin.test(source, extension)) { + return new ResourcePlugin(source, options); + } + } + throw new Error('Unrecognized source type to auto-detect Resource'); + } + + /*! ***************************************************************************** + Copyright (c) Microsoft Corporation. - THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED - WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, - MERCHANTABLITY OR NON-INFRINGEMENT. + Permission to use, copy, modify, and/or distribute this software for any + purpose with or without fee is hereby granted. - See the Apache Version 2.0 License for specific language governing permissions - and limitations under the License. - ***************************************************************************** */ - /* global Reflect, Promise */ + THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH + REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY + AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, + INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM + LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR + OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR + PERFORMANCE OF THIS SOFTWARE. + ***************************************************************************** */ + /* global Reflect, Promise */ - var extendStatics$2 = function(d, b) { - extendStatics$2 = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) { if (b.hasOwnProperty(p)) { d[p] = b[p]; } } }; - return extendStatics$2(d, b); - }; + var extendStatics$i = function(d, b) { + extendStatics$i = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) { if (b.hasOwnProperty(p)) { d[p] = b[p]; } } }; + return extendStatics$i(d, b); + }; - function __extends$2(d, b) { - extendStatics$2(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - } - - /** - * Base resource class for textures that manages validation and uploading, depending on its type. - * - * Uploading of a base texture to the GPU is required. - * - * @class - * @memberof PIXI.resources - */ - var Resource = /** @class */ (function () { - /** - * @param {number} [width=0] - Width of the resource - * @param {number} [height=0] - Height of the resource - */ - function Resource(width, height) { - if (width === void 0) { width = 0; } - if (height === void 0) { height = 0; } - /** - * Internal width of the resource - * @member {number} - * @protected - */ - this._width = width; - /** - * Internal height of the resource - * @member {number} - * @protected - */ - this._height = height; - /** - * If resource has been destroyed - * @member {boolean} - * @readonly - * @default false - */ - this.destroyed = false; - /** - * `true` if resource is created by BaseTexture - * useful for doing cleanup with BaseTexture destroy - * and not cleaning up resources that were created - * externally. - * @member {boolean} - * @protected - */ - this.internal = false; - /** - * Mini-runner for handling resize events - * accepts 2 parameters: width, height - * - * @member {Runner} - * @private - */ - this.onResize = new Runner('setRealSize'); - /** - * Mini-runner for handling update events - * - * @member {Runner} - * @private - */ - this.onUpdate = new Runner('update'); - /** - * Handle internal errors, such as loading errors - * accepts 1 param: error - * - * @member {Runner} - * @private - */ - this.onError = new Runner('onError'); - } - /** - * Bind to a parent BaseTexture - * - * @param {PIXI.BaseTexture} baseTexture - Parent texture - */ - Resource.prototype.bind = function (baseTexture) { - this.onResize.add(baseTexture); - this.onUpdate.add(baseTexture); - this.onError.add(baseTexture); - // Call a resize immediate if we already - // have the width and height of the resource - if (this._width || this._height) { - this.onResize.emit(this._width, this._height); - } - }; - /** - * Unbind to a parent BaseTexture - * - * @param {PIXI.BaseTexture} baseTexture - Parent texture - */ - Resource.prototype.unbind = function (baseTexture) { - this.onResize.remove(baseTexture); - this.onUpdate.remove(baseTexture); - this.onError.remove(baseTexture); - }; - /** - * Trigger a resize event - * @param {number} width - X dimension - * @param {number} height - Y dimension - */ - Resource.prototype.resize = function (width, height) { - if (width !== this._width || height !== this._height) { - this._width = width; - this._height = height; - this.onResize.emit(width, height); - } - }; - Object.defineProperty(Resource.prototype, "valid", { - /** - * Has been validated - * @readonly - * @member {boolean} - */ - get: function () { - return !!this._width && !!this._height; - }, - enumerable: false, - configurable: true - }); - /** - * Has been updated trigger event - */ - Resource.prototype.update = function () { - if (!this.destroyed) { - this.onUpdate.emit(); - } - }; - /** - * This can be overridden to start preloading a resource - * or do any other prepare step. - * @protected - * @return {Promise} Handle the validate event - */ - Resource.prototype.load = function () { - return Promise.resolve(this); - }; - Object.defineProperty(Resource.prototype, "width", { - /** - * The width of the resource. - * - * @member {number} - * @readonly - */ - get: function () { - return this._width; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(Resource.prototype, "height", { - /** - * The height of the resource. - * - * @member {number} - * @readonly - */ - get: function () { - return this._height; - }, - enumerable: false, - configurable: true - }); - /** - * Set the style, optional to override - * - * @param {PIXI.Renderer} renderer - yeah, renderer! - * @param {PIXI.BaseTexture} baseTexture - the texture - * @param {PIXI.GLTexture} glTexture - texture instance for this webgl context - * @returns {boolean} `true` is success - */ - Resource.prototype.style = function (_renderer, _baseTexture, _glTexture) { - return false; - }; - /** - * Clean up anything, this happens when destroying is ready. - * - * @protected - */ - Resource.prototype.dispose = function () { - // override - }; - /** - * Call when destroying resource, unbind any BaseTexture object - * before calling this method, as reference counts are maintained - * internally. - */ - Resource.prototype.destroy = function () { - if (!this.destroyed) { - this.destroyed = true; - this.dispose(); - this.onError.removeAll(); - this.onError = null; - this.onResize.removeAll(); - this.onResize = null; - this.onUpdate.removeAll(); - this.onUpdate = null; - } - }; - /** - * Abstract, used to auto-detect resource type - * - * @static - * @param {*} source - The source object - * @param {string} extension - The extension of source, if set - */ - Resource.test = function (_source, _extension) { - return false; - }; - return Resource; - }()); - - /** - * @interface SharedArrayBuffer - */ - /** - * Buffer resource with data of typed array. - * @class - * @extends PIXI.resources.Resource - * @memberof PIXI.resources - */ - var BufferResource = /** @class */ (function (_super) { - __extends$2(BufferResource, _super); - /** - * @param {Float32Array|Uint8Array|Uint32Array} source - Source buffer - * @param {object} options - Options - * @param {number} options.width - Width of the texture - * @param {number} options.height - Height of the texture - */ - function BufferResource(source, options) { - var _this = this; - var _a = options || {}, width = _a.width, height = _a.height; - if (!width || !height) { - throw new Error('BufferResource width or height invalid'); - } - _this = _super.call(this, width, height) || this; - /** - * Source array - * Cannot be ClampedUint8Array because it cant be uploaded to WebGL - * - * @member {Float32Array|Uint8Array|Uint32Array} - */ - _this.data = source; - return _this; - } - /** - * Upload the texture to the GPU. - * @param {PIXI.Renderer} renderer - Upload to the renderer - * @param {PIXI.BaseTexture} baseTexture - Reference to parent texture - * @param {PIXI.GLTexture} glTexture - glTexture - * @returns {boolean} true is success - */ - BufferResource.prototype.upload = function (renderer, baseTexture, glTexture) { - var gl = renderer.gl; - gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, baseTexture.alphaMode === exports.ALPHA_MODES.UNPACK); - if (glTexture.width === baseTexture.width && glTexture.height === baseTexture.height) { - gl.texSubImage2D(baseTexture.target, 0, 0, 0, baseTexture.width, baseTexture.height, baseTexture.format, baseTexture.type, this.data); - } - else { - glTexture.width = baseTexture.width; - glTexture.height = baseTexture.height; - gl.texImage2D(baseTexture.target, 0, glTexture.internalFormat, baseTexture.width, baseTexture.height, 0, baseTexture.format, glTexture.type, this.data); - } - return true; - }; - /** - * Destroy and don't use after this - * @override - */ - BufferResource.prototype.dispose = function () { - this.data = null; - }; - /** - * Used to auto-detect the type of resource. - * - * @static - * @param {*} source - The source object - * @return {boolean} `true` if - */ - BufferResource.test = function (source) { - return source instanceof Float32Array - || source instanceof Uint8Array - || source instanceof Uint32Array; - }; - return BufferResource; - }(Resource)); - - var defaultBufferOptions = { - scaleMode: exports.SCALE_MODES.NEAREST, - format: exports.FORMATS.RGBA, - alphaMode: exports.ALPHA_MODES.NPM, - }; - /** - * A Texture stores the information that represents an image. - * All textures have a base texture, which contains information about the source. - * Therefore you can have many textures all using a single BaseTexture - * - * @class - * @extends PIXI.utils.EventEmitter - * @memberof PIXI - * @param {PIXI.resources.Resource|string|HTMLImageElement|HTMLCanvasElement|HTMLVideoElement} [resource=null] - * The current resource to use, for things that aren't Resource objects, will be converted - * into a Resource. - * @param {Object} [options] - Collection of options - * @param {PIXI.MIPMAP_MODES} [options.mipmap=PIXI.settings.MIPMAP_TEXTURES] - If mipmapping is enabled for texture - * @param {number} [options.anisotropicLevel=PIXI.settings.ANISOTROPIC_LEVEL] - Anisotropic filtering level of texture - * @param {PIXI.WRAP_MODES} [options.wrapMode=PIXI.settings.WRAP_MODE] - Wrap mode for textures - * @param {PIXI.SCALE_MODES} [options.scaleMode=PIXI.settings.SCALE_MODE] - Default scale mode, linear, nearest - * @param {PIXI.FORMATS} [options.format=PIXI.FORMATS.RGBA] - GL format type - * @param {PIXI.TYPES} [options.type=PIXI.TYPES.UNSIGNED_BYTE] - GL data type - * @param {PIXI.TARGETS} [options.target=PIXI.TARGETS.TEXTURE_2D] - GL texture target - * @param {PIXI.ALPHA_MODES} [options.alphaMode=PIXI.ALPHA_MODES.UNPACK] - Pre multiply the image alpha - * @param {number} [options.width=0] - Width of the texture - * @param {number} [options.height=0] - Height of the texture - * @param {number} [options.resolution] - Resolution of the base texture - * @param {object} [options.resourceOptions] - Optional resource options, - * see {@link PIXI.resources.autoDetectResource autoDetectResource} - */ - var BaseTexture = /** @class */ (function (_super) { - __extends$2(BaseTexture, _super); - function BaseTexture(resource, options) { - if (resource === void 0) { resource = null; } - if (options === void 0) { options = null; } - var _this = _super.call(this) || this; - options = options || {}; - var alphaMode = options.alphaMode, mipmap = options.mipmap, anisotropicLevel = options.anisotropicLevel, scaleMode = options.scaleMode, width = options.width, height = options.height, wrapMode = options.wrapMode, format = options.format, type = options.type, target = options.target, resolution = options.resolution, resourceOptions = options.resourceOptions; - // Convert the resource to a Resource object - if (resource && !(resource instanceof Resource)) { - resource = autoDetectResource(resource, resourceOptions); - resource.internal = true; - } - /** - * The width of the base texture set when the image has loaded - * - * @readonly - * @member {number} - */ - _this.width = width || 0; - /** - * The height of the base texture set when the image has loaded - * - * @readonly - * @member {number} - */ - _this.height = height || 0; - /** - * The resolution / device pixel ratio of the texture - * - * @member {number} - * @default PIXI.settings.RESOLUTION - */ - _this.resolution = resolution || settings.RESOLUTION; - /** - * Mipmap mode of the texture, affects downscaled images - * - * @member {PIXI.MIPMAP_MODES} - * @default PIXI.settings.MIPMAP_TEXTURES - */ - _this.mipmap = mipmap !== undefined ? mipmap : settings.MIPMAP_TEXTURES; - /** - * Anisotropic filtering level of texture - * - * @member {number} - * @default PIXI.settings.ANISOTROPIC_LEVEL - */ - _this.anisotropicLevel = anisotropicLevel !== undefined ? anisotropicLevel : settings.ANISOTROPIC_LEVEL; - /** - * How the texture wraps - * @member {number} - */ - _this.wrapMode = wrapMode || settings.WRAP_MODE; - /** - * The scale mode to apply when scaling this texture - * - * @member {PIXI.SCALE_MODES} - * @default PIXI.settings.SCALE_MODE - */ - _this.scaleMode = scaleMode !== undefined ? scaleMode : settings.SCALE_MODE; - /** - * The pixel format of the texture - * - * @member {PIXI.FORMATS} - * @default PIXI.FORMATS.RGBA - */ - _this.format = format || exports.FORMATS.RGBA; - /** - * The type of resource data - * - * @member {PIXI.TYPES} - * @default PIXI.TYPES.UNSIGNED_BYTE - */ - _this.type = type || exports.TYPES.UNSIGNED_BYTE; - /** - * The target type - * - * @member {PIXI.TARGETS} - * @default PIXI.TARGETS.TEXTURE_2D - */ - _this.target = target || exports.TARGETS.TEXTURE_2D; - /** - * How to treat premultiplied alpha, see {@link PIXI.ALPHA_MODES}. - * - * @member {PIXI.ALPHA_MODES} - * @default PIXI.ALPHA_MODES.UNPACK - */ - _this.alphaMode = alphaMode !== undefined ? alphaMode : exports.ALPHA_MODES.UNPACK; - if (options.premultiplyAlpha !== undefined) { - // triggers deprecation - _this.premultiplyAlpha = options.premultiplyAlpha; - } - /** - * Global unique identifier for this BaseTexture - * - * @member {number} - * @protected - */ - _this.uid = uid(); - /** - * Used by automatic texture Garbage Collection, stores last GC tick when it was bound - * - * @member {number} - * @protected - */ - _this.touched = 0; - /** - * Whether or not the texture is a power of two, try to use power of two textures as much - * as you can - * - * @readonly - * @member {boolean} - * @default false - */ - _this.isPowerOfTwo = false; - _this._refreshPOT(); - /** - * The map of render context textures where this is bound - * - * @member {Object} - * @private - */ - _this._glTextures = {}; - /** - * Used by TextureSystem to only update texture to the GPU when needed. - * Please call `update()` to increment it. - * - * @readonly - * @member {number} - */ - _this.dirtyId = 0; - /** - * Used by TextureSystem to only update texture style when needed. - * - * @protected - * @member {number} - */ - _this.dirtyStyleId = 0; - /** - * Currently default cache ID. - * - * @member {string} - */ - _this.cacheId = null; - /** - * Generally speaking means when resource is loaded. - * @readonly - * @member {boolean} - */ - _this.valid = width > 0 && height > 0; - /** - * The collection of alternative cache ids, since some BaseTextures - * can have more than one ID, short name and longer full URL - * - * @member {Array} - * @readonly - */ - _this.textureCacheIds = []; - /** - * Flag if BaseTexture has been destroyed. - * - * @member {boolean} - * @readonly - */ - _this.destroyed = false; - /** - * The resource used by this BaseTexture, there can only - * be one resource per BaseTexture, but textures can share - * resources. - * - * @member {PIXI.resources.Resource} - * @readonly - */ - _this.resource = null; - /** - * Number of the texture batch, used by multi-texture renderers - * - * @member {number} - */ - _this._batchEnabled = 0; - /** - * Location inside texture batch, used by multi-texture renderers - * - * @member {number} - */ - _this._batchLocation = 0; - /** - * Whether its a part of another texture, handled by ArrayResource or CubeResource - * - * @member {PIXI.BaseTexture} - */ - _this.parentTextureArray = null; - /** - * Fired when a not-immediately-available source finishes loading. - * - * @protected - * @event PIXI.BaseTexture#loaded - * @param {PIXI.BaseTexture} baseTexture - Resource loaded. - */ - /** - * Fired when a not-immediately-available source fails to load. - * - * @protected - * @event PIXI.BaseTexture#error - * @param {PIXI.BaseTexture} baseTexture - Resource errored. - * @param {ErrorEvent} event - Load error event. - */ - /** - * Fired when BaseTexture is updated. - * - * @protected - * @event PIXI.BaseTexture#loaded - * @param {PIXI.BaseTexture} baseTexture - Resource loaded. - */ - /** - * Fired when BaseTexture is updated. - * - * @protected - * @event PIXI.BaseTexture#update - * @param {PIXI.BaseTexture} baseTexture - Instance of texture being updated. - */ - /** - * Fired when BaseTexture is destroyed. - * - * @protected - * @event PIXI.BaseTexture#dispose - * @param {PIXI.BaseTexture} baseTexture - Instance of texture being destroyed. - */ - // Set the resource - _this.setResource(resource); - return _this; - } - Object.defineProperty(BaseTexture.prototype, "realWidth", { - /** - * Pixel width of the source of this texture - * - * @readonly - * @member {number} - */ - get: function () { - return Math.ceil((this.width * this.resolution) - 1e-4); - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BaseTexture.prototype, "realHeight", { - /** - * Pixel height of the source of this texture - * - * @readonly - * @member {number} - */ - get: function () { - return Math.ceil((this.height * this.resolution) - 1e-4); - }, - enumerable: false, - configurable: true - }); - /** - * Changes style options of BaseTexture - * - * @param {PIXI.SCALE_MODES} [scaleMode] - Pixi scalemode - * @param {PIXI.MIPMAP_MODES} [mipmap] - enable mipmaps - * @returns {PIXI.BaseTexture} this - */ - BaseTexture.prototype.setStyle = function (scaleMode, mipmap) { - var dirty; - if (scaleMode !== undefined && scaleMode !== this.scaleMode) { - this.scaleMode = scaleMode; - dirty = true; - } - if (mipmap !== undefined && mipmap !== this.mipmap) { - this.mipmap = mipmap; - dirty = true; - } - if (dirty) { - this.dirtyStyleId++; - } - return this; - }; - /** - * Changes w/h/resolution. Texture becomes valid if width and height are greater than zero. - * - * @param {number} width - Visual width - * @param {number} height - Visual height - * @param {number} [resolution] - Optionally set resolution - * @returns {PIXI.BaseTexture} this - */ - BaseTexture.prototype.setSize = function (width, height, resolution) { - this.resolution = resolution || this.resolution; - this.width = width; - this.height = height; - this._refreshPOT(); - this.update(); - return this; - }; - /** - * Sets real size of baseTexture, preserves current resolution. - * - * @param {number} realWidth - Full rendered width - * @param {number} realHeight - Full rendered height - * @param {number} [resolution] - Optionally set resolution - * @returns {PIXI.BaseTexture} this - */ - BaseTexture.prototype.setRealSize = function (realWidth, realHeight, resolution) { - this.resolution = resolution || this.resolution; - this.width = realWidth / this.resolution; - this.height = realHeight / this.resolution; - this._refreshPOT(); - this.update(); - return this; - }; - /** - * Refresh check for isPowerOfTwo texture based on size - * - * @private - */ - BaseTexture.prototype._refreshPOT = function () { - this.isPowerOfTwo = isPow2(this.realWidth) && isPow2(this.realHeight); - }; - /** - * Changes resolution - * - * @param {number} resolution - res - * @returns {PIXI.BaseTexture} this - */ - BaseTexture.prototype.setResolution = function (resolution) { - var oldResolution = this.resolution; - if (oldResolution === resolution) { - return this; - } - this.resolution = resolution; - if (this.valid) { - this.width = this.width * oldResolution / resolution; - this.height = this.height * oldResolution / resolution; - this.emit('update', this); - } - this._refreshPOT(); - return this; - }; - /** - * Sets the resource if it wasn't set. Throws error if resource already present - * - * @param {PIXI.resources.Resource} resource - that is managing this BaseTexture - * @returns {PIXI.BaseTexture} this - */ - BaseTexture.prototype.setResource = function (resource) { - if (this.resource === resource) { - return this; - } - if (this.resource) { - throw new Error('Resource can be set only once'); - } - resource.bind(this); - this.resource = resource; - return this; - }; - /** - * Invalidates the object. Texture becomes valid if width and height are greater than zero. - */ - BaseTexture.prototype.update = function () { - if (!this.valid) { - if (this.width > 0 && this.height > 0) { - this.valid = true; - this.emit('loaded', this); - this.emit('update', this); - } - } - else { - this.dirtyId++; - this.dirtyStyleId++; - this.emit('update', this); - } - }; - /** - * Handle errors with resources. - * @private - * @param {ErrorEvent} event - Error event emitted. - */ - BaseTexture.prototype.onError = function (event) { - this.emit('error', this, event); - }; - /** - * Destroys this base texture. - * The method stops if resource doesn't want this texture to be destroyed. - * Removes texture from all caches. - */ - BaseTexture.prototype.destroy = function () { - // remove and destroy the resource - if (this.resource) { - this.resource.unbind(this); - // only destroy resourced created internally - if (this.resource.internal) { - this.resource.destroy(); - } - this.resource = null; - } - if (this.cacheId) { - delete BaseTextureCache[this.cacheId]; - delete TextureCache[this.cacheId]; - this.cacheId = null; - } - // finally let the WebGL renderer know.. - this.dispose(); - BaseTexture.removeFromCache(this); - this.textureCacheIds = null; - this.destroyed = true; - }; - /** - * Frees the texture from WebGL memory without destroying this texture object. - * This means you can still use the texture later which will upload it to GPU - * memory again. - * - * @fires PIXI.BaseTexture#dispose - */ - BaseTexture.prototype.dispose = function () { - this.emit('dispose', this); - }; - /** - * Utility function for BaseTexture|Texture cast - */ - BaseTexture.prototype.castToBaseTexture = function () { - return this; - }; - /** - * Helper function that creates a base texture based on the source you provide. - * The source can be - image url, image element, canvas element. If the - * source is an image url or an image element and not in the base texture - * cache, it will be created and loaded. - * - * @static - * @param {string|HTMLImageElement|HTMLCanvasElement|SVGElement|HTMLVideoElement} source - The - * source to create base texture from. - * @param {object} [options] See {@link PIXI.BaseTexture}'s constructor for options. - * @param {boolean} [strict] - Enforce strict-mode, see {@link PIXI.settings.STRICT_TEXTURE_CACHE}. - * @returns {PIXI.BaseTexture} The new base texture. - */ - BaseTexture.from = function (source, options, strict) { - if (strict === void 0) { strict = settings.STRICT_TEXTURE_CACHE; } - var isFrame = typeof source === 'string'; - var cacheId = null; - if (isFrame) { - cacheId = source; - } - else { - if (!source._pixiId) { - source._pixiId = "pixiid_" + uid(); - } - cacheId = source._pixiId; - } - var baseTexture = BaseTextureCache[cacheId]; - // Strict-mode rejects invalid cacheIds - if (isFrame && strict && !baseTexture) { - throw new Error("The cacheId \"" + cacheId + "\" does not exist in BaseTextureCache."); - } - if (!baseTexture) { - baseTexture = new BaseTexture(source, options); - baseTexture.cacheId = cacheId; - BaseTexture.addToCache(baseTexture, cacheId); - } - return baseTexture; - }; - /** - * Create a new BaseTexture with a BufferResource from a Float32Array. - * RGBA values are floats from 0 to 1. - * @static - * @param {Float32Array|Uint8Array} buffer - The optional array to use, if no data - * is provided, a new Float32Array is created. - * @param {number} width - Width of the resource - * @param {number} height - Height of the resource - * @param {object} [options] See {@link PIXI.BaseTexture}'s constructor for options. - * @return {PIXI.BaseTexture} The resulting new BaseTexture - */ - BaseTexture.fromBuffer = function (buffer, width, height, options) { - buffer = buffer || new Float32Array(width * height * 4); - var resource = new BufferResource(buffer, { width: width, height: height }); - var type = buffer instanceof Float32Array ? exports.TYPES.FLOAT : exports.TYPES.UNSIGNED_BYTE; - return new BaseTexture(resource, Object.assign(defaultBufferOptions, options || { width: width, height: height, type: type })); - }; - /** - * Adds a BaseTexture to the global BaseTextureCache. This cache is shared across the whole PIXI object. - * - * @static - * @param {PIXI.BaseTexture} baseTexture - The BaseTexture to add to the cache. - * @param {string} id - The id that the BaseTexture will be stored against. - */ - BaseTexture.addToCache = function (baseTexture, id) { - if (id) { - if (baseTexture.textureCacheIds.indexOf(id) === -1) { - baseTexture.textureCacheIds.push(id); - } - if (BaseTextureCache[id]) { - // eslint-disable-next-line no-console - console.warn("BaseTexture added to the cache with an id [" + id + "] that already had an entry"); - } - BaseTextureCache[id] = baseTexture; - } - }; - /** - * Remove a BaseTexture from the global BaseTextureCache. - * - * @static - * @param {string|PIXI.BaseTexture} baseTexture - id of a BaseTexture to be removed, or a BaseTexture instance itself. - * @return {PIXI.BaseTexture|null} The BaseTexture that was removed. - */ - BaseTexture.removeFromCache = function (baseTexture) { - if (typeof baseTexture === 'string') { - var baseTextureFromCache = BaseTextureCache[baseTexture]; - if (baseTextureFromCache) { - var index = baseTextureFromCache.textureCacheIds.indexOf(baseTexture); - if (index > -1) { - baseTextureFromCache.textureCacheIds.splice(index, 1); - } - delete BaseTextureCache[baseTexture]; - return baseTextureFromCache; - } - } - else if (baseTexture && baseTexture.textureCacheIds) { - for (var i = 0; i < baseTexture.textureCacheIds.length; ++i) { - delete BaseTextureCache[baseTexture.textureCacheIds[i]]; - } - baseTexture.textureCacheIds.length = 0; - return baseTexture; - } - return null; - }; - /** - * Global number of the texture batch, used by multi-texture renderers - * - * @static - * @member {number} - */ - BaseTexture._globalBatch = 0; - return BaseTexture; - }(eventemitter3)); - - /** - * Resource that can manage several resource (items) inside. - * All resources need to have the same pixel size. - * Parent class for CubeResource and ArrayResource - * - * @class - * @extends PIXI.resources.Resource - * @memberof PIXI.resources - * @param {object} [options] Options to for Resource constructor - * @param {number} [options.width] - Width of the resource - * @param {number} [options.height] - Height of the resource - */ - var AbstractMultiResource = /** @class */ (function (_super) { - __extends$2(AbstractMultiResource, _super); - function AbstractMultiResource(length, options) { - var _this = this; - var _a = options || {}, width = _a.width, height = _a.height; - _this = _super.call(this, width, height) || this; - /** - * Collection of partial baseTextures that correspond to resources - * @member {Array} - * @readonly - */ - _this.items = []; - /** - * Dirty IDs for each part - * @member {Array} - * @readonly - */ - _this.itemDirtyIds = []; - for (var i = 0; i < length; i++) { - var partTexture = new BaseTexture(); - _this.items.push(partTexture); - // -2 - first run of texture array upload - // -1 - texture item was allocated - // >=0 - texture item uploaded , in sync with items[i].dirtyId - _this.itemDirtyIds.push(-2); - } - /** - * Number of elements in array - * - * @member {number} - * @readonly - */ - _this.length = length; - /** - * Promise when loading - * @member {Promise} - * @private - * @default null - */ - _this._load = null; - /** - * Bound baseTexture, there can only be one - * @member {PIXI.BaseTexture} - */ - _this.baseTexture = null; - return _this; - } - /** - * used from ArrayResource and CubeResource constructors - * @param {Array<*>} resources - Can be resources, image elements, canvas, etc. , - * length should be same as constructor length - * @param {object} [options] - detect options for resources - * @protected - */ - AbstractMultiResource.prototype.initFromArray = function (resources, options) { - for (var i = 0; i < this.length; i++) { - if (!resources[i]) { - continue; - } - if (resources[i].castToBaseTexture) { - this.addBaseTextureAt(resources[i].castToBaseTexture(), i); - } - else if (resources[i] instanceof Resource) { - this.addResourceAt(resources[i], i); - } - else { - this.addResourceAt(autoDetectResource(resources[i], options), i); - } - } - }; - /** - * Destroy this BaseImageResource - * @override - */ - AbstractMultiResource.prototype.dispose = function () { - for (var i = 0, len = this.length; i < len; i++) { - this.items[i].destroy(); - } - this.items = null; - this.itemDirtyIds = null; - this._load = null; - }; - /** - * Set a resource by ID - * - * @param {PIXI.resources.Resource} resource - * @param {number} index - Zero-based index of resource to set - * @return {PIXI.resources.ArrayResource} Instance for chaining - */ - AbstractMultiResource.prototype.addResourceAt = function (resource, index) { - if (!this.items[index]) { - throw new Error("Index " + index + " is out of bounds"); - } - // Inherit the first resource dimensions - if (resource.valid && !this.valid) { - this.resize(resource.width, resource.height); - } - this.items[index].setResource(resource); - return this; - }; - /** - * Set the parent base texture - * @member {PIXI.BaseTexture} - * @override - */ - AbstractMultiResource.prototype.bind = function (baseTexture) { - if (this.baseTexture !== null) { - throw new Error('Only one base texture per TextureArray is allowed'); - } - _super.prototype.bind.call(this, baseTexture); - for (var i = 0; i < this.length; i++) { - this.items[i].parentTextureArray = baseTexture; - this.items[i].on('update', baseTexture.update, baseTexture); - } - }; - /** - * Unset the parent base texture - * @member {PIXI.BaseTexture} - * @override - */ - AbstractMultiResource.prototype.unbind = function (baseTexture) { - _super.prototype.unbind.call(this, baseTexture); - for (var i = 0; i < this.length; i++) { - this.items[i].parentTextureArray = null; - this.items[i].off('update', baseTexture.update, baseTexture); - } - }; - /** - * Load all the resources simultaneously - * @override - * @return {Promise} When load is resolved - */ - AbstractMultiResource.prototype.load = function () { - var _this = this; - if (this._load) { - return this._load; - } - var resources = this.items.map(function (item) { return item.resource; }).filter(function (item) { return item; }); - // TODO: also implement load part-by-part strategy - var promises = resources.map(function (item) { return item.load(); }); - this._load = Promise.all(promises) - .then(function () { - var _a = _this.items[0], realWidth = _a.realWidth, realHeight = _a.realHeight; - _this.resize(realWidth, realHeight); - return Promise.resolve(_this); - }); - return this._load; - }; - return AbstractMultiResource; - }(Resource)); - - /** - * A resource that contains a number of sources. - * - * @class - * @extends PIXI.resources.Resource - * @memberof PIXI.resources - * @param {number|Array<*>} source - Number of items in array or the collection - * of image URLs to use. Can also be resources, image elements, canvas, etc. - * @param {object} [options] - Options to apply to {@link PIXI.resources.autoDetectResource} - * @param {number} [options.width] - Width of the resource - * @param {number} [options.height] - Height of the resource - */ - var ArrayResource = /** @class */ (function (_super) { - __extends$2(ArrayResource, _super); - function ArrayResource(source, options) { - var _this = this; - var _a = options || {}, width = _a.width, height = _a.height; - var urls; - var length; - if (Array.isArray(source)) { - urls = source; - length = source.length; - } - else { - length = source; - } - _this = _super.call(this, length, { width: width, height: height }) || this; - if (urls) { - _this.initFromArray(urls, options); - } - return _this; - } - /** - * Set a baseTexture by ID, - * ArrayResource just takes resource from it, nothing more - * - * @param {PIXI.BaseTexture} baseTexture - * @param {number} index - Zero-based index of resource to set - * @return {PIXI.resources.ArrayResource} Instance for chaining - */ - ArrayResource.prototype.addBaseTextureAt = function (baseTexture, index) { - if (baseTexture.resource) { - this.addResourceAt(baseTexture.resource, index); - } - else { - throw new Error('ArrayResource does not support RenderTexture'); - } - return this; - }; - /** - * Add binding - * @member {PIXI.BaseTexture} - * @override - */ - ArrayResource.prototype.bind = function (baseTexture) { - _super.prototype.bind.call(this, baseTexture); - baseTexture.target = exports.TARGETS.TEXTURE_2D_ARRAY; - }; - /** - * Upload the resources to the GPU. - * @param {PIXI.Renderer} renderer - * @param {PIXI.BaseTexture} texture - * @param {PIXI.GLTexture} glTexture - * @returns {boolean} whether texture was uploaded - */ - ArrayResource.prototype.upload = function (renderer, texture, glTexture) { - var _a = this, length = _a.length, itemDirtyIds = _a.itemDirtyIds, items = _a.items; - var gl = renderer.gl; - if (glTexture.dirtyId < 0) { - gl.texImage3D(gl.TEXTURE_2D_ARRAY, 0, texture.format, this._width, this._height, length, 0, texture.format, texture.type, null); - } - for (var i = 0; i < length; i++) { - var item = items[i]; - if (itemDirtyIds[i] < item.dirtyId) { - itemDirtyIds[i] = item.dirtyId; - if (item.valid) { - gl.texSubImage3D(gl.TEXTURE_2D_ARRAY, 0, 0, // xoffset - 0, // yoffset - i, // zoffset - item.resource.width, item.resource.height, 1, texture.format, texture.type, item.resource.source); - } - } - } - return true; - }; - return ArrayResource; - }(AbstractMultiResource)); - - /** - * Base for all the image/canvas resources - * @class - * @extends PIXI.resources.Resource - * @memberof PIXI.resources - */ - var BaseImageResource = /** @class */ (function (_super) { - __extends$2(BaseImageResource, _super); - /** - * @param {HTMLImageElement|HTMLCanvasElement|HTMLVideoElement|SVGElement} source - */ - function BaseImageResource(source) { - var _this = this; - var sourceAny = source; - var width = sourceAny.naturalWidth || sourceAny.videoWidth || sourceAny.width; - var height = sourceAny.naturalHeight || sourceAny.videoHeight || sourceAny.height; - _this = _super.call(this, width, height) || this; - /** - * The source element - * @member {HTMLImageElement|HTMLCanvasElement|HTMLVideoElement|SVGElement} - * @readonly - */ - _this.source = source; - /** - * If set to `true`, will force `texImage2D` over `texSubImage2D` for uploading. - * Certain types of media (e.g. video) using `texImage2D` is more performant. - * @member {boolean} - * @default false - * @private - */ - _this.noSubImage = false; - return _this; - } - /** - * Set cross origin based detecting the url and the crossorigin - * @protected - * @param {HTMLElement} element - Element to apply crossOrigin - * @param {string} url - URL to check - * @param {boolean|string} [crossorigin=true] - Cross origin value to use - */ - BaseImageResource.crossOrigin = function (element, url, crossorigin) { - if (crossorigin === undefined && url.indexOf('data:') !== 0) { - element.crossOrigin = determineCrossOrigin(url); - } - else if (crossorigin !== false) { - element.crossOrigin = typeof crossorigin === 'string' ? crossorigin : 'anonymous'; - } - }; - /** - * Upload the texture to the GPU. - * @param {PIXI.Renderer} renderer - Upload to the renderer - * @param {PIXI.BaseTexture} baseTexture - Reference to parent texture - * @param {PIXI.GLTexture} glTexture - * @param {HTMLImageElement|HTMLCanvasElement|HTMLVideoElement|SVGElement} [source] (optional) - * @returns {boolean} true is success - */ - BaseImageResource.prototype.upload = function (renderer, baseTexture, glTexture, source) { - var gl = renderer.gl; - var width = baseTexture.realWidth; - var height = baseTexture.realHeight; - source = source || this.source; - gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, baseTexture.alphaMode === exports.ALPHA_MODES.UNPACK); - if (!this.noSubImage - && baseTexture.target === gl.TEXTURE_2D - && glTexture.width === width - && glTexture.height === height) { - gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, baseTexture.format, baseTexture.type, source); - } - else { - glTexture.width = width; - glTexture.height = height; - gl.texImage2D(baseTexture.target, 0, baseTexture.format, baseTexture.format, baseTexture.type, source); - } - return true; - }; - /** - * Checks if source width/height was changed, resize can cause extra baseTexture update. - * Triggers one update in any case. - */ - BaseImageResource.prototype.update = function () { - if (this.destroyed) { - return; - } - var source = this.source; - var width = source.naturalWidth || source.videoWidth || source.width; - var height = source.naturalHeight || source.videoHeight || source.height; - this.resize(width, height); - _super.prototype.update.call(this); - }; - /** - * Destroy this BaseImageResource - * @override - */ - BaseImageResource.prototype.dispose = function () { - this.source = null; - }; - return BaseImageResource; - }(Resource)); - - /** - * @interface OffscreenCanvas - */ - /** - * Resource type for HTMLCanvasElement. - * @class - * @extends PIXI.resources.BaseImageResource - * @memberof PIXI.resources - * @param {HTMLCanvasElement} source - Canvas element to use - */ - var CanvasResource = /** @class */ (function (_super) { - __extends$2(CanvasResource, _super); - function CanvasResource() { - return _super !== null && _super.apply(this, arguments) || this; - } - /** - * Used to auto-detect the type of resource. - * - * @static - * @param {HTMLCanvasElement|OffscreenCanvas} source - The source object - * @return {boolean} `true` if source is HTMLCanvasElement or OffscreenCanvas - */ - CanvasResource.test = function (source) { - var OffscreenCanvas = window.OffscreenCanvas; - // Check for browsers that don't yet support OffscreenCanvas - if (OffscreenCanvas && source instanceof OffscreenCanvas) { - return true; - } - return source instanceof HTMLCanvasElement; - }; - return CanvasResource; - }(BaseImageResource)); - - /** - * Resource for a CubeTexture which contains six resources. - * - * @class - * @extends PIXI.resources.ArrayResource - * @memberof PIXI.resources - * @param {Array} [source] - Collection of URLs or resources - * to use as the sides of the cube. - * @param {object} [options] - ImageResource options - * @param {number} [options.width] - Width of resource - * @param {number} [options.height] - Height of resource - * @param {number} [options.autoLoad=true] - Whether to auto-load resources - * @param {number} [options.linkBaseTexture=true] - In case BaseTextures are supplied, - * whether to copy them or use - */ - var CubeResource = /** @class */ (function (_super) { - __extends$2(CubeResource, _super); - function CubeResource(source, options) { - var _this = this; - var _a = options || {}, width = _a.width, height = _a.height, autoLoad = _a.autoLoad, linkBaseTexture = _a.linkBaseTexture; - if (source && source.length !== CubeResource.SIDES) { - throw new Error("Invalid length. Got " + source.length + ", expected 6"); - } - _this = _super.call(this, 6, { width: width, height: height }) || this; - for (var i = 0; i < CubeResource.SIDES; i++) { - _this.items[i].target = exports.TARGETS.TEXTURE_CUBE_MAP_POSITIVE_X + i; - } - /** - * In case BaseTextures are supplied, whether to use same resource or bind baseTexture itself - * @member {boolean} - * @protected - */ - _this.linkBaseTexture = linkBaseTexture !== false; - if (source) { - _this.initFromArray(source, options); - } - if (autoLoad !== false) { - _this.load(); - } - return _this; - } - /** - * Add binding - * - * @override - * @param {PIXI.BaseTexture} baseTexture - parent base texture - */ - CubeResource.prototype.bind = function (baseTexture) { - _super.prototype.bind.call(this, baseTexture); - baseTexture.target = exports.TARGETS.TEXTURE_CUBE_MAP; - }; - CubeResource.prototype.addBaseTextureAt = function (baseTexture, index, linkBaseTexture) { - if (linkBaseTexture === undefined) { - linkBaseTexture = this.linkBaseTexture; - } - if (!this.items[index]) { - throw new Error("Index " + index + " is out of bounds"); - } - if (!this.linkBaseTexture - || baseTexture.parentTextureArray - || Object.keys(baseTexture._glTextures).length > 0) { - // copy mode - if (baseTexture.resource) { - this.addResourceAt(baseTexture.resource, index); - } - else { - throw new Error("CubeResource does not support copying of renderTexture."); - } - } - else { - // link mode, the difficult one! - baseTexture.target = exports.TARGETS.TEXTURE_CUBE_MAP_POSITIVE_X + index; - baseTexture.parentTextureArray = this.baseTexture; - this.items[index] = baseTexture; - } - if (baseTexture.valid && !this.valid) { - this.resize(baseTexture.realWidth, baseTexture.realHeight); - } - this.items[index] = baseTexture; - return this; - }; - /** - * Upload the resource - * - * @returns {boolean} true is success - */ - CubeResource.prototype.upload = function (renderer, _baseTexture, glTexture) { - var dirty = this.itemDirtyIds; - for (var i = 0; i < CubeResource.SIDES; i++) { - var side = this.items[i]; - if (dirty[i] < side.dirtyId) { - if (side.valid && side.resource) { - side.resource.upload(renderer, side, glTexture); - dirty[i] = side.dirtyId; - } - else if (dirty[i] < -1) { - // either item is not valid yet, either its a renderTexture - // allocate the memory - renderer.gl.texImage2D(side.target, 0, glTexture.internalFormat, _baseTexture.realWidth, _baseTexture.realHeight, 0, _baseTexture.format, glTexture.type, null); - dirty[i] = -1; - } - } - } - return true; - }; - /** - * Used to auto-detect the type of resource. - * - * @static - * @param {object} source - The source object - * @return {boolean} `true` if source is an array of 6 elements - */ - CubeResource.test = function (source) { - return Array.isArray(source) && source.length === CubeResource.SIDES; - }; - /** - * Number of texture sides to store for CubeResources - * - * @name PIXI.resources.CubeResource.SIDES - * @static - * @member {number} - * @default 6 - */ - CubeResource.SIDES = 6; - return CubeResource; - }(AbstractMultiResource)); - - /** - * Resource type for HTMLImageElement. - * @class - * @extends PIXI.resources.BaseImageResource - * @memberof PIXI.resources - */ - var ImageResource = /** @class */ (function (_super) { - __extends$2(ImageResource, _super); - /** - * @param {HTMLImageElement|string} source - image source or URL - * @param {object} [options] - * @param {boolean} [options.autoLoad=true] - start loading process - * @param {boolean} [options.createBitmap=PIXI.settings.CREATE_IMAGE_BITMAP] - whether its required to create - * a bitmap before upload - * @param {boolean} [options.crossorigin=true] - Load image using cross origin - * @param {PIXI.ALPHA_MODES} [options.alphaMode=PIXI.ALPHA_MODES.UNPACK] - Premultiply image alpha in bitmap - */ - function ImageResource(source, options) { - var _this = this; - options = options || {}; - if (!(source instanceof HTMLImageElement)) { - var imageElement = new Image(); - BaseImageResource.crossOrigin(imageElement, source, options.crossorigin); - imageElement.src = source; - source = imageElement; - } - _this = _super.call(this, source) || this; - // FireFox 68, and possibly other versions, seems like setting the HTMLImageElement#width and #height - // to non-zero values before its loading completes if images are in a cache. - // Because of this, need to set the `_width` and the `_height` to zero to avoid uploading incomplete images. - // Please refer to the issue #5968 (https://github.com/pixijs/pixi.js/issues/5968). - if (!source.complete && !!_this._width && !!_this._height) { - _this._width = 0; - _this._height = 0; - } - /** - * URL of the image source - * @member {string} - */ - _this.url = source.src; - /** - * When process is completed - * @member {Promise} - * @private - */ - _this._process = null; - /** - * If the image should be disposed after upload - * @member {boolean} - * @default false - */ - _this.preserveBitmap = false; - /** - * If capable, convert the image using createImageBitmap API - * @member {boolean} - * @default PIXI.settings.CREATE_IMAGE_BITMAP - */ - _this.createBitmap = (options.createBitmap !== undefined - ? options.createBitmap : settings.CREATE_IMAGE_BITMAP) && !!window.createImageBitmap; - /** - * Controls texture alphaMode field - * Copies from options - * Default is `null`, copies option from baseTexture - * - * @member {PIXI.ALPHA_MODES|null} - * @readonly - */ - _this.alphaMode = typeof options.alphaMode === 'number' ? options.alphaMode : null; - if (options.premultiplyAlpha !== undefined) { - // triggers deprecation - _this.premultiplyAlpha = options.premultiplyAlpha; - } - /** - * The ImageBitmap element created for HTMLImageElement - * @member {ImageBitmap} - * @default null - */ - _this.bitmap = null; - /** - * Promise when loading - * @member {Promise} - * @private - * @default null - */ - _this._load = null; - if (options.autoLoad !== false) { - _this.load(); - } - return _this; - } - /** - * returns a promise when image will be loaded and processed - * - * @param {boolean} [createBitmap] - whether process image into bitmap - * @returns {Promise} - */ - ImageResource.prototype.load = function (createBitmap) { - var _this = this; - if (this._load) { - return this._load; - } - if (createBitmap !== undefined) { - this.createBitmap = createBitmap; - } - this._load = new Promise(function (resolve, reject) { - var source = _this.source; - _this.url = source.src; - var completed = function () { - if (_this.destroyed) { - return; - } - source.onload = null; - source.onerror = null; - _this.resize(source.width, source.height); - _this._load = null; - if (_this.createBitmap) { - resolve(_this.process()); - } - else { - resolve(_this); - } - }; - if (source.complete && source.src) { - completed(); - } - else { - source.onload = completed; - source.onerror = function (event) { - // Avoids Promise freezing when resource broken - reject(event); - _this.onError.emit(event); - }; - } - }); - return this._load; - }; - /** - * Called when we need to convert image into BitmapImage. - * Can be called multiple times, real promise is cached inside. - * - * @returns {Promise} cached promise to fill that bitmap - */ - ImageResource.prototype.process = function () { - var _this = this; - var source = this.source; - if (this._process !== null) { - return this._process; - } - if (this.bitmap !== null || !window.createImageBitmap) { - return Promise.resolve(this); - } - this._process = window.createImageBitmap(source, 0, 0, source.width, source.height, { - premultiplyAlpha: this.alphaMode === exports.ALPHA_MODES.UNPACK ? 'premultiply' : 'none', - }) - .then(function (bitmap) { - if (_this.destroyed) { - return Promise.reject(); - } - _this.bitmap = bitmap; - _this.update(); - _this._process = null; - return Promise.resolve(_this); - }); - return this._process; - }; - /** - * Upload the image resource to GPU. - * - * @param {PIXI.Renderer} renderer - Renderer to upload to - * @param {PIXI.BaseTexture} baseTexture - BaseTexture for this resource - * @param {PIXI.GLTexture} glTexture - GLTexture to use - * @returns {boolean} true is success - */ - ImageResource.prototype.upload = function (renderer, baseTexture, glTexture) { - if (typeof this.alphaMode === 'number') { - // bitmap stores unpack premultiply flag, we dont have to notify texImage2D about it - baseTexture.alphaMode = this.alphaMode; - } - if (!this.createBitmap) { - return _super.prototype.upload.call(this, renderer, baseTexture, glTexture); - } - if (!this.bitmap) { - // yeah, ignore the output - this.process(); - if (!this.bitmap) { - return false; - } - } - _super.prototype.upload.call(this, renderer, baseTexture, glTexture, this.bitmap); - if (!this.preserveBitmap) { - // checks if there are other renderers that possibly need this bitmap - var flag = true; - var glTextures = baseTexture._glTextures; - for (var key in glTextures) { - var otherTex = glTextures[key]; - if (otherTex !== glTexture && otherTex.dirtyId !== baseTexture.dirtyId) { - flag = false; - break; - } - } - if (flag) { - if (this.bitmap.close) { - this.bitmap.close(); - } - this.bitmap = null; - } - } - return true; - }; - /** - * Destroys this texture - * @override - */ - ImageResource.prototype.dispose = function () { - this.source.onload = null; - this.source.onerror = null; - _super.prototype.dispose.call(this); - if (this.bitmap) { - this.bitmap.close(); - this.bitmap = null; - } - this._process = null; - this._load = null; - }; - /** - * Used to auto-detect the type of resource. - * - * @static - * @param {string|HTMLImageElement} source - The source object - * @return {boolean} `true` if source is string or HTMLImageElement - */ - ImageResource.test = function (source) { - return typeof source === 'string' || source instanceof HTMLImageElement; - }; - return ImageResource; - }(BaseImageResource)); - - /** - * Resource type for SVG elements and graphics. - * @class - * @extends PIXI.resources.BaseImageResource - * @memberof PIXI.resources - * @param {string} source - Base64 encoded SVG element or URL for SVG file. - * @param {object} [options] - Options to use - * @param {number} [options.scale=1] - Scale to apply to SVG. Overridden by... - * @param {number} [options.width] - Rasterize SVG this wide. Aspect ratio preserved if height not specified. - * @param {number} [options.height] - Rasterize SVG this high. Aspect ratio preserved if width not specified. - * @param {boolean} [options.autoLoad=true] - Start loading right away. - */ - var SVGResource = /** @class */ (function (_super) { - __extends$2(SVGResource, _super); - function SVGResource(sourceBase64, options) { - var _this = this; - options = options || {}; - _this = _super.call(this, document.createElement('canvas')) || this; - _this._width = 0; - _this._height = 0; - /** - * Base64 encoded SVG element or URL for SVG file - * @readonly - * @member {string} - */ - _this.svg = sourceBase64; - /** - * The source scale to apply when rasterizing on load - * @readonly - * @member {number} - */ - _this.scale = options.scale || 1; - /** - * A width override for rasterization on load - * @readonly - * @member {number} - */ - _this._overrideWidth = options.width; - /** - * A height override for rasterization on load - * @readonly - * @member {number} - */ - _this._overrideHeight = options.height; - /** - * Call when completely loaded - * @private - * @member {function} - */ - _this._resolve = null; - /** - * Cross origin value to use - * @private - * @member {boolean|string} - */ - _this._crossorigin = options.crossorigin; - /** - * Promise when loading - * @member {Promise} - * @private - * @default null - */ - _this._load = null; - if (options.autoLoad !== false) { - _this.load(); - } - return _this; - } - SVGResource.prototype.load = function () { - var _this = this; - if (this._load) { - return this._load; - } - this._load = new Promise(function (resolve) { - // Save this until after load is finished - _this._resolve = function () { - _this.resize(_this.source.width, _this.source.height); - resolve(_this); - }; - // Convert SVG inline string to data-uri - if ((/^\]*(?:\s(width|height)=('|")(\d*(?:\.\d+)?)(?:px)?('|"))[^>]*(?:\s(width|height)=('|")(\d*(?:\.\d+)?)(?:px)?('|"))[^>]*>/i; // eslint-disable-line max-len - return SVGResource; - }(BaseImageResource)); - - /** - * Resource type for HTMLVideoElement. - * @class - * @extends PIXI.resources.BaseImageResource - * @memberof PIXI.resources - * @param {HTMLVideoElement|object|string|Array} source - Video element to use. - * @param {object} [options] - Options to use - * @param {boolean} [options.autoLoad=true] - Start loading the video immediately - * @param {boolean} [options.autoPlay=true] - Start playing video immediately - * @param {number} [options.updateFPS=0] - How many times a second to update the texture from the video. - * Leave at 0 to update at every render. - * @param {boolean} [options.crossorigin=true] - Load image using cross origin - */ - var VideoResource = /** @class */ (function (_super) { - __extends$2(VideoResource, _super); - function VideoResource(source, options) { - var _this = this; - options = options || {}; - if (!(source instanceof HTMLVideoElement)) { - var videoElement = document.createElement('video'); - // workaround for https://github.com/pixijs/pixi.js/issues/5996 - videoElement.setAttribute('preload', 'auto'); - videoElement.setAttribute('webkit-playsinline', ''); - videoElement.setAttribute('playsinline', ''); - if (typeof source === 'string') { - source = [source]; - } - var firstSrc = source[0].src || source[0]; - BaseImageResource.crossOrigin(videoElement, firstSrc, options.crossorigin); - // array of objects or strings - for (var i = 0; i < source.length; ++i) { - var sourceElement = document.createElement('source'); - var _a = source[i], src = _a.src, mime = _a.mime; - src = src || source[i]; - var baseSrc = src.split('?').shift().toLowerCase(); - var ext = baseSrc.substr(baseSrc.lastIndexOf('.') + 1); - mime = mime || VideoResource.MIME_TYPES[ext] || "video/" + ext; - sourceElement.src = src; - sourceElement.type = mime; - videoElement.appendChild(sourceElement); - } - // Override the source - source = videoElement; - } - _this = _super.call(this, source) || this; - _this.noSubImage = true; - /** - * `true` to use PIXI.Ticker.shared to auto update the base texture. - * - * @type {boolean} - * @default true - * @private - */ - _this._autoUpdate = true; - /** - * `true` if the instance is currently connected to PIXI.Ticker.shared to auto update the base texture. - * - * @type {boolean} - * @default false - * @private - */ - _this._isConnectedToTicker = false; - _this._updateFPS = options.updateFPS || 0; - _this._msToNextUpdate = 0; - /** - * When set to true will automatically play videos used by this texture once - * they are loaded. If false, it will not modify the playing state. - * - * @member {boolean} - * @default true - */ - _this.autoPlay = options.autoPlay !== false; - /** - * Promise when loading - * @member {Promise} - * @private - * @default null - */ - _this._load = null; - /** - * Callback when completed with load. - * @member {function} - * @private - */ - _this._resolve = null; - // Bind for listeners - _this._onCanPlay = _this._onCanPlay.bind(_this); - _this._onError = _this._onError.bind(_this); - if (options.autoLoad !== false) { - _this.load(); - } - return _this; - } - /** - * Trigger updating of the texture - * - * @param {number} [deltaTime=0] - time delta since last tick - */ - VideoResource.prototype.update = function (_deltaTime) { - if (_deltaTime === void 0) { _deltaTime = 0; } - if (!this.destroyed) { - // account for if video has had its playbackRate changed - var elapsedMS = Ticker.shared.elapsedMS * this.source.playbackRate; - this._msToNextUpdate = Math.floor(this._msToNextUpdate - elapsedMS); - if (!this._updateFPS || this._msToNextUpdate <= 0) { - _super.prototype.update.call(this); - this._msToNextUpdate = this._updateFPS ? Math.floor(1000 / this._updateFPS) : 0; - } - } - }; - /** - * Start preloading the video resource. - * - * @protected - * @return {Promise} Handle the validate event - */ - VideoResource.prototype.load = function () { - var _this = this; - if (this._load) { - return this._load; - } - var source = this.source; - if ((source.readyState === source.HAVE_ENOUGH_DATA || source.readyState === source.HAVE_FUTURE_DATA) - && source.width && source.height) { - source.complete = true; - } - source.addEventListener('play', this._onPlayStart.bind(this)); - source.addEventListener('pause', this._onPlayStop.bind(this)); - if (!this._isSourceReady()) { - source.addEventListener('canplay', this._onCanPlay); - source.addEventListener('canplaythrough', this._onCanPlay); - source.addEventListener('error', this._onError, true); - } - else { - this._onCanPlay(); - } - this._load = new Promise(function (resolve) { - if (_this.valid) { - resolve(_this); - } - else { - _this._resolve = resolve; - source.load(); - } - }); - return this._load; - }; - /** - * Handle video error events. - * - * @private - */ - VideoResource.prototype._onError = function (event) { - this.source.removeEventListener('error', this._onError, true); - this.onError.emit(event); - }; - /** - * Returns true if the underlying source is playing. - * - * @private - * @return {boolean} True if playing. - */ - VideoResource.prototype._isSourcePlaying = function () { - var source = this.source; - return (source.currentTime > 0 && source.paused === false && source.ended === false && source.readyState > 2); - }; - /** - * Returns true if the underlying source is ready for playing. - * - * @private - * @return {boolean} True if ready. - */ - VideoResource.prototype._isSourceReady = function () { - var source = this.source; - return source.readyState === 3 || source.readyState === 4; - }; - /** - * Runs the update loop when the video is ready to play - * - * @private - */ - VideoResource.prototype._onPlayStart = function () { - // Just in case the video has not received its can play even yet.. - if (!this.valid) { - this._onCanPlay(); - } - if (this.autoUpdate && !this._isConnectedToTicker) { - Ticker.shared.add(this.update, this); - this._isConnectedToTicker = true; - } - }; - /** - * Fired when a pause event is triggered, stops the update loop - * - * @private - */ - VideoResource.prototype._onPlayStop = function () { - if (this._isConnectedToTicker) { - Ticker.shared.remove(this.update, this); - this._isConnectedToTicker = false; - } - }; - /** - * Fired when the video is loaded and ready to play - * - * @private - */ - VideoResource.prototype._onCanPlay = function () { - var source = this.source; - source.removeEventListener('canplay', this._onCanPlay); - source.removeEventListener('canplaythrough', this._onCanPlay); - var valid = this.valid; - this.resize(source.videoWidth, source.videoHeight); - // prevent multiple loaded dispatches.. - if (!valid && this._resolve) { - this._resolve(this); - this._resolve = null; - } - if (this._isSourcePlaying()) { - this._onPlayStart(); - } - else if (this.autoPlay) { - source.play(); - } - }; - /** - * Destroys this texture - * @override - */ - VideoResource.prototype.dispose = function () { - if (this._isConnectedToTicker) { - Ticker.shared.remove(this.update, this); - } - var source = this.source; - if (source) { - source.removeEventListener('error', this._onError, true); - source.pause(); - source.src = ''; - source.load(); - } - _super.prototype.dispose.call(this); - }; - Object.defineProperty(VideoResource.prototype, "autoUpdate", { - /** - * Should the base texture automatically update itself, set to true by default - * - * @member {boolean} - */ - get: function () { - return this._autoUpdate; - }, - set: function (value) { - if (value !== this._autoUpdate) { - this._autoUpdate = value; - if (!this._autoUpdate && this._isConnectedToTicker) { - Ticker.shared.remove(this.update, this); - this._isConnectedToTicker = false; - } - else if (this._autoUpdate && !this._isConnectedToTicker && this._isSourcePlaying()) { - Ticker.shared.add(this.update, this); - this._isConnectedToTicker = true; - } - } - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(VideoResource.prototype, "updateFPS", { - /** - * How many times a second to update the texture from the video. Leave at 0 to update at every render. - * A lower fps can help performance, as updating the texture at 60fps on a 30ps video may not be efficient. - * - * @member {number} - */ - get: function () { - return this._updateFPS; - }, - set: function (value) { - if (value !== this._updateFPS) { - this._updateFPS = value; - } - }, - enumerable: false, - configurable: true - }); - /** - * Used to auto-detect the type of resource. - * - * @static - * @param {*} source - The source object - * @param {string} extension - The extension of source, if set - * @return {boolean} `true` if video source - */ - VideoResource.test = function (source, extension) { - return (source instanceof HTMLVideoElement) - || VideoResource.TYPES.indexOf(extension) > -1; - }; - /** - * List of common video file extensions supported by VideoResource. - * @constant - * @member {Array} - * @static - * @readonly - */ - VideoResource.TYPES = ['mp4', 'm4v', 'webm', 'ogg', 'ogv', 'h264', 'avi', 'mov']; - /** - * Map of video MIME types that can't be directly derived from file extensions. - * @constant - * @member {object} - * @static - * @readonly - */ - VideoResource.MIME_TYPES = { - ogv: 'video/ogg', - mov: 'video/quicktime', - m4v: 'video/mp4', - }; - return VideoResource; - }(BaseImageResource)); - - /** - * Resource type for ImageBitmap. - * @class - * @extends PIXI.resources.BaseImageResource - * @memberof PIXI.resources - * @param {ImageBitmap} source - Image element to use - */ - var ImageBitmapResource = /** @class */ (function (_super) { - __extends$2(ImageBitmapResource, _super); - function ImageBitmapResource() { - return _super !== null && _super.apply(this, arguments) || this; - } - /** - * Used to auto-detect the type of resource. - * - * @static - * @param {ImageBitmap} source - The source object - * @return {boolean} `true` if source is an ImageBitmap - */ - ImageBitmapResource.test = function (source) { - return !!window.createImageBitmap && source instanceof ImageBitmap; - }; - return ImageBitmapResource; - }(BaseImageResource)); - - INSTALLED.push(ImageResource, ImageBitmapResource, CanvasResource, VideoResource, SVGResource, BufferResource, CubeResource, ArrayResource); - - var index = ({ - Resource: Resource, - BaseImageResource: BaseImageResource, - INSTALLED: INSTALLED, - autoDetectResource: autoDetectResource, - AbstractMultiResource: AbstractMultiResource, - ArrayResource: ArrayResource, - BufferResource: BufferResource, - CanvasResource: CanvasResource, - CubeResource: CubeResource, - ImageResource: ImageResource, - SVGResource: SVGResource, - VideoResource: VideoResource, - ImageBitmapResource: ImageBitmapResource - }); - - /** - * System is a base class used for extending systems used by the {@link PIXI.Renderer} - * - * @see PIXI.Renderer#addSystem - * @class - * @memberof PIXI - */ - var System = /** @class */ (function () { - /** - * @param {PIXI.Renderer} renderer - The renderer this manager works for. - */ - function System(renderer) { - /** - * The renderer this manager works for. - * - * @member {PIXI.Renderer} - */ - this.renderer = renderer; - } - /** - * Generic destroy methods to be overridden by the subclass - */ - System.prototype.destroy = function () { - this.renderer = null; - }; - return System; - }()); - - /** - * Resource type for DepthTexture. - * @class - * @extends PIXI.resources.BufferResource - * @memberof PIXI.resources - */ - var DepthResource = /** @class */ (function (_super) { - __extends$2(DepthResource, _super); - function DepthResource() { - return _super !== null && _super.apply(this, arguments) || this; - } - /** - * Upload the texture to the GPU. - * @param {PIXI.Renderer} renderer - Upload to the renderer - * @param {PIXI.BaseTexture} baseTexture - Reference to parent texture - * @param {PIXI.GLTexture} glTexture - glTexture - * @returns {boolean} true is success - */ - DepthResource.prototype.upload = function (renderer, baseTexture, glTexture) { - var gl = renderer.gl; - gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, baseTexture.alphaMode === exports.ALPHA_MODES.UNPACK); - if (glTexture.width === baseTexture.width && glTexture.height === baseTexture.height) { - gl.texSubImage2D(baseTexture.target, 0, 0, 0, baseTexture.width, baseTexture.height, baseTexture.format, baseTexture.type, this.data); - } - else { - glTexture.width = baseTexture.width; - glTexture.height = baseTexture.height; - gl.texImage2D(baseTexture.target, 0, - // gl.DEPTH_COMPONENT16 Needed for depth to render properly in webgl2.0 - renderer.context.webGLVersion === 1 ? gl.DEPTH_COMPONENT : gl.DEPTH_COMPONENT16, baseTexture.width, baseTexture.height, 0, baseTexture.format, baseTexture.type, this.data); - } - return true; - }; - return DepthResource; - }(BufferResource)); - - /** - * Frame buffer used by the BaseRenderTexture - * - * @class - * @memberof PIXI - */ - var Framebuffer = /** @class */ (function () { - /** - * @param {number} width - Width of the frame buffer - * @param {number} height - Height of the frame buffer - */ - function Framebuffer(width, height) { - /** - * Width of framebuffer in pixels - * @member {number} - */ - this.width = Math.ceil(width || 100); - /** - * Height of framebuffer in pixels - * @member {number} - */ - this.height = Math.ceil(height || 100); - this.stencil = false; - this.depth = false; - this.dirtyId = 0; - this.dirtyFormat = 0; - this.dirtySize = 0; - this.depthTexture = null; - this.colorTextures = []; - this.glFramebuffers = {}; - this.disposeRunner = new Runner('disposeFramebuffer'); - /** - * Desired number of samples for antialiasing. 0 means AA should not be used. - * - * Experimental WebGL2 feature, allows to use antialiasing in individual renderTextures. - * Antialiasing is the same as for main buffer with renderer `antialias:true` options. - * Seriously affects GPU memory consumption and GPU performance. - * - *```js - * renderTexture.framebuffer.multisample = PIXI.MSAA_QUALITY.HIGH; - * //... - * renderer.render(renderTexture, myContainer); - * renderer.framebuffer.blit(); // copies data from MSAA framebuffer to texture - * ``` - * - * @member {PIXI.MSAA_QUALITY} - * @default PIXI.MSAA_QUALITY.NONE - */ - this.multisample = exports.MSAA_QUALITY.NONE; - } - Object.defineProperty(Framebuffer.prototype, "colorTexture", { - /** - * Reference to the colorTexture. - * - * @member {PIXI.BaseTexture[]} - * @readonly - */ - get: function () { - return this.colorTextures[0]; - }, - enumerable: false, - configurable: true - }); - /** - * Add texture to the colorTexture array - * - * @param {number} [index=0] - Index of the array to add the texture to - * @param {PIXI.BaseTexture} [texture] - Texture to add to the array - */ - Framebuffer.prototype.addColorTexture = function (index, texture) { - if (index === void 0) { index = 0; } - // TODO add some validation to the texture - same width / height etc? - this.colorTextures[index] = texture || new BaseTexture(null, { - scaleMode: exports.SCALE_MODES.NEAREST, - resolution: 1, - mipmap: exports.MIPMAP_MODES.OFF, - width: this.width, - height: this.height, - }); - this.dirtyId++; - this.dirtyFormat++; - return this; - }; - /** - * Add a depth texture to the frame buffer - * - * @param {PIXI.BaseTexture} [texture] - Texture to add - */ - Framebuffer.prototype.addDepthTexture = function (texture) { - /* eslint-disable max-len */ - this.depthTexture = texture || new BaseTexture(new DepthResource(null, { width: this.width, height: this.height }), { - scaleMode: exports.SCALE_MODES.NEAREST, - resolution: 1, - width: this.width, - height: this.height, - mipmap: exports.MIPMAP_MODES.OFF, - format: exports.FORMATS.DEPTH_COMPONENT, - type: exports.TYPES.UNSIGNED_SHORT, - }); - this.dirtyId++; - this.dirtyFormat++; - return this; - }; - /** - * Enable depth on the frame buffer - */ - Framebuffer.prototype.enableDepth = function () { - this.depth = true; - this.dirtyId++; - this.dirtyFormat++; - return this; - }; - /** - * Enable stencil on the frame buffer - */ - Framebuffer.prototype.enableStencil = function () { - this.stencil = true; - this.dirtyId++; - this.dirtyFormat++; - return this; - }; - /** - * Resize the frame buffer - * - * @param {number} width - Width of the frame buffer to resize to - * @param {number} height - Height of the frame buffer to resize to - */ - Framebuffer.prototype.resize = function (width, height) { - width = Math.ceil(width); - height = Math.ceil(height); - if (width === this.width && height === this.height) - { return; } - this.width = width; - this.height = height; - this.dirtyId++; - this.dirtySize++; - for (var i = 0; i < this.colorTextures.length; i++) { - var texture = this.colorTextures[i]; - var resolution = texture.resolution; - // take into acount the fact the texture may have a different resolution.. - texture.setSize(width / resolution, height / resolution); - } - if (this.depthTexture) { - var resolution = this.depthTexture.resolution; - this.depthTexture.setSize(width / resolution, height / resolution); - } - }; - /** - * Disposes WebGL resources that are connected to this geometry - */ - Framebuffer.prototype.dispose = function () { - this.disposeRunner.emit(this, false); - }; - /** - * Destroys and removes the depth texture added to this framebuffer. - */ - Framebuffer.prototype.destroyDepthTexture = function () { - if (this.depthTexture) { - this.depthTexture.destroy(); - this.depthTexture = null; - ++this.dirtyId; - ++this.dirtyFormat; - } - }; - return Framebuffer; - }()); - - /** - * A BaseRenderTexture is a special texture that allows any PixiJS display object to be rendered to it. - * - * __Hint__: All DisplayObjects (i.e. Sprites) that render to a BaseRenderTexture should be preloaded - * otherwise black rectangles will be drawn instead. - * - * A BaseRenderTexture takes a snapshot of any Display Object given to its render method. The position - * and rotation of the given Display Objects is ignored. For example: - * - * ```js - * let renderer = PIXI.autoDetectRenderer(); - * let baseRenderTexture = new PIXI.BaseRenderTexture({ width: 800, height: 600 }); - * let renderTexture = new PIXI.RenderTexture(baseRenderTexture); - * let sprite = PIXI.Sprite.from("spinObj_01.png"); - * - * sprite.position.x = 800/2; - * sprite.position.y = 600/2; - * sprite.anchor.x = 0.5; - * sprite.anchor.y = 0.5; - * - * renderer.render(sprite, renderTexture); - * ``` - * - * The Sprite in this case will be rendered using its local transform. To render this sprite at 0,0 - * you can clear the transform - * - * ```js - * - * sprite.setTransform() - * - * let baseRenderTexture = new PIXI.BaseRenderTexture({ width: 100, height: 100 }); - * let renderTexture = new PIXI.RenderTexture(baseRenderTexture); - * - * renderer.render(sprite, renderTexture); // Renders to center of RenderTexture - * ``` - * - * @class - * @extends PIXI.BaseTexture - * @memberof PIXI - */ - var BaseRenderTexture = /** @class */ (function (_super) { - __extends$2(BaseRenderTexture, _super); - /** - * @param {object} [options] - * @param {number} [options.width=100] - The width of the base render texture. - * @param {number} [options.height=100] - The height of the base render texture. - * @param {PIXI.SCALE_MODES} [options.scaleMode] - See {@link PIXI.SCALE_MODES} for possible values. - * @param {number} [options.resolution=1] - The resolution / device pixel ratio of the texture being generated. - */ - function BaseRenderTexture(options) { - var _this = this; - if (typeof options === 'number') { - /* eslint-disable prefer-rest-params */ - // Backward compatibility of signature - var width_1 = arguments[0]; - var height_1 = arguments[1]; - var scaleMode = arguments[2]; - var resolution = arguments[3]; - options = { width: width_1, height: height_1, scaleMode: scaleMode, resolution: resolution }; - /* eslint-enable prefer-rest-params */ - } - _this = _super.call(this, null, options) || this; - var _a = options || {}, width = _a.width, height = _a.height; - // Set defaults - _this.mipmap = 0; - _this.width = Math.ceil(width) || 100; - _this.height = Math.ceil(height) || 100; - _this.valid = true; - _this.clearColor = [0, 0, 0, 0]; - _this.framebuffer = new Framebuffer(_this.width * _this.resolution, _this.height * _this.resolution) - .addColorTexture(0, _this); - // TODO - could this be added the systems? - /** - * The data structure for the stencil masks. - * - * @member {PIXI.MaskData[]} - */ - _this.maskStack = []; - /** - * The data structure for the filters. - * - * @member {Object[]} - */ - _this.filterStack = [{}]; - return _this; - } - /** - * Resizes the BaseRenderTexture. - * - * @param {number} width - The width to resize to. - * @param {number} height - The height to resize to. - */ - BaseRenderTexture.prototype.resize = function (width, height) { - width = Math.ceil(width); - height = Math.ceil(height); - this.framebuffer.resize(width * this.resolution, height * this.resolution); - }; - /** - * Frees the texture and framebuffer from WebGL memory without destroying this texture object. - * This means you can still use the texture later which will upload it to GPU - * memory again. - * - * @fires PIXI.BaseTexture#dispose - */ - BaseRenderTexture.prototype.dispose = function () { - this.framebuffer.dispose(); - _super.prototype.dispose.call(this); - }; - /** - * Destroys this texture. - */ - BaseRenderTexture.prototype.destroy = function () { - _super.prototype.destroy.call(this); - this.framebuffer.destroyDepthTexture(); - this.framebuffer = null; - }; - return BaseRenderTexture; - }(BaseTexture)); - - /** - * Stores a texture's frame in UV coordinates, in - * which everything lies in the rectangle `[(0,0), (1,0), - * (1,1), (0,1)]`. - * - * | Corner | Coordinates | - * |--------------|-------------| - * | Top-Left | `(x0,y0)` | - * | Top-Right | `(x1,y1)` | - * | Bottom-Right | `(x2,y2)` | - * | Bottom-Left | `(x3,y3)` | - * - * @class - * @protected - * @memberof PIXI - */ - var TextureUvs = /** @class */ (function () { - function TextureUvs() { - /** - * X-component of top-left corner `(x0,y0)`. - * - * @member {number} - */ - this.x0 = 0; - /** - * Y-component of top-left corner `(x0,y0)`. - * - * @member {number} - */ - this.y0 = 0; - /** - * X-component of top-right corner `(x1,y1)`. - * - * @member {number} - */ - this.x1 = 1; - /** - * Y-component of top-right corner `(x1,y1)`. - * - * @member {number} - */ - this.y1 = 0; - /** - * X-component of bottom-right corner `(x2,y2)`. - * - * @member {number} - */ - this.x2 = 1; - /** - * Y-component of bottom-right corner `(x2,y2)`. - * - * @member {number} - */ - this.y2 = 1; - /** - * X-component of bottom-left corner `(x3,y3)`. - * - * @member {number} - */ - this.x3 = 0; - /** - * Y-component of bottom-right corner `(x3,y3)`. - * - * @member {number} - */ - this.y3 = 1; - this.uvsFloat32 = new Float32Array(8); - } - /** - * Sets the texture Uvs based on the given frame information. - * - * @protected - * @param {PIXI.Rectangle} frame - The frame of the texture - * @param {PIXI.Rectangle} baseFrame - The base frame of the texture - * @param {number} rotate - Rotation of frame, see {@link PIXI.groupD8} - */ - TextureUvs.prototype.set = function (frame, baseFrame, rotate) { - var tw = baseFrame.width; - var th = baseFrame.height; - if (rotate) { - // width and height div 2 div baseFrame size - var w2 = frame.width / 2 / tw; - var h2 = frame.height / 2 / th; - // coordinates of center - var cX = (frame.x / tw) + w2; - var cY = (frame.y / th) + h2; - rotate = groupD8.add(rotate, groupD8.NW); // NW is top-left corner - this.x0 = cX + (w2 * groupD8.uX(rotate)); - this.y0 = cY + (h2 * groupD8.uY(rotate)); - rotate = groupD8.add(rotate, 2); // rotate 90 degrees clockwise - this.x1 = cX + (w2 * groupD8.uX(rotate)); - this.y1 = cY + (h2 * groupD8.uY(rotate)); - rotate = groupD8.add(rotate, 2); - this.x2 = cX + (w2 * groupD8.uX(rotate)); - this.y2 = cY + (h2 * groupD8.uY(rotate)); - rotate = groupD8.add(rotate, 2); - this.x3 = cX + (w2 * groupD8.uX(rotate)); - this.y3 = cY + (h2 * groupD8.uY(rotate)); - } - else { - this.x0 = frame.x / tw; - this.y0 = frame.y / th; - this.x1 = (frame.x + frame.width) / tw; - this.y1 = frame.y / th; - this.x2 = (frame.x + frame.width) / tw; - this.y2 = (frame.y + frame.height) / th; - this.x3 = frame.x / tw; - this.y3 = (frame.y + frame.height) / th; - } - this.uvsFloat32[0] = this.x0; - this.uvsFloat32[1] = this.y0; - this.uvsFloat32[2] = this.x1; - this.uvsFloat32[3] = this.y1; - this.uvsFloat32[4] = this.x2; - this.uvsFloat32[5] = this.y2; - this.uvsFloat32[6] = this.x3; - this.uvsFloat32[7] = this.y3; - }; - return TextureUvs; - }()); - - var DEFAULT_UVS = new TextureUvs(); - /** - * A texture stores the information that represents an image or part of an image. - * - * It cannot be added to the display list directly; instead use it as the texture for a Sprite. - * If no frame is provided for a texture, then the whole image is used. - * - * You can directly create a texture from an image and then reuse it multiple times like this : - * - * ```js - * let texture = PIXI.Texture.from('assets/image.png'); - * let sprite1 = new PIXI.Sprite(texture); - * let sprite2 = new PIXI.Sprite(texture); - * ``` - * - * If you didnt pass the texture frame to constructor, it enables `noFrame` mode: - * it subscribes on baseTexture events, it automatically resizes at the same time as baseTexture. - * - * Textures made from SVGs, loaded or not, cannot be used before the file finishes processing. - * You can check for this by checking the sprite's _textureID property. - * ```js - * var texture = PIXI.Texture.from('assets/image.svg'); - * var sprite1 = new PIXI.Sprite(texture); - * //sprite1._textureID should not be undefined if the texture has finished processing the SVG file - * ``` - * You can use a ticker or rAF to ensure your sprites load the finished textures after processing. See issue #3068. - * - * @class - * @extends PIXI.utils.EventEmitter - * @memberof PIXI - */ - var Texture = /** @class */ (function (_super) { - __extends$2(Texture, _super); - /** - * @param {PIXI.BaseTexture} baseTexture - The base texture source to create the texture from - * @param {PIXI.Rectangle} [frame] - The rectangle frame of the texture to show - * @param {PIXI.Rectangle} [orig] - The area of original texture - * @param {PIXI.Rectangle} [trim] - Trimmed rectangle of original texture - * @param {number} [rotate] - indicates how the texture was rotated by texture packer. See {@link PIXI.groupD8} - * @param {PIXI.IPointData} [anchor] - Default anchor point used for sprite placement / rotation - */ - function Texture(baseTexture, frame, orig, trim, rotate, anchor) { - var _this = _super.call(this) || this; - /** - * Does this Texture have any frame data assigned to it? - * - * This mode is enabled automatically if no frame was passed inside constructor. - * - * In this mode texture is subscribed to baseTexture events, and fires `update` on any change. - * - * Beware, after loading or resize of baseTexture event can fired two times! - * If you want more control, subscribe on baseTexture itself. - * - * ```js - * texture.on('update', () => {}); - * ``` - * - * Any assignment of `frame` switches off `noFrame` mode. - * - * @member {boolean} - */ - _this.noFrame = false; - if (!frame) { - _this.noFrame = true; - frame = new Rectangle(0, 0, 1, 1); - } - if (baseTexture instanceof Texture) { - baseTexture = baseTexture.baseTexture; - } - /** - * The base texture that this texture uses. - * - * @member {PIXI.BaseTexture} - */ - _this.baseTexture = baseTexture; - /** - * This is the area of the BaseTexture image to actually copy to the Canvas / WebGL when rendering, - * irrespective of the actual frame size or placement (which can be influenced by trimmed texture atlases) - * - * @member {PIXI.Rectangle} - */ - _this._frame = frame; - /** - * This is the trimmed area of original texture, before it was put in atlas - * Please call `updateUvs()` after you change coordinates of `trim` manually. - * - * @member {PIXI.Rectangle} - */ - _this.trim = trim; - /** - * This will let the renderer know if the texture is valid. If it's not then it cannot be rendered. - * - * @member {boolean} - */ - _this.valid = false; - /** - * The WebGL UV data cache. Can be used as quad UV - * - * @member {PIXI.TextureUvs} - * @protected - */ - _this._uvs = DEFAULT_UVS; - /** - * Default TextureMatrix instance for this texture - * By default that object is not created because its heavy - * - * @member {PIXI.TextureMatrix} - */ - _this.uvMatrix = null; - /** - * This is the area of original texture, before it was put in atlas - * - * @member {PIXI.Rectangle} - */ - _this.orig = orig || frame; // new Rectangle(0, 0, 1, 1); - _this._rotate = Number(rotate || 0); - if (rotate === true) { - // this is old texturepacker legacy, some games/libraries are passing "true" for rotated textures - _this._rotate = 2; - } - else if (_this._rotate % 2 !== 0) { - throw new Error('attempt to use diamond-shaped UVs. If you are sure, set rotation manually'); - } - /** - * Anchor point that is used as default if sprite is created with this texture. - * Changing the `defaultAnchor` at a later point of time will not update Sprite's anchor point. - * @member {PIXI.Point} - * @default {0,0} - */ - _this.defaultAnchor = anchor ? new Point(anchor.x, anchor.y) : new Point(0, 0); - /** - * Update ID is observed by sprites and TextureMatrix instances. - * Call updateUvs() to increment it. - * - * @member {number} - * @protected - */ - _this._updateID = 0; - /** - * The ids under which this Texture has been added to the texture cache. This is - * automatically set as long as Texture.addToCache is used, but may not be set if a - * Texture is added directly to the TextureCache array. - * - * @member {string[]} - */ - _this.textureCacheIds = []; - if (!baseTexture.valid) { - baseTexture.once('loaded', _this.onBaseTextureUpdated, _this); - } - else if (_this.noFrame) { - // if there is no frame we should monitor for any base texture changes.. - if (baseTexture.valid) { - _this.onBaseTextureUpdated(baseTexture); - } - } - else { - _this.frame = frame; - } - if (_this.noFrame) { - baseTexture.on('update', _this.onBaseTextureUpdated, _this); - } - return _this; - } - /** - * Updates this texture on the gpu. - * - * Calls the TextureResource update. - * - * If you adjusted `frame` manually, please call `updateUvs()` instead. - * - */ - Texture.prototype.update = function () { - if (this.baseTexture.resource) { - this.baseTexture.resource.update(); - } - }; - /** - * Called when the base texture is updated - * - * @protected - * @param {PIXI.BaseTexture} baseTexture - The base texture. - */ - Texture.prototype.onBaseTextureUpdated = function (baseTexture) { - if (this.noFrame) { - if (!this.baseTexture.valid) { - return; - } - this._frame.width = baseTexture.width; - this._frame.height = baseTexture.height; - this.valid = true; - this.updateUvs(); - } - else { - // TODO this code looks confusing.. boo to abusing getters and setters! - // if user gave us frame that has bigger size than resized texture it can be a problem - this.frame = this._frame; - } - this.emit('update', this); - }; - /** - * Destroys this texture - * - * @param {boolean} [destroyBase=false] - Whether to destroy the base texture as well - */ - Texture.prototype.destroy = function (destroyBase) { - if (this.baseTexture) { - if (destroyBase) { - var resource = this.baseTexture; - // delete the texture if it exists in the texture cache.. - // this only needs to be removed if the base texture is actually destroyed too.. - if (resource && resource.url && TextureCache[resource.url]) { - Texture.removeFromCache(resource.url); - } - this.baseTexture.destroy(); - } - this.baseTexture.off('loaded', this.onBaseTextureUpdated, this); - this.baseTexture.off('update', this.onBaseTextureUpdated, this); - this.baseTexture = null; - } - this._frame = null; - this._uvs = null; - this.trim = null; - this.orig = null; - this.valid = false; - Texture.removeFromCache(this); - this.textureCacheIds = null; - }; - /** - * Creates a new texture object that acts the same as this one. - * - * @return {PIXI.Texture} The new texture - */ - Texture.prototype.clone = function () { - return new Texture(this.baseTexture, this.frame.clone(), this.orig.clone(), this.trim && this.trim.clone(), this.rotate, this.defaultAnchor); - }; - /** - * Updates the internal WebGL UV cache. Use it after you change `frame` or `trim` of the texture. - * Call it after changing the frame - */ - Texture.prototype.updateUvs = function () { - if (this._uvs === DEFAULT_UVS) { - this._uvs = new TextureUvs(); - } - this._uvs.set(this._frame, this.baseTexture, this.rotate); - this._updateID++; - }; - /** - * Helper function that creates a new Texture based on the source you provide. - * The source can be - frame id, image url, video url, canvas element, video element, base texture - * - * @static - * @param {string|HTMLImageElement|HTMLCanvasElement|HTMLVideoElement|PIXI.BaseTexture} source - * Source to create texture from - * @param {object} [options] See {@link PIXI.BaseTexture}'s constructor for options. - * @param {boolean} [strict] - Enforce strict-mode, see {@link PIXI.settings.STRICT_TEXTURE_CACHE}. - * @return {PIXI.Texture} The newly created texture - */ - Texture.from = function (source, options, strict) { - if (options === void 0) { options = {}; } - if (strict === void 0) { strict = settings.STRICT_TEXTURE_CACHE; } - var isFrame = typeof source === 'string'; - var cacheId = null; - if (isFrame) { - cacheId = source; - } - else { - if (!source._pixiId) { - source._pixiId = "pixiid_" + uid(); - } - cacheId = source._pixiId; - } - var texture = TextureCache[cacheId]; - // Strict-mode rejects invalid cacheIds - if (isFrame && strict && !texture) { - throw new Error("The cacheId \"" + cacheId + "\" does not exist in TextureCache."); - } - if (!texture) { - if (!options.resolution) { - options.resolution = getResolutionOfUrl(source); - } - texture = new Texture(new BaseTexture(source, options)); - texture.baseTexture.cacheId = cacheId; - BaseTexture.addToCache(texture.baseTexture, cacheId); - Texture.addToCache(texture, cacheId); - } - // lets assume its a base texture! - return texture; - }; - /** - * Useful for loading textures via URLs. Use instead of `Texture.from` because - * it does a better job of handling failed URLs more effectively. This also ignores - * `PIXI.settings.STRICT_TEXTURE_CACHE`. Works for Videos, SVGs, Images. - * @param {string} url The remote URL to load. - * @param {object} [options] Optional options to include - * @return {Promise} A Promise that resolves to a Texture. - */ - Texture.fromURL = function (url, options) { - var resourceOptions = Object.assign({ autoLoad: false }, options === null || options === void 0 ? void 0 : options.resourceOptions); - var texture = Texture.from(url, Object.assign({ resourceOptions: resourceOptions }, options), false); - var resource = texture.baseTexture.resource; - // The texture was already loaded - if (texture.baseTexture.valid) { - return Promise.resolve(texture); - } - // Manually load the texture, this should allow users to handle load errors - return resource.load().then(function () { return Promise.resolve(texture); }); - }; - /** - * Create a new Texture with a BufferResource from a Float32Array. - * RGBA values are floats from 0 to 1. - * @static - * @param {Float32Array|Uint8Array} buffer - The optional array to use, if no data - * is provided, a new Float32Array is created. - * @param {number} width - Width of the resource - * @param {number} height - Height of the resource - * @param {object} [options] See {@link PIXI.BaseTexture}'s constructor for options. - * @return {PIXI.Texture} The resulting new BaseTexture - */ - Texture.fromBuffer = function (buffer, width, height, options) { - return new Texture(BaseTexture.fromBuffer(buffer, width, height, options)); - }; - /** - * Create a texture from a source and add to the cache. - * - * @static - * @param {HTMLImageElement|HTMLCanvasElement} source - The input source. - * @param {String} imageUrl - File name of texture, for cache and resolving resolution. - * @param {String} [name] - Human readable name for the texture cache. If no name is - * specified, only `imageUrl` will be used as the cache ID. - * @return {PIXI.Texture} Output texture - */ - Texture.fromLoader = function (source, imageUrl, name) { - var resource = new ImageResource(source); - resource.url = imageUrl; - var baseTexture = new BaseTexture(resource, { - scaleMode: settings.SCALE_MODE, - resolution: getResolutionOfUrl(imageUrl), - }); - var texture = new Texture(baseTexture); - // No name, use imageUrl instead - if (!name) { - name = imageUrl; - } - // lets also add the frame to pixi's global cache for 'fromLoader' function - BaseTexture.addToCache(texture.baseTexture, name); - Texture.addToCache(texture, name); - // also add references by url if they are different. - if (name !== imageUrl) { - BaseTexture.addToCache(texture.baseTexture, imageUrl); - Texture.addToCache(texture, imageUrl); - } - return texture; - }; - /** - * Adds a Texture to the global TextureCache. This cache is shared across the whole PIXI object. - * - * @static - * @param {PIXI.Texture} texture - The Texture to add to the cache. - * @param {string} id - The id that the Texture will be stored against. - */ - Texture.addToCache = function (texture, id) { - if (id) { - if (texture.textureCacheIds.indexOf(id) === -1) { - texture.textureCacheIds.push(id); - } - if (TextureCache[id]) { - // eslint-disable-next-line no-console - console.warn("Texture added to the cache with an id [" + id + "] that already had an entry"); - } - TextureCache[id] = texture; - } - }; - /** - * Remove a Texture from the global TextureCache. - * - * @static - * @param {string|PIXI.Texture} texture - id of a Texture to be removed, or a Texture instance itself - * @return {PIXI.Texture|null} The Texture that was removed - */ - Texture.removeFromCache = function (texture) { - if (typeof texture === 'string') { - var textureFromCache = TextureCache[texture]; - if (textureFromCache) { - var index = textureFromCache.textureCacheIds.indexOf(texture); - if (index > -1) { - textureFromCache.textureCacheIds.splice(index, 1); - } - delete TextureCache[texture]; - return textureFromCache; - } - } - else if (texture && texture.textureCacheIds) { - for (var i = 0; i < texture.textureCacheIds.length; ++i) { - // Check that texture matches the one being passed in before deleting it from the cache. - if (TextureCache[texture.textureCacheIds[i]] === texture) { - delete TextureCache[texture.textureCacheIds[i]]; - } - } - texture.textureCacheIds.length = 0; - return texture; - } - return null; - }; - Object.defineProperty(Texture.prototype, "resolution", { - /** - * Returns resolution of baseTexture - * - * @member {number} - * @readonly - */ - get: function () { - return this.baseTexture.resolution; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(Texture.prototype, "frame", { - /** - * The frame specifies the region of the base texture that this texture uses. - * Please call `updateUvs()` after you change coordinates of `frame` manually. - * - * @member {PIXI.Rectangle} - */ - get: function () { - return this._frame; - }, - set: function (frame) { - this._frame = frame; - this.noFrame = false; - var x = frame.x, y = frame.y, width = frame.width, height = frame.height; - var xNotFit = x + width > this.baseTexture.width; - var yNotFit = y + height > this.baseTexture.height; - if (xNotFit || yNotFit) { - var relationship = xNotFit && yNotFit ? 'and' : 'or'; - var errorX = "X: " + x + " + " + width + " = " + (x + width) + " > " + this.baseTexture.width; - var errorY = "Y: " + y + " + " + height + " = " + (y + height) + " > " + this.baseTexture.height; - throw new Error('Texture Error: frame does not fit inside the base Texture dimensions: ' - + (errorX + " " + relationship + " " + errorY)); - } - this.valid = width && height && this.baseTexture.valid; - if (!this.trim && !this.rotate) { - this.orig = frame; - } - if (this.valid) { - this.updateUvs(); - } - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(Texture.prototype, "rotate", { - /** - * Indicates whether the texture is rotated inside the atlas - * set to 2 to compensate for texture packer rotation - * set to 6 to compensate for spine packer rotation - * can be used to rotate or mirror sprites - * See {@link PIXI.groupD8} for explanation - * - * @member {number} - */ - get: function () { - return this._rotate; - }, - set: function (rotate) { - this._rotate = rotate; - if (this.valid) { - this.updateUvs(); - } - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(Texture.prototype, "width", { - /** - * The width of the Texture in pixels. - * - * @member {number} - */ - get: function () { - return this.orig.width; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(Texture.prototype, "height", { - /** - * The height of the Texture in pixels. - * - * @member {number} - */ - get: function () { - return this.orig.height; - }, - enumerable: false, - configurable: true - }); - /** - * Utility function for BaseTexture|Texture cast - */ - Texture.prototype.castToBaseTexture = function () { - return this.baseTexture; - }; - return Texture; - }(eventemitter3)); - function createWhiteTexture() { - var canvas = document.createElement('canvas'); - canvas.width = 16; - canvas.height = 16; - var context = canvas.getContext('2d'); - context.fillStyle = 'white'; - context.fillRect(0, 0, 16, 16); - return new Texture(new BaseTexture(new CanvasResource(canvas))); - } - function removeAllHandlers(tex) { - tex.destroy = function _emptyDestroy() { }; - tex.on = function _emptyOn() { }; - tex.once = function _emptyOnce() { }; - tex.emit = function _emptyEmit() { }; - } - /** - * An empty texture, used often to not have to create multiple empty textures. - * Can not be destroyed. - * - * @static - * @constant - * @member {PIXI.Texture} - */ - Texture.EMPTY = new Texture(new BaseTexture()); - removeAllHandlers(Texture.EMPTY); - removeAllHandlers(Texture.EMPTY.baseTexture); - /** - * A white texture of 16x16 size, used for graphics and other things - * Can not be destroyed. - * - * @static - * @constant - * @member {PIXI.Texture} - */ - Texture.WHITE = createWhiteTexture(); - removeAllHandlers(Texture.WHITE); - removeAllHandlers(Texture.WHITE.baseTexture); - - /** - * A RenderTexture is a special texture that allows any PixiJS display object to be rendered to it. - * - * __Hint__: All DisplayObjects (i.e. Sprites) that render to a RenderTexture should be preloaded - * otherwise black rectangles will be drawn instead. - * - * __Hint-2__: The actual memory allocation will happen on first render. - * You shouldn't create renderTextures each frame just to delete them after, try to reuse them. - * - * A RenderTexture takes a snapshot of any Display Object given to its render method. For example: - * - * ```js - * let renderer = PIXI.autoDetectRenderer(); - * let renderTexture = PIXI.RenderTexture.create({ width: 800, height: 600 }); - * let sprite = PIXI.Sprite.from("spinObj_01.png"); - * - * sprite.position.x = 800/2; - * sprite.position.y = 600/2; - * sprite.anchor.x = 0.5; - * sprite.anchor.y = 0.5; - * - * renderer.render(sprite, renderTexture); - * ``` - * - * The Sprite in this case will be rendered using its local transform. To render this sprite at 0,0 - * you can clear the transform - * - * ```js - * - * sprite.setTransform() - * - * let renderTexture = new PIXI.RenderTexture.create(100, 100); - * - * renderer.render(sprite, renderTexture); // Renders to center of RenderTexture - * ``` - * - * @class - * @extends PIXI.Texture - * @memberof PIXI - */ - var RenderTexture = /** @class */ (function (_super) { - __extends$2(RenderTexture, _super); - /** - * @param {PIXI.BaseRenderTexture} baseRenderTexture - The base texture object that this texture uses - * @param {PIXI.Rectangle} [frame] - The rectangle frame of the texture to show - */ - function RenderTexture(baseRenderTexture, frame) { - var _this = this; - // support for legacy.. - var _legacyRenderer = null; - if (!(baseRenderTexture instanceof BaseRenderTexture)) { - /* eslint-disable prefer-rest-params, no-console */ - var width = arguments[1]; - var height = arguments[2]; - var scaleMode = arguments[3]; - var resolution = arguments[4]; - // we have an old render texture.. - console.warn("Please use RenderTexture.create(" + width + ", " + height + ") instead of the ctor directly."); - _legacyRenderer = arguments[0]; - /* eslint-enable prefer-rest-params, no-console */ - frame = null; - baseRenderTexture = new BaseRenderTexture({ - width: width, - height: height, - scaleMode: scaleMode, - resolution: resolution, - }); - } - /** - * The base texture object that this texture uses - * - * @member {PIXI.BaseTexture} - */ - _this = _super.call(this, baseRenderTexture, frame) || this; - _this.legacyRenderer = _legacyRenderer; - /** - * This will let the renderer know if the texture is valid. If it's not then it cannot be rendered. - * - * @member {boolean} - */ - _this.valid = true; - /** - * Stores `sourceFrame` when this texture is inside current filter stack. - * You can read it inside filters. - * - * @readonly - * @member {PIXI.Rectangle} - */ - _this.filterFrame = null; - /** - * The key for pooled texture of FilterSystem - * @protected - * @member {string} - */ - _this.filterPoolKey = null; - _this.updateUvs(); - return _this; - } - Object.defineProperty(RenderTexture.prototype, "framebuffer", { - /** - * Shortcut to `this.baseTexture.framebuffer`, saves baseTexture cast. - * @member {PIXI.Framebuffer} - * @readonly - */ - get: function () { - return this.baseTexture.framebuffer; - }, - enumerable: false, - configurable: true - }); - /** - * Resizes the RenderTexture. - * - * @param {number} width - The width to resize to. - * @param {number} height - The height to resize to. - * @param {boolean} [resizeBaseTexture=true] - Should the baseTexture.width and height values be resized as well? - */ - RenderTexture.prototype.resize = function (width, height, resizeBaseTexture) { - if (resizeBaseTexture === void 0) { resizeBaseTexture = true; } - width = Math.ceil(width); - height = Math.ceil(height); - // TODO - could be not required.. - this.valid = (width > 0 && height > 0); - this._frame.width = this.orig.width = width; - this._frame.height = this.orig.height = height; - if (resizeBaseTexture) { - this.baseTexture.resize(width, height); - } - this.updateUvs(); - }; - /** - * Changes the resolution of baseTexture, but does not change framebuffer size. - * - * @param {number} resolution - The new resolution to apply to RenderTexture - */ - RenderTexture.prototype.setResolution = function (resolution) { - var baseTexture = this.baseTexture; - if (baseTexture.resolution === resolution) { - return; - } - baseTexture.setResolution(resolution); - this.resize(baseTexture.width, baseTexture.height, false); - }; - /** - * A short hand way of creating a render texture. - * - * @param {object} [options] - Options - * @param {number} [options.width=100] - The width of the render texture - * @param {number} [options.height=100] - The height of the render texture - * @param {number} [options.scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values - * @param {number} [options.resolution=1] - The resolution / device pixel ratio of the texture being generated - * @return {PIXI.RenderTexture} The new render texture - */ - RenderTexture.create = function (options) { - // fallback, old-style: create(width, height, scaleMode, resolution) - if (typeof options === 'number') { - /* eslint-disable prefer-rest-params */ - options = { - width: options, - height: arguments[1], - scaleMode: arguments[2], - resolution: arguments[3], - }; - /* eslint-enable prefer-rest-params */ - } - return new RenderTexture(new BaseRenderTexture(options)); - }; - return RenderTexture; - }(Texture)); - - /** - * Experimental! - * - * Texture pool, used by FilterSystem and plugins - * Stores collection of temporary pow2 or screen-sized renderTextures - * - * If you use custom RenderTexturePool for your filters, you can use methods - * `getFilterTexture` and `returnFilterTexture` same as in - * - * @class - * @memberof PIXI - */ - var RenderTexturePool = /** @class */ (function () { - /** - * @param {object} [textureOptions] - options that will be passed to BaseRenderTexture constructor - * @param {PIXI.SCALE_MODES} [textureOptions.scaleMode] - See {@link PIXI.SCALE_MODES} for possible values. - */ - function RenderTexturePool(textureOptions) { - this.texturePool = {}; - this.textureOptions = textureOptions || {}; - /** - * Allow renderTextures of the same size as screen, not just pow2 - * - * Automatically sets to true after `setScreenSize` - * - * @member {boolean} - * @default false - */ - this.enableFullScreen = false; - this._pixelsWidth = 0; - this._pixelsHeight = 0; - } - /** - * creates of texture with params that were specified in pool constructor - * - * @param {number} realWidth - width of texture in pixels - * @param {number} realHeight - height of texture in pixels - * @returns {RenderTexture} - */ - RenderTexturePool.prototype.createTexture = function (realWidth, realHeight) { - var baseRenderTexture = new BaseRenderTexture(Object.assign({ - width: realWidth, - height: realHeight, - resolution: 1, - }, this.textureOptions)); - return new RenderTexture(baseRenderTexture); - }; - /** - * Gets a Power-of-Two render texture or fullScreen texture - * - * @protected - * @param {number} minWidth - The minimum width of the render texture in real pixels. - * @param {number} minHeight - The minimum height of the render texture in real pixels. - * @param {number} [resolution=1] - The resolution of the render texture. - * @return {PIXI.RenderTexture} The new render texture. - */ - RenderTexturePool.prototype.getOptimalTexture = function (minWidth, minHeight, resolution) { - if (resolution === void 0) { resolution = 1; } - var key = RenderTexturePool.SCREEN_KEY; - minWidth *= resolution; - minHeight *= resolution; - if (!this.enableFullScreen || minWidth !== this._pixelsWidth || minHeight !== this._pixelsHeight) { - minWidth = nextPow2(minWidth); - minHeight = nextPow2(minHeight); - key = ((minWidth & 0xFFFF) << 16) | (minHeight & 0xFFFF); - } - if (!this.texturePool[key]) { - this.texturePool[key] = []; - } - var renderTexture = this.texturePool[key].pop(); - if (!renderTexture) { - renderTexture = this.createTexture(minWidth, minHeight); - } - renderTexture.filterPoolKey = key; - renderTexture.setResolution(resolution); - return renderTexture; - }; - /** - * Gets extra texture of the same size as input renderTexture - * - * `getFilterTexture(input, 0.5)` or `getFilterTexture(0.5, input)` - * - * @param {PIXI.RenderTexture} input - renderTexture from which size and resolution will be copied - * @param {number} [resolution] - override resolution of the renderTexture - * It overrides, it does not multiply - * @returns {PIXI.RenderTexture} - */ - RenderTexturePool.prototype.getFilterTexture = function (input, resolution) { - var filterTexture = this.getOptimalTexture(input.width, input.height, resolution || input.resolution); - filterTexture.filterFrame = input.filterFrame; - return filterTexture; - }; - /** - * Place a render texture back into the pool. - * @param {PIXI.RenderTexture} renderTexture - The renderTexture to free - */ - RenderTexturePool.prototype.returnTexture = function (renderTexture) { - var key = renderTexture.filterPoolKey; - renderTexture.filterFrame = null; - this.texturePool[key].push(renderTexture); - }; - /** - * Alias for returnTexture, to be compliant with FilterSystem interface - * @param {PIXI.RenderTexture} renderTexture - The renderTexture to free - */ - RenderTexturePool.prototype.returnFilterTexture = function (renderTexture) { - this.returnTexture(renderTexture); - }; - /** - * Clears the pool - * - * @param {boolean} [destroyTextures=true] - destroy all stored textures - */ - RenderTexturePool.prototype.clear = function (destroyTextures) { - destroyTextures = destroyTextures !== false; - if (destroyTextures) { - for (var i in this.texturePool) { - var textures = this.texturePool[i]; - if (textures) { - for (var j = 0; j < textures.length; j++) { - textures[j].destroy(true); - } - } - } - } - this.texturePool = {}; - }; - /** - * If screen size was changed, drops all screen-sized textures, - * sets new screen size, sets `enableFullScreen` to true - * - * Size is measured in pixels, `renderer.view` can be passed here, not `renderer.screen` - * - * @param {PIXI.ISize} size - Initial size of screen - */ - RenderTexturePool.prototype.setScreenSize = function (size) { - if (size.width === this._pixelsWidth - && size.height === this._pixelsHeight) { - return; - } - var screenKey = RenderTexturePool.SCREEN_KEY; - var textures = this.texturePool[screenKey]; - this.enableFullScreen = size.width > 0 && size.height > 0; - if (textures) { - for (var j = 0; j < textures.length; j++) { - textures[j].destroy(true); - } - } - this.texturePool[screenKey] = []; - this._pixelsWidth = size.width; - this._pixelsHeight = size.height; - }; - /** - * Key that is used to store fullscreen renderTextures in a pool - * - * @static - * @const {string} - */ - RenderTexturePool.SCREEN_KEY = 'screen'; - return RenderTexturePool; - }()); - - /* eslint-disable max-len */ - /** - * Holds the information for a single attribute structure required to render geometry. - * - * This does not contain the actual data, but instead has a buffer id that maps to a {@link PIXI.Buffer} - * This can include anything from positions, uvs, normals, colors etc. - * - * @class - * @memberof PIXI - */ - var Attribute = /** @class */ (function () { - /** - * @param {string} buffer - the id of the buffer that this attribute will look for - * @param {Number} [size=0] - the size of the attribute. If you have 2 floats per vertex (eg position x and y) this would be 2. - * @param {Boolean} [normalized=false] - should the data be normalized. - * @param {Number} [type=PIXI.TYPES.FLOAT] - what type of number is the attribute. Check {@link PIXI.TYPES} to see the ones available - * @param {Number} [stride=0] - How far apart (in floats) the start of each value is. (used for interleaving data) - * @param {Number} [start=0] - How far into the array to start reading values (used for interleaving data) - */ - function Attribute(buffer, size, normalized, type, stride, start, instance) { - if (size === void 0) { size = 0; } - if (normalized === void 0) { normalized = false; } - if (type === void 0) { type = 5126; } - this.buffer = buffer; - this.size = size; - this.normalized = normalized; - this.type = type; - this.stride = stride; - this.start = start; - this.instance = instance; - } - /** - * Destroys the Attribute. - */ - Attribute.prototype.destroy = function () { - this.buffer = null; - }; - /** - * Helper function that creates an Attribute based on the information provided - * - * @static - * @param {string} buffer - the id of the buffer that this attribute will look for - * @param {Number} [size=0] - the size of the attribute. If you have 2 floats per vertex (eg position x and y) this would be 2 - * @param {Boolean} [normalized=false] - should the data be normalized. - * @param {Number} [type=PIXI.TYPES.FLOAT] - what type of number is the attribute. Check {@link PIXI.TYPES} to see the ones available - * @param {Number} [stride=0] - How far apart (in floats) the start of each value is. (used for interleaving data) - * - * @returns {PIXI.Attribute} A new {@link PIXI.Attribute} based on the information provided - */ - Attribute.from = function (buffer, size, normalized, type, stride) { - return new Attribute(buffer, size, normalized, type, stride); - }; - return Attribute; - }()); - - var UID = 0; - /** - * A wrapper for data so that it can be used and uploaded by WebGL - * - * @class - * @memberof PIXI - */ - var Buffer = /** @class */ (function () { - /** - * @param {ArrayBuffer| SharedArrayBuffer|ArrayBufferView} data - the data to store in the buffer. - * @param {boolean} [_static=true] - `true` for static buffer - * @param {boolean} [index=false] - `true` for index buffer - */ - function Buffer(data, _static, index) { - if (_static === void 0) { _static = true; } - if (index === void 0) { index = false; } - /** - * The data in the buffer, as a typed array - * - * @member {ArrayBuffer| SharedArrayBuffer | ArrayBufferView} - */ - this.data = (data || new Float32Array(1)); - /** - * A map of renderer IDs to webgl buffer - * - * @private - * @member {object} - */ - this._glBuffers = {}; - this._updateID = 0; - this.index = index; - this.static = _static; - this.id = UID++; - this.disposeRunner = new Runner('disposeBuffer'); - } - // TODO could explore flagging only a partial upload? - /** - * flags this buffer as requiring an upload to the GPU - * @param {ArrayBuffer|SharedArrayBuffer|ArrayBufferView} [data] - the data to update in the buffer. - */ - Buffer.prototype.update = function (data) { - this.data = data || this.data; - this._updateID++; - }; - /** - * disposes WebGL resources that are connected to this geometry - */ - Buffer.prototype.dispose = function () { - this.disposeRunner.emit(this, false); - }; - /** - * Destroys the buffer - */ - Buffer.prototype.destroy = function () { - this.dispose(); - this.data = null; - }; - /** - * Helper function that creates a buffer based on an array or TypedArray - * - * @static - * @param {ArrayBufferView | number[]} data - the TypedArray that the buffer will store. If this is a regular Array it will be converted to a Float32Array. - * @return {PIXI.Buffer} A new Buffer based on the data provided. - */ - Buffer.from = function (data) { - if (data instanceof Array) { - data = new Float32Array(data); - } - return new Buffer(data); - }; - return Buffer; - }()); - - function getBufferType$1(array) { - if (array.BYTES_PER_ELEMENT === 4) { - if (array instanceof Float32Array) { - return 'Float32Array'; - } - else if (array instanceof Uint32Array) { - return 'Uint32Array'; - } - return 'Int32Array'; - } - else if (array.BYTES_PER_ELEMENT === 2) { - if (array instanceof Uint16Array) { - return 'Uint16Array'; - } - } - else if (array.BYTES_PER_ELEMENT === 1) { - if (array instanceof Uint8Array) { - return 'Uint8Array'; - } - } - // TODO map out the rest of the array elements! - return null; - } - - /* eslint-disable object-shorthand */ - var map$1 = { - Float32Array: Float32Array, - Uint32Array: Uint32Array, - Int32Array: Int32Array, - Uint8Array: Uint8Array, - }; - function interleaveTypedArrays$1(arrays, sizes) { - var outSize = 0; - var stride = 0; - var views = {}; - for (var i = 0; i < arrays.length; i++) { - stride += sizes[i]; - outSize += arrays[i].length; - } - var buffer = new ArrayBuffer(outSize * 4); - var out = null; - var littleOffset = 0; - for (var i = 0; i < arrays.length; i++) { - var size = sizes[i]; - var array = arrays[i]; - var type = getBufferType$1(array); - if (!views[type]) { - views[type] = new map$1[type](buffer); - } - out = views[type]; - for (var j = 0; j < array.length; j++) { - var indexStart = ((j / size | 0) * stride) + littleOffset; - var index = j % size; - out[indexStart + index] = array[j]; - } - littleOffset += size; - } - return new Float32Array(buffer); - } - - var byteSizeMap = { 5126: 4, 5123: 2, 5121: 1 }; - var UID$1 = 0; - /* eslint-disable object-shorthand */ - var map$1$1 = { - Float32Array: Float32Array, - Uint32Array: Uint32Array, - Int32Array: Int32Array, - Uint8Array: Uint8Array, - Uint16Array: Uint16Array, - }; - /* eslint-disable max-len */ - /** - * The Geometry represents a model. It consists of two components: - * - GeometryStyle - The structure of the model such as the attributes layout - * - GeometryData - the data of the model - this consists of buffers. - * This can include anything from positions, uvs, normals, colors etc. - * - * Geometry can be defined without passing in a style or data if required (thats how I prefer!) - * - * ```js - * let geometry = new PIXI.Geometry(); - * - * geometry.addAttribute('positions', [0, 0, 100, 0, 100, 100, 0, 100], 2); - * geometry.addAttribute('uvs', [0,0,1,0,1,1,0,1],2) - * geometry.addIndex([0,1,2,1,3,2]) - * - * ``` - * @class - * @memberof PIXI - */ - var Geometry = /** @class */ (function () { - /** - * @param {PIXI.Buffer[]} [buffers] - an array of buffers. optional. - * @param {object} [attributes] - of the geometry, optional structure of the attributes layout - */ - function Geometry(buffers, attributes) { - if (buffers === void 0) { buffers = []; } - if (attributes === void 0) { attributes = {}; } - this.buffers = buffers; - this.indexBuffer = null; - this.attributes = attributes; - /** - * A map of renderer IDs to webgl VAOs - * - * @protected - * @type {object} - */ - this.glVertexArrayObjects = {}; - this.id = UID$1++; - this.instanced = false; - /** - * Number of instances in this geometry, pass it to `GeometrySystem.draw()` - * @member {number} - * @default 1 - */ - this.instanceCount = 1; - this.disposeRunner = new Runner('disposeGeometry'); - /** - * Count of existing (not destroyed) meshes that reference this geometry - * @member {number} - */ - this.refCount = 0; - } - /** - * - * Adds an attribute to the geometry - * Note: `stride` and `start` should be `undefined` if you dont know them, not 0! - * - * @param {String} id - the name of the attribute (matching up to a shader) - * @param {PIXI.Buffer|number[]} [buffer] - the buffer that holds the data of the attribute . You can also provide an Array and a buffer will be created from it. - * @param {Number} [size=0] - the size of the attribute. If you have 2 floats per vertex (eg position x and y) this would be 2 - * @param {Boolean} [normalized=false] - should the data be normalized. - * @param {Number} [type=PIXI.TYPES.FLOAT] - what type of number is the attribute. Check {PIXI.TYPES} to see the ones available - * @param {Number} [stride] - How far apart (in floats) the start of each value is. (used for interleaving data) - * @param {Number} [start] - How far into the array to start reading values (used for interleaving data) - * @param {boolean} [instance=false] - Instancing flag - * - * @return {PIXI.Geometry} returns self, useful for chaining. - */ - Geometry.prototype.addAttribute = function (id, buffer, size, normalized, type, stride, start, instance) { - if (size === void 0) { size = 0; } - if (normalized === void 0) { normalized = false; } - if (instance === void 0) { instance = false; } - if (!buffer) { - throw new Error('You must pass a buffer when creating an attribute'); - } - // check if this is a buffer! - if (!(buffer instanceof Buffer)) { - // its an array! - if (buffer instanceof Array) { - buffer = new Float32Array(buffer); - } - buffer = new Buffer(buffer); - } - var ids = id.split('|'); - if (ids.length > 1) { - for (var i = 0; i < ids.length; i++) { - this.addAttribute(ids[i], buffer, size, normalized, type); - } - return this; - } - var bufferIndex = this.buffers.indexOf(buffer); - if (bufferIndex === -1) { - this.buffers.push(buffer); - bufferIndex = this.buffers.length - 1; - } - this.attributes[id] = new Attribute(bufferIndex, size, normalized, type, stride, start, instance); - // assuming that if there is instanced data then this will be drawn with instancing! - this.instanced = this.instanced || instance; - return this; - }; - /** - * returns the requested attribute - * - * @param {String} id - the name of the attribute required - * @return {PIXI.Attribute} the attribute requested. - */ - Geometry.prototype.getAttribute = function (id) { - return this.attributes[id]; - }; - /** - * returns the requested buffer - * - * @param {String} id - the name of the buffer required - * @return {PIXI.Buffer} the buffer requested. - */ - Geometry.prototype.getBuffer = function (id) { - return this.buffers[this.getAttribute(id).buffer]; - }; - /** - * - * Adds an index buffer to the geometry - * The index buffer contains integers, three for each triangle in the geometry, which reference the various attribute buffers (position, colour, UV coordinates, other UV coordinates, normal, …). There is only ONE index buffer. - * - * @param {PIXI.Buffer|number[]} [buffer] - the buffer that holds the data of the index buffer. You can also provide an Array and a buffer will be created from it. - * @return {PIXI.Geometry} returns self, useful for chaining. - */ - Geometry.prototype.addIndex = function (buffer) { - if (!(buffer instanceof Buffer)) { - // its an array! - if (buffer instanceof Array) { - buffer = new Uint16Array(buffer); - } - buffer = new Buffer(buffer); - } - buffer.index = true; - this.indexBuffer = buffer; - if (this.buffers.indexOf(buffer) === -1) { - this.buffers.push(buffer); - } - return this; - }; - /** - * returns the index buffer - * - * @return {PIXI.Buffer} the index buffer. - */ - Geometry.prototype.getIndex = function () { - return this.indexBuffer; - }; - /** - * this function modifies the structure so that all current attributes become interleaved into a single buffer - * This can be useful if your model remains static as it offers a little performance boost - * - * @return {PIXI.Geometry} returns self, useful for chaining. - */ - Geometry.prototype.interleave = function () { - // a simple check to see if buffers are already interleaved.. - if (this.buffers.length === 1 || (this.buffers.length === 2 && this.indexBuffer)) - { return this; } - // assume already that no buffers are interleaved - var arrays = []; - var sizes = []; - var interleavedBuffer = new Buffer(); - var i; - for (i in this.attributes) { - var attribute = this.attributes[i]; - var buffer = this.buffers[attribute.buffer]; - arrays.push(buffer.data); - sizes.push((attribute.size * byteSizeMap[attribute.type]) / 4); - attribute.buffer = 0; - } - interleavedBuffer.data = interleaveTypedArrays$1(arrays, sizes); - for (i = 0; i < this.buffers.length; i++) { - if (this.buffers[i] !== this.indexBuffer) { - this.buffers[i].destroy(); - } - } - this.buffers = [interleavedBuffer]; - if (this.indexBuffer) { - this.buffers.push(this.indexBuffer); - } - return this; - }; - Geometry.prototype.getSize = function () { - for (var i in this.attributes) { - var attribute = this.attributes[i]; - var buffer = this.buffers[attribute.buffer]; - return buffer.data.length / ((attribute.stride / 4) || attribute.size); - } - return 0; - }; - /** - * disposes WebGL resources that are connected to this geometry - */ - Geometry.prototype.dispose = function () { - this.disposeRunner.emit(this, false); - }; - /** - * Destroys the geometry. - */ - Geometry.prototype.destroy = function () { - this.dispose(); - this.buffers = null; - this.indexBuffer = null; - this.attributes = null; - }; - /** - * returns a clone of the geometry - * - * @returns {PIXI.Geometry} a new clone of this geometry - */ - Geometry.prototype.clone = function () { - var geometry = new Geometry(); - for (var i = 0; i < this.buffers.length; i++) { - geometry.buffers[i] = new Buffer(this.buffers[i].data.slice(0)); - } - for (var i in this.attributes) { - var attrib = this.attributes[i]; - geometry.attributes[i] = new Attribute(attrib.buffer, attrib.size, attrib.normalized, attrib.type, attrib.stride, attrib.start, attrib.instance); - } - if (this.indexBuffer) { - geometry.indexBuffer = geometry.buffers[this.buffers.indexOf(this.indexBuffer)]; - geometry.indexBuffer.index = true; - } - return geometry; - }; - /** - * merges an array of geometries into a new single one - * geometry attribute styles must match for this operation to work - * - * @param {PIXI.Geometry[]} geometries - array of geometries to merge - * @returns {PIXI.Geometry} shiny new geometry! - */ - Geometry.merge = function (geometries) { - // todo add a geometry check! - // also a size check.. cant be too big!] - var geometryOut = new Geometry(); - var arrays = []; - var sizes = []; - var offsets = []; - var geometry; - // pass one.. get sizes.. - for (var i = 0; i < geometries.length; i++) { - geometry = geometries[i]; - for (var j = 0; j < geometry.buffers.length; j++) { - sizes[j] = sizes[j] || 0; - sizes[j] += geometry.buffers[j].data.length; - offsets[j] = 0; - } - } - // build the correct size arrays.. - for (var i = 0; i < geometry.buffers.length; i++) { - // TODO types! - arrays[i] = new map$1$1[getBufferType$1(geometry.buffers[i].data)](sizes[i]); - geometryOut.buffers[i] = new Buffer(arrays[i]); - } - // pass to set data.. - for (var i = 0; i < geometries.length; i++) { - geometry = geometries[i]; - for (var j = 0; j < geometry.buffers.length; j++) { - arrays[j].set(geometry.buffers[j].data, offsets[j]); - offsets[j] += geometry.buffers[j].data.length; - } - } - geometryOut.attributes = geometry.attributes; - if (geometry.indexBuffer) { - geometryOut.indexBuffer = geometryOut.buffers[geometry.buffers.indexOf(geometry.indexBuffer)]; - geometryOut.indexBuffer.index = true; - var offset = 0; - var stride = 0; - var offset2 = 0; - var bufferIndexToCount = 0; - // get a buffer - for (var i = 0; i < geometry.buffers.length; i++) { - if (geometry.buffers[i] !== geometry.indexBuffer) { - bufferIndexToCount = i; - break; - } - } - // figure out the stride of one buffer.. - for (var i in geometry.attributes) { - var attribute = geometry.attributes[i]; - if ((attribute.buffer | 0) === bufferIndexToCount) { - stride += ((attribute.size * byteSizeMap[attribute.type]) / 4); - } - } - // time to off set all indexes.. - for (var i = 0; i < geometries.length; i++) { - var indexBufferData = geometries[i].indexBuffer.data; - for (var j = 0; j < indexBufferData.length; j++) { - geometryOut.indexBuffer.data[j + offset2] += offset; - } - offset += geometry.buffers[bufferIndexToCount].data.length / (stride); - offset2 += indexBufferData.length; - } - } - return geometryOut; - }; - return Geometry; - }()); - - /** - * Helper class to create a quad - * - * @class - * @memberof PIXI - */ - var Quad = /** @class */ (function (_super) { - __extends$2(Quad, _super); - function Quad() { - var _this = _super.call(this) || this; - _this.addAttribute('aVertexPosition', new Float32Array([ - 0, 0, - 1, 0, - 1, 1, - 0, 1 ])) - .addIndex([0, 1, 3, 2]); - return _this; - } - return Quad; - }(Geometry)); - - /** - * Helper class to create a quad with uvs like in v4 - * - * @class - * @memberof PIXI - * @extends PIXI.Geometry - */ - var QuadUv = /** @class */ (function (_super) { - __extends$2(QuadUv, _super); - function QuadUv() { - var _this = _super.call(this) || this; - /** - * An array of vertices - * - * @member {Float32Array} - */ - _this.vertices = new Float32Array([ - -1, -1, - 1, -1, - 1, 1, - -1, 1 ]); - /** - * The Uvs of the quad - * - * @member {Float32Array} - */ - _this.uvs = new Float32Array([ - 0, 0, - 1, 0, - 1, 1, - 0, 1 ]); - _this.vertexBuffer = new Buffer(_this.vertices); - _this.uvBuffer = new Buffer(_this.uvs); - _this.addAttribute('aVertexPosition', _this.vertexBuffer) - .addAttribute('aTextureCoord', _this.uvBuffer) - .addIndex([0, 1, 2, 0, 2, 3]); - return _this; - } - /** - * Maps two Rectangle to the quad. - * - * @param {PIXI.Rectangle} targetTextureFrame - the first rectangle - * @param {PIXI.Rectangle} destinationFrame - the second rectangle - * @return {PIXI.Quad} Returns itself. - */ - QuadUv.prototype.map = function (targetTextureFrame, destinationFrame) { - var x = 0; // destinationFrame.x / targetTextureFrame.width; - var y = 0; // destinationFrame.y / targetTextureFrame.height; - this.uvs[0] = x; - this.uvs[1] = y; - this.uvs[2] = x + (destinationFrame.width / targetTextureFrame.width); - this.uvs[3] = y; - this.uvs[4] = x + (destinationFrame.width / targetTextureFrame.width); - this.uvs[5] = y + (destinationFrame.height / targetTextureFrame.height); - this.uvs[6] = x; - this.uvs[7] = y + (destinationFrame.height / targetTextureFrame.height); - x = destinationFrame.x; - y = destinationFrame.y; - this.vertices[0] = x; - this.vertices[1] = y; - this.vertices[2] = x + destinationFrame.width; - this.vertices[3] = y; - this.vertices[4] = x + destinationFrame.width; - this.vertices[5] = y + destinationFrame.height; - this.vertices[6] = x; - this.vertices[7] = y + destinationFrame.height; - this.invalidate(); - return this; - }; - /** - * legacy upload method, just marks buffers dirty - * @returns {PIXI.QuadUv} Returns itself. - */ - QuadUv.prototype.invalidate = function () { - this.vertexBuffer._updateID++; - this.uvBuffer._updateID++; - return this; - }; - return QuadUv; - }(Geometry)); - - var UID$2 = 0; - /** - * Uniform group holds uniform map and some ID's for work - * - * @class - * @memberof PIXI - */ - var UniformGroup = /** @class */ (function () { - /** - * @param {object} [uniforms] - Custom uniforms to use to augment the built-in ones. - * @param {boolean} [_static] - Uniforms wont be changed after creation - */ - function UniformGroup(uniforms, _static) { - /** - * uniform values - * @member {object} - * @readonly - */ - this.uniforms = uniforms; - /** - * Its a group and not a single uniforms - * @member {boolean} - * @readonly - * @default true - */ - this.group = true; - // lets generate this when the shader ? - this.syncUniforms = {}; - /** - * dirty version - * @protected - * @member {number} - */ - this.dirtyId = 0; - /** - * unique id - * @protected - * @member {number} - */ - this.id = UID$2++; - /** - * Uniforms wont be changed after creation - * @member {boolean} - */ - this.static = !!_static; - } - UniformGroup.prototype.update = function () { - this.dirtyId++; - }; - UniformGroup.prototype.add = function (name, uniforms, _static) { - this.uniforms[name] = new UniformGroup(uniforms, _static); - }; - UniformGroup.from = function (uniforms, _static) { - return new UniformGroup(uniforms, _static); - }; - return UniformGroup; - }()); - - /** - * System plugin to the renderer to manage filter states. - * - * @class - * @private - */ - var FilterState = /** @class */ (function () { - function FilterState() { - this.renderTexture = null; - /** - * Target of the filters - * We store for case when custom filter wants to know the element it was applied on - * @member {PIXI.DisplayObject} - * @private - */ - this.target = null; - /** - * Compatibility with PixiJS v4 filters - * @member {boolean} - * @default false - * @private - */ - this.legacy = false; - /** - * Resolution of filters - * @member {number} - * @default 1 - * @private - */ - this.resolution = 1; - // next three fields are created only for root - // re-assigned for everything else - /** - * Source frame - * @member {PIXI.Rectangle} - * @private - */ - this.sourceFrame = new Rectangle(); - /** - * Destination frame - * @member {PIXI.Rectangle} - * @private - */ - this.destinationFrame = new Rectangle(); - /** - * Collection of filters - * @member {PIXI.Filter[]} - * @private - */ - this.filters = []; - } - /** - * clears the state - * @private - */ - FilterState.prototype.clear = function () { - this.target = null; - this.filters = null; - this.renderTexture = null; - }; - return FilterState; - }()); - - /** - * System plugin to the renderer to manage the filters. - * - * @class - * @memberof PIXI.systems - * @extends PIXI.System - */ - var FilterSystem = /** @class */ (function (_super) { - __extends$2(FilterSystem, _super); - /** - * @param {PIXI.Renderer} renderer - The renderer this System works for. - */ - function FilterSystem(renderer) { - var _this = _super.call(this, renderer) || this; - /** - * List of filters for the FilterSystem - * @member {Object[]} - * @readonly - */ - _this.defaultFilterStack = [{}]; - /** - * stores a bunch of PO2 textures used for filtering - * @member {Object} - */ - _this.texturePool = new RenderTexturePool(); - _this.texturePool.setScreenSize(renderer.view); - /** - * a pool for storing filter states, save us creating new ones each tick - * @member {Object[]} - */ - _this.statePool = []; - /** - * A very simple geometry used when drawing a filter effect to the screen - * @member {PIXI.Quad} - */ - _this.quad = new Quad(); - /** - * Quad UVs - * @member {PIXI.QuadUv} - */ - _this.quadUv = new QuadUv(); - /** - * Temporary rect for maths - * @type {PIXI.Rectangle} - */ - _this.tempRect = new Rectangle(); - /** - * Active state - * @member {object} - */ - _this.activeState = {}; - /** - * This uniform group is attached to filter uniforms when used - * @member {PIXI.UniformGroup} - * @property {PIXI.Rectangle} outputFrame - * @property {Float32Array} inputSize - * @property {Float32Array} inputPixel - * @property {Float32Array} inputClamp - * @property {Number} resolution - * @property {Float32Array} filterArea - * @property {Fload32Array} filterClamp - */ - _this.globalUniforms = new UniformGroup({ - outputFrame: _this.tempRect, - inputSize: new Float32Array(4), - inputPixel: new Float32Array(4), - inputClamp: new Float32Array(4), - resolution: 1, - // legacy variables - filterArea: new Float32Array(4), - filterClamp: new Float32Array(4), - }, true); - /** - * Whether to clear output renderTexture in AUTO/BLIT mode. See {@link PIXI.CLEAR_MODES} - * @member {boolean} - */ - _this.forceClear = false; - /** - * Old padding behavior is to use the max amount instead of sum padding. - * Use this flag if you need the old behavior. - * @member {boolean} - * @default false - */ - _this.useMaxPadding = false; - return _this; - } - /** - * Adds a new filter to the System. - * - * @param {PIXI.DisplayObject} target - The target of the filter to render. - * @param {PIXI.Filter[]} filters - The filters to apply. - */ - FilterSystem.prototype.push = function (target, filters) { - var renderer = this.renderer; - var filterStack = this.defaultFilterStack; - var state = this.statePool.pop() || new FilterState(); - var resolution = filters[0].resolution; - var padding = filters[0].padding; - var autoFit = filters[0].autoFit; - var legacy = filters[0].legacy; - for (var i = 1; i < filters.length; i++) { - var filter = filters[i]; - // lets use the lowest resolution.. - resolution = Math.min(resolution, filter.resolution); - // figure out the padding required for filters - padding = this.useMaxPadding - // old behavior: use largest amount of padding! - ? Math.max(padding, filter.padding) - // new behavior: sum the padding - : padding + filter.padding; - // only auto fit if all filters are autofit - autoFit = autoFit || filter.autoFit; - legacy = legacy || filter.legacy; - } - if (filterStack.length === 1) { - this.defaultFilterStack[0].renderTexture = renderer.renderTexture.current; - } - filterStack.push(state); - state.resolution = resolution; - state.legacy = legacy; - state.target = target; - state.sourceFrame.copyFrom(target.filterArea || target.getBounds(true)); - state.sourceFrame.pad(padding); - if (autoFit) { - state.sourceFrame.fit(this.renderer.renderTexture.sourceFrame); - } - // round to whole number based on resolution - state.sourceFrame.ceil(resolution); - state.renderTexture = this.getOptimalFilterTexture(state.sourceFrame.width, state.sourceFrame.height, resolution); - state.filters = filters; - state.destinationFrame.width = state.renderTexture.width; - state.destinationFrame.height = state.renderTexture.height; - var destinationFrame = this.tempRect; - destinationFrame.width = state.sourceFrame.width; - destinationFrame.height = state.sourceFrame.height; - state.renderTexture.filterFrame = state.sourceFrame; - renderer.renderTexture.bind(state.renderTexture, state.sourceFrame, destinationFrame); - renderer.renderTexture.clear(); - }; - /** - * Pops off the filter and applies it. - * - */ - FilterSystem.prototype.pop = function () { - var filterStack = this.defaultFilterStack; - var state = filterStack.pop(); - var filters = state.filters; - this.activeState = state; - var globalUniforms = this.globalUniforms.uniforms; - globalUniforms.outputFrame = state.sourceFrame; - globalUniforms.resolution = state.resolution; - var inputSize = globalUniforms.inputSize; - var inputPixel = globalUniforms.inputPixel; - var inputClamp = globalUniforms.inputClamp; - inputSize[0] = state.destinationFrame.width; - inputSize[1] = state.destinationFrame.height; - inputSize[2] = 1.0 / inputSize[0]; - inputSize[3] = 1.0 / inputSize[1]; - inputPixel[0] = inputSize[0] * state.resolution; - inputPixel[1] = inputSize[1] * state.resolution; - inputPixel[2] = 1.0 / inputPixel[0]; - inputPixel[3] = 1.0 / inputPixel[1]; - inputClamp[0] = 0.5 * inputPixel[2]; - inputClamp[1] = 0.5 * inputPixel[3]; - inputClamp[2] = (state.sourceFrame.width * inputSize[2]) - (0.5 * inputPixel[2]); - inputClamp[3] = (state.sourceFrame.height * inputSize[3]) - (0.5 * inputPixel[3]); - // only update the rect if its legacy.. - if (state.legacy) { - var filterArea = globalUniforms.filterArea; - filterArea[0] = state.destinationFrame.width; - filterArea[1] = state.destinationFrame.height; - filterArea[2] = state.sourceFrame.x; - filterArea[3] = state.sourceFrame.y; - globalUniforms.filterClamp = globalUniforms.inputClamp; - } - this.globalUniforms.update(); - var lastState = filterStack[filterStack.length - 1]; - if (state.renderTexture.framebuffer.multisample > 1) { - this.renderer.framebuffer.blit(); - } - if (filters.length === 1) { - filters[0].apply(this, state.renderTexture, lastState.renderTexture, exports.CLEAR_MODES.BLEND, state); - this.returnFilterTexture(state.renderTexture); - } - else { - var flip = state.renderTexture; - var flop = this.getOptimalFilterTexture(flip.width, flip.height, state.resolution); - flop.filterFrame = flip.filterFrame; - var i = 0; - for (i = 0; i < filters.length - 1; ++i) { - filters[i].apply(this, flip, flop, exports.CLEAR_MODES.CLEAR, state); - var t = flip; - flip = flop; - flop = t; - } - filters[i].apply(this, flip, lastState.renderTexture, exports.CLEAR_MODES.BLEND, state); - this.returnFilterTexture(flip); - this.returnFilterTexture(flop); - } - state.clear(); - this.statePool.push(state); - }; - /** - * Binds a renderTexture with corresponding `filterFrame`, clears it if mode corresponds. - * @param {PIXI.RenderTexture} filterTexture - renderTexture to bind, should belong to filter pool or filter stack - * @param {PIXI.CLEAR_MODES} [clearMode] - clearMode, by default its CLEAR/YES. See {@link PIXI.CLEAR_MODES} - */ - FilterSystem.prototype.bindAndClear = function (filterTexture, clearMode) { - if (clearMode === void 0) { clearMode = exports.CLEAR_MODES.CLEAR; } - if (filterTexture && filterTexture.filterFrame) { - var destinationFrame = this.tempRect; - destinationFrame.width = filterTexture.filterFrame.width; - destinationFrame.height = filterTexture.filterFrame.height; - this.renderer.renderTexture.bind(filterTexture, filterTexture.filterFrame, destinationFrame); - } - else { - this.renderer.renderTexture.bind(filterTexture); - } - // TODO: remove in next major version - if (typeof clearMode === 'boolean') { - clearMode = clearMode ? exports.CLEAR_MODES.CLEAR : exports.CLEAR_MODES.BLEND; - // get deprecation function from utils - deprecation('5.2.1', 'Use CLEAR_MODES when using clear applyFilter option'); - } - if (clearMode === exports.CLEAR_MODES.CLEAR - || (clearMode === exports.CLEAR_MODES.BLIT && this.forceClear)) { - this.renderer.renderTexture.clear(); - } - }; - /** - * Draws a filter. - * - * @param {PIXI.Filter} filter - The filter to draw. - * @param {PIXI.RenderTexture} input - The input render target. - * @param {PIXI.RenderTexture} output - The target to output to. - * @param {PIXI.CLEAR_MODES} [clearMode] - Should the output be cleared before rendering to it - */ - FilterSystem.prototype.applyFilter = function (filter, input, output, clearMode) { - var renderer = this.renderer; - this.bindAndClear(output, clearMode); - // set the uniforms.. - filter.uniforms.uSampler = input; - filter.uniforms.filterGlobals = this.globalUniforms; - // TODO make it so that the order of this does not matter.. - // because it does at the moment cos of global uniforms. - // they need to get resynced - renderer.state.set(filter.state); - renderer.shader.bind(filter); - if (filter.legacy) { - this.quadUv.map(input._frame, input.filterFrame); - renderer.geometry.bind(this.quadUv); - renderer.geometry.draw(exports.DRAW_MODES.TRIANGLES); - } - else { - renderer.geometry.bind(this.quad); - renderer.geometry.draw(exports.DRAW_MODES.TRIANGLE_STRIP); - } - }; - /** - * Multiply _input normalized coordinates_ to this matrix to get _sprite texture normalized coordinates_. - * - * Use `outputMatrix * vTextureCoord` in the shader. - * - * @param {PIXI.Matrix} outputMatrix - The matrix to output to. - * @param {PIXI.Sprite} sprite - The sprite to map to. - * @return {PIXI.Matrix} The mapped matrix. - */ - FilterSystem.prototype.calculateSpriteMatrix = function (outputMatrix, sprite) { - var _a = this.activeState, sourceFrame = _a.sourceFrame, destinationFrame = _a.destinationFrame; - var orig = sprite._texture.orig; - var mappedMatrix = outputMatrix.set(destinationFrame.width, 0, 0, destinationFrame.height, sourceFrame.x, sourceFrame.y); - var worldTransform = sprite.worldTransform.copyTo(Matrix.TEMP_MATRIX); - worldTransform.invert(); - mappedMatrix.prepend(worldTransform); - mappedMatrix.scale(1.0 / orig.width, 1.0 / orig.height); - mappedMatrix.translate(sprite.anchor.x, sprite.anchor.y); - return mappedMatrix; - }; - /** - * Destroys this Filter System. - */ - FilterSystem.prototype.destroy = function () { - // Those textures has to be destroyed by RenderTextureSystem or FramebufferSystem - this.texturePool.clear(false); - }; - /** - * Gets a Power-of-Two render texture or fullScreen texture - * - * @protected - * @param {number} minWidth - The minimum width of the render texture in real pixels. - * @param {number} minHeight - The minimum height of the render texture in real pixels. - * @param {number} [resolution=1] - The resolution of the render texture. - * @return {PIXI.RenderTexture} The new render texture. - */ - FilterSystem.prototype.getOptimalFilterTexture = function (minWidth, minHeight, resolution) { - if (resolution === void 0) { resolution = 1; } - return this.texturePool.getOptimalTexture(minWidth, minHeight, resolution); - }; - /** - * Gets extra render texture to use inside current filter - * To be compliant with older filters, you can use params in any order - * - * @param {PIXI.RenderTexture} [input] - renderTexture from which size and resolution will be copied - * @param {number} [resolution] - override resolution of the renderTexture - * @returns {PIXI.RenderTexture} - */ - FilterSystem.prototype.getFilterTexture = function (input, resolution) { - if (typeof input === 'number') { - var swap = input; - input = resolution; - resolution = swap; - } - input = input || this.activeState.renderTexture; - var filterTexture = this.texturePool.getOptimalTexture(input.width, input.height, resolution || input.resolution); - filterTexture.filterFrame = input.filterFrame; - return filterTexture; - }; - /** - * Frees a render texture back into the pool. - * - * @param {PIXI.RenderTexture} renderTexture - The renderTarget to free - */ - FilterSystem.prototype.returnFilterTexture = function (renderTexture) { - this.texturePool.returnTexture(renderTexture); - }; - /** - * Empties the texture pool. - */ - FilterSystem.prototype.emptyPool = function () { - this.texturePool.clear(true); - }; - /** - * calls `texturePool.resize()`, affects fullScreen renderTextures - */ - FilterSystem.prototype.resize = function () { - this.texturePool.setScreenSize(this.renderer.view); - }; - return FilterSystem; - }(System)); - - /** - * Base for a common object renderer that can be used as a - * system renderer plugin. - * - * @class - * @extends PIXI.System - * @memberof PIXI - */ - var ObjectRenderer = /** @class */ (function () { - /** - * @param {PIXI.Renderer} renderer - The renderer this manager works for. - */ - function ObjectRenderer(renderer) { - /** - * The renderer this manager works for. - * - * @member {PIXI.Renderer} - */ - this.renderer = renderer; - } - /** - * Stub method that should be used to empty the current - * batch by rendering objects now. - */ - ObjectRenderer.prototype.flush = function () { - // flush! - }; - /** - * Generic destruction method that frees all resources. This - * should be called by subclasses. - */ - ObjectRenderer.prototype.destroy = function () { - this.renderer = null; - }; - /** - * Stub method that initializes any state required before - * rendering starts. It is different from the `prerender` - * signal, which occurs every frame, in that it is called - * whenever an object requests _this_ renderer specifically. - */ - ObjectRenderer.prototype.start = function () { - // set the shader.. - }; - /** - * Stops the renderer. It should free up any state and - * become dormant. - */ - ObjectRenderer.prototype.stop = function () { - this.flush(); - }; - /** - * Keeps the object to render. It doesn't have to be - * rendered immediately. - * - * @param {PIXI.DisplayObject} object - The object to render. - */ - ObjectRenderer.prototype.render = function (_object) { - // render the object - }; - return ObjectRenderer; - }()); - - /** - * System plugin to the renderer to manage batching. - * - * @class - * @extends PIXI.System - * @memberof PIXI.systems - */ - var BatchSystem = /** @class */ (function (_super) { - __extends$2(BatchSystem, _super); - /** - * @param {PIXI.Renderer} renderer - The renderer this System works for. - */ - function BatchSystem(renderer) { - var _this = _super.call(this, renderer) || this; - /** - * An empty renderer. - * - * @member {PIXI.ObjectRenderer} - */ - _this.emptyRenderer = new ObjectRenderer(renderer); - /** - * The currently active ObjectRenderer. - * - * @member {PIXI.ObjectRenderer} - */ - _this.currentRenderer = _this.emptyRenderer; - return _this; - } - /** - * Changes the current renderer to the one given in parameter - * - * @param {PIXI.ObjectRenderer} objectRenderer - The object renderer to use. - */ - BatchSystem.prototype.setObjectRenderer = function (objectRenderer) { - if (this.currentRenderer === objectRenderer) { - return; - } - this.currentRenderer.stop(); - this.currentRenderer = objectRenderer; - this.currentRenderer.start(); - }; - /** - * This should be called if you wish to do some custom rendering - * It will basically render anything that may be batched up such as sprites - */ - BatchSystem.prototype.flush = function () { - this.setObjectRenderer(this.emptyRenderer); - }; - /** - * Reset the system to an empty renderer - */ - BatchSystem.prototype.reset = function () { - this.setObjectRenderer(this.emptyRenderer); - }; - /** - * Handy function for batch renderers: copies bound textures in first maxTextures locations to array - * sets actual _batchLocation for them - * - * @param {PIXI.BaseTexture[]} - arr copy destination - * @param {number} maxTextures - number of copied elements - */ - BatchSystem.prototype.copyBoundTextures = function (arr, maxTextures) { - var boundTextures = this.renderer.texture.boundTextures; - for (var i = maxTextures - 1; i >= 0; --i) { - arr[i] = boundTextures[i] || null; - if (arr[i]) { - arr[i]._batchLocation = i; - } - } - }; - /** - * Assigns batch locations to textures in array based on boundTextures state. - * All textures in texArray should have `_batchEnabled = _batchId`, - * and their count should be less than `maxTextures`. - * - * @param {PIXI.BatchTextureArray} texArray - textures to bound - * @param {PIXI.BaseTexture[]} boundTextures - current state of bound textures - * @param {number} batchId - marker for _batchEnabled param of textures in texArray - * @param {number} maxTextures - number of texture locations to manipulate - */ - BatchSystem.prototype.boundArray = function (texArray, boundTextures, batchId, maxTextures) { - var elements = texArray.elements, ids = texArray.ids, count = texArray.count; - var j = 0; - for (var i = 0; i < count; i++) { - var tex = elements[i]; - var loc = tex._batchLocation; - if (loc >= 0 && loc < maxTextures - && boundTextures[loc] === tex) { - ids[i] = loc; - continue; - } - while (j < maxTextures) { - var bound = boundTextures[j]; - if (bound && bound._batchEnabled === batchId - && bound._batchLocation === j) { - j++; - continue; - } - ids[i] = j; - tex._batchLocation = j; - boundTextures[j] = tex; - break; - } - } - }; - return BatchSystem; - }(System)); - - var CONTEXT_UID_COUNTER = 0; - /** - * System plugin to the renderer to manage the context. - * - * @class - * @extends PIXI.System - * @memberof PIXI.systems - */ - var ContextSystem = /** @class */ (function (_super) { - __extends$2(ContextSystem, _super); - /* eslint-enable camelcase */ - /** - * @param {PIXI.Renderer} renderer - The renderer this System works for. - */ - function ContextSystem(renderer) { - var _this = _super.call(this, renderer) || this; - /** - * Either 1 or 2 to reflect the WebGL version being used - * @member {number} - * @readonly - */ - _this.webGLVersion = 1; - /** - * Extensions being used - * @member {object} - * @readonly - * @property {WEBGL_draw_buffers} drawBuffers - WebGL v1 extension - * @property {WEBGL_depth_texture} depthTexture - WebGL v1 extension - * @property {OES_texture_float} floatTexture - WebGL v1 extension - * @property {WEBGL_lose_context} loseContext - WebGL v1 extension - * @property {OES_vertex_array_object} vertexArrayObject - WebGL v1 extension - * @property {EXT_texture_filter_anisotropic} anisotropicFiltering - WebGL v1 and v2 extension - */ - _this.extensions = {}; - /** - * Features supported by current context - * @member {object} - * @private - * @readonly - * @property {boolean} uint32Indices - Supports of 32-bit indices buffer - */ - _this.supports = { - uint32Indices: false, - }; - // Bind functions - _this.handleContextLost = _this.handleContextLost.bind(_this); - _this.handleContextRestored = _this.handleContextRestored.bind(_this); - renderer.view.addEventListener('webglcontextlost', _this.handleContextLost, false); - renderer.view.addEventListener('webglcontextrestored', _this.handleContextRestored, false); - return _this; - } - Object.defineProperty(ContextSystem.prototype, "isLost", { - /** - * `true` if the context is lost - * @member {boolean} - * @readonly - */ - get: function () { - return (!this.gl || this.gl.isContextLost()); - }, - enumerable: false, - configurable: true - }); - /** - * Handle the context change event - * @param {WebGLRenderingContext} gl - new webgl context - */ - ContextSystem.prototype.contextChange = function (gl) { - this.gl = gl; - this.renderer.gl = gl; - this.renderer.CONTEXT_UID = CONTEXT_UID_COUNTER++; - // restore a context if it was previously lost - if (gl.isContextLost() && gl.getExtension('WEBGL_lose_context')) { - gl.getExtension('WEBGL_lose_context').restoreContext(); - } - }; - /** - * Initialize the context - * - * @protected - * @param {WebGLRenderingContext} gl - WebGL context - */ - ContextSystem.prototype.initFromContext = function (gl) { - this.gl = gl; - this.validateContext(gl); - this.renderer.gl = gl; - this.renderer.CONTEXT_UID = CONTEXT_UID_COUNTER++; - this.renderer.runners.contextChange.emit(gl); - }; - /** - * Initialize from context options - * - * @protected - * @see https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/getContext - * @param {object} options - context attributes - */ - ContextSystem.prototype.initFromOptions = function (options) { - var gl = this.createContext(this.renderer.view, options); - this.initFromContext(gl); - }; - /** - * Helper class to create a WebGL Context - * - * @param canvas {HTMLCanvasElement} the canvas element that we will get the context from - * @param options {object} An options object that gets passed in to the canvas element containing the context attributes - * @see https://developer.mozilla.org/en/docs/Web/API/HTMLCanvasElement/getContext - * @return {WebGLRenderingContext} the WebGL context - */ - ContextSystem.prototype.createContext = function (canvas, options) { - var gl; - if (settings.PREFER_ENV >= exports.ENV.WEBGL2) { - gl = canvas.getContext('webgl2', options); - } - if (gl) { - this.webGLVersion = 2; - } - else { - this.webGLVersion = 1; - gl = canvas.getContext('webgl', options) - || canvas.getContext('experimental-webgl', options); - if (!gl) { - // fail, not able to get a context - throw new Error('This browser does not support WebGL. Try using the canvas renderer'); - } - } - this.gl = gl; - this.getExtensions(); - return this.gl; - }; - /** - * Auto-populate the extensions - * - * @protected - */ - ContextSystem.prototype.getExtensions = function () { - // time to set up default extensions that Pixi uses. - var gl = this.gl; - if (this.webGLVersion === 1) { - Object.assign(this.extensions, { - drawBuffers: gl.getExtension('WEBGL_draw_buffers'), - depthTexture: gl.getExtension('WEBGL_depth_texture'), - loseContext: gl.getExtension('WEBGL_lose_context'), - vertexArrayObject: gl.getExtension('OES_vertex_array_object') - || gl.getExtension('MOZ_OES_vertex_array_object') - || gl.getExtension('WEBKIT_OES_vertex_array_object'), - anisotropicFiltering: gl.getExtension('EXT_texture_filter_anisotropic'), - uint32ElementIndex: gl.getExtension('OES_element_index_uint'), - // Floats and half-floats - floatTexture: gl.getExtension('OES_texture_float'), - floatTextureLinear: gl.getExtension('OES_texture_float_linear'), - textureHalfFloat: gl.getExtension('OES_texture_half_float'), - textureHalfFloatLinear: gl.getExtension('OES_texture_half_float_linear'), - }); - } - else if (this.webGLVersion === 2) { - Object.assign(this.extensions, { - anisotropicFiltering: gl.getExtension('EXT_texture_filter_anisotropic'), - // Floats and half-floats - colorBufferFloat: gl.getExtension('EXT_color_buffer_float'), - floatTextureLinear: gl.getExtension('OES_texture_float_linear'), - }); - } - }; - /** - * Handles a lost webgl context - * - * @protected - * @param {WebGLContextEvent} event - The context lost event. - */ - ContextSystem.prototype.handleContextLost = function (event) { - event.preventDefault(); - }; - /** - * Handles a restored webgl context - * - * @protected - */ - ContextSystem.prototype.handleContextRestored = function () { - this.renderer.runners.contextChange.emit(this.gl); - }; - ContextSystem.prototype.destroy = function () { - var view = this.renderer.view; - // remove listeners - view.removeEventListener('webglcontextlost', this.handleContextLost); - view.removeEventListener('webglcontextrestored', this.handleContextRestored); - this.gl.useProgram(null); - if (this.extensions.loseContext) { - this.extensions.loseContext.loseContext(); - } - }; - /** - * Handle the post-render runner event - * - * @protected - */ - ContextSystem.prototype.postrender = function () { - if (this.renderer.renderingToScreen) { - this.gl.flush(); - } - }; - /** - * Validate context - * - * @protected - * @param {WebGLRenderingContext} gl - Render context - */ - ContextSystem.prototype.validateContext = function (gl) { - var attributes = gl.getContextAttributes(); - // this is going to be fairly simple for now.. but at least we have room to grow! - if (!attributes.stencil) { - /* eslint-disable max-len, no-console */ - console.warn('Provided WebGL context does not have a stencil buffer, masks may not render correctly'); - /* eslint-enable max-len, no-console */ - } - var hasuint32 = ('WebGL2RenderingContext' in window && gl instanceof window.WebGL2RenderingContext) - || !!gl.getExtension('OES_element_index_uint'); - this.supports.uint32Indices = hasuint32; - if (!hasuint32) { - /* eslint-disable max-len, no-console */ - console.warn('Provided WebGL context does not support 32 index buffer, complex graphics may not render correctly'); - /* eslint-enable max-len, no-console */ - } - }; - return ContextSystem; - }(System)); - - /** - * Internal framebuffer for WebGL context - * @class - * @memberof PIXI - */ - var GLFramebuffer = /** @class */ (function () { - function GLFramebuffer(framebuffer) { - /** - * The WebGL framebuffer - * @member {WebGLFramebuffer} - */ - this.framebuffer = framebuffer; - /** - * stencil+depth , usually costs 32bits per pixel - * @member {WebGLRenderbuffer} - */ - this.stencil = null; - /** - * latest known version of framebuffer - * @member {number} - * @protected - */ - this.dirtyId = 0; - /** - * latest known version of framebuffer format - * @member {number} - * @protected - */ - this.dirtyFormat = 0; - /** - * latest known version of framebuffer size - * @member {number} - * @protected - */ - this.dirtySize = 0; - /** - * Detected AA samples number - * @member {PIXI.MSAA_QUALITY} - */ - this.multisample = exports.MSAA_QUALITY.NONE; - /** - * In case MSAA, we use this Renderbuffer instead of colorTextures[0] when we write info - * @member {WebGLRenderbuffer} - */ - this.msaaBuffer = null; - /** - * In case we use MSAA, this is actual framebuffer that has colorTextures[0] - * The contents of that framebuffer are read when we use that renderTexture in sprites - * @member {PIXI.Framebuffer} - */ - this.blitFramebuffer = null; - } - return GLFramebuffer; - }()); - - var tempRectangle = new Rectangle(); - /** - * System plugin to the renderer to manage framebuffers. - * - * @class - * @extends PIXI.System - * @memberof PIXI.systems - */ - var FramebufferSystem = /** @class */ (function (_super) { - __extends$2(FramebufferSystem, _super); - /** - * @param {PIXI.Renderer} renderer - The renderer this System works for. - */ - function FramebufferSystem(renderer) { - var _this = _super.call(this, renderer) || this; - /** - * A list of managed framebuffers - * @member {PIXI.Framebuffer[]} - * @readonly - */ - _this.managedFramebuffers = []; - /** - * Framebuffer value that shows that we don't know what is bound - * @member {Framebuffer} - * @readonly - */ - _this.unknownFramebuffer = new Framebuffer(10, 10); - _this.msaaSamples = null; - return _this; - } - /** - * Sets up the renderer context and necessary buffers. - */ - FramebufferSystem.prototype.contextChange = function () { - var gl = this.gl = this.renderer.gl; - this.CONTEXT_UID = this.renderer.CONTEXT_UID; - this.current = this.unknownFramebuffer; - this.viewport = new Rectangle(); - this.hasMRT = true; - this.writeDepthTexture = true; - this.disposeAll(true); - // webgl2 - if (this.renderer.context.webGLVersion === 1) { - // webgl 1! - var nativeDrawBuffersExtension_1 = this.renderer.context.extensions.drawBuffers; - var nativeDepthTextureExtension = this.renderer.context.extensions.depthTexture; - if (settings.PREFER_ENV === exports.ENV.WEBGL_LEGACY) { - nativeDrawBuffersExtension_1 = null; - nativeDepthTextureExtension = null; - } - if (nativeDrawBuffersExtension_1) { - gl.drawBuffers = function (activeTextures) { - return nativeDrawBuffersExtension_1.drawBuffersWEBGL(activeTextures); - }; - } - else { - this.hasMRT = false; - gl.drawBuffers = function () { - // empty - }; - } - if (!nativeDepthTextureExtension) { - this.writeDepthTexture = false; - } - } - else { - // WebGL2 - // cache possible MSAA samples - this.msaaSamples = gl.getInternalformatParameter(gl.RENDERBUFFER, gl.RGBA8, gl.SAMPLES); - } - }; - /** - * Bind a framebuffer - * - * @param {PIXI.Framebuffer} framebuffer - * @param {PIXI.Rectangle} [frame] frame, default is framebuffer size - */ - FramebufferSystem.prototype.bind = function (framebuffer, frame) { - var gl = this.gl; - if (framebuffer) { - // TODO caching layer! - var fbo = framebuffer.glFramebuffers[this.CONTEXT_UID] || this.initFramebuffer(framebuffer); - if (this.current !== framebuffer) { - this.current = framebuffer; - gl.bindFramebuffer(gl.FRAMEBUFFER, fbo.framebuffer); - } - // make sure all textures are unbound.. - // now check for updates... - if (fbo.dirtyId !== framebuffer.dirtyId) { - fbo.dirtyId = framebuffer.dirtyId; - if (fbo.dirtyFormat !== framebuffer.dirtyFormat) { - fbo.dirtyFormat = framebuffer.dirtyFormat; - this.updateFramebuffer(framebuffer); - } - else if (fbo.dirtySize !== framebuffer.dirtySize) { - fbo.dirtySize = framebuffer.dirtySize; - this.resizeFramebuffer(framebuffer); - } - } - for (var i = 0; i < framebuffer.colorTextures.length; i++) { - var tex = framebuffer.colorTextures[i]; - this.renderer.texture.unbind(tex.parentTextureArray || tex); - } - if (framebuffer.depthTexture) { - this.renderer.texture.unbind(framebuffer.depthTexture); - } - if (frame) { - this.setViewport(frame.x, frame.y, frame.width, frame.height); - } - else { - this.setViewport(0, 0, framebuffer.width, framebuffer.height); - } - } - else { - if (this.current) { - this.current = null; - gl.bindFramebuffer(gl.FRAMEBUFFER, null); - } - if (frame) { - this.setViewport(frame.x, frame.y, frame.width, frame.height); - } - else { - this.setViewport(0, 0, this.renderer.width, this.renderer.height); - } - } - }; - /** - * Set the WebGLRenderingContext's viewport. - * - * @param {Number} x - X position of viewport - * @param {Number} y - Y position of viewport - * @param {Number} width - Width of viewport - * @param {Number} height - Height of viewport - */ - FramebufferSystem.prototype.setViewport = function (x, y, width, height) { - var v = this.viewport; - if (v.width !== width || v.height !== height || v.x !== x || v.y !== y) { - v.x = x; - v.y = y; - v.width = width; - v.height = height; - this.gl.viewport(x, y, width, height); - } - }; - Object.defineProperty(FramebufferSystem.prototype, "size", { - /** - * Get the size of the current width and height. Returns object with `width` and `height` values. - * - * @member {object} - * @readonly - */ - get: function () { - if (this.current) { - // TODO store temp - return { x: 0, y: 0, width: this.current.width, height: this.current.height }; - } - return { x: 0, y: 0, width: this.renderer.width, height: this.renderer.height }; - }, - enumerable: false, - configurable: true - }); - /** - * Clear the color of the context - * - * @param {Number} r - Red value from 0 to 1 - * @param {Number} g - Green value from 0 to 1 - * @param {Number} b - Blue value from 0 to 1 - * @param {Number} a - Alpha value from 0 to 1 - * @param {PIXI.BUFFER_BITS} [mask=BUFFER_BITS.COLOR | BUFFER_BITS.DEPTH] - Bitwise OR of masks - * that indicate the buffers to be cleared, by default COLOR and DEPTH buffers. - */ - FramebufferSystem.prototype.clear = function (r, g, b, a, mask) { - if (mask === void 0) { mask = exports.BUFFER_BITS.COLOR | exports.BUFFER_BITS.DEPTH; } - var gl = this.gl; - // TODO clear color can be set only one right? - gl.clearColor(r, g, b, a); - gl.clear(mask); - }; - /** - * Initialize framebuffer for this context - * - * @protected - * @param {PIXI.Framebuffer} framebuffer - * @returns {PIXI.GLFramebuffer} created GLFramebuffer - */ - FramebufferSystem.prototype.initFramebuffer = function (framebuffer) { - var gl = this.gl; - var fbo = new GLFramebuffer(gl.createFramebuffer()); - fbo.multisample = this.detectSamples(framebuffer.multisample); - framebuffer.glFramebuffers[this.CONTEXT_UID] = fbo; - this.managedFramebuffers.push(framebuffer); - framebuffer.disposeRunner.add(this); - return fbo; - }; - /** - * Resize the framebuffer - * - * @protected - * @param {PIXI.Framebuffer} framebuffer - */ - FramebufferSystem.prototype.resizeFramebuffer = function (framebuffer) { - var gl = this.gl; - var fbo = framebuffer.glFramebuffers[this.CONTEXT_UID]; - if (fbo.stencil) { - gl.bindRenderbuffer(gl.RENDERBUFFER, fbo.stencil); - gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, framebuffer.width, framebuffer.height); - } - var colorTextures = framebuffer.colorTextures; - for (var i = 0; i < colorTextures.length; i++) { - this.renderer.texture.bind(colorTextures[i], 0); - } - if (framebuffer.depthTexture) { - this.renderer.texture.bind(framebuffer.depthTexture, 0); - } - }; - /** - * Update the framebuffer - * - * @protected - * @param {PIXI.Framebuffer} framebuffer - */ - FramebufferSystem.prototype.updateFramebuffer = function (framebuffer) { - var gl = this.gl; - var fbo = framebuffer.glFramebuffers[this.CONTEXT_UID]; - // bind the color texture - var colorTextures = framebuffer.colorTextures; - var count = colorTextures.length; - if (!gl.drawBuffers) { - count = Math.min(count, 1); - } - if (fbo.multisample > 1) { - fbo.msaaBuffer = gl.createRenderbuffer(); - gl.bindRenderbuffer(gl.RENDERBUFFER, fbo.msaaBuffer); - gl.renderbufferStorageMultisample(gl.RENDERBUFFER, fbo.multisample, gl.RGBA8, framebuffer.width, framebuffer.height); - gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, fbo.msaaBuffer); - } - var activeTextures = []; - for (var i = 0; i < count; i++) { - if (i === 0 && fbo.multisample > 1) { - continue; - } - var texture = framebuffer.colorTextures[i]; - var parentTexture = texture.parentTextureArray || texture; - this.renderer.texture.bind(parentTexture, 0); - gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, texture.target, parentTexture._glTextures[this.CONTEXT_UID].texture, 0); - activeTextures.push(gl.COLOR_ATTACHMENT0 + i); - } - if (activeTextures.length > 1) { - gl.drawBuffers(activeTextures); - } - if (framebuffer.depthTexture) { - var writeDepthTexture = this.writeDepthTexture; - if (writeDepthTexture) { - var depthTexture = framebuffer.depthTexture; - this.renderer.texture.bind(depthTexture, 0); - gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._glTextures[this.CONTEXT_UID].texture, 0); - } - } - if (!fbo.stencil && (framebuffer.stencil || framebuffer.depth)) { - fbo.stencil = gl.createRenderbuffer(); - gl.bindRenderbuffer(gl.RENDERBUFFER, fbo.stencil); - gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, framebuffer.width, framebuffer.height); - // TODO.. this is depth AND stencil? - if (!framebuffer.depthTexture) { // you can't have both, so one should take priority if enabled - gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, fbo.stencil); - } - } - }; - /** - * Detects number of samples that is not more than a param but as close to it as possible - * - * @param {PIXI.MSAA_QUALITY} samples - number of samples - * @returns {PIXI.MSAA_QUALITY} - recommended number of samples - */ - FramebufferSystem.prototype.detectSamples = function (samples) { - var msaaSamples = this.msaaSamples; - var res = exports.MSAA_QUALITY.NONE; - if (samples <= 1 || msaaSamples === null) { - return res; - } - for (var i = 0; i < msaaSamples.length; i++) { - if (msaaSamples[i] <= samples) { - res = msaaSamples[i]; - break; - } - } - if (res === 1) { - res = exports.MSAA_QUALITY.NONE; - } - return res; - }; - /** - * Only works with WebGL2 - * - * blits framebuffer to another of the same or bigger size - * after that target framebuffer is bound - * - * Fails with WebGL warning if blits multisample framebuffer to different size - * - * @param {PIXI.Framebuffer} [framebuffer] - by default it blits "into itself", from renderBuffer to texture. - * @param {PIXI.Rectangle} [sourcePixels] - source rectangle in pixels - * @param {PIXI.Rectangle} [destPixels] - dest rectangle in pixels, assumed to be the same as sourcePixels - */ - FramebufferSystem.prototype.blit = function (framebuffer, sourcePixels, destPixels) { - var _a = this, current = _a.current, renderer = _a.renderer, gl = _a.gl, CONTEXT_UID = _a.CONTEXT_UID; - if (renderer.context.webGLVersion !== 2) { - return; - } - if (!current) { - return; - } - var fbo = current.glFramebuffers[CONTEXT_UID]; - if (!fbo) { - return; - } - if (!framebuffer) { - if (fbo.multisample <= 1) { - return; - } - if (!fbo.blitFramebuffer) { - fbo.blitFramebuffer = new Framebuffer(current.width, current.height); - fbo.blitFramebuffer.addColorTexture(0, current.colorTextures[0]); - } - framebuffer = fbo.blitFramebuffer; - framebuffer.width = current.width; - framebuffer.height = current.height; - } - if (!sourcePixels) { - sourcePixels = tempRectangle; - sourcePixels.width = current.width; - sourcePixels.height = current.height; - } - if (!destPixels) { - destPixels = sourcePixels; - } - var sameSize = sourcePixels.width === destPixels.width && sourcePixels.height === destPixels.height; - this.bind(framebuffer); - gl.bindFramebuffer(gl.READ_FRAMEBUFFER, fbo.framebuffer); - gl.blitFramebuffer(sourcePixels.x, sourcePixels.y, sourcePixels.width, sourcePixels.height, destPixels.x, destPixels.y, destPixels.width, destPixels.height, gl.COLOR_BUFFER_BIT, sameSize ? gl.NEAREST : gl.LINEAR); - }; - /** - * Disposes framebuffer - * @param {PIXI.Framebuffer} framebuffer - framebuffer that has to be disposed of - * @param {boolean} [contextLost=false] - If context was lost, we suppress all delete function calls - */ - FramebufferSystem.prototype.disposeFramebuffer = function (framebuffer, contextLost) { - var fbo = framebuffer.glFramebuffers[this.CONTEXT_UID]; - var gl = this.gl; - if (!fbo) { - return; - } - delete framebuffer.glFramebuffers[this.CONTEXT_UID]; - var index = this.managedFramebuffers.indexOf(framebuffer); - if (index >= 0) { - this.managedFramebuffers.splice(index, 1); - } - framebuffer.disposeRunner.remove(this); - if (!contextLost) { - gl.deleteFramebuffer(fbo.framebuffer); - if (fbo.stencil) { - gl.deleteRenderbuffer(fbo.stencil); - } - } - }; - /** - * Disposes all framebuffers, but not textures bound to them - * @param {boolean} [contextLost=false] - If context was lost, we suppress all delete function calls - */ - FramebufferSystem.prototype.disposeAll = function (contextLost) { - var list = this.managedFramebuffers; - this.managedFramebuffers = []; - for (var i = 0; i < list.length; i++) { - this.disposeFramebuffer(list[i], contextLost); - } - }; - /** - * Forcing creation of stencil buffer for current framebuffer, if it wasn't done before. - * Used by MaskSystem, when its time to use stencil mask for Graphics element. - * - * Its an alternative for public lazy `framebuffer.enableStencil`, in case we need stencil without rebind. - * - * @private - */ - FramebufferSystem.prototype.forceStencil = function () { - var framebuffer = this.current; - if (!framebuffer) { - return; - } - var fbo = framebuffer.glFramebuffers[this.CONTEXT_UID]; - if (!fbo || fbo.stencil) { - return; - } - framebuffer.enableStencil(); - var w = framebuffer.width; - var h = framebuffer.height; - var gl = this.gl; - var stencil = gl.createRenderbuffer(); - gl.bindRenderbuffer(gl.RENDERBUFFER, stencil); - gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, w, h); - fbo.stencil = stencil; - gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, stencil); - }; - /** - * resets framebuffer stored state, binds screen framebuffer - * - * should be called before renderTexture reset() - */ - FramebufferSystem.prototype.reset = function () { - this.current = this.unknownFramebuffer; - this.viewport = new Rectangle(); - }; - return FramebufferSystem; - }(System)); - - var GLBuffer = /** @class */ (function () { - function GLBuffer(buffer) { - this.buffer = buffer || null; - this.updateID = -1; - this.byteLength = -1; - this.refCount = 0; - } - return GLBuffer; - }()); - - var byteSizeMap$1 = { 5126: 4, 5123: 2, 5121: 1 }; - /** - * System plugin to the renderer to manage geometry. - * - * @class - * @extends PIXI.System - * @memberof PIXI.systems - */ - var GeometrySystem = /** @class */ (function (_super) { - __extends$2(GeometrySystem, _super); - /** - * @param {PIXI.Renderer} renderer - The renderer this System works for. - */ - function GeometrySystem(renderer) { - var _this = _super.call(this, renderer) || this; - _this._activeGeometry = null; - _this._activeVao = null; - /** - * `true` if we has `*_vertex_array_object` extension - * @member {boolean} - * @readonly - */ - _this.hasVao = true; - /** - * `true` if has `ANGLE_instanced_arrays` extension - * @member {boolean} - * @readonly - */ - _this.hasInstance = true; - /** - * `true` if support `gl.UNSIGNED_INT` in `gl.drawElements` or `gl.drawElementsInstanced` - * @member {boolean} - * @readonly - */ - _this.canUseUInt32ElementIndex = false; - /** - * Cache for all geometries by id, used in case renderer gets destroyed or for profiling - * @member {object} - * @readonly - */ - _this.managedGeometries = {}; - /** - * Cache for all buffers by id, used in case renderer gets destroyed or for profiling - * @member {object} - * @readonly - */ - _this.managedBuffers = {}; - return _this; - } - /** - * Sets up the renderer context and necessary buffers. - */ - GeometrySystem.prototype.contextChange = function () { - this.disposeAll(true); - var gl = this.gl = this.renderer.gl; - var context = this.renderer.context; - this.CONTEXT_UID = this.renderer.CONTEXT_UID; - // webgl2 - if (!gl.createVertexArray) { - // webgl 1! - var nativeVaoExtension_1 = this.renderer.context.extensions.vertexArrayObject; - if (settings.PREFER_ENV === exports.ENV.WEBGL_LEGACY) { - nativeVaoExtension_1 = null; - } - if (nativeVaoExtension_1) { - gl.createVertexArray = function () { - return nativeVaoExtension_1.createVertexArrayOES(); - }; - gl.bindVertexArray = function (vao) { - return nativeVaoExtension_1.bindVertexArrayOES(vao); - }; - gl.deleteVertexArray = function (vao) { - return nativeVaoExtension_1.deleteVertexArrayOES(vao); - }; - } - else { - this.hasVao = false; - gl.createVertexArray = function () { - return null; - }; - gl.bindVertexArray = function () { - return null; - }; - gl.deleteVertexArray = function () { - return null; - }; - } - } - if (!gl.vertexAttribDivisor) { - var instanceExt_1 = gl.getExtension('ANGLE_instanced_arrays'); - if (instanceExt_1) { - gl.vertexAttribDivisor = function (a, b) { - return instanceExt_1.vertexAttribDivisorANGLE(a, b); - }; - gl.drawElementsInstanced = function (a, b, c, d, e) { - return instanceExt_1.drawElementsInstancedANGLE(a, b, c, d, e); - }; - gl.drawArraysInstanced = function (a, b, c, d) { - return instanceExt_1.drawArraysInstancedANGLE(a, b, c, d); - }; - } - else { - this.hasInstance = false; - } - } - this.canUseUInt32ElementIndex = context.webGLVersion === 2 || !!context.extensions.uint32ElementIndex; - }; - /** - * Binds geometry so that is can be drawn. Creating a Vao if required - * - * @param {PIXI.Geometry} geometry - instance of geometry to bind - * @param {PIXI.Shader} [shader] - instance of shader to use vao for - */ - GeometrySystem.prototype.bind = function (geometry, shader) { - shader = shader || this.renderer.shader.shader; - var gl = this.gl; - // not sure the best way to address this.. - // currently different shaders require different VAOs for the same geometry - // Still mulling over the best way to solve this one.. - // will likely need to modify the shader attribute locations at run time! - var vaos = geometry.glVertexArrayObjects[this.CONTEXT_UID]; - if (!vaos) { - this.managedGeometries[geometry.id] = geometry; - geometry.disposeRunner.add(this); - geometry.glVertexArrayObjects[this.CONTEXT_UID] = vaos = {}; - } - var vao = vaos[shader.program.id] || this.initGeometryVao(geometry, shader.program); - this._activeGeometry = geometry; - if (this._activeVao !== vao) { - this._activeVao = vao; - if (this.hasVao) { - gl.bindVertexArray(vao); - } - else { - this.activateVao(geometry, shader.program); - } - } - // TODO - optimise later! - // don't need to loop through if nothing changed! - // maybe look to add an 'autoupdate' to geometry? - this.updateBuffers(); - }; - /** - * Reset and unbind any active VAO and geometry - */ - GeometrySystem.prototype.reset = function () { - this.unbind(); - }; - /** - * Update buffers - * @protected - */ - GeometrySystem.prototype.updateBuffers = function () { - var geometry = this._activeGeometry; - var gl = this.gl; - for (var i = 0; i < geometry.buffers.length; i++) { - var buffer = geometry.buffers[i]; - var glBuffer = buffer._glBuffers[this.CONTEXT_UID]; - if (buffer._updateID !== glBuffer.updateID) { - glBuffer.updateID = buffer._updateID; - // TODO can cache this on buffer! maybe added a getter / setter? - var type = buffer.index ? gl.ELEMENT_ARRAY_BUFFER : gl.ARRAY_BUFFER; - // TODO this could change if the VAO changes... - // need to come up with a better way to cache.. - // if (this.boundBuffers[type] !== glBuffer) - // { - // this.boundBuffers[type] = glBuffer; - gl.bindBuffer(type, glBuffer.buffer); - // } - this._boundBuffer = glBuffer; - if (glBuffer.byteLength >= buffer.data.byteLength) { - // offset is always zero for now! - gl.bufferSubData(type, 0, buffer.data); - } - else { - var drawType = buffer.static ? gl.STATIC_DRAW : gl.DYNAMIC_DRAW; - glBuffer.byteLength = buffer.data.byteLength; - gl.bufferData(type, buffer.data, drawType); - } - } - } - }; - /** - * Check compability between a geometry and a program - * @protected - * @param {PIXI.Geometry} geometry - Geometry instance - * @param {PIXI.Program} program - Program instance - */ - GeometrySystem.prototype.checkCompatibility = function (geometry, program) { - // geometry must have at least all the attributes that the shader requires. - var geometryAttributes = geometry.attributes; - var shaderAttributes = program.attributeData; - for (var j in shaderAttributes) { - if (!geometryAttributes[j]) { - throw new Error("shader and geometry incompatible, geometry missing the \"" + j + "\" attribute"); - } - } - }; - /** - * Takes a geometry and program and generates a unique signature for them. - * - * @param {PIXI.Geometry} geometry - to get signature from - * @param {PIXI.Program} program - to test geometry against - * @returns {String} Unique signature of the geometry and program - * @protected - */ - GeometrySystem.prototype.getSignature = function (geometry, program) { - var attribs = geometry.attributes; - var shaderAttributes = program.attributeData; - var strings = ['g', geometry.id]; - for (var i in attribs) { - if (shaderAttributes[i]) { - strings.push(i); - } - } - return strings.join('-'); - }; - /** - * Creates or gets Vao with the same structure as the geometry and stores it on the geometry. - * If vao is created, it is bound automatically. - * - * @protected - * @param {PIXI.Geometry} geometry - Instance of geometry to to generate Vao for - * @param {PIXI.Program} program - Instance of program - */ - GeometrySystem.prototype.initGeometryVao = function (geometry, program) { - this.checkCompatibility(geometry, program); - var gl = this.gl; - var CONTEXT_UID = this.CONTEXT_UID; - var signature = this.getSignature(geometry, program); - var vaoObjectHash = geometry.glVertexArrayObjects[this.CONTEXT_UID]; - var vao = vaoObjectHash[signature]; - if (vao) { - // this will give us easy access to the vao - vaoObjectHash[program.id] = vao; - return vao; - } - var buffers = geometry.buffers; - var attributes = geometry.attributes; - var tempStride = {}; - var tempStart = {}; - for (var j in buffers) { - tempStride[j] = 0; - tempStart[j] = 0; - } - for (var j in attributes) { - if (!attributes[j].size && program.attributeData[j]) { - attributes[j].size = program.attributeData[j].size; - } - else if (!attributes[j].size) { - console.warn("PIXI Geometry attribute '" + j + "' size cannot be determined (likely the bound shader does not have the attribute)"); // eslint-disable-line - } - tempStride[attributes[j].buffer] += attributes[j].size * byteSizeMap$1[attributes[j].type]; - } - for (var j in attributes) { - var attribute = attributes[j]; - var attribSize = attribute.size; - if (attribute.stride === undefined) { - if (tempStride[attribute.buffer] === attribSize * byteSizeMap$1[attribute.type]) { - attribute.stride = 0; - } - else { - attribute.stride = tempStride[attribute.buffer]; - } - } - if (attribute.start === undefined) { - attribute.start = tempStart[attribute.buffer]; - tempStart[attribute.buffer] += attribSize * byteSizeMap$1[attribute.type]; - } - } - vao = gl.createVertexArray(); - gl.bindVertexArray(vao); - // first update - and create the buffers! - // only create a gl buffer if it actually gets - for (var i = 0; i < buffers.length; i++) { - var buffer = buffers[i]; - if (!buffer._glBuffers[CONTEXT_UID]) { - buffer._glBuffers[CONTEXT_UID] = new GLBuffer(gl.createBuffer()); - this.managedBuffers[buffer.id] = buffer; - buffer.disposeRunner.add(this); - } - buffer._glBuffers[CONTEXT_UID].refCount++; - } - // TODO - maybe make this a data object? - // lets wait to see if we need to first! - this.activateVao(geometry, program); - this._activeVao = vao; - // add it to the cache! - vaoObjectHash[program.id] = vao; - vaoObjectHash[signature] = vao; - return vao; - }; - /** - * Disposes buffer - * @param {PIXI.Buffer} buffer - buffer with data - * @param {boolean} [contextLost=false] - If context was lost, we suppress deleteVertexArray - */ - GeometrySystem.prototype.disposeBuffer = function (buffer, contextLost) { - if (!this.managedBuffers[buffer.id]) { - return; - } - delete this.managedBuffers[buffer.id]; - var glBuffer = buffer._glBuffers[this.CONTEXT_UID]; - var gl = this.gl; - buffer.disposeRunner.remove(this); - if (!glBuffer) { - return; - } - if (!contextLost) { - gl.deleteBuffer(glBuffer.buffer); - } - delete buffer._glBuffers[this.CONTEXT_UID]; - }; - /** - * Disposes geometry - * @param {PIXI.Geometry} geometry - Geometry with buffers. Only VAO will be disposed - * @param {boolean} [contextLost=false] - If context was lost, we suppress deleteVertexArray - */ - GeometrySystem.prototype.disposeGeometry = function (geometry, contextLost) { - if (!this.managedGeometries[geometry.id]) { - return; - } - delete this.managedGeometries[geometry.id]; - var vaos = geometry.glVertexArrayObjects[this.CONTEXT_UID]; - var gl = this.gl; - var buffers = geometry.buffers; - geometry.disposeRunner.remove(this); - if (!vaos) { - return; - } - for (var i = 0; i < buffers.length; i++) { - var buf = buffers[i]._glBuffers[this.CONTEXT_UID]; - buf.refCount--; - if (buf.refCount === 0 && !contextLost) { - this.disposeBuffer(buffers[i], contextLost); - } - } - if (!contextLost) { - for (var vaoId in vaos) { - // delete only signatures, everything else are copies - if (vaoId[0] === 'g') { - var vao = vaos[vaoId]; - if (this._activeVao === vao) { - this.unbind(); - } - gl.deleteVertexArray(vao); - } - } - } - delete geometry.glVertexArrayObjects[this.CONTEXT_UID]; - }; - /** - * dispose all WebGL resources of all managed geometries and buffers - * @param {boolean} [contextLost=false] - If context was lost, we suppress `gl.delete` calls - */ - GeometrySystem.prototype.disposeAll = function (contextLost) { - var all = Object.keys(this.managedGeometries); - for (var i = 0; i < all.length; i++) { - this.disposeGeometry(this.managedGeometries[all[i]], contextLost); - } - all = Object.keys(this.managedBuffers); - for (var i = 0; i < all.length; i++) { - this.disposeBuffer(this.managedBuffers[all[i]], contextLost); - } - }; - /** - * Activate vertex array object - * - * @protected - * @param {PIXI.Geometry} geometry - Geometry instance - * @param {PIXI.Program} program - Shader program instance - */ - GeometrySystem.prototype.activateVao = function (geometry, program) { - var gl = this.gl; - var CONTEXT_UID = this.CONTEXT_UID; - var buffers = geometry.buffers; - var attributes = geometry.attributes; - if (geometry.indexBuffer) { - // first update the index buffer if we have one.. - gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, geometry.indexBuffer._glBuffers[CONTEXT_UID].buffer); - } - var lastBuffer = null; - // add a new one! - for (var j in attributes) { - var attribute = attributes[j]; - var buffer = buffers[attribute.buffer]; - var glBuffer = buffer._glBuffers[CONTEXT_UID]; - if (program.attributeData[j]) { - if (lastBuffer !== glBuffer) { - gl.bindBuffer(gl.ARRAY_BUFFER, glBuffer.buffer); - lastBuffer = glBuffer; - } - var location = program.attributeData[j].location; - // TODO introduce state again - // we can optimise this for older devices that have no VAOs - gl.enableVertexAttribArray(location); - gl.vertexAttribPointer(location, attribute.size, attribute.type || gl.FLOAT, attribute.normalized, attribute.stride, attribute.start); - if (attribute.instance) { - // TODO calculate instance count based of this... - if (this.hasInstance) { - gl.vertexAttribDivisor(location, 1); - } - else { - throw new Error('geometry error, GPU Instancing is not supported on this device'); - } - } - } - } - }; - /** - * Draw the geometry - * - * @param {Number} type - the type primitive to render - * @param {Number} [size] - the number of elements to be rendered - * @param {Number} [start] - Starting index - * @param {Number} [instanceCount] - the number of instances of the set of elements to execute - */ - GeometrySystem.prototype.draw = function (type, size, start, instanceCount) { - var gl = this.gl; - var geometry = this._activeGeometry; - // TODO.. this should not change so maybe cache the function? - if (geometry.indexBuffer) { - var byteSize = geometry.indexBuffer.data.BYTES_PER_ELEMENT; - var glType = byteSize === 2 ? gl.UNSIGNED_SHORT : gl.UNSIGNED_INT; - if (byteSize === 2 || (byteSize === 4 && this.canUseUInt32ElementIndex)) { - if (geometry.instanced) { - /* eslint-disable max-len */ - gl.drawElementsInstanced(type, size || geometry.indexBuffer.data.length, glType, (start || 0) * byteSize, instanceCount || 1); - /* eslint-enable max-len */ - } - else { - /* eslint-disable max-len */ - gl.drawElements(type, size || geometry.indexBuffer.data.length, glType, (start || 0) * byteSize); - /* eslint-enable max-len */ - } - } - else { - console.warn('unsupported index buffer type: uint32'); - } - } - else if (geometry.instanced) { - // TODO need a better way to calculate size.. - gl.drawArraysInstanced(type, start, size || geometry.getSize(), instanceCount || 1); - } - else { - gl.drawArrays(type, start, size || geometry.getSize()); - } - return this; - }; - /** - * Unbind/reset everything - * @protected - */ - GeometrySystem.prototype.unbind = function () { - this.gl.bindVertexArray(null); - this._activeVao = null; - this._activeGeometry = null; - }; - return GeometrySystem; - }(System)); - - /** - * Component for masked elements - * - * Holds mask mode and temporary data about current mask - * - * @class - * @memberof PIXI - */ - var MaskData = /** @class */ (function () { - /** - * Create MaskData - * - * @param {PIXI.DisplayObject} [maskObject=null] - object that describes the mask - */ - function MaskData(maskObject) { - if (maskObject === void 0) { maskObject = null; } - /** - * Mask type - * @member {PIXI.MASK_TYPES} - */ - this.type = exports.MASK_TYPES.NONE; - /** - * Whether we know the mask type beforehand - * @member {boolean} - * @default true - */ - this.autoDetect = true; - /** - * Which element we use to mask - * @member {PIXI.DisplayObject} - */ - this.maskObject = maskObject || null; - /** - * Whether it belongs to MaskSystem pool - * @member {boolean} - */ - this.pooled = false; - /** - * Indicator of the type - * @member {boolean} - */ - this.isMaskData = true; - /** - * Stencil counter above the mask in stack - * @member {number} - * @private - */ - this._stencilCounter = 0; - /** - * Scissor counter above the mask in stack - * @member {number} - * @private - */ - this._scissorCounter = 0; - /** - * Scissor operation above the mask in stack. - * Null if _scissorCounter is zero, rectangle instance if positive. - * @member {PIXI.Rectangle} - */ - this._scissorRect = null; - /** - * Targeted element. Temporary variable set by MaskSystem - * @member {PIXI.DisplayObject} - * @private - */ - this._target = null; - } - /** - * resets the mask data after popMask() - */ - MaskData.prototype.reset = function () { - if (this.pooled) { - this.maskObject = null; - this.type = exports.MASK_TYPES.NONE; - this.autoDetect = true; - } - this._target = null; - }; - /** - * copies counters from maskData above, called from pushMask() - * @param {PIXI.MaskData|null} maskAbove - */ - MaskData.prototype.copyCountersOrReset = function (maskAbove) { - if (maskAbove) { - this._stencilCounter = maskAbove._stencilCounter; - this._scissorCounter = maskAbove._scissorCounter; - this._scissorRect = maskAbove._scissorRect; - } - else { - this._stencilCounter = 0; - this._scissorCounter = 0; - this._scissorRect = null; - } - }; - return MaskData; - }()); - - /** - * @private - * @param gl {WebGLRenderingContext} The current WebGL context {WebGLProgram} - * @param type {Number} the type, can be either VERTEX_SHADER or FRAGMENT_SHADER - * @param src {string} The vertex shader source as an array of strings. - * @return {WebGLShader} the shader - */ - function compileShader(gl, type, src) { - var shader = gl.createShader(type); - gl.shaderSource(shader, src); - gl.compileShader(shader); - return shader; - } - /** - * @method compileProgram - * @private - * @memberof PIXI.glCore.shader - * @param gl {WebGLRenderingContext} The current WebGL context {WebGLProgram} - * @param vertexSrc {string|string[]} The vertex shader source as an array of strings. - * @param fragmentSrc {string|string[]} The fragment shader source as an array of strings. - * @param attributeLocations {Object} An attribute location map that lets you manually set the attribute locations - * @return {WebGLProgram} the shader program - */ - function compileProgram(gl, vertexSrc, fragmentSrc, attributeLocations) { - var glVertShader = compileShader(gl, gl.VERTEX_SHADER, vertexSrc); - var glFragShader = compileShader(gl, gl.FRAGMENT_SHADER, fragmentSrc); - var program = gl.createProgram(); - gl.attachShader(program, glVertShader); - gl.attachShader(program, glFragShader); - // optionally, set the attributes manually for the program rather than letting WebGL decide.. - if (attributeLocations) { - for (var i in attributeLocations) { - gl.bindAttribLocation(program, attributeLocations[i], i); - } - } - gl.linkProgram(program); - // if linking fails, then log and cleanup - if (!gl.getProgramParameter(program, gl.LINK_STATUS)) { - if (!gl.getShaderParameter(glVertShader, gl.COMPILE_STATUS)) { - console.warn(vertexSrc); - console.error(gl.getShaderInfoLog(glVertShader)); - } - if (!gl.getShaderParameter(glFragShader, gl.COMPILE_STATUS)) { - console.warn(fragmentSrc); - console.error(gl.getShaderInfoLog(glFragShader)); - } - console.error('Pixi.js Error: Could not initialize shader.'); - console.error('gl.VALIDATE_STATUS', gl.getProgramParameter(program, gl.VALIDATE_STATUS)); - console.error('gl.getError()', gl.getError()); - // if there is a program info log, log it - if (gl.getProgramInfoLog(program) !== '') { - console.warn('Pixi.js Warning: gl.getProgramInfoLog()', gl.getProgramInfoLog(program)); - } - gl.deleteProgram(program); - program = null; - } - // clean up some shaders - gl.deleteShader(glVertShader); - gl.deleteShader(glFragShader); - return program; - } - - function booleanArray(size) { - var array = new Array(size); - for (var i = 0; i < array.length; i++) { - array[i] = false; - } - return array; - } - /** - * @method defaultValue - * @memberof PIXI.glCore.shader - * @param type {String} Type of value - * @param size {Number} - * @private - */ - function defaultValue(type, size) { - switch (type) { - case 'float': - return 0; - case 'vec2': - return new Float32Array(2 * size); - case 'vec3': - return new Float32Array(3 * size); - case 'vec4': - return new Float32Array(4 * size); - case 'int': - case 'sampler2D': - case 'sampler2DArray': - return 0; - case 'ivec2': - return new Int32Array(2 * size); - case 'ivec3': - return new Int32Array(3 * size); - case 'ivec4': - return new Int32Array(4 * size); - case 'bool': - return false; - case 'bvec2': - return booleanArray(2 * size); - case 'bvec3': - return booleanArray(3 * size); - case 'bvec4': - return booleanArray(4 * size); - case 'mat2': - return new Float32Array([1, 0, - 0, 1]); - case 'mat3': - return new Float32Array([1, 0, 0, - 0, 1, 0, - 0, 0, 1]); - case 'mat4': - return new Float32Array([1, 0, 0, 0, - 0, 1, 0, 0, - 0, 0, 1, 0, - 0, 0, 0, 1]); - } - return null; - } - - var unknownContext = {}; - var context = unknownContext; - /** - * returns a little WebGL context to use for program inspection. - * - * @static - * @private - * @returns {WebGLRenderingContext} a gl context to test with - */ - function getTestContext() { - if (context === unknownContext || (context && context.isContextLost())) { - var canvas = document.createElement('canvas'); - var gl = void 0; - if (settings.PREFER_ENV >= exports.ENV.WEBGL2) { - gl = canvas.getContext('webgl2', {}); - } - if (!gl) { - gl = canvas.getContext('webgl', {}) - || canvas.getContext('experimental-webgl', {}); - if (!gl) { - // fail, not able to get a context - gl = null; - } - else { - // for shader testing.. - gl.getExtension('WEBGL_draw_buffers'); - } - } - context = gl; - } - return context; - } - - var maxFragmentPrecision; - function getMaxFragmentPrecision() { - if (!maxFragmentPrecision) { - maxFragmentPrecision = exports.PRECISION.MEDIUM; - var gl = getTestContext(); - if (gl) { - if (gl.getShaderPrecisionFormat) { - var shaderFragment = gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.HIGH_FLOAT); - maxFragmentPrecision = shaderFragment.precision ? exports.PRECISION.HIGH : exports.PRECISION.MEDIUM; - } - } - } - return maxFragmentPrecision; - } - - /** - * Sets the float precision on the shader, ensuring the device supports the request precision. - * If the precision is already present, it just ensures that the device is able to handle it. - * - * @private - * @param {string} src - The shader source - * @param {string} requestedPrecision - The request float precision of the shader. Options are 'lowp', 'mediump' or 'highp'. - * @param {string} maxSupportedPrecision - The maximum precision the shader supports. - * - * @return {string} modified shader source - */ - function setPrecision(src, requestedPrecision, maxSupportedPrecision) { - if (src.substring(0, 9) !== 'precision') { - // no precision supplied, so PixiJS will add the requested level. - var precision = requestedPrecision; - // If highp is requested but not supported, downgrade precision to a level all devices support. - if (requestedPrecision === exports.PRECISION.HIGH && maxSupportedPrecision !== exports.PRECISION.HIGH) { - precision = exports.PRECISION.MEDIUM; - } - return "precision " + precision + " float;\n" + src; - } - else if (maxSupportedPrecision !== exports.PRECISION.HIGH && src.substring(0, 15) === 'precision highp') { - // precision was supplied, but at a level this device does not support, so downgrading to mediump. - return src.replace('precision highp', 'precision mediump'); - } - return src; - } - - var GLSL_TO_SIZE = { - float: 1, - vec2: 2, - vec3: 3, - vec4: 4, - int: 1, - ivec2: 2, - ivec3: 3, - ivec4: 4, - bool: 1, - bvec2: 2, - bvec3: 3, - bvec4: 4, - mat2: 4, - mat3: 9, - mat4: 16, - sampler2D: 1, - }; - /** - * @private - * @method mapSize - * @memberof PIXI.glCore.shader - * @param type {String} - * @return {Number} - */ - function mapSize(type) { - return GLSL_TO_SIZE[type]; - } - - var GL_TABLE = null; - var GL_TO_GLSL_TYPES = { - FLOAT: 'float', - FLOAT_VEC2: 'vec2', - FLOAT_VEC3: 'vec3', - FLOAT_VEC4: 'vec4', - INT: 'int', - INT_VEC2: 'ivec2', - INT_VEC3: 'ivec3', - INT_VEC4: 'ivec4', - BOOL: 'bool', - BOOL_VEC2: 'bvec2', - BOOL_VEC3: 'bvec3', - BOOL_VEC4: 'bvec4', - FLOAT_MAT2: 'mat2', - FLOAT_MAT3: 'mat3', - FLOAT_MAT4: 'mat4', - SAMPLER_2D: 'sampler2D', - INT_SAMPLER_2D: 'sampler2D', - UNSIGNED_INT_SAMPLER_2D: 'sampler2D', - SAMPLER_CUBE: 'samplerCube', - INT_SAMPLER_CUBE: 'samplerCube', - UNSIGNED_INT_SAMPLER_CUBE: 'samplerCube', - SAMPLER_2D_ARRAY: 'sampler2DArray', - INT_SAMPLER_2D_ARRAY: 'sampler2DArray', - UNSIGNED_INT_SAMPLER_2D_ARRAY: 'sampler2DArray', - }; - // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types - function mapType(gl, type) { - if (!GL_TABLE) { - var typeNames = Object.keys(GL_TO_GLSL_TYPES); - GL_TABLE = {}; - for (var i = 0; i < typeNames.length; ++i) { - var tn = typeNames[i]; - GL_TABLE[gl[tn]] = GL_TO_GLSL_TYPES[tn]; - } - } - return GL_TABLE[type]; - } - - /* eslint-disable @typescript-eslint/explicit-module-boundary-types */ - // Parsers, each one of these will take a look at the type of shader property and uniform. - // if they pass the test function then the code function is called that returns a the shader upload code for that uniform. - // Shader upload code is automagically generated with these parsers. - // If no parser is valid then the default upload functions are used. - // exposing Parsers means that custom upload logic can be added to pixi's shaders. - // A good example would be a pixi rectangle can be directly set on a uniform. - // If the shader sees it it knows how to upload the rectangle structure as a vec4 - // format is as follows: - // - // { - // test: (data, uniform) => {} <--- test is this code should be used for this uniform - // code: (name, uniform) => {} <--- returns the string of the piece of code that uploads the uniform - // } - var uniformParsers = [ - // a float cache layer - { - test: function (data) { - return data.type === 'float' && data.size === 1; - }, - code: function (name) { - return "\n if(uv[\"" + name + "\"] !== ud[\"" + name + "\"].value)\n {\n ud[\"" + name + "\"].value = uv[\"" + name + "\"]\n gl.uniform1f(ud[\"" + name + "\"].location, uv[\"" + name + "\"])\n }\n "; - }, - }, - // handling samplers - { - test: function (data) { - // eslint-disable-next-line max-len - return (data.type === 'sampler2D' || data.type === 'samplerCube' || data.type === 'sampler2DArray') && data.size === 1 && !data.isArray; - }, - code: function (name) { return "t = syncData.textureCount++;\n\n renderer.texture.bind(uv[\"" + name + "\"], t);\n\n if(ud[\"" + name + "\"].value !== t)\n {\n ud[\"" + name + "\"].value = t;\n gl.uniform1i(ud[\"" + name + "\"].location, t);\n; // eslint-disable-line max-len\n }"; }, - }, - // uploading pixi matrix object to mat3 - { - test: function (data, uniform) { - return data.type === 'mat3' && data.size === 1 && uniform.a !== undefined; - }, - code: function (name) { - // TODO and some smart caching dirty ids here! - return "\n gl.uniformMatrix3fv(ud[\"" + name + "\"].location, false, uv[\"" + name + "\"].toArray(true));\n "; - }, - }, - // uploading a pixi point as a vec2 with caching layer - { - test: function (data, uniform) { - return data.type === 'vec2' && data.size === 1 && uniform.x !== undefined; - }, - code: function (name) { - return "\n cv = ud[\"" + name + "\"].value;\n v = uv[\"" + name + "\"];\n\n if(cv[0] !== v.x || cv[1] !== v.y)\n {\n cv[0] = v.x;\n cv[1] = v.y;\n gl.uniform2f(ud[\"" + name + "\"].location, v.x, v.y);\n }"; - }, - }, - // caching layer for a vec2 - { - test: function (data) { - return data.type === 'vec2' && data.size === 1; - }, - code: function (name) { - return "\n cv = ud[\"" + name + "\"].value;\n v = uv[\"" + name + "\"];\n\n if(cv[0] !== v[0] || cv[1] !== v[1])\n {\n cv[0] = v[0];\n cv[1] = v[1];\n gl.uniform2f(ud[\"" + name + "\"].location, v[0], v[1]);\n }\n "; - }, - }, - // upload a pixi rectangle as a vec4 with caching layer - { - test: function (data, uniform) { - return data.type === 'vec4' && data.size === 1 && uniform.width !== undefined; - }, - code: function (name) { - return "\n cv = ud[\"" + name + "\"].value;\n v = uv[\"" + name + "\"];\n\n if(cv[0] !== v.x || cv[1] !== v.y || cv[2] !== v.width || cv[3] !== v.height)\n {\n cv[0] = v.x;\n cv[1] = v.y;\n cv[2] = v.width;\n cv[3] = v.height;\n gl.uniform4f(ud[\"" + name + "\"].location, v.x, v.y, v.width, v.height)\n }"; - }, - }, - // a caching layer for vec4 uploading - { - test: function (data) { - return data.type === 'vec4' && data.size === 1; - }, - code: function (name) { - return "\n cv = ud[\"" + name + "\"].value;\n v = uv[\"" + name + "\"];\n\n if(cv[0] !== v[0] || cv[1] !== v[1] || cv[2] !== v[2] || cv[3] !== v[3])\n {\n cv[0] = v[0];\n cv[1] = v[1];\n cv[2] = v[2];\n cv[3] = v[3];\n\n gl.uniform4f(ud[\"" + name + "\"].location, v[0], v[1], v[2], v[3])\n }"; - }, - } ]; - - // cv = CachedValue - // v = value - // ud = uniformData - // uv = uniformValue - // l = location - var GLSL_TO_SINGLE_SETTERS_CACHED = { - float: "\n if(cv !== v)\n {\n cv.v = v;\n gl.uniform1f(location, v)\n }", - vec2: "\n if(cv[0] !== v[0] || cv[1] !== v[1])\n {\n cv[0] = v[0];\n cv[1] = v[1];\n gl.uniform2f(location, v[0], v[1])\n }", - vec3: "\n if(cv[0] !== v[0] || cv[1] !== v[1] || cv[2] !== v[2])\n {\n cv[0] = v[0];\n cv[1] = v[1];\n cv[2] = v[2];\n\n gl.uniform3f(location, v[0], v[1], v[2])\n }", - vec4: 'gl.uniform4f(location, v[0], v[1], v[2], v[3])', - int: 'gl.uniform1i(location, v)', - ivec2: 'gl.uniform2i(location, v[0], v[1])', - ivec3: 'gl.uniform3i(location, v[0], v[1], v[2])', - ivec4: 'gl.uniform4i(location, v[0], v[1], v[2], v[3])', - bool: 'gl.uniform1i(location, v)', - bvec2: 'gl.uniform2i(location, v[0], v[1])', - bvec3: 'gl.uniform3i(location, v[0], v[1], v[2])', - bvec4: 'gl.uniform4i(location, v[0], v[1], v[2], v[3])', - mat2: 'gl.uniformMatrix2fv(location, false, v)', - mat3: 'gl.uniformMatrix3fv(location, false, v)', - mat4: 'gl.uniformMatrix4fv(location, false, v)', - sampler2D: 'gl.uniform1i(location, v)', - samplerCube: 'gl.uniform1i(location, v)', - sampler2DArray: 'gl.uniform1i(location, v)', - }; - var GLSL_TO_ARRAY_SETTERS = { - float: "gl.uniform1fv(location, v)", - vec2: "gl.uniform2fv(location, v)", - vec3: "gl.uniform3fv(location, v)", - vec4: 'gl.uniform4fv(location, v)', - mat4: 'gl.uniformMatrix4fv(location, false, v)', - mat3: 'gl.uniformMatrix3fv(location, false, v)', - mat2: 'gl.uniformMatrix2fv(location, false, v)', - int: 'gl.uniform1iv(location, v)', - ivec2: 'gl.uniform2iv(location, v)', - ivec3: 'gl.uniform3iv(location, v)', - ivec4: 'gl.uniform4iv(location, v)', - bool: 'gl.uniform1iv(location, v)', - bvec2: 'gl.uniform2iv(location, v)', - bvec3: 'gl.uniform3iv(location, v)', - bvec4: 'gl.uniform4iv(location, v)', - sampler2D: 'gl.uniform1iv(location, v)', - samplerCube: 'gl.uniform1iv(location, v)', - sampler2DArray: 'gl.uniform1iv(location, v)', - }; - function generateUniformsSync(group, uniformData) { - var funcFragments = ["\n var v = null;\n var cv = null\n var t = 0;\n var gl = renderer.gl\n "]; - for (var i in group.uniforms) { - var data = uniformData[i]; - if (!data) { - if (group.uniforms[i].group) { - funcFragments.push("\n renderer.shader.syncUniformGroup(uv[\"" + i + "\"], syncData);\n "); - } - continue; - } - var uniform = group.uniforms[i]; - var parsed = false; - for (var j = 0; j < uniformParsers.length; j++) { - if (uniformParsers[j].test(data, uniform)) { - funcFragments.push(uniformParsers[j].code(i, uniform)); - parsed = true; - break; - } - } - if (!parsed) { - var templateType = (data.size === 1) ? GLSL_TO_SINGLE_SETTERS_CACHED : GLSL_TO_ARRAY_SETTERS; - var template = templateType[data.type].replace('location', "ud[\"" + i + "\"].location"); - funcFragments.push("\n cv = ud[\"" + i + "\"].value;\n v = uv[\"" + i + "\"];\n " + template + ";"); - } - } - /** - * the introduction of syncData is to solve an issue where textures in uniform groups are not set correctly - * the texture count was always starting from 0 in each group. This needs to increment each time a texture is used - * no matter which group is being used - * - */ - // eslint-disable-next-line no-new-func - return new Function('ud', 'uv', 'renderer', 'syncData', funcFragments.join('\n')); - } - - var fragTemplate = [ - 'precision mediump float;', - 'void main(void){', - 'float test = 0.1;', - '%forloop%', - 'gl_FragColor = vec4(0.0);', - '}' ].join('\n'); - function generateIfTestSrc(maxIfs) { - var src = ''; - for (var i = 0; i < maxIfs; ++i) { - if (i > 0) { - src += '\nelse '; - } - if (i < maxIfs - 1) { - src += "if(test == " + i + ".0){}"; - } - } - return src; - } - function checkMaxIfStatementsInShader(maxIfs, gl) { - if (maxIfs === 0) { - throw new Error('Invalid value of `0` passed to `checkMaxIfStatementsInShader`'); - } - var shader = gl.createShader(gl.FRAGMENT_SHADER); - while (true) // eslint-disable-line no-constant-condition - { - var fragmentSrc = fragTemplate.replace(/%forloop%/gi, generateIfTestSrc(maxIfs)); - gl.shaderSource(shader, fragmentSrc); - gl.compileShader(shader); - if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) { - maxIfs = (maxIfs / 2) | 0; - } - else { - // valid! - break; - } - } - return maxIfs; - } - - // Cache the result to prevent running this over and over - var unsafeEval; - /** - * Not all platforms allow to generate function code (e.g., `new Function`). - * this provides the platform-level detection. - * - * @private - * @returns {boolean} - */ - function unsafeEvalSupported() { - if (typeof unsafeEval === 'boolean') { - return unsafeEval; - } - try { - /* eslint-disable no-new-func */ - var func = new Function('param1', 'param2', 'param3', 'return param1[param2] === param3;'); - /* eslint-enable no-new-func */ - unsafeEval = func({ a: 'b' }, 'a', 'b') === true; - } - catch (e) { - unsafeEval = false; - } - return unsafeEval; - } - - var defaultFragment = "varying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\n\nvoid main(void){\n gl_FragColor *= texture2D(uSampler, vTextureCoord);\n}"; - - var defaultVertex = "attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void){\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n vTextureCoord = aTextureCoord;\n}\n"; - - var UID$3 = 0; - var nameCache = {}; - /** - * Helper class to create a shader program. - * - * @class - * @memberof PIXI - */ - var Program = /** @class */ (function () { - /** - * @param {string} [vertexSrc] - The source of the vertex shader. - * @param {string} [fragmentSrc] - The source of the fragment shader. - * @param {string} [name] - Name for shader - */ - function Program(vertexSrc, fragmentSrc, name) { - if (name === void 0) { name = 'pixi-shader'; } - this.id = UID$3++; - /** - * The vertex shader. - * - * @member {string} - */ - this.vertexSrc = vertexSrc || Program.defaultVertexSrc; - /** - * The fragment shader. - * - * @member {string} - */ - this.fragmentSrc = fragmentSrc || Program.defaultFragmentSrc; - this.vertexSrc = this.vertexSrc.trim(); - this.fragmentSrc = this.fragmentSrc.trim(); - if (this.vertexSrc.substring(0, 8) !== '#version') { - name = name.replace(/\s+/g, '-'); - if (nameCache[name]) { - nameCache[name]++; - name += "-" + nameCache[name]; - } - else { - nameCache[name] = 1; - } - this.vertexSrc = "#define SHADER_NAME " + name + "\n" + this.vertexSrc; - this.fragmentSrc = "#define SHADER_NAME " + name + "\n" + this.fragmentSrc; - this.vertexSrc = setPrecision(this.vertexSrc, settings.PRECISION_VERTEX, exports.PRECISION.HIGH); - this.fragmentSrc = setPrecision(this.fragmentSrc, settings.PRECISION_FRAGMENT, getMaxFragmentPrecision()); - } - // currently this does not extract structs only default types - this.extractData(this.vertexSrc, this.fragmentSrc); - // this is where we store shader references.. - this.glPrograms = {}; - this.syncUniforms = null; - } - /** - * Extracts the data for a buy creating a small test program - * or reading the src directly. - * @protected - * - * @param {string} [vertexSrc] - The source of the vertex shader. - * @param {string} [fragmentSrc] - The source of the fragment shader. - */ - Program.prototype.extractData = function (vertexSrc, fragmentSrc) { - var gl = getTestContext(); - if (gl) { - var program = compileProgram(gl, vertexSrc, fragmentSrc); - this.attributeData = this.getAttributeData(program, gl); - this.uniformData = this.getUniformData(program, gl); - gl.deleteProgram(program); - } - else { - this.uniformData = {}; - this.attributeData = {}; - } - }; - /** - * returns the attribute data from the program - * @private - * - * @param {WebGLProgram} [program] - the WebGL program - * @param {WebGLRenderingContext} [gl] - the WebGL context - * - * @returns {object} the attribute data for this program - */ - Program.prototype.getAttributeData = function (program, gl) { - var attributes = {}; - var attributesArray = []; - var totalAttributes = gl.getProgramParameter(program, gl.ACTIVE_ATTRIBUTES); - for (var i = 0; i < totalAttributes; i++) { - var attribData = gl.getActiveAttrib(program, i); - var type = mapType(gl, attribData.type); - /*eslint-disable */ - var data = { - type: type, - name: attribData.name, - size: mapSize(type), - location: 0, - }; - /* eslint-enable */ - attributes[attribData.name] = data; - attributesArray.push(data); - } - attributesArray.sort(function (a, b) { return (a.name > b.name) ? 1 : -1; }); // eslint-disable-line no-confusing-arrow - for (var i = 0; i < attributesArray.length; i++) { - attributesArray[i].location = i; - } - return attributes; - }; - /** - * returns the uniform data from the program - * @private - * - * @param {webGL-program} [program] - the webgl program - * @param {context} [gl] - the WebGL context - * - * @returns {object} the uniform data for this program - */ - Program.prototype.getUniformData = function (program, gl) { - var uniforms = {}; - var totalUniforms = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS); - // TODO expose this as a prop? - // const maskRegex = new RegExp('^(projectionMatrix|uSampler|translationMatrix)$'); - // const maskRegex = new RegExp('^(projectionMatrix|uSampler|translationMatrix)$'); - for (var i = 0; i < totalUniforms; i++) { - var uniformData = gl.getActiveUniform(program, i); - var name = uniformData.name.replace(/\[.*?\]$/, ''); - var isArray = uniformData.name.match(/\[.*?\]$/); - var type = mapType(gl, uniformData.type); - /*eslint-disable */ - uniforms[name] = { - type: type, - size: uniformData.size, - isArray: isArray, - value: defaultValue(type, uniformData.size), - }; - /* eslint-enable */ - } - return uniforms; - }; - Object.defineProperty(Program, "defaultVertexSrc", { - /** - * The default vertex shader source - * - * @static - * @constant - * @member {string} - */ - get: function () { - return defaultVertex; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(Program, "defaultFragmentSrc", { - /** - * The default fragment shader source - * - * @static - * @constant - * @member {string} - */ - get: function () { - return defaultFragment; - }, - enumerable: false, - configurable: true - }); - /** - * A short hand function to create a program based of a vertex and fragment shader - * this method will also check to see if there is a cached program. - * - * @param {string} [vertexSrc] - The source of the vertex shader. - * @param {string} [fragmentSrc] - The source of the fragment shader. - * @param {string} [name=pixi-shader] - Name for shader - * - * @returns {PIXI.Program} an shiny new Pixi shader! - */ - Program.from = function (vertexSrc, fragmentSrc, name) { - var key = vertexSrc + fragmentSrc; - var program = ProgramCache[key]; - if (!program) { - ProgramCache[key] = program = new Program(vertexSrc, fragmentSrc, name); - } - return program; - }; - return Program; - }()); - - /** - * A helper class for shaders - * - * @class - * @memberof PIXI - */ - var Shader = /** @class */ (function () { - /** - * @param {PIXI.Program} [program] - The program the shader will use. - * @param {object} [uniforms] - Custom uniforms to use to augment the built-in ones. - */ - function Shader(program, uniforms) { - /** - * Program that the shader uses - * - * @member {PIXI.Program} - */ - this.program = program; - // lets see whats been passed in - // uniforms should be converted to a uniform group - if (uniforms) { - if (uniforms instanceof UniformGroup) { - this.uniformGroup = uniforms; - } - else { - this.uniformGroup = new UniformGroup(uniforms); - } - } - else { - this.uniformGroup = new UniformGroup({}); - } - // time to build some getters and setters! - // I guess down the line this could sort of generate an instruction list rather than use dirty ids? - // does the trick for now though! - for (var i in program.uniformData) { - if (this.uniformGroup.uniforms[i] instanceof Array) { - this.uniformGroup.uniforms[i] = new Float32Array(this.uniformGroup.uniforms[i]); - } - } - } - // TODO move to shader system.. - Shader.prototype.checkUniformExists = function (name, group) { - if (group.uniforms[name]) { - return true; - } - for (var i in group.uniforms) { - var uniform = group.uniforms[i]; - if (uniform.group) { - if (this.checkUniformExists(name, uniform)) { - return true; - } - } - } - return false; - }; - Shader.prototype.destroy = function () { - // usage count on programs? - // remove if not used! - this.uniformGroup = null; - }; - Object.defineProperty(Shader.prototype, "uniforms", { - /** - * Shader uniform values, shortcut for `uniformGroup.uniforms` - * @readonly - * @member {object} - */ - get: function () { - return this.uniformGroup.uniforms; - }, - enumerable: false, - configurable: true - }); - /** - * A short hand function to create a shader based of a vertex and fragment shader - * - * @param {string} [vertexSrc] - The source of the vertex shader. - * @param {string} [fragmentSrc] - The source of the fragment shader. - * @param {object} [uniforms] - Custom uniforms to use to augment the built-in ones. - * - * @returns {PIXI.Shader} an shiny new Pixi shader! - */ - Shader.from = function (vertexSrc, fragmentSrc, uniforms) { - var program = Program.from(vertexSrc, fragmentSrc); - return new Shader(program, uniforms); - }; - return Shader; - }()); - - /* eslint-disable max-len */ - var BLEND = 0; - var OFFSET = 1; - var CULLING = 2; - var DEPTH_TEST = 3; - var WINDING = 4; - /** - * This is a WebGL state, and is is passed The WebGL StateManager. - * - * Each mesh rendered may require WebGL to be in a different state. - * For example you may want different blend mode or to enable polygon offsets - * - * @class - * @memberof PIXI - */ - var State = /** @class */ (function () { - function State() { - this.data = 0; - this.blendMode = exports.BLEND_MODES.NORMAL; - this.polygonOffset = 0; - this.blend = true; - // this.depthTest = true; - } - Object.defineProperty(State.prototype, "blend", { - /** - * Activates blending of the computed fragment color values - * - * @member {boolean} - */ - get: function () { - return !!(this.data & (1 << BLEND)); - }, - set: function (value) { - if (!!(this.data & (1 << BLEND)) !== value) { - this.data ^= (1 << BLEND); - } - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(State.prototype, "offsets", { - /** - * Activates adding an offset to depth values of polygon's fragments - * - * @member {boolean} - * @default false - */ - get: function () { - return !!(this.data & (1 << OFFSET)); - }, - set: function (value) { - if (!!(this.data & (1 << OFFSET)) !== value) { - this.data ^= (1 << OFFSET); - } - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(State.prototype, "culling", { - /** - * Activates culling of polygons. - * - * @member {boolean} - * @default false - */ - get: function () { - return !!(this.data & (1 << CULLING)); - }, - set: function (value) { - if (!!(this.data & (1 << CULLING)) !== value) { - this.data ^= (1 << CULLING); - } - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(State.prototype, "depthTest", { - /** - * Activates depth comparisons and updates to the depth buffer. - * - * @member {boolean} - * @default false - */ - get: function () { - return !!(this.data & (1 << DEPTH_TEST)); - }, - set: function (value) { - if (!!(this.data & (1 << DEPTH_TEST)) !== value) { - this.data ^= (1 << DEPTH_TEST); - } - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(State.prototype, "clockwiseFrontFace", { - /** - * Specifies whether or not front or back-facing polygons can be culled. - * @member {boolean} - * @default false - */ - get: function () { - return !!(this.data & (1 << WINDING)); - }, - set: function (value) { - if (!!(this.data & (1 << WINDING)) !== value) { - this.data ^= (1 << WINDING); - } - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(State.prototype, "blendMode", { - /** - * The blend mode to be applied when this state is set. Apply a value of `PIXI.BLEND_MODES.NORMAL` to reset the blend mode. - * Setting this mode to anything other than NO_BLEND will automatically switch blending on. - * - * @member {number} - * @default PIXI.BLEND_MODES.NORMAL - * @see PIXI.BLEND_MODES - */ - get: function () { - return this._blendMode; - }, - set: function (value) { - this.blend = (value !== exports.BLEND_MODES.NONE); - this._blendMode = value; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(State.prototype, "polygonOffset", { - /** - * The polygon offset. Setting this property to anything other than 0 will automatically enable polygon offset fill. - * - * @member {number} - * @default 0 - */ - get: function () { - return this._polygonOffset; - }, - set: function (value) { - this.offsets = !!value; - this._polygonOffset = value; - }, - enumerable: false, - configurable: true - }); - State.for2d = function () { - var state = new State(); - state.depthTest = false; - state.blend = true; - return state; - }; - return State; - }()); - - var defaultVertex$1 = "attribute vec2 aVertexPosition;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 vTextureCoord;\n\nuniform vec4 inputSize;\nuniform vec4 outputFrame;\n\nvec4 filterVertexPosition( void )\n{\n vec2 position = aVertexPosition * max(outputFrame.zw, vec2(0.)) + outputFrame.xy;\n\n return vec4((projectionMatrix * vec3(position, 1.0)).xy, 0.0, 1.0);\n}\n\nvec2 filterTextureCoord( void )\n{\n return aVertexPosition * (outputFrame.zw * inputSize.zw);\n}\n\nvoid main(void)\n{\n gl_Position = filterVertexPosition();\n vTextureCoord = filterTextureCoord();\n}\n"; - - var defaultFragment$1 = "varying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\n\nvoid main(void){\n gl_FragColor = texture2D(uSampler, vTextureCoord);\n}\n"; - - /** - * Filter is a special type of WebGL shader that is applied to the screen. - * - * {@link http://pixijs.io/examples/#/filters/blur-filter.js Example} of the - * {@link PIXI.filters.BlurFilter BlurFilter}. - * - * ### Usage - * Filters can be applied to any DisplayObject or Container. - * PixiJS' `FilterSystem` renders the container into temporary Framebuffer, - * then filter renders it to the screen. - * Multiple filters can be added to the `filters` array property and stacked on each other. - * - * ``` - * const filter = new PIXI.Filter(myShaderVert, myShaderFrag, { myUniform: 0.5 }); - * const container = new PIXI.Container(); - * container.filters = [filter]; - * ``` - * - * ### Previous Version Differences - * - * In PixiJS **v3**, a filter was always applied to _whole screen_. - * - * In PixiJS **v4**, a filter can be applied _only part of the screen_. - * Developers had to create a set of uniforms to deal with coordinates. - * - * In PixiJS **v5** combines _both approaches_. - * Developers can use normal coordinates of v3 and then allow filter to use partial Framebuffers, - * bringing those extra uniforms into account. - * - * Also be aware that we have changed default vertex shader, please consult - * {@link https://github.com/pixijs/pixi.js/wiki/v5-Creating-filters Wiki}. - * - * ### Built-in Uniforms - * - * PixiJS viewport uses screen (CSS) coordinates, `(0, 0, renderer.screen.width, renderer.screen.height)`, - * and `projectionMatrix` uniform maps it to the gl viewport. - * - * **uSampler** - * - * The most important uniform is the input texture that container was rendered into. - * _Important note: as with all Framebuffers in PixiJS, both input and output are - * premultiplied by alpha._ - * - * By default, input normalized coordinates are passed to fragment shader with `vTextureCoord`. - * Use it to sample the input. - * - * ``` - * const fragment = ` - * varying vec2 vTextureCoord; - * uniform sampler2D uSampler; - * void main(void) - * { - * gl_FragColor = texture2D(uSampler, vTextureCoord); - * } - * `; - * - * const myFilter = new PIXI.Filter(null, fragment); - * ``` - * - * This filter is just one uniform less than {@link PIXI.filters.AlphaFilter AlphaFilter}. - * - * **outputFrame** - * - * The `outputFrame` holds the rectangle where filter is applied in screen (CSS) coordinates. - * It's the same as `renderer.screen` for a fullscreen filter. - * Only a part of `outputFrame.zw` size of temporary Framebuffer is used, - * `(0, 0, outputFrame.width, outputFrame.height)`, - * - * Filters uses this quad to normalized (0-1) space, its passed into `aVertexPosition` attribute. - * To calculate vertex position in screen space using normalized (0-1) space: - * - * ``` - * vec4 filterVertexPosition( void ) - * { - * vec2 position = aVertexPosition * max(outputFrame.zw, vec2(0.)) + outputFrame.xy; - * return vec4((projectionMatrix * vec3(position, 1.0)).xy, 0.0, 1.0); - * } - * ``` - * - * **inputSize** - * - * Temporary framebuffer is different, it can be either the size of screen, either power-of-two. - * The `inputSize.xy` are size of temporary framebuffer that holds input. - * The `inputSize.zw` is inverted, it's a shortcut to evade division inside the shader. - * - * Set `inputSize.xy = outputFrame.zw` for a fullscreen filter. - * - * To calculate input normalized coordinate, you have to map it to filter normalized space. - * Multiply by `outputFrame.zw` to get input coordinate. - * Divide by `inputSize.xy` to get input normalized coordinate. - * - * ``` - * vec2 filterTextureCoord( void ) - * { - * return aVertexPosition * (outputFrame.zw * inputSize.zw); // same as /inputSize.xy - * } - * ``` - * **resolution** - * - * The `resolution` is the ratio of screen (CSS) pixels to real pixels. - * - * **inputPixel** - * - * `inputPixel.xy` is the size of framebuffer in real pixels, same as `inputSize.xy * resolution` - * `inputPixel.zw` is inverted `inputPixel.xy`. - * - * It's handy for filters that use neighbour pixels, like {@link PIXI.filters.FXAAFilter FXAAFilter}. - * - * **inputClamp** - * - * If you try to get info from outside of used part of Framebuffer - you'll get undefined behaviour. - * For displacements, coordinates has to be clamped. - * - * The `inputClamp.xy` is left-top pixel center, you may ignore it, because we use left-top part of Framebuffer - * `inputClamp.zw` is bottom-right pixel center. - * - * ``` - * vec4 color = texture2D(uSampler, clamp(modifigedTextureCoord, inputClamp.xy, inputClamp.zw)) - * ``` - * OR - * ``` - * vec4 color = texture2D(uSampler, min(modifigedTextureCoord, inputClamp.zw)) - * ``` - * - * ### Additional Information - * - * Complete documentation on Filter usage is located in the - * {@link https://github.com/pixijs/pixi.js/wiki/v5-Creating-filters Wiki}. - * - * Since PixiJS only had a handful of built-in filters, additional filters can be downloaded - * {@link https://github.com/pixijs/pixi-filters here} from the PixiJS Filters repository. - * - * @class - * @memberof PIXI - * @extends PIXI.Shader - */ - var Filter = /** @class */ (function (_super) { - __extends$2(Filter, _super); - /** - * @param {string} [vertexSrc] - The source of the vertex shader. - * @param {string} [fragmentSrc] - The source of the fragment shader. - * @param {object} [uniforms] - Custom uniforms to use to augment the built-in ones. - */ - function Filter(vertexSrc, fragmentSrc, uniforms) { - var _this = this; - var program = Program.from(vertexSrc || Filter.defaultVertexSrc, fragmentSrc || Filter.defaultFragmentSrc); - _this = _super.call(this, program, uniforms) || this; - /** - * The padding of the filter. Some filters require extra space to breath such as a blur. - * Increasing this will add extra width and height to the bounds of the object that the - * filter is applied to. - * - * @member {number} - */ - _this.padding = 0; - /** - * The resolution of the filter. Setting this to be lower will lower the quality but - * increase the performance of the filter. - * - * @member {number} - */ - _this.resolution = settings.FILTER_RESOLUTION; - /** - * If enabled is true the filter is applied, if false it will not. - * - * @member {boolean} - */ - _this.enabled = true; - /** - * If enabled, PixiJS will fit the filter area into boundaries for better performance. - * Switch it off if it does not work for specific shader. - * - * @member {boolean} - */ - _this.autoFit = true; - /** - * Legacy filters use position and uvs from attributes - * @member {boolean} - * @readonly - */ - _this.legacy = !!_this.program.attributeData.aTextureCoord; - /** - * The WebGL state the filter requires to render - * @member {PIXI.State} - */ - _this.state = new State(); - return _this; - } - /** - * Applies the filter - * - * @param {PIXI.systems.FilterSystem} filterManager - The renderer to retrieve the filter from - * @param {PIXI.RenderTexture} input - The input render target. - * @param {PIXI.RenderTexture} output - The target to output to. - * @param {PIXI.CLEAR_MODES} clearMode - Should the output be cleared before rendering to it. - * @param {object} [currentState] - It's current state of filter. - * There are some useful properties in the currentState : - * target, filters, sourceFrame, destinationFrame, renderTarget, resolution - */ - Filter.prototype.apply = function (filterManager, input, output, clearMode, _currentState) { - // do as you please! - filterManager.applyFilter(this, input, output, clearMode); - // or just do a regular render.. - }; - Object.defineProperty(Filter.prototype, "blendMode", { - /** - * Sets the blendmode of the filter - * - * @member {number} - * @default PIXI.BLEND_MODES.NORMAL - */ - get: function () { - return this.state.blendMode; - }, - set: function (value) { - this.state.blendMode = value; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(Filter, "defaultVertexSrc", { - /** - * The default vertex shader source - * - * @static - * @type {string} - * @constant - */ - get: function () { - return defaultVertex$1; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(Filter, "defaultFragmentSrc", { - /** - * The default fragment shader source - * - * @static - * @type {string} - * @constant - */ - get: function () { - return defaultFragment$1; - }, - enumerable: false, - configurable: true - }); - return Filter; - }(Shader)); - - var vertex = "attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\nuniform mat3 otherMatrix;\n\nvarying vec2 vMaskCoord;\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n vTextureCoord = aTextureCoord;\n vMaskCoord = ( otherMatrix * vec3( aTextureCoord, 1.0) ).xy;\n}\n"; - - var fragment = "varying vec2 vMaskCoord;\nvarying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\nuniform sampler2D mask;\nuniform float alpha;\nuniform float npmAlpha;\nuniform vec4 maskClamp;\n\nvoid main(void)\n{\n float clip = step(3.5,\n step(maskClamp.x, vMaskCoord.x) +\n step(maskClamp.y, vMaskCoord.y) +\n step(vMaskCoord.x, maskClamp.z) +\n step(vMaskCoord.y, maskClamp.w));\n\n vec4 original = texture2D(uSampler, vTextureCoord);\n vec4 masky = texture2D(mask, vMaskCoord);\n float alphaMul = 1.0 - npmAlpha * (1.0 - masky.a);\n\n original *= (alphaMul * masky.r * alpha * clip);\n\n gl_FragColor = original;\n}\n"; - - var tempMat = new Matrix(); - /** - * Class controls uv mapping from Texture normal space to BaseTexture normal space. - * - * Takes `trim` and `rotate` into account. May contain clamp settings for Meshes and TilingSprite. - * - * Can be used in Texture `uvMatrix` field, or separately, you can use different clamp settings on the same texture. - * If you want to add support for texture region of certain feature or filter, that's what you're looking for. - * - * Takes track of Texture changes through `_lastTextureID` private field. - * Use `update()` method call to track it from outside. - * - * @see PIXI.Texture - * @see PIXI.Mesh - * @see PIXI.TilingSprite - * @class - * @memberof PIXI - */ - var TextureMatrix = /** @class */ (function () { - /** - * - * @param {PIXI.Texture} texture - observed texture - * @param {number} [clampMargin] - Changes frame clamping, 0.5 by default. Use -0.5 for extra border. - * @constructor - */ - function TextureMatrix(texture, clampMargin) { - this._texture = texture; - /** - * Matrix operation that converts texture region coords to texture coords - * @member {PIXI.Matrix} - * @readonly - */ - this.mapCoord = new Matrix(); - /** - * Clamp region for normalized coords, left-top pixel center in xy , bottom-right in zw. - * Calculated based on clampOffset. - * @member {Float32Array} - * @readonly - */ - this.uClampFrame = new Float32Array(4); - /** - * Normalized clamp offset. - * Calculated based on clampOffset. - * @member {Float32Array} - * @readonly - */ - this.uClampOffset = new Float32Array(2); - /** - * Tracks Texture frame changes - * @member {number} - * @protected - */ - this._textureID = -1; - /** - * Tracks Texture frame changes - * @member {number} - * @protected - */ - this._updateID = 0; - /** - * Changes frame clamping - * Works with TilingSprite and Mesh - * Change to 1.5 if you texture has repeated right and bottom lines, that leads to smoother borders - * - * @default 0 - * @member {number} - */ - this.clampOffset = 0; - /** - * Changes frame clamping - * Works with TilingSprite and Mesh - * Change to -0.5 to add a pixel to the edge, recommended for transparent trimmed textures in atlas - * - * @default 0.5 - * @member {number} - */ - this.clampMargin = (typeof clampMargin === 'undefined') ? 0.5 : clampMargin; - /** - * If texture size is the same as baseTexture - * @member {boolean} - * @default false - * @readonly - */ - this.isSimple = false; - } - Object.defineProperty(TextureMatrix.prototype, "texture", { - /** - * texture property - * @member {PIXI.Texture} - */ - get: function () { - return this._texture; - }, - set: function (value) { - this._texture = value; - this._textureID = -1; - }, - enumerable: false, - configurable: true - }); - /** - * Multiplies uvs array to transform - * @param {Float32Array} uvs - mesh uvs - * @param {Float32Array} [out=uvs] output - * @returns {Float32Array} output - */ - TextureMatrix.prototype.multiplyUvs = function (uvs, out) { - if (out === undefined) { - out = uvs; - } - var mat = this.mapCoord; - for (var i = 0; i < uvs.length; i += 2) { - var x = uvs[i]; - var y = uvs[i + 1]; - out[i] = (x * mat.a) + (y * mat.c) + mat.tx; - out[i + 1] = (x * mat.b) + (y * mat.d) + mat.ty; - } - return out; - }; - /** - * updates matrices if texture was changed - * @param {boolean} [forceUpdate=false] - if true, matrices will be updated any case - * @returns {boolean} whether or not it was updated - */ - TextureMatrix.prototype.update = function (forceUpdate) { - var tex = this._texture; - if (!tex || !tex.valid) { - return false; - } - if (!forceUpdate - && this._textureID === tex._updateID) { - return false; - } - this._textureID = tex._updateID; - this._updateID++; - var uvs = tex._uvs; - this.mapCoord.set(uvs.x1 - uvs.x0, uvs.y1 - uvs.y0, uvs.x3 - uvs.x0, uvs.y3 - uvs.y0, uvs.x0, uvs.y0); - var orig = tex.orig; - var trim = tex.trim; - if (trim) { - tempMat.set(orig.width / trim.width, 0, 0, orig.height / trim.height, -trim.x / trim.width, -trim.y / trim.height); - this.mapCoord.append(tempMat); - } - var texBase = tex.baseTexture; - var frame = this.uClampFrame; - var margin = this.clampMargin / texBase.resolution; - var offset = this.clampOffset; - frame[0] = (tex._frame.x + margin + offset) / texBase.width; - frame[1] = (tex._frame.y + margin + offset) / texBase.height; - frame[2] = (tex._frame.x + tex._frame.width - margin + offset) / texBase.width; - frame[3] = (tex._frame.y + tex._frame.height - margin + offset) / texBase.height; - this.uClampOffset[0] = offset / texBase.realWidth; - this.uClampOffset[1] = offset / texBase.realHeight; - this.isSimple = tex._frame.width === texBase.width - && tex._frame.height === texBase.height - && tex.rotate === 0; - return true; - }; - return TextureMatrix; - }()); - - /** - * This handles a Sprite acting as a mask, as opposed to a Graphic. - * - * WebGL only. - * - * @class - * @extends PIXI.Filter - * @memberof PIXI - */ - var SpriteMaskFilter = /** @class */ (function (_super) { - __extends$2(SpriteMaskFilter, _super); - /** - * @param {PIXI.Sprite} sprite - the target sprite - */ - function SpriteMaskFilter(sprite) { - var _this = this; - var maskMatrix = new Matrix(); - _this = _super.call(this, vertex, fragment) || this; - sprite.renderable = false; - /** - * Sprite mask - * @member {PIXI.Sprite} - */ - _this.maskSprite = sprite; - /** - * Mask matrix - * @member {PIXI.Matrix} - */ - _this.maskMatrix = maskMatrix; - return _this; - } - /** - * Applies the filter - * - * @param {PIXI.systems.FilterSystem} filterManager - The renderer to retrieve the filter from - * @param {PIXI.RenderTexture} input - The input render target. - * @param {PIXI.RenderTexture} output - The target to output to. - * @param {PIXI.CLEAR_MODES} clearMode - Should the output be cleared before rendering to it. - */ - SpriteMaskFilter.prototype.apply = function (filterManager, input, output, clearMode) { - var maskSprite = this.maskSprite; - var tex = maskSprite._texture; - if (!tex.valid) { - return; - } - if (!tex.uvMatrix) { - // margin = 0.0, let it bleed a bit, shader code becomes easier - // assuming that atlas textures were made with 1-pixel padding - tex.uvMatrix = new TextureMatrix(tex, 0.0); - } - tex.uvMatrix.update(); - this.uniforms.npmAlpha = tex.baseTexture.alphaMode ? 0.0 : 1.0; - this.uniforms.mask = tex; - // get _normalized sprite texture coords_ and convert them to _normalized atlas texture coords_ with `prepend` - this.uniforms.otherMatrix = filterManager.calculateSpriteMatrix(this.maskMatrix, maskSprite) - .prepend(tex.uvMatrix.mapCoord); - this.uniforms.alpha = maskSprite.worldAlpha; - this.uniforms.maskClamp = tex.uvMatrix.uClampFrame; - filterManager.applyFilter(this, input, output, clearMode); - }; - return SpriteMaskFilter; - }(Filter)); - - /** - * System plugin to the renderer to manage masks. - * - * @class - * @extends PIXI.System - * @memberof PIXI.systems - */ - var MaskSystem = /** @class */ (function (_super) { - __extends$2(MaskSystem, _super); - /** - * @param {PIXI.Renderer} renderer - The renderer this System works for. - */ - function MaskSystem(renderer) { - var _this = _super.call(this, renderer) || this; - /** - * Enable scissor - * @member {boolean} - * @readonly - */ - _this.enableScissor = false; - /** - * Pool of used sprite mask filters - * @member {PIXI.SpriteMaskFilter[]} - * @readonly - */ - _this.alphaMaskPool = []; - /** - * Pool of mask data - * @member {PIXI.MaskData[]} - * @readonly - */ - _this.maskDataPool = []; - _this.maskStack = []; - /** - * Current index of alpha mask pool - * @member {number} - * @default 0 - * @readonly - */ - _this.alphaMaskIndex = 0; - return _this; - } - /** - * Changes the mask stack that is used by this System. - * - * @param {PIXI.MaskData[]} maskStack - The mask stack - */ - MaskSystem.prototype.setMaskStack = function (maskStack) { - this.maskStack = maskStack; - this.renderer.scissor.setMaskStack(maskStack); - this.renderer.stencil.setMaskStack(maskStack); - }; - /** - * Applies the Mask and adds it to the current filter stack. - * Renderer batch must be flushed beforehand. - * - * @param {PIXI.DisplayObject} target - Display Object to push the mask to - * @param {PIXI.MaskData|PIXI.Sprite|PIXI.Graphics|PIXI.DisplayObject} maskData - The masking data. - */ - MaskSystem.prototype.push = function (target, maskDataOrTarget) { - var maskData = maskDataOrTarget; - if (!maskData.isMaskData) { - var d = this.maskDataPool.pop() || new MaskData(); - d.pooled = true; - d.maskObject = maskDataOrTarget; - maskData = d; - } - if (maskData.autoDetect) { - this.detect(maskData); - } - maskData.copyCountersOrReset(this.maskStack[this.maskStack.length - 1]); - maskData._target = target; - switch (maskData.type) { - case exports.MASK_TYPES.SCISSOR: - this.maskStack.push(maskData); - this.renderer.scissor.push(maskData); - break; - case exports.MASK_TYPES.STENCIL: - this.maskStack.push(maskData); - this.renderer.stencil.push(maskData); - break; - case exports.MASK_TYPES.SPRITE: - maskData.copyCountersOrReset(null); - this.pushSpriteMask(maskData); - this.maskStack.push(maskData); - break; - default: - break; - } - }; - /** - * Removes the last mask from the mask stack and doesn't return it. - * Renderer batch must be flushed beforehand. - * - * @param {PIXI.DisplayObject} target - Display Object to pop the mask from - */ - MaskSystem.prototype.pop = function (target) { - var maskData = this.maskStack.pop(); - if (!maskData || maskData._target !== target) { - // TODO: add an assert when we have it - return; - } - switch (maskData.type) { - case exports.MASK_TYPES.SCISSOR: - this.renderer.scissor.pop(); - break; - case exports.MASK_TYPES.STENCIL: - this.renderer.stencil.pop(maskData.maskObject); - break; - case exports.MASK_TYPES.SPRITE: - this.popSpriteMask(); - break; - default: - break; - } - maskData.reset(); - if (maskData.pooled) { - this.maskDataPool.push(maskData); - } - }; - /** - * Sets type of MaskData based on its maskObject - * @param {PIXI.MaskData} maskData - */ - MaskSystem.prototype.detect = function (maskData) { - var maskObject = maskData.maskObject; - if (maskObject.isSprite) { - maskData.type = exports.MASK_TYPES.SPRITE; - return; - } - maskData.type = exports.MASK_TYPES.STENCIL; - // detect scissor in graphics - if (this.enableScissor - && maskObject.isFastRect - && maskObject.isFastRect()) { - var matrix = maskObject.worldTransform; - // TODO: move the check to the matrix itself - // we are checking that its orthogonal and x rotation is 0 90 180 or 270 - var rotX = Math.atan2(matrix.b, matrix.a); - var rotXY = Math.atan2(matrix.d, matrix.c); - // use the nearest degree to 0.01 - rotX = Math.round(rotX * (180 / Math.PI) * 100); - rotXY = Math.round(rotXY * (180 / Math.PI) * 100) - rotX; - rotX = ((rotX % 9000) + 9000) % 9000; - rotXY = ((rotXY % 18000) + 18000) % 18000; - if (rotX === 0 && rotXY === 9000) { - maskData.type = exports.MASK_TYPES.SCISSOR; - } - } - }; - /** - * Applies the Mask and adds it to the current filter stack. - * - * @param {PIXI.MaskData} maskData - Sprite to be used as the mask - */ - MaskSystem.prototype.pushSpriteMask = function (maskData) { - var maskObject = maskData.maskObject; - var target = maskData._target; - var alphaMaskFilter = this.alphaMaskPool[this.alphaMaskIndex]; - if (!alphaMaskFilter) { - alphaMaskFilter = this.alphaMaskPool[this.alphaMaskIndex] = [new SpriteMaskFilter(maskObject)]; - } - alphaMaskFilter[0].resolution = this.renderer.resolution; - alphaMaskFilter[0].maskSprite = maskObject; - var stashFilterArea = target.filterArea; - target.filterArea = maskObject.getBounds(true); - this.renderer.filter.push(target, alphaMaskFilter); - target.filterArea = stashFilterArea; - this.alphaMaskIndex++; - }; - /** - * Removes the last filter from the filter stack and doesn't return it. - */ - MaskSystem.prototype.popSpriteMask = function () { - this.renderer.filter.pop(); - this.alphaMaskIndex--; - }; - return MaskSystem; - }(System)); - - /** - * System plugin to the renderer to manage masks of certain type - * - * @class - * @extends PIXI.System - * @memberof PIXI.systems - */ - var AbstractMaskSystem = /** @class */ (function (_super) { - __extends$2(AbstractMaskSystem, _super); - /** - * @param {PIXI.Renderer} renderer - The renderer this System works for. - */ - function AbstractMaskSystem(renderer) { - var _this = _super.call(this, renderer) || this; - /** - * The mask stack - * @member {PIXI.MaskData[]} - */ - _this.maskStack = []; - /** - * Constant for gl.enable - * @member {number} - * @private - */ - _this.glConst = 0; - return _this; - } - /** - * gets count of masks of certain type - * @returns {number} - */ - AbstractMaskSystem.prototype.getStackLength = function () { - return this.maskStack.length; - }; - /** - * Changes the mask stack that is used by this System. - * - * @param {PIXI.MaskData[]} maskStack - The mask stack - */ - AbstractMaskSystem.prototype.setMaskStack = function (maskStack) { - var gl = this.renderer.gl; - var curStackLen = this.getStackLength(); - this.maskStack = maskStack; - var newStackLen = this.getStackLength(); - if (newStackLen !== curStackLen) { - if (newStackLen === 0) { - gl.disable(this.glConst); - } - else { - gl.enable(this.glConst); - this._useCurrent(); - } - } - }; - /** - * Setup renderer to use the current mask data. - * @private - */ - AbstractMaskSystem.prototype._useCurrent = function () { - // OVERWRITE; - }; - /** - * Destroys the mask stack. - * - */ - AbstractMaskSystem.prototype.destroy = function () { - _super.prototype.destroy.call(this); - this.maskStack = null; - }; - return AbstractMaskSystem; - }(System)); - - /** - * System plugin to the renderer to manage scissor rects (used for masks). - * - * @class - * @extends PIXI.System - * @memberof PIXI.systems - */ - var ScissorSystem = /** @class */ (function (_super) { - __extends$2(ScissorSystem, _super); - /** - * @param {PIXI.Renderer} renderer - The renderer this System works for. - */ - function ScissorSystem(renderer) { - var _this = _super.call(this, renderer) || this; - _this.glConst = WebGLRenderingContext.SCISSOR_TEST; - return _this; - } - ScissorSystem.prototype.getStackLength = function () { - var maskData = this.maskStack[this.maskStack.length - 1]; - if (maskData) { - return maskData._scissorCounter; - } - return 0; - }; - /** - * Applies the Mask and adds it to the current stencil stack. @alvin - * - * @param {PIXI.MaskData} maskData - The mask data - */ - ScissorSystem.prototype.push = function (maskData) { - var maskObject = maskData.maskObject; - maskObject.renderable = true; - var prevData = maskData._scissorRect; - var bounds = maskObject.getBounds(true); - var gl = this.renderer.gl; - maskObject.renderable = false; - if (prevData) { - bounds.fit(prevData); - } - else { - gl.enable(gl.SCISSOR_TEST); - } - maskData._scissorCounter++; - maskData._scissorRect = bounds; - this._useCurrent(); - }; - /** - * Pops scissor mask. MaskData is already removed from stack - */ - ScissorSystem.prototype.pop = function () { - var gl = this.renderer.gl; - if (this.getStackLength() > 0) { - this._useCurrent(); - } - else { - gl.disable(gl.SCISSOR_TEST); - } - }; - /** - * Setup renderer to use the current scissor data. - * @private - */ - ScissorSystem.prototype._useCurrent = function () { - var rect = this.maskStack[this.maskStack.length - 1]._scissorRect; - var rt = this.renderer.renderTexture.current; - var _a = this.renderer.projection, transform = _a.transform, sourceFrame = _a.sourceFrame, destinationFrame = _a.destinationFrame; - var resolution = rt ? rt.resolution : this.renderer.resolution; - var x = ((rect.x - sourceFrame.x) * resolution) + destinationFrame.x; - var y = ((rect.y - sourceFrame.y) * resolution) + destinationFrame.y; - var width = rect.width * resolution; - var height = rect.height * resolution; - if (transform) { - x += transform.tx * resolution; - y += transform.ty * resolution; - } - if (!rt) { - // flipY. In future we'll have it over renderTextures as an option - y = this.renderer.height - height - y; - } - this.renderer.gl.scissor(x, y, width, height); - }; - return ScissorSystem; - }(AbstractMaskSystem)); - - /** - * System plugin to the renderer to manage stencils (used for masks). - * - * @class - * @extends PIXI.System - * @memberof PIXI.systems - */ - var StencilSystem = /** @class */ (function (_super) { - __extends$2(StencilSystem, _super); - /** - * @param {PIXI.Renderer} renderer - The renderer this System works for. - */ - function StencilSystem(renderer) { - var _this = _super.call(this, renderer) || this; - _this.glConst = WebGLRenderingContext.STENCIL_TEST; - return _this; - } - StencilSystem.prototype.getStackLength = function () { - var maskData = this.maskStack[this.maskStack.length - 1]; - if (maskData) { - return maskData._stencilCounter; - } - return 0; - }; - /** - * Applies the Mask and adds it to the current stencil stack. - * - * @param {PIXI.MaskData} maskData - The mask data - */ - StencilSystem.prototype.push = function (maskData) { - var maskObject = maskData.maskObject; - var gl = this.renderer.gl; - var prevMaskCount = maskData._stencilCounter; - if (prevMaskCount === 0) { - // force use stencil texture in current framebuffer - this.renderer.framebuffer.forceStencil(); - gl.enable(gl.STENCIL_TEST); - } - maskData._stencilCounter++; - // Increment the reference stencil value where the new mask overlaps with the old ones. - gl.colorMask(false, false, false, false); - gl.stencilFunc(gl.EQUAL, prevMaskCount, this._getBitwiseMask()); - gl.stencilOp(gl.KEEP, gl.KEEP, gl.INCR); - maskObject.renderable = true; - maskObject.render(this.renderer); - this.renderer.batch.flush(); - maskObject.renderable = false; - this._useCurrent(); - }; - /** - * Pops stencil mask. MaskData is already removed from stack - * - * @param {PIXI.DisplayObject} maskObject - object of popped mask data - */ - StencilSystem.prototype.pop = function (maskObject) { - var gl = this.renderer.gl; - if (this.getStackLength() === 0) { - // the stack is empty! - gl.disable(gl.STENCIL_TEST); - gl.clear(gl.STENCIL_BUFFER_BIT); - gl.clearStencil(0); - } - else { - // Decrement the reference stencil value where the popped mask overlaps with the other ones - gl.colorMask(false, false, false, false); - gl.stencilOp(gl.KEEP, gl.KEEP, gl.DECR); - maskObject.renderable = true; - maskObject.render(this.renderer); - this.renderer.batch.flush(); - maskObject.renderable = false; - this._useCurrent(); - } - }; - /** - * Setup renderer to use the current stencil data. - * @private - */ - StencilSystem.prototype._useCurrent = function () { - var gl = this.renderer.gl; - gl.colorMask(true, true, true, true); - gl.stencilFunc(gl.EQUAL, this.getStackLength(), this._getBitwiseMask()); - gl.stencilOp(gl.KEEP, gl.KEEP, gl.KEEP); - }; - /** - * Fill 1s equal to the number of acitve stencil masks. - * @private - * @return {number} The bitwise mask. - */ - StencilSystem.prototype._getBitwiseMask = function () { - return (1 << this.getStackLength()) - 1; - }; - return StencilSystem; - }(AbstractMaskSystem)); - - /** - * System plugin to the renderer to manage the projection matrix. - * - * @class - * @extends PIXI.System - * @memberof PIXI.systems - */ - var ProjectionSystem = /** @class */ (function (_super) { - __extends$2(ProjectionSystem, _super); - /** - * @param {PIXI.Renderer} renderer - The renderer this System works for. - */ - function ProjectionSystem(renderer) { - var _this = _super.call(this, renderer) || this; - /** - * Destination frame - * @member {PIXI.Rectangle} - * @readonly - */ - _this.destinationFrame = null; - /** - * Source frame - * @member {PIXI.Rectangle} - * @readonly - */ - _this.sourceFrame = null; - /** - * Default destination frame - * @member {PIXI.Rectangle} - * @readonly - */ - _this.defaultFrame = null; - /** - * Project matrix - * @member {PIXI.Matrix} - * @readonly - */ - _this.projectionMatrix = new Matrix(); - /** - * A transform that will be appended to the projection matrix - * if null, nothing will be applied - * @member {PIXI.Matrix} - */ - _this.transform = null; - return _this; - } - /** - * Updates the projection matrix based on a projection frame (which is a rectangle). - * - * Make sure to run `renderer.framebuffer.setViewport(destinationFrame)` after calling this. - * - * @param {PIXI.Rectangle} destinationFrame - The destination frame. - * @param {PIXI.Rectangle} sourceFrame - The source frame. - * @param {Number} resolution - Resolution - * @param {boolean} root - If is root - */ - ProjectionSystem.prototype.update = function (destinationFrame, sourceFrame, resolution, root) { - this.destinationFrame = destinationFrame || this.destinationFrame || this.defaultFrame; - this.sourceFrame = sourceFrame || this.sourceFrame || destinationFrame; - // Calculate object-space to clip-space projection - this.calculateProjection(this.destinationFrame, this.sourceFrame, resolution, root); - if (this.transform) { - this.projectionMatrix.append(this.transform); - } - var renderer = this.renderer; - renderer.globalUniforms.uniforms.projectionMatrix = this.projectionMatrix; - renderer.globalUniforms.update(); - // this will work for now - // but would be sweet to stick and even on the global uniforms.. - if (renderer.shader.shader) { - renderer.shader.syncUniformGroup(renderer.shader.shader.uniforms.globals); - } - }; - /** - * Updates the projection matrix based on a projection frame (which is a rectangle) - * - * @param {PIXI.Rectangle} destinationFrame - The destination frame. - * @param {PIXI.Rectangle} sourceFrame - The source frame. - * @param {Number} resolution - Resolution - * @param {boolean} root - If is root - */ - ProjectionSystem.prototype.calculateProjection = function (_destinationFrame, sourceFrame, _resolution, root) { - var pm = this.projectionMatrix; - var sign = !root ? 1 : -1; - pm.identity(); - pm.a = (1 / sourceFrame.width * 2); - pm.d = sign * (1 / sourceFrame.height * 2); - pm.tx = -1 - (sourceFrame.x * pm.a); - pm.ty = -sign - (sourceFrame.y * pm.d); - }; - /** - * Sets the transform of the active render target to the given matrix - * - * @param {PIXI.Matrix} matrix - The transformation matrix - */ - ProjectionSystem.prototype.setTransform = function (_matrix) { - // this._activeRenderTarget.transform = matrix; - }; - return ProjectionSystem; - }(System)); - - // Temporary rectangle for assigned sourceFrame or destinationFrame - var tempRect = new Rectangle(); - // Temporary rectangle for renderTexture destinationFrame - var tempRect2 = new Rectangle(); - // Temporary rectangle for passing the framebuffer viewport - var viewportFrame = new Rectangle(); - /** - * System plugin to the renderer to manage render textures. - * - * Should be added after FramebufferSystem - * - * @class - * @extends PIXI.System - * @memberof PIXI.systems - */ - var RenderTextureSystem = /** @class */ (function (_super) { - __extends$2(RenderTextureSystem, _super); - /** - * @param {PIXI.Renderer} renderer - The renderer this System works for. - */ - function RenderTextureSystem(renderer) { - var _this = _super.call(this, renderer) || this; - /** - * The clear background color as rgba - * @member {number[]} - */ - _this.clearColor = renderer._backgroundColorRgba; - // TODO move this property somewhere else! - /** - * List of masks for the StencilSystem - * @member {PIXI.Graphics[]} - * @readonly - */ - _this.defaultMaskStack = []; - // empty render texture? - /** - * Render texture - * @member {PIXI.RenderTexture} - * @readonly - */ - _this.current = null; - /** - * Source frame - * @member {PIXI.Rectangle} - * @readonly - */ - _this.sourceFrame = new Rectangle(); - /** - * Destination frame - * @member {PIXI.Rectangle} - * @readonly - */ - _this.destinationFrame = new Rectangle(); - return _this; - } - /** - * Bind the current render texture - * - * @param {PIXI.RenderTexture} [renderTexture] - RenderTexture to bind, by default its `null`, the screen - * @param {PIXI.Rectangle} [sourceFrame] - part of screen that is mapped to the renderTexture - * @param {PIXI.Rectangle} [destinationFrame] - part of renderTexture, by default it has the same size as sourceFrame - */ - RenderTextureSystem.prototype.bind = function (renderTexture, sourceFrame, destinationFrame) { - if (renderTexture === void 0) { renderTexture = null; } - var renderer = this.renderer; - this.current = renderTexture; - var baseTexture; - var framebuffer; - var resolution; - if (renderTexture) { - baseTexture = renderTexture.baseTexture; - resolution = baseTexture.resolution; - if (!sourceFrame) { - tempRect.width = renderTexture.frame.width; - tempRect.height = renderTexture.frame.height; - sourceFrame = tempRect; - } - if (!destinationFrame) { - tempRect2.x = renderTexture.frame.x; - tempRect2.y = renderTexture.frame.y; - tempRect2.width = sourceFrame.width; - tempRect2.height = sourceFrame.height; - destinationFrame = tempRect2; - } - framebuffer = baseTexture.framebuffer; - } - else { - resolution = renderer.resolution; - if (!sourceFrame) { - tempRect.width = renderer.screen.width; - tempRect.height = renderer.screen.height; - sourceFrame = tempRect; - } - if (!destinationFrame) { - destinationFrame = tempRect; - destinationFrame.width = sourceFrame.width; - destinationFrame.height = sourceFrame.height; - } - } - viewportFrame.x = destinationFrame.x * resolution; - viewportFrame.y = destinationFrame.y * resolution; - viewportFrame.width = destinationFrame.width * resolution; - viewportFrame.height = destinationFrame.height * resolution; - this.renderer.framebuffer.bind(framebuffer, viewportFrame); - this.renderer.projection.update(destinationFrame, sourceFrame, resolution, !framebuffer); - if (renderTexture) { - this.renderer.mask.setMaskStack(baseTexture.maskStack); - } - else { - this.renderer.mask.setMaskStack(this.defaultMaskStack); - } - this.sourceFrame.copyFrom(sourceFrame); - this.destinationFrame.copyFrom(destinationFrame); - }; - /** - * Erases the render texture and fills the drawing area with a colour - * - * @param {number[]} [clearColor] - The color as rgba, default to use the renderer backgroundColor - * @param {PIXI.BUFFER_BITS} [mask=BUFFER_BITS.COLOR | BUFFER_BITS.DEPTH] - Bitwise OR of masks - * that indicate the buffers to be cleared, by default COLOR and DEPTH buffers. - * @return {PIXI.Renderer} Returns itself. - */ - RenderTextureSystem.prototype.clear = function (clearColor, mask) { - if (this.current) { - clearColor = clearColor || this.current.baseTexture.clearColor; - } - else { - clearColor = clearColor || this.clearColor; - } - this.renderer.framebuffer.clear(clearColor[0], clearColor[1], clearColor[2], clearColor[3], mask); - }; - RenderTextureSystem.prototype.resize = function () { - // resize the root only! - this.bind(null); - }; - /** - * Resets renderTexture state - */ - RenderTextureSystem.prototype.reset = function () { - this.bind(null); - }; - return RenderTextureSystem; - }(System)); - - var IGLUniformData = /** @class */ (function () { - function IGLUniformData() { - } - return IGLUniformData; - }()); - /** - * Helper class to create a WebGL Program - * - * @class - * @memberof PIXI - */ - var GLProgram = /** @class */ (function () { - /** - * Makes a new Pixi program - * - * @param program {WebGLProgram} webgl program - * @param uniformData {Object} uniforms - */ - function GLProgram(program, uniformData) { - /** - * The shader program - * - * @member {WebGLProgram} - */ - this.program = program; - /** - * holds the uniform data which contains uniform locations - * and current uniform values used for caching and preventing unneeded GPU commands - * @member {Object} - */ - this.uniformData = uniformData; - /** - * uniformGroups holds the various upload functions for the shader. Each uniform group - * and program have a unique upload function generated. - * @member {Object} - */ - this.uniformGroups = {}; - } - /** - * Destroys this program - */ - GLProgram.prototype.destroy = function () { - this.uniformData = null; - this.uniformGroups = null; - this.program = null; - }; - return GLProgram; - }()); - - var UID$4 = 0; - // defualt sync data so we don't create a new one each time! - var defaultSyncData = { textureCount: 0 }; - /** - * System plugin to the renderer to manage shaders. - * - * @class - * @memberof PIXI.systems - * @extends PIXI.System - */ - var ShaderSystem = /** @class */ (function (_super) { - __extends$2(ShaderSystem, _super); - /** - * @param {PIXI.Renderer} renderer - The renderer this System works for. - */ - function ShaderSystem(renderer) { - var _this = _super.call(this, renderer) || this; - _this.destroyed = false; - // Validation check that this environment support `new Function` - _this.systemCheck(); - /** - * The current WebGL rendering context - * - * @member {WebGLRenderingContext} - */ - _this.gl = null; - _this.shader = null; - _this.program = null; - /** - * Cache to holds the generated functions. Stored against UniformObjects unique signature - * @type {Object} - * @private - */ - _this.cache = {}; - _this.id = UID$4++; - return _this; - } - /** - * Overrideable function by `@pixi/unsafe-eval` to silence - * throwing an error if platform doesn't support unsafe-evals. - * - * @private - */ - ShaderSystem.prototype.systemCheck = function () { - if (!unsafeEvalSupported()) { - throw new Error('Current environment does not allow unsafe-eval, ' - + 'please use @pixi/unsafe-eval module to enable support.'); - } - }; - ShaderSystem.prototype.contextChange = function (gl) { - this.gl = gl; - this.reset(); - }; - /** - * Changes the current shader to the one given in parameter - * - * @param {PIXI.Shader} shader - the new shader - * @param {boolean} [dontSync] - false if the shader should automatically sync its uniforms. - * @returns {PIXI.GLProgram} the glProgram that belongs to the shader. - */ - ShaderSystem.prototype.bind = function (shader, dontSync) { - shader.uniforms.globals = this.renderer.globalUniforms; - var program = shader.program; - var glProgram = program.glPrograms[this.renderer.CONTEXT_UID] || this.generateShader(shader); - this.shader = shader; - // TODO - some current Pixi plugins bypass this.. so it not safe to use yet.. - if (this.program !== program) { - this.program = program; - this.gl.useProgram(glProgram.program); - } - if (!dontSync) { - defaultSyncData.textureCount = 0; - this.syncUniformGroup(shader.uniformGroup, defaultSyncData); - } - return glProgram; - }; - /** - * Uploads the uniforms values to the currently bound shader. - * - * @param {object} uniforms - the uniforms values that be applied to the current shader - */ - ShaderSystem.prototype.setUniforms = function (uniforms) { - var shader = this.shader.program; - var glProgram = shader.glPrograms[this.renderer.CONTEXT_UID]; - shader.syncUniforms(glProgram.uniformData, uniforms, this.renderer); - }; - /* eslint-disable @typescript-eslint/explicit-module-boundary-types */ - /** - * - * syncs uniforms on the group - * @param {*} group - the uniform group to sync - * @param {*} [syncData] - this is data that is passed to the sync function and any nested sync functions - */ - ShaderSystem.prototype.syncUniformGroup = function (group, syncData) { - var glProgram = this.getglProgram(); - if (!group.static || group.dirtyId !== glProgram.uniformGroups[group.id]) { - glProgram.uniformGroups[group.id] = group.dirtyId; - this.syncUniforms(group, glProgram, syncData); - } - }; - /** - * Overrideable by the @pixi/unsafe-eval package to use static - * syncUnforms instead. - * - * @private - */ - ShaderSystem.prototype.syncUniforms = function (group, glProgram, syncData) { - var syncFunc = group.syncUniforms[this.shader.program.id] || this.createSyncGroups(group); - syncFunc(glProgram.uniformData, group.uniforms, this.renderer, syncData); - }; - /* eslint-enable @typescript-eslint/explicit-module-boundary-types */ - ShaderSystem.prototype.createSyncGroups = function (group) { - var id = this.getSignature(group, this.shader.program.uniformData); - if (!this.cache[id]) { - this.cache[id] = generateUniformsSync(group, this.shader.program.uniformData); - } - group.syncUniforms[this.shader.program.id] = this.cache[id]; - return group.syncUniforms[this.shader.program.id]; - }; - /** - * Takes a uniform group and data and generates a unique signature for them. - * - * @param {PIXI.UniformGroup} group - the uniform group to get signature of - * @param {Object} uniformData - uniform information generated by the shader - * @returns {String} Unique signature of the uniform group - * @private - */ - ShaderSystem.prototype.getSignature = function (group, uniformData) { - var uniforms = group.uniforms; - var strings = []; - for (var i in uniforms) { - strings.push(i); - if (uniformData[i]) { - strings.push(uniformData[i].type); - } - } - return strings.join('-'); - }; - /** - * Returns the underlying GLShade rof the currently bound shader. - * This can be handy for when you to have a little more control over the setting of your uniforms. - * - * @return {PIXI.GLProgram} the glProgram for the currently bound Shader for this context - */ - ShaderSystem.prototype.getglProgram = function () { - if (this.shader) { - return this.shader.program.glPrograms[this.renderer.CONTEXT_UID]; - } - return null; - }; - /** - * Generates a glProgram version of the Shader provided. - * - * @private - * @param {PIXI.Shader} shader - the shader that the glProgram will be based on. - * @return {PIXI.GLProgram} A shiny new glProgram! - */ - ShaderSystem.prototype.generateShader = function (shader) { - var gl = this.gl; - var program = shader.program; - var attribMap = {}; - for (var i in program.attributeData) { - attribMap[i] = program.attributeData[i].location; - } - var shaderProgram = compileProgram(gl, program.vertexSrc, program.fragmentSrc, attribMap); - var uniformData = {}; - for (var i in program.uniformData) { - var data = program.uniformData[i]; - uniformData[i] = { - location: gl.getUniformLocation(shaderProgram, i), - value: defaultValue(data.type, data.size), - }; - } - var glProgram = new GLProgram(shaderProgram, uniformData); - program.glPrograms[this.renderer.CONTEXT_UID] = glProgram; - return glProgram; - }; - /** - * Resets ShaderSystem state, does not affect WebGL state - */ - ShaderSystem.prototype.reset = function () { - this.program = null; - this.shader = null; - }; - /** - * Destroys this System and removes all its textures - */ - ShaderSystem.prototype.destroy = function () { - // TODO implement destroy method for ShaderSystem - this.destroyed = true; - }; - return ShaderSystem; - }(System)); - - /** - * Maps gl blend combinations to WebGL. - * - * @memberof PIXI - * @function mapWebGLBlendModesToPixi - * @private - * @param {WebGLRenderingContext} gl - The rendering context. - * @param {number[][]} [array=[]] - The array to output into. - * @return {number[][]} Mapped modes. - */ - function mapWebGLBlendModesToPixi(gl, array) { - if (array === void 0) { array = []; } - // TODO - premultiply alpha would be different. - // add a boolean for that! - array[exports.BLEND_MODES.NORMAL] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; - array[exports.BLEND_MODES.ADD] = [gl.ONE, gl.ONE]; - array[exports.BLEND_MODES.MULTIPLY] = [gl.DST_COLOR, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; - array[exports.BLEND_MODES.SCREEN] = [gl.ONE, gl.ONE_MINUS_SRC_COLOR, gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; - array[exports.BLEND_MODES.OVERLAY] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; - array[exports.BLEND_MODES.DARKEN] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; - array[exports.BLEND_MODES.LIGHTEN] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; - array[exports.BLEND_MODES.COLOR_DODGE] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; - array[exports.BLEND_MODES.COLOR_BURN] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; - array[exports.BLEND_MODES.HARD_LIGHT] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; - array[exports.BLEND_MODES.SOFT_LIGHT] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; - array[exports.BLEND_MODES.DIFFERENCE] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; - array[exports.BLEND_MODES.EXCLUSION] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; - array[exports.BLEND_MODES.HUE] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; - array[exports.BLEND_MODES.SATURATION] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; - array[exports.BLEND_MODES.COLOR] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; - array[exports.BLEND_MODES.LUMINOSITY] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; - array[exports.BLEND_MODES.NONE] = [0, 0]; - // not-premultiplied blend modes - array[exports.BLEND_MODES.NORMAL_NPM] = [gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; - array[exports.BLEND_MODES.ADD_NPM] = [gl.SRC_ALPHA, gl.ONE, gl.ONE, gl.ONE]; - array[exports.BLEND_MODES.SCREEN_NPM] = [gl.SRC_ALPHA, gl.ONE_MINUS_SRC_COLOR, gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; - // composite operations - array[exports.BLEND_MODES.SRC_IN] = [gl.DST_ALPHA, gl.ZERO]; - array[exports.BLEND_MODES.SRC_OUT] = [gl.ONE_MINUS_DST_ALPHA, gl.ZERO]; - array[exports.BLEND_MODES.SRC_ATOP] = [gl.DST_ALPHA, gl.ONE_MINUS_SRC_ALPHA]; - array[exports.BLEND_MODES.DST_OVER] = [gl.ONE_MINUS_DST_ALPHA, gl.ONE]; - array[exports.BLEND_MODES.DST_IN] = [gl.ZERO, gl.SRC_ALPHA]; - array[exports.BLEND_MODES.DST_OUT] = [gl.ZERO, gl.ONE_MINUS_SRC_ALPHA]; - array[exports.BLEND_MODES.DST_ATOP] = [gl.ONE_MINUS_DST_ALPHA, gl.SRC_ALPHA]; - array[exports.BLEND_MODES.XOR] = [gl.ONE_MINUS_DST_ALPHA, gl.ONE_MINUS_SRC_ALPHA]; - // SUBTRACT from flash - array[exports.BLEND_MODES.SUBTRACT] = [gl.ONE, gl.ONE, gl.ONE, gl.ONE, gl.FUNC_REVERSE_SUBTRACT, gl.FUNC_ADD]; - return array; - } - - var BLEND$1 = 0; - var OFFSET$1 = 1; - var CULLING$1 = 2; - var DEPTH_TEST$1 = 3; - var WINDING$1 = 4; - /** - * System plugin to the renderer to manage WebGL state machines. - * - * @class - * @extends PIXI.System - * @memberof PIXI.systems - */ - var StateSystem = /** @class */ (function (_super) { - __extends$2(StateSystem, _super); - /** - * @param {PIXI.Renderer} renderer - The renderer this System works for. - */ - function StateSystem(renderer) { - var _this = _super.call(this, renderer) || this; - /** - * GL context - * @member {WebGLRenderingContext} - * @readonly - */ - _this.gl = null; - /** - * State ID - * @member {number} - * @readonly - */ - _this.stateId = 0; - /** - * Polygon offset - * @member {number} - * @readonly - */ - _this.polygonOffset = 0; - /** - * Blend mode - * @member {number} - * @default PIXI.BLEND_MODES.NONE - * @readonly - */ - _this.blendMode = exports.BLEND_MODES.NONE; - /** - * Whether current blend equation is different - * @member {boolean} - * @protected - */ - _this._blendEq = false; - /** - * Collection of calls - * @member {function[]} - * @readonly - */ - _this.map = []; - // map functions for when we set state.. - _this.map[BLEND$1] = _this.setBlend; - _this.map[OFFSET$1] = _this.setOffset; - _this.map[CULLING$1] = _this.setCullFace; - _this.map[DEPTH_TEST$1] = _this.setDepthTest; - _this.map[WINDING$1] = _this.setFrontFace; - /** - * Collection of check calls - * @member {function[]} - * @readonly - */ - _this.checks = []; - /** - * Default WebGL State - * @member {PIXI.State} - * @readonly - */ - _this.defaultState = new State(); - _this.defaultState.blend = true; - return _this; - } - StateSystem.prototype.contextChange = function (gl) { - this.gl = gl; - this.blendModes = mapWebGLBlendModesToPixi(gl); - this.set(this.defaultState); - this.reset(); - }; - /** - * Sets the current state - * - * @param {*} state - The state to set. - */ - StateSystem.prototype.set = function (state) { - state = state || this.defaultState; - // TODO maybe to an object check? ( this.state === state )? - if (this.stateId !== state.data) { - var diff = this.stateId ^ state.data; - var i = 0; - // order from least to most common - while (diff) { - if (diff & 1) { - // state change! - this.map[i].call(this, !!(state.data & (1 << i))); - } - diff = diff >> 1; - i++; - } - this.stateId = state.data; - } - // based on the above settings we check for specific modes.. - // for example if blend is active we check and set the blend modes - // or of polygon offset is active we check the poly depth. - for (var i = 0; i < this.checks.length; i++) { - this.checks[i](this, state); - } - }; - /** - * Sets the state, when previous state is unknown - * - * @param {*} state - The state to set - */ - StateSystem.prototype.forceState = function (state) { - state = state || this.defaultState; - for (var i = 0; i < this.map.length; i++) { - this.map[i].call(this, !!(state.data & (1 << i))); - } - for (var i = 0; i < this.checks.length; i++) { - this.checks[i](this, state); - } - this.stateId = state.data; - }; - /** - * Enables or disabled blending. - * - * @param {boolean} value - Turn on or off webgl blending. - */ - StateSystem.prototype.setBlend = function (value) { - this.updateCheck(StateSystem.checkBlendMode, value); - this.gl[value ? 'enable' : 'disable'](this.gl.BLEND); - }; - /** - * Enables or disable polygon offset fill - * - * @param {boolean} value - Turn on or off webgl polygon offset testing. - */ - StateSystem.prototype.setOffset = function (value) { - this.updateCheck(StateSystem.checkPolygonOffset, value); - this.gl[value ? 'enable' : 'disable'](this.gl.POLYGON_OFFSET_FILL); - }; - /** - * Sets whether to enable or disable depth test. - * - * @param {boolean} value - Turn on or off webgl depth testing. - */ - StateSystem.prototype.setDepthTest = function (value) { - this.gl[value ? 'enable' : 'disable'](this.gl.DEPTH_TEST); - }; - /** - * Sets whether to enable or disable cull face. - * - * @param {boolean} value - Turn on or off webgl cull face. - */ - StateSystem.prototype.setCullFace = function (value) { - this.gl[value ? 'enable' : 'disable'](this.gl.CULL_FACE); - }; - /** - * Sets the gl front face. - * - * @param {boolean} value - true is clockwise and false is counter-clockwise - */ - StateSystem.prototype.setFrontFace = function (value) { - this.gl.frontFace(this.gl[value ? 'CW' : 'CCW']); - }; - /** - * Sets the blend mode. - * - * @param {number} value - The blend mode to set to. - */ - StateSystem.prototype.setBlendMode = function (value) { - if (value === this.blendMode) { - return; - } - this.blendMode = value; - var mode = this.blendModes[value]; - var gl = this.gl; - if (mode.length === 2) { - gl.blendFunc(mode[0], mode[1]); - } - else { - gl.blendFuncSeparate(mode[0], mode[1], mode[2], mode[3]); - } - if (mode.length === 6) { - this._blendEq = true; - gl.blendEquationSeparate(mode[4], mode[5]); - } - else if (this._blendEq) { - this._blendEq = false; - gl.blendEquationSeparate(gl.FUNC_ADD, gl.FUNC_ADD); - } - }; - /** - * Sets the polygon offset. - * - * @param {number} value - the polygon offset - * @param {number} scale - the polygon offset scale - */ - StateSystem.prototype.setPolygonOffset = function (value, scale) { - this.gl.polygonOffset(value, scale); - }; - // used - /** - * Resets all the logic and disables the vaos - */ - StateSystem.prototype.reset = function () { - this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL, false); - this.forceState(this.defaultState); - this._blendEq = true; - this.blendMode = -1; - this.setBlendMode(0); - }; - /** - * checks to see which updates should be checked based on which settings have been activated. - * For example, if blend is enabled then we should check the blend modes each time the state is changed - * or if polygon fill is activated then we need to check if the polygon offset changes. - * The idea is that we only check what we have too. - * - * @param {Function} func - the checking function to add or remove - * @param {boolean} value - should the check function be added or removed. - */ - StateSystem.prototype.updateCheck = function (func, value) { - var index = this.checks.indexOf(func); - if (value && index === -1) { - this.checks.push(func); - } - else if (!value && index !== -1) { - this.checks.splice(index, 1); - } - }; - /** - * A private little wrapper function that we call to check the blend mode. - * - * @static - * @private - * @param {PIXI.StateSystem} System - the System to perform the state check on - * @param {PIXI.State} state - the state that the blendMode will pulled from - */ - StateSystem.checkBlendMode = function (system, state) { - system.setBlendMode(state.blendMode); - }; - /** - * A private little wrapper function that we call to check the polygon offset. - * - * @static - * @private - * @param {PIXI.StateSystem} System - the System to perform the state check on - * @param {PIXI.State} state - the state that the blendMode will pulled from - */ - StateSystem.checkPolygonOffset = function (system, state) { - system.setPolygonOffset(1, state.polygonOffset); - }; - return StateSystem; - }(System)); - - /** - * System plugin to the renderer to manage texture garbage collection on the GPU, - * ensuring that it does not get clogged up with textures that are no longer being used. - * - * @class - * @memberof PIXI.systems - * @extends PIXI.System - */ - var TextureGCSystem = /** @class */ (function (_super) { - __extends$2(TextureGCSystem, _super); - /** - * @param {PIXI.Renderer} renderer - The renderer this System works for. - */ - function TextureGCSystem(renderer) { - var _this = _super.call(this, renderer) || this; - /** - * Count - * @member {number} - * @readonly - */ - _this.count = 0; - /** - * Check count - * @member {number} - * @readonly - */ - _this.checkCount = 0; - /** - * Maximum idle time, in seconds - * @member {number} - * @see PIXI.settings.GC_MAX_IDLE - */ - _this.maxIdle = settings.GC_MAX_IDLE; - /** - * Maximum number of item to check - * @member {number} - * @see PIXI.settings.GC_MAX_CHECK_COUNT - */ - _this.checkCountMax = settings.GC_MAX_CHECK_COUNT; - /** - * Current garabage collection mode - * @member {PIXI.GC_MODES} - * @see PIXI.settings.GC_MODE - */ - _this.mode = settings.GC_MODE; - return _this; - } - /** - * Checks to see when the last time a texture was used - * if the texture has not been used for a specified amount of time it will be removed from the GPU - */ - TextureGCSystem.prototype.postrender = function () { - if (!this.renderer.renderingToScreen) { - return; - } - this.count++; - if (this.mode === exports.GC_MODES.MANUAL) { - return; - } - this.checkCount++; - if (this.checkCount > this.checkCountMax) { - this.checkCount = 0; - this.run(); - } - }; - /** - * Checks to see when the last time a texture was used - * if the texture has not been used for a specified amount of time it will be removed from the GPU - */ - TextureGCSystem.prototype.run = function () { - var tm = this.renderer.texture; - var managedTextures = tm.managedTextures; - var wasRemoved = false; - for (var i = 0; i < managedTextures.length; i++) { - var texture = managedTextures[i]; - // only supports non generated textures at the moment! - if (!texture.framebuffer && this.count - texture.touched > this.maxIdle) { - tm.destroyTexture(texture, true); - managedTextures[i] = null; - wasRemoved = true; - } - } - if (wasRemoved) { - var j = 0; - for (var i = 0; i < managedTextures.length; i++) { - if (managedTextures[i] !== null) { - managedTextures[j++] = managedTextures[i]; - } - } - managedTextures.length = j; - } - }; - /** - * Removes all the textures within the specified displayObject and its children from the GPU - * - * @param {PIXI.DisplayObject} displayObject - the displayObject to remove the textures from. - */ - TextureGCSystem.prototype.unload = function (displayObject) { - var _a; - var tm = this.renderer.texture; - // only destroy non generated textures - if ((_a = displayObject._texture) === null || _a === void 0 ? void 0 : _a.framebuffer) { - tm.destroyTexture(displayObject._texture); - } - for (var i = displayObject.children.length - 1; i >= 0; i--) { - this.unload(displayObject.children[i]); - } - }; - return TextureGCSystem; - }(System)); - - /** - * Internal texture for WebGL context - * @class - * @memberof PIXI - */ - var GLTexture = /** @class */ (function () { - function GLTexture(texture) { - /** - * The WebGL texture - * @member {WebGLTexture} - */ - this.texture = texture; - /** - * Width of texture that was used in texImage2D - * @member {number} - */ - this.width = -1; - /** - * Height of texture that was used in texImage2D - * @member {number} - */ - this.height = -1; - /** - * Texture contents dirty flag - * @member {number} - */ - this.dirtyId = -1; - /** - * Texture style dirty flag - * @member {number} - */ - this.dirtyStyleId = -1; - /** - * Whether mip levels has to be generated - * @member {boolean} - */ - this.mipmap = false; - /** - * WrapMode copied from baseTexture - * @member {number} - */ - this.wrapMode = 33071; - /** - * Type copied from baseTexture - * @member {number} - */ - this.type = 6408; - /** - * Type copied from baseTexture - * @member {number} - */ - this.internalFormat = 5121; - } - return GLTexture; - }()); - - /** - * System plugin to the renderer to manage textures. - * - * @class - * @extends PIXI.System - * @memberof PIXI.systems - */ - var TextureSystem = /** @class */ (function (_super) { - __extends$2(TextureSystem, _super); - /** - * @param {PIXI.Renderer} renderer - The renderer this System works for. - */ - function TextureSystem(renderer) { - var _this = _super.call(this, renderer) || this; - // TODO set to max textures... - /** - * Bound textures - * @member {PIXI.BaseTexture[]} - * @readonly - */ - _this.boundTextures = []; - /** - * Current location - * @member {number} - * @readonly - */ - _this.currentLocation = -1; - /** - * List of managed textures - * @member {PIXI.BaseTexture[]} - * @readonly - */ - _this.managedTextures = []; - /** - * Did someone temper with textures state? We'll overwrite them when we need to unbind something. - * @member {boolean} - * @private - */ - _this._unknownBoundTextures = false; - /** - * BaseTexture value that shows that we don't know what is bound - * @member {PIXI.BaseTexture} - * @readonly - */ - _this.unknownTexture = new BaseTexture(); - return _this; - } - /** - * Sets up the renderer context and necessary buffers. - */ - TextureSystem.prototype.contextChange = function () { - var gl = this.gl = this.renderer.gl; - this.CONTEXT_UID = this.renderer.CONTEXT_UID; - this.webGLVersion = this.renderer.context.webGLVersion; - var maxTextures = gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS); - this.boundTextures.length = maxTextures; - for (var i = 0; i < maxTextures; i++) { - this.boundTextures[i] = null; - } - // TODO move this.. to a nice make empty textures class.. - this.emptyTextures = {}; - var emptyTexture2D = new GLTexture(gl.createTexture()); - gl.bindTexture(gl.TEXTURE_2D, emptyTexture2D.texture); - gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, new Uint8Array(4)); - this.emptyTextures[gl.TEXTURE_2D] = emptyTexture2D; - this.emptyTextures[gl.TEXTURE_CUBE_MAP] = new GLTexture(gl.createTexture()); - gl.bindTexture(gl.TEXTURE_CUBE_MAP, this.emptyTextures[gl.TEXTURE_CUBE_MAP].texture); - for (var i = 0; i < 6; i++) { - gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, null); - } - gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR); - gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR); - for (var i = 0; i < this.boundTextures.length; i++) { - this.bind(null, i); - } - }; - /** - * Bind a texture to a specific location - * - * If you want to unbind something, please use `unbind(texture)` instead of `bind(null, textureLocation)` - * - * @param {PIXI.Texture|PIXI.BaseTexture} texture_ - Texture to bind - * @param {number} [location=0] - Location to bind at - */ - TextureSystem.prototype.bind = function (texture, location) { - if (location === void 0) { location = 0; } - var gl = this.gl; - if (texture) { - texture = texture.castToBaseTexture(); - if (texture.parentTextureArray) { - // cannot bind partial texture - // TODO: report a warning - return; - } - if (texture.valid) { - texture.touched = this.renderer.textureGC.count; - var glTexture = texture._glTextures[this.CONTEXT_UID] || this.initTexture(texture); - if (this.boundTextures[location] !== texture) { - if (this.currentLocation !== location) { - this.currentLocation = location; - gl.activeTexture(gl.TEXTURE0 + location); - } - gl.bindTexture(texture.target, glTexture.texture); - } - if (glTexture.dirtyId !== texture.dirtyId) { - if (this.currentLocation !== location) { - this.currentLocation = location; - gl.activeTexture(gl.TEXTURE0 + location); - } - this.updateTexture(texture); - } - this.boundTextures[location] = texture; - } - } - else { - if (this.currentLocation !== location) { - this.currentLocation = location; - gl.activeTexture(gl.TEXTURE0 + location); - } - gl.bindTexture(gl.TEXTURE_2D, this.emptyTextures[gl.TEXTURE_2D].texture); - this.boundTextures[location] = null; - } - }; - /** - * Resets texture location and bound textures - * - * Actual `bind(null, i)` calls will be performed at next `unbind()` call - */ - TextureSystem.prototype.reset = function () { - this._unknownBoundTextures = true; - this.currentLocation = -1; - for (var i = 0; i < this.boundTextures.length; i++) { - this.boundTextures[i] = this.unknownTexture; - } - }; - /** - * Unbind a texture - * @param {PIXI.BaseTexture} texture - Texture to bind - */ - TextureSystem.prototype.unbind = function (texture) { - var _a = this, gl = _a.gl, boundTextures = _a.boundTextures; - if (this._unknownBoundTextures) { - this._unknownBoundTextures = false; - // someone changed webGL state, - // we have to be sure that our texture does not appear in multi-texture renderer samplers - for (var i = 0; i < boundTextures.length; i++) { - if (boundTextures[i] === this.unknownTexture) { - this.bind(null, i); - } - } - } - for (var i = 0; i < boundTextures.length; i++) { - if (boundTextures[i] === texture) { - if (this.currentLocation !== i) { - gl.activeTexture(gl.TEXTURE0 + i); - this.currentLocation = i; - } - gl.bindTexture(gl.TEXTURE_2D, this.emptyTextures[texture.target].texture); - boundTextures[i] = null; - } - } - }; - /** - * Initialize a texture - * - * @private - * @param {PIXI.BaseTexture} texture - Texture to initialize - */ - TextureSystem.prototype.initTexture = function (texture) { - var glTexture = new GLTexture(this.gl.createTexture()); - // guarantee an update.. - glTexture.dirtyId = -1; - texture._glTextures[this.CONTEXT_UID] = glTexture; - this.managedTextures.push(texture); - texture.on('dispose', this.destroyTexture, this); - return glTexture; - }; - TextureSystem.prototype.initTextureType = function (texture, glTexture) { - glTexture.internalFormat = texture.format; - glTexture.type = texture.type; - if (this.webGLVersion !== 2) { - return; - } - var gl = this.renderer.gl; - if (texture.type === gl.FLOAT - && texture.format === gl.RGBA) { - glTexture.internalFormat = gl.RGBA32F; - } - // that's WebGL1 HALF_FLOAT_OES - // we have to convert it to WebGL HALF_FLOAT - if (texture.type === exports.TYPES.HALF_FLOAT) { - glTexture.type = gl.HALF_FLOAT; - } - if (glTexture.type === gl.HALF_FLOAT - && texture.format === gl.RGBA) { - glTexture.internalFormat = gl.RGBA16F; - } - }; - /** - * Update a texture - * - * @private - * @param {PIXI.BaseTexture} texture - Texture to initialize - */ - TextureSystem.prototype.updateTexture = function (texture) { - var glTexture = texture._glTextures[this.CONTEXT_UID]; - if (!glTexture) { - return; - } - var renderer = this.renderer; - this.initTextureType(texture, glTexture); - if (texture.resource && texture.resource.upload(renderer, texture, glTexture)) { ; } - else { - // default, renderTexture-like logic - var width = texture.realWidth; - var height = texture.realHeight; - var gl = renderer.gl; - if (glTexture.width !== width - || glTexture.height !== height - || glTexture.dirtyId < 0) { - glTexture.width = width; - glTexture.height = height; - gl.texImage2D(texture.target, 0, glTexture.internalFormat, width, height, 0, texture.format, glTexture.type, null); - } - } - // lets only update what changes.. - if (texture.dirtyStyleId !== glTexture.dirtyStyleId) { - this.updateTextureStyle(texture); - } - glTexture.dirtyId = texture.dirtyId; - }; - /** - * Deletes the texture from WebGL - * - * @private - * @param {PIXI.BaseTexture|PIXI.Texture} texture_ - the texture to destroy - * @param {boolean} [skipRemove=false] - Whether to skip removing the texture from the TextureManager. - */ - TextureSystem.prototype.destroyTexture = function (texture, skipRemove) { - var gl = this.gl; - texture = texture.castToBaseTexture(); - if (texture._glTextures[this.CONTEXT_UID]) { - this.unbind(texture); - gl.deleteTexture(texture._glTextures[this.CONTEXT_UID].texture); - texture.off('dispose', this.destroyTexture, this); - delete texture._glTextures[this.CONTEXT_UID]; - if (!skipRemove) { - var i = this.managedTextures.indexOf(texture); - if (i !== -1) { - removeItems(this.managedTextures, i, 1); - } - } - } - }; - /** - * Update texture style such as mipmap flag - * - * @private - * @param {PIXI.BaseTexture} texture - Texture to update - */ - TextureSystem.prototype.updateTextureStyle = function (texture) { - var glTexture = texture._glTextures[this.CONTEXT_UID]; - if (!glTexture) { - return; - } - if ((texture.mipmap === exports.MIPMAP_MODES.POW2 || this.webGLVersion !== 2) && !texture.isPowerOfTwo) { - glTexture.mipmap = false; - } - else { - glTexture.mipmap = texture.mipmap >= 1; - } - if (this.webGLVersion !== 2 && !texture.isPowerOfTwo) { - glTexture.wrapMode = exports.WRAP_MODES.CLAMP; - } - else { - glTexture.wrapMode = texture.wrapMode; - } - if (texture.resource && texture.resource.style(this.renderer, texture, glTexture)) { ; } - else { - this.setStyle(texture, glTexture); - } - glTexture.dirtyStyleId = texture.dirtyStyleId; - }; - /** - * Set style for texture - * - * @private - * @param {PIXI.BaseTexture} texture - Texture to update - * @param {PIXI.GLTexture} glTexture - */ - TextureSystem.prototype.setStyle = function (texture, glTexture) { - var gl = this.gl; - if (glTexture.mipmap) { - gl.generateMipmap(texture.target); - } - gl.texParameteri(texture.target, gl.TEXTURE_WRAP_S, glTexture.wrapMode); - gl.texParameteri(texture.target, gl.TEXTURE_WRAP_T, glTexture.wrapMode); - if (glTexture.mipmap) { - /* eslint-disable max-len */ - gl.texParameteri(texture.target, gl.TEXTURE_MIN_FILTER, texture.scaleMode === exports.SCALE_MODES.LINEAR ? gl.LINEAR_MIPMAP_LINEAR : gl.NEAREST_MIPMAP_NEAREST); - /* eslint-disable max-len */ - var anisotropicExt = this.renderer.context.extensions.anisotropicFiltering; - if (anisotropicExt && texture.anisotropicLevel > 0 && texture.scaleMode === exports.SCALE_MODES.LINEAR) { - var level = Math.min(texture.anisotropicLevel, gl.getParameter(anisotropicExt.MAX_TEXTURE_MAX_ANISOTROPY_EXT)); - gl.texParameterf(texture.target, anisotropicExt.TEXTURE_MAX_ANISOTROPY_EXT, level); - } - } - else { - gl.texParameteri(texture.target, gl.TEXTURE_MIN_FILTER, texture.scaleMode === exports.SCALE_MODES.LINEAR ? gl.LINEAR : gl.NEAREST); - } - gl.texParameteri(texture.target, gl.TEXTURE_MAG_FILTER, texture.scaleMode === exports.SCALE_MODES.LINEAR ? gl.LINEAR : gl.NEAREST); - }; - return TextureSystem; - }(System)); - - /** - * Systems are individual components to the Renderer pipeline. - * @namespace PIXI.systems - */ - - var systems = ({ - FilterSystem: FilterSystem, - BatchSystem: BatchSystem, - ContextSystem: ContextSystem, - FramebufferSystem: FramebufferSystem, - GeometrySystem: GeometrySystem, - MaskSystem: MaskSystem, - ScissorSystem: ScissorSystem, - StencilSystem: StencilSystem, - ProjectionSystem: ProjectionSystem, - RenderTextureSystem: RenderTextureSystem, - ShaderSystem: ShaderSystem, - StateSystem: StateSystem, - TextureGCSystem: TextureGCSystem, - TextureSystem: TextureSystem - }); - - var tempMatrix = new Matrix(); - /** - * The AbstractRenderer is the base for a PixiJS Renderer. It is extended by the {@link PIXI.CanvasRenderer} - * and {@link PIXI.Renderer} which can be used for rendering a PixiJS scene. - * - * @abstract - * @class - * @extends PIXI.utils.EventEmitter - * @memberof PIXI - */ - var AbstractRenderer = /** @class */ (function (_super) { - __extends$2(AbstractRenderer, _super); - /** - * @param {string} system - The name of the system this renderer is for. - * @param {object} [options] - The optional renderer parameters. - * @param {number} [options.width=800] - The width of the screen. - * @param {number} [options.height=600] - The height of the screen. - * @param {HTMLCanvasElement} [options.view] - The canvas to use as a view, optional. - * @param {boolean} [options.transparent=false] - If the render view is transparent. - * @param {boolean} [options.autoDensity=false] - Resizes renderer view in CSS pixels to allow for - * resolutions other than 1. - * @param {boolean} [options.antialias=false] - Sets antialias - * @param {number} [options.resolution=1] - The resolution / device pixel ratio of the renderer. The - * resolution of the renderer retina would be 2. - * @param {boolean} [options.preserveDrawingBuffer=false] - Enables drawing buffer preservation, - * enable this if you need to call toDataUrl on the WebGL context. - * @param {boolean} [options.clearBeforeRender=true] - This sets if the renderer will clear the canvas or - * not before the new render pass. - * @param {number} [options.backgroundColor=0x000000] - The background color of the rendered area - * (shown if not transparent). - */ - function AbstractRenderer(type, options) { - if (type === void 0) { type = exports.RENDERER_TYPE.UNKNOWN; } - var _this = _super.call(this) || this; - // Add the default render options - options = Object.assign({}, settings.RENDER_OPTIONS, options); - // Deprecation notice for renderer roundPixels option - if (options.roundPixels) { - settings.ROUND_PIXELS = options.roundPixels; - deprecation('5.0.0', 'Renderer roundPixels option is deprecated, please use PIXI.settings.ROUND_PIXELS', 2); - } - /** - * The supplied constructor options. - * - * @member {Object} - * @readOnly - */ - _this.options = options; - /** - * The type of the renderer. - * - * @member {number} - * @default PIXI.RENDERER_TYPE.UNKNOWN - * @see PIXI.RENDERER_TYPE - */ - _this.type = type; - /** - * Measurements of the screen. (0, 0, screenWidth, screenHeight). - * - * Its safe to use as filterArea or hitArea for the whole stage. - * - * @member {PIXI.Rectangle} - */ - _this.screen = new Rectangle(0, 0, options.width, options.height); - /** - * The canvas element that everything is drawn to. - * - * @member {HTMLCanvasElement} - */ - _this.view = options.view || document.createElement('canvas'); - /** - * The resolution / device pixel ratio of the renderer. - * - * @member {number} - * @default 1 - */ - _this.resolution = options.resolution || settings.RESOLUTION; - /** - * Whether the render view is transparent. - * - * @member {boolean} - */ - _this.transparent = options.transparent; - /** - * Whether CSS dimensions of canvas view should be resized to screen dimensions automatically. - * - * @member {boolean} - */ - _this.autoDensity = options.autoDensity || options.autoResize || false; - // autoResize is deprecated, provides fallback support - /** - * The value of the preserveDrawingBuffer flag affects whether or not the contents of - * the stencil buffer is retained after rendering. - * - * @member {boolean} - */ - _this.preserveDrawingBuffer = options.preserveDrawingBuffer; - /** - * This sets if the CanvasRenderer will clear the canvas or not before the new render pass. - * If the scene is NOT transparent PixiJS will use a canvas sized fillRect operation every - * frame to set the canvas background color. If the scene is transparent PixiJS will use clearRect - * to clear the canvas every frame. Disable this by setting this to false. For example, if - * your game has a canvas filling background image you often don't need this set. - * - * @member {boolean} - * @default - */ - _this.clearBeforeRender = options.clearBeforeRender; - /** - * The background color as a number. - * - * @member {number} - * @protected - */ - _this._backgroundColor = 0x000000; - /** - * The background color as an [R, G, B] array. - * - * @member {number[]} - * @protected - */ - _this._backgroundColorRgba = [0, 0, 0, 0]; - /** - * The background color as a string. - * - * @member {string} - * @protected - */ - _this._backgroundColorString = '#000000'; - _this.backgroundColor = options.backgroundColor || _this._backgroundColor; // run bg color setter - /** - * The last root object that the renderer tried to render. - * - * @member {PIXI.DisplayObject} - * @protected - */ - _this._lastObjectRendered = null; - /** - * Collection of plugins. - * @readonly - * @member {object} - */ - _this.plugins = {}; - return _this; - } - /** - * Initialize the plugins. - * - * @protected - * @param {object} staticMap - The dictionary of statically saved plugins. - */ - AbstractRenderer.prototype.initPlugins = function (staticMap) { - for (var o in staticMap) { - this.plugins[o] = new (staticMap[o])(this); - } - }; - Object.defineProperty(AbstractRenderer.prototype, "width", { - /** - * Same as view.width, actual number of pixels in the canvas by horizontal. - * - * @member {number} - * @readonly - * @default 800 - */ - get: function () { - return this.view.width; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(AbstractRenderer.prototype, "height", { - /** - * Same as view.height, actual number of pixels in the canvas by vertical. - * - * @member {number} - * @readonly - * @default 600 - */ - get: function () { - return this.view.height; - }, - enumerable: false, - configurable: true - }); - /** - * Resizes the screen and canvas to the specified width and height. - * Canvas dimensions are multiplied by resolution. - * - * @param {number} screenWidth - The new width of the screen. - * @param {number} screenHeight - The new height of the screen. - */ - AbstractRenderer.prototype.resize = function (screenWidth, screenHeight) { - this.screen.width = screenWidth; - this.screen.height = screenHeight; - this.view.width = screenWidth * this.resolution; - this.view.height = screenHeight * this.resolution; - if (this.autoDensity) { - this.view.style.width = screenWidth + "px"; - this.view.style.height = screenHeight + "px"; - } - /** - * Fired after view has been resized. - * - * @event PIXI.Renderer#resize - * @param {number} screenWidth - The new width of the screen. - * @param {number} screenHeight - The new height of the screen. - */ - this.emit('resize', screenWidth, screenHeight); - }; - /** - * Useful function that returns a texture of the display object that can then be used to create sprites - * This can be quite useful if your displayObject is complicated and needs to be reused multiple times. - * - * @param {PIXI.DisplayObject} displayObject - The displayObject the object will be generated from. - * @param {PIXI.SCALE_MODES} scaleMode - The scale mode of the texture. - * @param {number} resolution - The resolution / device pixel ratio of the texture being generated. - * @param {PIXI.Rectangle} [region] - The region of the displayObject, that shall be rendered, - * if no region is specified, defaults to the local bounds of the displayObject. - * @return {PIXI.RenderTexture} A texture of the graphics object. - */ - AbstractRenderer.prototype.generateTexture = function (displayObject, scaleMode, resolution, region) { - region = region || displayObject.getLocalBounds(null, true); - // minimum texture size is 1x1, 0x0 will throw an error - if (region.width === 0) - { region.width = 1; } - if (region.height === 0) - { region.height = 1; } - var renderTexture = RenderTexture.create({ - width: region.width | 0, - height: region.height | 0, - scaleMode: scaleMode, - resolution: resolution, - }); - tempMatrix.tx = -region.x; - tempMatrix.ty = -region.y; - this.render(displayObject, renderTexture, false, tempMatrix, !!displayObject.parent); - return renderTexture; - }; - /** - * Removes everything from the renderer and optionally removes the Canvas DOM element. - * - * @param {boolean} [removeView=false] - Removes the Canvas element from the DOM. - */ - AbstractRenderer.prototype.destroy = function (removeView) { - for (var o in this.plugins) { - this.plugins[o].destroy(); - this.plugins[o] = null; - } - if (removeView && this.view.parentNode) { - this.view.parentNode.removeChild(this.view); - } - var thisAny = this; - // null-ing all objects, that's a tradition! - thisAny.plugins = null; - thisAny.type = exports.RENDERER_TYPE.UNKNOWN; - thisAny.view = null; - thisAny.screen = null; - thisAny._tempDisplayObjectParent = null; - thisAny.options = null; - this._backgroundColorRgba = null; - this._backgroundColorString = null; - this._lastObjectRendered = null; - }; - Object.defineProperty(AbstractRenderer.prototype, "backgroundColor", { - /** - * The background color to fill if not transparent - * - * @member {number} - */ - get: function () { - return this._backgroundColor; - }, - set: function (value) { - this._backgroundColor = value; - this._backgroundColorString = hex2string(value); - hex2rgb(value, this._backgroundColorRgba); - }, - enumerable: false, - configurable: true - }); - return AbstractRenderer; - }(eventemitter3)); - - /** - * The Renderer draws the scene and all its content onto a WebGL enabled canvas. - * - * This renderer should be used for browsers that support WebGL. - * - * This renderer works by automatically managing WebGLBatchesm, so no need for Sprite Batches or Sprite Clouds. - * Don't forget to add the view to your DOM or you will not see anything! - * - * @class - * @memberof PIXI - * @extends PIXI.AbstractRenderer - */ - var Renderer = /** @class */ (function (_super) { - __extends$2(Renderer, _super); - /** - * @param {object} [options] - The optional renderer parameters. - * @param {number} [options.width=800] - The width of the screen. - * @param {number} [options.height=600] - The height of the screen. - * @param {HTMLCanvasElement} [options.view] - The canvas to use as a view, optional. - * @param {boolean} [options.transparent=false] - If the render view is transparent. - * @param {boolean} [options.autoDensity=false] - Resizes renderer view in CSS pixels to allow for - * resolutions other than 1. - * @param {boolean} [options.antialias=false] - Sets antialias. If not available natively then FXAA - * antialiasing is used. - * @param {number} [options.resolution=1] - The resolution / device pixel ratio of the renderer. - * The resolution of the renderer retina would be 2. - * @param {boolean} [options.clearBeforeRender=true] - This sets if the renderer will clear - * the canvas or not before the new render pass. If you wish to set this to false, you *must* set - * preserveDrawingBuffer to `true`. - * @param {boolean} [options.preserveDrawingBuffer=false] - Enables drawing buffer preservation, - * enable this if you need to call toDataUrl on the WebGL context. - * @param {number} [options.backgroundColor=0x000000] - The background color of the rendered area - * (shown if not transparent). - * @param {string} [options.powerPreference] - Parameter passed to WebGL context, set to "high-performance" - * for devices with dual graphics card. - * @param {object} [options.context] - If WebGL context already exists, all parameters must be taken from it. - * @public - */ - function Renderer(options) { - var _this = _super.call(this, exports.RENDERER_TYPE.WEBGL, options) || this; - // the options will have been modified here in the super constructor with pixi's default settings.. - options = _this.options; - /** - * WebGL context, set by the contextSystem (this.context) - * - * @readonly - * @member {WebGLRenderingContext} - */ - _this.gl = null; - _this.CONTEXT_UID = 0; - // TODO legacy! - /** - * Internal signal instances of **runner**, these - * are assigned to each system created. - * @see PIXI.Runner - * @name PIXI.Renderer#runners - * @private - * @type {object} - * @readonly - * @property {PIXI.Runner} destroy - Destroy runner - * @property {PIXI.Runner} contextChange - Context change runner - * @property {PIXI.Runner} reset - Reset runner - * @property {PIXI.Runner} update - Update runner - * @property {PIXI.Runner} postrender - Post-render runner - * @property {PIXI.Runner} prerender - Pre-render runner - * @property {PIXI.Runner} resize - Resize runner - */ - _this.runners = { - destroy: new Runner('destroy'), - contextChange: new Runner('contextChange'), - reset: new Runner('reset'), - update: new Runner('update'), - postrender: new Runner('postrender'), - prerender: new Runner('prerender'), - resize: new Runner('resize'), - }; - /** - * Global uniforms - * @member {PIXI.UniformGroup} - */ - _this.globalUniforms = new UniformGroup({ - projectionMatrix: new Matrix(), - }, true); - /** - * Mask system instance - * @member {PIXI.systems.MaskSystem} mask - * @memberof PIXI.Renderer# - * @readonly - */ - _this.addSystem(MaskSystem, 'mask') - /** - * Context system instance - * @member {PIXI.systems.ContextSystem} context - * @memberof PIXI.Renderer# - * @readonly - */ - .addSystem(ContextSystem, 'context') - /** - * State system instance - * @member {PIXI.systems.StateSystem} state - * @memberof PIXI.Renderer# - * @readonly - */ - .addSystem(StateSystem, 'state') - /** - * Shader system instance - * @member {PIXI.systems.ShaderSystem} shader - * @memberof PIXI.Renderer# - * @readonly - */ - .addSystem(ShaderSystem, 'shader') - /** - * Texture system instance - * @member {PIXI.systems.TextureSystem} texture - * @memberof PIXI.Renderer# - * @readonly - */ - .addSystem(TextureSystem, 'texture') - /** - * Geometry system instance - * @member {PIXI.systems.GeometrySystem} geometry - * @memberof PIXI.Renderer# - * @readonly - */ - .addSystem(GeometrySystem, 'geometry') - /** - * Framebuffer system instance - * @member {PIXI.systems.FramebufferSystem} framebuffer - * @memberof PIXI.Renderer# - * @readonly - */ - .addSystem(FramebufferSystem, 'framebuffer') - /** - * Scissor system instance - * @member {PIXI.systems.ScissorSystem} scissor - * @memberof PIXI.Renderer# - * @readonly - */ - .addSystem(ScissorSystem, 'scissor') - /** - * Stencil system instance - * @member {PIXI.systems.StencilSystem} stencil - * @memberof PIXI.Renderer# - * @readonly - */ - .addSystem(StencilSystem, 'stencil') - /** - * Projection system instance - * @member {PIXI.systems.ProjectionSystem} projection - * @memberof PIXI.Renderer# - * @readonly - */ - .addSystem(ProjectionSystem, 'projection') - /** - * Texture garbage collector system instance - * @member {PIXI.systems.TextureGCSystem} textureGC - * @memberof PIXI.Renderer# - * @readonly - */ - .addSystem(TextureGCSystem, 'textureGC') - /** - * Filter system instance - * @member {PIXI.systems.FilterSystem} filter - * @memberof PIXI.Renderer# - * @readonly - */ - .addSystem(FilterSystem, 'filter') - /** - * RenderTexture system instance - * @member {PIXI.systems.RenderTextureSystem} renderTexture - * @memberof PIXI.Renderer# - * @readonly - */ - .addSystem(RenderTextureSystem, 'renderTexture') - /** - * Batch system instance - * @member {PIXI.systems.BatchSystem} batch - * @memberof PIXI.Renderer# - * @readonly - */ - .addSystem(BatchSystem, 'batch'); - _this.initPlugins(Renderer.__plugins); - /** - * The options passed in to create a new WebGL context. - */ - if (options.context) { - _this.context.initFromContext(options.context); - } - else { - _this.context.initFromOptions({ - alpha: !!_this.transparent, - antialias: options.antialias, - premultipliedAlpha: _this.transparent && _this.transparent !== 'notMultiplied', - stencil: true, - preserveDrawingBuffer: options.preserveDrawingBuffer, - powerPreference: _this.options.powerPreference, - }); - } - /** - * Flag if we are rendering to the screen vs renderTexture - * @member {boolean} - * @readonly - * @default true - */ - _this.renderingToScreen = true; - sayHello(_this.context.webGLVersion === 2 ? 'WebGL 2' : 'WebGL 1'); - _this.resize(_this.options.width, _this.options.height); - return _this; - } - /** - * Create renderer if WebGL is available. Overrideable - * by the **@pixi/canvas-renderer** package to allow fallback. - * throws error if WebGL is not available. - * @static - * @private - */ - Renderer.create = function (options) { - if (isWebGLSupported()) { - return new Renderer(options); - } - throw new Error('WebGL unsupported in this browser, use "pixi.js-legacy" for fallback canvas2d support.'); - }; - /** - * Add a new system to the renderer. - * @param {Function} ClassRef - Class reference - * @param {string} [name] - Property name for system, if not specified - * will use a static `name` property on the class itself. This - * name will be assigned as s property on the Renderer so make - * sure it doesn't collide with properties on Renderer. - * @return {PIXI.Renderer} Return instance of renderer - */ - Renderer.prototype.addSystem = function (ClassRef, name) { - if (!name) { - name = ClassRef.name; - } - var system = new ClassRef(this); - if (this[name]) { - throw new Error("Whoops! The name \"" + name + "\" is already in use"); - } - this[name] = system; - for (var i in this.runners) { - this.runners[i].add(system); - } - /** - * Fired after rendering finishes. - * - * @event PIXI.Renderer#postrender - */ - /** - * Fired before rendering starts. - * - * @event PIXI.Renderer#prerender - */ - /** - * Fired when the WebGL context is set. - * - * @event PIXI.Renderer#context - * @param {WebGLRenderingContext} gl - WebGL context. - */ - return this; - }; - /** - * Renders the object to its WebGL view - * - * @param {PIXI.DisplayObject} displayObject - The object to be rendered. - * @param {PIXI.RenderTexture} [renderTexture] - The render texture to render to. - * @param {boolean} [clear=true] - Should the canvas be cleared before the new render. - * @param {PIXI.Matrix} [transform] - A transform to apply to the render texture before rendering. - * @param {boolean} [skipUpdateTransform=false] - Should we skip the update transform pass? - */ - Renderer.prototype.render = function (displayObject, renderTexture, clear, transform, skipUpdateTransform) { - // can be handy to know! - this.renderingToScreen = !renderTexture; - this.runners.prerender.emit(); - this.emit('prerender'); - // apply a transform at a GPU level - this.projection.transform = transform; - // no point rendering if our context has been blown up! - if (this.context.isLost) { - return; - } - if (!renderTexture) { - this._lastObjectRendered = displayObject; - } - if (!skipUpdateTransform) { - // update the scene graph - var cacheParent = displayObject.enableTempParent(); - displayObject.updateTransform(); - displayObject.disableTempParent(cacheParent); - // displayObject.hitArea = //TODO add a temp hit area - } - this.renderTexture.bind(renderTexture); - this.batch.currentRenderer.start(); - if (clear !== undefined ? clear : this.clearBeforeRender) { - this.renderTexture.clear(); - } - displayObject.render(this); - // apply transform.. - this.batch.currentRenderer.flush(); - if (renderTexture) { - renderTexture.baseTexture.update(); - } - this.runners.postrender.emit(); - // reset transform after render - this.projection.transform = null; - this.emit('postrender'); - }; - /** - * Resizes the WebGL view to the specified width and height. - * - * @param {number} screenWidth - The new width of the screen. - * @param {number} screenHeight - The new height of the screen. - */ - Renderer.prototype.resize = function (screenWidth, screenHeight) { - _super.prototype.resize.call(this, screenWidth, screenHeight); - this.runners.resize.emit(screenWidth, screenHeight); - }; - /** - * Resets the WebGL state so you can render things however you fancy! - * - * @return {PIXI.Renderer} Returns itself. - */ - Renderer.prototype.reset = function () { - this.runners.reset.emit(); - return this; - }; - /** - * Clear the frame buffer - */ - Renderer.prototype.clear = function () { - this.renderTexture.bind(); - this.renderTexture.clear(); - }; - /** - * Removes everything from the renderer (event listeners, spritebatch, etc...) - * - * @param {boolean} [removeView=false] - Removes the Canvas element from the DOM. - * See: https://github.com/pixijs/pixi.js/issues/2233 - */ - Renderer.prototype.destroy = function (removeView) { - this.runners.destroy.emit(); - for (var r in this.runners) { - this.runners[r].destroy(); - } - // call base destroy - _super.prototype.destroy.call(this, removeView); - // TODO nullify all the managers.. - this.gl = null; - }; - /** - * Adds a plugin to the renderer. - * - * @method - * @param {string} pluginName - The name of the plugin. - * @param {Function} ctor - The constructor function or class for the plugin. - */ - Renderer.registerPlugin = function (pluginName, ctor) { - Renderer.__plugins = Renderer.__plugins || {}; - Renderer.__plugins[pluginName] = ctor; - }; - return Renderer; - }(AbstractRenderer)); - - /** - * This helper function will automatically detect which renderer you should be using. - * WebGL is the preferred renderer as it is a lot faster. If WebGL is not supported by - * the browser then this function will return a canvas renderer - * - * @memberof PIXI - * @function autoDetectRenderer - * @param {object} [options] - The optional renderer parameters - * @param {number} [options.width=800] - the width of the renderers view - * @param {number} [options.height=600] - the height of the renderers view - * @param {HTMLCanvasElement} [options.view] - the canvas to use as a view, optional - * @param {boolean} [options.transparent=false] - If the render view is transparent, default false - * @param {boolean} [options.autoDensity=false] - Resizes renderer view in CSS pixels to allow for - * resolutions other than 1 - * @param {boolean} [options.antialias=false] - sets antialias - * @param {boolean} [options.preserveDrawingBuffer=false] - enables drawing buffer preservation, enable this if you - * need to call toDataUrl on the webgl context - * @param {number} [options.backgroundColor=0x000000] - The background color of the rendered area - * (shown if not transparent). - * @param {boolean} [options.clearBeforeRender=true] - This sets if the renderer will clear the canvas or - * not before the new render pass. - * @param {number} [options.resolution=1] - The resolution / device pixel ratio of the renderer, retina would be 2 - * @param {boolean} [options.forceCanvas=false] - prevents selection of WebGL renderer, even if such is present, this - * option only is available when using **pixi.js-legacy** or **@pixi/canvas-renderer** modules, otherwise - * it is ignored. - * @param {string} [options.powerPreference] - Parameter passed to webgl context, set to "high-performance" - * for devices with dual graphics card **webgl only** - * @return {PIXI.Renderer|PIXI.CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer - */ - function autoDetectRenderer(options) { - return Renderer.create(options); - } - - var _default = "attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n vTextureCoord = aTextureCoord;\n}"; - - var defaultFilter = "attribute vec2 aVertexPosition;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 vTextureCoord;\n\nuniform vec4 inputSize;\nuniform vec4 outputFrame;\n\nvec4 filterVertexPosition( void )\n{\n vec2 position = aVertexPosition * max(outputFrame.zw, vec2(0.)) + outputFrame.xy;\n\n return vec4((projectionMatrix * vec3(position, 1.0)).xy, 0.0, 1.0);\n}\n\nvec2 filterTextureCoord( void )\n{\n return aVertexPosition * (outputFrame.zw * inputSize.zw);\n}\n\nvoid main(void)\n{\n gl_Position = filterVertexPosition();\n vTextureCoord = filterTextureCoord();\n}\n"; - - /** - * Used by the batcher to draw batches. - * Each one of these contains all information required to draw a bound geometry. - * - * @class - * @memberof PIXI - */ - var BatchDrawCall = /** @class */ (function () { - function BatchDrawCall() { - this.texArray = null; - this.blend = 0; - this.type = exports.DRAW_MODES.TRIANGLES; - this.start = 0; - this.size = 0; - /** - * data for uniforms or custom webgl state - * @member {object} - */ - this.data = null; - } - return BatchDrawCall; - }()); - - /** - * Used by the batcher to build texture batches. - * Holds list of textures and their respective locations. - * - * @class - * @memberof PIXI - */ - var BatchTextureArray = /** @class */ (function () { - function BatchTextureArray() { - /** - * inside textures array - * @member {PIXI.BaseTexture[]} - */ - this.elements = []; - /** - * Respective locations for textures - * @member {number[]} - */ - this.ids = []; - /** - * number of filled elements - * @member {number} - */ - this.count = 0; - } - BatchTextureArray.prototype.clear = function () { - for (var i = 0; i < this.count; i++) { - this.elements[i] = null; - } - this.count = 0; - }; - return BatchTextureArray; - }()); - - /** - * Flexible wrapper around `ArrayBuffer` that also provides - * typed array views on demand. - * - * @class - * @memberof PIXI - */ - var ViewableBuffer = /** @class */ (function () { - /** - * @param {number} size - The size of the buffer in bytes. - */ - function ViewableBuffer(size) { - /** - * Underlying `ArrayBuffer` that holds all the data - * and is of capacity `size`. - * - * @member {ArrayBuffer} - */ - this.rawBinaryData = new ArrayBuffer(size); - /** - * View on the raw binary data as a `Uint32Array`. - * - * @member {Uint32Array} - */ - this.uint32View = new Uint32Array(this.rawBinaryData); - /** - * View on the raw binary data as a `Float32Array`. - * - * @member {Float32Array} - */ - this.float32View = new Float32Array(this.rawBinaryData); - } - Object.defineProperty(ViewableBuffer.prototype, "int8View", { - /** - * View on the raw binary data as a `Int8Array`. - * - * @member {Int8Array} - */ - get: function () { - if (!this._int8View) { - this._int8View = new Int8Array(this.rawBinaryData); - } - return this._int8View; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(ViewableBuffer.prototype, "uint8View", { - /** - * View on the raw binary data as a `Uint8Array`. - * - * @member {Uint8Array} - */ - get: function () { - if (!this._uint8View) { - this._uint8View = new Uint8Array(this.rawBinaryData); - } - return this._uint8View; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(ViewableBuffer.prototype, "int16View", { - /** - * View on the raw binary data as a `Int16Array`. - * - * @member {Int16Array} - */ - get: function () { - if (!this._int16View) { - this._int16View = new Int16Array(this.rawBinaryData); - } - return this._int16View; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(ViewableBuffer.prototype, "uint16View", { - /** - * View on the raw binary data as a `Uint16Array`. - * - * @member {Uint16Array} - */ - get: function () { - if (!this._uint16View) { - this._uint16View = new Uint16Array(this.rawBinaryData); - } - return this._uint16View; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(ViewableBuffer.prototype, "int32View", { - /** - * View on the raw binary data as a `Int32Array`. - * - * @member {Int32Array} - */ - get: function () { - if (!this._int32View) { - this._int32View = new Int32Array(this.rawBinaryData); - } - return this._int32View; - }, - enumerable: false, - configurable: true - }); - /** - * Returns the view of the given type. - * - * @param {string} type - One of `int8`, `uint8`, `int16`, - * `uint16`, `int32`, `uint32`, and `float32`. - * @return {object} typed array of given type - */ - ViewableBuffer.prototype.view = function (type) { - return this[type + "View"]; - }; - /** - * Destroys all buffer references. Do not use after calling - * this. - */ - ViewableBuffer.prototype.destroy = function () { - this.rawBinaryData = null; - this._int8View = null; - this._uint8View = null; - this._int16View = null; - this._uint16View = null; - this._int32View = null; - this.uint32View = null; - this.float32View = null; - }; - ViewableBuffer.sizeOf = function (type) { - switch (type) { - case 'int8': - case 'uint8': - return 1; - case 'int16': - case 'uint16': - return 2; - case 'int32': - case 'uint32': - case 'float32': - return 4; - default: - throw new Error(type + " isn't a valid view type"); - } - }; - return ViewableBuffer; - }()); - - /** - * Renderer dedicated to drawing and batching sprites. - * - * This is the default batch renderer. It buffers objects - * with texture-based geometries and renders them in - * batches. It uploads multiple textures to the GPU to - * reduce to the number of draw calls. - * - * @class - * @protected - * @memberof PIXI - * @extends PIXI.ObjectRenderer - */ - var AbstractBatchRenderer = /** @class */ (function (_super) { - __extends$2(AbstractBatchRenderer, _super); - /** - * This will hook onto the renderer's `contextChange` - * and `prerender` signals. - * - * @param {PIXI.Renderer} renderer - The renderer this works for. - */ - function AbstractBatchRenderer(renderer) { - var _this = _super.call(this, renderer) || this; - /** - * This is used to generate a shader that can - * color each vertex based on a `aTextureId` - * attribute that points to an texture in `uSampler`. - * - * This enables the objects with different textures - * to be drawn in the same draw call. - * - * You can customize your shader by creating your - * custom shader generator. - * - * @member {PIXI.BatchShaderGenerator} - * @protected - */ - _this.shaderGenerator = null; - /** - * The class that represents the geometry of objects - * that are going to be batched with this. - * - * @member {object} - * @default PIXI.BatchGeometry - * @protected - */ - _this.geometryClass = null; - /** - * Size of data being buffered per vertex in the - * attribute buffers (in floats). By default, the - * batch-renderer plugin uses 6: - * - * | aVertexPosition | 2 | - * |-----------------|---| - * | aTextureCoords | 2 | - * | aColor | 1 | - * | aTextureId | 1 | - * - * @member {number} - * @readonly - */ - _this.vertexSize = null; - /** - * The WebGL state in which this renderer will work. - * - * @member {PIXI.State} - * @readonly - */ - _this.state = State.for2d(); - /** - * The number of bufferable objects before a flush - * occurs automatically. - * - * @member {number} - * @default settings.SPRITE_BATCH_SIZE * 4 - */ - _this.size = settings.SPRITE_BATCH_SIZE * 4; - /** - * Total count of all vertices used by the currently - * buffered objects. - * - * @member {number} - * @private - */ - _this._vertexCount = 0; - /** - * Total count of all indices used by the currently - * buffered objects. - * - * @member {number} - * @private - */ - _this._indexCount = 0; - /** - * Buffer of objects that are yet to be rendered. - * - * @member {PIXI.DisplayObject[]} - * @private - */ - _this._bufferedElements = []; - /** - * Data for texture batch builder, helps to save a bit of CPU on a pass. - * @type {PIXI.BaseTexture[]} - * @private - */ - _this._bufferedTextures = []; - /** - * Number of elements that are buffered and are - * waiting to be flushed. - * - * @member {number} - * @private - */ - _this._bufferSize = 0; - /** - * This shader is generated by `this.shaderGenerator`. - * - * It is generated specifically to handle the required - * number of textures being batched together. - * - * @member {PIXI.Shader} - * @protected - */ - _this._shader = null; - /** - * Pool of `this.geometryClass` geometry objects - * that store buffers. They are used to pass data - * to the shader on each draw call. - * - * These are never re-allocated again, unless a - * context change occurs; however, the pool may - * be expanded if required. - * - * @member {PIXI.Geometry[]} - * @private - * @see PIXI.AbstractBatchRenderer.contextChange - */ - _this._packedGeometries = []; - /** - * Size of `this._packedGeometries`. It can be expanded - * if more than `this._packedGeometryPoolSize` flushes - * occur in a single frame. - * - * @member {number} - * @private - */ - _this._packedGeometryPoolSize = 2; - /** - * A flush may occur multiple times in a single - * frame. On iOS devices or when - * `settings.CAN_UPLOAD_SAME_BUFFER` is false, the - * batch renderer does not upload data to the same - * `WebGLBuffer` for performance reasons. - * - * This is the index into `packedGeometries` that points to - * geometry holding the most recent buffers. - * - * @member {number} - * @private - */ - _this._flushId = 0; - /** - * Pool of `ViewableBuffer` objects that are sorted in - * order of increasing size. The flush method uses - * the buffer with the least size above the amount - * it requires. These are used for passing attributes. - * - * The first buffer has a size of 8; each subsequent - * buffer has double capacity of its previous. - * - * @member {PIXI.ViewableBuffer[]} - * @private - * @see PIXI.AbstractBatchRenderer#getAttributeBuffer - */ - _this._aBuffers = {}; - /** - * Pool of `Uint16Array` objects that are sorted in - * order of increasing size. The flush method uses - * the buffer with the least size above the amount - * it requires. These are used for passing indices. - * - * The first buffer has a size of 12; each subsequent - * buffer has double capacity of its previous. - * - * @member {Uint16Array[]} - * @private - * @see PIXI.AbstractBatchRenderer#getIndexBuffer - */ - _this._iBuffers = {}; - /** - * Maximum number of textures that can be uploaded to - * the GPU under the current context. It is initialized - * properly in `this.contextChange`. - * - * @member {number} - * @see PIXI.AbstractBatchRenderer#contextChange - * @readonly - */ - _this.MAX_TEXTURES = 1; - _this.renderer.on('prerender', _this.onPrerender, _this); - renderer.runners.contextChange.add(_this); - _this._dcIndex = 0; - _this._aIndex = 0; - _this._iIndex = 0; - _this._attributeBuffer = null; - _this._indexBuffer = null; - _this._tempBoundTextures = []; - return _this; - } - /** - * Handles the `contextChange` signal. - * - * It calculates `this.MAX_TEXTURES` and allocating the - * packed-geometry object pool. - */ - AbstractBatchRenderer.prototype.contextChange = function () { - var gl = this.renderer.gl; - if (settings.PREFER_ENV === exports.ENV.WEBGL_LEGACY) { - this.MAX_TEXTURES = 1; - } - else { - // step 1: first check max textures the GPU can handle. - this.MAX_TEXTURES = Math.min(gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS), settings.SPRITE_MAX_TEXTURES); - // step 2: check the maximum number of if statements the shader can have too.. - this.MAX_TEXTURES = checkMaxIfStatementsInShader(this.MAX_TEXTURES, gl); - } - this._shader = this.shaderGenerator.generateShader(this.MAX_TEXTURES); - // we use the second shader as the first one depending on your browser - // may omit aTextureId as it is not used by the shader so is optimized out. - for (var i = 0; i < this._packedGeometryPoolSize; i++) { - /* eslint-disable max-len */ - this._packedGeometries[i] = new (this.geometryClass)(); - } - this.initFlushBuffers(); - }; - /** - * Makes sure that static and dynamic flush pooled objects have correct dimensions - */ - AbstractBatchRenderer.prototype.initFlushBuffers = function () { - var _drawCallPool = AbstractBatchRenderer._drawCallPool, _textureArrayPool = AbstractBatchRenderer._textureArrayPool; - // max draw calls - var MAX_SPRITES = this.size / 4; - // max texture arrays - var MAX_TA = Math.floor(MAX_SPRITES / this.MAX_TEXTURES) + 1; - while (_drawCallPool.length < MAX_SPRITES) { - _drawCallPool.push(new BatchDrawCall()); - } - while (_textureArrayPool.length < MAX_TA) { - _textureArrayPool.push(new BatchTextureArray()); - } - for (var i = 0; i < this.MAX_TEXTURES; i++) { - this._tempBoundTextures[i] = null; - } - }; - /** - * Handles the `prerender` signal. - * - * It ensures that flushes start from the first geometry - * object again. - */ - AbstractBatchRenderer.prototype.onPrerender = function () { - this._flushId = 0; - }; - /** - * Buffers the "batchable" object. It need not be rendered - * immediately. - * - * @param {PIXI.DisplayObject} element - the element to render when - * using this renderer - */ - AbstractBatchRenderer.prototype.render = function (element) { - if (!element._texture.valid) { - return; - } - if (this._vertexCount + (element.vertexData.length / 2) > this.size) { - this.flush(); - } - this._vertexCount += element.vertexData.length / 2; - this._indexCount += element.indices.length; - this._bufferedTextures[this._bufferSize] = element._texture.baseTexture; - this._bufferedElements[this._bufferSize++] = element; - }; - AbstractBatchRenderer.prototype.buildTexturesAndDrawCalls = function () { - var _a = this, textures = _a._bufferedTextures, MAX_TEXTURES = _a.MAX_TEXTURES; - var textureArrays = AbstractBatchRenderer._textureArrayPool; - var batch = this.renderer.batch; - var boundTextures = this._tempBoundTextures; - var touch = this.renderer.textureGC.count; - var TICK = ++BaseTexture._globalBatch; - var countTexArrays = 0; - var texArray = textureArrays[0]; - var start = 0; - batch.copyBoundTextures(boundTextures, MAX_TEXTURES); - for (var i = 0; i < this._bufferSize; ++i) { - var tex = textures[i]; - textures[i] = null; - if (tex._batchEnabled === TICK) { - continue; - } - if (texArray.count >= MAX_TEXTURES) { - batch.boundArray(texArray, boundTextures, TICK, MAX_TEXTURES); - this.buildDrawCalls(texArray, start, i); - start = i; - texArray = textureArrays[++countTexArrays]; - ++TICK; - } - tex._batchEnabled = TICK; - tex.touched = touch; - texArray.elements[texArray.count++] = tex; - } - if (texArray.count > 0) { - batch.boundArray(texArray, boundTextures, TICK, MAX_TEXTURES); - this.buildDrawCalls(texArray, start, this._bufferSize); - ++countTexArrays; - ++TICK; - } - // Clean-up - for (var i = 0; i < boundTextures.length; i++) { - boundTextures[i] = null; - } - BaseTexture._globalBatch = TICK; - }; - /** - * Populating drawcalls for rendering - * - * @param {PIXI.BatchTextureArray} texArray - * @param {number} start - * @param {number} finish - */ - AbstractBatchRenderer.prototype.buildDrawCalls = function (texArray, start, finish) { - var _a = this, elements = _a._bufferedElements, _attributeBuffer = _a._attributeBuffer, _indexBuffer = _a._indexBuffer, vertexSize = _a.vertexSize; - var drawCalls = AbstractBatchRenderer._drawCallPool; - var dcIndex = this._dcIndex; - var aIndex = this._aIndex; - var iIndex = this._iIndex; - var drawCall = drawCalls[dcIndex]; - drawCall.start = this._iIndex; - drawCall.texArray = texArray; - for (var i = start; i < finish; ++i) { - var sprite = elements[i]; - var tex = sprite._texture.baseTexture; - var spriteBlendMode = premultiplyBlendMode[tex.alphaMode ? 1 : 0][sprite.blendMode]; - elements[i] = null; - if (start < i && drawCall.blend !== spriteBlendMode) { - drawCall.size = iIndex - drawCall.start; - start = i; - drawCall = drawCalls[++dcIndex]; - drawCall.texArray = texArray; - drawCall.start = iIndex; - } - this.packInterleavedGeometry(sprite, _attributeBuffer, _indexBuffer, aIndex, iIndex); - aIndex += sprite.vertexData.length / 2 * vertexSize; - iIndex += sprite.indices.length; - drawCall.blend = spriteBlendMode; - } - if (start < finish) { - drawCall.size = iIndex - drawCall.start; - ++dcIndex; - } - this._dcIndex = dcIndex; - this._aIndex = aIndex; - this._iIndex = iIndex; - }; - /** - * Bind textures for current rendering - * - * @param {PIXI.BatchTextureArray} texArray - */ - AbstractBatchRenderer.prototype.bindAndClearTexArray = function (texArray) { - var textureSystem = this.renderer.texture; - for (var j = 0; j < texArray.count; j++) { - textureSystem.bind(texArray.elements[j], texArray.ids[j]); - texArray.elements[j] = null; - } - texArray.count = 0; - }; - AbstractBatchRenderer.prototype.updateGeometry = function () { - var _a = this, packedGeometries = _a._packedGeometries, attributeBuffer = _a._attributeBuffer, indexBuffer = _a._indexBuffer; - if (!settings.CAN_UPLOAD_SAME_BUFFER) { /* Usually on iOS devices, where the browser doesn't - like uploads to the same buffer in a single frame. */ - if (this._packedGeometryPoolSize <= this._flushId) { - this._packedGeometryPoolSize++; - packedGeometries[this._flushId] = new (this.geometryClass)(); - } - packedGeometries[this._flushId]._buffer.update(attributeBuffer.rawBinaryData); - packedGeometries[this._flushId]._indexBuffer.update(indexBuffer); - this.renderer.geometry.bind(packedGeometries[this._flushId]); - this.renderer.geometry.updateBuffers(); - this._flushId++; - } - else { - // lets use the faster option, always use buffer number 0 - packedGeometries[this._flushId]._buffer.update(attributeBuffer.rawBinaryData); - packedGeometries[this._flushId]._indexBuffer.update(indexBuffer); - this.renderer.geometry.updateBuffers(); - } - }; - AbstractBatchRenderer.prototype.drawBatches = function () { - var dcCount = this._dcIndex; - var _a = this.renderer, gl = _a.gl, stateSystem = _a.state; - var drawCalls = AbstractBatchRenderer._drawCallPool; - var curTexArray = null; - // Upload textures and do the draw calls - for (var i = 0; i < dcCount; i++) { - var _b = drawCalls[i], texArray = _b.texArray, type = _b.type, size = _b.size, start = _b.start, blend = _b.blend; - if (curTexArray !== texArray) { - curTexArray = texArray; - this.bindAndClearTexArray(texArray); - } - this.state.blendMode = blend; - stateSystem.set(this.state); - gl.drawElements(type, size, gl.UNSIGNED_SHORT, start * 2); - } - }; - /** - * Renders the content _now_ and empties the current batch. - */ - AbstractBatchRenderer.prototype.flush = function () { - if (this._vertexCount === 0) { - return; - } - this._attributeBuffer = this.getAttributeBuffer(this._vertexCount); - this._indexBuffer = this.getIndexBuffer(this._indexCount); - this._aIndex = 0; - this._iIndex = 0; - this._dcIndex = 0; - this.buildTexturesAndDrawCalls(); - this.updateGeometry(); - this.drawBatches(); - // reset elements buffer for the next flush - this._bufferSize = 0; - this._vertexCount = 0; - this._indexCount = 0; - }; - /** - * Starts a new sprite batch. - */ - AbstractBatchRenderer.prototype.start = function () { - this.renderer.state.set(this.state); - this.renderer.shader.bind(this._shader); - if (settings.CAN_UPLOAD_SAME_BUFFER) { - // bind buffer #0, we don't need others - this.renderer.geometry.bind(this._packedGeometries[this._flushId]); - } - }; - /** - * Stops and flushes the current batch. - */ - AbstractBatchRenderer.prototype.stop = function () { - this.flush(); - }; - /** - * Destroys this `AbstractBatchRenderer`. It cannot be used again. - */ - AbstractBatchRenderer.prototype.destroy = function () { - for (var i = 0; i < this._packedGeometryPoolSize; i++) { - if (this._packedGeometries[i]) { - this._packedGeometries[i].destroy(); - } - } - this.renderer.off('prerender', this.onPrerender, this); - this._aBuffers = null; - this._iBuffers = null; - this._packedGeometries = null; - this._attributeBuffer = null; - this._indexBuffer = null; - if (this._shader) { - this._shader.destroy(); - this._shader = null; - } - _super.prototype.destroy.call(this); - }; - /** - * Fetches an attribute buffer from `this._aBuffers` that - * can hold atleast `size` floats. - * - * @param {number} size - minimum capacity required - * @return {ViewableBuffer} - buffer than can hold atleast `size` floats - * @private - */ - AbstractBatchRenderer.prototype.getAttributeBuffer = function (size) { - // 8 vertices is enough for 2 quads - var roundedP2 = nextPow2(Math.ceil(size / 8)); - var roundedSizeIndex = log2(roundedP2); - var roundedSize = roundedP2 * 8; - if (this._aBuffers.length <= roundedSizeIndex) { - this._iBuffers.length = roundedSizeIndex + 1; - } - var buffer = this._aBuffers[roundedSize]; - if (!buffer) { - this._aBuffers[roundedSize] = buffer = new ViewableBuffer(roundedSize * this.vertexSize * 4); - } - return buffer; - }; - /** - * Fetches an index buffer from `this._iBuffers` that can - * have at least `size` capacity. - * - * @param {number} size - minimum required capacity - * @return {Uint16Array} - buffer that can fit `size` - * indices. - * @private - */ - AbstractBatchRenderer.prototype.getIndexBuffer = function (size) { - // 12 indices is enough for 2 quads - var roundedP2 = nextPow2(Math.ceil(size / 12)); - var roundedSizeIndex = log2(roundedP2); - var roundedSize = roundedP2 * 12; - if (this._iBuffers.length <= roundedSizeIndex) { - this._iBuffers.length = roundedSizeIndex + 1; - } - var buffer = this._iBuffers[roundedSizeIndex]; - if (!buffer) { - this._iBuffers[roundedSizeIndex] = buffer = new Uint16Array(roundedSize); - } - return buffer; - }; - /** - * Takes the four batching parameters of `element`, interleaves - * and pushes them into the batching attribute/index buffers given. - * - * It uses these properties: `vertexData` `uvs`, `textureId` and - * `indicies`. It also uses the "tint" of the base-texture, if - * present. - * - * @param {PIXI.Sprite} element - element being rendered - * @param {PIXI.ViewableBuffer} attributeBuffer - attribute buffer. - * @param {Uint16Array} indexBuffer - index buffer - * @param {number} aIndex - number of floats already in the attribute buffer - * @param {number} iIndex - number of indices already in `indexBuffer` - */ - AbstractBatchRenderer.prototype.packInterleavedGeometry = function (element, attributeBuffer, indexBuffer, aIndex, iIndex) { - var uint32View = attributeBuffer.uint32View, float32View = attributeBuffer.float32View; - var packedVertices = aIndex / this.vertexSize; - var uvs = element.uvs; - var indicies = element.indices; - var vertexData = element.vertexData; - var textureId = element._texture.baseTexture._batchLocation; - var alpha = Math.min(element.worldAlpha, 1.0); - var argb = (alpha < 1.0 - && element._texture.baseTexture.alphaMode) - ? premultiplyTint(element._tintRGB, alpha) - : element._tintRGB + (alpha * 255 << 24); - // lets not worry about tint! for now.. - for (var i = 0; i < vertexData.length; i += 2) { - float32View[aIndex++] = vertexData[i]; - float32View[aIndex++] = vertexData[i + 1]; - float32View[aIndex++] = uvs[i]; - float32View[aIndex++] = uvs[i + 1]; - uint32View[aIndex++] = argb; - float32View[aIndex++] = textureId; - } - for (var i = 0; i < indicies.length; i++) { - indexBuffer[iIndex++] = packedVertices + indicies[i]; - } - }; - /** - * Pool of `BatchDrawCall` objects that `flush` used - * to create "batches" of the objects being rendered. - * - * These are never re-allocated again. - * Shared between all batch renderers because it can be only one "flush" working at the moment. - * - * @static - * @member {PIXI.BatchDrawCall[]} - */ - AbstractBatchRenderer._drawCallPool = []; - /** - * Pool of `BatchDrawCall` objects that `flush` used - * to create "batches" of the objects being rendered. - * - * These are never re-allocated again. - * Shared between all batch renderers because it can be only one "flush" working at the moment. - * - * @static - * @member {PIXI.BatchTextureArray[]} - */ - AbstractBatchRenderer._textureArrayPool = []; - return AbstractBatchRenderer; - }(ObjectRenderer)); - - /** - * Helper that generates batching multi-texture shader. Use it with your new BatchRenderer - * - * @class - * @memberof PIXI - */ - var BatchShaderGenerator = /** @class */ (function () { - /** - * @param {string} vertexSrc - Vertex shader - * @param {string} fragTemplate - Fragment shader template - */ - function BatchShaderGenerator(vertexSrc, fragTemplate) { - /** - * Reference to the vertex shader source. - * - * @member {string} - */ - this.vertexSrc = vertexSrc; - /** - * Reference to the fragement shader template. Must contain "%count%" and "%forloop%". - * - * @member {string} - */ - this.fragTemplate = fragTemplate; - this.programCache = {}; - this.defaultGroupCache = {}; - if (fragTemplate.indexOf('%count%') < 0) { - throw new Error('Fragment template must contain "%count%".'); - } - if (fragTemplate.indexOf('%forloop%') < 0) { - throw new Error('Fragment template must contain "%forloop%".'); - } - } - BatchShaderGenerator.prototype.generateShader = function (maxTextures) { - if (!this.programCache[maxTextures]) { - var sampleValues = new Int32Array(maxTextures); - for (var i = 0; i < maxTextures; i++) { - sampleValues[i] = i; - } - this.defaultGroupCache[maxTextures] = UniformGroup.from({ uSamplers: sampleValues }, true); - var fragmentSrc = this.fragTemplate; - fragmentSrc = fragmentSrc.replace(/%count%/gi, "" + maxTextures); - fragmentSrc = fragmentSrc.replace(/%forloop%/gi, this.generateSampleSrc(maxTextures)); - this.programCache[maxTextures] = new Program(this.vertexSrc, fragmentSrc); - } - var uniforms = { - tint: new Float32Array([1, 1, 1, 1]), - translationMatrix: new Matrix(), - default: this.defaultGroupCache[maxTextures], - }; - return new Shader(this.programCache[maxTextures], uniforms); - }; - BatchShaderGenerator.prototype.generateSampleSrc = function (maxTextures) { - var src = ''; - src += '\n'; - src += '\n'; - for (var i = 0; i < maxTextures; i++) { - if (i > 0) { - src += '\nelse '; - } - if (i < maxTextures - 1) { - src += "if(vTextureId < " + i + ".5)"; - } - src += '\n{'; - src += "\n\tcolor = texture2D(uSamplers[" + i + "], vTextureCoord);"; - src += '\n}'; - } - src += '\n'; - src += '\n'; - return src; - }; - return BatchShaderGenerator; - }()); - - /** - * Geometry used to batch standard PIXI content (e.g. Mesh, Sprite, Graphics objects). - * - * @class - * @memberof PIXI - */ - var BatchGeometry = /** @class */ (function (_super) { - __extends$2(BatchGeometry, _super); - /** - * @param {boolean} [_static=false] - Optimization flag, where `false` - * is updated every frame, `true` doesn't change frame-to-frame. - */ - function BatchGeometry(_static) { - if (_static === void 0) { _static = false; } - var _this = _super.call(this) || this; - /** - * Buffer used for position, color, texture IDs - * - * @member {PIXI.Buffer} - * @protected - */ - _this._buffer = new Buffer(null, _static, false); - /** - * Index buffer data - * - * @member {PIXI.Buffer} - * @protected - */ - _this._indexBuffer = new Buffer(null, _static, true); - _this.addAttribute('aVertexPosition', _this._buffer, 2, false, exports.TYPES.FLOAT) - .addAttribute('aTextureCoord', _this._buffer, 2, false, exports.TYPES.FLOAT) - .addAttribute('aColor', _this._buffer, 4, true, exports.TYPES.UNSIGNED_BYTE) - .addAttribute('aTextureId', _this._buffer, 1, true, exports.TYPES.FLOAT) - .addIndex(_this._indexBuffer); - return _this; - } - return BatchGeometry; - }(Geometry)); - - var defaultVertex$2 = "precision highp float;\nattribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\nattribute vec4 aColor;\nattribute float aTextureId;\n\nuniform mat3 projectionMatrix;\nuniform mat3 translationMatrix;\nuniform vec4 tint;\n\nvarying vec2 vTextureCoord;\nvarying vec4 vColor;\nvarying float vTextureId;\n\nvoid main(void){\n gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n vTextureCoord = aTextureCoord;\n vTextureId = aTextureId;\n vColor = aColor * tint;\n}\n"; - - var defaultFragment$2 = "varying vec2 vTextureCoord;\nvarying vec4 vColor;\nvarying float vTextureId;\nuniform sampler2D uSamplers[%count%];\n\nvoid main(void){\n vec4 color;\n %forloop%\n gl_FragColor = color * vColor;\n}\n"; - - /** - * @class - * @memberof PIXI - * @hideconstructor - */ - var BatchPluginFactory = /** @class */ (function () { - function BatchPluginFactory() { - } - /** - * Create a new BatchRenderer plugin for Renderer. this convenience can provide an easy way - * to extend BatchRenderer with all the necessary pieces. - * @example - * const fragment = ` - * varying vec2 vTextureCoord; - * varying vec4 vColor; - * varying float vTextureId; - * uniform sampler2D uSamplers[%count%]; - * - * void main(void){ - * vec4 color; - * %forloop% - * gl_FragColor = vColor * vec4(color.a - color.rgb, color.a); - * } - * `; - * const InvertBatchRenderer = PIXI.BatchPluginFactory.create({ fragment }); - * PIXI.Renderer.registerPlugin('invert', InvertBatchRenderer); - * const sprite = new PIXI.Sprite(); - * sprite.pluginName = 'invert'; - * - * @static - * @param {object} [options] - * @param {string} [options.vertex=PIXI.BatchPluginFactory.defaultVertexSrc] - Vertex shader source - * @param {string} [options.fragment=PIXI.BatchPluginFactory.defaultFragmentTemplate] - Fragment shader template - * @param {number} [options.vertexSize=6] - Vertex size - * @param {object} [options.geometryClass=PIXI.BatchGeometry] - * @return {*} New batch renderer plugin - */ - BatchPluginFactory.create = function (options) { - var _a = Object.assign({ - vertex: defaultVertex$2, - fragment: defaultFragment$2, - geometryClass: BatchGeometry, - vertexSize: 6, - }, options), vertex = _a.vertex, fragment = _a.fragment, vertexSize = _a.vertexSize, geometryClass = _a.geometryClass; - return /** @class */ (function (_super) { - __extends$2(BatchPlugin, _super); - function BatchPlugin(renderer) { - var _this = _super.call(this, renderer) || this; - _this.shaderGenerator = new BatchShaderGenerator(vertex, fragment); - _this.geometryClass = geometryClass; - _this.vertexSize = vertexSize; - return _this; - } - return BatchPlugin; - }(AbstractBatchRenderer)); - }; - Object.defineProperty(BatchPluginFactory, "defaultVertexSrc", { - /** - * The default vertex shader source - * - * @static - * @type {string} - * @constant - */ - get: function () { - return defaultVertex$2; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BatchPluginFactory, "defaultFragmentTemplate", { - /** - * The default fragment shader source - * - * @static - * @type {string} - * @constant - */ - get: function () { - return defaultFragment$2; - }, - enumerable: false, - configurable: true - }); - return BatchPluginFactory; - }()); - // Setup the default BatchRenderer plugin, this is what - // we'll actually export at the root level - var BatchRenderer = BatchPluginFactory.create(); - - /*! - * @pixi/app - v5.3.3 - * Compiled Tue, 04 Aug 2020 16:23:09 UTC - * - * @pixi/app is licensed under the MIT License. - * http://www.opensource.org/licenses/mit-license - */ - - /** - * Convenience class to create a new PIXI application. - * - * This class automatically creates the renderer, ticker and root container. - * - * @example - * // Create the application - * const app = new PIXI.Application(); - * - * // Add the view to the DOM - * document.body.appendChild(app.view); - * - * // ex, add display objects - * app.stage.addChild(PIXI.Sprite.from('something.png')); - * - * @class - * @memberof PIXI - */ - var Application = /** @class */ (function () { - /** - * @param {object} [options] - The optional renderer parameters. - * @param {boolean} [options.autoStart=true] - Automatically starts the rendering after the construction. - * **Note**: Setting this parameter to false does NOT stop the shared ticker even if you set - * options.sharedTicker to true in case that it is already started. Stop it by your own. - * @param {number} [options.width=800] - The width of the renderers view. - * @param {number} [options.height=600] - The height of the renderers view. - * @param {HTMLCanvasElement} [options.view] - The canvas to use as a view, optional. - * @param {boolean} [options.transparent=false] - If the render view is transparent. - * @param {boolean} [options.autoDensity=false] - Resizes renderer view in CSS pixels to allow for - * resolutions other than 1. - * @param {boolean} [options.antialias=false] - Sets antialias - * @param {boolean} [options.preserveDrawingBuffer=false] - Enables drawing buffer preservation, enable this if you - * need to call toDataUrl on the WebGL context. - * @param {number} [options.resolution=1] - The resolution / device pixel ratio of the renderer, retina would be 2. - * @param {boolean} [options.forceCanvas=false] - prevents selection of WebGL renderer, even if such is present, this - * option only is available when using **pixi.js-legacy** or **@pixi/canvas-renderer** modules, otherwise - * it is ignored. - * @param {number} [options.backgroundColor=0x000000] - The background color of the rendered area - * (shown if not transparent). - * @param {boolean} [options.clearBeforeRender=true] - This sets if the renderer will clear the canvas or - * not before the new render pass. - * @param {string} [options.powerPreference] - Parameter passed to webgl context, set to "high-performance" - * for devices with dual graphics card. **(WebGL only)**. - * @param {boolean} [options.sharedTicker=false] - `true` to use PIXI.Ticker.shared, `false` to create new ticker. - * If set to false, you cannot register a handler to occur before anything that runs on the shared ticker. - * The system ticker will always run before both the shared ticker and the app ticker. - * @param {boolean} [options.sharedLoader=false] - `true` to use PIXI.Loader.shared, `false` to create new Loader. - * @param {Window|HTMLElement} [options.resizeTo] - Element to automatically resize stage to. - */ - function Application(options) { - var _this = this; - // The default options - options = Object.assign({ - forceCanvas: false, - }, options); - /** - * WebGL renderer if available, otherwise CanvasRenderer. - * @member {PIXI.Renderer|PIXI.CanvasRenderer} - */ - this.renderer = autoDetectRenderer(options); - /** - * The root display container that's rendered. - * @member {PIXI.Container} - */ - this.stage = new Container(); - // install plugins here - Application._plugins.forEach(function (plugin) { - plugin.init.call(_this, options); - }); - } - /** - * Register a middleware plugin for the application - * @static - * @param {PIXI.Application.Plugin} plugin - Plugin being installed - */ - Application.registerPlugin = function (plugin) { - Application._plugins.push(plugin); - }; - /** - * Render the current stage. - */ - Application.prototype.render = function () { - // TODO: Since CanvasRenderer has not been converted this function thinks it takes DisplayObject & PIXI.DisplayObject - // This can be fixed when CanvasRenderer is converted. - this.renderer.render(this.stage); - }; - Object.defineProperty(Application.prototype, "view", { - /** - * Reference to the renderer's canvas element. - * @member {HTMLCanvasElement} - * @readonly - */ - get: function () { - return this.renderer.view; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(Application.prototype, "screen", { - /** - * Reference to the renderer's screen rectangle. Its safe to use as `filterArea` or `hitArea` for the whole screen. - * @member {PIXI.Rectangle} - * @readonly - */ - get: function () { - return this.renderer.screen; - }, - enumerable: false, - configurable: true - }); - /** - * Destroy and don't use after this. - * @param {Boolean} [removeView=false] - Automatically remove canvas from DOM. - * @param {object|boolean} [stageOptions] - Options parameter. A boolean will act as if all options - * have been set to that value - * @param {boolean} [stageOptions.children=false] - if set to true, all the children will have their destroy - * method called as well. 'stageOptions' will be passed on to those calls. - * @param {boolean} [stageOptions.texture=false] - Only used for child Sprites if stageOptions.children is set - * to true. Should it destroy the texture of the child sprite - * @param {boolean} [stageOptions.baseTexture=false] - Only used for child Sprites if stageOptions.children is set - * to true. Should it destroy the base texture of the child sprite - */ - Application.prototype.destroy = function (removeView, stageOptions) { - var _this = this; - // Destroy plugins in the opposite order - // which they were constructed - var plugins = Application._plugins.slice(0); - plugins.reverse(); - plugins.forEach(function (plugin) { - plugin.destroy.call(_this); - }); - this.stage.destroy(stageOptions); - this.stage = null; - this.renderer.destroy(removeView); - this.renderer = null; - }; - return Application; - }()); - /** - * @memberof PIXI.Application - * @typedef {object} Plugin - * @property {function} init - Called when Application is constructed, scoped to Application instance. - * Passes in `options` as the only argument, which are Application constructor options. - * @property {function} destroy - Called when destroying Application, scoped to Application instance - */ - /** - * Collection of installed plugins. - * @static - * @private - * @type {PIXI.Application.Plugin[]} - */ - Application._plugins = []; - - /** - * Middleware for for Application's resize functionality - * @private - * @class - */ - var ResizePlugin = /** @class */ (function () { - function ResizePlugin() { - } - /** - * Initialize the plugin with scope of application instance - * @static - * @private - * @param {object} [options] - See application options - */ - ResizePlugin.init = function (options) { - var _this = this; - /** - * The HTML element or window to automatically resize the - * renderer's view element to match width and height. - * @type {Window|HTMLElement} - * @name resizeTo - * @memberof PIXI.Application# - */ - Object.defineProperty(this, 'resizeTo', { - set: function (dom) { - window.removeEventListener('resize', this.queueResize); - this._resizeTo = dom; - if (dom) { - window.addEventListener('resize', this.queueResize); - this.resize(); - } - }, - get: function () { - return this._resizeTo; - }, - }); - /** - * Resize is throttled, so it's - * safe to call this multiple times per frame and it'll - * only be called once. - * @method PIXI.Application#queueResize - */ - this.queueResize = function () { - if (!_this._resizeTo) { - return; - } - _this.cancelResize(); - // // Throttle resize events per raf - _this._resizeId = requestAnimationFrame(function () { return _this.resize(); }); - }; - /** - * Cancel the resize queue. - * @method PIXI.Application#cancelResize - * @private - */ - this.cancelResize = function () { - if (_this._resizeId) { - cancelAnimationFrame(_this._resizeId); - _this._resizeId = null; - } - }; - /** - * Execute an immediate resize on the renderer, this is not - * throttled and can be expensive to call many times in a row. - * Will resize only if `resizeTo` property is set. - * @method PIXI.Application#resize - */ - this.resize = function () { - if (!_this._resizeTo) { - return; - } - // clear queue resize - _this.cancelResize(); - var width; - var height; - // Resize to the window - if (_this._resizeTo === window) { - width = window.innerWidth; - height = window.innerHeight; - } - // Resize to other HTML entities - else { - var _a = _this._resizeTo, clientWidth = _a.clientWidth, clientHeight = _a.clientHeight; - width = clientWidth; - height = clientHeight; - } - _this.renderer.resize(width, height); - }; - // On resize - this._resizeId = null; - this._resizeTo = null; - this.resizeTo = options.resizeTo || null; - }; - /** - * Clean up the ticker, scoped to application - * @static - * @private - */ - ResizePlugin.destroy = function () { - this.cancelResize(); - this.cancelResize = null; - this.queueResize = null; - this.resizeTo = null; - this.resize = null; - }; - return ResizePlugin; - }()); - - Application.registerPlugin(ResizePlugin); - - /*! - * @pixi/extract - v5.3.3 - * Compiled Tue, 04 Aug 2020 16:23:09 UTC - * - * @pixi/extract is licensed under the MIT License. - * http://www.opensource.org/licenses/mit-license - */ - - var TEMP_RECT = new Rectangle(); - var BYTES_PER_PIXEL = 4; - /** - * This class provides renderer-specific plugins for exporting content from a renderer. - * For instance, these plugins can be used for saving an Image, Canvas element or for exporting the raw image data (pixels). - * - * Do not instantiate these plugins directly. It is available from the `renderer.plugins` property. - * See {@link PIXI.CanvasRenderer#plugins} or {@link PIXI.Renderer#plugins}. - * @example - * // Create a new app (will auto-add extract plugin to renderer) - * const app = new PIXI.Application(); - * - * // Draw a red circle - * const graphics = new PIXI.Graphics() - * .beginFill(0xFF0000) - * .drawCircle(0, 0, 50); - * - * // Render the graphics as an HTMLImageElement - * const image = app.renderer.plugins.extract.image(graphics); - * document.body.appendChild(image); - * @class - * @memberof PIXI - */ - var Extract = /** @class */ (function () { - /** - * @param {PIXI.Renderer} renderer - A reference to the current renderer - */ - function Extract(renderer) { - this.renderer = renderer; - /** - * Collection of methods for extracting data (image, pixels, etc.) from a display object or render texture - * - * @member {PIXI.Extract} extract - * @memberof PIXI.Renderer# - * @see PIXI.Extract - */ - renderer.extract = this; - } - /** - * Will return a HTML Image of the target - * - * @param {PIXI.DisplayObject|PIXI.RenderTexture} target - A displayObject or renderTexture - * to convert. If left empty will use the main renderer - * @param {string} [format] - Image format, e.g. "image/jpeg" or "image/webp". - * @param {number} [quality] - JPEG or Webp compression from 0 to 1. Default is 0.92. - * @return {HTMLImageElement} HTML Image of the target - */ - Extract.prototype.image = function (target, format, quality) { - var image = new Image(); - image.src = this.base64(target, format, quality); - return image; - }; - /** - * Will return a a base64 encoded string of this target. It works by calling - * `Extract.getCanvas` and then running toDataURL on that. - * - * @param {PIXI.DisplayObject|PIXI.RenderTexture} target - A displayObject or renderTexture - * to convert. If left empty will use the main renderer - * @param {string} [format] - Image format, e.g. "image/jpeg" or "image/webp". - * @param {number} [quality] - JPEG or Webp compression from 0 to 1. Default is 0.92. - * @return {string} A base64 encoded string of the texture. - */ - Extract.prototype.base64 = function (target, format, quality) { - return this.canvas(target).toDataURL(format, quality); - }; - /** - * Creates a Canvas element, renders this target to it and then returns it. - * - * @param {PIXI.DisplayObject|PIXI.RenderTexture} target - A displayObject or renderTexture - * to convert. If left empty will use the main renderer - * @return {HTMLCanvasElement} A Canvas element with the texture rendered on. - */ - Extract.prototype.canvas = function (target) { - var renderer = this.renderer; - var resolution; - var frame; - var flipY = false; - var renderTexture; - var generated = false; - if (target) { - if (target instanceof RenderTexture) { - renderTexture = target; - } - else { - renderTexture = this.renderer.generateTexture(target); - generated = true; - } - } - if (renderTexture) { - resolution = renderTexture.baseTexture.resolution; - frame = renderTexture.frame; - flipY = false; - renderer.renderTexture.bind(renderTexture); - } - else { - resolution = this.renderer.resolution; - flipY = true; - frame = TEMP_RECT; - frame.width = this.renderer.width; - frame.height = this.renderer.height; - renderer.renderTexture.bind(null); - } - var width = Math.floor((frame.width * resolution) + 1e-4); - var height = Math.floor((frame.height * resolution) + 1e-4); - var canvasBuffer = new CanvasRenderTarget(width, height, 1); - var webglPixels = new Uint8Array(BYTES_PER_PIXEL * width * height); - // read pixels to the array - var gl = renderer.gl; - gl.readPixels(frame.x * resolution, frame.y * resolution, width, height, gl.RGBA, gl.UNSIGNED_BYTE, webglPixels); - // add the pixels to the canvas - var canvasData = canvasBuffer.context.getImageData(0, 0, width, height); - Extract.arrayPostDivide(webglPixels, canvasData.data); - canvasBuffer.context.putImageData(canvasData, 0, 0); - // pulling pixels - if (flipY) { - var target_1 = new CanvasRenderTarget(canvasBuffer.width, canvasBuffer.height, 1); - target_1.context.scale(1, -1); - // we can't render to itself because we should be empty before render. - target_1.context.drawImage(canvasBuffer.canvas, 0, -height); - canvasBuffer.destroy(); - canvasBuffer = target_1; - } - if (generated) { - renderTexture.destroy(true); - } - // send the canvas back.. - return canvasBuffer.canvas; - }; - /** - * Will return a one-dimensional array containing the pixel data of the entire texture in RGBA - * order, with integer values between 0 and 255 (included). - * - * @param {PIXI.DisplayObject|PIXI.RenderTexture} target - A displayObject or renderTexture - * to convert. If left empty will use the main renderer - * @return {Uint8Array} One-dimensional array containing the pixel data of the entire texture - */ - Extract.prototype.pixels = function (target) { - var renderer = this.renderer; - var resolution; - var frame; - var renderTexture; - var generated = false; - if (target) { - if (target instanceof RenderTexture) { - renderTexture = target; - } - else { - renderTexture = this.renderer.generateTexture(target); - generated = true; - } - } - if (renderTexture) { - resolution = renderTexture.baseTexture.resolution; - frame = renderTexture.frame; - // bind the buffer - renderer.renderTexture.bind(renderTexture); - } - else { - resolution = renderer.resolution; - frame = TEMP_RECT; - frame.width = renderer.width; - frame.height = renderer.height; - renderer.renderTexture.bind(null); - } - var width = frame.width * resolution; - var height = frame.height * resolution; - var webglPixels = new Uint8Array(BYTES_PER_PIXEL * width * height); - // read pixels to the array - var gl = renderer.gl; - gl.readPixels(frame.x * resolution, frame.y * resolution, width, height, gl.RGBA, gl.UNSIGNED_BYTE, webglPixels); - if (generated) { - renderTexture.destroy(true); - } - Extract.arrayPostDivide(webglPixels, webglPixels); - return webglPixels; - }; - /** - * Destroys the extract - * - */ - Extract.prototype.destroy = function () { - this.renderer.extract = null; - this.renderer = null; - }; - /** - * Takes premultiplied pixel data and produces regular pixel data - * - * @private - * @param pixels {number[] | Uint8Array | Uint8ClampedArray} array of pixel data - * @param out {number[] | Uint8Array | Uint8ClampedArray} output array - */ - Extract.arrayPostDivide = function (pixels, out) { - for (var i = 0; i < pixels.length; i += 4) { - var alpha = out[i + 3] = pixels[i + 3]; - if (alpha !== 0) { - out[i] = Math.round(Math.min(pixels[i] * 255.0 / alpha, 255.0)); - out[i + 1] = Math.round(Math.min(pixels[i + 1] * 255.0 / alpha, 255.0)); - out[i + 2] = Math.round(Math.min(pixels[i + 2] * 255.0 / alpha, 255.0)); - } - else { - out[i] = pixels[i]; - out[i + 1] = pixels[i + 1]; - out[i + 2] = pixels[i + 2]; - } - } - }; - return Extract; - }()); - - 'use strict'; - - var parseUri = function parseURI (str, opts) { - opts = opts || {}; - - var o = { - key: ['source', 'protocol', 'authority', 'userInfo', 'user', 'password', 'host', 'port', 'relative', 'path', 'directory', 'file', 'query', 'anchor'], - q: { - name: 'queryKey', - parser: /(?:^|&)([^&=]*)=?([^&]*)/g - }, - parser: { - strict: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/, - loose: /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/ - } - }; - - var m = o.parser[opts.strictMode ? 'strict' : 'loose'].exec(str); - var uri = {}; - var i = 14; - - while (i--) { uri[o.key[i]] = m[i] || ''; } - - uri[o.q.name] = {}; - uri[o.key[12]].replace(o.q.parser, function ($0, $1, $2) { - if ($1) { uri[o.q.name][$1] = $2; } - }); - - return uri - }; - - var miniSignals = createCommonjsModule(function (module, exports) { - 'use strict'; - - Object.defineProperty(exports, '__esModule', { - value: true - }); - - var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) { descriptor.writable = true; } Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) { defineProperties(Constructor.prototype, protoProps); } if (staticProps) { defineProperties(Constructor, staticProps); } return Constructor; }; })(); - - function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } - - var MiniSignalBinding = (function () { - function MiniSignalBinding(fn, once, thisArg) { - if (once === undefined) { once = false; } - - _classCallCheck(this, MiniSignalBinding); - - this._fn = fn; - this._once = once; - this._thisArg = thisArg; - this._next = this._prev = this._owner = null; - } - - _createClass(MiniSignalBinding, [{ - key: 'detach', - value: function detach() { - if (this._owner === null) { return false; } - this._owner.detach(this); - return true; - } - }]); - - return MiniSignalBinding; - })(); - - function _addMiniSignalBinding(self, node) { - if (!self._head) { - self._head = node; - self._tail = node; - } else { - self._tail._next = node; - node._prev = self._tail; - self._tail = node; - } - - node._owner = self; - - return node; - } - - var MiniSignal = (function () { - function MiniSignal() { - _classCallCheck(this, MiniSignal); - - this._head = this._tail = undefined; - } - - _createClass(MiniSignal, [{ - key: 'handlers', - value: function handlers() { - var exists = arguments.length <= 0 || arguments[0] === undefined ? false : arguments[0]; - - var node = this._head; - - if (exists) { return !!node; } - - var ee = []; - - while (node) { - ee.push(node); - node = node._next; - } - - return ee; - } - }, { - key: 'has', - value: function has(node) { - if (!(node instanceof MiniSignalBinding)) { - throw new Error('MiniSignal#has(): First arg must be a MiniSignalBinding object.'); - } - - return node._owner === this; - } - }, { - key: 'dispatch', - value: function dispatch() { - var arguments$1 = arguments; - - var node = this._head; - - if (!node) { return false; } - - while (node) { - if (node._once) { this.detach(node); } - node._fn.apply(node._thisArg, arguments$1); - node = node._next; - } - - return true; - } - }, { - key: 'add', - value: function add(fn) { - var thisArg = arguments.length <= 1 || arguments[1] === undefined ? null : arguments[1]; - - if (typeof fn !== 'function') { - throw new Error('MiniSignal#add(): First arg must be a Function.'); - } - return _addMiniSignalBinding(this, new MiniSignalBinding(fn, false, thisArg)); - } - }, { - key: 'once', - value: function once(fn) { - var thisArg = arguments.length <= 1 || arguments[1] === undefined ? null : arguments[1]; - - if (typeof fn !== 'function') { - throw new Error('MiniSignal#once(): First arg must be a Function.'); - } - return _addMiniSignalBinding(this, new MiniSignalBinding(fn, true, thisArg)); - } - }, { - key: 'detach', - value: function detach(node) { - if (!(node instanceof MiniSignalBinding)) { - throw new Error('MiniSignal#detach(): First arg must be a MiniSignalBinding object.'); - } - if (node._owner !== this) { return this; } - - if (node._prev) { node._prev._next = node._next; } - if (node._next) { node._next._prev = node._prev; } - - if (node === this._head) { - this._head = node._next; - if (node._next === null) { - this._tail = null; - } - } else if (node === this._tail) { - this._tail = node._prev; - this._tail._next = null; - } - - node._owner = null; - return this; - } - }, { - key: 'detachAll', - value: function detachAll() { - var node = this._head; - if (!node) { return this; } - - this._head = this._tail = null; - - while (node) { - node._owner = null; - node = node._next; - } - return this; - } - }]); - - return MiniSignal; - })(); - - MiniSignal.MiniSignalBinding = MiniSignalBinding; - - exports['default'] = MiniSignal; - module.exports = exports['default']; - }); - - var Signal = unwrapExports(miniSignals); - - /*! - * resource-loader - v3.0.1 - * https://github.com/pixijs/pixi-sound - * Compiled Tue, 02 Jul 2019 14:06:18 UTC - * - * resource-loader is licensed under the MIT license. - * http://www.opensource.org/licenses/mit-license - */ - - /** - * Smaller version of the async library constructs. - * - * @namespace async - */ - - /** - * Noop function - * - * @ignore - * @function - * @memberof async - */ - function _noop() {} - /* empty */ - - /** - * Iterates an array in series. - * - * @memberof async - * @function eachSeries - * @param {Array.<*>} array - Array to iterate. - * @param {function} iterator - Function to call for each element. - * @param {function} callback - Function to call when done, or on error. - * @param {boolean} [deferNext=false] - Break synchronous each loop by calling next with a setTimeout of 1. - */ - - - function eachSeries(array, iterator, callback, deferNext) { - var i = 0; - var len = array.length; - - (function next(err) { - if (err || i === len) { - if (callback) { - callback(err); - } - - return; - } - - if (deferNext) { - setTimeout(function () { - iterator(array[i++], next); - }, 1); - } else { - iterator(array[i++], next); - } - })(); - } - /** - * Ensures a function is only called once. - * - * @ignore - * @memberof async - * @param {function} fn - The function to wrap. - * @return {function} The wrapping function. - */ - - function onlyOnce(fn) { - return function onceWrapper() { - if (fn === null) { - throw new Error('Callback was already called.'); - } - - var callFn = fn; - fn = null; - callFn.apply(this, arguments); - }; - } - /** - * Async queue implementation, - * - * @memberof async - * @function queue - * @param {function} worker - The worker function to call for each task. - * @param {number} concurrency - How many workers to run in parrallel. - * @return {*} The async queue object. - */ - - - function queue(worker, concurrency) { - if (concurrency == null) { - // eslint-disable-line no-eq-null,eqeqeq - concurrency = 1; - } else if (concurrency === 0) { - throw new Error('Concurrency must not be zero'); - } - - var workers = 0; - var q = { - _tasks: [], - concurrency: concurrency, - saturated: _noop, - unsaturated: _noop, - buffer: concurrency / 4, - empty: _noop, - drain: _noop, - error: _noop, - started: false, - paused: false, - push: function push(data, callback) { - _insert(data, false, callback); - }, - kill: function kill() { - workers = 0; - q.drain = _noop; - q.started = false; - q._tasks = []; - }, - unshift: function unshift(data, callback) { - _insert(data, true, callback); - }, - process: function process() { - while (!q.paused && workers < q.concurrency && q._tasks.length) { - var task = q._tasks.shift(); - - if (q._tasks.length === 0) { - q.empty(); - } - - workers += 1; - - if (workers === q.concurrency) { - q.saturated(); - } - - worker(task.data, onlyOnce(_next(task))); - } - }, - length: function length() { - return q._tasks.length; - }, - running: function running() { - return workers; - }, - idle: function idle() { - return q._tasks.length + workers === 0; - }, - pause: function pause() { - if (q.paused === true) { - return; - } - - q.paused = true; - }, - resume: function resume() { - if (q.paused === false) { - return; - } - - q.paused = false; // Need to call q.process once per concurrent - // worker to preserve full concurrency after pause - - for (var w = 1; w <= q.concurrency; w++) { - q.process(); - } - } - }; - - function _insert(data, insertAtFront, callback) { - if (callback != null && typeof callback !== 'function') { - // eslint-disable-line no-eq-null,eqeqeq - throw new Error('task callback must be a function'); - } - - q.started = true; - - if (data == null && q.idle()) { - // eslint-disable-line no-eq-null,eqeqeq - // call drain immediately if there are no tasks - setTimeout(function () { - return q.drain(); - }, 1); - return; - } - - var item = { - data: data, - callback: typeof callback === 'function' ? callback : _noop - }; - - if (insertAtFront) { - q._tasks.unshift(item); - } else { - q._tasks.push(item); - } - - setTimeout(function () { - return q.process(); - }, 1); - } - - function _next(task) { - return function next() { - workers -= 1; - task.callback.apply(task, arguments); - - if (arguments[0] != null) { - // eslint-disable-line no-eq-null,eqeqeq - q.error(arguments[0], task.data); - } - - if (workers <= q.concurrency - q.buffer) { - q.unsaturated(); - } - - if (q.idle()) { - q.drain(); - } - - q.process(); - }; - } - - return q; - } - - var async = ({ - eachSeries: eachSeries, - queue: queue - }); - - // a simple in-memory cache for resources - var cache = {}; - /** - * A simple in-memory cache for resource. - * - * @memberof middleware - * @function caching - * @example - * import { Loader, middleware } from 'resource-loader'; - * const loader = new Loader(); - * loader.use(middleware.caching); - * @param {Resource} resource - Current Resource - * @param {function} next - Callback when complete - */ - - function caching(resource, next) { - var _this = this; - - // if cached, then set data and complete the resource - if (cache[resource.url]) { - resource.data = cache[resource.url]; - resource.complete(); // marks resource load complete and stops processing before middlewares - } // if not cached, wait for complete and store it in the cache. - else { - resource.onComplete.once(function () { - return cache[_this.url] = _this.data; - }); - } - - next(); - } - - function _defineProperties(target, props) { - for (var i = 0; i < props.length; i++) { - var descriptor = props[i]; - descriptor.enumerable = descriptor.enumerable || false; - descriptor.configurable = true; - if ("value" in descriptor) { descriptor.writable = true; } - Object.defineProperty(target, descriptor.key, descriptor); - } - } - - function _createClass(Constructor, protoProps, staticProps) { - if (protoProps) { _defineProperties(Constructor.prototype, protoProps); } - if (staticProps) { _defineProperties(Constructor, staticProps); } - return Constructor; - } - - var useXdr = !!(window.XDomainRequest && !('withCredentials' in new XMLHttpRequest())); - var tempAnchor$1 = null; // some status constants - - var STATUS_NONE = 0; - var STATUS_OK = 200; - var STATUS_EMPTY = 204; - var STATUS_IE_BUG_EMPTY = 1223; - var STATUS_TYPE_OK = 2; // noop - - function _noop$1() {} - /* empty */ - - /** - * Manages the state and loading of a resource and all child resources. - * - * @class - */ - - - var Resource$1 = - /*#__PURE__*/ - function () { - /** - * Sets the load type to be used for a specific extension. - * - * @static - * @param {string} extname - The extension to set the type for, e.g. "png" or "fnt" - * @param {Resource.LOAD_TYPE} loadType - The load type to set it to. - */ - Resource.setExtensionLoadType = function setExtensionLoadType(extname, loadType) { - setExtMap(Resource._loadTypeMap, extname, loadType); - } - /** - * Sets the load type to be used for a specific extension. - * - * @static - * @param {string} extname - The extension to set the type for, e.g. "png" or "fnt" - * @param {Resource.XHR_RESPONSE_TYPE} xhrType - The xhr type to set it to. - */ - ; - - Resource.setExtensionXhrType = function setExtensionXhrType(extname, xhrType) { - setExtMap(Resource._xhrTypeMap, extname, xhrType); - } - /** - * @param {string} name - The name of the resource to load. - * @param {string|string[]} url - The url for this resource, for audio/video loads you can pass - * an array of sources. - * @param {object} [options] - The options for the load. - * @param {string|boolean} [options.crossOrigin] - Is this request cross-origin? Default is to - * determine automatically. - * @param {number} [options.timeout=0] - A timeout in milliseconds for the load. If the load takes - * longer than this time it is cancelled and the load is considered a failure. If this value is - * set to `0` then there is no explicit timeout. - * @param {Resource.LOAD_TYPE} [options.loadType=Resource.LOAD_TYPE.XHR] - How should this resource - * be loaded? - * @param {Resource.XHR_RESPONSE_TYPE} [options.xhrType=Resource.XHR_RESPONSE_TYPE.DEFAULT] - How - * should the data being loaded be interpreted when using XHR? - * @param {Resource.IMetadata} [options.metadata] - Extra configuration for middleware and the Resource object. - */ - ; - - function Resource(name, url, options) { - if (typeof name !== 'string' || typeof url !== 'string') { - throw new Error('Both name and url are required for constructing a resource.'); - } - - options = options || {}; - /** - * The state flags of this resource. - * - * @private - * @member {number} - */ - - this._flags = 0; // set data url flag, needs to be set early for some _determineX checks to work. - - this._setFlag(Resource.STATUS_FLAGS.DATA_URL, url.indexOf('data:') === 0); - /** - * The name of this resource. - * - * @readonly - * @member {string} - */ - - - this.name = name; - /** - * The url used to load this resource. - * - * @readonly - * @member {string} - */ - - this.url = url; - /** - * The extension used to load this resource. - * - * @readonly - * @member {string} - */ - - this.extension = this._getExtension(); - /** - * The data that was loaded by the resource. - * - * @member {any} - */ - - this.data = null; - /** - * Is this request cross-origin? If unset, determined automatically. - * - * @member {string} - */ - - this.crossOrigin = options.crossOrigin === true ? 'anonymous' : options.crossOrigin; - /** - * A timeout in milliseconds for the load. If the load takes longer than this time - * it is cancelled and the load is considered a failure. If this value is set to `0` - * then there is no explicit timeout. - * - * @member {number} - */ - - this.timeout = options.timeout || 0; - /** - * The method of loading to use for this resource. - * - * @member {Resource.LOAD_TYPE} - */ - - this.loadType = options.loadType || this._determineLoadType(); - /** - * The type used to load the resource via XHR. If unset, determined automatically. - * - * @member {string} - */ - - this.xhrType = options.xhrType; - /** - * Extra info for middleware, and controlling specifics about how the resource loads. - * - * Note that if you pass in a `loadElement`, the Resource class takes ownership of it. - * Meaning it will modify it as it sees fit. - * - * @member {Resource.IMetadata} - */ - - this.metadata = options.metadata || {}; - /** - * The error that occurred while loading (if any). - * - * @readonly - * @member {Error} - */ - - this.error = null; - /** - * The XHR object that was used to load this resource. This is only set - * when `loadType` is `Resource.LOAD_TYPE.XHR`. - * - * @readonly - * @member {XMLHttpRequest} - */ - - this.xhr = null; - /** - * The child resources this resource owns. - * - * @readonly - * @member {Resource[]} - */ - - this.children = []; - /** - * The resource type. - * - * @readonly - * @member {Resource.TYPE} - */ - - this.type = Resource.TYPE.UNKNOWN; - /** - * The progress chunk owned by this resource. - * - * @readonly - * @member {number} - */ - - this.progressChunk = 0; - /** - * The `dequeue` method that will be used a storage place for the async queue dequeue method - * used privately by the loader. - * - * @private - * @member {function} - */ - - this._dequeue = _noop$1; - /** - * Used a storage place for the on load binding used privately by the loader. - * - * @private - * @member {function} - */ - - this._onLoadBinding = null; - /** - * The timer for element loads to check if they timeout. - * - * @private - * @member {number} - */ - - this._elementTimer = 0; - /** - * The `complete` function bound to this resource's context. - * - * @private - * @member {function} - */ - - this._boundComplete = this.complete.bind(this); - /** - * The `_onError` function bound to this resource's context. - * - * @private - * @member {function} - */ - - this._boundOnError = this._onError.bind(this); - /** - * The `_onProgress` function bound to this resource's context. - * - * @private - * @member {function} - */ - - this._boundOnProgress = this._onProgress.bind(this); - /** - * The `_onTimeout` function bound to this resource's context. - * - * @private - * @member {function} - */ - - this._boundOnTimeout = this._onTimeout.bind(this); // xhr callbacks - - this._boundXhrOnError = this._xhrOnError.bind(this); - this._boundXhrOnTimeout = this._xhrOnTimeout.bind(this); - this._boundXhrOnAbort = this._xhrOnAbort.bind(this); - this._boundXhrOnLoad = this._xhrOnLoad.bind(this); - /** - * Dispatched when the resource beings to load. - * - * The callback looks like {@link Resource.OnStartSignal}. - * - * @member {Signal} - */ - - this.onStart = new Signal(); - /** - * Dispatched each time progress of this resource load updates. - * Not all resources types and loader systems can support this event - * so sometimes it may not be available. If the resource - * is being loaded on a modern browser, using XHR, and the remote server - * properly sets Content-Length headers, then this will be available. - * - * The callback looks like {@link Resource.OnProgressSignal}. - * - * @member {Signal} - */ - - this.onProgress = new Signal(); - /** - * Dispatched once this resource has loaded, if there was an error it will - * be in the `error` property. - * - * The callback looks like {@link Resource.OnCompleteSignal}. - * - * @member {Signal} - */ - - this.onComplete = new Signal(); - /** - * Dispatched after this resource has had all the *after* middleware run on it. - * - * The callback looks like {@link Resource.OnCompleteSignal}. - * - * @member {Signal} - */ - - this.onAfterMiddleware = new Signal(); - } - /** - * When the resource starts to load. - * - * @memberof Resource - * @callback OnStartSignal - * @param {Resource} resource - The resource that the event happened on. - */ - - /** - * When the resource reports loading progress. - * - * @memberof Resource - * @callback OnProgressSignal - * @param {Resource} resource - The resource that the event happened on. - * @param {number} percentage - The progress of the load in the range [0, 1]. - */ - - /** - * When the resource finishes loading. - * - * @memberof Resource - * @callback OnCompleteSignal - * @param {Resource} resource - The resource that the event happened on. - */ - - /** - * @memberof Resource - * @typedef {object} IMetadata - * @property {HTMLImageElement|HTMLAudioElement|HTMLVideoElement} [loadElement=null] - The - * element to use for loading, instead of creating one. - * @property {boolean} [skipSource=false] - Skips adding source(s) to the load element. This - * is useful if you want to pass in a `loadElement` that you already added load sources to. - * @property {string|string[]} [mimeType] - The mime type to use for the source element - * of a video/audio elment. If the urls are an array, you can pass this as an array as well - * where each index is the mime type to use for the corresponding url index. - */ - - /** - * Stores whether or not this url is a data url. - * - * @readonly - * @member {boolean} - */ - - - var _proto = Resource.prototype; - - /** - * Marks the resource as complete. - * - */ - _proto.complete = function complete() { - this._clearEvents(); - - this._finish(); - } - /** - * Aborts the loading of this resource, with an optional message. - * - * @param {string} message - The message to use for the error - */ - ; - - _proto.abort = function abort(message) { - // abort can be called multiple times, ignore subsequent calls. - if (this.error) { - return; - } // store error - - - this.error = new Error(message); // clear events before calling aborts - - this._clearEvents(); // abort the actual loading - - - if (this.xhr) { - this.xhr.abort(); - } else if (this.xdr) { - this.xdr.abort(); - } else if (this.data) { - // single source - if (this.data.src) { - this.data.src = Resource.EMPTY_GIF; - } // multi-source - else { - while (this.data.firstChild) { - this.data.removeChild(this.data.firstChild); - } - } - } // done now. - - - this._finish(); - } - /** - * Kicks off loading of this resource. This method is asynchronous. - * - * @param {Resource.OnCompleteSignal} [cb] - Optional callback to call once the resource is loaded. - */ - ; - - _proto.load = function load(cb) { - var _this = this; - - if (this.isLoading) { - return; - } - - if (this.isComplete) { - if (cb) { - setTimeout(function () { - return cb(_this); - }, 1); - } - - return; - } else if (cb) { - this.onComplete.once(cb); - } - - this._setFlag(Resource.STATUS_FLAGS.LOADING, true); - - this.onStart.dispatch(this); // if unset, determine the value - - if (this.crossOrigin === false || typeof this.crossOrigin !== 'string') { - this.crossOrigin = this._determineCrossOrigin(this.url); - } - - switch (this.loadType) { - case Resource.LOAD_TYPE.IMAGE: - this.type = Resource.TYPE.IMAGE; - - this._loadElement('image'); - - break; - - case Resource.LOAD_TYPE.AUDIO: - this.type = Resource.TYPE.AUDIO; - - this._loadSourceElement('audio'); - - break; - - case Resource.LOAD_TYPE.VIDEO: - this.type = Resource.TYPE.VIDEO; - - this._loadSourceElement('video'); - - break; - - case Resource.LOAD_TYPE.XHR: - /* falls through */ - - default: - if (useXdr && this.crossOrigin) { - this._loadXdr(); - } else { - this._loadXhr(); - } - - break; - } - } - /** - * Checks if the flag is set. - * - * @private - * @param {number} flag - The flag to check. - * @return {boolean} True if the flag is set. - */ - ; - - _proto._hasFlag = function _hasFlag(flag) { - return (this._flags & flag) !== 0; - } - /** - * (Un)Sets the flag. - * - * @private - * @param {number} flag - The flag to (un)set. - * @param {boolean} value - Whether to set or (un)set the flag. - */ - ; - - _proto._setFlag = function _setFlag(flag, value) { - this._flags = value ? this._flags | flag : this._flags & ~flag; - } - /** - * Clears all the events from the underlying loading source. - * - * @private - */ - ; - - _proto._clearEvents = function _clearEvents() { - clearTimeout(this._elementTimer); - - if (this.data && this.data.removeEventListener) { - this.data.removeEventListener('error', this._boundOnError, false); - this.data.removeEventListener('load', this._boundComplete, false); - this.data.removeEventListener('progress', this._boundOnProgress, false); - this.data.removeEventListener('canplaythrough', this._boundComplete, false); - } - - if (this.xhr) { - if (this.xhr.removeEventListener) { - this.xhr.removeEventListener('error', this._boundXhrOnError, false); - this.xhr.removeEventListener('timeout', this._boundXhrOnTimeout, false); - this.xhr.removeEventListener('abort', this._boundXhrOnAbort, false); - this.xhr.removeEventListener('progress', this._boundOnProgress, false); - this.xhr.removeEventListener('load', this._boundXhrOnLoad, false); - } else { - this.xhr.onerror = null; - this.xhr.ontimeout = null; - this.xhr.onprogress = null; - this.xhr.onload = null; - } - } - } - /** - * Finalizes the load. - * - * @private - */ - ; - - _proto._finish = function _finish() { - if (this.isComplete) { - throw new Error('Complete called again for an already completed resource.'); - } - - this._setFlag(Resource.STATUS_FLAGS.COMPLETE, true); - - this._setFlag(Resource.STATUS_FLAGS.LOADING, false); - - this.onComplete.dispatch(this); - } - /** - * Loads this resources using an element that has a single source, - * like an HTMLImageElement. - * - * @private - * @param {string} type - The type of element to use. - */ - ; - - _proto._loadElement = function _loadElement(type) { - if (this.metadata.loadElement) { - this.data = this.metadata.loadElement; - } else if (type === 'image' && typeof window.Image !== 'undefined') { - this.data = new Image(); - } else { - this.data = document.createElement(type); - } - - if (this.crossOrigin) { - this.data.crossOrigin = this.crossOrigin; - } - - if (!this.metadata.skipSource) { - this.data.src = this.url; - } - - this.data.addEventListener('error', this._boundOnError, false); - this.data.addEventListener('load', this._boundComplete, false); - this.data.addEventListener('progress', this._boundOnProgress, false); - - if (this.timeout) { - this._elementTimer = setTimeout(this._boundOnTimeout, this.timeout); - } - } - /** - * Loads this resources using an element that has multiple sources, - * like an HTMLAudioElement or HTMLVideoElement. - * - * @private - * @param {string} type - The type of element to use. - */ - ; - - _proto._loadSourceElement = function _loadSourceElement(type) { - if (this.metadata.loadElement) { - this.data = this.metadata.loadElement; - } else if (type === 'audio' && typeof window.Audio !== 'undefined') { - this.data = new Audio(); - } else { - this.data = document.createElement(type); - } - - if (this.data === null) { - this.abort("Unsupported element: " + type); - return; - } - - if (this.crossOrigin) { - this.data.crossOrigin = this.crossOrigin; - } - - if (!this.metadata.skipSource) { - // support for CocoonJS Canvas+ runtime, lacks document.createElement('source') - if (navigator.isCocoonJS) { - this.data.src = Array.isArray(this.url) ? this.url[0] : this.url; - } else if (Array.isArray(this.url)) { - var mimeTypes = this.metadata.mimeType; - - for (var i = 0; i < this.url.length; ++i) { - this.data.appendChild(this._createSource(type, this.url[i], Array.isArray(mimeTypes) ? mimeTypes[i] : mimeTypes)); - } - } else { - var _mimeTypes = this.metadata.mimeType; - this.data.appendChild(this._createSource(type, this.url, Array.isArray(_mimeTypes) ? _mimeTypes[0] : _mimeTypes)); - } - } - - this.data.addEventListener('error', this._boundOnError, false); - this.data.addEventListener('load', this._boundComplete, false); - this.data.addEventListener('progress', this._boundOnProgress, false); - this.data.addEventListener('canplaythrough', this._boundComplete, false); - this.data.load(); - - if (this.timeout) { - this._elementTimer = setTimeout(this._boundOnTimeout, this.timeout); - } - } - /** - * Loads this resources using an XMLHttpRequest. - * - * @private - */ - ; - - _proto._loadXhr = function _loadXhr() { - // if unset, determine the value - if (typeof this.xhrType !== 'string') { - this.xhrType = this._determineXhrType(); - } - - var xhr = this.xhr = new XMLHttpRequest(); // set the request type and url - - xhr.open('GET', this.url, true); - xhr.timeout = this.timeout; // load json as text and parse it ourselves. We do this because some browsers - // *cough* safari *cough* can't deal with it. - - if (this.xhrType === Resource.XHR_RESPONSE_TYPE.JSON || this.xhrType === Resource.XHR_RESPONSE_TYPE.DOCUMENT) { - xhr.responseType = Resource.XHR_RESPONSE_TYPE.TEXT; - } else { - xhr.responseType = this.xhrType; - } - - xhr.addEventListener('error', this._boundXhrOnError, false); - xhr.addEventListener('timeout', this._boundXhrOnTimeout, false); - xhr.addEventListener('abort', this._boundXhrOnAbort, false); - xhr.addEventListener('progress', this._boundOnProgress, false); - xhr.addEventListener('load', this._boundXhrOnLoad, false); - xhr.send(); - } - /** - * Loads this resources using an XDomainRequest. This is here because we need to support IE9 (gross). - * - * @private - */ - ; - - _proto._loadXdr = function _loadXdr() { - // if unset, determine the value - if (typeof this.xhrType !== 'string') { - this.xhrType = this._determineXhrType(); - } - - var xdr = this.xhr = new XDomainRequest(); // eslint-disable-line no-undef - // XDomainRequest has a few quirks. Occasionally it will abort requests - // A way to avoid this is to make sure ALL callbacks are set even if not used - // More info here: http://stackoverflow.com/questions/15786966/xdomainrequest-aborts-post-on-ie-9 - - xdr.timeout = this.timeout || 5000; // XDR needs a timeout value or it breaks in IE9 - - xdr.onerror = this._boundXhrOnError; - xdr.ontimeout = this._boundXhrOnTimeout; - xdr.onprogress = this._boundOnProgress; - xdr.onload = this._boundXhrOnLoad; - xdr.open('GET', this.url, true); // Note: The xdr.send() call is wrapped in a timeout to prevent an - // issue with the interface where some requests are lost if multiple - // XDomainRequests are being sent at the same time. - // Some info here: https://github.com/photonstorm/phaser/issues/1248 - - setTimeout(function () { - return xdr.send(); - }, 1); - } - /** - * Creates a source used in loading via an element. - * - * @private - * @param {string} type - The element type (video or audio). - * @param {string} url - The source URL to load from. - * @param {string} [mime] - The mime type of the video - * @return {HTMLSourceElement} The source element. - */ - ; - - _proto._createSource = function _createSource(type, url, mime) { - if (!mime) { - mime = type + "/" + this._getExtension(url); - } - - var source = document.createElement('source'); - source.src = url; - source.type = mime; - return source; - } - /** - * Called if a load errors out. - * - * @param {Event} event - The error event from the element that emits it. - * @private - */ - ; - - _proto._onError = function _onError(event) { - this.abort("Failed to load element using: " + event.target.nodeName); - } - /** - * Called if a load progress event fires for an element or xhr/xdr. - * - * @private - * @param {XMLHttpRequestProgressEvent|Event} event - Progress event. - */ - ; - - _proto._onProgress = function _onProgress(event) { - if (event && event.lengthComputable) { - this.onProgress.dispatch(this, event.loaded / event.total); - } - } - /** - * Called if a timeout event fires for an element. - * - * @private - */ - ; - - _proto._onTimeout = function _onTimeout() { - this.abort("Load timed out."); - } - /** - * Called if an error event fires for xhr/xdr. - * - * @private - */ - ; - - _proto._xhrOnError = function _xhrOnError() { - var xhr = this.xhr; - this.abort(reqType(xhr) + " Request failed. Status: " + xhr.status + ", text: \"" + xhr.statusText + "\""); - } - /** - * Called if an error event fires for xhr/xdr. - * - * @private - */ - ; - - _proto._xhrOnTimeout = function _xhrOnTimeout() { - var xhr = this.xhr; - this.abort(reqType(xhr) + " Request timed out."); - } - /** - * Called if an abort event fires for xhr/xdr. - * - * @private - */ - ; - - _proto._xhrOnAbort = function _xhrOnAbort() { - var xhr = this.xhr; - this.abort(reqType(xhr) + " Request was aborted by the user."); - } - /** - * Called when data successfully loads from an xhr/xdr request. - * - * @private - * @param {XMLHttpRequestLoadEvent|Event} event - Load event - */ - ; - - _proto._xhrOnLoad = function _xhrOnLoad() { - var xhr = this.xhr; - var text = ''; - var status = typeof xhr.status === 'undefined' ? STATUS_OK : xhr.status; // XDR has no `.status`, assume 200. - // responseText is accessible only if responseType is '' or 'text' and on older browsers - - if (xhr.responseType === '' || xhr.responseType === 'text' || typeof xhr.responseType === 'undefined') { - text = xhr.responseText; - } // status can be 0 when using the `file://` protocol so we also check if a response is set. - // If it has a response, we assume 200; otherwise a 0 status code with no contents is an aborted request. - - - if (status === STATUS_NONE && (text.length > 0 || xhr.responseType === Resource.XHR_RESPONSE_TYPE.BUFFER)) { - status = STATUS_OK; - } // handle IE9 bug: http://stackoverflow.com/questions/10046972/msie-returns-status-code-of-1223-for-ajax-request - else if (status === STATUS_IE_BUG_EMPTY) { - status = STATUS_EMPTY; - } - - var statusType = status / 100 | 0; - - if (statusType === STATUS_TYPE_OK) { - // if text, just return it - if (this.xhrType === Resource.XHR_RESPONSE_TYPE.TEXT) { - this.data = text; - this.type = Resource.TYPE.TEXT; - } // if json, parse into json object - else if (this.xhrType === Resource.XHR_RESPONSE_TYPE.JSON) { - try { - this.data = JSON.parse(text); - this.type = Resource.TYPE.JSON; - } catch (e) { - this.abort("Error trying to parse loaded json: " + e); - return; - } - } // if xml, parse into an xml document or div element - else if (this.xhrType === Resource.XHR_RESPONSE_TYPE.DOCUMENT) { - try { - if (window.DOMParser) { - var domparser = new DOMParser(); - this.data = domparser.parseFromString(text, 'text/xml'); - } else { - var div = document.createElement('div'); - div.innerHTML = text; - this.data = div; - } - - this.type = Resource.TYPE.XML; - } catch (e) { - this.abort("Error trying to parse loaded xml: " + e); - return; - } - } // other types just return the response - else { - this.data = xhr.response || text; - } - } else { - this.abort("[" + xhr.status + "] " + xhr.statusText + ": " + xhr.responseURL); - return; - } - - this.complete(); - } - /** - * Sets the `crossOrigin` property for this resource based on if the url - * for this resource is cross-origin. If crossOrigin was manually set, this - * function does nothing. - * - * @private - * @param {string} url - The url to test. - * @param {object} [loc=window.location] - The location object to test against. - * @return {string} The crossOrigin value to use (or empty string for none). - */ - ; - - _proto._determineCrossOrigin = function _determineCrossOrigin(url, loc) { - // data: and javascript: urls are considered same-origin - if (url.indexOf('data:') === 0) { - return ''; - } // A sandboxed iframe without the 'allow-same-origin' attribute will have a special - // origin designed not to match window.location.origin, and will always require - // crossOrigin requests regardless of whether the location matches. - - - if (window.origin !== window.location.origin) { - return 'anonymous'; - } // default is window.location - - - loc = loc || window.location; - - if (!tempAnchor$1) { - tempAnchor$1 = document.createElement('a'); - } // let the browser determine the full href for the url of this resource and then - // parse with the node url lib, we can't use the properties of the anchor element - // because they don't work in IE9 :( - - - tempAnchor$1.href = url; - url = parseUri(tempAnchor$1.href, { - strictMode: true - }); - var samePort = !url.port && loc.port === '' || url.port === loc.port; - var protocol = url.protocol ? url.protocol + ":" : ''; // if cross origin - - if (url.host !== loc.hostname || !samePort || protocol !== loc.protocol) { - return 'anonymous'; - } - - return ''; - } - /** - * Determines the responseType of an XHR request based on the extension of the - * resource being loaded. - * - * @private - * @return {Resource.XHR_RESPONSE_TYPE} The responseType to use. - */ - ; - - _proto._determineXhrType = function _determineXhrType() { - return Resource._xhrTypeMap[this.extension] || Resource.XHR_RESPONSE_TYPE.TEXT; - } - /** - * Determines the loadType of a resource based on the extension of the - * resource being loaded. - * - * @private - * @return {Resource.LOAD_TYPE} The loadType to use. - */ - ; - - _proto._determineLoadType = function _determineLoadType() { - return Resource._loadTypeMap[this.extension] || Resource.LOAD_TYPE.XHR; - } - /** - * Extracts the extension (sans '.') of the file being loaded by the resource. - * - * @private - * @return {string} The extension. - */ - ; - - _proto._getExtension = function _getExtension() { - var url = this.url; - var ext = ''; - - if (this.isDataUrl) { - var slashIndex = url.indexOf('/'); - ext = url.substring(slashIndex + 1, url.indexOf(';', slashIndex)); - } else { - var queryStart = url.indexOf('?'); - var hashStart = url.indexOf('#'); - var index = Math.min(queryStart > -1 ? queryStart : url.length, hashStart > -1 ? hashStart : url.length); - url = url.substring(0, index); - ext = url.substring(url.lastIndexOf('.') + 1); - } - - return ext.toLowerCase(); - } - /** - * Determines the mime type of an XHR request based on the responseType of - * resource being loaded. - * - * @private - * @param {Resource.XHR_RESPONSE_TYPE} type - The type to get a mime type for. - * @return {string} The mime type to use. - */ - ; - - _proto._getMimeFromXhrType = function _getMimeFromXhrType(type) { - switch (type) { - case Resource.XHR_RESPONSE_TYPE.BUFFER: - return 'application/octet-binary'; - - case Resource.XHR_RESPONSE_TYPE.BLOB: - return 'application/blob'; - - case Resource.XHR_RESPONSE_TYPE.DOCUMENT: - return 'application/xml'; - - case Resource.XHR_RESPONSE_TYPE.JSON: - return 'application/json'; - - case Resource.XHR_RESPONSE_TYPE.DEFAULT: - case Resource.XHR_RESPONSE_TYPE.TEXT: - /* falls through */ - - default: - return 'text/plain'; - } - }; - - _createClass(Resource, [{ - key: "isDataUrl", - get: function get() { - return this._hasFlag(Resource.STATUS_FLAGS.DATA_URL); - } - /** - * Describes if this resource has finished loading. Is true when the resource has completely - * loaded. - * - * @readonly - * @member {boolean} - */ - - }, { - key: "isComplete", - get: function get() { - return this._hasFlag(Resource.STATUS_FLAGS.COMPLETE); - } - /** - * Describes if this resource is currently loading. Is true when the resource starts loading, - * and is false again when complete. - * - * @readonly - * @member {boolean} - */ - - }, { - key: "isLoading", - get: function get() { - return this._hasFlag(Resource.STATUS_FLAGS.LOADING); - } - }]); - - return Resource; - }(); - /** - * The types of resources a resource could represent. - * - * @static - * @readonly - * @enum {number} - */ - - - Resource$1.STATUS_FLAGS = { - NONE: 0, - DATA_URL: 1 << 0, - COMPLETE: 1 << 1, - LOADING: 1 << 2 - }; - /** - * The types of resources a resource could represent. - * - * @static - * @readonly - * @enum {number} - */ - - Resource$1.TYPE = { - UNKNOWN: 0, - JSON: 1, - XML: 2, - IMAGE: 3, - AUDIO: 4, - VIDEO: 5, - TEXT: 6 - }; - /** - * The types of loading a resource can use. - * - * @static - * @readonly - * @enum {number} - */ - - Resource$1.LOAD_TYPE = { - /** Uses XMLHttpRequest to load the resource. */ - XHR: 1, - - /** Uses an `Image` object to load the resource. */ - IMAGE: 2, - - /** Uses an `Audio` object to load the resource. */ - AUDIO: 3, - - /** Uses a `Video` object to load the resource. */ - VIDEO: 4 - }; - /** - * The XHR ready states, used internally. - * - * @static - * @readonly - * @enum {string} - */ - - Resource$1.XHR_RESPONSE_TYPE = { - /** string */ - DEFAULT: 'text', - - /** ArrayBuffer */ - BUFFER: 'arraybuffer', - - /** Blob */ - BLOB: 'blob', - - /** Document */ - DOCUMENT: 'document', - - /** Object */ - JSON: 'json', - - /** String */ - TEXT: 'text' - }; - Resource$1._loadTypeMap = { - // images - gif: Resource$1.LOAD_TYPE.IMAGE, - png: Resource$1.LOAD_TYPE.IMAGE, - bmp: Resource$1.LOAD_TYPE.IMAGE, - jpg: Resource$1.LOAD_TYPE.IMAGE, - jpeg: Resource$1.LOAD_TYPE.IMAGE, - tif: Resource$1.LOAD_TYPE.IMAGE, - tiff: Resource$1.LOAD_TYPE.IMAGE, - webp: Resource$1.LOAD_TYPE.IMAGE, - tga: Resource$1.LOAD_TYPE.IMAGE, - svg: Resource$1.LOAD_TYPE.IMAGE, - 'svg+xml': Resource$1.LOAD_TYPE.IMAGE, - // for SVG data urls - // audio - mp3: Resource$1.LOAD_TYPE.AUDIO, - ogg: Resource$1.LOAD_TYPE.AUDIO, - wav: Resource$1.LOAD_TYPE.AUDIO, - // videos - mp4: Resource$1.LOAD_TYPE.VIDEO, - webm: Resource$1.LOAD_TYPE.VIDEO - }; - Resource$1._xhrTypeMap = { - // xml - xhtml: Resource$1.XHR_RESPONSE_TYPE.DOCUMENT, - html: Resource$1.XHR_RESPONSE_TYPE.DOCUMENT, - htm: Resource$1.XHR_RESPONSE_TYPE.DOCUMENT, - xml: Resource$1.XHR_RESPONSE_TYPE.DOCUMENT, - tmx: Resource$1.XHR_RESPONSE_TYPE.DOCUMENT, - svg: Resource$1.XHR_RESPONSE_TYPE.DOCUMENT, - // This was added to handle Tiled Tileset XML, but .tsx is also a TypeScript React Component. - // Since it is way less likely for people to be loading TypeScript files instead of Tiled files, - // this should probably be fine. - tsx: Resource$1.XHR_RESPONSE_TYPE.DOCUMENT, - // images - gif: Resource$1.XHR_RESPONSE_TYPE.BLOB, - png: Resource$1.XHR_RESPONSE_TYPE.BLOB, - bmp: Resource$1.XHR_RESPONSE_TYPE.BLOB, - jpg: Resource$1.XHR_RESPONSE_TYPE.BLOB, - jpeg: Resource$1.XHR_RESPONSE_TYPE.BLOB, - tif: Resource$1.XHR_RESPONSE_TYPE.BLOB, - tiff: Resource$1.XHR_RESPONSE_TYPE.BLOB, - webp: Resource$1.XHR_RESPONSE_TYPE.BLOB, - tga: Resource$1.XHR_RESPONSE_TYPE.BLOB, - // json - json: Resource$1.XHR_RESPONSE_TYPE.JSON, - // text - text: Resource$1.XHR_RESPONSE_TYPE.TEXT, - txt: Resource$1.XHR_RESPONSE_TYPE.TEXT, - // fonts - ttf: Resource$1.XHR_RESPONSE_TYPE.BUFFER, - otf: Resource$1.XHR_RESPONSE_TYPE.BUFFER - }; // We can't set the `src` attribute to empty string, so on abort we set it to this 1px transparent gif - - Resource$1.EMPTY_GIF = 'data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw=='; - /** - * Quick helper to set a value on one of the extension maps. Ensures there is no - * dot at the start of the extension. - * - * @ignore - * @param {object} map - The map to set on. - * @param {string} extname - The extension (or key) to set. - * @param {number} val - The value to set. - */ - - function setExtMap(map, extname, val) { - if (extname && extname.indexOf('.') === 0) { - extname = extname.substring(1); - } - - if (!extname) { - return; - } - - map[extname] = val; - } - /** - * Quick helper to get string xhr type. - * - * @ignore - * @param {XMLHttpRequest|XDomainRequest} xhr - The request to check. - * @return {string} The type. - */ - - - function reqType(xhr) { - return xhr.toString().replace('object ', ''); - } - - var _keyStr = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='; - /** - * Encodes binary into base64. - * - * @function encodeBinary - * @param {string} input The input data to encode. - * @returns {string} The encoded base64 string - */ - - function encodeBinary(input) { - var output = ''; - var inx = 0; - - while (inx < input.length) { - // Fill byte buffer array - var bytebuffer = [0, 0, 0]; - var encodedCharIndexes = [0, 0, 0, 0]; - - for (var jnx = 0; jnx < bytebuffer.length; ++jnx) { - if (inx < input.length) { - // throw away high-order byte, as documented at: - // https://developer.mozilla.org/En/Using_XMLHttpRequest#Handling_binary_data - bytebuffer[jnx] = input.charCodeAt(inx++) & 0xff; - } else { - bytebuffer[jnx] = 0; - } - } // Get each encoded character, 6 bits at a time - // index 1: first 6 bits - - - encodedCharIndexes[0] = bytebuffer[0] >> 2; // index 2: second 6 bits (2 least significant bits from input byte 1 + 4 most significant bits from byte 2) - - encodedCharIndexes[1] = (bytebuffer[0] & 0x3) << 4 | bytebuffer[1] >> 4; // index 3: third 6 bits (4 least significant bits from input byte 2 + 2 most significant bits from byte 3) - - encodedCharIndexes[2] = (bytebuffer[1] & 0x0f) << 2 | bytebuffer[2] >> 6; // index 3: forth 6 bits (6 least significant bits from input byte 3) - - encodedCharIndexes[3] = bytebuffer[2] & 0x3f; // Determine whether padding happened, and adjust accordingly - - var paddingBytes = inx - (input.length - 1); - - switch (paddingBytes) { - case 2: - // Set last 2 characters to padding char - encodedCharIndexes[3] = 64; - encodedCharIndexes[2] = 64; - break; - - case 1: - // Set last character to padding char - encodedCharIndexes[3] = 64; - break; - - default: - break; - // No padding - proceed - } // Now we will grab each appropriate character out of our keystring - // based on our index array and append it to the output string - - - for (var _jnx = 0; _jnx < encodedCharIndexes.length; ++_jnx) { - output += _keyStr.charAt(encodedCharIndexes[_jnx]); - } - } - - return output; - } - - var Url$1 = window.URL || window.webkitURL; - /** - * A middleware for transforming XHR loaded Blobs into more useful objects - * - * @memberof middleware - * @function parsing - * @example - * import { Loader, middleware } from 'resource-loader'; - * const loader = new Loader(); - * loader.use(middleware.parsing); - * @param {Resource} resource - Current Resource - * @param {function} next - Callback when complete - */ - - function parsing(resource, next) { - if (!resource.data) { - next(); - return; - } // if this was an XHR load of a blob - - - if (resource.xhr && resource.xhrType === Resource$1.XHR_RESPONSE_TYPE.BLOB) { - // if there is no blob support we probably got a binary string back - if (!window.Blob || typeof resource.data === 'string') { - var type = resource.xhr.getResponseHeader('content-type'); // this is an image, convert the binary string into a data url - - if (type && type.indexOf('image') === 0) { - resource.data = new Image(); - resource.data.src = "data:" + type + ";base64," + encodeBinary(resource.xhr.responseText); - resource.type = Resource$1.TYPE.IMAGE; // wait until the image loads and then callback - - resource.data.onload = function () { - resource.data.onload = null; - next(); - }; // next will be called on load - - - return; - } - } // if content type says this is an image, then we should transform the blob into an Image object - else if (resource.data.type.indexOf('image') === 0) { - var src = Url$1.createObjectURL(resource.data); - resource.blob = resource.data; - resource.data = new Image(); - resource.data.src = src; - resource.type = Resource$1.TYPE.IMAGE; // cleanup the no longer used blob after the image loads - // TODO: Is this correct? Will the image be invalid after revoking? - - resource.data.onload = function () { - Url$1.revokeObjectURL(src); - resource.data.onload = null; - next(); - }; // next will be called on load. - - - return; - } - } - - next(); - } - - /** - * @namespace middleware - */ - - var index$1 = ({ - caching: caching, - parsing: parsing - }); - - var MAX_PROGRESS = 100; - var rgxExtractUrlHash = /(#[\w-]+)?$/; - /** - * Manages the state and loading of multiple resources to load. - * - * @class - */ - - var Loader = - /*#__PURE__*/ - function () { - /** - * @param {string} [baseUrl=''] - The base url for all resources loaded by this loader. - * @param {number} [concurrency=10] - The number of resources to load concurrently. - */ - function Loader(baseUrl, concurrency) { - var _this = this; - - if (baseUrl === void 0) { - baseUrl = ''; - } - - if (concurrency === void 0) { - concurrency = 10; - } - - /** - * The base url for all resources loaded by this loader. - * - * @member {string} - */ - this.baseUrl = baseUrl; - /** - * The progress percent of the loader going through the queue. - * - * @member {number} - * @default 0 - */ - - this.progress = 0; - /** - * Loading state of the loader, true if it is currently loading resources. - * - * @member {boolean} - * @default false - */ - - this.loading = false; - /** - * A querystring to append to every URL added to the loader. - * - * This should be a valid query string *without* the question-mark (`?`). The loader will - * also *not* escape values for you. Make sure to escape your parameters with - * [`encodeURIComponent`](https://mdn.io/encodeURIComponent) before assigning this property. - * - * @example - * const loader = new Loader(); - * - * loader.defaultQueryString = 'user=me&password=secret'; - * - * // This will request 'image.png?user=me&password=secret' - * loader.add('image.png').load(); - * - * loader.reset(); - * - * // This will request 'image.png?v=1&user=me&password=secret' - * loader.add('iamge.png?v=1').load(); - * - * @member {string} - * @default '' - */ - - this.defaultQueryString = ''; - /** - * The middleware to run before loading each resource. - * - * @private - * @member {function[]} - */ - - this._beforeMiddleware = []; - /** - * The middleware to run after loading each resource. - * - * @private - * @member {function[]} - */ - - this._afterMiddleware = []; - /** - * The tracks the resources we are currently completing parsing for. - * - * @private - * @member {Resource[]} - */ - - this._resourcesParsing = []; - /** - * The `_loadResource` function bound with this object context. - * - * @private - * @member {function} - * @param {Resource} r - The resource to load - * @param {Function} d - The dequeue function - * @return {undefined} - */ - - this._boundLoadResource = function (r, d) { - return _this._loadResource(r, d); - }; - /** - * The resources waiting to be loaded. - * - * @private - * @member {Resource[]} - */ - - - this._queue = queue(this._boundLoadResource, concurrency); - - this._queue.pause(); - /** - * All the resources for this loader keyed by name. - * - * @member {object} - */ - - - this.resources = {}; - /** - * Dispatched once per loaded or errored resource. - * - * The callback looks like {@link Loader.OnProgressSignal}. - * - * @member {Signal} - */ - - this.onProgress = new Signal(); - /** - * Dispatched once per errored resource. - * - * The callback looks like {@link Loader.OnErrorSignal}. - * - * @member {Signal} - */ - - this.onError = new Signal(); - /** - * Dispatched once per loaded resource. - * - * The callback looks like {@link Loader.OnLoadSignal}. - * - * @member {Signal} - */ - - this.onLoad = new Signal(); - /** - * Dispatched when the loader begins to process the queue. - * - * The callback looks like {@link Loader.OnStartSignal}. - * - * @member {Signal} - */ - - this.onStart = new Signal(); - /** - * Dispatched when the queued resources all load. - * - * The callback looks like {@link Loader.OnCompleteSignal}. - * - * @member {Signal} - */ - - this.onComplete = new Signal(); // Add default before middleware - - for (var i = 0; i < Loader._defaultBeforeMiddleware.length; ++i) { - this.pre(Loader._defaultBeforeMiddleware[i]); - } // Add default after middleware - - - for (var _i = 0; _i < Loader._defaultAfterMiddleware.length; ++_i) { - this.use(Loader._defaultAfterMiddleware[_i]); - } - } - /** - * When the progress changes the loader and resource are disaptched. - * - * @memberof Loader - * @callback OnProgressSignal - * @param {Loader} loader - The loader the progress is advancing on. - * @param {Resource} resource - The resource that has completed or failed to cause the progress to advance. - */ - - /** - * When an error occurrs the loader and resource are disaptched. - * - * @memberof Loader - * @callback OnErrorSignal - * @param {Loader} loader - The loader the error happened in. - * @param {Resource} resource - The resource that caused the error. - */ - - /** - * When a load completes the loader and resource are disaptched. - * - * @memberof Loader - * @callback OnLoadSignal - * @param {Loader} loader - The loader that laoded the resource. - * @param {Resource} resource - The resource that has completed loading. - */ - - /** - * When the loader starts loading resources it dispatches this callback. - * - * @memberof Loader - * @callback OnStartSignal - * @param {Loader} loader - The loader that has started loading resources. - */ - - /** - * When the loader completes loading resources it dispatches this callback. - * - * @memberof Loader - * @callback OnCompleteSignal - * @param {Loader} loader - The loader that has finished loading resources. - */ - - /** - * Options for a call to `.add()`. - * - * @see Loader#add - * - * @typedef {object} IAddOptions - * @property {string} [name] - The name of the resource to load, if not passed the url is used. - * @property {string} [key] - Alias for `name`. - * @property {string} [url] - The url for this resource, relative to the baseUrl of this loader. - * @property {string|boolean} [crossOrigin] - Is this request cross-origin? Default is to - * determine automatically. - * @property {number} [timeout=0] - A timeout in milliseconds for the load. If the load takes - * longer than this time it is cancelled and the load is considered a failure. If this value is - * set to `0` then there is no explicit timeout. - * @property {Resource.LOAD_TYPE} [loadType=Resource.LOAD_TYPE.XHR] - How should this resource - * be loaded? - * @property {Resource.XHR_RESPONSE_TYPE} [xhrType=Resource.XHR_RESPONSE_TYPE.DEFAULT] - How - * should the data being loaded be interpreted when using XHR? - * @property {Resource.OnCompleteSignal} [onComplete] - Callback to add an an onComplete signal istener. - * @property {Resource.OnCompleteSignal} [callback] - Alias for `onComplete`. - * @property {Resource.IMetadata} [metadata] - Extra configuration for middleware and the Resource object. - */ - - /* eslint-disable require-jsdoc,valid-jsdoc */ - - /** - * Adds a resource (or multiple resources) to the loader queue. - * - * This function can take a wide variety of different parameters. The only thing that is always - * required the url to load. All the following will work: - * - * ```js - * loader - * // normal param syntax - * .add('key', 'http://...', function () {}) - * .add('http://...', function () {}) - * .add('http://...') - * - * // object syntax - * .add({ - * name: 'key2', - * url: 'http://...' - * }, function () {}) - * .add({ - * url: 'http://...' - * }, function () {}) - * .add({ - * name: 'key3', - * url: 'http://...' - * onComplete: function () {} - * }) - * .add({ - * url: 'https://...', - * onComplete: function () {}, - * crossOrigin: true - * }) - * - * // you can also pass an array of objects or urls or both - * .add([ - * { name: 'key4', url: 'http://...', onComplete: function () {} }, - * { url: 'http://...', onComplete: function () {} }, - * 'http://...' - * ]) - * - * // and you can use both params and options - * .add('key', 'http://...', { crossOrigin: true }, function () {}) - * .add('http://...', { crossOrigin: true }, function () {}); - * ``` - * - * @function - * @variation 1 - * @param {string} name - The name of the resource to load. - * @param {string} url - The url for this resource, relative to the baseUrl of this loader. - * @param {Resource.OnCompleteSignal} [callback] - Function to call when this specific resource completes loading. - * @return {this} Returns itself. - */ - - /** - * @function - * @variation 2 - * @param {string} name - The name of the resource to load. - * @param {string} url - The url for this resource, relative to the baseUrl of this loader. - * @param {IAddOptions} [options] - The options for the load. - * @param {Resource.OnCompleteSignal} [callback] - Function to call when this specific resource completes loading. - * @return {this} Returns itself. - */ - - /** - * @function - * @variation 3 - * @param {string} url - The url for this resource, relative to the baseUrl of this loader. - * @param {Resource.OnCompleteSignal} [callback] - Function to call when this specific resource completes loading. - * @return {this} Returns itself. - */ - - /** - * @function - * @variation 4 - * @param {string} url - The url for this resource, relative to the baseUrl of this loader. - * @param {IAddOptions} [options] - The options for the load. - * @param {Resource.OnCompleteSignal} [callback] - Function to call when this specific resource completes loading. - * @return {this} Returns itself. - */ - - /** - * @function - * @variation 5 - * @param {IAddOptions} options - The options for the load. This object must contain a `url` property. - * @param {Resource.OnCompleteSignal} [callback] - Function to call when this specific resource completes loading. - * @return {this} Returns itself. - */ - - /** - * @function - * @variation 6 - * @param {Array} resources - An array of resources to load, where each is - * either an object with the options or a string url. If you pass an object, it must contain a `url` property. - * @param {Resource.OnCompleteSignal} [callback] - Function to call when this specific resource completes loading. - * @return {this} Returns itself. - */ - - - var _proto = Loader.prototype; - - _proto.add = function add(name, url, options, cb) { - // special case of an array of objects or urls - if (Array.isArray(name)) { - for (var i = 0; i < name.length; ++i) { - this.add(name[i]); - } - - return this; - } // if an object is passed instead of params - - - if (typeof name === 'object') { - cb = url || name.callback || name.onComplete; - options = name; - url = name.url; - name = name.name || name.key || name.url; - } // case where no name is passed shift all args over by one. - - - if (typeof url !== 'string') { - cb = options; - options = url; - url = name; - } // now that we shifted make sure we have a proper url. - - - if (typeof url !== 'string') { - throw new Error('No url passed to add resource to loader.'); - } // options are optional so people might pass a function and no options - - - if (typeof options === 'function') { - cb = options; - options = null; - } // if loading already you can only add resources that have a parent. - - - if (this.loading && (!options || !options.parentResource)) { - throw new Error('Cannot add resources while the loader is running.'); - } // check if resource already exists. - - - if (this.resources[name]) { - throw new Error("Resource named \"" + name + "\" already exists."); - } // add base url if this isn't an absolute url - - - url = this._prepareUrl(url); // create the store the resource - - this.resources[name] = new Resource$1(name, url, options); - - if (typeof cb === 'function') { - this.resources[name].onAfterMiddleware.once(cb); - } // if actively loading, make sure to adjust progress chunks for that parent and its children - - - if (this.loading) { - var parent = options.parentResource; - var incompleteChildren = []; - - for (var _i2 = 0; _i2 < parent.children.length; ++_i2) { - if (!parent.children[_i2].isComplete) { - incompleteChildren.push(parent.children[_i2]); - } - } - - var fullChunk = parent.progressChunk * (incompleteChildren.length + 1); // +1 for parent - - var eachChunk = fullChunk / (incompleteChildren.length + 2); // +2 for parent & new child - - parent.children.push(this.resources[name]); - parent.progressChunk = eachChunk; - - for (var _i3 = 0; _i3 < incompleteChildren.length; ++_i3) { - incompleteChildren[_i3].progressChunk = eachChunk; - } - - this.resources[name].progressChunk = eachChunk; - } // add the resource to the queue - - - this._queue.push(this.resources[name]); - - return this; - } - /* eslint-enable require-jsdoc,valid-jsdoc */ - - /** - * Sets up a middleware function that will run *before* the - * resource is loaded. - * - * @param {function} fn - The middleware function to register. - * @return {this} Returns itself. - */ - ; - - _proto.pre = function pre(fn) { - this._beforeMiddleware.push(fn); - - return this; - } - /** - * Sets up a middleware function that will run *after* the - * resource is loaded. - * - * @param {function} fn - The middleware function to register. - * @return {this} Returns itself. - */ - ; - - _proto.use = function use(fn) { - this._afterMiddleware.push(fn); - - return this; - } - /** - * Resets the queue of the loader to prepare for a new load. - * - * @return {this} Returns itself. - */ - ; - - _proto.reset = function reset() { - this.progress = 0; - this.loading = false; - - this._queue.kill(); - - this._queue.pause(); // abort all resource loads - - - for (var k in this.resources) { - var res = this.resources[k]; - - if (res._onLoadBinding) { - res._onLoadBinding.detach(); - } - - if (res.isLoading) { - res.abort(); - } - } - - this.resources = {}; - return this; - } - /** - * Starts loading the queued resources. - * - * @param {function} [cb] - Optional callback that will be bound to the `complete` event. - * @return {this} Returns itself. - */ - ; - - _proto.load = function load(cb) { - // register complete callback if they pass one - if (typeof cb === 'function') { - this.onComplete.once(cb); - } // if the queue has already started we are done here - - - if (this.loading) { - return this; - } - - if (this._queue.idle()) { - this._onStart(); - - this._onComplete(); - } else { - // distribute progress chunks - var numTasks = this._queue._tasks.length; - var chunk = MAX_PROGRESS / numTasks; - - for (var i = 0; i < this._queue._tasks.length; ++i) { - this._queue._tasks[i].data.progressChunk = chunk; - } // notify we are starting - - - this._onStart(); // start loading - - - this._queue.resume(); - } - - return this; - } - /** - * The number of resources to load concurrently. - * - * @member {number} - * @default 10 - */ - ; - - /** - * Prepares a url for usage based on the configuration of this object - * - * @private - * @param {string} url - The url to prepare. - * @return {string} The prepared url. - */ - _proto._prepareUrl = function _prepareUrl(url) { - var parsedUrl = parseUri(url, { - strictMode: true - }); - var result; // absolute url, just use it as is. - - if (parsedUrl.protocol || !parsedUrl.path || url.indexOf('//') === 0) { - result = url; - } // if baseUrl doesn't end in slash and url doesn't start with slash, then add a slash inbetween - else if (this.baseUrl.length && this.baseUrl.lastIndexOf('/') !== this.baseUrl.length - 1 && url.charAt(0) !== '/') { - result = this.baseUrl + "/" + url; - } else { - result = this.baseUrl + url; - } // if we need to add a default querystring, there is a bit more work - - - if (this.defaultQueryString) { - var hash = rgxExtractUrlHash.exec(result)[0]; - result = result.substr(0, result.length - hash.length); - - if (result.indexOf('?') !== -1) { - result += "&" + this.defaultQueryString; - } else { - result += "?" + this.defaultQueryString; - } - - result += hash; - } - - return result; - } - /** - * Loads a single resource. - * - * @private - * @param {Resource} resource - The resource to load. - * @param {function} dequeue - The function to call when we need to dequeue this item. - */ - ; - - _proto._loadResource = function _loadResource(resource, dequeue) { - var _this2 = this; - - resource._dequeue = dequeue; // run before middleware - - eachSeries(this._beforeMiddleware, function (fn, next) { - fn.call(_this2, resource, function () { - // if the before middleware marks the resource as complete, - // break and don't process any more before middleware - next(resource.isComplete ? {} : null); - }); - }, function () { - if (resource.isComplete) { - _this2._onLoad(resource); - } else { - resource._onLoadBinding = resource.onComplete.once(_this2._onLoad, _this2); - resource.load(); - } - }, true); - } - /** - * Called once loading has started. - * - * @private - */ - ; - - _proto._onStart = function _onStart() { - this.progress = 0; - this.loading = true; - this.onStart.dispatch(this); - } - /** - * Called once each resource has loaded. - * - * @private - */ - ; - - _proto._onComplete = function _onComplete() { - this.progress = MAX_PROGRESS; - this.loading = false; - this.onComplete.dispatch(this, this.resources); - } - /** - * Called each time a resources is loaded. - * - * @private - * @param {Resource} resource - The resource that was loaded - */ - ; - - _proto._onLoad = function _onLoad(resource) { - var _this3 = this; - - resource._onLoadBinding = null; // remove this resource from the async queue, and add it to our list of resources that are being parsed - - this._resourcesParsing.push(resource); - - resource._dequeue(); // run all the after middleware for this resource - - - eachSeries(this._afterMiddleware, function (fn, next) { - fn.call(_this3, resource, next); - }, function () { - resource.onAfterMiddleware.dispatch(resource); - _this3.progress = Math.min(MAX_PROGRESS, _this3.progress + resource.progressChunk); - - _this3.onProgress.dispatch(_this3, resource); - - if (resource.error) { - _this3.onError.dispatch(resource.error, _this3, resource); - } else { - _this3.onLoad.dispatch(_this3, resource); - } - - _this3._resourcesParsing.splice(_this3._resourcesParsing.indexOf(resource), 1); // do completion check - - - if (_this3._queue.idle() && _this3._resourcesParsing.length === 0) { - _this3._onComplete(); - } - }, true); - }; - - _createClass(Loader, [{ - key: "concurrency", - get: function get() { - return this._queue.concurrency; - } // eslint-disable-next-line require-jsdoc - , - set: function set(concurrency) { - this._queue.concurrency = concurrency; - } - }]); - - return Loader; - }(); - /** - * A default array of middleware to run before loading each resource. - * Each of these middlewares are added to any new Loader instances when they are created. - * - * @private - * @member {function[]} - */ - - - Loader._defaultBeforeMiddleware = []; - /** - * A default array of middleware to run after loading each resource. - * Each of these middlewares are added to any new Loader instances when they are created. - * - * @private - * @member {function[]} - */ - - Loader._defaultAfterMiddleware = []; - /** - * Sets up a middleware function that will run *before* the - * resource is loaded. - * - * @static - * @param {function} fn - The middleware function to register. - * @return {Loader} Returns itself. - */ - - Loader.pre = function LoaderPreStatic(fn) { - Loader._defaultBeforeMiddleware.push(fn); - - return Loader; - }; - /** - * Sets up a middleware function that will run *after* the - * resource is loaded. - * - * @static - * @param {function} fn - The middleware function to register. - * @return {Loader} Returns itself. - */ - - - Loader.use = function LoaderUseStatic(fn) { - Loader._defaultAfterMiddleware.push(fn); - - return Loader; - }; - - /*! - * @pixi/loaders - v5.3.3 - * Compiled Tue, 04 Aug 2020 16:23:09 UTC - * - * @pixi/loaders is licensed under the MIT License. - * http://www.opensource.org/licenses/mit-license - */ - - /** - * Reference to **{@link https://github.com/englercj/resource-loader - * resource-loader}**'s Resource class. - * @see http://englercj.github.io/resource-loader/Resource.html - * @class LoaderResource - * @memberof PIXI - */ - var LoaderResource = Resource$1; - - /*! ***************************************************************************** - Copyright (c) Microsoft Corporation. All rights reserved. - Licensed under the Apache License, Version 2.0 (the "License"); you may not use - this file except in compliance with the License. You may obtain a copy of the - License at http://www.apache.org/licenses/LICENSE-2.0 - - THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED - WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, - MERCHANTABLITY OR NON-INFRINGEMENT. - - See the Apache Version 2.0 License for specific language governing permissions - and limitations under the License. - ***************************************************************************** */ - /* global Reflect, Promise */ - - var extendStatics$3 = function(d, b) { - extendStatics$3 = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) { if (b.hasOwnProperty(p)) { d[p] = b[p]; } } }; - return extendStatics$3(d, b); - }; - - function __extends$3(d, b) { - extendStatics$3(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - } - - /** - * Loader plugin for handling Texture resources. - * @class - * @memberof PIXI - * @implements PIXI.ILoaderPlugin - */ - var TextureLoader = /** @class */ (function () { - function TextureLoader() { - } - /** - * Called after a resource is loaded. - * @see PIXI.Loader.loaderMiddleware - * @param {PIXI.LoaderResource} resource - * @param {function} next - */ - TextureLoader.use = function (resource, next) { - // create a new texture if the data is an Image object - if (resource.data && resource.type === Resource$1.TYPE.IMAGE) { - resource.texture = Texture.fromLoader(resource.data, resource.url, resource.name); - } - next(); - }; - return TextureLoader; - }()); - - /** - * The new loader, extends Resource Loader by Chad Engler: https://github.com/englercj/resource-loader - * - * ```js - * const loader = PIXI.Loader.shared; // PixiJS exposes a premade instance for you to use. - * //or - * const loader = new PIXI.Loader(); // you can also create your own if you want - * - * const sprites = {}; - * - * // Chainable `add` to enqueue a resource - * loader.add('bunny', 'data/bunny.png') - * .add('spaceship', 'assets/spritesheet.json'); - * loader.add('scoreFont', 'assets/score.fnt'); - * - * // Chainable `pre` to add a middleware that runs for each resource, *before* loading that resource. - * // This is useful to implement custom caching modules (using filesystem, indexeddb, memory, etc). - * loader.pre(cachingMiddleware); - * - * // Chainable `use` to add a middleware that runs for each resource, *after* loading that resource. - * // This is useful to implement custom parsing modules (like spritesheet parsers, spine parser, etc). - * loader.use(parsingMiddleware); - * - * // The `load` method loads the queue of resources, and calls the passed in callback called once all - * // resources have loaded. - * loader.load((loader, resources) => { - * // resources is an object where the key is the name of the resource loaded and the value is the resource object. - * // They have a couple default properties: - * // - `url`: The URL that the resource was loaded from - * // - `error`: The error that happened when trying to load (if any) - * // - `data`: The raw data that was loaded - * // also may contain other properties based on the middleware that runs. - * sprites.bunny = new PIXI.TilingSprite(resources.bunny.texture); - * sprites.spaceship = new PIXI.TilingSprite(resources.spaceship.texture); - * sprites.scoreFont = new PIXI.TilingSprite(resources.scoreFont.texture); - * }); - * - * // throughout the process multiple signals can be dispatched. - * loader.onProgress.add(() => {}); // called once per loaded/errored file - * loader.onError.add(() => {}); // called once per errored file - * loader.onLoad.add(() => {}); // called once per loaded file - * loader.onComplete.add(() => {}); // called once when the queued resources all load. - * ``` - * - * @see https://github.com/englercj/resource-loader - * - * @class Loader - * @memberof PIXI - * @param {string} [baseUrl=''] - The base url for all resources loaded by this loader. - * @param {number} [concurrency=10] - The number of resources to load concurrently. - */ - var Loader$1 = /** @class */ (function (_super) { - __extends$3(Loader, _super); - function Loader(baseUrl, concurrency) { - var _this = _super.call(this, baseUrl, concurrency) || this; - for (var i = 0; i < Loader._plugins.length; ++i) { - var plugin = Loader._plugins[i]; - var pre = plugin.pre, use = plugin.use; - if (pre) { - _this.pre(pre); - } - if (use) { - _this.use(use); - } - } - /** - * If this loader cannot be destroyed. - * @member {boolean} - * @default false - * @private - */ - _this._protected = false; - return _this; - } - /** - * Destroy the loader, removes references. - * @memberof PIXI.Loader# - * @method destroy - * @public - */ - Loader.prototype.destroy = function () { - if (!this._protected) { - this.reset(); - } - }; - Object.defineProperty(Loader, "shared", { - /** - * A premade instance of the loader that can be used to load resources. - * @name shared - * @type {PIXI.Loader} - * @static - * @memberof PIXI.Loader - */ - get: function () { - var shared = Loader._shared; - if (!shared) { - shared = new Loader(); - shared._protected = true; - Loader._shared = shared; - } - return shared; - }, - enumerable: false, - configurable: true - }); - /** - * Adds a Loader plugin for the global shared loader and all - * new Loader instances created. - * - * @static - * @method registerPlugin - * @memberof PIXI.Loader - * @param {PIXI.ILoaderPlugin} plugin - The plugin to add - * @return {PIXI.Loader} Reference to PIXI.Loader for chaining - */ - Loader.registerPlugin = function (plugin) { - Loader._plugins.push(plugin); - if (plugin.add) { - plugin.add(); - } - return Loader; - }; - /** - * Collection of all installed `use` middleware for Loader. - * - * @static - * @member {Array} _plugins - * @memberof PIXI.Loader - * @private - */ - Loader._plugins = []; - return Loader; - }(Loader)); - // parse any blob into more usable objects (e.g. Image) - Loader$1.registerPlugin({ use: index$1.parsing }); - // parse any Image objects into textures - Loader$1.registerPlugin(TextureLoader); - /** - * Plugin to be installed for handling specific Loader resources. - * - * @memberof PIXI - * @typedef {object} ILoaderPlugin - * @property {function} [add] - Function to call immediate after registering plugin. - * @property {PIXI.Loader.loaderMiddleware} [pre] - Middleware function to run before load, the - * arguments for this are `(resource, next)` - * @property {PIXI.Loader.loaderMiddleware} [use] - Middleware function to run after load, the - * arguments for this are `(resource, next)` - */ - /** - * @memberof PIXI.Loader - * @typedef {object} ICallbackID - */ - /** - * @memberof PIXI.Loader - * @typedef {function} ISignalCallback - * @param {function} callback - Callback function - * @param {object} [context] - Context - * @returns {ICallbackID} - CallbackID - */ - /** - * @memberof PIXI.Loader - * @typedef {function} ISignalDetach - * @param {ICallbackID} id - CallbackID returned by `add`/`once` methods - */ - /** - * @memberof PIXI.Loader - * @typedef ILoaderSignal - * @property {ISignalCallback} add - Register callback - * @property {ISignalCallback} once - Register oneshot callback - * @property {ISignalDetach} detach - Detach specific callback by ID - */ - /** - * @memberof PIXI.Loader - * @callback loaderMiddleware - * @param {PIXI.LoaderResource} resource - * @param {function} next - */ - /** - * @memberof PIXI.Loader# - * @description Dispatched when the loader begins to loading process. - * @member {PIXI.Loader.ILoaderSignal} onStart - */ - /** - * @memberof PIXI.Loader# - * @description Dispatched once per loaded or errored resource. - * @member {PIXI.Loader.ILoaderSignal} onProgress - */ - /** - * @memberof PIXI.Loader# - * @description Dispatched once per errored resource. - * @member {PIXI.Loader.ILoaderSignal} onError - */ - /** - * @memberof PIXI.Loader# - * @description Dispatched once per loaded resource. - * @member {PIXI.Loader.ILoaderSignal} onLoad - */ - /** - * @memberof PIXI.Loader# - * @description Dispatched when completely loaded all resources. - * @member {PIXI.Loader.ILoaderSignal} onComplete - */ - - /** - * Application plugin for supporting loader option. Installing the LoaderPlugin - * is not necessary if using **pixi.js** or **pixi.js-legacy**. - * @example - * import {AppLoaderPlugin} from '@pixi/loaders'; - * import {Application} from '@pixi/app'; - * Application.registerPlugin(AppLoaderPlugin); - * @class - * @memberof PIXI - */ - var AppLoaderPlugin = /** @class */ (function () { - function AppLoaderPlugin() { - } - /** - * Called on application constructor - * @param {object} options - * @private - */ - AppLoaderPlugin.init = function (options) { - options = Object.assign({ - sharedLoader: false, - }, options); - /** - * Loader instance to help with asset loading. - * @name PIXI.Application#loader - * @type {PIXI.Loader} - * @readonly - */ - this.loader = options.sharedLoader ? Loader$1.shared : new Loader$1(); - }; - /** - * Called when application destroyed - * @private - */ - AppLoaderPlugin.destroy = function () { - if (this.loader) { - this.loader.destroy(); - this.loader = null; - } - }; - return AppLoaderPlugin; - }()); - - /*! - * @pixi/particles - v5.3.3 - * Compiled Tue, 04 Aug 2020 16:23:09 UTC - * - * @pixi/particles is licensed under the MIT License. - * http://www.opensource.org/licenses/mit-license - */ - - /*! ***************************************************************************** - Copyright (c) Microsoft Corporation. All rights reserved. - Licensed under the Apache License, Version 2.0 (the "License"); you may not use - this file except in compliance with the License. You may obtain a copy of the - License at http://www.apache.org/licenses/LICENSE-2.0 - - THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED - WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, - MERCHANTABLITY OR NON-INFRINGEMENT. - - See the Apache Version 2.0 License for specific language governing permissions - and limitations under the License. - ***************************************************************************** */ - /* global Reflect, Promise */ - - var extendStatics$4 = function(d, b) { - extendStatics$4 = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) { if (b.hasOwnProperty(p)) { d[p] = b[p]; } } }; - return extendStatics$4(d, b); - }; - - function __extends$4(d, b) { - extendStatics$4(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - } - - /** - * The ParticleContainer class is a really fast version of the Container built solely for speed, - * so use when you need a lot of sprites or particles. - * - * The tradeoff of the ParticleContainer is that most advanced functionality will not work. - * ParticleContainer implements the basic object transform (position, scale, rotation) - * and some advanced functionality like tint (as of v4.5.6). - * - * Other more advanced functionality like masking, children, filters, etc will not work on sprites in this batch. - * - * It's extremely easy to use: - * ```js - * let container = new ParticleContainer(); - * - * for (let i = 0; i < 100; ++i) - * { - * let sprite = PIXI.Sprite.from("myImage.png"); - * container.addChild(sprite); - * } - * ``` - * - * And here you have a hundred sprites that will be rendered at the speed of light. - * - * @class - * @extends PIXI.Container - * @memberof PIXI - */ - var ParticleContainer = /** @class */ (function (_super) { - __extends$4(ParticleContainer, _super); - /** - * @param {number} [maxSize=1500] - The maximum number of particles that can be rendered by the container. - * Affects size of allocated buffers. - * @param {object} [properties] - The properties of children that should be uploaded to the gpu and applied. - * @param {boolean} [properties.vertices=false] - When true, vertices be uploaded and applied. - * if sprite's ` scale/anchor/trim/frame/orig` is dynamic, please set `true`. - * @param {boolean} [properties.position=true] - When true, position be uploaded and applied. - * @param {boolean} [properties.rotation=false] - When true, rotation be uploaded and applied. - * @param {boolean} [properties.uvs=false] - When true, uvs be uploaded and applied. - * @param {boolean} [properties.tint=false] - When true, alpha and tint be uploaded and applied. - * @param {number} [batchSize=16384] - Number of particles per batch. If less than maxSize, it uses maxSize instead. - * @param {boolean} [autoResize=false] - If true, container allocates more batches in case - * there are more than `maxSize` particles. - */ - function ParticleContainer(maxSize, properties, batchSize, autoResize) { - if (maxSize === void 0) { maxSize = 1500; } - if (batchSize === void 0) { batchSize = 16384; } - if (autoResize === void 0) { autoResize = false; } - var _this = _super.call(this) || this; - // Making sure the batch size is valid - // 65535 is max vertex index in the index buffer (see ParticleRenderer) - // so max number of particles is 65536 / 4 = 16384 - var maxBatchSize = 16384; - if (batchSize > maxBatchSize) { - batchSize = maxBatchSize; - } - /** - * Set properties to be dynamic (true) / static (false) - * - * @member {boolean[]} - * @private - */ - _this._properties = [false, true, false, false, false]; - /** - * @member {number} - * @private - */ - _this._maxSize = maxSize; - /** - * @member {number} - * @private - */ - _this._batchSize = batchSize; - /** - * @member {Array} - * @private - */ - _this._buffers = null; - /** - * for every batch stores _updateID corresponding to the last change in that batch - * @member {number[]} - * @private - */ - _this._bufferUpdateIDs = []; - /** - * when child inserted, removed or changes position this number goes up - * @member {number[]} - * @private - */ - _this._updateID = 0; - /** - * @member {boolean} - * - */ - _this.interactiveChildren = false; - /** - * The blend mode to be applied to the sprite. Apply a value of `PIXI.BLEND_MODES.NORMAL` - * to reset the blend mode. - * - * @member {number} - * @default PIXI.BLEND_MODES.NORMAL - * @see PIXI.BLEND_MODES - */ - _this.blendMode = exports.BLEND_MODES.NORMAL; - /** - * If true, container allocates more batches in case there are more than `maxSize` particles. - * @member {boolean} - * @default false - */ - _this.autoResize = autoResize; - /** - * If true PixiJS will Math.floor() x/y values when rendering, stopping pixel interpolation. - * Advantages can include sharper image quality (like text) and faster rendering on canvas. - * The main disadvantage is movement of objects may appear less smooth. - * Default to true here as performance is usually the priority for particles. - * - * @member {boolean} - * @default true - */ - _this.roundPixels = true; - /** - * The texture used to render the children. - * - * @readonly - * @member {PIXI.BaseTexture} - */ - _this.baseTexture = null; - _this.setProperties(properties); - /** - * The tint applied to the container. - * This is a hex value. A value of 0xFFFFFF will remove any tint effect. - * - * @private - * @member {number} - * @default 0xFFFFFF - */ - _this._tint = 0; - _this.tintRgb = new Float32Array(4); - _this.tint = 0xFFFFFF; - return _this; - } - /** - * Sets the private properties array to dynamic / static based on the passed properties object - * - * @param {object} properties - The properties to be uploaded - */ - ParticleContainer.prototype.setProperties = function (properties) { - if (properties) { - this._properties[0] = 'vertices' in properties || 'scale' in properties - ? !!properties.vertices || !!properties.scale : this._properties[0]; - this._properties[1] = 'position' in properties ? !!properties.position : this._properties[1]; - this._properties[2] = 'rotation' in properties ? !!properties.rotation : this._properties[2]; - this._properties[3] = 'uvs' in properties ? !!properties.uvs : this._properties[3]; - this._properties[4] = 'tint' in properties || 'alpha' in properties - ? !!properties.tint || !!properties.alpha : this._properties[4]; - } - }; - /** - * Updates the object transform for rendering - * - * @private - */ - ParticleContainer.prototype.updateTransform = function () { - // TODO don't need to! - this.displayObjectUpdateTransform(); - }; - Object.defineProperty(ParticleContainer.prototype, "tint", { - /** - * The tint applied to the container. This is a hex value. - * A value of 0xFFFFFF will remove any tint effect. - ** IMPORTANT: This is a WebGL only feature and will be ignored by the canvas renderer. - * @member {number} - * @default 0xFFFFFF - */ - get: function () { - return this._tint; - }, - set: function (value) { - this._tint = value; - hex2rgb(value, this.tintRgb); - }, - enumerable: false, - configurable: true - }); - /** - * Renders the container using the WebGL renderer - * - * @private - * @param {PIXI.Renderer} renderer - The webgl renderer - */ - ParticleContainer.prototype.render = function (renderer) { - var _this = this; - if (!this.visible || this.worldAlpha <= 0 || !this.children.length || !this.renderable) { - return; - } - if (!this.baseTexture) { - this.baseTexture = this.children[0]._texture.baseTexture; - if (!this.baseTexture.valid) { - this.baseTexture.once('update', function () { return _this.onChildrenChange(0); }); - } - } - renderer.batch.setObjectRenderer(renderer.plugins.particle); - renderer.plugins.particle.render(this); - }; - /** - * Set the flag that static data should be updated to true - * - * @private - * @param {number} smallestChildIndex - The smallest child index - */ - ParticleContainer.prototype.onChildrenChange = function (smallestChildIndex) { - var bufferIndex = Math.floor(smallestChildIndex / this._batchSize); - while (this._bufferUpdateIDs.length < bufferIndex) { - this._bufferUpdateIDs.push(0); - } - this._bufferUpdateIDs[bufferIndex] = ++this._updateID; - }; - ParticleContainer.prototype.dispose = function () { - if (this._buffers) { - for (var i = 0; i < this._buffers.length; ++i) { - this._buffers[i].destroy(); - } - this._buffers = null; - } - }; - /** - * Destroys the container - * - * @param {object|boolean} [options] - Options parameter. A boolean will act as if all options - * have been set to that value - * @param {boolean} [options.children=false] - if set to true, all the children will have their - * destroy method called as well. 'options' will be passed on to those calls. - * @param {boolean} [options.texture=false] - Only used for child Sprites if options.children is set to true - * Should it destroy the texture of the child sprite - * @param {boolean} [options.baseTexture=false] - Only used for child Sprites if options.children is set to true - * Should it destroy the base texture of the child sprite - */ - ParticleContainer.prototype.destroy = function (options) { - _super.prototype.destroy.call(this, options); - this.dispose(); - this._properties = null; - this._buffers = null; - this._bufferUpdateIDs = null; - }; - return ParticleContainer; - }(Container)); - - /** - * @author Mat Groves - * - * Big thanks to the very clever Matt DesLauriers https://github.com/mattdesl/ - * for creating the original PixiJS version! - * Also a thanks to https://github.com/bchevalier for tweaking the tint and alpha so that - * they now share 4 bytes on the vertex buffer - * - * Heavily inspired by LibGDX's ParticleBuffer: - * https://github.com/libgdx/libgdx/blob/master/gdx/src/com/badlogic/gdx/graphics/g2d/ParticleBuffer.java - */ - /** - * The particle buffer manages the static and dynamic buffers for a particle container. - * - * @class - * @private - * @memberof PIXI - */ - var ParticleBuffer = /** @class */ (function () { - /** - * @private - * @param {object} properties - The properties to upload. - * @param {boolean[]} dynamicPropertyFlags - Flags for which properties are dynamic. - * @param {number} size - The size of the batch. - */ - function ParticleBuffer(properties, dynamicPropertyFlags, size) { - this.geometry = new Geometry(); - this.indexBuffer = null; - /** - * The number of particles the buffer can hold - * - * @private - * @member {number} - */ - this.size = size; - /** - * A list of the properties that are dynamic. - * - * @private - * @member {object[]} - */ - this.dynamicProperties = []; - /** - * A list of the properties that are static. - * - * @private - * @member {object[]} - */ - this.staticProperties = []; - for (var i = 0; i < properties.length; ++i) { - var property = properties[i]; - // Make copy of properties object so that when we edit the offset it doesn't - // change all other instances of the object literal - property = { - attributeName: property.attributeName, - size: property.size, - uploadFunction: property.uploadFunction, - type: property.type || exports.TYPES.FLOAT, - offset: property.offset, - }; - if (dynamicPropertyFlags[i]) { - this.dynamicProperties.push(property); - } - else { - this.staticProperties.push(property); - } - } - this.staticStride = 0; - this.staticBuffer = null; - this.staticData = null; - this.staticDataUint32 = null; - this.dynamicStride = 0; - this.dynamicBuffer = null; - this.dynamicData = null; - this.dynamicDataUint32 = null; - this._updateID = 0; - this.initBuffers(); - } - /** - * Sets up the renderer context and necessary buffers. - * - * @private - */ - ParticleBuffer.prototype.initBuffers = function () { - var geometry = this.geometry; - var dynamicOffset = 0; - /** - * Holds the indices of the geometry (quads) to draw - * - * @member {Uint16Array} - * @private - */ - this.indexBuffer = new Buffer(createIndicesForQuads(this.size), true, true); - geometry.addIndex(this.indexBuffer); - this.dynamicStride = 0; - for (var i = 0; i < this.dynamicProperties.length; ++i) { - var property = this.dynamicProperties[i]; - property.offset = dynamicOffset; - dynamicOffset += property.size; - this.dynamicStride += property.size; - } - var dynBuffer = new ArrayBuffer(this.size * this.dynamicStride * 4 * 4); - this.dynamicData = new Float32Array(dynBuffer); - this.dynamicDataUint32 = new Uint32Array(dynBuffer); - this.dynamicBuffer = new Buffer(this.dynamicData, false, false); - // static // - var staticOffset = 0; - this.staticStride = 0; - for (var i = 0; i < this.staticProperties.length; ++i) { - var property = this.staticProperties[i]; - property.offset = staticOffset; - staticOffset += property.size; - this.staticStride += property.size; - } - var statBuffer = new ArrayBuffer(this.size * this.staticStride * 4 * 4); - this.staticData = new Float32Array(statBuffer); - this.staticDataUint32 = new Uint32Array(statBuffer); - this.staticBuffer = new Buffer(this.staticData, true, false); - for (var i = 0; i < this.dynamicProperties.length; ++i) { - var property = this.dynamicProperties[i]; - geometry.addAttribute(property.attributeName, this.dynamicBuffer, 0, property.type === exports.TYPES.UNSIGNED_BYTE, property.type, this.dynamicStride * 4, property.offset * 4); - } - for (var i = 0; i < this.staticProperties.length; ++i) { - var property = this.staticProperties[i]; - geometry.addAttribute(property.attributeName, this.staticBuffer, 0, property.type === exports.TYPES.UNSIGNED_BYTE, property.type, this.staticStride * 4, property.offset * 4); - } - }; - /** - * Uploads the dynamic properties. - * - * @private - * @param {PIXI.DisplayObject[]} children - The children to upload. - * @param {number} startIndex - The index to start at. - * @param {number} amount - The number to upload. - */ - ParticleBuffer.prototype.uploadDynamic = function (children, startIndex, amount) { - for (var i = 0; i < this.dynamicProperties.length; i++) { - var property = this.dynamicProperties[i]; - property.uploadFunction(children, startIndex, amount, property.type === exports.TYPES.UNSIGNED_BYTE ? this.dynamicDataUint32 : this.dynamicData, this.dynamicStride, property.offset); - } - this.dynamicBuffer._updateID++; - }; - /** - * Uploads the static properties. - * - * @private - * @param {PIXI.DisplayObject[]} children - The children to upload. - * @param {number} startIndex - The index to start at. - * @param {number} amount - The number to upload. - */ - ParticleBuffer.prototype.uploadStatic = function (children, startIndex, amount) { - for (var i = 0; i < this.staticProperties.length; i++) { - var property = this.staticProperties[i]; - property.uploadFunction(children, startIndex, amount, property.type === exports.TYPES.UNSIGNED_BYTE ? this.staticDataUint32 : this.staticData, this.staticStride, property.offset); - } - this.staticBuffer._updateID++; - }; - /** - * Destroys the ParticleBuffer. - * - * @private - */ - ParticleBuffer.prototype.destroy = function () { - this.indexBuffer = null; - this.dynamicProperties = null; - this.dynamicBuffer = null; - this.dynamicData = null; - this.dynamicDataUint32 = null; - this.staticProperties = null; - this.staticBuffer = null; - this.staticData = null; - this.staticDataUint32 = null; - // all buffers are destroyed inside geometry - this.geometry.destroy(); - }; - return ParticleBuffer; - }()); - - var fragment$1 = "varying vec2 vTextureCoord;\nvarying vec4 vColor;\n\nuniform sampler2D uSampler;\n\nvoid main(void){\n vec4 color = texture2D(uSampler, vTextureCoord) * vColor;\n gl_FragColor = color;\n}"; - - var vertex$1 = "attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\nattribute vec4 aColor;\n\nattribute vec2 aPositionCoord;\nattribute float aRotation;\n\nuniform mat3 translationMatrix;\nuniform vec4 uColor;\n\nvarying vec2 vTextureCoord;\nvarying vec4 vColor;\n\nvoid main(void){\n float x = (aVertexPosition.x) * cos(aRotation) - (aVertexPosition.y) * sin(aRotation);\n float y = (aVertexPosition.x) * sin(aRotation) + (aVertexPosition.y) * cos(aRotation);\n\n vec2 v = vec2(x, y);\n v = v + aPositionCoord;\n\n gl_Position = vec4((translationMatrix * vec3(v, 1.0)).xy, 0.0, 1.0);\n\n vTextureCoord = aTextureCoord;\n vColor = aColor * uColor;\n}\n"; - - /** - * @author Mat Groves - * - * Big thanks to the very clever Matt DesLauriers https://github.com/mattdesl/ - * for creating the original PixiJS version! - * Also a thanks to https://github.com/bchevalier for tweaking the tint and alpha so that they now - * share 4 bytes on the vertex buffer - * - * Heavily inspired by LibGDX's ParticleRenderer: - * https://github.com/libgdx/libgdx/blob/master/gdx/src/com/badlogic/gdx/graphics/g2d/ParticleRenderer.java - */ - /** - * Renderer for Particles that is designer for speed over feature set. - * - * @class - * @memberof PIXI - */ - var ParticleRenderer = /** @class */ (function (_super) { - __extends$4(ParticleRenderer, _super); - /** - * @param {PIXI.Renderer} renderer - The renderer this sprite batch works for. - */ - function ParticleRenderer(renderer) { - var _this = _super.call(this, renderer) || this; - // 65535 is max vertex index in the index buffer (see ParticleRenderer) - // so max number of particles is 65536 / 4 = 16384 - // and max number of element in the index buffer is 16384 * 6 = 98304 - // Creating a full index buffer, overhead is 98304 * 2 = 196Ko - // let numIndices = 98304; - /** - * The default shader that is used if a sprite doesn't have a more specific one. - * - * @member {PIXI.Shader} - */ - _this.shader = null; - _this.properties = null; - _this.tempMatrix = new Matrix(); - _this.properties = [ - // verticesData - { - attributeName: 'aVertexPosition', - size: 2, - uploadFunction: _this.uploadVertices, - offset: 0, - }, - // positionData - { - attributeName: 'aPositionCoord', - size: 2, - uploadFunction: _this.uploadPosition, - offset: 0, - }, - // rotationData - { - attributeName: 'aRotation', - size: 1, - uploadFunction: _this.uploadRotation, - offset: 0, - }, - // uvsData - { - attributeName: 'aTextureCoord', - size: 2, - uploadFunction: _this.uploadUvs, - offset: 0, - }, - // tintData - { - attributeName: 'aColor', - size: 1, - type: exports.TYPES.UNSIGNED_BYTE, - uploadFunction: _this.uploadTint, - offset: 0, - } ]; - _this.shader = Shader.from(vertex$1, fragment$1, {}); - /** - * The WebGL state in which this renderer will work. - * - * @member {PIXI.State} - * @readonly - */ - _this.state = State.for2d(); - return _this; - } - /** - * Renders the particle container object. - * - * @param {PIXI.ParticleContainer} container - The container to render using this ParticleRenderer - */ - ParticleRenderer.prototype.render = function (container) { - var children = container.children; - var maxSize = container._maxSize; - var batchSize = container._batchSize; - var renderer = this.renderer; - var totalChildren = children.length; - if (totalChildren === 0) { - return; - } - else if (totalChildren > maxSize && !container.autoResize) { - totalChildren = maxSize; - } - var buffers = container._buffers; - if (!buffers) { - buffers = container._buffers = this.generateBuffers(container); - } - var baseTexture = children[0]._texture.baseTexture; - // if the uvs have not updated then no point rendering just yet! - this.state.blendMode = correctBlendMode(container.blendMode, baseTexture.alphaMode); - renderer.state.set(this.state); - var gl = renderer.gl; - var m = container.worldTransform.copyTo(this.tempMatrix); - m.prepend(renderer.globalUniforms.uniforms.projectionMatrix); - this.shader.uniforms.translationMatrix = m.toArray(true); - this.shader.uniforms.uColor = premultiplyRgba(container.tintRgb, container.worldAlpha, this.shader.uniforms.uColor, baseTexture.alphaMode); - this.shader.uniforms.uSampler = baseTexture; - this.renderer.shader.bind(this.shader); - var updateStatic = false; - // now lets upload and render the buffers.. - for (var i = 0, j = 0; i < totalChildren; i += batchSize, j += 1) { - var amount = (totalChildren - i); - if (amount > batchSize) { - amount = batchSize; - } - if (j >= buffers.length) { - buffers.push(this._generateOneMoreBuffer(container)); - } - var buffer = buffers[j]; - // we always upload the dynamic - buffer.uploadDynamic(children, i, amount); - var bid = container._bufferUpdateIDs[j] || 0; - updateStatic = updateStatic || (buffer._updateID < bid); - // we only upload the static content when we have to! - if (updateStatic) { - buffer._updateID = container._updateID; - buffer.uploadStatic(children, i, amount); - } - // bind the buffer - renderer.geometry.bind(buffer.geometry); - gl.drawElements(gl.TRIANGLES, amount * 6, gl.UNSIGNED_SHORT, 0); - } - }; - /** - * Creates one particle buffer for each child in the container we want to render and updates internal properties - * - * @param {PIXI.ParticleContainer} container - The container to render using this ParticleRenderer - * @return {PIXI.ParticleBuffer[]} The buffers - * @private - */ - ParticleRenderer.prototype.generateBuffers = function (container) { - var buffers = []; - var size = container._maxSize; - var batchSize = container._batchSize; - var dynamicPropertyFlags = container._properties; - for (var i = 0; i < size; i += batchSize) { - buffers.push(new ParticleBuffer(this.properties, dynamicPropertyFlags, batchSize)); - } - return buffers; - }; - /** - * Creates one more particle buffer, because container has autoResize feature - * - * @param {PIXI.ParticleContainer} container - The container to render using this ParticleRenderer - * @return {PIXI.ParticleBuffer} generated buffer - * @private - */ - ParticleRenderer.prototype._generateOneMoreBuffer = function (container) { - var batchSize = container._batchSize; - var dynamicPropertyFlags = container._properties; - return new ParticleBuffer(this.properties, dynamicPropertyFlags, batchSize); - }; - /** - * Uploads the vertices. - * - * @param {PIXI.DisplayObject[]} children - the array of display objects to render - * @param {number} startIndex - the index to start from in the children array - * @param {number} amount - the amount of children that will have their vertices uploaded - * @param {number[]} array - The vertices to upload. - * @param {number} stride - Stride to use for iteration. - * @param {number} offset - Offset to start at. - */ - ParticleRenderer.prototype.uploadVertices = function (children, startIndex, amount, array, stride, offset) { - var w0 = 0; - var w1 = 0; - var h0 = 0; - var h1 = 0; - for (var i = 0; i < amount; ++i) { - var sprite = children[startIndex + i]; - var texture = sprite._texture; - var sx = sprite.scale.x; - var sy = sprite.scale.y; - var trim = texture.trim; - var orig = texture.orig; - if (trim) { - // if the sprite is trimmed and is not a tilingsprite then we need to add the - // extra space before transforming the sprite coords.. - w1 = trim.x - (sprite.anchor.x * orig.width); - w0 = w1 + trim.width; - h1 = trim.y - (sprite.anchor.y * orig.height); - h0 = h1 + trim.height; - } - else { - w0 = (orig.width) * (1 - sprite.anchor.x); - w1 = (orig.width) * -sprite.anchor.x; - h0 = orig.height * (1 - sprite.anchor.y); - h1 = orig.height * -sprite.anchor.y; - } - array[offset] = w1 * sx; - array[offset + 1] = h1 * sy; - array[offset + stride] = w0 * sx; - array[offset + stride + 1] = h1 * sy; - array[offset + (stride * 2)] = w0 * sx; - array[offset + (stride * 2) + 1] = h0 * sy; - array[offset + (stride * 3)] = w1 * sx; - array[offset + (stride * 3) + 1] = h0 * sy; - offset += stride * 4; - } - }; - /** - * Uploads the position. - * - * @param {PIXI.DisplayObject[]} children - the array of display objects to render - * @param {number} startIndex - the index to start from in the children array - * @param {number} amount - the amount of children that will have their positions uploaded - * @param {number[]} array - The vertices to upload. - * @param {number} stride - Stride to use for iteration. - * @param {number} offset - Offset to start at. - */ - ParticleRenderer.prototype.uploadPosition = function (children, startIndex, amount, array, stride, offset) { - for (var i = 0; i < amount; i++) { - var spritePosition = children[startIndex + i].position; - array[offset] = spritePosition.x; - array[offset + 1] = spritePosition.y; - array[offset + stride] = spritePosition.x; - array[offset + stride + 1] = spritePosition.y; - array[offset + (stride * 2)] = spritePosition.x; - array[offset + (stride * 2) + 1] = spritePosition.y; - array[offset + (stride * 3)] = spritePosition.x; - array[offset + (stride * 3) + 1] = spritePosition.y; - offset += stride * 4; - } - }; - /** - * Uploads the rotation. - * - * @param {PIXI.DisplayObject[]} children - the array of display objects to render - * @param {number} startIndex - the index to start from in the children array - * @param {number} amount - the amount of children that will have their rotation uploaded - * @param {number[]} array - The vertices to upload. - * @param {number} stride - Stride to use for iteration. - * @param {number} offset - Offset to start at. - */ - ParticleRenderer.prototype.uploadRotation = function (children, startIndex, amount, array, stride, offset) { - for (var i = 0; i < amount; i++) { - var spriteRotation = children[startIndex + i].rotation; - array[offset] = spriteRotation; - array[offset + stride] = spriteRotation; - array[offset + (stride * 2)] = spriteRotation; - array[offset + (stride * 3)] = spriteRotation; - offset += stride * 4; - } - }; - /** - * Uploads the Uvs - * - * @param {PIXI.DisplayObject[]} children - the array of display objects to render - * @param {number} startIndex - the index to start from in the children array - * @param {number} amount - the amount of children that will have their rotation uploaded - * @param {number[]} array - The vertices to upload. - * @param {number} stride - Stride to use for iteration. - * @param {number} offset - Offset to start at. - */ - ParticleRenderer.prototype.uploadUvs = function (children, startIndex, amount, array, stride, offset) { - for (var i = 0; i < amount; ++i) { - var textureUvs = children[startIndex + i]._texture._uvs; - if (textureUvs) { - array[offset] = textureUvs.x0; - array[offset + 1] = textureUvs.y0; - array[offset + stride] = textureUvs.x1; - array[offset + stride + 1] = textureUvs.y1; - array[offset + (stride * 2)] = textureUvs.x2; - array[offset + (stride * 2) + 1] = textureUvs.y2; - array[offset + (stride * 3)] = textureUvs.x3; - array[offset + (stride * 3) + 1] = textureUvs.y3; - offset += stride * 4; - } - else { - // TODO you know this can be easier! - array[offset] = 0; - array[offset + 1] = 0; - array[offset + stride] = 0; - array[offset + stride + 1] = 0; - array[offset + (stride * 2)] = 0; - array[offset + (stride * 2) + 1] = 0; - array[offset + (stride * 3)] = 0; - array[offset + (stride * 3) + 1] = 0; - offset += stride * 4; - } - } - }; - /** - * Uploads the tint. - * - * @param {PIXI.DisplayObject[]} children - the array of display objects to render - * @param {number} startIndex - the index to start from in the children array - * @param {number} amount - the amount of children that will have their rotation uploaded - * @param {number[]} array - The vertices to upload. - * @param {number} stride - Stride to use for iteration. - * @param {number} offset - Offset to start at. - */ - ParticleRenderer.prototype.uploadTint = function (children, startIndex, amount, array, stride, offset) { - for (var i = 0; i < amount; ++i) { - var sprite = children[startIndex + i]; - var premultiplied = sprite._texture.baseTexture.alphaMode > 0; - var alpha = sprite.alpha; - // we dont call extra function if alpha is 1.0, that's faster - var argb = alpha < 1.0 && premultiplied - ? premultiplyTint(sprite._tintRGB, alpha) : sprite._tintRGB + (alpha * 255 << 24); - array[offset] = argb; - array[offset + stride] = argb; - array[offset + (stride * 2)] = argb; - array[offset + (stride * 3)] = argb; - offset += stride * 4; - } - }; - /** - * Destroys the ParticleRenderer. - */ - ParticleRenderer.prototype.destroy = function () { - _super.prototype.destroy.call(this); - if (this.shader) { - this.shader.destroy(); - this.shader = null; - } - this.tempMatrix = null; - }; - return ParticleRenderer; - }(ObjectRenderer)); - - /*! - * @pixi/graphics - v5.3.3 - * Compiled Tue, 04 Aug 2020 16:23:09 UTC - * - * @pixi/graphics is licensed under the MIT License. - * http://www.opensource.org/licenses/mit-license - */ - - /** - * Supported line joints in `PIXI.LineStyle` for graphics. - * - * @see PIXI.Graphics#lineStyle - * @see https://graphicdesign.stackexchange.com/questions/59018/what-is-a-bevel-join-of-two-lines-exactly-illustrator - * - * @name LINE_JOIN - * @memberof PIXI - * @static - * @enum {string} - * @property {string} MITER - 'miter': make a sharp corner where outer part of lines meet - * @property {string} BEVEL - 'bevel': add a square butt at each end of line segment and fill the triangle at turn - * @property {string} ROUND - 'round': add an arc at the joint - */ - - (function (LINE_JOIN) { - LINE_JOIN["MITER"] = "miter"; - LINE_JOIN["BEVEL"] = "bevel"; - LINE_JOIN["ROUND"] = "round"; - })(exports.LINE_JOIN || (exports.LINE_JOIN = {})); - /** - * Support line caps in `PIXI.LineStyle` for graphics. - * - * @see PIXI.Graphics#lineStyle - * - * @name LINE_CAP - * @memberof PIXI - * @static - * @enum {string} - * @property {string} BUTT - 'butt': don't add any cap at line ends (leaves orthogonal edges) - * @property {string} ROUND - 'round': add semicircle at ends - * @property {string} SQUARE - 'square': add square at end (like `BUTT` except more length at end) - */ - - (function (LINE_CAP) { - LINE_CAP["BUTT"] = "butt"; - LINE_CAP["ROUND"] = "round"; - LINE_CAP["SQUARE"] = "square"; - })(exports.LINE_CAP || (exports.LINE_CAP = {})); - /** - * Graphics curves resolution settings. If `adaptive` flag is set to `true`, - * the resolution is calculated based on the curve's length to ensure better visual quality. - * Adaptive draw works with `bezierCurveTo` and `quadraticCurveTo`. - * - * @static - * @constant - * @memberof PIXI - * @name GRAPHICS_CURVES - * @type {object} - * @property {boolean} adaptive=false - flag indicating if the resolution should be adaptive - * @property {number} maxLength=10 - maximal length of a single segment of the curve (if adaptive = false, ignored) - * @property {number} minSegments=8 - minimal number of segments in the curve (if adaptive = false, ignored) - * @property {number} maxSegments=2048 - maximal number of segments in the curve (if adaptive = false, ignored) - */ - var GRAPHICS_CURVES = { - adaptive: true, - maxLength: 10, - minSegments: 8, - maxSegments: 2048, - epsilon: 0.0001, - _segmentsCount: function (length, defaultSegments) { - if (defaultSegments === void 0) { defaultSegments = 20; } - if (!this.adaptive || !length || isNaN(length)) { - return defaultSegments; - } - var result = Math.ceil(length / this.maxLength); - if (result < this.minSegments) { - result = this.minSegments; - } - else if (result > this.maxSegments) { - result = this.maxSegments; - } - return result; - }, - }; - - /** - * Fill style object for Graphics. - * - * @class - * @memberof PIXI - */ - var FillStyle = /** @class */ (function () { - function FillStyle() { - /** - * The hex color value used when coloring the Graphics object. - * - * @member {number} - * @default 0xFFFFFF - */ - this.color = 0xFFFFFF; - /** - * The alpha value used when filling the Graphics object. - * - * @member {number} - * @default 1 - */ - this.alpha = 1.0; - /** - * The texture to be used for the fill. - * - * @member {PIXI.Texture} - * @default 0 - */ - this.texture = Texture.WHITE; - /** - * The transform aplpied to the texture. - * - * @member {PIXI.Matrix} - * @default null - */ - this.matrix = null; - /** - * If the current fill is visible. - * - * @member {boolean} - * @default false - */ - this.visible = false; - this.reset(); - } - /** - * Clones the object - * - * @return {PIXI.FillStyle} - */ - FillStyle.prototype.clone = function () { - var obj = new FillStyle(); - obj.color = this.color; - obj.alpha = this.alpha; - obj.texture = this.texture; - obj.matrix = this.matrix; - obj.visible = this.visible; - return obj; - }; - /** - * Reset - */ - FillStyle.prototype.reset = function () { - this.color = 0xFFFFFF; - this.alpha = 1; - this.texture = Texture.WHITE; - this.matrix = null; - this.visible = false; - }; - /** - * Destroy and don't use after this - */ - FillStyle.prototype.destroy = function () { - this.texture = null; - this.matrix = null; - }; - return FillStyle; - }()); - - /*! ***************************************************************************** - Copyright (c) Microsoft Corporation. All rights reserved. - Licensed under the Apache License, Version 2.0 (the "License"); you may not use - this file except in compliance with the License. You may obtain a copy of the - License at http://www.apache.org/licenses/LICENSE-2.0 - - THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED - WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, - MERCHANTABLITY OR NON-INFRINGEMENT. - - See the Apache Version 2.0 License for specific language governing permissions - and limitations under the License. - ***************************************************************************** */ - /* global Reflect, Promise */ - - var extendStatics$5 = function(d, b) { - extendStatics$5 = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) { if (b.hasOwnProperty(p)) { d[p] = b[p]; } } }; - return extendStatics$5(d, b); - }; - - function __extends$5(d, b) { - extendStatics$5(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - } - - /** - * Builds a polygon to draw - * - * Ignored from docs since it is not directly exposed. - * - * @ignore - * @private - * @param {PIXI.WebGLGraphicsData} graphicsData - The graphics object containing all the necessary properties - * @param {object} webGLData - an object containing all the WebGL-specific information to create this shape - * @param {object} webGLDataNativeLines - an object containing all the WebGL-specific information to create nativeLines - */ - var buildPoly = { - build: function (graphicsData) { - graphicsData.points = graphicsData.shape.points.slice(); - }, - triangulate: function (graphicsData, graphicsGeometry) { - var points = graphicsData.points; - var holes = graphicsData.holes; - var verts = graphicsGeometry.points; - var indices = graphicsGeometry.indices; - if (points.length >= 6) { - var holeArray = []; - // Process holes.. - for (var i = 0; i < holes.length; i++) { - var hole = holes[i]; - holeArray.push(points.length / 2); - points = points.concat(hole.points); - } - // sort color - var triangles = earcut_1(points, holeArray, 2); - if (!triangles) { - return; - } - var vertPos = verts.length / 2; - for (var i = 0; i < triangles.length; i += 3) { - indices.push(triangles[i] + vertPos); - indices.push(triangles[i + 1] + vertPos); - indices.push(triangles[i + 2] + vertPos); - } - for (var i = 0; i < points.length; i++) { - verts.push(points[i]); - } - } - }, - }; - - // for type only - /** - * Builds a circle to draw - * - * Ignored from docs since it is not directly exposed. - * - * @ignore - * @private - * @param {PIXI.WebGLGraphicsData} graphicsData - The graphics object to draw - * @param {object} webGLData - an object containing all the WebGL-specific information to create this shape - * @param {object} webGLDataNativeLines - an object containing all the WebGL-specific information to create nativeLines - */ - var buildCircle = { - build: function (graphicsData) { - // need to convert points to a nice regular data - var circleData = graphicsData.shape; - var points = graphicsData.points; - var x = circleData.x; - var y = circleData.y; - var width; - var height; - points.length = 0; - // TODO - bit hacky?? - if (graphicsData.type === exports.SHAPES.CIRC) { - width = circleData.radius; - height = circleData.radius; - } - else { - var ellipseData = graphicsData.shape; - width = ellipseData.width; - height = ellipseData.height; - } - if (width === 0 || height === 0) { - return; - } - var totalSegs = Math.floor(30 * Math.sqrt(circleData.radius)) - || Math.floor(15 * Math.sqrt(width + height)); - totalSegs /= 2.3; - var seg = (Math.PI * 2) / totalSegs; - for (var i = 0; i < totalSegs - 0.5; i++) { - points.push(x + (Math.sin(-seg * i) * width), y + (Math.cos(-seg * i) * height)); - } - points.push(points[0], points[1]); - }, - triangulate: function (graphicsData, graphicsGeometry) { - var points = graphicsData.points; - var verts = graphicsGeometry.points; - var indices = graphicsGeometry.indices; - var vertPos = verts.length / 2; - var center = vertPos; - var circle = (graphicsData.shape); - var matrix = graphicsData.matrix; - var x = circle.x; - var y = circle.y; - // Push center (special point) - verts.push(graphicsData.matrix ? (matrix.a * x) + (matrix.c * y) + matrix.tx : x, graphicsData.matrix ? (matrix.b * x) + (matrix.d * y) + matrix.ty : y); - for (var i = 0; i < points.length; i += 2) { - verts.push(points[i], points[i + 1]); - // add some uvs - indices.push(vertPos++, center, vertPos); - } - }, - }; - - /** - * Builds a rectangle to draw - * - * Ignored from docs since it is not directly exposed. - * - * @ignore - * @private - * @param {PIXI.WebGLGraphicsData} graphicsData - The graphics object containing all the necessary properties - * @param {object} webGLData - an object containing all the WebGL-specific information to create this shape - * @param {object} webGLDataNativeLines - an object containing all the WebGL-specific information to create nativeLines - */ - var buildRectangle = { - build: function (graphicsData) { - // --- // - // need to convert points to a nice regular data - // - var rectData = graphicsData.shape; - var x = rectData.x; - var y = rectData.y; - var width = rectData.width; - var height = rectData.height; - var points = graphicsData.points; - points.length = 0; - points.push(x, y, x + width, y, x + width, y + height, x, y + height); - }, - triangulate: function (graphicsData, graphicsGeometry) { - var points = graphicsData.points; - var verts = graphicsGeometry.points; - var vertPos = verts.length / 2; - verts.push(points[0], points[1], points[2], points[3], points[6], points[7], points[4], points[5]); - graphicsGeometry.indices.push(vertPos, vertPos + 1, vertPos + 2, vertPos + 1, vertPos + 2, vertPos + 3); - }, - }; - - /** - * Calculate a single point for a quadratic bezier curve. - * Utility function used by quadraticBezierCurve. - * Ignored from docs since it is not directly exposed. - * - * @ignore - * @private - * @param {number} n1 - first number - * @param {number} n2 - second number - * @param {number} perc - percentage - * @return {number} the result - * - */ - function getPt(n1, n2, perc) { - var diff = n2 - n1; - return n1 + (diff * perc); - } - /** - * Calculate the points for a quadratic bezier curve. (helper function..) - * Based on: https://stackoverflow.com/questions/785097/how-do-i-implement-a-bezier-curve-in-c - * - * Ignored from docs since it is not directly exposed. - * - * @ignore - * @private - * @param {number} fromX - Origin point x - * @param {number} fromY - Origin point x - * @param {number} cpX - Control point x - * @param {number} cpY - Control point y - * @param {number} toX - Destination point x - * @param {number} toY - Destination point y - * @param {number[]} [out=[]] - The output array to add points into. If not passed, a new array is created. - * @return {number[]} an array of points - */ - function quadraticBezierCurve(fromX, fromY, cpX, cpY, toX, toY, out) { - if (out === void 0) { out = []; } - var n = 20; - var points = out; - var xa = 0; - var ya = 0; - var xb = 0; - var yb = 0; - var x = 0; - var y = 0; - for (var i = 0, j = 0; i <= n; ++i) { - j = i / n; - // The Green Line - xa = getPt(fromX, cpX, j); - ya = getPt(fromY, cpY, j); - xb = getPt(cpX, toX, j); - yb = getPt(cpY, toY, j); - // The Black Dot - x = getPt(xa, xb, j); - y = getPt(ya, yb, j); - points.push(x, y); - } - return points; - } - /** - * Builds a rounded rectangle to draw - * - * Ignored from docs since it is not directly exposed. - * - * @ignore - * @private - * @param {PIXI.WebGLGraphicsData} graphicsData - The graphics object containing all the necessary properties - * @param {object} webGLData - an object containing all the WebGL-specific information to create this shape - * @param {object} webGLDataNativeLines - an object containing all the WebGL-specific information to create nativeLines - */ - var buildRoundedRectangle = { - build: function (graphicsData) { - var rrectData = graphicsData.shape; - var points = graphicsData.points; - var x = rrectData.x; - var y = rrectData.y; - var width = rrectData.width; - var height = rrectData.height; - // Don't allow negative radius or greater than half the smallest width - var radius = Math.max(0, Math.min(rrectData.radius, Math.min(width, height) / 2)); - points.length = 0; - // No radius, do a simple rectangle - if (!radius) { - points.push(x, y, x + width, y, x + width, y + height, x, y + height); - } - else { - quadraticBezierCurve(x, y + radius, x, y, x + radius, y, points); - quadraticBezierCurve(x + width - radius, y, x + width, y, x + width, y + radius, points); - quadraticBezierCurve(x + width, y + height - radius, x + width, y + height, x + width - radius, y + height, points); - quadraticBezierCurve(x + radius, y + height, x, y + height, x, y + height - radius, points); - } - // this tiny number deals with the issue that occurs when points overlap and earcut fails to triangulate the item. - // TODO - fix this properly, this is not very elegant.. but it works for now. - }, - triangulate: function (graphicsData, graphicsGeometry) { - var points = graphicsData.points; - var verts = graphicsGeometry.points; - var indices = graphicsGeometry.indices; - var vecPos = verts.length / 2; - var triangles = earcut_1(points, null, 2); - for (var i = 0, j = triangles.length; i < j; i += 3) { - indices.push(triangles[i] + vecPos); - // indices.push(triangles[i] + vecPos); - indices.push(triangles[i + 1] + vecPos); - // indices.push(triangles[i + 2] + vecPos); - indices.push(triangles[i + 2] + vecPos); - } - for (var i = 0, j = points.length; i < j; i++) { - verts.push(points[i], points[++i]); - } - }, - }; - - /** - * Buffers vertices to draw a square cap. - * - * Ignored from docs since it is not directly exposed. - * - * @ignore - * @private - * @param {number} x - X-coord of end point - * @param {number} y - Y-coord of end point - * @param {number} nx - X-coord of line normal pointing inside - * @param {number} ny - Y-coord of line normal pointing inside - * @param {Array} verts - vertex buffer - * @returns {} - */ - function square(x, y, nx, ny, innerWeight, outerWeight, clockwise, /* rotation for square (true at left end, false at right end) */ verts) { - var ix = x - (nx * innerWeight); - var iy = y - (ny * innerWeight); - var ox = x + (nx * outerWeight); - var oy = y + (ny * outerWeight); - /* Rotate nx,ny for extension vector */ - var exx; - var eyy; - if (clockwise) { - exx = ny; - eyy = -nx; - } - else { - exx = -ny; - eyy = nx; - } - /* [i|0]x,y extended at cap */ - var eix = ix + exx; - var eiy = iy + eyy; - var eox = ox + exx; - var eoy = oy + eyy; - /* Square itself must be inserted clockwise*/ - verts.push(eix, eiy); - verts.push(eox, eoy); - return 2; - } - /** - * Buffers vertices to draw an arc at the line joint or cap. - * - * Ignored from docs since it is not directly exposed. - * - * @ignore - * @private - * @param {number} cx - X-coord of center - * @param {number} cy - Y-coord of center - * @param {number} sx - X-coord of arc start - * @param {number} sy - Y-coord of arc start - * @param {number} ex - X-coord of arc end - * @param {number} ey - Y-coord of arc end - * @param {Array} verts - buffer of vertices - * @param {boolean} clockwise - orientation of vertices - * @returns {number} - no. of vertices pushed - */ - function round(cx, cy, sx, sy, ex, ey, verts, clockwise) { - var cx2p0x = sx - cx; - var cy2p0y = sy - cy; - var angle0 = Math.atan2(cx2p0x, cy2p0y); - var angle1 = Math.atan2(ex - cx, ey - cy); - if (clockwise && angle0 < angle1) { - angle0 += Math.PI * 2; - } - else if (!clockwise && angle0 > angle1) { - angle1 += Math.PI * 2; - } - var startAngle = angle0; - var angleDiff = angle1 - angle0; - var absAngleDiff = Math.abs(angleDiff); - /* if (absAngleDiff >= PI_LBOUND && absAngleDiff <= PI_UBOUND) - { - const r1x = cx - nxtPx; - const r1y = cy - nxtPy; - - if (r1x === 0) - { - if (r1y > 0) - { - angleDiff = -angleDiff; - } - } - else if (r1x >= -GRAPHICS_CURVES.epsilon) - { - angleDiff = -angleDiff; - } - }*/ - var radius = Math.sqrt((cx2p0x * cx2p0x) + (cy2p0y * cy2p0y)); - var segCount = ((15 * absAngleDiff * Math.sqrt(radius) / Math.PI) >> 0) + 1; - var angleInc = angleDiff / segCount; - startAngle += angleInc; - if (clockwise) { - verts.push(cx, cy); - verts.push(sx, sy); - for (var i = 1, angle = startAngle; i < segCount; i++, angle += angleInc) { - verts.push(cx, cy); - verts.push(cx + ((Math.sin(angle) * radius)), cy + ((Math.cos(angle) * radius))); - } - verts.push(cx, cy); - verts.push(ex, ey); - } - else { - verts.push(sx, sy); - verts.push(cx, cy); - for (var i = 1, angle = startAngle; i < segCount; i++, angle += angleInc) { - verts.push(cx + ((Math.sin(angle) * radius)), cy + ((Math.cos(angle) * radius))); - verts.push(cx, cy); - } - verts.push(ex, ey); - verts.push(cx, cy); - } - return segCount * 2; - } - /** - * Builds a line to draw using the polygon method. - * - * Ignored from docs since it is not directly exposed. - * - * @ignore - * @private - * @param {PIXI.GraphicsData} graphicsData - The graphics object containing all the necessary properties - * @param {PIXI.GraphicsGeometry} graphicsGeometry - Geometry where to append output - */ - function buildNonNativeLine(graphicsData, graphicsGeometry) { - var shape = graphicsData.shape; - var points = graphicsData.points || shape.points.slice(); - var eps = graphicsGeometry.closePointEps; - if (points.length === 0) { - return; - } - // if the line width is an odd number add 0.5 to align to a whole pixel - // commenting this out fixes #711 and #1620 - // if (graphicsData.lineWidth%2) - // { - // for (i = 0; i < points.length; i++) - // { - // points[i] += 0.5; - // } - // } - var style = graphicsData.lineStyle; - // get first and last point.. figure out the middle! - var firstPoint = new Point(points[0], points[1]); - var lastPoint = new Point(points[points.length - 2], points[points.length - 1]); - var closedShape = shape.type !== exports.SHAPES.POLY || shape.closeStroke; - var closedPath = Math.abs(firstPoint.x - lastPoint.x) < eps - && Math.abs(firstPoint.y - lastPoint.y) < eps; - // if the first point is the last point - gonna have issues :) - if (closedShape) { - // need to clone as we are going to slightly modify the shape.. - points = points.slice(); - if (closedPath) { - points.pop(); - points.pop(); - lastPoint.set(points[points.length - 2], points[points.length - 1]); - } - var midPointX = (firstPoint.x + lastPoint.x) * 0.5; - var midPointY = (lastPoint.y + firstPoint.y) * 0.5; - points.unshift(midPointX, midPointY); - points.push(midPointX, midPointY); - } - var verts = graphicsGeometry.points; - var length = points.length / 2; - var indexCount = points.length; - var indexStart = verts.length / 2; - // Max. inner and outer width - var width = style.width / 2; - var widthSquared = width * width; - var miterLimitSquared = style.miterLimit * style.miterLimit; - /* Line segments of interest where (x1,y1) forms the corner. */ - var x0 = points[0]; - var y0 = points[1]; - var x1 = points[2]; - var y1 = points[3]; - var x2 = 0; - var y2 = 0; - /* perp[?](x|y) = the line normal with magnitude lineWidth. */ - var perpx = -(y0 - y1); - var perpy = x0 - x1; - var perp1x = 0; - var perp1y = 0; - var dist = Math.sqrt((perpx * perpx) + (perpy * perpy)); - perpx /= dist; - perpy /= dist; - perpx *= width; - perpy *= width; - var ratio = style.alignment; // 0.5; - var innerWeight = (1 - ratio) * 2; - var outerWeight = ratio * 2; - if (!closedShape) { - if (style.cap === exports.LINE_CAP.ROUND) { - indexCount += round(x0 - (perpx * (innerWeight - outerWeight) * 0.5), y0 - (perpy * (innerWeight - outerWeight) * 0.5), x0 - (perpx * innerWeight), y0 - (perpy * innerWeight), x0 + (perpx * outerWeight), y0 + (perpy * outerWeight), verts, true) + 2; - } - else if (style.cap === exports.LINE_CAP.SQUARE) { - indexCount += square(x0, y0, perpx, perpy, innerWeight, outerWeight, true, verts); - } - } - // Push first point (below & above vertices) - verts.push(x0 - (perpx * innerWeight), y0 - (perpy * innerWeight)); - verts.push(x0 + (perpx * outerWeight), y0 + (perpy * outerWeight)); - for (var i = 1; i < length - 1; ++i) { - x0 = points[(i - 1) * 2]; - y0 = points[((i - 1) * 2) + 1]; - x1 = points[i * 2]; - y1 = points[(i * 2) + 1]; - x2 = points[(i + 1) * 2]; - y2 = points[((i + 1) * 2) + 1]; - perpx = -(y0 - y1); - perpy = x0 - x1; - dist = Math.sqrt((perpx * perpx) + (perpy * perpy)); - perpx /= dist; - perpy /= dist; - perpx *= width; - perpy *= width; - perp1x = -(y1 - y2); - perp1y = x1 - x2; - dist = Math.sqrt((perp1x * perp1x) + (perp1y * perp1y)); - perp1x /= dist; - perp1y /= dist; - perp1x *= width; - perp1y *= width; - /* d[x|y](0|1) = the component displacment between points p(0,1|1,2) */ - var dx0 = x1 - x0; - var dy0 = y0 - y1; - var dx1 = x1 - x2; - var dy1 = y2 - y1; - /* +ve if internal angle counterclockwise, -ve if internal angle clockwise. */ - var cross = (dy0 * dx1) - (dy1 * dx0); - var clockwise = (cross < 0); - /* Going nearly straight? */ - if (Math.abs(cross) < 0.1) { - verts.push(x1 - (perpx * innerWeight), y1 - (perpy * innerWeight)); - verts.push(x1 + (perpx * outerWeight), y1 + (perpy * outerWeight)); - continue; - } - /* p[x|y] is the miter point. pdist is the distance between miter point and p1. */ - var c1 = ((-perpx + x0) * (-perpy + y1)) - ((-perpx + x1) * (-perpy + y0)); - var c2 = ((-perp1x + x2) * (-perp1y + y1)) - ((-perp1x + x1) * (-perp1y + y2)); - var px = ((dx0 * c2) - (dx1 * c1)) / cross; - var py = ((dy1 * c1) - (dy0 * c2)) / cross; - var pdist = ((px - x1) * (px - x1)) + ((py - y1) * (py - y1)); - /* Inner miter point */ - var imx = x1 + ((px - x1) * innerWeight); - var imy = y1 + ((py - y1) * innerWeight); - /* Outer miter point */ - var omx = x1 - ((px - x1) * outerWeight); - var omy = y1 - ((py - y1) * outerWeight); - if (style.join === exports.LINE_JOIN.BEVEL || pdist / widthSquared > miterLimitSquared) { - if (clockwise) /* rotating at inner angle */ { - verts.push(imx, imy); // inner miter point - verts.push(x1 + (perpx * outerWeight), y1 + (perpy * outerWeight)); // first segment's outer vertex - verts.push(imx, imy); // inner miter point - verts.push(x1 + (perp1x * outerWeight), y1 + (perp1y * outerWeight)); // second segment's outer vertex - } - else /* rotating at outer angle */ { - verts.push(x1 - (perpx * innerWeight), y1 - (perpy * innerWeight)); // first segment's inner vertex - verts.push(omx, omy); // outer miter point - verts.push(x1 - (perp1x * innerWeight), y1 - (perp1y * innerWeight)); // second segment's outer vertex - verts.push(omx, omy); // outer miter point - } - indexCount += 2; - } - else if (style.join === exports.LINE_JOIN.ROUND) { - if (clockwise) /* arc is outside */ { - verts.push(imx, imy); - verts.push(x1 + (perpx * outerWeight), y1 + (perpy * outerWeight)); - indexCount += round(x1, y1, x1 + (perpx * outerWeight), y1 + (perpy * outerWeight), x1 + (perp1x * outerWeight), y1 + (perp1y * outerWeight), verts, true) + 4; - verts.push(imx, imy); - verts.push(x1 + (perp1x * outerWeight), y1 + (perp1y * outerWeight)); - } - else /* arc is inside */ { - verts.push(x1 - (perpx * innerWeight), y1 - (perpy * innerWeight)); - verts.push(omx, omy); - indexCount += round(x1, y1, x1 - (perpx * innerWeight), y1 - (perpy * innerWeight), x1 - (perp1x * innerWeight), y1 - (perp1y * innerWeight), verts, false) + 4; - verts.push(x1 - (perp1x * innerWeight), y1 - (perp1y * innerWeight)); - verts.push(omx, omy); - } - } - else { - verts.push(imx, imy); - verts.push(omx, omy); - } - } - x0 = points[(length - 2) * 2]; - y0 = points[((length - 2) * 2) + 1]; - x1 = points[(length - 1) * 2]; - y1 = points[((length - 1) * 2) + 1]; - perpx = -(y0 - y1); - perpy = x0 - x1; - dist = Math.sqrt((perpx * perpx) + (perpy * perpy)); - perpx /= dist; - perpy /= dist; - perpx *= width; - perpy *= width; - verts.push(x1 - (perpx * innerWeight), y1 - (perpy * innerWeight)); - verts.push(x1 + (perpx * outerWeight), y1 + (perpy * outerWeight)); - if (!closedShape) { - if (style.cap === exports.LINE_CAP.ROUND) { - indexCount += round(x1 - (perpx * (innerWeight - outerWeight) * 0.5), y1 - (perpy * (innerWeight - outerWeight) * 0.5), x1 - (perpx * innerWeight), y1 - (perpy * innerWeight), x1 + (perpx * outerWeight), y1 + (perpy * outerWeight), verts, false) + 2; - } - else if (style.cap === exports.LINE_CAP.SQUARE) { - indexCount += square(x1, y1, perpx, perpy, innerWeight, outerWeight, false, verts); - } - } - var indices = graphicsGeometry.indices; - var eps2 = GRAPHICS_CURVES.epsilon * GRAPHICS_CURVES.epsilon; - // indices.push(indexStart); - for (var i = indexStart; i < indexCount + indexStart - 2; ++i) { - x0 = verts[(i * 2)]; - y0 = verts[(i * 2) + 1]; - x1 = verts[(i + 1) * 2]; - y1 = verts[((i + 1) * 2) + 1]; - x2 = verts[(i + 2) * 2]; - y2 = verts[((i + 2) * 2) + 1]; - /* Skip zero area triangles */ - if (Math.abs((x0 * (y1 - y2)) + (x1 * (y2 - y0)) + (x2 * (y0 - y1))) < eps2) { - continue; - } - indices.push(i, i + 1, i + 2); - } - } - /** - * Builds a line to draw using the gl.drawArrays(gl.LINES) method - * - * Ignored from docs since it is not directly exposed. - * - * @ignore - * @private - * @param {PIXI.GraphicsData} graphicsData - The graphics object containing all the necessary properties - * @param {PIXI.GraphicsGeometry} graphicsGeometry - Geometry where to append output - */ - function buildNativeLine(graphicsData, graphicsGeometry) { - var i = 0; - var shape = graphicsData.shape; - var points = graphicsData.points || shape.points; - var closedShape = shape.type !== exports.SHAPES.POLY || shape.closeStroke; - if (points.length === 0) - { return; } - var verts = graphicsGeometry.points; - var indices = graphicsGeometry.indices; - var length = points.length / 2; - var startIndex = verts.length / 2; - var currentIndex = startIndex; - verts.push(points[0], points[1]); - for (i = 1; i < length; i++) { - verts.push(points[i * 2], points[(i * 2) + 1]); - indices.push(currentIndex, currentIndex + 1); - currentIndex++; - } - if (closedShape) { - indices.push(currentIndex, startIndex); - } - } - /** - * Builds a line to draw - * - * Ignored from docs since it is not directly exposed. - * - * @ignore - * @private - * @param {PIXI.GraphicsData} graphicsData - The graphics object containing all the necessary properties - * @param {PIXI.GraphicsGeometry} graphicsGeometry - Geometry where to append output - */ - function buildLine(graphicsData, graphicsGeometry) { - if (graphicsData.lineStyle.native) { - buildNativeLine(graphicsData, graphicsGeometry); - } - else { - buildNonNativeLine(graphicsData, graphicsGeometry); - } - } - - /** - * Draw a star shape with an arbitrary number of points. - * - * @class - * @extends PIXI.Polygon - * @memberof PIXI.graphicsUtils - * @param {number} x - Center X position of the star - * @param {number} y - Center Y position of the star - * @param {number} points - The number of points of the star, must be > 1 - * @param {number} radius - The outer radius of the star - * @param {number} [innerRadius] - The inner radius between points, default half `radius` - * @param {number} [rotation=0] - The rotation of the star in radians, where 0 is vertical - * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls - */ - var Star = /** @class */ (function (_super) { - __extends$5(Star, _super); - function Star(x, y, points, radius, innerRadius, rotation) { - if (rotation === void 0) { rotation = 0; } - var _this = this; - innerRadius = innerRadius || radius / 2; - var startAngle = (-1 * Math.PI / 2) + rotation; - var len = points * 2; - var delta = PI_2 / len; - var polygon = []; - for (var i = 0; i < len; i++) { - var r = i % 2 ? innerRadius : radius; - var angle = (i * delta) + startAngle; - polygon.push(x + (r * Math.cos(angle)), y + (r * Math.sin(angle))); - } - _this = _super.call(this, polygon) || this; - return _this; - } - return Star; - }(Polygon)); - - /** - * Utilities for arc curves - * @class - * @private - */ - var ArcUtils = /** @class */ (function () { - function ArcUtils() { - } - /** - * The arcTo() method creates an arc/curve between two tangents on the canvas. - * - * "borrowed" from https://code.google.com/p/fxcanvas/ - thanks google! - * - * @private - * @param {number} x1 - The x-coordinate of the beginning of the arc - * @param {number} y1 - The y-coordinate of the beginning of the arc - * @param {number} x2 - The x-coordinate of the end of the arc - * @param {number} y2 - The y-coordinate of the end of the arc - * @param {number} radius - The radius of the arc - * @return {object} If the arc length is valid, return center of circle, radius and other info otherwise `null`. - */ - ArcUtils.curveTo = function (x1, y1, x2, y2, radius, points) { - var fromX = points[points.length - 2]; - var fromY = points[points.length - 1]; - var a1 = fromY - y1; - var b1 = fromX - x1; - var a2 = y2 - y1; - var b2 = x2 - x1; - var mm = Math.abs((a1 * b2) - (b1 * a2)); - if (mm < 1.0e-8 || radius === 0) { - if (points[points.length - 2] !== x1 || points[points.length - 1] !== y1) { - points.push(x1, y1); - } - return null; - } - var dd = (a1 * a1) + (b1 * b1); - var cc = (a2 * a2) + (b2 * b2); - var tt = (a1 * a2) + (b1 * b2); - var k1 = radius * Math.sqrt(dd) / mm; - var k2 = radius * Math.sqrt(cc) / mm; - var j1 = k1 * tt / dd; - var j2 = k2 * tt / cc; - var cx = (k1 * b2) + (k2 * b1); - var cy = (k1 * a2) + (k2 * a1); - var px = b1 * (k2 + j1); - var py = a1 * (k2 + j1); - var qx = b2 * (k1 + j2); - var qy = a2 * (k1 + j2); - var startAngle = Math.atan2(py - cy, px - cx); - var endAngle = Math.atan2(qy - cy, qx - cx); - return { - cx: (cx + x1), - cy: (cy + y1), - radius: radius, - startAngle: startAngle, - endAngle: endAngle, - anticlockwise: (b1 * a2 > b2 * a1), - }; - }; - /* eslint-disable max-len */ - /** - * The arc method creates an arc/curve (used to create circles, or parts of circles). - * - * @private - * @param {number} startX - Start x location of arc - * @param {number} startY - Start y location of arc - * @param {number} cx - The x-coordinate of the center of the circle - * @param {number} cy - The y-coordinate of the center of the circle - * @param {number} radius - The radius of the circle - * @param {number} startAngle - The starting angle, in radians (0 is at the 3 o'clock position - * of the arc's circle) - * @param {number} endAngle - The ending angle, in radians - * @param {boolean} anticlockwise - Specifies whether the drawing should be - * counter-clockwise or clockwise. False is default, and indicates clockwise, while true - * indicates counter-clockwise. - * @param {number[]} points - Collection of points to add to - */ - ArcUtils.arc = function (_startX, _startY, cx, cy, radius, startAngle, endAngle, _anticlockwise, points) { - var sweep = endAngle - startAngle; - var n = GRAPHICS_CURVES._segmentsCount(Math.abs(sweep) * radius, Math.ceil(Math.abs(sweep) / PI_2) * 40); - var theta = (sweep) / (n * 2); - var theta2 = theta * 2; - var cTheta = Math.cos(theta); - var sTheta = Math.sin(theta); - var segMinus = n - 1; - var remainder = (segMinus % 1) / segMinus; - for (var i = 0; i <= segMinus; ++i) { - var real = i + (remainder * i); - var angle = ((theta) + startAngle + (theta2 * real)); - var c = Math.cos(angle); - var s = -Math.sin(angle); - points.push((((cTheta * c) + (sTheta * s)) * radius) + cx, (((cTheta * -s) + (sTheta * c)) * radius) + cy); - } - }; - return ArcUtils; - }()); - - /** - * Utilities for bezier curves - * @class - * @private - */ - var BezierUtils = /** @class */ (function () { - function BezierUtils() { - } - /** - * Calculate length of bezier curve. - * Analytical solution is impossible, since it involves an integral that does not integrate in general. - * Therefore numerical solution is used. - * - * @private - * @param {number} fromX - Starting point x - * @param {number} fromY - Starting point y - * @param {number} cpX - Control point x - * @param {number} cpY - Control point y - * @param {number} cpX2 - Second Control point x - * @param {number} cpY2 - Second Control point y - * @param {number} toX - Destination point x - * @param {number} toY - Destination point y - * @return {number} Length of bezier curve - */ - BezierUtils.curveLength = function (fromX, fromY, cpX, cpY, cpX2, cpY2, toX, toY) { - var n = 10; - var result = 0.0; - var t = 0.0; - var t2 = 0.0; - var t3 = 0.0; - var nt = 0.0; - var nt2 = 0.0; - var nt3 = 0.0; - var x = 0.0; - var y = 0.0; - var dx = 0.0; - var dy = 0.0; - var prevX = fromX; - var prevY = fromY; - for (var i = 1; i <= n; ++i) { - t = i / n; - t2 = t * t; - t3 = t2 * t; - nt = (1.0 - t); - nt2 = nt * nt; - nt3 = nt2 * nt; - x = (nt3 * fromX) + (3.0 * nt2 * t * cpX) + (3.0 * nt * t2 * cpX2) + (t3 * toX); - y = (nt3 * fromY) + (3.0 * nt2 * t * cpY) + (3 * nt * t2 * cpY2) + (t3 * toY); - dx = prevX - x; - dy = prevY - y; - prevX = x; - prevY = y; - result += Math.sqrt((dx * dx) + (dy * dy)); - } - return result; - }; - /** - * Calculate the points for a bezier curve and then draws it. - * - * Ignored from docs since it is not directly exposed. - * - * @ignore - * @param {number} cpX - Control point x - * @param {number} cpY - Control point y - * @param {number} cpX2 - Second Control point x - * @param {number} cpY2 - Second Control point y - * @param {number} toX - Destination point x - * @param {number} toY - Destination point y - * @param {number[]} points - Path array to push points into - */ - BezierUtils.curveTo = function (cpX, cpY, cpX2, cpY2, toX, toY, points) { - var fromX = points[points.length - 2]; - var fromY = points[points.length - 1]; - points.length -= 2; - var n = GRAPHICS_CURVES._segmentsCount(BezierUtils.curveLength(fromX, fromY, cpX, cpY, cpX2, cpY2, toX, toY)); - var dt = 0; - var dt2 = 0; - var dt3 = 0; - var t2 = 0; - var t3 = 0; - points.push(fromX, fromY); - for (var i = 1, j = 0; i <= n; ++i) { - j = i / n; - dt = (1 - j); - dt2 = dt * dt; - dt3 = dt2 * dt; - t2 = j * j; - t3 = t2 * j; - points.push((dt3 * fromX) + (3 * dt2 * j * cpX) + (3 * dt * t2 * cpX2) + (t3 * toX), (dt3 * fromY) + (3 * dt2 * j * cpY) + (3 * dt * t2 * cpY2) + (t3 * toY)); - } - }; - return BezierUtils; - }()); - - /** - * Utilities for quadratic curves - * @class - * @private - */ - var QuadraticUtils = /** @class */ (function () { - function QuadraticUtils() { - } - /** - * Calculate length of quadratic curve - * @see {@link http://www.malczak.linuxpl.com/blog/quadratic-bezier-curve-length/} - * for the detailed explanation of math behind this. - * - * @private - * @param {number} fromX - x-coordinate of curve start point - * @param {number} fromY - y-coordinate of curve start point - * @param {number} cpX - x-coordinate of curve control point - * @param {number} cpY - y-coordinate of curve control point - * @param {number} toX - x-coordinate of curve end point - * @param {number} toY - y-coordinate of curve end point - * @return {number} Length of quadratic curve - */ - QuadraticUtils.curveLength = function (fromX, fromY, cpX, cpY, toX, toY) { - var ax = fromX - (2.0 * cpX) + toX; - var ay = fromY - (2.0 * cpY) + toY; - var bx = (2.0 * cpX) - (2.0 * fromX); - var by = (2.0 * cpY) - (2.0 * fromY); - var a = 4.0 * ((ax * ax) + (ay * ay)); - var b = 4.0 * ((ax * bx) + (ay * by)); - var c = (bx * bx) + (by * by); - var s = 2.0 * Math.sqrt(a + b + c); - var a2 = Math.sqrt(a); - var a32 = 2.0 * a * a2; - var c2 = 2.0 * Math.sqrt(c); - var ba = b / a2; - return ((a32 * s) - + (a2 * b * (s - c2)) - + (((4.0 * c * a) - (b * b)) - * Math.log(((2.0 * a2) + ba + s) / (ba + c2)))) / (4.0 * a32); - }; - /** - * Calculate the points for a quadratic bezier curve and then draws it. - * Based on: https://stackoverflow.com/questions/785097/how-do-i-implement-a-bezier-curve-in-c - * - * @private - * @param {number} cpX - Control point x - * @param {number} cpY - Control point y - * @param {number} toX - Destination point x - * @param {number} toY - Destination point y - * @param {number[]} points - Points to add segments to. - */ - QuadraticUtils.curveTo = function (cpX, cpY, toX, toY, points) { - var fromX = points[points.length - 2]; - var fromY = points[points.length - 1]; - var n = GRAPHICS_CURVES._segmentsCount(QuadraticUtils.curveLength(fromX, fromY, cpX, cpY, toX, toY)); - var xa = 0; - var ya = 0; - for (var i = 1; i <= n; ++i) { - var j = i / n; - xa = fromX + ((cpX - fromX) * j); - ya = fromY + ((cpY - fromY) * j); - points.push(xa + (((cpX + ((toX - cpX) * j)) - xa) * j), ya + (((cpY + ((toY - cpY) * j)) - ya) * j)); - } - }; - return QuadraticUtils; - }()); - - /** - * A structure to hold interim batch objects for Graphics. - * @class - * @memberof PIXI.graphicsUtils - */ - var BatchPart = /** @class */ (function () { - function BatchPart() { - this.reset(); - } - /** - * Begin batch part - * - * @param {PIXI.FillStyle | PIXI.LineStyle} style - * @param {number} startIndex - * @param {number} attribStart - */ - BatchPart.prototype.begin = function (style, startIndex, attribStart) { - this.reset(); - this.style = style; - this.start = startIndex; - this.attribStart = attribStart; - }; - /** - * End batch part - * - * @param {number} endIndex - * @param {number} endAttrib - */ - BatchPart.prototype.end = function (endIndex, endAttrib) { - this.attribSize = endAttrib - this.attribStart; - this.size = endIndex - this.start; - }; - BatchPart.prototype.reset = function () { - this.style = null; - this.size = 0; - this.start = 0; - this.attribStart = 0; - this.attribSize = 0; - }; - return BatchPart; - }()); - - /** - * Generalized convenience utilities for Graphics. - * - * @namespace graphicsUtils - * @memberof PIXI - */ - var _a; - /** - * Map of fill commands for each shape type. - * - * @memberof PIXI.graphicsUtils - * @member {Object} FILL_COMMANDS - */ - var FILL_COMMANDS = (_a = {}, - _a[exports.SHAPES.POLY] = buildPoly, - _a[exports.SHAPES.CIRC] = buildCircle, - _a[exports.SHAPES.ELIP] = buildCircle, - _a[exports.SHAPES.RECT] = buildRectangle, - _a[exports.SHAPES.RREC] = buildRoundedRectangle, - _a); - /** - * Batch pool, stores unused batches for preventing allocations. - * - * @memberof PIXI.graphicsUtils - * @member {Array} BATCH_POOL - */ - var BATCH_POOL = []; - /** - * Draw call pool, stores unused draw calls for preventing allocations. - * - * @memberof PIXI.graphicsUtils - * @member {Array} DRAW_CALL_POOL - */ - var DRAW_CALL_POOL = []; - - var index$2 = ({ - buildPoly: buildPoly, - buildCircle: buildCircle, - buildRectangle: buildRectangle, - buildRoundedRectangle: buildRoundedRectangle, - FILL_COMMANDS: FILL_COMMANDS, - BATCH_POOL: BATCH_POOL, - DRAW_CALL_POOL: DRAW_CALL_POOL, - buildLine: buildLine, - Star: Star, - ArcUtils: ArcUtils, - BezierUtils: BezierUtils, - QuadraticUtils: QuadraticUtils, - BatchPart: BatchPart - }); - - /** - * A class to contain data useful for Graphics objects - * - * @class - * @memberof PIXI - */ - var GraphicsData = /** @class */ (function () { - /** - * - * @param {PIXI.Circle|PIXI.Ellipse|PIXI.Polygon|PIXI.Rectangle|PIXI.RoundedRectangle} shape - The shape object to draw. - * @param {PIXI.FillStyle} [fillStyle] - the width of the line to draw - * @param {PIXI.LineStyle} [lineStyle] - the color of the line to draw - * @param {PIXI.Matrix} [matrix] - Transform matrix - */ - function GraphicsData(shape, fillStyle, lineStyle, matrix) { - if (fillStyle === void 0) { fillStyle = null; } - if (lineStyle === void 0) { lineStyle = null; } - if (matrix === void 0) { matrix = null; } - /** - * The shape object to draw. - * @member {PIXI.Circle|PIXI.Ellipse|PIXI.Polygon|PIXI.Rectangle|PIXI.RoundedRectangle} - */ - this.shape = shape; - /** - * The style of the line. - * @member {PIXI.LineStyle} - */ - this.lineStyle = lineStyle; - /** - * The style of the fill. - * @member {PIXI.FillStyle} - */ - this.fillStyle = fillStyle; - /** - * The transform matrix. - * @member {PIXI.Matrix} - */ - this.matrix = matrix; - /** - * The type of the shape, see the Const.Shapes file for all the existing types, - * @member {number} - */ - this.type = shape.type; - /** - * The collection of points. - * @member {number[]} - */ - this.points = []; - /** - * The collection of holes. - * @member {PIXI.GraphicsData[]} - */ - this.holes = []; - } - /** - * Creates a new GraphicsData object with the same values as this one. - * - * @return {PIXI.GraphicsData} Cloned GraphicsData object - */ - GraphicsData.prototype.clone = function () { - return new GraphicsData(this.shape, this.fillStyle, this.lineStyle, this.matrix); - }; - /** - * Destroys the Graphics data. - * - */ - GraphicsData.prototype.destroy = function () { - this.shape = null; - this.holes.length = 0; - this.holes = null; - this.points.length = 0; - this.points = null; - this.lineStyle = null; - this.fillStyle = null; - }; - return GraphicsData; - }()); - - var tmpPoint = new Point(); - var tmpBounds = new Bounds(); - /** - * The Graphics class contains methods used to draw primitive shapes such as lines, circles and - * rectangles to the display, and to color and fill them. - * - * GraphicsGeometry is designed to not be continually updating the geometry since it's expensive - * to re-tesselate using **earcut**. Consider using {@link PIXI.Mesh} for this use-case, it's much faster. - * - * @class - * @extends PIXI.BatchGeometry - * @memberof PIXI - */ - var GraphicsGeometry = /** @class */ (function (_super) { - __extends$5(GraphicsGeometry, _super); - function GraphicsGeometry() { - var _this = _super.call(this) || this; - _this.uvsFloat32 = null; - _this.indicesUint16 = null; - /** - * An array of points to draw, 2 numbers per point - * - * @member {number[]} - * @protected - */ - _this.points = []; - /** - * The collection of colors - * - * @member {number[]} - * @protected - */ - _this.colors = []; - /** - * The UVs collection - * - * @member {number[]} - * @protected - */ - _this.uvs = []; - /** - * The indices of the vertices - * - * @member {number[]} - * @protected - */ - _this.indices = []; - /** - * Reference to the texture IDs. - * - * @member {number[]} - * @protected - */ - _this.textureIds = []; - /** - * The collection of drawn shapes. - * - * @member {PIXI.GraphicsData[]} - * @protected - */ - _this.graphicsData = []; - /** - * Used to detect if the graphics object has changed. - * - * @member {number} - * @protected - */ - _this.dirty = 0; - /** - * Batches need to regenerated if the geometry is updated. - * - * @member {number} - * @protected - */ - _this.batchDirty = -1; - /** - * Used to check if the cache is dirty. - * - * @member {number} - * @protected - */ - _this.cacheDirty = -1; - /** - * Used to detect if we cleared the graphicsData. - * - * @member {number} - * @default 0 - * @protected - */ - _this.clearDirty = 0; - /** - * List of current draw calls drived from the batches. - * - * @member {object[]} - * @protected - */ - _this.drawCalls = []; - /** - * Intermediate abstract format sent to batch system. - * Can be converted to drawCalls or to batchable objects. - * - * @member {PIXI.graphicsUtils.BatchPart[]} - * @protected - */ - _this.batches = []; - /** - * Index of the last batched shape in the stack of calls. - * - * @member {number} - * @protected - */ - _this.shapeIndex = 0; - /** - * Cached bounds. - * - * @member {PIXI.Bounds} - * @protected - */ - _this._bounds = new Bounds(); - /** - * The bounds dirty flag. - * - * @member {number} - * @protected - */ - _this.boundsDirty = -1; - /** - * Padding to add to the bounds. - * - * @member {number} - * @default 0 - */ - _this.boundsPadding = 0; - _this.batchable = false; - _this.indicesUint16 = null; - _this.uvsFloat32 = null; - /** - * Minimal distance between points that are considered different. - * Affects line tesselation. - * - * @member {number} - */ - _this.closePointEps = 1e-4; - return _this; - } - Object.defineProperty(GraphicsGeometry.prototype, "bounds", { - /** - * Get the current bounds of the graphic geometry. - * - * @member {PIXI.Bounds} - * @readonly - */ - get: function () { - if (this.boundsDirty !== this.dirty) { - this.boundsDirty = this.dirty; - this.calculateBounds(); - } - return this._bounds; - }, - enumerable: false, - configurable: true - }); - /** - * Call if you changed graphicsData manually. - * Empties all batch buffers. - */ - GraphicsGeometry.prototype.invalidate = function () { - this.boundsDirty = -1; - this.dirty++; - this.batchDirty++; - this.shapeIndex = 0; - this.points.length = 0; - this.colors.length = 0; - this.uvs.length = 0; - this.indices.length = 0; - this.textureIds.length = 0; - for (var i = 0; i < this.drawCalls.length; i++) { - this.drawCalls[i].texArray.clear(); - DRAW_CALL_POOL.push(this.drawCalls[i]); - } - this.drawCalls.length = 0; - for (var i = 0; i < this.batches.length; i++) { - var batchPart = this.batches[i]; - batchPart.reset(); - BATCH_POOL.push(batchPart); - } - this.batches.length = 0; - }; - /** - * Clears the graphics that were drawn to this Graphics object, and resets fill and line style settings. - * - * @return {PIXI.GraphicsGeometry} This GraphicsGeometry object. Good for chaining method calls - */ - GraphicsGeometry.prototype.clear = function () { - if (this.graphicsData.length > 0) { - this.invalidate(); - this.clearDirty++; - this.graphicsData.length = 0; - } - return this; - }; - /** - * Draws the given shape to this Graphics object. Can be any of Circle, Rectangle, Ellipse, Line or Polygon. - * - * @param {PIXI.Circle|PIXI.Ellipse|PIXI.Polygon|PIXI.Rectangle|PIXI.RoundedRectangle} shape - The shape object to draw. - * @param {PIXI.FillStyle} fillStyle - Defines style of the fill. - * @param {PIXI.LineStyle} lineStyle - Defines style of the lines. - * @param {PIXI.Matrix} matrix - Transform applied to the points of the shape. - * @return {PIXI.GraphicsGeometry} Returns geometry for chaining. - */ - GraphicsGeometry.prototype.drawShape = function (shape, fillStyle, lineStyle, matrix) { - if (fillStyle === void 0) { fillStyle = null; } - if (lineStyle === void 0) { lineStyle = null; } - if (matrix === void 0) { matrix = null; } - var data = new GraphicsData(shape, fillStyle, lineStyle, matrix); - this.graphicsData.push(data); - this.dirty++; - return this; - }; - /** - * Draws the given shape to this Graphics object. Can be any of Circle, Rectangle, Ellipse, Line or Polygon. - * - * @param {PIXI.Circle|PIXI.Ellipse|PIXI.Polygon|PIXI.Rectangle|PIXI.RoundedRectangle} shape - The shape object to draw. - * @param {PIXI.Matrix} matrix - Transform applied to the points of the shape. - * @return {PIXI.GraphicsGeometry} Returns geometry for chaining. - */ - GraphicsGeometry.prototype.drawHole = function (shape, matrix) { - if (matrix === void 0) { matrix = null; } - if (!this.graphicsData.length) { - return null; - } - var data = new GraphicsData(shape, null, null, matrix); - var lastShape = this.graphicsData[this.graphicsData.length - 1]; - data.lineStyle = lastShape.lineStyle; - lastShape.holes.push(data); - this.dirty++; - return this; - }; - /** - * Destroys the GraphicsGeometry object. - * - */ - GraphicsGeometry.prototype.destroy = function () { - _super.prototype.destroy.call(this); - // destroy each of the GraphicsData objects - for (var i = 0; i < this.graphicsData.length; ++i) { - this.graphicsData[i].destroy(); - } - this.points.length = 0; - this.points = null; - this.colors.length = 0; - this.colors = null; - this.uvs.length = 0; - this.uvs = null; - this.indices.length = 0; - this.indices = null; - this.indexBuffer.destroy(); - this.indexBuffer = null; - this.graphicsData.length = 0; - this.graphicsData = null; - this.drawCalls.length = 0; - this.drawCalls = null; - this.batches.length = 0; - this.batches = null; - this._bounds = null; - }; - /** - * Check to see if a point is contained within this geometry. - * - * @param {PIXI.IPointData} point - Point to check if it's contained. - * @return {Boolean} `true` if the point is contained within geometry. - */ - GraphicsGeometry.prototype.containsPoint = function (point) { - var graphicsData = this.graphicsData; - for (var i = 0; i < graphicsData.length; ++i) { - var data = graphicsData[i]; - if (!data.fillStyle.visible) { - continue; - } - // only deal with fills.. - if (data.shape) { - if (data.matrix) { - data.matrix.applyInverse(point, tmpPoint); - } - else { - tmpPoint.copyFrom(point); - } - if (data.shape.contains(tmpPoint.x, tmpPoint.y)) { - var hitHole = false; - if (data.holes) { - for (var i_1 = 0; i_1 < data.holes.length; i_1++) { - var hole = data.holes[i_1]; - if (hole.shape.contains(tmpPoint.x, tmpPoint.y)) { - hitHole = true; - break; - } - } - } - if (!hitHole) { - return true; - } - } - } - } - return false; - }; - /** - * Generates intermediate batch data. Either gets converted to drawCalls - * or used to convert to batch objects directly by the Graphics object. - * - * @param {boolean} [aloow32Indices] - Allow using 32-bit indices for preventings artefacts when more that 65535 vertices - */ - GraphicsGeometry.prototype.updateBatches = function (allow32Indices) { - if (!this.graphicsData.length) { - this.batchable = true; - return; - } - if (!this.validateBatching()) { - return; - } - this.cacheDirty = this.dirty; - var uvs = this.uvs; - var graphicsData = this.graphicsData; - var batchPart = null; - var currentStyle = null; - if (this.batches.length > 0) { - batchPart = this.batches[this.batches.length - 1]; - currentStyle = batchPart.style; - } - for (var i = this.shapeIndex; i < graphicsData.length; i++) { - this.shapeIndex++; - var data = graphicsData[i]; - var fillStyle = data.fillStyle; - var lineStyle = data.lineStyle; - var command = FILL_COMMANDS[data.type]; - // build out the shapes points.. - command.build(data); - if (data.matrix) { - this.transformPoints(data.points, data.matrix); - } - for (var j = 0; j < 2; j++) { - var style = (j === 0) ? fillStyle : lineStyle; - if (!style.visible) - { continue; } - var nextTexture = style.texture.baseTexture; - var index_1 = this.indices.length; - var attribIndex = this.points.length / 2; - nextTexture.wrapMode = exports.WRAP_MODES.REPEAT; - if (j === 0) { - this.processFill(data); - } - else { - this.processLine(data); - } - var size = (this.points.length / 2) - attribIndex; - if (size === 0) - { continue; } - // close batch if style is different - if (batchPart && !this._compareStyles(currentStyle, style)) { - batchPart.end(index_1, attribIndex); - batchPart = null; - } - // spawn new batch if its first batch or previous was closed - if (!batchPart) { - batchPart = BATCH_POOL.pop() || new BatchPart(); - batchPart.begin(style, index_1, attribIndex); - this.batches.push(batchPart); - currentStyle = style; - } - this.addUvs(this.points, uvs, style.texture, attribIndex, size, style.matrix); - } - } - var index = this.indices.length; - var attrib = this.points.length / 2; - if (batchPart) { - batchPart.end(index, attrib); - } - if (this.batches.length === 0) { - // there are no visible styles in GraphicsData - // its possible that someone wants Graphics just for the bounds - this.batchable = true; - return; - } - // prevent allocation when length is same as buffer - if (this.indicesUint16 && this.indices.length === this.indicesUint16.length) { - this.indicesUint16.set(this.indices); - } - else { - var need32 = attrib > 0xffff && allow32Indices; - this.indicesUint16 = need32 ? new Uint32Array(this.indices) : new Uint16Array(this.indices); - } - // TODO make this a const.. - this.batchable = this.isBatchable(); - if (this.batchable) { - this.packBatches(); - } - else { - this.buildDrawCalls(); - } - }; - /** - * Affinity check - * - * @param {PIXI.FillStyle | PIXI.LineStyle} styleA - * @param {PIXI.FillStyle | PIXI.LineStyle} styleB - */ - GraphicsGeometry.prototype._compareStyles = function (styleA, styleB) { - if (!styleA || !styleB) { - return false; - } - if (styleA.texture.baseTexture !== styleB.texture.baseTexture) { - return false; - } - if (styleA.color + styleA.alpha !== styleB.color + styleB.alpha) { - return false; - } - if (!!styleA.native !== !!styleB.native) { - return false; - } - return true; - }; - /** - * Test geometry for batching process. - * - * @protected - */ - GraphicsGeometry.prototype.validateBatching = function () { - if (this.dirty === this.cacheDirty || !this.graphicsData.length) { - return false; - } - for (var i = 0, l = this.graphicsData.length; i < l; i++) { - var data = this.graphicsData[i]; - var fill = data.fillStyle; - var line = data.lineStyle; - if (fill && !fill.texture.baseTexture.valid) - { return false; } - if (line && !line.texture.baseTexture.valid) - { return false; } - } - return true; - }; - /** - * Offset the indices so that it works with the batcher. - * - * @protected - */ - GraphicsGeometry.prototype.packBatches = function () { - this.batchDirty++; - this.uvsFloat32 = new Float32Array(this.uvs); - var batches = this.batches; - for (var i = 0, l = batches.length; i < l; i++) { - var batch = batches[i]; - for (var j = 0; j < batch.size; j++) { - var index = batch.start + j; - this.indicesUint16[index] = this.indicesUint16[index] - batch.attribStart; - } - } - }; - /** - * Checks to see if this graphics geometry can be batched. - * Currently it needs to be small enough and not contain any native lines. - * - * @protected - */ - GraphicsGeometry.prototype.isBatchable = function () { - // prevent heavy mesh batching - if (this.points.length > 0xffff * 2) { - return false; - } - var batches = this.batches; - for (var i = 0; i < batches.length; i++) { - if (batches[i].style.native) { - return false; - } - } - return (this.points.length < GraphicsGeometry.BATCHABLE_SIZE * 2); - }; - /** - * Converts intermediate batches data to drawCalls. - * - * @protected - */ - GraphicsGeometry.prototype.buildDrawCalls = function () { - var TICK = ++BaseTexture._globalBatch; - for (var i = 0; i < this.drawCalls.length; i++) { - this.drawCalls[i].texArray.clear(); - DRAW_CALL_POOL.push(this.drawCalls[i]); - } - this.drawCalls.length = 0; - var colors = this.colors; - var textureIds = this.textureIds; - var currentGroup = DRAW_CALL_POOL.pop(); - if (!currentGroup) { - currentGroup = new BatchDrawCall(); - currentGroup.texArray = new BatchTextureArray(); - } - currentGroup.texArray.count = 0; - currentGroup.start = 0; - currentGroup.size = 0; - currentGroup.type = exports.DRAW_MODES.TRIANGLES; - var textureCount = 0; - var currentTexture = null; - var textureId = 0; - var native = false; - var drawMode = exports.DRAW_MODES.TRIANGLES; - var index = 0; - this.drawCalls.push(currentGroup); - // TODO - this can be simplified - for (var i = 0; i < this.batches.length; i++) { - var data = this.batches[i]; - // TODO add some full on MAX_TEXTURE CODE.. - var MAX_TEXTURES = 8; - // Forced cast for checking `native` without errors - var style = data.style; - var nextTexture = style.texture.baseTexture; - if (native !== !!style.native) { - native = !!style.native; - drawMode = native ? exports.DRAW_MODES.LINES : exports.DRAW_MODES.TRIANGLES; - // force the batch to break! - currentTexture = null; - textureCount = MAX_TEXTURES; - TICK++; - } - if (currentTexture !== nextTexture) { - currentTexture = nextTexture; - if (nextTexture._batchEnabled !== TICK) { - if (textureCount === MAX_TEXTURES) { - TICK++; - textureCount = 0; - if (currentGroup.size > 0) { - currentGroup = DRAW_CALL_POOL.pop(); - if (!currentGroup) { - currentGroup = new BatchDrawCall(); - currentGroup.texArray = new BatchTextureArray(); - } - this.drawCalls.push(currentGroup); - } - currentGroup.start = index; - currentGroup.size = 0; - currentGroup.texArray.count = 0; - currentGroup.type = drawMode; - } - // TODO add this to the render part.. - // Hack! Because texture has protected `touched` - nextTexture.touched = 1; // touch; - nextTexture._batchEnabled = TICK; - nextTexture._batchLocation = textureCount; - nextTexture.wrapMode = 10497; - currentGroup.texArray.elements[currentGroup.texArray.count++] = nextTexture; - textureCount++; - } - } - currentGroup.size += data.size; - index += data.size; - textureId = nextTexture._batchLocation; - this.addColors(colors, style.color, style.alpha, data.attribSize); - this.addTextureIds(textureIds, textureId, data.attribSize); - } - BaseTexture._globalBatch = TICK; - // upload.. - // merge for now! - this.packAttributes(); - }; - /** - * Packs attributes to single buffer. - * - * @protected - */ - GraphicsGeometry.prototype.packAttributes = function () { - var verts = this.points; - var uvs = this.uvs; - var colors = this.colors; - var textureIds = this.textureIds; - // verts are 2 positions.. so we * by 3 as there are 6 properties.. then 4 cos its bytes - var glPoints = new ArrayBuffer(verts.length * 3 * 4); - var f32 = new Float32Array(glPoints); - var u32 = new Uint32Array(glPoints); - var p = 0; - for (var i = 0; i < verts.length / 2; i++) { - f32[p++] = verts[i * 2]; - f32[p++] = verts[(i * 2) + 1]; - f32[p++] = uvs[i * 2]; - f32[p++] = uvs[(i * 2) + 1]; - u32[p++] = colors[i]; - f32[p++] = textureIds[i]; - } - this._buffer.update(glPoints); - this._indexBuffer.update(this.indicesUint16); - }; - /** - * Process fill part of Graphics. - * - * @param {PIXI.GraphicsData} data - * @protected - */ - GraphicsGeometry.prototype.processFill = function (data) { - if (data.holes.length) { - this.processHoles(data.holes); - buildPoly.triangulate(data, this); - } - else { - var command = FILL_COMMANDS[data.type]; - command.triangulate(data, this); - } - }; - /** - * Process line part of Graphics. - * - * @param {PIXI.GraphicsData} data - * @protected - */ - GraphicsGeometry.prototype.processLine = function (data) { - buildLine(data, this); - for (var i = 0; i < data.holes.length; i++) { - buildLine(data.holes[i], this); - } - }; - /** - * Process the holes data. - * - * @param {PIXI.GraphicsData[]} holes - Holes to render - * @protected - */ - GraphicsGeometry.prototype.processHoles = function (holes) { - for (var i = 0; i < holes.length; i++) { - var hole = holes[i]; - var command = FILL_COMMANDS[hole.type]; - command.build(hole); - if (hole.matrix) { - this.transformPoints(hole.points, hole.matrix); - } - } - }; - /** - * Update the local bounds of the object. Expensive to use performance-wise. - * - * @protected - */ - GraphicsGeometry.prototype.calculateBounds = function () { - var bounds = this._bounds; - var sequenceBounds = tmpBounds; - var curMatrix = Matrix.IDENTITY; - this._bounds.clear(); - sequenceBounds.clear(); - for (var i = 0; i < this.graphicsData.length; i++) { - var data = this.graphicsData[i]; - var shape = data.shape; - var type = data.type; - var lineStyle = data.lineStyle; - var nextMatrix = data.matrix || Matrix.IDENTITY; - var lineWidth = 0.0; - if (lineStyle && lineStyle.visible) { - var alignment = lineStyle.alignment; - lineWidth = lineStyle.width; - if (type === exports.SHAPES.POLY) { - lineWidth = lineWidth * (0.5 + Math.abs(0.5 - alignment)); - } - else { - lineWidth = lineWidth * Math.max(0, alignment); - } - } - if (curMatrix !== nextMatrix) { - if (!sequenceBounds.isEmpty()) { - bounds.addBoundsMatrix(sequenceBounds, curMatrix); - sequenceBounds.clear(); - } - curMatrix = nextMatrix; - } - if (type === exports.SHAPES.RECT || type === exports.SHAPES.RREC) { - var rect = shape; - sequenceBounds.addFramePad(rect.x, rect.y, rect.x + rect.width, rect.y + rect.height, lineWidth, lineWidth); - } - else if (type === exports.SHAPES.CIRC) { - var circle = shape; - sequenceBounds.addFramePad(circle.x, circle.y, circle.x, circle.y, circle.radius + lineWidth, circle.radius + lineWidth); - } - else if (type === exports.SHAPES.ELIP) { - var ellipse = shape; - sequenceBounds.addFramePad(ellipse.x, ellipse.y, ellipse.x, ellipse.y, ellipse.width + lineWidth, ellipse.height + lineWidth); - } - else { - var poly = shape; - // adding directly to the bounds - bounds.addVerticesMatrix(curMatrix, poly.points, 0, poly.points.length, lineWidth, lineWidth); - } - } - if (!sequenceBounds.isEmpty()) { - bounds.addBoundsMatrix(sequenceBounds, curMatrix); - } - bounds.pad(this.boundsPadding, this.boundsPadding); - }; - /** - * Transform points using matrix. - * - * @protected - * @param {number[]} points - Points to transform - * @param {PIXI.Matrix} matrix - Transform matrix - */ - GraphicsGeometry.prototype.transformPoints = function (points, matrix) { - for (var i = 0; i < points.length / 2; i++) { - var x = points[(i * 2)]; - var y = points[(i * 2) + 1]; - points[(i * 2)] = (matrix.a * x) + (matrix.c * y) + matrix.tx; - points[(i * 2) + 1] = (matrix.b * x) + (matrix.d * y) + matrix.ty; - } - }; - /** - * Add colors. - * - * @protected - * @param {number[]} colors - List of colors to add to - * @param {number} color - Color to add - * @param {number} alpha - Alpha to use - * @param {number} size - Number of colors to add - */ - GraphicsGeometry.prototype.addColors = function (colors, color, alpha, size) { - // TODO use the premultiply bits Ivan added - var rgb = (color >> 16) + (color & 0xff00) + ((color & 0xff) << 16); - var rgba = premultiplyTint(rgb, alpha); - while (size-- > 0) { - colors.push(rgba); - } - }; - /** - * Add texture id that the shader/fragment wants to use. - * - * @protected - * @param {number[]} textureIds - * @param {number} id - * @param {number} size - */ - GraphicsGeometry.prototype.addTextureIds = function (textureIds, id, size) { - while (size-- > 0) { - textureIds.push(id); - } - }; - /** - * Generates the UVs for a shape. - * - * @protected - * @param {number[]} verts - Vertices - * @param {number[]} uvs - UVs - * @param {PIXI.Texture} texture - Reference to Texture - * @param {number} start - Index buffer start index. - * @param {number} size - The size/length for index buffer. - * @param {PIXI.Matrix} [matrix] - Optional transform for all points. - */ - GraphicsGeometry.prototype.addUvs = function (verts, uvs, texture, start, size, matrix) { - if (matrix === void 0) { matrix = null; } - var index = 0; - var uvsStart = uvs.length; - var frame = texture.frame; - while (index < size) { - var x = verts[(start + index) * 2]; - var y = verts[((start + index) * 2) + 1]; - if (matrix) { - var nx = (matrix.a * x) + (matrix.c * y) + matrix.tx; - y = (matrix.b * x) + (matrix.d * y) + matrix.ty; - x = nx; - } - index++; - uvs.push(x / frame.width, y / frame.height); - } - var baseTexture = texture.baseTexture; - if (frame.width < baseTexture.width - || frame.height < baseTexture.height) { - this.adjustUvs(uvs, texture, uvsStart, size); - } - }; - /** - * Modify uvs array according to position of texture region - * Does not work with rotated or trimmed textures - * - * @param {number[]} uvs - array - * @param {PIXI.Texture} texture - region - * @param {number} start - starting index for uvs - * @param {number} size - how many points to adjust - */ - GraphicsGeometry.prototype.adjustUvs = function (uvs, texture, start, size) { - var baseTexture = texture.baseTexture; - var eps = 1e-6; - var finish = start + (size * 2); - var frame = texture.frame; - var scaleX = frame.width / baseTexture.width; - var scaleY = frame.height / baseTexture.height; - var offsetX = frame.x / frame.width; - var offsetY = frame.y / frame.height; - var minX = Math.floor(uvs[start] + eps); - var minY = Math.floor(uvs[start + 1] + eps); - for (var i = start + 2; i < finish; i += 2) { - minX = Math.min(minX, Math.floor(uvs[i] + eps)); - minY = Math.min(minY, Math.floor(uvs[i + 1] + eps)); - } - offsetX -= minX; - offsetY -= minY; - for (var i = start; i < finish; i += 2) { - uvs[i] = (uvs[i] + offsetX) * scaleX; - uvs[i + 1] = (uvs[i + 1] + offsetY) * scaleY; - } - }; - /** - * The maximum number of points to consider an object "batchable", - * able to be batched by the renderer's batch system. - * - * @memberof PIXI.GraphicsGeometry - * @static - * @member {number} BATCHABLE_SIZE - * @default 100 - */ - GraphicsGeometry.BATCHABLE_SIZE = 100; - return GraphicsGeometry; - }(BatchGeometry)); - - /** - * Represents the line style for Graphics. - * @memberof PIXI - * @class - * @extends PIXI.FillStyle - */ - var LineStyle = /** @class */ (function (_super) { - __extends$5(LineStyle, _super); - function LineStyle() { - var _this = _super !== null && _super.apply(this, arguments) || this; - /** - * The width (thickness) of any lines drawn. - * - * @member {number} - * @default 0 - */ - _this.width = 0; - /** - * The alignment of any lines drawn (0.5 = middle, 1 = outer, 0 = inner). - * - * @member {number} - * @default 0.5 - */ - _this.alignment = 0.5; - /** - * If true the lines will be draw using LINES instead of TRIANGLE_STRIP - * - * @member {boolean} - * @default false - */ - _this.native = false; - /** - * Line cap style. - * - * @member {PIXI.LINE_CAP} - * @default PIXI.LINE_CAP.BUTT - */ - _this.cap = exports.LINE_CAP.BUTT; - /** - * Line join style. - * - * @member {PIXI.LINE_JOIN} - * @default PIXI.LINE_JOIN.MITER - */ - _this.join = exports.LINE_JOIN.MITER; - /** - * Miter limit. - * - * @member {number} - * @default 10 - */ - _this.miterLimit = 10; - return _this; - } - /** - * Clones the object - * - * @return {PIXI.LineStyle} - */ - LineStyle.prototype.clone = function () { - var obj = new LineStyle(); - obj.color = this.color; - obj.alpha = this.alpha; - obj.texture = this.texture; - obj.matrix = this.matrix; - obj.visible = this.visible; - obj.width = this.width; - obj.alignment = this.alignment; - obj.native = this.native; - obj.cap = this.cap; - obj.join = this.join; - obj.miterLimit = this.miterLimit; - return obj; - }; - /** - * Reset the line style to default. - */ - LineStyle.prototype.reset = function () { - _super.prototype.reset.call(this); - // Override default line style color - this.color = 0x0; - this.alignment = 0.5; - this.width = 0; - this.native = false; - }; - return LineStyle; - }(FillStyle)); - - var temp = new Float32Array(3); - // a default shaders map used by graphics.. - var DEFAULT_SHADERS = {}; - /** - * The Graphics class contains methods used to draw primitive shapes such as lines, circles and - * rectangles to the display, and to color and fill them. - * - * Note that because Graphics can share a GraphicsGeometry with other instances, - * it is necessary to call `destroy()` to properly dereference the underlying - * GraphicsGeometry and avoid a memory leak. Alternatively, keep using the same - * Graphics instance and call `clear()` between redraws. - * - * @class - * @extends PIXI.Container - * @memberof PIXI - */ - var Graphics = /** @class */ (function (_super) { - __extends$5(Graphics, _super); - /** - * @param {PIXI.GraphicsGeometry} [geometry=null] - Geometry to use, if omitted - * will create a new GraphicsGeometry instance. - */ - function Graphics(geometry) { - if (geometry === void 0) { geometry = null; } - var _this = _super.call(this) || this; - _this._geometry = geometry || new GraphicsGeometry(); - _this._geometry.refCount++; - /** - * Represents the vertex and fragment shaders that processes the geometry and runs on the GPU. - * Can be shared between multiple Graphics objects. - * - * @member {PIXI.Shader} - */ - _this.shader = null; - /** - * Represents the WebGL state the Graphics required to render, excludes shader and geometry. E.g., - * blend mode, culling, depth testing, direction of rendering triangles, backface, etc. - * - * @member {PIXI.State} - */ - _this.state = State.for2d(); - /** - * Current fill style - * - * @member {PIXI.FillStyle} - * @protected - */ - _this._fillStyle = new FillStyle(); - /** - * Current line style - * - * @member {PIXI.LineStyle} - * @protected - */ - _this._lineStyle = new LineStyle(); - /** - * Current shape transform matrix. - * - * @member {PIXI.Matrix} - * @protected - */ - _this._matrix = null; - /** - * Current hole mode is enabled. - * - * @member {boolean} - * @default false - * @protected - */ - _this._holeMode = false; - /** - * Current path - * - * @member {PIXI.Polygon} - * @protected - */ - _this.currentPath = null; - /** - * When cacheAsBitmap is set to true the graphics object will be rendered as if it was a sprite. - * This is useful if your graphics element does not change often, as it will speed up the rendering - * of the object in exchange for taking up texture memory. It is also useful if you need the graphics - * object to be anti-aliased, because it will be rendered using canvas. This is not recommended if - * you are constantly redrawing the graphics element. - * - * @name cacheAsBitmap - * @member {boolean} - * @memberof PIXI.Graphics# - * @default false - */ - /** - * A collections of batches! These can be drawn by the renderer batch system. - * - * @protected - * @member {object[]} - */ - _this.batches = []; - /** - * Update dirty for limiting calculating tints for batches. - * - * @protected - * @member {number} - * @default -1 - */ - _this.batchTint = -1; - /** - * Update dirty for limiting calculating batches. - * - * @protected - * @member {number} - * @default -1 - */ - _this.batchDirty = -1; - /** - * Copy of the object vertex data. - * - * @protected - * @member {Float32Array} - */ - _this.vertexData = null; - /** - * Renderer plugin for batching - * - * @member {string} - * @default 'batch' - */ - _this.pluginName = 'batch'; - _this._transformID = -1; - // Set default - _this.tint = 0xFFFFFF; - _this.blendMode = exports.BLEND_MODES.NORMAL; - return _this; - } - Object.defineProperty(Graphics.prototype, "geometry", { - /** - * Includes vertex positions, face indices, normals, colors, UVs, and - * custom attributes within buffers, reducing the cost of passing all - * this data to the GPU. Can be shared between multiple Mesh or Graphics objects. - * - * @member {PIXI.GraphicsGeometry} - * @readonly - */ - get: function () { - return this._geometry; - }, - enumerable: false, - configurable: true - }); - /** - * Creates a new Graphics object with the same values as this one. - * Note that only the geometry of the object is cloned, not its transform (position,scale,etc) - * - * @return {PIXI.Graphics} A clone of the graphics object - */ - Graphics.prototype.clone = function () { - this.finishPoly(); - return new Graphics(this._geometry); - }; - Object.defineProperty(Graphics.prototype, "blendMode", { - get: function () { - return this.state.blendMode; - }, - /** - * The blend mode to be applied to the graphic shape. Apply a value of - * `PIXI.BLEND_MODES.NORMAL` to reset the blend mode. - * - * @member {number} - * @default PIXI.BLEND_MODES.NORMAL; - * @see PIXI.BLEND_MODES - */ - set: function (value) { - this.state.blendMode = value; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(Graphics.prototype, "tint", { - /** - * The tint applied to the graphic shape. This is a hex value. A value of - * 0xFFFFFF will remove any tint effect. - * - * @member {number} - * @default 0xFFFFFF - */ - get: function () { - return this._tint; - }, - set: function (value) { - this._tint = value; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(Graphics.prototype, "fill", { - /** - * The current fill style. - * - * @member {PIXI.FillStyle} - * @readonly - */ - get: function () { - return this._fillStyle; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(Graphics.prototype, "line", { - /** - * The current line style. - * - * @member {PIXI.LineStyle} - * @readonly - */ - get: function () { - return this._lineStyle; - }, - enumerable: false, - configurable: true - }); - /** - * Specifies the line style used for subsequent calls to Graphics methods such as the lineTo() - * method or the drawCircle() method. - * - * @method PIXI.Graphics#lineStyle - * @param {number} [width=0] - width of the line to draw, will update the objects stored style - * @param {number} [color=0x0] - color of the line to draw, will update the objects stored style - * @param {number} [alpha=1] - alpha of the line to draw, will update the objects stored style - * @param {number} [alignment=0.5] - alignment of the line to draw, (0 = inner, 0.5 = middle, 1 = outter) - * @param {boolean} [native=false] - If true the lines will be draw using LINES instead of TRIANGLE_STRIP - * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls - */ - /** - * Specifies the line style used for subsequent calls to Graphics methods such as the lineTo() - * method or the drawCircle() method. - * - * @param {object} [options] - Line style options - * @param {number} [options.width=0] - width of the line to draw, will update the objects stored style - * @param {number} [options.color=0x0] - color of the line to draw, will update the objects stored style - * @param {number} [options.alpha=1] - alpha of the line to draw, will update the objects stored style - * @param {number} [options.alignment=0.5] - alignment of the line to draw, (0 = inner, 0.5 = middle, 1 = outter) - * @param {boolean} [options.native=false] - If true the lines will be draw using LINES instead of TRIANGLE_STRIP - * @param {PIXI.LINE_CAP}[options.cap=PIXI.LINE_CAP.BUTT] - line cap style - * @param {PIXI.LINE_JOIN}[options.join=PIXI.LINE_JOIN.MITER] - line join style - * @param {number}[options.miterLimit=10] - miter limit ratio - * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls - */ - Graphics.prototype.lineStyle = function (options) { - if (options === void 0) { options = null; } - // Support non-object params: (width, color, alpha, alignment, native) - if (typeof options === 'number') { - // eslint-disable-next-line - var args = arguments; - options = { - width: args[0] || 0, - color: args[1] || 0x0, - alpha: args[2] !== undefined ? args[2] : 1, - alignment: args[3] !== undefined ? args[3] : 0.5, - native: !!args[4], - }; - } - return this.lineTextureStyle(options); - }; - /** - * Like line style but support texture for line fill. - * - * @param {object} [options] - Collection of options for setting line style. - * @param {number} [options.width=0] - width of the line to draw, will update the objects stored style - * @param {PIXI.Texture} [options.texture=PIXI.Texture.WHITE] - Texture to use - * @param {number} [options.color=0x0] - color of the line to draw, will update the objects stored style. - * Default 0xFFFFFF if texture present. - * @param {number} [options.alpha=1] - alpha of the line to draw, will update the objects stored style - * @param {PIXI.Matrix} [options.matrix=null] - Texture matrix to transform texture - * @param {number} [options.alignment=0.5] - alignment of the line to draw, (0 = inner, 0.5 = middle, 1 = outter) - * @param {boolean} [options.native=false] - If true the lines will be draw using LINES instead of TRIANGLE_STRIP - * @param {PIXI.LINE_CAP}[options.cap=PIXI.LINE_CAP.BUTT] - line cap style - * @param {PIXI.LINE_JOIN}[options.join=PIXI.LINE_JOIN.MITER] - line join style - * @param {number}[options.miterLimit=10] - miter limit ratio - * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls - */ - Graphics.prototype.lineTextureStyle = function (options) { - // backward compatibility with params: (width, texture, - // color, alpha, matrix, alignment, native) - if (typeof options === 'number') { - deprecation('v5.2.0', 'Please use object-based options for Graphics#lineTextureStyle'); - // eslint-disable-next-line - var _a = arguments, width = _a[0], texture = _a[1], color = _a[2], alpha = _a[3], matrix = _a[4], alignment = _a[5], native = _a[6]; - options = { width: width, texture: texture, color: color, alpha: alpha, matrix: matrix, alignment: alignment, native: native }; - // Remove undefined keys - Object.keys(options).forEach(function (key) { return options[key] === undefined && delete options[key]; }); - } - // Apply defaults - options = Object.assign({ - width: 0, - texture: Texture.WHITE, - color: (options && options.texture) ? 0xFFFFFF : 0x0, - alpha: 1, - matrix: null, - alignment: 0.5, - native: false, - cap: exports.LINE_CAP.BUTT, - join: exports.LINE_JOIN.MITER, - miterLimit: 10, - }, options); - if (this.currentPath) { - this.startPoly(); - } - var visible = options.width > 0 && options.alpha > 0; - if (!visible) { - this._lineStyle.reset(); - } - else { - if (options.matrix) { - options.matrix = options.matrix.clone(); - options.matrix.invert(); - } - Object.assign(this._lineStyle, { visible: visible }, options); - } - return this; - }; - /** - * Start a polygon object internally - * @protected - */ - Graphics.prototype.startPoly = function () { - if (this.currentPath) { - var points = this.currentPath.points; - var len = this.currentPath.points.length; - if (len > 2) { - this.drawShape(this.currentPath); - this.currentPath = new Polygon(); - this.currentPath.closeStroke = false; - this.currentPath.points.push(points[len - 2], points[len - 1]); - } - } - else { - this.currentPath = new Polygon(); - this.currentPath.closeStroke = false; - } - }; - /** - * Finish the polygon object. - * @protected - */ - Graphics.prototype.finishPoly = function () { - if (this.currentPath) { - if (this.currentPath.points.length > 2) { - this.drawShape(this.currentPath); - this.currentPath = null; - } - else { - this.currentPath.points.length = 0; - } - } - }; - /** - * Moves the current drawing position to x, y. - * - * @param {number} x - the X coordinate to move to - * @param {number} y - the Y coordinate to move to - * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls - */ - Graphics.prototype.moveTo = function (x, y) { - this.startPoly(); - this.currentPath.points[0] = x; - this.currentPath.points[1] = y; - return this; - }; - /** - * Draws a line using the current line style from the current drawing position to (x, y); - * The current drawing position is then set to (x, y). - * - * @param {number} x - the X coordinate to draw to - * @param {number} y - the Y coordinate to draw to - * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls - */ - Graphics.prototype.lineTo = function (x, y) { - if (!this.currentPath) { - this.moveTo(0, 0); - } - // remove duplicates.. - var points = this.currentPath.points; - var fromX = points[points.length - 2]; - var fromY = points[points.length - 1]; - if (fromX !== x || fromY !== y) { - points.push(x, y); - } - return this; - }; - /** - * Initialize the curve - * - * @protected - * @param {number} [x=0] - * @param {number} [y=0] - */ - Graphics.prototype._initCurve = function (x, y) { - if (x === void 0) { x = 0; } - if (y === void 0) { y = 0; } - if (this.currentPath) { - if (this.currentPath.points.length === 0) { - this.currentPath.points = [x, y]; - } - } - else { - this.moveTo(x, y); - } - }; - /** - * Calculate the points for a quadratic bezier curve and then draws it. - * Based on: https://stackoverflow.com/questions/785097/how-do-i-implement-a-bezier-curve-in-c - * - * @param {number} cpX - Control point x - * @param {number} cpY - Control point y - * @param {number} toX - Destination point x - * @param {number} toY - Destination point y - * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls - */ - Graphics.prototype.quadraticCurveTo = function (cpX, cpY, toX, toY) { - this._initCurve(); - var points = this.currentPath.points; - if (points.length === 0) { - this.moveTo(0, 0); - } - QuadraticUtils.curveTo(cpX, cpY, toX, toY, points); - return this; - }; - /** - * Calculate the points for a bezier curve and then draws it. - * - * @param {number} cpX - Control point x - * @param {number} cpY - Control point y - * @param {number} cpX2 - Second Control point x - * @param {number} cpY2 - Second Control point y - * @param {number} toX - Destination point x - * @param {number} toY - Destination point y - * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls - */ - Graphics.prototype.bezierCurveTo = function (cpX, cpY, cpX2, cpY2, toX, toY) { - this._initCurve(); - BezierUtils.curveTo(cpX, cpY, cpX2, cpY2, toX, toY, this.currentPath.points); - return this; - }; - /** - * The arcTo() method creates an arc/curve between two tangents on the canvas. - * - * "borrowed" from https://code.google.com/p/fxcanvas/ - thanks google! - * - * @param {number} x1 - The x-coordinate of the first tangent point of the arc - * @param {number} y1 - The y-coordinate of the first tangent point of the arc - * @param {number} x2 - The x-coordinate of the end of the arc - * @param {number} y2 - The y-coordinate of the end of the arc - * @param {number} radius - The radius of the arc - * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls - */ - Graphics.prototype.arcTo = function (x1, y1, x2, y2, radius) { - this._initCurve(x1, y1); - var points = this.currentPath.points; - var result = ArcUtils.curveTo(x1, y1, x2, y2, radius, points); - if (result) { - var cx = result.cx, cy = result.cy, radius_1 = result.radius, startAngle = result.startAngle, endAngle = result.endAngle, anticlockwise = result.anticlockwise; - this.arc(cx, cy, radius_1, startAngle, endAngle, anticlockwise); - } - return this; - }; - /** - * The arc method creates an arc/curve (used to create circles, or parts of circles). - * - * @param {number} cx - The x-coordinate of the center of the circle - * @param {number} cy - The y-coordinate of the center of the circle - * @param {number} radius - The radius of the circle - * @param {number} startAngle - The starting angle, in radians (0 is at the 3 o'clock position - * of the arc's circle) - * @param {number} endAngle - The ending angle, in radians - * @param {boolean} [anticlockwise=false] - Specifies whether the drawing should be - * counter-clockwise or clockwise. False is default, and indicates clockwise, while true - * indicates counter-clockwise. - * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls - */ - Graphics.prototype.arc = function (cx, cy, radius, startAngle, endAngle, anticlockwise) { - if (anticlockwise === void 0) { anticlockwise = false; } - if (startAngle === endAngle) { - return this; - } - if (!anticlockwise && endAngle <= startAngle) { - endAngle += PI_2; - } - else if (anticlockwise && startAngle <= endAngle) { - startAngle += PI_2; - } - var sweep = endAngle - startAngle; - if (sweep === 0) { - return this; - } - var startX = cx + (Math.cos(startAngle) * radius); - var startY = cy + (Math.sin(startAngle) * radius); - var eps = this._geometry.closePointEps; - // If the currentPath exists, take its points. Otherwise call `moveTo` to start a path. - var points = this.currentPath ? this.currentPath.points : null; - if (points) { - // TODO: make a better fix. - // We check how far our start is from the last existing point - var xDiff = Math.abs(points[points.length - 2] - startX); - var yDiff = Math.abs(points[points.length - 1] - startY); - if (xDiff < eps && yDiff < eps) { ; } - else { - points.push(startX, startY); - } - } - else { - this.moveTo(startX, startY); - points = this.currentPath.points; - } - ArcUtils.arc(startX, startY, cx, cy, radius, startAngle, endAngle, anticlockwise, points); - return this; - }; - /** - * Specifies a simple one-color fill that subsequent calls to other Graphics methods - * (such as lineTo() or drawCircle()) use when drawing. - * - * @param {number} [color=0] - the color of the fill - * @param {number} [alpha=1] - the alpha of the fill - * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls - */ - Graphics.prototype.beginFill = function (color, alpha) { - if (color === void 0) { color = 0; } - if (alpha === void 0) { alpha = 1; } - return this.beginTextureFill({ texture: Texture.WHITE, color: color, alpha: alpha }); - }; - /** - * Begin the texture fill - * - * @param {object} [options] - Object object. - * @param {PIXI.Texture} [options.texture=PIXI.Texture.WHITE] - Texture to fill - * @param {number} [options.color=0xffffff] - Background to fill behind texture - * @param {number} [options.alpha=1] - Alpha of fill - * @param {PIXI.Matrix} [options.matrix=null] - Transform matrix - * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls - */ - Graphics.prototype.beginTextureFill = function (options) { - // backward compatibility with params: (texture, color, alpha, matrix) - if (options instanceof Texture) { - deprecation('v5.2.0', 'Please use object-based options for Graphics#beginTextureFill'); - // eslint-disable-next-line - var _a = arguments, texture = _a[0], color = _a[1], alpha = _a[2], matrix = _a[3]; - options = { texture: texture, color: color, alpha: alpha, matrix: matrix }; - // Remove undefined keys - Object.keys(options).forEach(function (key) { return options[key] === undefined && delete options[key]; }); - } - // Apply defaults - options = Object.assign({ - texture: Texture.WHITE, - color: 0xFFFFFF, - alpha: 1, - matrix: null, - }, options); - if (this.currentPath) { - this.startPoly(); - } - var visible = options.alpha > 0; - if (!visible) { - this._fillStyle.reset(); - } - else { - if (options.matrix) { - options.matrix = options.matrix.clone(); - options.matrix.invert(); - } - Object.assign(this._fillStyle, { visible: visible }, options); - } - return this; - }; - /** - * Applies a fill to the lines and shapes that were added since the last call to the beginFill() method. - * - * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls - */ - Graphics.prototype.endFill = function () { - this.finishPoly(); - this._fillStyle.reset(); - return this; - }; - /** - * Draws a rectangle shape. - * - * @param {number} x - The X coord of the top-left of the rectangle - * @param {number} y - The Y coord of the top-left of the rectangle - * @param {number} width - The width of the rectangle - * @param {number} height - The height of the rectangle - * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls - */ - Graphics.prototype.drawRect = function (x, y, width, height) { - return this.drawShape(new Rectangle(x, y, width, height)); - }; - /** - * Draw a rectangle shape with rounded/beveled corners. - * - * @param {number} x - The X coord of the top-left of the rectangle - * @param {number} y - The Y coord of the top-left of the rectangle - * @param {number} width - The width of the rectangle - * @param {number} height - The height of the rectangle - * @param {number} radius - Radius of the rectangle corners - * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls - */ - Graphics.prototype.drawRoundedRect = function (x, y, width, height, radius) { - return this.drawShape(new RoundedRectangle(x, y, width, height, radius)); - }; - /** - * Draws a circle. - * - * @param {number} x - The X coordinate of the center of the circle - * @param {number} y - The Y coordinate of the center of the circle - * @param {number} radius - The radius of the circle - * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls - */ - Graphics.prototype.drawCircle = function (x, y, radius) { - return this.drawShape(new Circle(x, y, radius)); - }; - /** - * Draws an ellipse. - * - * @param {number} x - The X coordinate of the center of the ellipse - * @param {number} y - The Y coordinate of the center of the ellipse - * @param {number} width - The half width of the ellipse - * @param {number} height - The half height of the ellipse - * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls - */ - Graphics.prototype.drawEllipse = function (x, y, width, height) { - return this.drawShape(new Ellipse(x, y, width, height)); - }; - /** - * Draws a polygon using the given path. - * - * @param {number[]|PIXI.Point[]|PIXI.Polygon} path - The path data used to construct the polygon. - * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls - */ - Graphics.prototype.drawPolygon = function () { - var arguments$1 = arguments; - - var path = []; - for (var _i = 0; _i < arguments.length; _i++) { - path[_i] = arguments$1[_i]; - } - var points; - var closeStroke = true; // !!this._fillStyle; - var poly = path[0]; - // check if data has points.. - if (poly.points) { - closeStroke = poly.closeStroke; - points = poly.points; - } - else if (Array.isArray(path[0])) { - points = path[0]; - } - else { - points = path; - } - var shape = new Polygon(points); - shape.closeStroke = closeStroke; - this.drawShape(shape); - return this; - }; - /** - * Draw any shape. - * - * @param {PIXI.Circle|PIXI.Ellipse|PIXI.Polygon|PIXI.Rectangle|PIXI.RoundedRectangle} shape - Shape to draw - * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls - */ - Graphics.prototype.drawShape = function (shape) { - if (!this._holeMode) { - this._geometry.drawShape(shape, this._fillStyle.clone(), this._lineStyle.clone(), this._matrix); - } - else { - this._geometry.drawHole(shape, this._matrix); - } - return this; - }; - /** - * Draw a star shape with an arbitrary number of points. - * - * @param {number} x - Center X position of the star - * @param {number} y - Center Y position of the star - * @param {number} points - The number of points of the star, must be > 1 - * @param {number} radius - The outer radius of the star - * @param {number} [innerRadius] - The inner radius between points, default half `radius` - * @param {number} [rotation=0] - The rotation of the star in radians, where 0 is vertical - * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls - */ - Graphics.prototype.drawStar = function (x, y, points, radius, innerRadius, rotation) { - if (rotation === void 0) { rotation = 0; } - return this.drawPolygon(new Star(x, y, points, radius, innerRadius, rotation)); - }; - /** - * Clears the graphics that were drawn to this Graphics object, and resets fill and line style settings. - * - * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls - */ - Graphics.prototype.clear = function () { - this._geometry.clear(); - this._lineStyle.reset(); - this._fillStyle.reset(); - this._boundsID++; - this._matrix = null; - this._holeMode = false; - this.currentPath = null; - return this; - }; - /** - * True if graphics consists of one rectangle, and thus, can be drawn like a Sprite and - * masked with gl.scissor. - * - * @returns {boolean} True if only 1 rect. - */ - Graphics.prototype.isFastRect = function () { - var data = this._geometry.graphicsData; - return data.length === 1 - && data[0].shape.type === exports.SHAPES.RECT - && !(data[0].lineStyle.visible && data[0].lineStyle.width); - }; - /** - * Renders the object using the WebGL renderer - * - * @protected - * @param {PIXI.Renderer} renderer - The renderer - */ - Graphics.prototype._render = function (renderer) { - this.finishPoly(); - var geometry = this._geometry; - var hasuit32 = renderer.context.supports.uint32Indices; - // batch part.. - // batch it! - geometry.updateBatches(hasuit32); - if (geometry.batchable) { - if (this.batchDirty !== geometry.batchDirty) { - this._populateBatches(); - } - this._renderBatched(renderer); - } - else { - // no batching... - renderer.batch.flush(); - this._renderDirect(renderer); - } - }; - /** - * Populating batches for rendering - * - * @protected - */ - Graphics.prototype._populateBatches = function () { - var geometry = this._geometry; - var blendMode = this.blendMode; - var len = geometry.batches.length; - this.batchTint = -1; - this._transformID = -1; - this.batchDirty = geometry.batchDirty; - this.batches.length = len; - this.vertexData = new Float32Array(geometry.points); - for (var i = 0; i < len; i++) { - var gI = geometry.batches[i]; - var color = gI.style.color; - var vertexData = new Float32Array(this.vertexData.buffer, gI.attribStart * 4 * 2, gI.attribSize * 2); - var uvs = new Float32Array(geometry.uvsFloat32.buffer, gI.attribStart * 4 * 2, gI.attribSize * 2); - var indices = new Uint16Array(geometry.indicesUint16.buffer, gI.start * 2, gI.size); - var batch = { - vertexData: vertexData, - blendMode: blendMode, - indices: indices, - uvs: uvs, - _batchRGB: hex2rgb(color), - _tintRGB: color, - _texture: gI.style.texture, - alpha: gI.style.alpha, - worldAlpha: 1 - }; - this.batches[i] = batch; - } - }; - /** - * Renders the batches using the BathedRenderer plugin - * - * @protected - * @param {PIXI.Renderer} renderer - The renderer - */ - Graphics.prototype._renderBatched = function (renderer) { - if (!this.batches.length) { - return; - } - renderer.batch.setObjectRenderer(renderer.plugins[this.pluginName]); - this.calculateVertices(); - this.calculateTints(); - for (var i = 0, l = this.batches.length; i < l; i++) { - var batch = this.batches[i]; - batch.worldAlpha = this.worldAlpha * batch.alpha; - renderer.plugins[this.pluginName].render(batch); - } - }; - /** - * Renders the graphics direct - * - * @protected - * @param {PIXI.Renderer} renderer - The renderer - */ - Graphics.prototype._renderDirect = function (renderer) { - var shader = this._resolveDirectShader(renderer); - var geometry = this._geometry; - var tint = this.tint; - var worldAlpha = this.worldAlpha; - var uniforms = shader.uniforms; - var drawCalls = geometry.drawCalls; - // lets set the transfomr - uniforms.translationMatrix = this.transform.worldTransform; - // and then lets set the tint.. - uniforms.tint[0] = (((tint >> 16) & 0xFF) / 255) * worldAlpha; - uniforms.tint[1] = (((tint >> 8) & 0xFF) / 255) * worldAlpha; - uniforms.tint[2] = ((tint & 0xFF) / 255) * worldAlpha; - uniforms.tint[3] = worldAlpha; - // the first draw call, we can set the uniforms of the shader directly here. - // this means that we can tack advantage of the sync function of pixi! - // bind and sync uniforms.. - // there is a way to optimise this.. - renderer.shader.bind(shader); - renderer.geometry.bind(geometry, shader); - // set state.. - renderer.state.set(this.state); - // then render the rest of them... - for (var i = 0, l = drawCalls.length; i < l; i++) { - this._renderDrawCallDirect(renderer, geometry.drawCalls[i]); - } - }; - /** - * Renders specific DrawCall - * - * @param {PIXI.Renderer} renderer - * @param {PIXI.BatchDrawCall} drawCall - */ - Graphics.prototype._renderDrawCallDirect = function (renderer, drawCall) { - var texArray = drawCall.texArray, type = drawCall.type, size = drawCall.size, start = drawCall.start; - var groupTextureCount = texArray.count; - for (var j = 0; j < groupTextureCount; j++) { - renderer.texture.bind(texArray.elements[j], j); - } - renderer.geometry.draw(type, size, start); - }; - /** - * Resolves shader for direct rendering - * - * @protected - * @param {PIXI.Renderer} renderer - The renderer - */ - Graphics.prototype._resolveDirectShader = function (renderer) { - var shader = this.shader; - var pluginName = this.pluginName; - if (!shader) { - // if there is no shader here, we can use the default shader. - // and that only gets created if we actually need it.. - // but may be more than one plugins for graphics - if (!DEFAULT_SHADERS[pluginName]) { - var sampleValues = new Int32Array(16); - for (var i = 0; i < 16; i++) { - sampleValues[i] = i; - } - var uniforms = { - tint: new Float32Array([1, 1, 1, 1]), - translationMatrix: new Matrix(), - default: UniformGroup.from({ uSamplers: sampleValues }, true), - }; - var program = renderer.plugins[pluginName]._shader.program; - DEFAULT_SHADERS[pluginName] = new Shader(program, uniforms); - } - shader = DEFAULT_SHADERS[pluginName]; - } - return shader; - }; - /** - * Retrieves the bounds of the graphic shape as a rectangle object - * - * @protected - */ - Graphics.prototype._calculateBounds = function () { - this.finishPoly(); - var geometry = this._geometry; - // skipping when graphics is empty, like a container - if (!geometry.graphicsData.length) { - return; - } - var _a = geometry.bounds, minX = _a.minX, minY = _a.minY, maxX = _a.maxX, maxY = _a.maxY; - this._bounds.addFrame(this.transform, minX, minY, maxX, maxY); - }; - /** - * Tests if a point is inside this graphics object - * - * @param {PIXI.IPointData} point - the point to test - * @return {boolean} the result of the test - */ - Graphics.prototype.containsPoint = function (point) { - this.worldTransform.applyInverse(point, Graphics._TEMP_POINT); - return this._geometry.containsPoint(Graphics._TEMP_POINT); - }; - /** - * Recalcuate the tint by applying tin to batches using Graphics tint. - * @protected - */ - Graphics.prototype.calculateTints = function () { - if (this.batchTint !== this.tint) { - this.batchTint = this.tint; - var tintRGB = hex2rgb(this.tint, temp); - for (var i = 0; i < this.batches.length; i++) { - var batch = this.batches[i]; - var batchTint = batch._batchRGB; - var r = (tintRGB[0] * batchTint[0]) * 255; - var g = (tintRGB[1] * batchTint[1]) * 255; - var b = (tintRGB[2] * batchTint[2]) * 255; - // TODO Ivan, can this be done in one go? - var color = (r << 16) + (g << 8) + (b | 0); - batch._tintRGB = (color >> 16) - + (color & 0xff00) - + ((color & 0xff) << 16); - } - } - }; - /** - * If there's a transform update or a change to the shape of the - * geometry, recaculate the vertices. - * @protected - */ - Graphics.prototype.calculateVertices = function () { - var wtID = this.transform._worldID; - if (this._transformID === wtID) { - return; - } - this._transformID = wtID; - var wt = this.transform.worldTransform; - var a = wt.a; - var b = wt.b; - var c = wt.c; - var d = wt.d; - var tx = wt.tx; - var ty = wt.ty; - var data = this._geometry.points; // batch.vertexDataOriginal; - var vertexData = this.vertexData; - var count = 0; - for (var i = 0; i < data.length; i += 2) { - var x = data[i]; - var y = data[i + 1]; - vertexData[count++] = (a * x) + (c * y) + tx; - vertexData[count++] = (d * y) + (b * x) + ty; - } - }; - /** - * Closes the current path. - * - * @return {PIXI.Graphics} Returns itself. - */ - Graphics.prototype.closePath = function () { - var currentPath = this.currentPath; - if (currentPath) { - // we don't need to add extra point in the end because buildLine will take care of that - currentPath.closeStroke = true; - } - return this; - }; - /** - * Apply a matrix to the positional data. - * - * @param {PIXI.Matrix} matrix - Matrix to use for transform current shape. - * @return {PIXI.Graphics} Returns itself. - */ - Graphics.prototype.setMatrix = function (matrix) { - this._matrix = matrix; - return this; - }; - /** - * Begin adding holes to the last draw shape - * IMPORTANT: holes must be fully inside a shape to work - * Also weirdness ensues if holes overlap! - * Ellipses, Circles, Rectangles and Rounded Rectangles cannot be holes or host for holes in CanvasRenderer, - * please use `moveTo` `lineTo`, `quadraticCurveTo` if you rely on pixi-legacy bundle. - * @return {PIXI.Graphics} Returns itself. - */ - Graphics.prototype.beginHole = function () { - this.finishPoly(); - this._holeMode = true; - return this; - }; - /** - * End adding holes to the last draw shape - * @return {PIXI.Graphics} Returns itself. - */ - Graphics.prototype.endHole = function () { - this.finishPoly(); - this._holeMode = false; - return this; - }; - /** - * Destroys the Graphics object. - * - * @param {object|boolean} [options] - Options parameter. A boolean will act as if all - * options have been set to that value - * @param {boolean} [options.children=false] - if set to true, all the children will have - * their destroy method called as well. 'options' will be passed on to those calls. - * @param {boolean} [options.texture=false] - Only used for child Sprites if options.children is set to true - * Should it destroy the texture of the child sprite - * @param {boolean} [options.baseTexture=false] - Only used for child Sprites if options.children is set to true - * Should it destroy the base texture of the child sprite - */ - Graphics.prototype.destroy = function (options) { - _super.prototype.destroy.call(this, options); - this._geometry.refCount--; - if (this._geometry.refCount === 0) { - this._geometry.dispose(); - } - this._matrix = null; - this.currentPath = null; - this._lineStyle.destroy(); - this._lineStyle = null; - this._fillStyle.destroy(); - this._fillStyle = null; - this._geometry = null; - this.shader = null; - this.vertexData = null; - this.batches.length = 0; - this.batches = null; - _super.prototype.destroy.call(this, options); - }; - /** - * Temporary point to use for containsPoint - * - * @static - * @private - * @member {PIXI.Point} - */ - Graphics._TEMP_POINT = new Point(); - return Graphics; - }(Container)); - - /*! - * @pixi/sprite - v5.3.3 - * Compiled Tue, 04 Aug 2020 16:23:09 UTC - * - * @pixi/sprite is licensed under the MIT License. - * http://www.opensource.org/licenses/mit-license - */ - - /*! ***************************************************************************** - Copyright (c) Microsoft Corporation. All rights reserved. - Licensed under the Apache License, Version 2.0 (the "License"); you may not use - this file except in compliance with the License. You may obtain a copy of the - License at http://www.apache.org/licenses/LICENSE-2.0 - - THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED - WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, - MERCHANTABLITY OR NON-INFRINGEMENT. - - See the Apache Version 2.0 License for specific language governing permissions - and limitations under the License. - ***************************************************************************** */ - /* global Reflect, Promise */ - - var extendStatics$6 = function(d, b) { - extendStatics$6 = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) { if (b.hasOwnProperty(p)) { d[p] = b[p]; } } }; - return extendStatics$6(d, b); - }; + function __extends$i(d, b) { + extendStatics$i(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + } - function __extends$6(d, b) { - extendStatics$6(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - } - - var tempPoint = new Point(); - var indices = new Uint16Array([0, 1, 2, 0, 2, 3]); - /** - * The Sprite object is the base for all textured objects that are rendered to the screen - * - * A sprite can be created directly from an image like this: - * - * ```js - * let sprite = PIXI.Sprite.from('assets/image.png'); - * ``` - * - * The more efficient way to create sprites is using a {@link PIXI.Spritesheet}, - * as swapping base textures when rendering to the screen is inefficient. - * - * ```js - * PIXI.Loader.shared.add("assets/spritesheet.json").load(setup); - * - * function setup() { - * let sheet = PIXI.Loader.shared.resources["assets/spritesheet.json"].spritesheet; - * let sprite = new PIXI.Sprite(sheet.textures["image.png"]); - * ... - * } - * ``` - * - * @class - * @extends PIXI.Container - * @memberof PIXI - */ - var Sprite = /** @class */ (function (_super) { - __extends$6(Sprite, _super); - /** - * @param {PIXI.Texture} [texture] - The texture for this sprite. - */ - function Sprite(texture) { - var _this = _super.call(this) || this; - /** - * The anchor point defines the normalized coordinates - * in the texture that map to the position of this - * sprite. - * - * By default, this is `(0,0)` (or `texture.defaultAnchor` - * if you have modified that), which means the position - * `(x,y)` of this `Sprite` will be the top-left corner. - * - * Note: Updating `texture.defaultAnchor` after - * constructing a `Sprite` does _not_ update its anchor. - * - * {@link https://docs.cocos2d-x.org/cocos2d-x/en/sprites/manipulation.html} - * - * @default `texture.defaultAnchor` - * @member {PIXI.ObservablePoint} - * @private - */ - _this._anchor = new ObservablePoint(_this._onAnchorUpdate, _this, (texture ? texture.defaultAnchor.x : 0), (texture ? texture.defaultAnchor.y : 0)); - /** - * The texture that the sprite is using - * - * @private - * @member {PIXI.Texture} - */ - _this._texture = null; - /** - * The width of the sprite (this is initially set by the texture) - * - * @protected - * @member {number} - */ - _this._width = 0; - /** - * The height of the sprite (this is initially set by the texture) - * - * @protected - * @member {number} - */ - _this._height = 0; - /** - * The tint applied to the sprite. This is a hex value. A value of 0xFFFFFF will remove any tint effect. - * - * @private - * @member {number} - * @default 0xFFFFFF - */ - _this._tint = null; - /** - * The tint applied to the sprite. This is a RGB value. A value of 0xFFFFFF will remove any tint effect. - * - * @private - * @member {number} - * @default 16777215 - */ - _this._tintRGB = null; - _this.tint = 0xFFFFFF; - /** - * The blend mode to be applied to the sprite. Apply a value of `PIXI.BLEND_MODES.NORMAL` to reset the blend mode. - * - * @member {number} - * @default PIXI.BLEND_MODES.NORMAL - * @see PIXI.BLEND_MODES - */ - _this.blendMode = exports.BLEND_MODES.NORMAL; - /** - * Cached tint value so we can tell when the tint is changed. - * Value is used for 2d CanvasRenderer. - * - * @protected - * @member {number} - * @default 0xFFFFFF - */ - _this._cachedTint = 0xFFFFFF; - /** - * this is used to store the uvs data of the sprite, assigned at the same time - * as the vertexData in calculateVertices() - * - * @private - * @member {Float32Array} - */ - _this.uvs = null; - // call texture setter - _this.texture = texture || Texture.EMPTY; - /** - * this is used to store the vertex data of the sprite (basically a quad) - * - * @private - * @member {Float32Array} - */ - _this.vertexData = new Float32Array(8); - /** - * This is used to calculate the bounds of the object IF it is a trimmed sprite - * - * @private - * @member {Float32Array} - */ - _this.vertexTrimmedData = null; - _this._transformID = -1; - _this._textureID = -1; - _this._transformTrimmedID = -1; - _this._textureTrimmedID = -1; - // Batchable stuff.. - // TODO could make this a mixin? - _this.indices = indices; - /** - * Plugin that is responsible for rendering this element. - * Allows to customize the rendering process without overriding '_render' & '_renderCanvas' methods. - * - * @member {string} - * @default 'batch' - */ - _this.pluginName = 'batch'; - /** - * used to fast check if a sprite is.. a sprite! - * @member {boolean} - */ - _this.isSprite = true; - /** - * Internal roundPixels field - * - * @member {boolean} - * @private - */ - _this._roundPixels = settings.ROUND_PIXELS; - return _this; - } - /** - * When the texture is updated, this event will fire to update the scale and frame - * - * @protected - */ - Sprite.prototype._onTextureUpdate = function () { - this._textureID = -1; - this._textureTrimmedID = -1; - this._cachedTint = 0xFFFFFF; - // so if _width is 0 then width was not set.. - if (this._width) { - this.scale.x = sign$1(this.scale.x) * this._width / this._texture.orig.width; - } - if (this._height) { - this.scale.y = sign$1(this.scale.y) * this._height / this._texture.orig.height; - } - }; - /** - * Called when the anchor position updates. - * - * @private - */ - Sprite.prototype._onAnchorUpdate = function () { - this._transformID = -1; - this._transformTrimmedID = -1; - }; - /** - * calculates worldTransform * vertices, store it in vertexData - */ - Sprite.prototype.calculateVertices = function () { - var texture = this._texture; - if (this._transformID === this.transform._worldID && this._textureID === texture._updateID) { - return; - } - // update texture UV here, because base texture can be changed without calling `_onTextureUpdate` - if (this._textureID !== texture._updateID) { - this.uvs = this._texture._uvs.uvsFloat32; - } - this._transformID = this.transform._worldID; - this._textureID = texture._updateID; - // set the vertex data - var wt = this.transform.worldTransform; - var a = wt.a; - var b = wt.b; - var c = wt.c; - var d = wt.d; - var tx = wt.tx; - var ty = wt.ty; - var vertexData = this.vertexData; - var trim = texture.trim; - var orig = texture.orig; - var anchor = this._anchor; - var w0 = 0; - var w1 = 0; - var h0 = 0; - var h1 = 0; - if (trim) { - // if the sprite is trimmed and is not a tilingsprite then we need to add the extra - // space before transforming the sprite coords. - w1 = trim.x - (anchor._x * orig.width); - w0 = w1 + trim.width; - h1 = trim.y - (anchor._y * orig.height); - h0 = h1 + trim.height; - } - else { - w1 = -anchor._x * orig.width; - w0 = w1 + orig.width; - h1 = -anchor._y * orig.height; - h0 = h1 + orig.height; - } - // xy - vertexData[0] = (a * w1) + (c * h1) + tx; - vertexData[1] = (d * h1) + (b * w1) + ty; - // xy - vertexData[2] = (a * w0) + (c * h1) + tx; - vertexData[3] = (d * h1) + (b * w0) + ty; - // xy - vertexData[4] = (a * w0) + (c * h0) + tx; - vertexData[5] = (d * h0) + (b * w0) + ty; - // xy - vertexData[6] = (a * w1) + (c * h0) + tx; - vertexData[7] = (d * h0) + (b * w1) + ty; - if (this._roundPixels) { - var resolution = settings.RESOLUTION; - for (var i = 0; i < vertexData.length; ++i) { - vertexData[i] = Math.round((vertexData[i] * resolution | 0) / resolution); - } - } - }; - /** - * calculates worldTransform * vertices for a non texture with a trim. store it in vertexTrimmedData - * This is used to ensure that the true width and height of a trimmed texture is respected - */ - Sprite.prototype.calculateTrimmedVertices = function () { - if (!this.vertexTrimmedData) { - this.vertexTrimmedData = new Float32Array(8); - } - else if (this._transformTrimmedID === this.transform._worldID && this._textureTrimmedID === this._texture._updateID) { - return; - } - this._transformTrimmedID = this.transform._worldID; - this._textureTrimmedID = this._texture._updateID; - // lets do some special trim code! - var texture = this._texture; - var vertexData = this.vertexTrimmedData; - var orig = texture.orig; - var anchor = this._anchor; - // lets calculate the new untrimmed bounds.. - var wt = this.transform.worldTransform; - var a = wt.a; - var b = wt.b; - var c = wt.c; - var d = wt.d; - var tx = wt.tx; - var ty = wt.ty; - var w1 = -anchor._x * orig.width; - var w0 = w1 + orig.width; - var h1 = -anchor._y * orig.height; - var h0 = h1 + orig.height; - // xy - vertexData[0] = (a * w1) + (c * h1) + tx; - vertexData[1] = (d * h1) + (b * w1) + ty; - // xy - vertexData[2] = (a * w0) + (c * h1) + tx; - vertexData[3] = (d * h1) + (b * w0) + ty; - // xy - vertexData[4] = (a * w0) + (c * h0) + tx; - vertexData[5] = (d * h0) + (b * w0) + ty; - // xy - vertexData[6] = (a * w1) + (c * h0) + tx; - vertexData[7] = (d * h0) + (b * w1) + ty; - }; - /** - * - * Renders the object using the WebGL renderer - * - * @protected - * @param {PIXI.Renderer} renderer - The webgl renderer to use. - */ - Sprite.prototype._render = function (renderer) { - this.calculateVertices(); - renderer.batch.setObjectRenderer(renderer.plugins[this.pluginName]); - renderer.plugins[this.pluginName].render(this); - }; - /** - * Updates the bounds of the sprite. - * - * @protected - */ - Sprite.prototype._calculateBounds = function () { - var trim = this._texture.trim; - var orig = this._texture.orig; - // First lets check to see if the current texture has a trim.. - if (!trim || (trim.width === orig.width && trim.height === orig.height)) { - // no trim! lets use the usual calculations.. - this.calculateVertices(); - this._bounds.addQuad(this.vertexData); - } - else { - // lets calculate a special trimmed bounds... - this.calculateTrimmedVertices(); - this._bounds.addQuad(this.vertexTrimmedData); - } - }; - /** - * Gets the local bounds of the sprite object. - * - * @param {PIXI.Rectangle} [rect] - The output rectangle. - * @return {PIXI.Rectangle} The bounds. - */ - Sprite.prototype.getLocalBounds = function (rect) { - // we can do a fast local bounds if the sprite has no children! - if (this.children.length === 0) { - this._bounds.minX = this._texture.orig.width * -this._anchor._x; - this._bounds.minY = this._texture.orig.height * -this._anchor._y; - this._bounds.maxX = this._texture.orig.width * (1 - this._anchor._x); - this._bounds.maxY = this._texture.orig.height * (1 - this._anchor._y); - if (!rect) { - if (!this._localBoundsRect) { - this._localBoundsRect = new Rectangle(); - } - rect = this._localBoundsRect; - } - return this._bounds.getRectangle(rect); - } - return _super.prototype.getLocalBounds.call(this, rect); - }; - /** - * Tests if a point is inside this sprite - * - * @param {PIXI.IPointData} point - the point to test - * @return {boolean} the result of the test - */ - Sprite.prototype.containsPoint = function (point) { - this.worldTransform.applyInverse(point, tempPoint); - var width = this._texture.orig.width; - var height = this._texture.orig.height; - var x1 = -width * this.anchor.x; - var y1 = 0; - if (tempPoint.x >= x1 && tempPoint.x < x1 + width) { - y1 = -height * this.anchor.y; - if (tempPoint.y >= y1 && tempPoint.y < y1 + height) { - return true; - } - } - return false; - }; - /** - * Destroys this sprite and optionally its texture and children - * - * @param {object|boolean} [options] - Options parameter. A boolean will act as if all options - * have been set to that value - * @param {boolean} [options.children=false] - if set to true, all the children will have their destroy - * method called as well. 'options' will be passed on to those calls. - * @param {boolean} [options.texture=false] - Should it destroy the current texture of the sprite as well - * @param {boolean} [options.baseTexture=false] - Should it destroy the base texture of the sprite as well - */ - Sprite.prototype.destroy = function (options) { - _super.prototype.destroy.call(this, options); - this._texture.off('update', this._onTextureUpdate, this); - this._anchor = null; - var destroyTexture = typeof options === 'boolean' ? options : options && options.texture; - if (destroyTexture) { - var destroyBaseTexture = typeof options === 'boolean' ? options : options && options.baseTexture; - this._texture.destroy(!!destroyBaseTexture); - } - this._texture = null; - }; - // some helper functions.. - /** - * Helper function that creates a new sprite based on the source you provide. - * The source can be - frame id, image url, video url, canvas element, video element, base texture - * - * @static - * @param {string|PIXI.Texture|HTMLCanvasElement|HTMLVideoElement} source - Source to create texture from - * @param {object} [options] - See {@link PIXI.BaseTexture}'s constructor for options. - * @return {PIXI.Sprite} The newly created sprite - */ - Sprite.from = function (source, options) { - var texture = (source instanceof Texture) - ? source - : Texture.from(source, options); - return new Sprite(texture); - }; - Object.defineProperty(Sprite.prototype, "roundPixels", { - get: function () { - return this._roundPixels; - }, - /** - * If true PixiJS will Math.floor() x/y values when rendering, stopping pixel interpolation. - * Advantages can include sharper image quality (like text) and faster rendering on canvas. - * The main disadvantage is movement of objects may appear less smooth. - * To set the global default, change {@link PIXI.settings.ROUND_PIXELS} - * - * @member {boolean} - * @default false - */ - set: function (value) { - if (this._roundPixels !== value) { - this._transformID = -1; - } - this._roundPixels = value; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(Sprite.prototype, "width", { - /** - * The width of the sprite, setting this will actually modify the scale to achieve the value set - * - * @member {number} - */ - get: function () { - return Math.abs(this.scale.x) * this._texture.orig.width; - }, - set: function (value) { - var s = sign$1(this.scale.x) || 1; - this.scale.x = s * value / this._texture.orig.width; - this._width = value; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(Sprite.prototype, "height", { - /** - * The height of the sprite, setting this will actually modify the scale to achieve the value set - * - * @member {number} - */ - get: function () { - return Math.abs(this.scale.y) * this._texture.orig.height; - }, - set: function (value) { - var s = sign$1(this.scale.y) || 1; - this.scale.y = s * value / this._texture.orig.height; - this._height = value; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(Sprite.prototype, "anchor", { - /** - * The anchor sets the origin point of the sprite. The default value is taken from the {@link PIXI.Texture|Texture} - * and passed to the constructor. - * - * The default is `(0,0)`, this means the sprite's origin is the top left. - * - * Setting the anchor to `(0.5,0.5)` means the sprite's origin is centered. - * - * Setting the anchor to `(1,1)` would mean the sprite's origin point will be the bottom right corner. - * - * If you pass only single parameter, it will set both x and y to the same value as shown in the example below. - * - * @example - * const sprite = new PIXI.Sprite(texture); - * sprite.anchor.set(0.5); // This will set the origin to center. (0.5) is same as (0.5, 0.5). - * - * @member {PIXI.ObservablePoint} - */ - get: function () { - return this._anchor; - }, - set: function (value) { - this._anchor.copyFrom(value); - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(Sprite.prototype, "tint", { - /** - * The tint applied to the sprite. This is a hex value. - * A value of 0xFFFFFF will remove any tint effect. - * - * @member {number} - * @default 0xFFFFFF - */ - get: function () { - return this._tint; - }, - set: function (value) { - this._tint = value; - this._tintRGB = (value >> 16) + (value & 0xff00) + ((value & 0xff) << 16); - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(Sprite.prototype, "texture", { - /** - * The texture that the sprite is using - * - * @member {PIXI.Texture} - */ - get: function () { - return this._texture; - }, - set: function (value) { - if (this._texture === value) { - return; - } - if (this._texture) { - this._texture.off('update', this._onTextureUpdate, this); - } - this._texture = value || Texture.EMPTY; - this._cachedTint = 0xFFFFFF; - this._textureID = -1; - this._textureTrimmedID = -1; - if (value) { - // wait for the texture to load - if (value.baseTexture.valid) { - this._onTextureUpdate(); - } - else { - value.once('update', this._onTextureUpdate, this); - } - } - }, - enumerable: false, - configurable: true - }); - return Sprite; - }(Container)); - - /*! - * @pixi/text - v5.3.3 - * Compiled Tue, 04 Aug 2020 16:23:09 UTC - * - * @pixi/text is licensed under the MIT License. - * http://www.opensource.org/licenses/mit-license - */ - - /*! ***************************************************************************** - Copyright (c) Microsoft Corporation. All rights reserved. - Licensed under the Apache License, Version 2.0 (the "License"); you may not use - this file except in compliance with the License. You may obtain a copy of the - License at http://www.apache.org/licenses/LICENSE-2.0 + var __assign = function() { + __assign = Object.assign || function __assign(t) { + var arguments$1 = arguments; - THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED - WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, - MERCHANTABLITY OR NON-INFRINGEMENT. + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments$1[i]; + for (var p in s) { if (Object.prototype.hasOwnProperty.call(s, p)) { t[p] = s[p]; } } + } + return t; + }; + return __assign.apply(this, arguments); + }; - See the Apache Version 2.0 License for specific language governing permissions - and limitations under the License. - ***************************************************************************** */ - /* global Reflect, Promise */ + function __rest(s, e) { + var t = {}; + for (var p in s) { if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) + { t[p] = s[p]; } } + if (s != null && typeof Object.getOwnPropertySymbols === "function") + { for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { + if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) + { t[p[i]] = s[p[i]]; } + } } + return t; + } + + /** + * Base resource class for textures that manages validation and uploading, depending on its type. + * + * Uploading of a base texture to the GPU is required. + * @memberof PIXI + */ + var Resource = /** @class */ (function () { + /** + * @param width - Width of the resource + * @param height - Height of the resource + */ + function Resource(width, height) { + if (width === void 0) { width = 0; } + if (height === void 0) { height = 0; } + this._width = width; + this._height = height; + this.destroyed = false; + this.internal = false; + this.onResize = new Runner('setRealSize'); + this.onUpdate = new Runner('update'); + this.onError = new Runner('onError'); + } + /** + * Bind to a parent BaseTexture + * @param baseTexture - Parent texture + */ + Resource.prototype.bind = function (baseTexture) { + this.onResize.add(baseTexture); + this.onUpdate.add(baseTexture); + this.onError.add(baseTexture); + // Call a resize immediate if we already + // have the width and height of the resource + if (this._width || this._height) { + this.onResize.emit(this._width, this._height); + } + }; + /** + * Unbind to a parent BaseTexture + * @param baseTexture - Parent texture + */ + Resource.prototype.unbind = function (baseTexture) { + this.onResize.remove(baseTexture); + this.onUpdate.remove(baseTexture); + this.onError.remove(baseTexture); + }; + /** + * Trigger a resize event + * @param width - X dimension + * @param height - Y dimension + */ + Resource.prototype.resize = function (width, height) { + if (width !== this._width || height !== this._height) { + this._width = width; + this._height = height; + this.onResize.emit(width, height); + } + }; + Object.defineProperty(Resource.prototype, "valid", { + /** + * Has been validated + * @readonly + */ + get: function () { + return !!this._width && !!this._height; + }, + enumerable: false, + configurable: true + }); + /** Has been updated trigger event. */ + Resource.prototype.update = function () { + if (!this.destroyed) { + this.onUpdate.emit(); + } + }; + /** + * This can be overridden to start preloading a resource + * or do any other prepare step. + * @protected + * @returns Handle the validate event + */ + Resource.prototype.load = function () { + return Promise.resolve(this); + }; + Object.defineProperty(Resource.prototype, "width", { + /** + * The width of the resource. + * @readonly + */ + get: function () { + return this._width; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(Resource.prototype, "height", { + /** + * The height of the resource. + * @readonly + */ + get: function () { + return this._height; + }, + enumerable: false, + configurable: true + }); + /** + * Set the style, optional to override + * @param _renderer - yeah, renderer! + * @param _baseTexture - the texture + * @param _glTexture - texture instance for this webgl context + * @returns - `true` is success + */ + Resource.prototype.style = function (_renderer, _baseTexture, _glTexture) { + return false; + }; + /** Clean up anything, this happens when destroying is ready. */ + Resource.prototype.dispose = function () { + // override + }; + /** + * Call when destroying resource, unbind any BaseTexture object + * before calling this method, as reference counts are maintained + * internally. + */ + Resource.prototype.destroy = function () { + if (!this.destroyed) { + this.destroyed = true; + this.dispose(); + this.onError.removeAll(); + this.onError = null; + this.onResize.removeAll(); + this.onResize = null; + this.onUpdate.removeAll(); + this.onUpdate = null; + } + }; + /** + * Abstract, used to auto-detect resource type. + * @param {*} _source - The source object + * @param {string} _extension - The extension of source, if set + */ + Resource.test = function (_source, _extension) { + return false; + }; + return Resource; + }()); + + /** + * @interface SharedArrayBuffer + */ + /** + * Buffer resource with data of typed array. + * @memberof PIXI + */ + var BufferResource = /** @class */ (function (_super) { + __extends$i(BufferResource, _super); + /** + * @param source - Source buffer + * @param options - Options + * @param {number} options.width - Width of the texture + * @param {number} options.height - Height of the texture + */ + function BufferResource(source, options) { + var _this = this; + var _a = options || {}, width = _a.width, height = _a.height; + if (!width || !height) { + throw new Error('BufferResource width or height invalid'); + } + _this = _super.call(this, width, height) || this; + _this.data = source; + return _this; + } + /** + * Upload the texture to the GPU. + * @param renderer - Upload to the renderer + * @param baseTexture - Reference to parent texture + * @param glTexture - glTexture + * @returns - true is success + */ + BufferResource.prototype.upload = function (renderer, baseTexture, glTexture) { + var gl = renderer.gl; + gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, baseTexture.alphaMode === exports.ALPHA_MODES.UNPACK); + var width = baseTexture.realWidth; + var height = baseTexture.realHeight; + if (glTexture.width === width && glTexture.height === height) { + gl.texSubImage2D(baseTexture.target, 0, 0, 0, width, height, baseTexture.format, glTexture.type, this.data); + } + else { + glTexture.width = width; + glTexture.height = height; + gl.texImage2D(baseTexture.target, 0, glTexture.internalFormat, width, height, 0, baseTexture.format, glTexture.type, this.data); + } + return true; + }; + /** Destroy and don't use after this. */ + BufferResource.prototype.dispose = function () { + this.data = null; + }; + /** + * Used to auto-detect the type of resource. + * @param {*} source - The source object + * @returns {boolean} `true` if + */ + BufferResource.test = function (source) { + return source instanceof Float32Array + || source instanceof Uint8Array + || source instanceof Uint32Array; + }; + return BufferResource; + }(Resource)); + + var defaultBufferOptions = { + scaleMode: exports.SCALE_MODES.NEAREST, + format: exports.FORMATS.RGBA, + alphaMode: exports.ALPHA_MODES.NPM, + }; + /** + * A Texture stores the information that represents an image. + * All textures have a base texture, which contains information about the source. + * Therefore you can have many textures all using a single BaseTexture + * @memberof PIXI + * @typeParam R - The BaseTexture's Resource type. + * @typeParam RO - The options for constructing resource. + */ + var BaseTexture = /** @class */ (function (_super) { + __extends$i(BaseTexture, _super); + /** + * @param {PIXI.Resource|string|HTMLImageElement|HTMLCanvasElement|HTMLVideoElement} [resource=null] - + * The current resource to use, for things that aren't Resource objects, will be converted + * into a Resource. + * @param options - Collection of options + * @param {PIXI.MIPMAP_MODES} [options.mipmap=PIXI.settings.MIPMAP_TEXTURES] - If mipmapping is enabled for texture + * @param {number} [options.anisotropicLevel=PIXI.settings.ANISOTROPIC_LEVEL] - Anisotropic filtering level of texture + * @param {PIXI.WRAP_MODES} [options.wrapMode=PIXI.settings.WRAP_MODE] - Wrap mode for textures + * @param {PIXI.SCALE_MODES} [options.scaleMode=PIXI.settings.SCALE_MODE] - Default scale mode, linear, nearest + * @param {PIXI.FORMATS} [options.format=PIXI.FORMATS.RGBA] - GL format type + * @param {PIXI.TYPES} [options.type=PIXI.TYPES.UNSIGNED_BYTE] - GL data type + * @param {PIXI.TARGETS} [options.target=PIXI.TARGETS.TEXTURE_2D] - GL texture target + * @param {PIXI.ALPHA_MODES} [options.alphaMode=PIXI.ALPHA_MODES.UNPACK] - Pre multiply the image alpha + * @param {number} [options.width=0] - Width of the texture + * @param {number} [options.height=0] - Height of the texture + * @param {number} [options.resolution=PIXI.settings.RESOLUTION] - Resolution of the base texture + * @param {object} [options.resourceOptions] - Optional resource options, + * see {@link PIXI.autoDetectResource autoDetectResource} + */ + function BaseTexture(resource, options) { + if (resource === void 0) { resource = null; } + if (options === void 0) { options = null; } + var _this = _super.call(this) || this; + options = options || {}; + var alphaMode = options.alphaMode, mipmap = options.mipmap, anisotropicLevel = options.anisotropicLevel, scaleMode = options.scaleMode, width = options.width, height = options.height, wrapMode = options.wrapMode, format = options.format, type = options.type, target = options.target, resolution = options.resolution, resourceOptions = options.resourceOptions; + // Convert the resource to a Resource object + if (resource && !(resource instanceof Resource)) { + resource = autoDetectResource(resource, resourceOptions); + resource.internal = true; + } + _this.resolution = resolution || settings$1.RESOLUTION; + _this.width = Math.round((width || 0) * _this.resolution) / _this.resolution; + _this.height = Math.round((height || 0) * _this.resolution) / _this.resolution; + _this._mipmap = mipmap !== undefined ? mipmap : settings$1.MIPMAP_TEXTURES; + _this.anisotropicLevel = anisotropicLevel !== undefined ? anisotropicLevel : settings$1.ANISOTROPIC_LEVEL; + _this._wrapMode = wrapMode || settings$1.WRAP_MODE; + _this._scaleMode = scaleMode !== undefined ? scaleMode : settings$1.SCALE_MODE; + _this.format = format || exports.FORMATS.RGBA; + _this.type = type || exports.TYPES.UNSIGNED_BYTE; + _this.target = target || exports.TARGETS.TEXTURE_2D; + _this.alphaMode = alphaMode !== undefined ? alphaMode : exports.ALPHA_MODES.UNPACK; + _this.uid = uid(); + _this.touched = 0; + _this.isPowerOfTwo = false; + _this._refreshPOT(); + _this._glTextures = {}; + _this.dirtyId = 0; + _this.dirtyStyleId = 0; + _this.cacheId = null; + _this.valid = width > 0 && height > 0; + _this.textureCacheIds = []; + _this.destroyed = false; + _this.resource = null; + _this._batchEnabled = 0; + _this._batchLocation = 0; + _this.parentTextureArray = null; + /** + * Fired when a not-immediately-available source finishes loading. + * @protected + * @event PIXI.BaseTexture#loaded + * @param {PIXI.BaseTexture} baseTexture - Resource loaded. + */ + /** + * Fired when a not-immediately-available source fails to load. + * @protected + * @event PIXI.BaseTexture#error + * @param {PIXI.BaseTexture} baseTexture - Resource errored. + * @param {ErrorEvent} event - Load error event. + */ + /** + * Fired when BaseTexture is updated. + * @protected + * @event PIXI.BaseTexture#loaded + * @param {PIXI.BaseTexture} baseTexture - Resource loaded. + */ + /** + * Fired when BaseTexture is updated. + * @protected + * @event PIXI.BaseTexture#update + * @param {PIXI.BaseTexture} baseTexture - Instance of texture being updated. + */ + /** + * Fired when BaseTexture is destroyed. + * @protected + * @event PIXI.BaseTexture#dispose + * @param {PIXI.BaseTexture} baseTexture - Instance of texture being destroyed. + */ + // Set the resource + _this.setResource(resource); + return _this; + } + Object.defineProperty(BaseTexture.prototype, "realWidth", { + /** + * Pixel width of the source of this texture + * @readonly + */ + get: function () { + return Math.round(this.width * this.resolution); + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(BaseTexture.prototype, "realHeight", { + /** + * Pixel height of the source of this texture + * @readonly + */ + get: function () { + return Math.round(this.height * this.resolution); + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(BaseTexture.prototype, "mipmap", { + /** + * Mipmap mode of the texture, affects downscaled images + * @default PIXI.settings.MIPMAP_TEXTURES + */ + get: function () { + return this._mipmap; + }, + set: function (value) { + if (this._mipmap !== value) { + this._mipmap = value; + this.dirtyStyleId++; + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(BaseTexture.prototype, "scaleMode", { + /** + * The scale mode to apply when scaling this texture + * @default PIXI.settings.SCALE_MODE + */ + get: function () { + return this._scaleMode; + }, + set: function (value) { + if (this._scaleMode !== value) { + this._scaleMode = value; + this.dirtyStyleId++; + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(BaseTexture.prototype, "wrapMode", { + /** + * How the texture wraps + * @default PIXI.settings.WRAP_MODE + */ + get: function () { + return this._wrapMode; + }, + set: function (value) { + if (this._wrapMode !== value) { + this._wrapMode = value; + this.dirtyStyleId++; + } + }, + enumerable: false, + configurable: true + }); + /** + * Changes style options of BaseTexture + * @param scaleMode - Pixi scalemode + * @param mipmap - enable mipmaps + * @returns - this + */ + BaseTexture.prototype.setStyle = function (scaleMode, mipmap) { + var dirty; + if (scaleMode !== undefined && scaleMode !== this.scaleMode) { + this.scaleMode = scaleMode; + dirty = true; + } + if (mipmap !== undefined && mipmap !== this.mipmap) { + this.mipmap = mipmap; + dirty = true; + } + if (dirty) { + this.dirtyStyleId++; + } + return this; + }; + /** + * Changes w/h/resolution. Texture becomes valid if width and height are greater than zero. + * @param desiredWidth - Desired visual width + * @param desiredHeight - Desired visual height + * @param resolution - Optionally set resolution + * @returns - this + */ + BaseTexture.prototype.setSize = function (desiredWidth, desiredHeight, resolution) { + resolution = resolution || this.resolution; + return this.setRealSize(desiredWidth * resolution, desiredHeight * resolution, resolution); + }; + /** + * Sets real size of baseTexture, preserves current resolution. + * @param realWidth - Full rendered width + * @param realHeight - Full rendered height + * @param resolution - Optionally set resolution + * @returns - this + */ + BaseTexture.prototype.setRealSize = function (realWidth, realHeight, resolution) { + this.resolution = resolution || this.resolution; + this.width = Math.round(realWidth) / this.resolution; + this.height = Math.round(realHeight) / this.resolution; + this._refreshPOT(); + this.update(); + return this; + }; + /** + * Refresh check for isPowerOfTwo texture based on size + * @private + */ + BaseTexture.prototype._refreshPOT = function () { + this.isPowerOfTwo = isPow2(this.realWidth) && isPow2(this.realHeight); + }; + /** + * Changes resolution + * @param resolution - res + * @returns - this + */ + BaseTexture.prototype.setResolution = function (resolution) { + var oldResolution = this.resolution; + if (oldResolution === resolution) { + return this; + } + this.resolution = resolution; + if (this.valid) { + this.width = Math.round(this.width * oldResolution) / resolution; + this.height = Math.round(this.height * oldResolution) / resolution; + this.emit('update', this); + } + this._refreshPOT(); + return this; + }; + /** + * Sets the resource if it wasn't set. Throws error if resource already present + * @param resource - that is managing this BaseTexture + * @returns - this + */ + BaseTexture.prototype.setResource = function (resource) { + if (this.resource === resource) { + return this; + } + if (this.resource) { + throw new Error('Resource can be set only once'); + } + resource.bind(this); + this.resource = resource; + return this; + }; + /** Invalidates the object. Texture becomes valid if width and height are greater than zero. */ + BaseTexture.prototype.update = function () { + if (!this.valid) { + if (this.width > 0 && this.height > 0) { + this.valid = true; + this.emit('loaded', this); + this.emit('update', this); + } + } + else { + this.dirtyId++; + this.dirtyStyleId++; + this.emit('update', this); + } + }; + /** + * Handle errors with resources. + * @private + * @param event - Error event emitted. + */ + BaseTexture.prototype.onError = function (event) { + this.emit('error', this, event); + }; + /** + * Destroys this base texture. + * The method stops if resource doesn't want this texture to be destroyed. + * Removes texture from all caches. + */ + BaseTexture.prototype.destroy = function () { + // remove and destroy the resource + if (this.resource) { + this.resource.unbind(this); + // only destroy resourced created internally + if (this.resource.internal) { + this.resource.destroy(); + } + this.resource = null; + } + if (this.cacheId) { + delete BaseTextureCache[this.cacheId]; + delete TextureCache[this.cacheId]; + this.cacheId = null; + } + // finally let the WebGL renderer know.. + this.dispose(); + BaseTexture.removeFromCache(this); + this.textureCacheIds = null; + this.destroyed = true; + }; + /** + * Frees the texture from WebGL memory without destroying this texture object. + * This means you can still use the texture later which will upload it to GPU + * memory again. + * @fires PIXI.BaseTexture#dispose + */ + BaseTexture.prototype.dispose = function () { + this.emit('dispose', this); + }; + /** Utility function for BaseTexture|Texture cast. */ + BaseTexture.prototype.castToBaseTexture = function () { + return this; + }; + /** + * Helper function that creates a base texture based on the source you provide. + * The source can be - image url, image element, canvas element. If the + * source is an image url or an image element and not in the base texture + * cache, it will be created and loaded. + * @static + * @param {string|string[]|HTMLImageElement|HTMLCanvasElement|SVGElement|HTMLVideoElement} source - The + * source to create base texture from. + * @param options - See {@link PIXI.BaseTexture}'s constructor for options. + * @param {string} [options.pixiIdPrefix=pixiid] - If a source has no id, this is the prefix of the generated id + * @param {boolean} [strict] - Enforce strict-mode, see {@link PIXI.settings.STRICT_TEXTURE_CACHE}. + * @returns {PIXI.BaseTexture} The new base texture. + */ + BaseTexture.from = function (source, options, strict) { + if (strict === void 0) { strict = settings$1.STRICT_TEXTURE_CACHE; } + var isFrame = typeof source === 'string'; + var cacheId = null; + if (isFrame) { + cacheId = source; + } + else { + if (!source._pixiId) { + var prefix = (options && options.pixiIdPrefix) || 'pixiid'; + source._pixiId = prefix + "_" + uid(); + } + cacheId = source._pixiId; + } + var baseTexture = BaseTextureCache[cacheId]; + // Strict-mode rejects invalid cacheIds + if (isFrame && strict && !baseTexture) { + throw new Error("The cacheId \"" + cacheId + "\" does not exist in BaseTextureCache."); + } + if (!baseTexture) { + baseTexture = new BaseTexture(source, options); + baseTexture.cacheId = cacheId; + BaseTexture.addToCache(baseTexture, cacheId); + } + return baseTexture; + }; + /** + * Create a new BaseTexture with a BufferResource from a Float32Array. + * RGBA values are floats from 0 to 1. + * @param {Float32Array|Uint8Array} buffer - The optional array to use, if no data + * is provided, a new Float32Array is created. + * @param width - Width of the resource + * @param height - Height of the resource + * @param options - See {@link PIXI.BaseTexture}'s constructor for options. + * Default properties are different from the constructor's defaults. + * @param {PIXI.FORMATS} [options.format=PIXI.FORMATS.RGBA] - GL format type + * @param {PIXI.ALPHA_MODES} [options.alphaMode=PIXI.ALPHA_MODES.NPM] - Image alpha, not premultiplied by default + * @param {PIXI.SCALE_MODES} [options.scaleMode=PIXI.SCALE_MODES.NEAREST] - Scale mode, pixelating by default + * @returns - The resulting new BaseTexture + */ + BaseTexture.fromBuffer = function (buffer, width, height, options) { + buffer = buffer || new Float32Array(width * height * 4); + var resource = new BufferResource(buffer, { width: width, height: height }); + var type = buffer instanceof Float32Array ? exports.TYPES.FLOAT : exports.TYPES.UNSIGNED_BYTE; + return new BaseTexture(resource, Object.assign(defaultBufferOptions, options || { width: width, height: height, type: type })); + }; + /** + * Adds a BaseTexture to the global BaseTextureCache. This cache is shared across the whole PIXI object. + * @param {PIXI.BaseTexture} baseTexture - The BaseTexture to add to the cache. + * @param {string} id - The id that the BaseTexture will be stored against. + */ + BaseTexture.addToCache = function (baseTexture, id) { + if (id) { + if (baseTexture.textureCacheIds.indexOf(id) === -1) { + baseTexture.textureCacheIds.push(id); + } + if (BaseTextureCache[id]) { + // eslint-disable-next-line no-console + console.warn("BaseTexture added to the cache with an id [" + id + "] that already had an entry"); + } + BaseTextureCache[id] = baseTexture; + } + }; + /** + * Remove a BaseTexture from the global BaseTextureCache. + * @param {string|PIXI.BaseTexture} baseTexture - id of a BaseTexture to be removed, or a BaseTexture instance itself. + * @returns {PIXI.BaseTexture|null} The BaseTexture that was removed. + */ + BaseTexture.removeFromCache = function (baseTexture) { + if (typeof baseTexture === 'string') { + var baseTextureFromCache = BaseTextureCache[baseTexture]; + if (baseTextureFromCache) { + var index = baseTextureFromCache.textureCacheIds.indexOf(baseTexture); + if (index > -1) { + baseTextureFromCache.textureCacheIds.splice(index, 1); + } + delete BaseTextureCache[baseTexture]; + return baseTextureFromCache; + } + } + else if (baseTexture && baseTexture.textureCacheIds) { + for (var i = 0; i < baseTexture.textureCacheIds.length; ++i) { + delete BaseTextureCache[baseTexture.textureCacheIds[i]]; + } + baseTexture.textureCacheIds.length = 0; + return baseTexture; + } + return null; + }; + /** Global number of the texture batch, used by multi-texture renderers. */ + BaseTexture._globalBatch = 0; + return BaseTexture; + }(eventemitter3)); + + /** + * Resource that can manage several resource (items) inside. + * All resources need to have the same pixel size. + * Parent class for CubeResource and ArrayResource + * @memberof PIXI + */ + var AbstractMultiResource = /** @class */ (function (_super) { + __extends$i(AbstractMultiResource, _super); + /** + * @param length + * @param options - Options to for Resource constructor + * @param {number} [options.width] - Width of the resource + * @param {number} [options.height] - Height of the resource + */ + function AbstractMultiResource(length, options) { + var _this = this; + var _a = options || {}, width = _a.width, height = _a.height; + _this = _super.call(this, width, height) || this; + _this.items = []; + _this.itemDirtyIds = []; + for (var i = 0; i < length; i++) { + var partTexture = new BaseTexture(); + _this.items.push(partTexture); + // -2 - first run of texture array upload + // -1 - texture item was allocated + // >=0 - texture item uploaded , in sync with items[i].dirtyId + _this.itemDirtyIds.push(-2); + } + _this.length = length; + _this._load = null; + _this.baseTexture = null; + return _this; + } + /** + * Used from ArrayResource and CubeResource constructors. + * @param resources - Can be resources, image elements, canvas, etc. , + * length should be same as constructor length + * @param options - Detect options for resources + */ + AbstractMultiResource.prototype.initFromArray = function (resources, options) { + for (var i = 0; i < this.length; i++) { + if (!resources[i]) { + continue; + } + if (resources[i].castToBaseTexture) { + this.addBaseTextureAt(resources[i].castToBaseTexture(), i); + } + else if (resources[i] instanceof Resource) { + this.addResourceAt(resources[i], i); + } + else { + this.addResourceAt(autoDetectResource(resources[i], options), i); + } + } + }; + /** Destroy this BaseImageResource. */ + AbstractMultiResource.prototype.dispose = function () { + for (var i = 0, len = this.length; i < len; i++) { + this.items[i].destroy(); + } + this.items = null; + this.itemDirtyIds = null; + this._load = null; + }; + /** + * Set a resource by ID + * @param resource + * @param index - Zero-based index of resource to set + * @returns - Instance for chaining + */ + AbstractMultiResource.prototype.addResourceAt = function (resource, index) { + if (!this.items[index]) { + throw new Error("Index " + index + " is out of bounds"); + } + // Inherit the first resource dimensions + if (resource.valid && !this.valid) { + this.resize(resource.width, resource.height); + } + this.items[index].setResource(resource); + return this; + }; + /** + * Set the parent base texture. + * @param baseTexture + */ + AbstractMultiResource.prototype.bind = function (baseTexture) { + if (this.baseTexture !== null) { + throw new Error('Only one base texture per TextureArray is allowed'); + } + _super.prototype.bind.call(this, baseTexture); + for (var i = 0; i < this.length; i++) { + this.items[i].parentTextureArray = baseTexture; + this.items[i].on('update', baseTexture.update, baseTexture); + } + }; + /** + * Unset the parent base texture. + * @param baseTexture + */ + AbstractMultiResource.prototype.unbind = function (baseTexture) { + _super.prototype.unbind.call(this, baseTexture); + for (var i = 0; i < this.length; i++) { + this.items[i].parentTextureArray = null; + this.items[i].off('update', baseTexture.update, baseTexture); + } + }; + /** + * Load all the resources simultaneously + * @returns - When load is resolved + */ + AbstractMultiResource.prototype.load = function () { + var _this = this; + if (this._load) { + return this._load; + } + var resources = this.items.map(function (item) { return item.resource; }).filter(function (item) { return item; }); + // TODO: also implement load part-by-part strategy + var promises = resources.map(function (item) { return item.load(); }); + this._load = Promise.all(promises) + .then(function () { + var _a = _this.items[0], realWidth = _a.realWidth, realHeight = _a.realHeight; + _this.resize(realWidth, realHeight); + return Promise.resolve(_this); + }); + return this._load; + }; + return AbstractMultiResource; + }(Resource)); + + /** + * A resource that contains a number of sources. + * @memberof PIXI + */ + var ArrayResource = /** @class */ (function (_super) { + __extends$i(ArrayResource, _super); + /** + * @param source - Number of items in array or the collection + * of image URLs to use. Can also be resources, image elements, canvas, etc. + * @param options - Options to apply to {@link PIXI.autoDetectResource} + * @param {number} [options.width] - Width of the resource + * @param {number} [options.height] - Height of the resource + */ + function ArrayResource(source, options) { + var _this = this; + var _a = options || {}, width = _a.width, height = _a.height; + var urls; + var length; + if (Array.isArray(source)) { + urls = source; + length = source.length; + } + else { + length = source; + } + _this = _super.call(this, length, { width: width, height: height }) || this; + if (urls) { + _this.initFromArray(urls, options); + } + return _this; + } + /** + * Set a baseTexture by ID, + * ArrayResource just takes resource from it, nothing more + * @param baseTexture + * @param index - Zero-based index of resource to set + * @returns - Instance for chaining + */ + ArrayResource.prototype.addBaseTextureAt = function (baseTexture, index) { + if (baseTexture.resource) { + this.addResourceAt(baseTexture.resource, index); + } + else { + throw new Error('ArrayResource does not support RenderTexture'); + } + return this; + }; + /** + * Add binding + * @param baseTexture + */ + ArrayResource.prototype.bind = function (baseTexture) { + _super.prototype.bind.call(this, baseTexture); + baseTexture.target = exports.TARGETS.TEXTURE_2D_ARRAY; + }; + /** + * Upload the resources to the GPU. + * @param renderer + * @param texture + * @param glTexture + * @returns - whether texture was uploaded + */ + ArrayResource.prototype.upload = function (renderer, texture, glTexture) { + var _a = this, length = _a.length, itemDirtyIds = _a.itemDirtyIds, items = _a.items; + var gl = renderer.gl; + if (glTexture.dirtyId < 0) { + gl.texImage3D(gl.TEXTURE_2D_ARRAY, 0, glTexture.internalFormat, this._width, this._height, length, 0, texture.format, glTexture.type, null); + } + for (var i = 0; i < length; i++) { + var item = items[i]; + if (itemDirtyIds[i] < item.dirtyId) { + itemDirtyIds[i] = item.dirtyId; + if (item.valid) { + gl.texSubImage3D(gl.TEXTURE_2D_ARRAY, 0, 0, // xoffset + 0, // yoffset + i, // zoffset + item.resource.width, item.resource.height, 1, texture.format, glTexture.type, item.resource.source); + } + } + } + return true; + }; + return ArrayResource; + }(AbstractMultiResource)); + + /** + * Base for all the image/canvas resources. + * @memberof PIXI + */ + var BaseImageResource = /** @class */ (function (_super) { + __extends$i(BaseImageResource, _super); + /** + * @param {HTMLImageElement|HTMLCanvasElement|HTMLVideoElement|SVGElement} source + */ + function BaseImageResource(source) { + var _this = this; + var sourceAny = source; + var width = sourceAny.naturalWidth || sourceAny.videoWidth || sourceAny.width; + var height = sourceAny.naturalHeight || sourceAny.videoHeight || sourceAny.height; + _this = _super.call(this, width, height) || this; + _this.source = source; + _this.noSubImage = false; + return _this; + } + /** + * Set cross origin based detecting the url and the crossorigin + * @param element - Element to apply crossOrigin + * @param url - URL to check + * @param crossorigin - Cross origin value to use + */ + BaseImageResource.crossOrigin = function (element, url, crossorigin) { + if (crossorigin === undefined && url.indexOf('data:') !== 0) { + element.crossOrigin = determineCrossOrigin(url); + } + else if (crossorigin !== false) { + element.crossOrigin = typeof crossorigin === 'string' ? crossorigin : 'anonymous'; + } + }; + /** + * Upload the texture to the GPU. + * @param renderer - Upload to the renderer + * @param baseTexture - Reference to parent texture + * @param glTexture + * @param {HTMLImageElement|HTMLCanvasElement|HTMLVideoElement|SVGElement} [source] - (optional) + * @returns - true is success + */ + BaseImageResource.prototype.upload = function (renderer, baseTexture, glTexture, source) { + var gl = renderer.gl; + var width = baseTexture.realWidth; + var height = baseTexture.realHeight; + source = source || this.source; + if (source instanceof HTMLImageElement) { + if (!source.complete || source.naturalWidth === 0) { + return false; + } + } + else if (source instanceof HTMLVideoElement) { + if (source.readyState <= 1) { + return false; + } + } + gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, baseTexture.alphaMode === exports.ALPHA_MODES.UNPACK); + if (!this.noSubImage + && baseTexture.target === gl.TEXTURE_2D + && glTexture.width === width + && glTexture.height === height) { + gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, baseTexture.format, glTexture.type, source); + } + else { + glTexture.width = width; + glTexture.height = height; + gl.texImage2D(baseTexture.target, 0, glTexture.internalFormat, baseTexture.format, glTexture.type, source); + } + return true; + }; + /** + * Checks if source width/height was changed, resize can cause extra baseTexture update. + * Triggers one update in any case. + */ + BaseImageResource.prototype.update = function () { + if (this.destroyed) { + return; + } + var source = this.source; + var width = source.naturalWidth || source.videoWidth || source.width; + var height = source.naturalHeight || source.videoHeight || source.height; + this.resize(width, height); + _super.prototype.update.call(this); + }; + /** Destroy this {@link BaseImageResource} */ + BaseImageResource.prototype.dispose = function () { + this.source = null; + }; + return BaseImageResource; + }(Resource)); + + /** + * @interface OffscreenCanvas + */ + /** + * Resource type for HTMLCanvasElement. + * @memberof PIXI + */ + var CanvasResource = /** @class */ (function (_super) { + __extends$i(CanvasResource, _super); + /** + * @param source - Canvas element to use + */ + // eslint-disable-next-line @typescript-eslint/no-useless-constructor + function CanvasResource(source) { + return _super.call(this, source) || this; + } + /** + * Used to auto-detect the type of resource. + * @param {*} source - The source object + * @returns {boolean} `true` if source is HTMLCanvasElement or OffscreenCanvas + */ + CanvasResource.test = function (source) { + var OffscreenCanvas = globalThis.OffscreenCanvas; + // Check for browsers that don't yet support OffscreenCanvas + if (OffscreenCanvas && source instanceof OffscreenCanvas) { + return true; + } + return globalThis.HTMLCanvasElement && source instanceof HTMLCanvasElement; + }; + return CanvasResource; + }(BaseImageResource)); + + /** + * Resource for a CubeTexture which contains six resources. + * @memberof PIXI + */ + var CubeResource = /** @class */ (function (_super) { + __extends$i(CubeResource, _super); + /** + * @param {Array} [source] - Collection of URLs or resources + * to use as the sides of the cube. + * @param options - ImageResource options + * @param {number} [options.width] - Width of resource + * @param {number} [options.height] - Height of resource + * @param {number} [options.autoLoad=true] - Whether to auto-load resources + * @param {number} [options.linkBaseTexture=true] - In case BaseTextures are supplied, + * whether to copy them or use + */ + function CubeResource(source, options) { + var _this = this; + var _a = options || {}, width = _a.width, height = _a.height, autoLoad = _a.autoLoad, linkBaseTexture = _a.linkBaseTexture; + if (source && source.length !== CubeResource.SIDES) { + throw new Error("Invalid length. Got " + source.length + ", expected 6"); + } + _this = _super.call(this, 6, { width: width, height: height }) || this; + for (var i = 0; i < CubeResource.SIDES; i++) { + _this.items[i].target = exports.TARGETS.TEXTURE_CUBE_MAP_POSITIVE_X + i; + } + _this.linkBaseTexture = linkBaseTexture !== false; + if (source) { + _this.initFromArray(source, options); + } + if (autoLoad !== false) { + _this.load(); + } + return _this; + } + /** + * Add binding. + * @param baseTexture - parent base texture + */ + CubeResource.prototype.bind = function (baseTexture) { + _super.prototype.bind.call(this, baseTexture); + baseTexture.target = exports.TARGETS.TEXTURE_CUBE_MAP; + }; + CubeResource.prototype.addBaseTextureAt = function (baseTexture, index, linkBaseTexture) { + if (!this.items[index]) { + throw new Error("Index " + index + " is out of bounds"); + } + if (!this.linkBaseTexture + || baseTexture.parentTextureArray + || Object.keys(baseTexture._glTextures).length > 0) { + // copy mode + if (baseTexture.resource) { + this.addResourceAt(baseTexture.resource, index); + } + else { + throw new Error("CubeResource does not support copying of renderTexture."); + } + } + else { + // link mode, the difficult one! + baseTexture.target = exports.TARGETS.TEXTURE_CUBE_MAP_POSITIVE_X + index; + baseTexture.parentTextureArray = this.baseTexture; + this.items[index] = baseTexture; + } + if (baseTexture.valid && !this.valid) { + this.resize(baseTexture.realWidth, baseTexture.realHeight); + } + this.items[index] = baseTexture; + return this; + }; + /** + * Upload the resource + * @param renderer + * @param _baseTexture + * @param glTexture + * @returns {boolean} true is success + */ + CubeResource.prototype.upload = function (renderer, _baseTexture, glTexture) { + var dirty = this.itemDirtyIds; + for (var i = 0; i < CubeResource.SIDES; i++) { + var side = this.items[i]; + if (dirty[i] < side.dirtyId || glTexture.dirtyId < _baseTexture.dirtyId) { + if (side.valid && side.resource) { + side.resource.upload(renderer, side, glTexture); + dirty[i] = side.dirtyId; + } + else if (dirty[i] < -1) { + // either item is not valid yet, either its a renderTexture + // allocate the memory + renderer.gl.texImage2D(side.target, 0, glTexture.internalFormat, _baseTexture.realWidth, _baseTexture.realHeight, 0, _baseTexture.format, glTexture.type, null); + dirty[i] = -1; + } + } + } + return true; + }; + /** + * Used to auto-detect the type of resource. + * @param {*} source - The source object + * @returns {boolean} `true` if source is an array of 6 elements + */ + CubeResource.test = function (source) { + return Array.isArray(source) && source.length === CubeResource.SIDES; + }; + /** Number of texture sides to store for CubeResources. */ + CubeResource.SIDES = 6; + return CubeResource; + }(AbstractMultiResource)); + + /** + * Resource type for HTMLImageElement. + * @memberof PIXI + */ + var ImageResource = /** @class */ (function (_super) { + __extends$i(ImageResource, _super); + /** + * @param source - image source or URL + * @param options + * @param {boolean} [options.autoLoad=true] - start loading process + * @param {boolean} [options.createBitmap=PIXI.settings.CREATE_IMAGE_BITMAP] - whether its required to create + * a bitmap before upload + * @param {boolean} [options.crossorigin=true] - Load image using cross origin + * @param {PIXI.ALPHA_MODES} [options.alphaMode=PIXI.ALPHA_MODES.UNPACK] - Premultiply image alpha in bitmap + */ + function ImageResource(source, options) { + var _this = this; + options = options || {}; + if (!(source instanceof HTMLImageElement)) { + var imageElement = new Image(); + BaseImageResource.crossOrigin(imageElement, source, options.crossorigin); + imageElement.src = source; + source = imageElement; + } + _this = _super.call(this, source) || this; + // FireFox 68, and possibly other versions, seems like setting the HTMLImageElement#width and #height + // to non-zero values before its loading completes if images are in a cache. + // Because of this, need to set the `_width` and the `_height` to zero to avoid uploading incomplete images. + // Please refer to the issue #5968 (https://github.com/pixijs/pixi.js/issues/5968). + if (!source.complete && !!_this._width && !!_this._height) { + _this._width = 0; + _this._height = 0; + } + _this.url = source.src; + _this._process = null; + _this.preserveBitmap = false; + _this.createBitmap = (options.createBitmap !== undefined + ? options.createBitmap : settings$1.CREATE_IMAGE_BITMAP) && !!globalThis.createImageBitmap; + _this.alphaMode = typeof options.alphaMode === 'number' ? options.alphaMode : null; + _this.bitmap = null; + _this._load = null; + if (options.autoLoad !== false) { + _this.load(); + } + return _this; + } + /** + * Returns a promise when image will be loaded and processed. + * @param createBitmap - whether process image into bitmap + */ + ImageResource.prototype.load = function (createBitmap) { + var _this = this; + if (this._load) { + return this._load; + } + if (createBitmap !== undefined) { + this.createBitmap = createBitmap; + } + this._load = new Promise(function (resolve, reject) { + var source = _this.source; + _this.url = source.src; + var completed = function () { + if (_this.destroyed) { + return; + } + source.onload = null; + source.onerror = null; + _this.resize(source.width, source.height); + _this._load = null; + if (_this.createBitmap) { + resolve(_this.process()); + } + else { + resolve(_this); + } + }; + if (source.complete && source.src) { + completed(); + } + else { + source.onload = completed; + source.onerror = function (event) { + // Avoids Promise freezing when resource broken + reject(event); + _this.onError.emit(event); + }; + } + }); + return this._load; + }; + /** + * Called when we need to convert image into BitmapImage. + * Can be called multiple times, real promise is cached inside. + * @returns - Cached promise to fill that bitmap + */ + ImageResource.prototype.process = function () { + var _this = this; + var source = this.source; + if (this._process !== null) { + return this._process; + } + if (this.bitmap !== null || !globalThis.createImageBitmap) { + return Promise.resolve(this); + } + var createImageBitmap = globalThis.createImageBitmap; + var cors = !source.crossOrigin || source.crossOrigin === 'anonymous'; + this._process = fetch(source.src, { + mode: cors ? 'cors' : 'no-cors' + }) + .then(function (r) { return r.blob(); }) + .then(function (blob) { return createImageBitmap(blob, 0, 0, source.width, source.height, { + premultiplyAlpha: _this.alphaMode === exports.ALPHA_MODES.UNPACK ? 'premultiply' : 'none', + }); }) + .then(function (bitmap) { + if (_this.destroyed) { + return Promise.reject(); + } + _this.bitmap = bitmap; + _this.update(); + _this._process = null; + return Promise.resolve(_this); + }); + return this._process; + }; + /** + * Upload the image resource to GPU. + * @param renderer - Renderer to upload to + * @param baseTexture - BaseTexture for this resource + * @param glTexture - GLTexture to use + * @returns {boolean} true is success + */ + ImageResource.prototype.upload = function (renderer, baseTexture, glTexture) { + if (typeof this.alphaMode === 'number') { + // bitmap stores unpack premultiply flag, we dont have to notify texImage2D about it + baseTexture.alphaMode = this.alphaMode; + } + if (!this.createBitmap) { + return _super.prototype.upload.call(this, renderer, baseTexture, glTexture); + } + if (!this.bitmap) { + // yeah, ignore the output + this.process(); + if (!this.bitmap) { + return false; + } + } + _super.prototype.upload.call(this, renderer, baseTexture, glTexture, this.bitmap); + if (!this.preserveBitmap) { + // checks if there are other renderers that possibly need this bitmap + var flag = true; + var glTextures = baseTexture._glTextures; + for (var key in glTextures) { + var otherTex = glTextures[key]; + if (otherTex !== glTexture && otherTex.dirtyId !== baseTexture.dirtyId) { + flag = false; + break; + } + } + if (flag) { + if (this.bitmap.close) { + this.bitmap.close(); + } + this.bitmap = null; + } + } + return true; + }; + /** Destroys this resource. */ + ImageResource.prototype.dispose = function () { + this.source.onload = null; + this.source.onerror = null; + _super.prototype.dispose.call(this); + if (this.bitmap) { + this.bitmap.close(); + this.bitmap = null; + } + this._process = null; + this._load = null; + }; + /** + * Used to auto-detect the type of resource. + * @param {*} source - The source object + * @returns {boolean} `true` if source is string or HTMLImageElement + */ + ImageResource.test = function (source) { + return typeof source === 'string' || source instanceof HTMLImageElement; + }; + return ImageResource; + }(BaseImageResource)); + + /** + * Resource type for SVG elements and graphics. + * @memberof PIXI + */ + var SVGResource = /** @class */ (function (_super) { + __extends$i(SVGResource, _super); + /** + * @param sourceBase64 - Base64 encoded SVG element or URL for SVG file. + * @param {object} [options] - Options to use + * @param {number} [options.scale=1] - Scale to apply to SVG. Overridden by... + * @param {number} [options.width] - Rasterize SVG this wide. Aspect ratio preserved if height not specified. + * @param {number} [options.height] - Rasterize SVG this high. Aspect ratio preserved if width not specified. + * @param {boolean} [options.autoLoad=true] - Start loading right away. + */ + function SVGResource(sourceBase64, options) { + var _this = this; + options = options || {}; + _this = _super.call(this, settings$1.ADAPTER.createCanvas()) || this; + _this._width = 0; + _this._height = 0; + _this.svg = sourceBase64; + _this.scale = options.scale || 1; + _this._overrideWidth = options.width; + _this._overrideHeight = options.height; + _this._resolve = null; + _this._crossorigin = options.crossorigin; + _this._load = null; + if (options.autoLoad !== false) { + _this.load(); + } + return _this; + } + SVGResource.prototype.load = function () { + var _this = this; + if (this._load) { + return this._load; + } + this._load = new Promise(function (resolve) { + // Save this until after load is finished + _this._resolve = function () { + _this.resize(_this.source.width, _this.source.height); + resolve(_this); + }; + // Convert SVG inline string to data-uri + if (SVGResource.SVG_XML.test(_this.svg.trim())) { + if (!btoa) { + throw new Error('Your browser doesn\'t support base64 conversions.'); + } + _this.svg = "data:image/svg+xml;base64," + btoa(unescape(encodeURIComponent(_this.svg))); + } + _this._loadSvg(); + }); + return this._load; + }; + /** Loads an SVG image from `imageUrl` or `data URL`. */ + SVGResource.prototype._loadSvg = function () { + var _this = this; + var tempImage = new Image(); + BaseImageResource.crossOrigin(tempImage, this.svg, this._crossorigin); + tempImage.src = this.svg; + tempImage.onerror = function (event) { + if (!_this._resolve) { + return; + } + tempImage.onerror = null; + _this.onError.emit(event); + }; + tempImage.onload = function () { + if (!_this._resolve) { + return; + } + var svgWidth = tempImage.width; + var svgHeight = tempImage.height; + if (!svgWidth || !svgHeight) { + throw new Error('The SVG image must have width and height defined (in pixels), canvas API needs them.'); + } + // Set render size + var width = svgWidth * _this.scale; + var height = svgHeight * _this.scale; + if (_this._overrideWidth || _this._overrideHeight) { + width = _this._overrideWidth || _this._overrideHeight / svgHeight * svgWidth; + height = _this._overrideHeight || _this._overrideWidth / svgWidth * svgHeight; + } + width = Math.round(width); + height = Math.round(height); + // Create a canvas element + var canvas = _this.source; + canvas.width = width; + canvas.height = height; + canvas._pixiId = "canvas_" + uid(); + // Draw the Svg to the canvas + canvas + .getContext('2d') + .drawImage(tempImage, 0, 0, svgWidth, svgHeight, 0, 0, width, height); + _this._resolve(); + _this._resolve = null; + }; + }; + /** + * Get size from an svg string using a regular expression. + * @param svgString - a serialized svg element + * @returns - image extension + */ + SVGResource.getSize = function (svgString) { + var sizeMatch = SVGResource.SVG_SIZE.exec(svgString); + var size = {}; + if (sizeMatch) { + size[sizeMatch[1]] = Math.round(parseFloat(sizeMatch[3])); + size[sizeMatch[5]] = Math.round(parseFloat(sizeMatch[7])); + } + return size; + }; + /** Destroys this texture. */ + SVGResource.prototype.dispose = function () { + _super.prototype.dispose.call(this); + this._resolve = null; + this._crossorigin = null; + }; + /** + * Used to auto-detect the type of resource. + * @param {*} source - The source object + * @param {string} extension - The extension of source, if set + * @returns {boolean} - If the source is a SVG source or data file + */ + SVGResource.test = function (source, extension) { + // url file extension is SVG + return extension === 'svg' + // source is SVG data-uri + || (typeof source === 'string' && (/^data:image\/svg\+xml(;(charset=utf8|utf8))?;base64/).test(source)) + // source is SVG inline + || (typeof source === 'string' && SVGResource.SVG_XML.test(source)); + }; + /** + * Regular expression for SVG XML document. + * @example <?xml version="1.0" encoding="utf-8" ?><!-- image/svg --><svg + * @readonly + */ + SVGResource.SVG_XML = /^(<\?xml[^?]+\?>)?\s*()]*-->)?\s*\]*(?:\s(width|height)=('|")(\d*(?:\.\d+)?)(?:px)?('|"))[^>]*(?:\s(width|height)=('|")(\d*(?:\.\d+)?)(?:px)?('|"))[^>]*>/i; // eslint-disable-line max-len + return SVGResource; + }(BaseImageResource)); + + /** + * Resource type for {@code HTMLVideoElement}. + * @memberof PIXI + */ + var VideoResource = /** @class */ (function (_super) { + __extends$i(VideoResource, _super); + /** + * @param {HTMLVideoElement|object|string|Array} source - Video element to use. + * @param {object} [options] - Options to use + * @param {boolean} [options.autoLoad=true] - Start loading the video immediately + * @param {boolean} [options.autoPlay=true] - Start playing video immediately + * @param {number} [options.updateFPS=0] - How many times a second to update the texture from the video. + * Leave at 0 to update at every render. + * @param {boolean} [options.crossorigin=true] - Load image using cross origin + */ + function VideoResource(source, options) { + var _this = this; + options = options || {}; + if (!(source instanceof HTMLVideoElement)) { + var videoElement = document.createElement('video'); + // workaround for https://github.com/pixijs/pixi.js/issues/5996 + videoElement.setAttribute('preload', 'auto'); + videoElement.setAttribute('webkit-playsinline', ''); + videoElement.setAttribute('playsinline', ''); + if (typeof source === 'string') { + source = [source]; + } + var firstSrc = source[0].src || source[0]; + BaseImageResource.crossOrigin(videoElement, firstSrc, options.crossorigin); + // array of objects or strings + for (var i = 0; i < source.length; ++i) { + var sourceElement = document.createElement('source'); + var _a = source[i], src = _a.src, mime = _a.mime; + src = src || source[i]; + var baseSrc = src.split('?').shift().toLowerCase(); + var ext = baseSrc.slice(baseSrc.lastIndexOf('.') + 1); + mime = mime || VideoResource.MIME_TYPES[ext] || "video/" + ext; + sourceElement.src = src; + sourceElement.type = mime; + videoElement.appendChild(sourceElement); + } + // Override the source + source = videoElement; + } + _this = _super.call(this, source) || this; + _this.noSubImage = true; + _this._autoUpdate = true; + _this._isConnectedToTicker = false; + _this._updateFPS = options.updateFPS || 0; + _this._msToNextUpdate = 0; + _this.autoPlay = options.autoPlay !== false; + _this._load = null; + _this._resolve = null; + // Bind for listeners + _this._onCanPlay = _this._onCanPlay.bind(_this); + _this._onError = _this._onError.bind(_this); + if (options.autoLoad !== false) { + _this.load(); + } + return _this; + } + /** + * Trigger updating of the texture. + * @param _deltaTime - time delta since last tick + */ + VideoResource.prototype.update = function (_deltaTime) { + if (!this.destroyed) { + // account for if video has had its playbackRate changed + var elapsedMS = Ticker.shared.elapsedMS * this.source.playbackRate; + this._msToNextUpdate = Math.floor(this._msToNextUpdate - elapsedMS); + if (!this._updateFPS || this._msToNextUpdate <= 0) { + _super.prototype.update.call(this); + this._msToNextUpdate = this._updateFPS ? Math.floor(1000 / this._updateFPS) : 0; + } + } + }; + /** + * Start preloading the video resource. + * @returns {Promise} Handle the validate event + */ + VideoResource.prototype.load = function () { + var _this = this; + if (this._load) { + return this._load; + } + var source = this.source; + if ((source.readyState === source.HAVE_ENOUGH_DATA || source.readyState === source.HAVE_FUTURE_DATA) + && source.width && source.height) { + source.complete = true; + } + source.addEventListener('play', this._onPlayStart.bind(this)); + source.addEventListener('pause', this._onPlayStop.bind(this)); + if (!this._isSourceReady()) { + source.addEventListener('canplay', this._onCanPlay); + source.addEventListener('canplaythrough', this._onCanPlay); + source.addEventListener('error', this._onError, true); + } + else { + this._onCanPlay(); + } + this._load = new Promise(function (resolve) { + if (_this.valid) { + resolve(_this); + } + else { + _this._resolve = resolve; + source.load(); + } + }); + return this._load; + }; + /** + * Handle video error events. + * @param event + */ + VideoResource.prototype._onError = function (event) { + this.source.removeEventListener('error', this._onError, true); + this.onError.emit(event); + }; + /** + * Returns true if the underlying source is playing. + * @returns - True if playing. + */ + VideoResource.prototype._isSourcePlaying = function () { + var source = this.source; + return (source.currentTime > 0 && source.paused === false && source.ended === false && source.readyState > 2); + }; + /** + * Returns true if the underlying source is ready for playing. + * @returns - True if ready. + */ + VideoResource.prototype._isSourceReady = function () { + var source = this.source; + return source.readyState === 3 || source.readyState === 4; + }; + /** Runs the update loop when the video is ready to play. */ + VideoResource.prototype._onPlayStart = function () { + // Just in case the video has not received its can play even yet.. + if (!this.valid) { + this._onCanPlay(); + } + if (this.autoUpdate && !this._isConnectedToTicker) { + Ticker.shared.add(this.update, this); + this._isConnectedToTicker = true; + } + }; + /** Fired when a pause event is triggered, stops the update loop. */ + VideoResource.prototype._onPlayStop = function () { + if (this._isConnectedToTicker) { + Ticker.shared.remove(this.update, this); + this._isConnectedToTicker = false; + } + }; + /** Fired when the video is loaded and ready to play. */ + VideoResource.prototype._onCanPlay = function () { + var source = this.source; + source.removeEventListener('canplay', this._onCanPlay); + source.removeEventListener('canplaythrough', this._onCanPlay); + var valid = this.valid; + this.resize(source.videoWidth, source.videoHeight); + // prevent multiple loaded dispatches.. + if (!valid && this._resolve) { + this._resolve(this); + this._resolve = null; + } + if (this._isSourcePlaying()) { + this._onPlayStart(); + } + else if (this.autoPlay) { + source.play(); + } + }; + /** Destroys this texture. */ + VideoResource.prototype.dispose = function () { + if (this._isConnectedToTicker) { + Ticker.shared.remove(this.update, this); + this._isConnectedToTicker = false; + } + var source = this.source; + if (source) { + source.removeEventListener('error', this._onError, true); + source.pause(); + source.src = ''; + source.load(); + } + _super.prototype.dispose.call(this); + }; + Object.defineProperty(VideoResource.prototype, "autoUpdate", { + /** Should the base texture automatically update itself, set to true by default. */ + get: function () { + return this._autoUpdate; + }, + set: function (value) { + if (value !== this._autoUpdate) { + this._autoUpdate = value; + if (!this._autoUpdate && this._isConnectedToTicker) { + Ticker.shared.remove(this.update, this); + this._isConnectedToTicker = false; + } + else if (this._autoUpdate && !this._isConnectedToTicker && this._isSourcePlaying()) { + Ticker.shared.add(this.update, this); + this._isConnectedToTicker = true; + } + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(VideoResource.prototype, "updateFPS", { + /** + * How many times a second to update the texture from the video. Leave at 0 to update at every render. + * A lower fps can help performance, as updating the texture at 60fps on a 30ps video may not be efficient. + */ + get: function () { + return this._updateFPS; + }, + set: function (value) { + if (value !== this._updateFPS) { + this._updateFPS = value; + } + }, + enumerable: false, + configurable: true + }); + /** + * Used to auto-detect the type of resource. + * @param {*} source - The source object + * @param {string} extension - The extension of source, if set + * @returns {boolean} `true` if video source + */ + VideoResource.test = function (source, extension) { + return (globalThis.HTMLVideoElement && source instanceof HTMLVideoElement) + || VideoResource.TYPES.indexOf(extension) > -1; + }; + /** + * List of common video file extensions supported by VideoResource. + * @readonly + */ + VideoResource.TYPES = ['mp4', 'm4v', 'webm', 'ogg', 'ogv', 'h264', 'avi', 'mov']; + /** + * Map of video MIME types that can't be directly derived from file extensions. + * @readonly + */ + VideoResource.MIME_TYPES = { + ogv: 'video/ogg', + mov: 'video/quicktime', + m4v: 'video/mp4', + }; + return VideoResource; + }(BaseImageResource)); + + /** + * Resource type for ImageBitmap. + * @memberof PIXI + */ + var ImageBitmapResource = /** @class */ (function (_super) { + __extends$i(ImageBitmapResource, _super); + /** + * @param source - Image element to use + */ + // eslint-disable-next-line @typescript-eslint/no-useless-constructor + function ImageBitmapResource(source) { + return _super.call(this, source) || this; + } + /** + * Used to auto-detect the type of resource. + * @param {*} source - The source object + * @returns {boolean} `true` if source is an ImageBitmap + */ + ImageBitmapResource.test = function (source) { + return !!globalThis.createImageBitmap && typeof ImageBitmap !== 'undefined' && source instanceof ImageBitmap; + }; + return ImageBitmapResource; + }(BaseImageResource)); + + INSTALLED.push(ImageResource, ImageBitmapResource, CanvasResource, VideoResource, SVGResource, BufferResource, CubeResource, ArrayResource); + + var _resources = { + __proto__: null, + Resource: Resource, + BaseImageResource: BaseImageResource, + INSTALLED: INSTALLED, + autoDetectResource: autoDetectResource, + AbstractMultiResource: AbstractMultiResource, + ArrayResource: ArrayResource, + BufferResource: BufferResource, + CanvasResource: CanvasResource, + CubeResource: CubeResource, + ImageResource: ImageResource, + SVGResource: SVGResource, + VideoResource: VideoResource, + ImageBitmapResource: ImageBitmapResource + }; + + /** + * Resource type for DepthTexture. + * @memberof PIXI + */ + var DepthResource = /** @class */ (function (_super) { + __extends$i(DepthResource, _super); + function DepthResource() { + return _super !== null && _super.apply(this, arguments) || this; + } + /** + * Upload the texture to the GPU. + * @param renderer - Upload to the renderer + * @param baseTexture - Reference to parent texture + * @param glTexture - glTexture + * @returns - true is success + */ + DepthResource.prototype.upload = function (renderer, baseTexture, glTexture) { + var gl = renderer.gl; + gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, baseTexture.alphaMode === exports.ALPHA_MODES.UNPACK); + var width = baseTexture.realWidth; + var height = baseTexture.realHeight; + if (glTexture.width === width && glTexture.height === height) { + gl.texSubImage2D(baseTexture.target, 0, 0, 0, width, height, baseTexture.format, glTexture.type, this.data); + } + else { + glTexture.width = width; + glTexture.height = height; + gl.texImage2D(baseTexture.target, 0, glTexture.internalFormat, width, height, 0, baseTexture.format, glTexture.type, this.data); + } + return true; + }; + return DepthResource; + }(BufferResource)); + + /** + * A framebuffer can be used to render contents off of the screen. {@link PIXI.BaseRenderTexture} uses + * one internally to render into itself. You can attach a depth or stencil buffer to a framebuffer. + * + * On WebGL 2 machines, shaders can output to multiple textures simultaneously with GLSL 300 ES. + * @memberof PIXI + */ + var Framebuffer = /** @class */ (function () { + /** + * @param width - Width of the frame buffer + * @param height - Height of the frame buffer + */ + function Framebuffer(width, height) { + this.width = Math.round(width || 100); + this.height = Math.round(height || 100); + this.stencil = false; + this.depth = false; + this.dirtyId = 0; + this.dirtyFormat = 0; + this.dirtySize = 0; + this.depthTexture = null; + this.colorTextures = []; + this.glFramebuffers = {}; + this.disposeRunner = new Runner('disposeFramebuffer'); + this.multisample = exports.MSAA_QUALITY.NONE; + } + Object.defineProperty(Framebuffer.prototype, "colorTexture", { + /** + * Reference to the colorTexture. + * @readonly + */ + get: function () { + return this.colorTextures[0]; + }, + enumerable: false, + configurable: true + }); + /** + * Add texture to the colorTexture array. + * @param index - Index of the array to add the texture to + * @param texture - Texture to add to the array + */ + Framebuffer.prototype.addColorTexture = function (index, texture) { + if (index === void 0) { index = 0; } + // TODO add some validation to the texture - same width / height etc? + this.colorTextures[index] = texture || new BaseTexture(null, { + scaleMode: exports.SCALE_MODES.NEAREST, + resolution: 1, + mipmap: exports.MIPMAP_MODES.OFF, + width: this.width, + height: this.height, + }); + this.dirtyId++; + this.dirtyFormat++; + return this; + }; + /** + * Add a depth texture to the frame buffer. + * @param texture - Texture to add. + */ + Framebuffer.prototype.addDepthTexture = function (texture) { + /* eslint-disable max-len */ + this.depthTexture = texture || new BaseTexture(new DepthResource(null, { width: this.width, height: this.height }), { + scaleMode: exports.SCALE_MODES.NEAREST, + resolution: 1, + width: this.width, + height: this.height, + mipmap: exports.MIPMAP_MODES.OFF, + format: exports.FORMATS.DEPTH_COMPONENT, + type: exports.TYPES.UNSIGNED_SHORT, + }); + this.dirtyId++; + this.dirtyFormat++; + return this; + }; + /** Enable depth on the frame buffer. */ + Framebuffer.prototype.enableDepth = function () { + this.depth = true; + this.dirtyId++; + this.dirtyFormat++; + return this; + }; + /** Enable stencil on the frame buffer. */ + Framebuffer.prototype.enableStencil = function () { + this.stencil = true; + this.dirtyId++; + this.dirtyFormat++; + return this; + }; + /** + * Resize the frame buffer + * @param width - Width of the frame buffer to resize to + * @param height - Height of the frame buffer to resize to + */ + Framebuffer.prototype.resize = function (width, height) { + width = Math.round(width); + height = Math.round(height); + if (width === this.width && height === this.height) + { return; } + this.width = width; + this.height = height; + this.dirtyId++; + this.dirtySize++; + for (var i = 0; i < this.colorTextures.length; i++) { + var texture = this.colorTextures[i]; + var resolution = texture.resolution; + // take into account the fact the texture may have a different resolution.. + texture.setSize(width / resolution, height / resolution); + } + if (this.depthTexture) { + var resolution = this.depthTexture.resolution; + this.depthTexture.setSize(width / resolution, height / resolution); + } + }; + /** Disposes WebGL resources that are connected to this geometry. */ + Framebuffer.prototype.dispose = function () { + this.disposeRunner.emit(this, false); + }; + /** Destroys and removes the depth texture added to this framebuffer. */ + Framebuffer.prototype.destroyDepthTexture = function () { + if (this.depthTexture) { + this.depthTexture.destroy(); + this.depthTexture = null; + ++this.dirtyId; + ++this.dirtyFormat; + } + }; + return Framebuffer; + }()); + + /** + * A BaseRenderTexture is a special texture that allows any PixiJS display object to be rendered to it. + * + * __Hint__: All DisplayObjects (i.e. Sprites) that render to a BaseRenderTexture should be preloaded + * otherwise black rectangles will be drawn instead. + * + * A BaseRenderTexture takes a snapshot of any Display Object given to its render method. The position + * and rotation of the given Display Objects is ignored. For example: + * + * ```js + * let renderer = PIXI.autoDetectRenderer(); + * let baseRenderTexture = new PIXI.BaseRenderTexture({ width: 800, height: 600 }); + * let renderTexture = new PIXI.RenderTexture(baseRenderTexture); + * let sprite = PIXI.Sprite.from("spinObj_01.png"); + * + * sprite.position.x = 800/2; + * sprite.position.y = 600/2; + * sprite.anchor.x = 0.5; + * sprite.anchor.y = 0.5; + * + * renderer.render(sprite, {renderTexture}); + * ``` + * + * The Sprite in this case will be rendered using its local transform. To render this sprite at 0,0 + * you can clear the transform + * + * ```js + * + * sprite.setTransform() + * + * let baseRenderTexture = new PIXI.BaseRenderTexture({ width: 100, height: 100 }); + * let renderTexture = new PIXI.RenderTexture(baseRenderTexture); + * + * renderer.render(sprite, {renderTexture}); // Renders to center of RenderTexture + * ``` + * @memberof PIXI + */ + var BaseRenderTexture = /** @class */ (function (_super) { + __extends$i(BaseRenderTexture, _super); + /** + * @param options + * @param {number} [options.width=100] - The width of the base render texture. + * @param {number} [options.height=100] - The height of the base render texture. + * @param {PIXI.SCALE_MODES} [options.scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} + * for possible values. + * @param {number} [options.resolution=PIXI.settings.RESOLUTION] - The resolution / device pixel ratio + * of the texture being generated. + * @param {PIXI.MSAA_QUALITY} [options.multisample=PIXI.MSAA_QUALITY.NONE] - The number of samples of the frame buffer. + */ + function BaseRenderTexture(options) { + if (options === void 0) { options = {}; } + var _this = this; + if (typeof options === 'number') { + /* eslint-disable prefer-rest-params */ + // Backward compatibility of signature + var width = arguments[0]; + var height = arguments[1]; + var scaleMode = arguments[2]; + var resolution = arguments[3]; + options = { width: width, height: height, scaleMode: scaleMode, resolution: resolution }; + /* eslint-enable prefer-rest-params */ + } + options.width = options.width || 100; + options.height = options.height || 100; + options.multisample = options.multisample !== undefined ? options.multisample : exports.MSAA_QUALITY.NONE; + _this = _super.call(this, null, options) || this; + // Set defaults + _this.mipmap = exports.MIPMAP_MODES.OFF; + _this.valid = true; + _this.clearColor = [0, 0, 0, 0]; + _this.framebuffer = new Framebuffer(_this.realWidth, _this.realHeight) + .addColorTexture(0, _this); + _this.framebuffer.multisample = options.multisample; + // TODO - could this be added the systems? + _this.maskStack = []; + _this.filterStack = [{}]; + return _this; + } + /** + * Resizes the BaseRenderTexture. + * @param desiredWidth - The desired width to resize to. + * @param desiredHeight - The desired height to resize to. + */ + BaseRenderTexture.prototype.resize = function (desiredWidth, desiredHeight) { + this.framebuffer.resize(desiredWidth * this.resolution, desiredHeight * this.resolution); + this.setRealSize(this.framebuffer.width, this.framebuffer.height); + }; + /** + * Frees the texture and framebuffer from WebGL memory without destroying this texture object. + * This means you can still use the texture later which will upload it to GPU + * memory again. + * @fires PIXI.BaseTexture#dispose + */ + BaseRenderTexture.prototype.dispose = function () { + this.framebuffer.dispose(); + _super.prototype.dispose.call(this); + }; + /** Destroys this texture. */ + BaseRenderTexture.prototype.destroy = function () { + _super.prototype.destroy.call(this); + this.framebuffer.destroyDepthTexture(); + this.framebuffer = null; + }; + return BaseRenderTexture; + }(BaseTexture)); + + /** + * Stores a texture's frame in UV coordinates, in + * which everything lies in the rectangle `[(0,0), (1,0), + * (1,1), (0,1)]`. + * + * | Corner | Coordinates | + * |--------------|-------------| + * | Top-Left | `(x0,y0)` | + * | Top-Right | `(x1,y1)` | + * | Bottom-Right | `(x2,y2)` | + * | Bottom-Left | `(x3,y3)` | + * @protected + * @memberof PIXI + */ + var TextureUvs = /** @class */ (function () { + function TextureUvs() { + this.x0 = 0; + this.y0 = 0; + this.x1 = 1; + this.y1 = 0; + this.x2 = 1; + this.y2 = 1; + this.x3 = 0; + this.y3 = 1; + this.uvsFloat32 = new Float32Array(8); + } + /** + * Sets the texture Uvs based on the given frame information. + * @protected + * @param frame - The frame of the texture + * @param baseFrame - The base frame of the texture + * @param rotate - Rotation of frame, see {@link PIXI.groupD8} + */ + TextureUvs.prototype.set = function (frame, baseFrame, rotate) { + var tw = baseFrame.width; + var th = baseFrame.height; + if (rotate) { + // width and height div 2 div baseFrame size + var w2 = frame.width / 2 / tw; + var h2 = frame.height / 2 / th; + // coordinates of center + var cX = (frame.x / tw) + w2; + var cY = (frame.y / th) + h2; + rotate = groupD8.add(rotate, groupD8.NW); // NW is top-left corner + this.x0 = cX + (w2 * groupD8.uX(rotate)); + this.y0 = cY + (h2 * groupD8.uY(rotate)); + rotate = groupD8.add(rotate, 2); // rotate 90 degrees clockwise + this.x1 = cX + (w2 * groupD8.uX(rotate)); + this.y1 = cY + (h2 * groupD8.uY(rotate)); + rotate = groupD8.add(rotate, 2); + this.x2 = cX + (w2 * groupD8.uX(rotate)); + this.y2 = cY + (h2 * groupD8.uY(rotate)); + rotate = groupD8.add(rotate, 2); + this.x3 = cX + (w2 * groupD8.uX(rotate)); + this.y3 = cY + (h2 * groupD8.uY(rotate)); + } + else { + this.x0 = frame.x / tw; + this.y0 = frame.y / th; + this.x1 = (frame.x + frame.width) / tw; + this.y1 = frame.y / th; + this.x2 = (frame.x + frame.width) / tw; + this.y2 = (frame.y + frame.height) / th; + this.x3 = frame.x / tw; + this.y3 = (frame.y + frame.height) / th; + } + this.uvsFloat32[0] = this.x0; + this.uvsFloat32[1] = this.y0; + this.uvsFloat32[2] = this.x1; + this.uvsFloat32[3] = this.y1; + this.uvsFloat32[4] = this.x2; + this.uvsFloat32[5] = this.y2; + this.uvsFloat32[6] = this.x3; + this.uvsFloat32[7] = this.y3; + }; + TextureUvs.prototype.toString = function () { + return "[@pixi/core:TextureUvs " + + ("x0=" + this.x0 + " y0=" + this.y0 + " ") + + ("x1=" + this.x1 + " y1=" + this.y1 + " x2=" + this.x2 + " ") + + ("y2=" + this.y2 + " x3=" + this.x3 + " y3=" + this.y3) + + "]"; + }; + return TextureUvs; + }()); + + var DEFAULT_UVS = new TextureUvs(); + /** + * Used to remove listeners from WHITE and EMPTY Textures + * @ignore + */ + function removeAllHandlers(tex) { + tex.destroy = function _emptyDestroy() { }; + tex.on = function _emptyOn() { }; + tex.once = function _emptyOnce() { }; + tex.emit = function _emptyEmit() { }; + } + /** + * A texture stores the information that represents an image or part of an image. + * + * It cannot be added to the display list directly; instead use it as the texture for a Sprite. + * If no frame is provided for a texture, then the whole image is used. + * + * You can directly create a texture from an image and then reuse it multiple times like this : + * + * ```js + * let texture = PIXI.Texture.from('assets/image.png'); + * let sprite1 = new PIXI.Sprite(texture); + * let sprite2 = new PIXI.Sprite(texture); + * ``` + * + * If you didnt pass the texture frame to constructor, it enables `noFrame` mode: + * it subscribes on baseTexture events, it automatically resizes at the same time as baseTexture. + * + * Textures made from SVGs, loaded or not, cannot be used before the file finishes processing. + * You can check for this by checking the sprite's _textureID property. + * ```js + * var texture = PIXI.Texture.from('assets/image.svg'); + * var sprite1 = new PIXI.Sprite(texture); + * //sprite1._textureID should not be undefined if the texture has finished processing the SVG file + * ``` + * You can use a ticker or rAF to ensure your sprites load the finished textures after processing. See issue #3068. + * @memberof PIXI + * @typeParam R - The BaseTexture's Resource type. + */ + var Texture = /** @class */ (function (_super) { + __extends$i(Texture, _super); + /** + * @param baseTexture - The base texture source to create the texture from + * @param frame - The rectangle frame of the texture to show + * @param orig - The area of original texture + * @param trim - Trimmed rectangle of original texture + * @param rotate - indicates how the texture was rotated by texture packer. See {@link PIXI.groupD8} + * @param anchor - Default anchor point used for sprite placement / rotation + */ + function Texture(baseTexture, frame, orig, trim, rotate, anchor) { + var _this = _super.call(this) || this; + _this.noFrame = false; + if (!frame) { + _this.noFrame = true; + frame = new Rectangle(0, 0, 1, 1); + } + if (baseTexture instanceof Texture) { + baseTexture = baseTexture.baseTexture; + } + _this.baseTexture = baseTexture; + _this._frame = frame; + _this.trim = trim; + _this.valid = false; + _this._uvs = DEFAULT_UVS; + _this.uvMatrix = null; + _this.orig = orig || frame; // new Rectangle(0, 0, 1, 1); + _this._rotate = Number(rotate || 0); + if (rotate === true) { + // this is old texturepacker legacy, some games/libraries are passing "true" for rotated textures + _this._rotate = 2; + } + else if (_this._rotate % 2 !== 0) { + throw new Error('attempt to use diamond-shaped UVs. If you are sure, set rotation manually'); + } + _this.defaultAnchor = anchor ? new Point(anchor.x, anchor.y) : new Point(0, 0); + _this._updateID = 0; + _this.textureCacheIds = []; + if (!baseTexture.valid) { + baseTexture.once('loaded', _this.onBaseTextureUpdated, _this); + } + else if (_this.noFrame) { + // if there is no frame we should monitor for any base texture changes.. + if (baseTexture.valid) { + _this.onBaseTextureUpdated(baseTexture); + } + } + else { + _this.frame = frame; + } + if (_this.noFrame) { + baseTexture.on('update', _this.onBaseTextureUpdated, _this); + } + return _this; + } + /** + * Updates this texture on the gpu. + * + * Calls the TextureResource update. + * + * If you adjusted `frame` manually, please call `updateUvs()` instead. + */ + Texture.prototype.update = function () { + if (this.baseTexture.resource) { + this.baseTexture.resource.update(); + } + }; + /** + * Called when the base texture is updated + * @protected + * @param baseTexture - The base texture. + */ + Texture.prototype.onBaseTextureUpdated = function (baseTexture) { + if (this.noFrame) { + if (!this.baseTexture.valid) { + return; + } + this._frame.width = baseTexture.width; + this._frame.height = baseTexture.height; + this.valid = true; + this.updateUvs(); + } + else { + // TODO this code looks confusing.. boo to abusing getters and setters! + // if user gave us frame that has bigger size than resized texture it can be a problem + this.frame = this._frame; + } + this.emit('update', this); + }; + /** + * Destroys this texture + * @param [destroyBase=false] - Whether to destroy the base texture as well + */ + Texture.prototype.destroy = function (destroyBase) { + if (this.baseTexture) { + if (destroyBase) { + var resource = this.baseTexture.resource; + // delete the texture if it exists in the texture cache.. + // this only needs to be removed if the base texture is actually destroyed too.. + if (resource && resource.url && TextureCache[resource.url]) { + Texture.removeFromCache(resource.url); + } + this.baseTexture.destroy(); + } + this.baseTexture.off('loaded', this.onBaseTextureUpdated, this); + this.baseTexture.off('update', this.onBaseTextureUpdated, this); + this.baseTexture = null; + } + this._frame = null; + this._uvs = null; + this.trim = null; + this.orig = null; + this.valid = false; + Texture.removeFromCache(this); + this.textureCacheIds = null; + }; + /** + * Creates a new texture object that acts the same as this one. + * @returns - The new texture + */ + Texture.prototype.clone = function () { + var clonedFrame = this._frame.clone(); + var clonedOrig = this._frame === this.orig ? clonedFrame : this.orig.clone(); + var clonedTexture = new Texture(this.baseTexture, !this.noFrame && clonedFrame, clonedOrig, this.trim && this.trim.clone(), this.rotate, this.defaultAnchor); + if (this.noFrame) { + clonedTexture._frame = clonedFrame; + } + return clonedTexture; + }; + /** + * Updates the internal WebGL UV cache. Use it after you change `frame` or `trim` of the texture. + * Call it after changing the frame + */ + Texture.prototype.updateUvs = function () { + if (this._uvs === DEFAULT_UVS) { + this._uvs = new TextureUvs(); + } + this._uvs.set(this._frame, this.baseTexture, this.rotate); + this._updateID++; + }; + /** + * Helper function that creates a new Texture based on the source you provide. + * The source can be - frame id, image url, video url, canvas element, video element, base texture + * @param {string|HTMLImageElement|HTMLCanvasElement|HTMLVideoElement|PIXI.BaseTexture} source - + * Source or array of sources to create texture from + * @param options - See {@link PIXI.BaseTexture}'s constructor for options. + * @param {string} [options.pixiIdPrefix=pixiid] - If a source has no id, this is the prefix of the generated id + * @param {boolean} [strict] - Enforce strict-mode, see {@link PIXI.settings.STRICT_TEXTURE_CACHE}. + * @returns {PIXI.Texture} The newly created texture + */ + Texture.from = function (source, options, strict) { + if (options === void 0) { options = {}; } + if (strict === void 0) { strict = settings$1.STRICT_TEXTURE_CACHE; } + var isFrame = typeof source === 'string'; + var cacheId = null; + if (isFrame) { + cacheId = source; + } + else if (source instanceof BaseTexture) { + if (!source.cacheId) { + var prefix = (options && options.pixiIdPrefix) || 'pixiid'; + source.cacheId = prefix + "-" + uid(); + BaseTexture.addToCache(source, source.cacheId); + } + cacheId = source.cacheId; + } + else { + if (!source._pixiId) { + var prefix = (options && options.pixiIdPrefix) || 'pixiid'; + source._pixiId = prefix + "_" + uid(); + } + cacheId = source._pixiId; + } + var texture = TextureCache[cacheId]; + // Strict-mode rejects invalid cacheIds + if (isFrame && strict && !texture) { + throw new Error("The cacheId \"" + cacheId + "\" does not exist in TextureCache."); + } + if (!texture && !(source instanceof BaseTexture)) { + if (!options.resolution) { + options.resolution = getResolutionOfUrl(source); + } + texture = new Texture(new BaseTexture(source, options)); + texture.baseTexture.cacheId = cacheId; + BaseTexture.addToCache(texture.baseTexture, cacheId); + Texture.addToCache(texture, cacheId); + } + else if (!texture && (source instanceof BaseTexture)) { + texture = new Texture(source); + Texture.addToCache(texture, cacheId); + } + // lets assume its a base texture! + return texture; + }; + /** + * Useful for loading textures via URLs. Use instead of `Texture.from` because + * it does a better job of handling failed URLs more effectively. This also ignores + * `PIXI.settings.STRICT_TEXTURE_CACHE`. Works for Videos, SVGs, Images. + * @param url - The remote URL or array of URLs to load. + * @param options - Optional options to include + * @returns - A Promise that resolves to a Texture. + */ + Texture.fromURL = function (url, options) { + var resourceOptions = Object.assign({ autoLoad: false }, options === null || options === void 0 ? void 0 : options.resourceOptions); + var texture = Texture.from(url, Object.assign({ resourceOptions: resourceOptions }, options), false); + var resource = texture.baseTexture.resource; + // The texture was already loaded + if (texture.baseTexture.valid) { + return Promise.resolve(texture); + } + // Manually load the texture, this should allow users to handle load errors + return resource.load().then(function () { return Promise.resolve(texture); }); + }; + /** + * Create a new Texture with a BufferResource from a Float32Array. + * RGBA values are floats from 0 to 1. + * @param {Float32Array|Uint8Array} buffer - The optional array to use, if no data + * is provided, a new Float32Array is created. + * @param width - Width of the resource + * @param height - Height of the resource + * @param options - See {@link PIXI.BaseTexture}'s constructor for options. + * @returns - The resulting new BaseTexture + */ + Texture.fromBuffer = function (buffer, width, height, options) { + return new Texture(BaseTexture.fromBuffer(buffer, width, height, options)); + }; + /** + * Create a texture from a source and add to the cache. + * @param {HTMLImageElement|HTMLCanvasElement|string} source - The input source. + * @param imageUrl - File name of texture, for cache and resolving resolution. + * @param name - Human readable name for the texture cache. If no name is + * specified, only `imageUrl` will be used as the cache ID. + * @param options + * @returns - Output texture + */ + Texture.fromLoader = function (source, imageUrl, name, options) { + var baseTexture = new BaseTexture(source, Object.assign({ + scaleMode: settings$1.SCALE_MODE, + resolution: getResolutionOfUrl(imageUrl), + }, options)); + var resource = baseTexture.resource; + if (resource instanceof ImageResource) { + resource.url = imageUrl; + } + var texture = new Texture(baseTexture); + // No name, use imageUrl instead + if (!name) { + name = imageUrl; + } + // lets also add the frame to pixi's global cache for 'fromLoader' function + BaseTexture.addToCache(texture.baseTexture, name); + Texture.addToCache(texture, name); + // also add references by url if they are different. + if (name !== imageUrl) { + BaseTexture.addToCache(texture.baseTexture, imageUrl); + Texture.addToCache(texture, imageUrl); + } + // Generally images are valid right away + if (texture.baseTexture.valid) { + return Promise.resolve(texture); + } + // SVG assets need to be parsed async, let's wait + return new Promise(function (resolve) { + texture.baseTexture.once('loaded', function () { return resolve(texture); }); + }); + }; + /** + * Adds a Texture to the global TextureCache. This cache is shared across the whole PIXI object. + * @param texture - The Texture to add to the cache. + * @param id - The id that the Texture will be stored against. + */ + Texture.addToCache = function (texture, id) { + if (id) { + if (texture.textureCacheIds.indexOf(id) === -1) { + texture.textureCacheIds.push(id); + } + if (TextureCache[id]) { + // eslint-disable-next-line no-console + console.warn("Texture added to the cache with an id [" + id + "] that already had an entry"); + } + TextureCache[id] = texture; + } + }; + /** + * Remove a Texture from the global TextureCache. + * @param texture - id of a Texture to be removed, or a Texture instance itself + * @returns - The Texture that was removed + */ + Texture.removeFromCache = function (texture) { + if (typeof texture === 'string') { + var textureFromCache = TextureCache[texture]; + if (textureFromCache) { + var index = textureFromCache.textureCacheIds.indexOf(texture); + if (index > -1) { + textureFromCache.textureCacheIds.splice(index, 1); + } + delete TextureCache[texture]; + return textureFromCache; + } + } + else if (texture && texture.textureCacheIds) { + for (var i = 0; i < texture.textureCacheIds.length; ++i) { + // Check that texture matches the one being passed in before deleting it from the cache. + if (TextureCache[texture.textureCacheIds[i]] === texture) { + delete TextureCache[texture.textureCacheIds[i]]; + } + } + texture.textureCacheIds.length = 0; + return texture; + } + return null; + }; + Object.defineProperty(Texture.prototype, "resolution", { + /** + * Returns resolution of baseTexture + * @readonly + */ + get: function () { + return this.baseTexture.resolution; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(Texture.prototype, "frame", { + /** + * The frame specifies the region of the base texture that this texture uses. + * Please call `updateUvs()` after you change coordinates of `frame` manually. + */ + get: function () { + return this._frame; + }, + set: function (frame) { + this._frame = frame; + this.noFrame = false; + var x = frame.x, y = frame.y, width = frame.width, height = frame.height; + var xNotFit = x + width > this.baseTexture.width; + var yNotFit = y + height > this.baseTexture.height; + if (xNotFit || yNotFit) { + var relationship = xNotFit && yNotFit ? 'and' : 'or'; + var errorX = "X: " + x + " + " + width + " = " + (x + width) + " > " + this.baseTexture.width; + var errorY = "Y: " + y + " + " + height + " = " + (y + height) + " > " + this.baseTexture.height; + throw new Error('Texture Error: frame does not fit inside the base Texture dimensions: ' + + (errorX + " " + relationship + " " + errorY)); + } + this.valid = width && height && this.baseTexture.valid; + if (!this.trim && !this.rotate) { + this.orig = frame; + } + if (this.valid) { + this.updateUvs(); + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(Texture.prototype, "rotate", { + /** + * Indicates whether the texture is rotated inside the atlas + * set to 2 to compensate for texture packer rotation + * set to 6 to compensate for spine packer rotation + * can be used to rotate or mirror sprites + * See {@link PIXI.groupD8} for explanation + */ + get: function () { + return this._rotate; + }, + set: function (rotate) { + this._rotate = rotate; + if (this.valid) { + this.updateUvs(); + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(Texture.prototype, "width", { + /** The width of the Texture in pixels. */ + get: function () { + return this.orig.width; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(Texture.prototype, "height", { + /** The height of the Texture in pixels. */ + get: function () { + return this.orig.height; + }, + enumerable: false, + configurable: true + }); + /** Utility function for BaseTexture|Texture cast. */ + Texture.prototype.castToBaseTexture = function () { + return this.baseTexture; + }; + Object.defineProperty(Texture, "EMPTY", { + /** An empty texture, used often to not have to create multiple empty textures. Can not be destroyed. */ + get: function () { + if (!Texture._EMPTY) { + Texture._EMPTY = new Texture(new BaseTexture()); + removeAllHandlers(Texture._EMPTY); + removeAllHandlers(Texture._EMPTY.baseTexture); + } + return Texture._EMPTY; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(Texture, "WHITE", { + /** A white texture of 16x16 size, used for graphics and other things Can not be destroyed. */ + get: function () { + if (!Texture._WHITE) { + var canvas = settings$1.ADAPTER.createCanvas(16, 16); + var context = canvas.getContext('2d'); + canvas.width = 16; + canvas.height = 16; + context.fillStyle = 'white'; + context.fillRect(0, 0, 16, 16); + Texture._WHITE = new Texture(BaseTexture.from(canvas)); + removeAllHandlers(Texture._WHITE); + removeAllHandlers(Texture._WHITE.baseTexture); + } + return Texture._WHITE; + }, + enumerable: false, + configurable: true + }); + return Texture; + }(eventemitter3)); + + /** + * A RenderTexture is a special texture that allows any PixiJS display object to be rendered to it. + * + * __Hint__: All DisplayObjects (i.e. Sprites) that render to a RenderTexture should be preloaded + * otherwise black rectangles will be drawn instead. + * + * __Hint-2__: The actual memory allocation will happen on first render. + * You shouldn't create renderTextures each frame just to delete them after, try to reuse them. + * + * A RenderTexture takes a snapshot of any Display Object given to its render method. For example: + * + * ```js + * let renderer = PIXI.autoDetectRenderer(); + * let renderTexture = PIXI.RenderTexture.create({ width: 800, height: 600 }); + * let sprite = PIXI.Sprite.from("spinObj_01.png"); + * + * sprite.position.x = 800/2; + * sprite.position.y = 600/2; + * sprite.anchor.x = 0.5; + * sprite.anchor.y = 0.5; + * + * renderer.render(sprite, {renderTexture}); + * ``` + * Note that you should not create a new renderer, but reuse the same one as the rest of the application. + * + * The Sprite in this case will be rendered using its local transform. To render this sprite at 0,0 + * you can clear the transform + * + * ```js + * + * sprite.setTransform() + * + * let renderTexture = new PIXI.RenderTexture.create({ width: 100, height: 100 }); + * + * renderer.render(sprite, {renderTexture}); // Renders to center of RenderTexture + * ``` + * @memberof PIXI + */ + var RenderTexture = /** @class */ (function (_super) { + __extends$i(RenderTexture, _super); + /** + * @param baseRenderTexture - The base texture object that this texture uses. + * @param frame - The rectangle frame of the texture to show. + */ + function RenderTexture(baseRenderTexture, frame) { + var _this = _super.call(this, baseRenderTexture, frame) || this; + _this.valid = true; + _this.filterFrame = null; + _this.filterPoolKey = null; + _this.updateUvs(); + return _this; + } + Object.defineProperty(RenderTexture.prototype, "framebuffer", { + /** + * Shortcut to `this.baseTexture.framebuffer`, saves baseTexture cast. + * @readonly + */ + get: function () { + return this.baseTexture.framebuffer; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(RenderTexture.prototype, "multisample", { + /** + * Shortcut to `this.framebuffer.multisample`. + * @default PIXI.MSAA_QUALITY.NONE + */ + get: function () { + return this.framebuffer.multisample; + }, + set: function (value) { + this.framebuffer.multisample = value; + }, + enumerable: false, + configurable: true + }); + /** + * Resizes the RenderTexture. + * @param desiredWidth - The desired width to resize to. + * @param desiredHeight - The desired height to resize to. + * @param resizeBaseTexture - Should the baseTexture.width and height values be resized as well? + */ + RenderTexture.prototype.resize = function (desiredWidth, desiredHeight, resizeBaseTexture) { + if (resizeBaseTexture === void 0) { resizeBaseTexture = true; } + var resolution = this.baseTexture.resolution; + var width = Math.round(desiredWidth * resolution) / resolution; + var height = Math.round(desiredHeight * resolution) / resolution; + // TODO - could be not required.. + this.valid = (width > 0 && height > 0); + this._frame.width = this.orig.width = width; + this._frame.height = this.orig.height = height; + if (resizeBaseTexture) { + this.baseTexture.resize(width, height); + } + this.updateUvs(); + }; + /** + * Changes the resolution of baseTexture, but does not change framebuffer size. + * @param resolution - The new resolution to apply to RenderTexture + */ + RenderTexture.prototype.setResolution = function (resolution) { + var baseTexture = this.baseTexture; + if (baseTexture.resolution === resolution) { + return; + } + baseTexture.setResolution(resolution); + this.resize(baseTexture.width, baseTexture.height, false); + }; + RenderTexture.create = function (options) { + var arguments$1 = arguments; + + var rest = []; + for (var _i = 1; _i < arguments.length; _i++) { + rest[_i - 1] = arguments$1[_i]; + } + // @deprecated fallback, old-style: create(width, height, scaleMode, resolution) + if (typeof options === 'number') { + deprecation$1('6.0.0', 'Arguments (width, height, scaleMode, resolution) have been deprecated.'); + /* eslint-disable prefer-rest-params */ + options = { + width: options, + height: rest[0], + scaleMode: rest[1], + resolution: rest[2], + }; + /* eslint-enable prefer-rest-params */ + } + return new RenderTexture(new BaseRenderTexture(options)); + }; + return RenderTexture; + }(Texture)); + + /** + * Texture pool, used by FilterSystem and plugins. + * + * Stores collection of temporary pow2 or screen-sized renderTextures + * + * If you use custom RenderTexturePool for your filters, you can use methods + * `getFilterTexture` and `returnFilterTexture` same as in + * @memberof PIXI + */ + var RenderTexturePool = /** @class */ (function () { + /** + * @param textureOptions - options that will be passed to BaseRenderTexture constructor + * @param {PIXI.SCALE_MODES} [textureOptions.scaleMode] - See {@link PIXI.SCALE_MODES} for possible values. + */ + function RenderTexturePool(textureOptions) { + this.texturePool = {}; + this.textureOptions = textureOptions || {}; + this.enableFullScreen = false; + this._pixelsWidth = 0; + this._pixelsHeight = 0; + } + /** + * Creates texture with params that were specified in pool constructor. + * @param realWidth - Width of texture in pixels. + * @param realHeight - Height of texture in pixels. + * @param multisample - Number of samples of the framebuffer. + */ + RenderTexturePool.prototype.createTexture = function (realWidth, realHeight, multisample) { + if (multisample === void 0) { multisample = exports.MSAA_QUALITY.NONE; } + var baseRenderTexture = new BaseRenderTexture(Object.assign({ + width: realWidth, + height: realHeight, + resolution: 1, + multisample: multisample, + }, this.textureOptions)); + return new RenderTexture(baseRenderTexture); + }; + /** + * Gets a Power-of-Two render texture or fullScreen texture + * @param minWidth - The minimum width of the render texture. + * @param minHeight - The minimum height of the render texture. + * @param resolution - The resolution of the render texture. + * @param multisample - Number of samples of the render texture. + * @returns The new render texture. + */ + RenderTexturePool.prototype.getOptimalTexture = function (minWidth, minHeight, resolution, multisample) { + if (resolution === void 0) { resolution = 1; } + if (multisample === void 0) { multisample = exports.MSAA_QUALITY.NONE; } + var key; + minWidth = Math.ceil((minWidth * resolution) - 1e-6); + minHeight = Math.ceil((minHeight * resolution) - 1e-6); + if (!this.enableFullScreen || minWidth !== this._pixelsWidth || minHeight !== this._pixelsHeight) { + minWidth = nextPow2(minWidth); + minHeight = nextPow2(minHeight); + key = (((minWidth & 0xFFFF) << 16) | (minHeight & 0xFFFF)) >>> 0; + if (multisample > 1) { + key += multisample * 0x100000000; + } + } + else { + key = multisample > 1 ? -multisample : -1; + } + if (!this.texturePool[key]) { + this.texturePool[key] = []; + } + var renderTexture = this.texturePool[key].pop(); + if (!renderTexture) { + renderTexture = this.createTexture(minWidth, minHeight, multisample); + } + renderTexture.filterPoolKey = key; + renderTexture.setResolution(resolution); + return renderTexture; + }; + /** + * Gets extra texture of the same size as input renderTexture + * + * `getFilterTexture(input, 0.5)` or `getFilterTexture(0.5, input)` + * @param input - renderTexture from which size and resolution will be copied + * @param resolution - override resolution of the renderTexture + * It overrides, it does not multiply + * @param multisample - number of samples of the renderTexture + */ + RenderTexturePool.prototype.getFilterTexture = function (input, resolution, multisample) { + var filterTexture = this.getOptimalTexture(input.width, input.height, resolution || input.resolution, multisample || exports.MSAA_QUALITY.NONE); + filterTexture.filterFrame = input.filterFrame; + return filterTexture; + }; + /** + * Place a render texture back into the pool. + * @param renderTexture - The renderTexture to free + */ + RenderTexturePool.prototype.returnTexture = function (renderTexture) { + var key = renderTexture.filterPoolKey; + renderTexture.filterFrame = null; + this.texturePool[key].push(renderTexture); + }; + /** + * Alias for returnTexture, to be compliant with FilterSystem interface. + * @param renderTexture - The renderTexture to free + */ + RenderTexturePool.prototype.returnFilterTexture = function (renderTexture) { + this.returnTexture(renderTexture); + }; + /** + * Clears the pool. + * @param destroyTextures - Destroy all stored textures. + */ + RenderTexturePool.prototype.clear = function (destroyTextures) { + destroyTextures = destroyTextures !== false; + if (destroyTextures) { + for (var i in this.texturePool) { + var textures = this.texturePool[i]; + if (textures) { + for (var j = 0; j < textures.length; j++) { + textures[j].destroy(true); + } + } + } + } + this.texturePool = {}; + }; + /** + * If screen size was changed, drops all screen-sized textures, + * sets new screen size, sets `enableFullScreen` to true + * + * Size is measured in pixels, `renderer.view` can be passed here, not `renderer.screen` + * @param size - Initial size of screen. + */ + RenderTexturePool.prototype.setScreenSize = function (size) { + if (size.width === this._pixelsWidth + && size.height === this._pixelsHeight) { + return; + } + this.enableFullScreen = size.width > 0 && size.height > 0; + for (var i in this.texturePool) { + if (!(Number(i) < 0)) { + continue; + } + var textures = this.texturePool[i]; + if (textures) { + for (var j = 0; j < textures.length; j++) { + textures[j].destroy(true); + } + } + this.texturePool[i] = []; + } + this._pixelsWidth = size.width; + this._pixelsHeight = size.height; + }; + /** + * Key that is used to store fullscreen renderTextures in a pool + * @constant + */ + RenderTexturePool.SCREEN_KEY = -1; + return RenderTexturePool; + }()); + + /* eslint-disable max-len */ + /** + * Holds the information for a single attribute structure required to render geometry. + * + * This does not contain the actual data, but instead has a buffer id that maps to a {@link PIXI.Buffer} + * This can include anything from positions, uvs, normals, colors etc. + * @memberof PIXI + */ + var Attribute = /** @class */ (function () { + /** + * @param buffer - the id of the buffer that this attribute will look for + * @param size - the size of the attribute. If you have 2 floats per vertex (eg position x and y) this would be 2. + * @param normalized - should the data be normalized. + * @param {PIXI.TYPES} [type=PIXI.TYPES.FLOAT] - what type of number is the attribute. Check {@link PIXI.TYPES} to see the ones available + * @param [stride=0] - How far apart, in bytes, the start of each value is. (used for interleaving data) + * @param [start=0] - How far into the array to start reading values (used for interleaving data) + * @param [instance=false] - Whether the geometry is instanced. + */ + function Attribute(buffer, size, normalized, type, stride, start, instance) { + if (size === void 0) { size = 0; } + if (normalized === void 0) { normalized = false; } + if (type === void 0) { type = exports.TYPES.FLOAT; } + this.buffer = buffer; + this.size = size; + this.normalized = normalized; + this.type = type; + this.stride = stride; + this.start = start; + this.instance = instance; + } + /** Destroys the Attribute. */ + Attribute.prototype.destroy = function () { + this.buffer = null; + }; + /** + * Helper function that creates an Attribute based on the information provided + * @param buffer - the id of the buffer that this attribute will look for + * @param [size=0] - the size of the attribute. If you have 2 floats per vertex (eg position x and y) this would be 2 + * @param [normalized=false] - should the data be normalized. + * @param [type=PIXI.TYPES.FLOAT] - what type of number is the attribute. Check {@link PIXI.TYPES} to see the ones available + * @param [stride=0] - How far apart, in bytes, the start of each value is. (used for interleaving data) + * @returns - A new {@link PIXI.Attribute} based on the information provided + */ + Attribute.from = function (buffer, size, normalized, type, stride) { + return new Attribute(buffer, size, normalized, type, stride); + }; + return Attribute; + }()); + + var UID$4 = 0; + /** + * A wrapper for data so that it can be used and uploaded by WebGL + * @memberof PIXI + */ + var Buffer = /** @class */ (function () { + /** + * @param {PIXI.IArrayBuffer} data - the data to store in the buffer. + * @param _static - `true` for static buffer + * @param index - `true` for index buffer + */ + function Buffer(data, _static, index) { + if (_static === void 0) { _static = true; } + if (index === void 0) { index = false; } + this.data = (data || new Float32Array(1)); + this._glBuffers = {}; + this._updateID = 0; + this.index = index; + this.static = _static; + this.id = UID$4++; + this.disposeRunner = new Runner('disposeBuffer'); + } + // TODO could explore flagging only a partial upload? + /** + * Flags this buffer as requiring an upload to the GPU. + * @param {PIXI.IArrayBuffer|number[]} [data] - the data to update in the buffer. + */ + Buffer.prototype.update = function (data) { + if (data instanceof Array) { + data = new Float32Array(data); + } + this.data = data || this.data; + this._updateID++; + }; + /** Disposes WebGL resources that are connected to this geometry. */ + Buffer.prototype.dispose = function () { + this.disposeRunner.emit(this, false); + }; + /** Destroys the buffer. */ + Buffer.prototype.destroy = function () { + this.dispose(); + this.data = null; + }; + Object.defineProperty(Buffer.prototype, "index", { + get: function () { + return this.type === exports.BUFFER_TYPE.ELEMENT_ARRAY_BUFFER; + }, + /** + * Flags whether this is an index buffer. + * + * Index buffers are of type `ELEMENT_ARRAY_BUFFER`. Note that setting this property to false will make + * the buffer of type `ARRAY_BUFFER`. + * + * For backwards compatibility. + */ + set: function (value) { + this.type = value ? exports.BUFFER_TYPE.ELEMENT_ARRAY_BUFFER : exports.BUFFER_TYPE.ARRAY_BUFFER; + }, + enumerable: false, + configurable: true + }); + /** + * Helper function that creates a buffer based on an array or TypedArray + * @param {ArrayBufferView | number[]} data - the TypedArray that the buffer will store. If this is a regular Array it will be converted to a Float32Array. + * @returns - A new Buffer based on the data provided. + */ + Buffer.from = function (data) { + if (data instanceof Array) { + data = new Float32Array(data); + } + return new Buffer(data); + }; + return Buffer; + }()); + + /* eslint-disable object-shorthand */ + var map$1 = { + Float32Array: Float32Array, + Uint32Array: Uint32Array, + Int32Array: Int32Array, + Uint8Array: Uint8Array, + }; + function interleaveTypedArrays(arrays, sizes) { + var outSize = 0; + var stride = 0; + var views = {}; + for (var i = 0; i < arrays.length; i++) { + stride += sizes[i]; + outSize += arrays[i].length; + } + var buffer = new ArrayBuffer(outSize * 4); + var out = null; + var littleOffset = 0; + for (var i = 0; i < arrays.length; i++) { + var size = sizes[i]; + var array = arrays[i]; + var type = getBufferType(array); + if (!views[type]) { + views[type] = new map$1[type](buffer); + } + out = views[type]; + for (var j = 0; j < array.length; j++) { + var indexStart = ((j / size | 0) * stride) + littleOffset; + var index = j % size; + out[indexStart + index] = array[j]; + } + littleOffset += size; + } + return new Float32Array(buffer); + } + + var byteSizeMap$1 = { 5126: 4, 5123: 2, 5121: 1 }; + var UID$3 = 0; + /* eslint-disable object-shorthand */ + var map = { + Float32Array: Float32Array, + Uint32Array: Uint32Array, + Int32Array: Int32Array, + Uint8Array: Uint8Array, + Uint16Array: Uint16Array, + }; + /* eslint-disable max-len */ + /** + * The Geometry represents a model. It consists of two components: + * - GeometryStyle - The structure of the model such as the attributes layout + * - GeometryData - the data of the model - this consists of buffers. + * This can include anything from positions, uvs, normals, colors etc. + * + * Geometry can be defined without passing in a style or data if required (thats how I prefer!) + * + * ```js + * let geometry = new PIXI.Geometry(); + * + * geometry.addAttribute('positions', [0, 0, 100, 0, 100, 100, 0, 100], 2); + * geometry.addAttribute('uvs', [0,0,1,0,1,1,0,1],2) + * geometry.addIndex([0,1,2,1,3,2]) + * ``` + * @memberof PIXI + */ + var Geometry = /** @class */ (function () { + /** + * @param buffers - An array of buffers. optional. + * @param attributes - Of the geometry, optional structure of the attributes layout + */ + function Geometry(buffers, attributes) { + if (buffers === void 0) { buffers = []; } + if (attributes === void 0) { attributes = {}; } + this.buffers = buffers; + this.indexBuffer = null; + this.attributes = attributes; + this.glVertexArrayObjects = {}; + this.id = UID$3++; + this.instanced = false; + this.instanceCount = 1; + this.disposeRunner = new Runner('disposeGeometry'); + this.refCount = 0; + } + /** + * + * Adds an attribute to the geometry + * Note: `stride` and `start` should be `undefined` if you dont know them, not 0! + * @param id - the name of the attribute (matching up to a shader) + * @param {PIXI.Buffer|number[]} buffer - the buffer that holds the data of the attribute . You can also provide an Array and a buffer will be created from it. + * @param size - the size of the attribute. If you have 2 floats per vertex (eg position x and y) this would be 2 + * @param normalized - should the data be normalized. + * @param [type=PIXI.TYPES.FLOAT] - what type of number is the attribute. Check {PIXI.TYPES} to see the ones available + * @param [stride=0] - How far apart, in bytes, the start of each value is. (used for interleaving data) + * @param [start=0] - How far into the array to start reading values (used for interleaving data) + * @param instance - Instancing flag + * @returns - Returns self, useful for chaining. + */ + Geometry.prototype.addAttribute = function (id, buffer, size, normalized, type, stride, start, instance) { + if (size === void 0) { size = 0; } + if (normalized === void 0) { normalized = false; } + if (instance === void 0) { instance = false; } + if (!buffer) { + throw new Error('You must pass a buffer when creating an attribute'); + } + // check if this is a buffer! + if (!(buffer instanceof Buffer)) { + // its an array! + if (buffer instanceof Array) { + buffer = new Float32Array(buffer); + } + buffer = new Buffer(buffer); + } + var ids = id.split('|'); + if (ids.length > 1) { + for (var i = 0; i < ids.length; i++) { + this.addAttribute(ids[i], buffer, size, normalized, type); + } + return this; + } + var bufferIndex = this.buffers.indexOf(buffer); + if (bufferIndex === -1) { + this.buffers.push(buffer); + bufferIndex = this.buffers.length - 1; + } + this.attributes[id] = new Attribute(bufferIndex, size, normalized, type, stride, start, instance); + // assuming that if there is instanced data then this will be drawn with instancing! + this.instanced = this.instanced || instance; + return this; + }; + /** + * Returns the requested attribute. + * @param id - The name of the attribute required + * @returns - The attribute requested. + */ + Geometry.prototype.getAttribute = function (id) { + return this.attributes[id]; + }; + /** + * Returns the requested buffer. + * @param id - The name of the buffer required. + * @returns - The buffer requested. + */ + Geometry.prototype.getBuffer = function (id) { + return this.buffers[this.getAttribute(id).buffer]; + }; + /** + * + * Adds an index buffer to the geometry + * The index buffer contains integers, three for each triangle in the geometry, which reference the various attribute buffers (position, colour, UV coordinates, other UV coordinates, normal, …). There is only ONE index buffer. + * @param {PIXI.Buffer|number[]} [buffer] - The buffer that holds the data of the index buffer. You can also provide an Array and a buffer will be created from it. + * @returns - Returns self, useful for chaining. + */ + Geometry.prototype.addIndex = function (buffer) { + if (!(buffer instanceof Buffer)) { + // its an array! + if (buffer instanceof Array) { + buffer = new Uint16Array(buffer); + } + buffer = new Buffer(buffer); + } + buffer.type = exports.BUFFER_TYPE.ELEMENT_ARRAY_BUFFER; + this.indexBuffer = buffer; + if (this.buffers.indexOf(buffer) === -1) { + this.buffers.push(buffer); + } + return this; + }; + /** + * Returns the index buffer + * @returns - The index buffer. + */ + Geometry.prototype.getIndex = function () { + return this.indexBuffer; + }; + /** + * This function modifies the structure so that all current attributes become interleaved into a single buffer + * This can be useful if your model remains static as it offers a little performance boost + * @returns - Returns self, useful for chaining. + */ + Geometry.prototype.interleave = function () { + // a simple check to see if buffers are already interleaved.. + if (this.buffers.length === 1 || (this.buffers.length === 2 && this.indexBuffer)) + { return this; } + // assume already that no buffers are interleaved + var arrays = []; + var sizes = []; + var interleavedBuffer = new Buffer(); + var i; + for (i in this.attributes) { + var attribute = this.attributes[i]; + var buffer = this.buffers[attribute.buffer]; + arrays.push(buffer.data); + sizes.push((attribute.size * byteSizeMap$1[attribute.type]) / 4); + attribute.buffer = 0; + } + interleavedBuffer.data = interleaveTypedArrays(arrays, sizes); + for (i = 0; i < this.buffers.length; i++) { + if (this.buffers[i] !== this.indexBuffer) { + this.buffers[i].destroy(); + } + } + this.buffers = [interleavedBuffer]; + if (this.indexBuffer) { + this.buffers.push(this.indexBuffer); + } + return this; + }; + /** Get the size of the geometries, in vertices. */ + Geometry.prototype.getSize = function () { + for (var i in this.attributes) { + var attribute = this.attributes[i]; + var buffer = this.buffers[attribute.buffer]; + return buffer.data.length / ((attribute.stride / 4) || attribute.size); + } + return 0; + }; + /** Disposes WebGL resources that are connected to this geometry. */ + Geometry.prototype.dispose = function () { + this.disposeRunner.emit(this, false); + }; + /** Destroys the geometry. */ + Geometry.prototype.destroy = function () { + this.dispose(); + this.buffers = null; + this.indexBuffer = null; + this.attributes = null; + }; + /** + * Returns a clone of the geometry. + * @returns - A new clone of this geometry. + */ + Geometry.prototype.clone = function () { + var geometry = new Geometry(); + for (var i = 0; i < this.buffers.length; i++) { + geometry.buffers[i] = new Buffer(this.buffers[i].data.slice(0)); + } + for (var i in this.attributes) { + var attrib = this.attributes[i]; + geometry.attributes[i] = new Attribute(attrib.buffer, attrib.size, attrib.normalized, attrib.type, attrib.stride, attrib.start, attrib.instance); + } + if (this.indexBuffer) { + geometry.indexBuffer = geometry.buffers[this.buffers.indexOf(this.indexBuffer)]; + geometry.indexBuffer.type = exports.BUFFER_TYPE.ELEMENT_ARRAY_BUFFER; + } + return geometry; + }; + /** + * Merges an array of geometries into a new single one. + * + * Geometry attribute styles must match for this operation to work. + * @param geometries - array of geometries to merge + * @returns - Shiny new geometry! + */ + Geometry.merge = function (geometries) { + // todo add a geometry check! + // also a size check.. cant be too big!] + var geometryOut = new Geometry(); + var arrays = []; + var sizes = []; + var offsets = []; + var geometry; + // pass one.. get sizes.. + for (var i = 0; i < geometries.length; i++) { + geometry = geometries[i]; + for (var j = 0; j < geometry.buffers.length; j++) { + sizes[j] = sizes[j] || 0; + sizes[j] += geometry.buffers[j].data.length; + offsets[j] = 0; + } + } + // build the correct size arrays.. + for (var i = 0; i < geometry.buffers.length; i++) { + // TODO types! + arrays[i] = new map[getBufferType(geometry.buffers[i].data)](sizes[i]); + geometryOut.buffers[i] = new Buffer(arrays[i]); + } + // pass to set data.. + for (var i = 0; i < geometries.length; i++) { + geometry = geometries[i]; + for (var j = 0; j < geometry.buffers.length; j++) { + arrays[j].set(geometry.buffers[j].data, offsets[j]); + offsets[j] += geometry.buffers[j].data.length; + } + } + geometryOut.attributes = geometry.attributes; + if (geometry.indexBuffer) { + geometryOut.indexBuffer = geometryOut.buffers[geometry.buffers.indexOf(geometry.indexBuffer)]; + geometryOut.indexBuffer.type = exports.BUFFER_TYPE.ELEMENT_ARRAY_BUFFER; + var offset = 0; + var stride = 0; + var offset2 = 0; + var bufferIndexToCount = 0; + // get a buffer + for (var i = 0; i < geometry.buffers.length; i++) { + if (geometry.buffers[i] !== geometry.indexBuffer) { + bufferIndexToCount = i; + break; + } + } + // figure out the stride of one buffer.. + for (var i in geometry.attributes) { + var attribute = geometry.attributes[i]; + if ((attribute.buffer | 0) === bufferIndexToCount) { + stride += ((attribute.size * byteSizeMap$1[attribute.type]) / 4); + } + } + // time to off set all indexes.. + for (var i = 0; i < geometries.length; i++) { + var indexBufferData = geometries[i].indexBuffer.data; + for (var j = 0; j < indexBufferData.length; j++) { + geometryOut.indexBuffer.data[j + offset2] += offset; + } + offset += geometries[i].buffers[bufferIndexToCount].data.length / (stride); + offset2 += indexBufferData.length; + } + } + return geometryOut; + }; + return Geometry; + }()); + + /** + * Helper class to create a quad + * @memberof PIXI + */ + var Quad = /** @class */ (function (_super) { + __extends$i(Quad, _super); + function Quad() { + var _this = _super.call(this) || this; + _this.addAttribute('aVertexPosition', new Float32Array([ + 0, 0, + 1, 0, + 1, 1, + 0, 1 ])) + .addIndex([0, 1, 3, 2]); + return _this; + } + return Quad; + }(Geometry)); + + /** + * Helper class to create a quad with uvs like in v4 + * @memberof PIXI + */ + var QuadUv = /** @class */ (function (_super) { + __extends$i(QuadUv, _super); + function QuadUv() { + var _this = _super.call(this) || this; + _this.vertices = new Float32Array([ + -1, -1, + 1, -1, + 1, 1, + -1, 1 ]); + _this.uvs = new Float32Array([ + 0, 0, + 1, 0, + 1, 1, + 0, 1 ]); + _this.vertexBuffer = new Buffer(_this.vertices); + _this.uvBuffer = new Buffer(_this.uvs); + _this.addAttribute('aVertexPosition', _this.vertexBuffer) + .addAttribute('aTextureCoord', _this.uvBuffer) + .addIndex([0, 1, 2, 0, 2, 3]); + return _this; + } + /** + * Maps two Rectangle to the quad. + * @param targetTextureFrame - The first rectangle + * @param destinationFrame - The second rectangle + * @returns - Returns itself. + */ + QuadUv.prototype.map = function (targetTextureFrame, destinationFrame) { + var x = 0; // destinationFrame.x / targetTextureFrame.width; + var y = 0; // destinationFrame.y / targetTextureFrame.height; + this.uvs[0] = x; + this.uvs[1] = y; + this.uvs[2] = x + (destinationFrame.width / targetTextureFrame.width); + this.uvs[3] = y; + this.uvs[4] = x + (destinationFrame.width / targetTextureFrame.width); + this.uvs[5] = y + (destinationFrame.height / targetTextureFrame.height); + this.uvs[6] = x; + this.uvs[7] = y + (destinationFrame.height / targetTextureFrame.height); + x = destinationFrame.x; + y = destinationFrame.y; + this.vertices[0] = x; + this.vertices[1] = y; + this.vertices[2] = x + destinationFrame.width; + this.vertices[3] = y; + this.vertices[4] = x + destinationFrame.width; + this.vertices[5] = y + destinationFrame.height; + this.vertices[6] = x; + this.vertices[7] = y + destinationFrame.height; + this.invalidate(); + return this; + }; + /** + * Legacy upload method, just marks buffers dirty. + * @returns - Returns itself. + */ + QuadUv.prototype.invalidate = function () { + this.vertexBuffer._updateID++; + this.uvBuffer._updateID++; + return this; + }; + return QuadUv; + }(Geometry)); + + var UID$2 = 0; + /** + * Uniform group holds uniform map and some ID's for work + * + * `UniformGroup` has two modes: + * + * 1: Normal mode + * Normal mode will upload the uniforms with individual function calls as required + * + * 2: Uniform buffer mode + * This mode will treat the uniforms as a uniform buffer. You can pass in either a buffer that you manually handle, or + * or a generic object that PixiJS will automatically map to a buffer for you. + * For maximum benefits, make Ubo UniformGroups static, and only update them each frame. + * + * Rules of UBOs: + * - UBOs only work with WebGL2, so make sure you have a fallback! + * - Only floats are supported (including vec[2,3,4], mat[2,3,4]) + * - Samplers cannot be used in ubo's (a GPU limitation) + * - You must ensure that the object you pass in exactly matches in the shader ubo structure. + * Otherwise, weirdness will ensue! + * - The name of the ubo object added to the group must match exactly the name of the ubo in the shader. + * + * ``` + * // ubo in shader: + * uniform myCoolData { // declaring a ubo.. + * mat4 uCoolMatrix; + * float uFloatyMcFloatFace + * + * + * // a new uniform buffer object.. + * const myCoolData = new UniformBufferGroup({ + * uCoolMatrix: new Matrix(), + * uFloatyMcFloatFace: 23, + * }} + * + * // build a shader... + * const shader = Shader.from(srcVert, srcFrag, { + * myCoolData // name matches the ubo name in the shader. will be processed accordingly. + * }) + * + * ``` + * @memberof PIXI + */ + var UniformGroup = /** @class */ (function () { + /** + * @param {object | Buffer} [uniforms] - Custom uniforms to use to augment the built-in ones. Or a pixi buffer. + * @param isStatic - Uniforms wont be changed after creation. + * @param isUbo - If true, will treat this uniform group as a uniform buffer object. + */ + function UniformGroup(uniforms, isStatic, isUbo) { + this.group = true; + // lets generate this when the shader ? + this.syncUniforms = {}; + this.dirtyId = 0; + this.id = UID$2++; + this.static = !!isStatic; + this.ubo = !!isUbo; + if (uniforms instanceof Buffer) { + this.buffer = uniforms; + this.buffer.type = exports.BUFFER_TYPE.UNIFORM_BUFFER; + this.autoManage = false; + this.ubo = true; + } + else { + this.uniforms = uniforms; + if (this.ubo) { + this.buffer = new Buffer(new Float32Array(1)); + this.buffer.type = exports.BUFFER_TYPE.UNIFORM_BUFFER; + this.autoManage = true; + } + } + } + UniformGroup.prototype.update = function () { + this.dirtyId++; + if (!this.autoManage && this.buffer) { + this.buffer.update(); + } + }; + UniformGroup.prototype.add = function (name, uniforms, _static) { + if (!this.ubo) { + this.uniforms[name] = new UniformGroup(uniforms, _static); + } + else { + // eslint-disable-next-line max-len + throw new Error('[UniformGroup] uniform groups in ubo mode cannot be modified, or have uniform groups nested in them'); + } + }; + UniformGroup.from = function (uniforms, _static, _ubo) { + return new UniformGroup(uniforms, _static, _ubo); + }; + /** + * A short hand function for creating a static UBO UniformGroup. + * @param uniforms - the ubo item + * @param _static - should this be updated each time it is used? defaults to true here! + */ + UniformGroup.uboFrom = function (uniforms, _static) { + return new UniformGroup(uniforms, _static !== null && _static !== void 0 ? _static : true, true); + }; + return UniformGroup; + }()); + + /** + * System plugin to the renderer to manage filter states. + * @ignore + */ + var FilterState = /** @class */ (function () { + function FilterState() { + this.renderTexture = null; + this.target = null; + this.legacy = false; + this.resolution = 1; + this.multisample = exports.MSAA_QUALITY.NONE; + // next three fields are created only for root + // re-assigned for everything else + this.sourceFrame = new Rectangle(); + this.destinationFrame = new Rectangle(); + this.bindingSourceFrame = new Rectangle(); + this.bindingDestinationFrame = new Rectangle(); + this.filters = []; + this.transform = null; + } + /** Clears the state */ + FilterState.prototype.clear = function () { + this.target = null; + this.filters = null; + this.renderTexture = null; + }; + return FilterState; + }()); + + var tempPoints = [new Point(), new Point(), new Point(), new Point()]; + var tempMatrix$2 = new Matrix(); + /** + * System plugin to the renderer to manage filters. + * + * ## Pipeline + * + * The FilterSystem executes the filtering pipeline by rendering the display-object into a texture, applying its + * [filters]{@link PIXI.Filter} in series, and the last filter outputs into the final render-target. + * + * The filter-frame is the rectangle in world space being filtered, and those contents are mapped into + * `(0, 0, filterFrame.width, filterFrame.height)` into the filter render-texture. The filter-frame is also called + * the source-frame, as it is used to bind the filter render-textures. The last filter outputs to the `filterFrame` + * in the final render-target. + * + * ## Usage + * + * {@link PIXI.Container#renderAdvanced} is an example of how to use the filter system. It is a 3 step process: + * + * **push**: Use {@link PIXI.FilterSystem#push} to push the set of filters to be applied on a filter-target. + * **render**: Render the contents to be filtered using the renderer. The filter-system will only capture the contents + * inside the bounds of the filter-target. NOTE: Using {@link PIXI.Renderer#render} is + * illegal during an existing render cycle, and it may reset the filter system. + * **pop**: Use {@link PIXI.FilterSystem#pop} to pop & execute the filters you initially pushed. It will apply them + * serially and output to the bounds of the filter-target. + * @memberof PIXI + */ + var FilterSystem = /** @class */ (function () { + /** + * @param renderer - The renderer this System works for. + */ + function FilterSystem(renderer) { + this.renderer = renderer; + this.defaultFilterStack = [{}]; + this.texturePool = new RenderTexturePool(); + this.texturePool.setScreenSize(renderer.view); + this.statePool = []; + this.quad = new Quad(); + this.quadUv = new QuadUv(); + this.tempRect = new Rectangle(); + this.activeState = {}; + this.globalUniforms = new UniformGroup({ + outputFrame: new Rectangle(), + inputSize: new Float32Array(4), + inputPixel: new Float32Array(4), + inputClamp: new Float32Array(4), + resolution: 1, + // legacy variables + filterArea: new Float32Array(4), + filterClamp: new Float32Array(4), + }, true); + this.forceClear = false; + this.useMaxPadding = false; + } + /** + * Pushes a set of filters to be applied later to the system. This will redirect further rendering into an + * input render-texture for the rest of the filtering pipeline. + * @param {PIXI.DisplayObject} target - The target of the filter to render. + * @param filters - The filters to apply. + */ + FilterSystem.prototype.push = function (target, filters) { + var _a, _b; + var renderer = this.renderer; + var filterStack = this.defaultFilterStack; + var state = this.statePool.pop() || new FilterState(); + var renderTextureSystem = this.renderer.renderTexture; + var resolution = filters[0].resolution; + var multisample = filters[0].multisample; + var padding = filters[0].padding; + var autoFit = filters[0].autoFit; + // We don't know whether it's a legacy filter until it was bound for the first time, + // therefore we have to assume that it is if legacy is undefined. + var legacy = (_a = filters[0].legacy) !== null && _a !== void 0 ? _a : true; + for (var i = 1; i < filters.length; i++) { + var filter = filters[i]; + // let's use the lowest resolution + resolution = Math.min(resolution, filter.resolution); + // let's use the lowest number of samples + multisample = Math.min(multisample, filter.multisample); + // figure out the padding required for filters + padding = this.useMaxPadding + // old behavior: use largest amount of padding! + ? Math.max(padding, filter.padding) + // new behavior: sum the padding + : padding + filter.padding; + // only auto fit if all filters are autofit + autoFit = autoFit && filter.autoFit; + legacy = legacy || ((_b = filter.legacy) !== null && _b !== void 0 ? _b : true); + } + if (filterStack.length === 1) { + this.defaultFilterStack[0].renderTexture = renderTextureSystem.current; + } + filterStack.push(state); + state.resolution = resolution; + state.multisample = multisample; + state.legacy = legacy; + state.target = target; + state.sourceFrame.copyFrom(target.filterArea || target.getBounds(true)); + state.sourceFrame.pad(padding); + var sourceFrameProjected = this.tempRect.copyFrom(renderTextureSystem.sourceFrame); + // Project source frame into world space (if projection is applied) + if (renderer.projection.transform) { + this.transformAABB(tempMatrix$2.copyFrom(renderer.projection.transform).invert(), sourceFrameProjected); + } + if (autoFit) { + state.sourceFrame.fit(sourceFrameProjected); + if (state.sourceFrame.width <= 0 || state.sourceFrame.height <= 0) { + state.sourceFrame.width = 0; + state.sourceFrame.height = 0; + } + } + else if (!state.sourceFrame.intersects(sourceFrameProjected)) { + state.sourceFrame.width = 0; + state.sourceFrame.height = 0; + } + // Round sourceFrame in screen space based on render-texture. + this.roundFrame(state.sourceFrame, renderTextureSystem.current ? renderTextureSystem.current.resolution : renderer.resolution, renderTextureSystem.sourceFrame, renderTextureSystem.destinationFrame, renderer.projection.transform); + state.renderTexture = this.getOptimalFilterTexture(state.sourceFrame.width, state.sourceFrame.height, resolution, multisample); + state.filters = filters; + state.destinationFrame.width = state.renderTexture.width; + state.destinationFrame.height = state.renderTexture.height; + var destinationFrame = this.tempRect; + destinationFrame.x = 0; + destinationFrame.y = 0; + destinationFrame.width = state.sourceFrame.width; + destinationFrame.height = state.sourceFrame.height; + state.renderTexture.filterFrame = state.sourceFrame; + state.bindingSourceFrame.copyFrom(renderTextureSystem.sourceFrame); + state.bindingDestinationFrame.copyFrom(renderTextureSystem.destinationFrame); + state.transform = renderer.projection.transform; + renderer.projection.transform = null; + renderTextureSystem.bind(state.renderTexture, state.sourceFrame, destinationFrame); + renderer.framebuffer.clear(0, 0, 0, 0); + }; + /** Pops off the filter and applies it. */ + FilterSystem.prototype.pop = function () { + var filterStack = this.defaultFilterStack; + var state = filterStack.pop(); + var filters = state.filters; + this.activeState = state; + var globalUniforms = this.globalUniforms.uniforms; + globalUniforms.outputFrame = state.sourceFrame; + globalUniforms.resolution = state.resolution; + var inputSize = globalUniforms.inputSize; + var inputPixel = globalUniforms.inputPixel; + var inputClamp = globalUniforms.inputClamp; + inputSize[0] = state.destinationFrame.width; + inputSize[1] = state.destinationFrame.height; + inputSize[2] = 1.0 / inputSize[0]; + inputSize[3] = 1.0 / inputSize[1]; + inputPixel[0] = Math.round(inputSize[0] * state.resolution); + inputPixel[1] = Math.round(inputSize[1] * state.resolution); + inputPixel[2] = 1.0 / inputPixel[0]; + inputPixel[3] = 1.0 / inputPixel[1]; + inputClamp[0] = 0.5 * inputPixel[2]; + inputClamp[1] = 0.5 * inputPixel[3]; + inputClamp[2] = (state.sourceFrame.width * inputSize[2]) - (0.5 * inputPixel[2]); + inputClamp[3] = (state.sourceFrame.height * inputSize[3]) - (0.5 * inputPixel[3]); + // only update the rect if its legacy.. + if (state.legacy) { + var filterArea = globalUniforms.filterArea; + filterArea[0] = state.destinationFrame.width; + filterArea[1] = state.destinationFrame.height; + filterArea[2] = state.sourceFrame.x; + filterArea[3] = state.sourceFrame.y; + globalUniforms.filterClamp = globalUniforms.inputClamp; + } + this.globalUniforms.update(); + var lastState = filterStack[filterStack.length - 1]; + this.renderer.framebuffer.blit(); + if (filters.length === 1) { + filters[0].apply(this, state.renderTexture, lastState.renderTexture, exports.CLEAR_MODES.BLEND, state); + this.returnFilterTexture(state.renderTexture); + } + else { + var flip = state.renderTexture; + var flop = this.getOptimalFilterTexture(flip.width, flip.height, state.resolution); + flop.filterFrame = flip.filterFrame; + var i = 0; + for (i = 0; i < filters.length - 1; ++i) { + if (i === 1 && state.multisample > 1) { + flop = this.getOptimalFilterTexture(flip.width, flip.height, state.resolution); + flop.filterFrame = flip.filterFrame; + } + filters[i].apply(this, flip, flop, exports.CLEAR_MODES.CLEAR, state); + var t = flip; + flip = flop; + flop = t; + } + filters[i].apply(this, flip, lastState.renderTexture, exports.CLEAR_MODES.BLEND, state); + if (i > 1 && state.multisample > 1) { + this.returnFilterTexture(state.renderTexture); + } + this.returnFilterTexture(flip); + this.returnFilterTexture(flop); + } + // lastState.renderTexture is blitted when lastState is popped + state.clear(); + this.statePool.push(state); + }; + /** + * Binds a renderTexture with corresponding `filterFrame`, clears it if mode corresponds. + * @param filterTexture - renderTexture to bind, should belong to filter pool or filter stack + * @param clearMode - clearMode, by default its CLEAR/YES. See {@link PIXI.CLEAR_MODES} + */ + FilterSystem.prototype.bindAndClear = function (filterTexture, clearMode) { + if (clearMode === void 0) { clearMode = exports.CLEAR_MODES.CLEAR; } + var _a = this.renderer, renderTextureSystem = _a.renderTexture, stateSystem = _a.state; + if (filterTexture === this.defaultFilterStack[this.defaultFilterStack.length - 1].renderTexture) { + // Restore projection transform if rendering into the output render-target. + this.renderer.projection.transform = this.activeState.transform; + } + else { + // Prevent projection within filtering pipeline. + this.renderer.projection.transform = null; + } + if (filterTexture && filterTexture.filterFrame) { + var destinationFrame = this.tempRect; + destinationFrame.x = 0; + destinationFrame.y = 0; + destinationFrame.width = filterTexture.filterFrame.width; + destinationFrame.height = filterTexture.filterFrame.height; + renderTextureSystem.bind(filterTexture, filterTexture.filterFrame, destinationFrame); + } + else if (filterTexture !== this.defaultFilterStack[this.defaultFilterStack.length - 1].renderTexture) { + renderTextureSystem.bind(filterTexture); + } + else { + // Restore binding for output render-target. + this.renderer.renderTexture.bind(filterTexture, this.activeState.bindingSourceFrame, this.activeState.bindingDestinationFrame); + } + // Clear the texture in BLIT mode if blending is disabled or the forceClear flag is set. The blending + // is stored in the 0th bit of the state. + var autoClear = (stateSystem.stateId & 1) || this.forceClear; + if (clearMode === exports.CLEAR_MODES.CLEAR + || (clearMode === exports.CLEAR_MODES.BLIT && autoClear)) { + // Use framebuffer.clear because we want to clear the whole filter texture, not just the filtering + // area over which the shaders are run. This is because filters may sampling outside of it (e.g. blur) + // instead of clamping their arithmetic. + this.renderer.framebuffer.clear(0, 0, 0, 0); + } + }; + /** + * Draws a filter using the default rendering process. + * + * This should be called only by {@link Filter#apply}. + * @param filter - The filter to draw. + * @param input - The input render target. + * @param output - The target to output to. + * @param clearMode - Should the output be cleared before rendering to it + */ + FilterSystem.prototype.applyFilter = function (filter, input, output, clearMode) { + var renderer = this.renderer; + // Set state before binding, so bindAndClear gets the blend mode. + renderer.state.set(filter.state); + this.bindAndClear(output, clearMode); + // set the uniforms.. + filter.uniforms.uSampler = input; + filter.uniforms.filterGlobals = this.globalUniforms; + // TODO make it so that the order of this does not matter.. + // because it does at the moment cos of global uniforms. + // they need to get resynced + renderer.shader.bind(filter); + // check to see if the filter is a legacy one.. + filter.legacy = !!filter.program.attributeData.aTextureCoord; + if (filter.legacy) { + this.quadUv.map(input._frame, input.filterFrame); + renderer.geometry.bind(this.quadUv); + renderer.geometry.draw(exports.DRAW_MODES.TRIANGLES); + } + else { + renderer.geometry.bind(this.quad); + renderer.geometry.draw(exports.DRAW_MODES.TRIANGLE_STRIP); + } + }; + /** + * Multiply _input normalized coordinates_ to this matrix to get _sprite texture normalized coordinates_. + * + * Use `outputMatrix * vTextureCoord` in the shader. + * @param outputMatrix - The matrix to output to. + * @param {PIXI.Sprite} sprite - The sprite to map to. + * @returns The mapped matrix. + */ + FilterSystem.prototype.calculateSpriteMatrix = function (outputMatrix, sprite) { + var _a = this.activeState, sourceFrame = _a.sourceFrame, destinationFrame = _a.destinationFrame; + var orig = sprite._texture.orig; + var mappedMatrix = outputMatrix.set(destinationFrame.width, 0, 0, destinationFrame.height, sourceFrame.x, sourceFrame.y); + var worldTransform = sprite.worldTransform.copyTo(Matrix.TEMP_MATRIX); + worldTransform.invert(); + mappedMatrix.prepend(worldTransform); + mappedMatrix.scale(1.0 / orig.width, 1.0 / orig.height); + mappedMatrix.translate(sprite.anchor.x, sprite.anchor.y); + return mappedMatrix; + }; + /** Destroys this Filter System. */ + FilterSystem.prototype.destroy = function () { + this.renderer = null; + // Those textures has to be destroyed by RenderTextureSystem or FramebufferSystem + this.texturePool.clear(false); + }; + /** + * Gets a Power-of-Two render texture or fullScreen texture + * @param minWidth - The minimum width of the render texture in real pixels. + * @param minHeight - The minimum height of the render texture in real pixels. + * @param resolution - The resolution of the render texture. + * @param multisample - Number of samples of the render texture. + * @returns - The new render texture. + */ + FilterSystem.prototype.getOptimalFilterTexture = function (minWidth, minHeight, resolution, multisample) { + if (resolution === void 0) { resolution = 1; } + if (multisample === void 0) { multisample = exports.MSAA_QUALITY.NONE; } + return this.texturePool.getOptimalTexture(minWidth, minHeight, resolution, multisample); + }; + /** + * Gets extra render texture to use inside current filter + * To be compliant with older filters, you can use params in any order + * @param input - renderTexture from which size and resolution will be copied + * @param resolution - override resolution of the renderTexture + * @param multisample - number of samples of the renderTexture + */ + FilterSystem.prototype.getFilterTexture = function (input, resolution, multisample) { + if (typeof input === 'number') { + var swap = input; + input = resolution; + resolution = swap; + } + input = input || this.activeState.renderTexture; + var filterTexture = this.texturePool.getOptimalTexture(input.width, input.height, resolution || input.resolution, multisample || exports.MSAA_QUALITY.NONE); + filterTexture.filterFrame = input.filterFrame; + return filterTexture; + }; + /** + * Frees a render texture back into the pool. + * @param renderTexture - The renderTarget to free + */ + FilterSystem.prototype.returnFilterTexture = function (renderTexture) { + this.texturePool.returnTexture(renderTexture); + }; + /** Empties the texture pool. */ + FilterSystem.prototype.emptyPool = function () { + this.texturePool.clear(true); + }; + /** Calls `texturePool.resize()`, affects fullScreen renderTextures. */ + FilterSystem.prototype.resize = function () { + this.texturePool.setScreenSize(this.renderer.view); + }; + /** + * @param matrix - first param + * @param rect - second param + */ + FilterSystem.prototype.transformAABB = function (matrix, rect) { + var lt = tempPoints[0]; + var lb = tempPoints[1]; + var rt = tempPoints[2]; + var rb = tempPoints[3]; + lt.set(rect.left, rect.top); + lb.set(rect.left, rect.bottom); + rt.set(rect.right, rect.top); + rb.set(rect.right, rect.bottom); + matrix.apply(lt, lt); + matrix.apply(lb, lb); + matrix.apply(rt, rt); + matrix.apply(rb, rb); + var x0 = Math.min(lt.x, lb.x, rt.x, rb.x); + var y0 = Math.min(lt.y, lb.y, rt.y, rb.y); + var x1 = Math.max(lt.x, lb.x, rt.x, rb.x); + var y1 = Math.max(lt.y, lb.y, rt.y, rb.y); + rect.x = x0; + rect.y = y0; + rect.width = x1 - x0; + rect.height = y1 - y0; + }; + FilterSystem.prototype.roundFrame = function (frame, resolution, bindingSourceFrame, bindingDestinationFrame, transform) { + if (frame.width <= 0 || frame.height <= 0 || bindingSourceFrame.width <= 0 || bindingSourceFrame.height <= 0) { + return; + } + if (transform) { + var a = transform.a, b = transform.b, c = transform.c, d = transform.d; + // Skip if skew/rotation present in matrix, except for multiple of 90° rotation. If rotation + // is a multiple of 90°, then either pair of (b,c) or (a,d) will be (0,0). + if ((Math.abs(b) > 1e-4 || Math.abs(c) > 1e-4) + && (Math.abs(a) > 1e-4 || Math.abs(d) > 1e-4)) { + return; + } + } + transform = transform ? tempMatrix$2.copyFrom(transform) : tempMatrix$2.identity(); + // Get forward transform from world space to screen space + transform + .translate(-bindingSourceFrame.x, -bindingSourceFrame.y) + .scale(bindingDestinationFrame.width / bindingSourceFrame.width, bindingDestinationFrame.height / bindingSourceFrame.height) + .translate(bindingDestinationFrame.x, bindingDestinationFrame.y); + // Convert frame to screen space + this.transformAABB(transform, frame); + // Round frame in screen space + frame.ceil(resolution); + // Project back into world space. + this.transformAABB(transform.invert(), frame); + }; + return FilterSystem; + }()); + + /** + * Base for a common object renderer that can be used as a + * system renderer plugin. + * @memberof PIXI + */ + var ObjectRenderer = /** @class */ (function () { + /** + * @param renderer - The renderer this manager works for. + */ + function ObjectRenderer(renderer) { + this.renderer = renderer; + } + /** Stub method that should be used to empty the current batch by rendering objects now. */ + ObjectRenderer.prototype.flush = function () { + // flush! + }; + /** Generic destruction method that frees all resources. This should be called by subclasses. */ + ObjectRenderer.prototype.destroy = function () { + this.renderer = null; + }; + /** + * Stub method that initializes any state required before + * rendering starts. It is different from the `prerender` + * signal, which occurs every frame, in that it is called + * whenever an object requests _this_ renderer specifically. + */ + ObjectRenderer.prototype.start = function () { + // set the shader.. + }; + /** Stops the renderer. It should free up any state and become dormant. */ + ObjectRenderer.prototype.stop = function () { + this.flush(); + }; + /** + * Keeps the object to render. It doesn't have to be + * rendered immediately. + * @param {PIXI.DisplayObject} _object - The object to render. + */ + ObjectRenderer.prototype.render = function (_object) { + // render the object + }; + return ObjectRenderer; + }()); + + /** + * System plugin to the renderer to manage batching. + * @memberof PIXI + */ + var BatchSystem = /** @class */ (function () { + /** + * @param renderer - The renderer this System works for. + */ + function BatchSystem(renderer) { + this.renderer = renderer; + this.emptyRenderer = new ObjectRenderer(renderer); + this.currentRenderer = this.emptyRenderer; + } + /** + * Changes the current renderer to the one given in parameter + * @param objectRenderer - The object renderer to use. + */ + BatchSystem.prototype.setObjectRenderer = function (objectRenderer) { + if (this.currentRenderer === objectRenderer) { + return; + } + this.currentRenderer.stop(); + this.currentRenderer = objectRenderer; + this.currentRenderer.start(); + }; + /** + * This should be called if you wish to do some custom rendering + * It will basically render anything that may be batched up such as sprites + */ + BatchSystem.prototype.flush = function () { + this.setObjectRenderer(this.emptyRenderer); + }; + /** Reset the system to an empty renderer */ + BatchSystem.prototype.reset = function () { + this.setObjectRenderer(this.emptyRenderer); + }; + /** + * Handy function for batch renderers: copies bound textures in first maxTextures locations to array + * sets actual _batchLocation for them + * @param arr - arr copy destination + * @param maxTextures - number of copied elements + */ + BatchSystem.prototype.copyBoundTextures = function (arr, maxTextures) { + var boundTextures = this.renderer.texture.boundTextures; + for (var i = maxTextures - 1; i >= 0; --i) { + arr[i] = boundTextures[i] || null; + if (arr[i]) { + arr[i]._batchLocation = i; + } + } + }; + /** + * Assigns batch locations to textures in array based on boundTextures state. + * All textures in texArray should have `_batchEnabled = _batchId`, + * and their count should be less than `maxTextures`. + * @param texArray - textures to bound + * @param boundTextures - current state of bound textures + * @param batchId - marker for _batchEnabled param of textures in texArray + * @param maxTextures - number of texture locations to manipulate + */ + BatchSystem.prototype.boundArray = function (texArray, boundTextures, batchId, maxTextures) { + var elements = texArray.elements, ids = texArray.ids, count = texArray.count; + var j = 0; + for (var i = 0; i < count; i++) { + var tex = elements[i]; + var loc = tex._batchLocation; + if (loc >= 0 && loc < maxTextures + && boundTextures[loc] === tex) { + ids[i] = loc; + continue; + } + while (j < maxTextures) { + var bound = boundTextures[j]; + if (bound && bound._batchEnabled === batchId + && bound._batchLocation === j) { + j++; + continue; + } + ids[i] = j; + tex._batchLocation = j; + boundTextures[j] = tex; + break; + } + } + }; + /** + * @ignore + */ + BatchSystem.prototype.destroy = function () { + this.renderer = null; + }; + return BatchSystem; + }()); + + var CONTEXT_UID_COUNTER = 0; + /** + * System plugin to the renderer to manage the context. + * @memberof PIXI + */ + var ContextSystem = /** @class */ (function () { + /** @param renderer - The renderer this System works for. */ + function ContextSystem(renderer) { + this.renderer = renderer; + this.webGLVersion = 1; + this.extensions = {}; + this.supports = { + uint32Indices: false, + }; + // Bind functions + this.handleContextLost = this.handleContextLost.bind(this); + this.handleContextRestored = this.handleContextRestored.bind(this); + renderer.view.addEventListener('webglcontextlost', this.handleContextLost, false); + renderer.view.addEventListener('webglcontextrestored', this.handleContextRestored, false); + } + Object.defineProperty(ContextSystem.prototype, "isLost", { + /** + * `true` if the context is lost + * @readonly + */ + get: function () { + return (!this.gl || this.gl.isContextLost()); + }, + enumerable: false, + configurable: true + }); + /** + * Handles the context change event. + * @param {WebGLRenderingContext} gl - New WebGL context. + */ + ContextSystem.prototype.contextChange = function (gl) { + this.gl = gl; + this.renderer.gl = gl; + this.renderer.CONTEXT_UID = CONTEXT_UID_COUNTER++; + // restore a context if it was previously lost + if (gl.isContextLost() && gl.getExtension('WEBGL_lose_context')) { + gl.getExtension('WEBGL_lose_context').restoreContext(); + } + }; + /** + * Initializes the context. + * @protected + * @param {WebGLRenderingContext} gl - WebGL context + */ + ContextSystem.prototype.initFromContext = function (gl) { + this.gl = gl; + this.validateContext(gl); + this.renderer.gl = gl; + this.renderer.CONTEXT_UID = CONTEXT_UID_COUNTER++; + this.renderer.runners.contextChange.emit(gl); + }; + /** + * Initialize from context options + * @protected + * @see https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/getContext + * @param {object} options - context attributes + */ + ContextSystem.prototype.initFromOptions = function (options) { + var gl = this.createContext(this.renderer.view, options); + this.initFromContext(gl); + }; + /** + * Helper class to create a WebGL Context + * @param canvas - the canvas element that we will get the context from + * @param options - An options object that gets passed in to the canvas element containing the + * context attributes + * @see https://developer.mozilla.org/en/docs/Web/API/HTMLCanvasElement/getContext + * @returns {WebGLRenderingContext} the WebGL context + */ + ContextSystem.prototype.createContext = function (canvas, options) { + var gl; + if (settings$1.PREFER_ENV >= exports.ENV.WEBGL2) { + gl = canvas.getContext('webgl2', options); + } + if (gl) { + this.webGLVersion = 2; + } + else { + this.webGLVersion = 1; + gl = canvas.getContext('webgl', options) || canvas.getContext('experimental-webgl', options); + if (!gl) { + // fail, not able to get a context + throw new Error('This browser does not support WebGL. Try using the canvas renderer'); + } + } + this.gl = gl; + this.getExtensions(); + return this.gl; + }; + /** Auto-populate the {@link PIXI.ContextSystem.extensions extensions}. */ + ContextSystem.prototype.getExtensions = function () { + // time to set up default extensions that Pixi uses. + var gl = this.gl; + var common = { + anisotropicFiltering: gl.getExtension('EXT_texture_filter_anisotropic'), + floatTextureLinear: gl.getExtension('OES_texture_float_linear'), + s3tc: gl.getExtension('WEBGL_compressed_texture_s3tc'), + s3tc_sRGB: gl.getExtension('WEBGL_compressed_texture_s3tc_srgb'), + etc: gl.getExtension('WEBGL_compressed_texture_etc'), + etc1: gl.getExtension('WEBGL_compressed_texture_etc1'), + pvrtc: gl.getExtension('WEBGL_compressed_texture_pvrtc') + || gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc'), + atc: gl.getExtension('WEBGL_compressed_texture_atc'), + astc: gl.getExtension('WEBGL_compressed_texture_astc') + }; + if (this.webGLVersion === 1) { + Object.assign(this.extensions, common, { + drawBuffers: gl.getExtension('WEBGL_draw_buffers'), + depthTexture: gl.getExtension('WEBGL_depth_texture'), + loseContext: gl.getExtension('WEBGL_lose_context'), + vertexArrayObject: gl.getExtension('OES_vertex_array_object') + || gl.getExtension('MOZ_OES_vertex_array_object') + || gl.getExtension('WEBKIT_OES_vertex_array_object'), + uint32ElementIndex: gl.getExtension('OES_element_index_uint'), + // Floats and half-floats + floatTexture: gl.getExtension('OES_texture_float'), + floatTextureLinear: gl.getExtension('OES_texture_float_linear'), + textureHalfFloat: gl.getExtension('OES_texture_half_float'), + textureHalfFloatLinear: gl.getExtension('OES_texture_half_float_linear'), + }); + } + else if (this.webGLVersion === 2) { + Object.assign(this.extensions, common, { + // Floats and half-floats + colorBufferFloat: gl.getExtension('EXT_color_buffer_float') + }); + } + }; + /** + * Handles a lost webgl context + * @param {WebGLContextEvent} event - The context lost event. + */ + ContextSystem.prototype.handleContextLost = function (event) { + event.preventDefault(); + }; + /** Handles a restored webgl context. */ + ContextSystem.prototype.handleContextRestored = function () { + this.renderer.runners.contextChange.emit(this.gl); + }; + ContextSystem.prototype.destroy = function () { + var view = this.renderer.view; + this.renderer = null; + // remove listeners + view.removeEventListener('webglcontextlost', this.handleContextLost); + view.removeEventListener('webglcontextrestored', this.handleContextRestored); + this.gl.useProgram(null); + if (this.extensions.loseContext) { + this.extensions.loseContext.loseContext(); + } + }; + /** Handle the post-render runner event. */ + ContextSystem.prototype.postrender = function () { + if (this.renderer.renderingToScreen) { + this.gl.flush(); + } + }; + /** + * Validate context. + * @param {WebGLRenderingContext} gl - Render context. + */ + ContextSystem.prototype.validateContext = function (gl) { + var attributes = gl.getContextAttributes(); + var isWebGl2 = 'WebGL2RenderingContext' in globalThis && gl instanceof globalThis.WebGL2RenderingContext; + if (isWebGl2) { + this.webGLVersion = 2; + } + // this is going to be fairly simple for now.. but at least we have room to grow! + if (attributes && !attributes.stencil) { + /* eslint-disable max-len, no-console */ + console.warn('Provided WebGL context does not have a stencil buffer, masks may not render correctly'); + /* eslint-enable max-len, no-console */ + } + var hasuint32 = isWebGl2 || !!gl.getExtension('OES_element_index_uint'); + this.supports.uint32Indices = hasuint32; + if (!hasuint32) { + /* eslint-disable max-len, no-console */ + console.warn('Provided WebGL context does not support 32 index buffer, complex graphics may not render correctly'); + /* eslint-enable max-len, no-console */ + } + }; + return ContextSystem; + }()); + + /** + * Internal framebuffer for WebGL context. + * @memberof PIXI + */ + var GLFramebuffer = /** @class */ (function () { + function GLFramebuffer(framebuffer) { + this.framebuffer = framebuffer; + this.stencil = null; + this.dirtyId = -1; + this.dirtyFormat = -1; + this.dirtySize = -1; + this.multisample = exports.MSAA_QUALITY.NONE; + this.msaaBuffer = null; + this.blitFramebuffer = null; + this.mipLevel = 0; + } + return GLFramebuffer; + }()); + + var tempRectangle = new Rectangle(); + /** + * System plugin to the renderer to manage framebuffers. + * @memberof PIXI + */ + var FramebufferSystem = /** @class */ (function () { + /** + * @param renderer - The renderer this System works for. + */ + function FramebufferSystem(renderer) { + this.renderer = renderer; + this.managedFramebuffers = []; + this.unknownFramebuffer = new Framebuffer(10, 10); + this.msaaSamples = null; + } + /** Sets up the renderer context and necessary buffers. */ + FramebufferSystem.prototype.contextChange = function () { + var gl = this.gl = this.renderer.gl; + this.CONTEXT_UID = this.renderer.CONTEXT_UID; + this.current = this.unknownFramebuffer; + this.viewport = new Rectangle(); + this.hasMRT = true; + this.writeDepthTexture = true; + this.disposeAll(true); + // webgl2 + if (this.renderer.context.webGLVersion === 1) { + // webgl 1! + var nativeDrawBuffersExtension_1 = this.renderer.context.extensions.drawBuffers; + var nativeDepthTextureExtension = this.renderer.context.extensions.depthTexture; + if (settings$1.PREFER_ENV === exports.ENV.WEBGL_LEGACY) { + nativeDrawBuffersExtension_1 = null; + nativeDepthTextureExtension = null; + } + if (nativeDrawBuffersExtension_1) { + gl.drawBuffers = function (activeTextures) { + return nativeDrawBuffersExtension_1.drawBuffersWEBGL(activeTextures); + }; + } + else { + this.hasMRT = false; + gl.drawBuffers = function () { + // empty + }; + } + if (!nativeDepthTextureExtension) { + this.writeDepthTexture = false; + } + } + else { + // WebGL2 + // cache possible MSAA samples + this.msaaSamples = gl.getInternalformatParameter(gl.RENDERBUFFER, gl.RGBA8, gl.SAMPLES); + } + }; + /** + * Bind a framebuffer. + * @param framebuffer + * @param frame - frame, default is framebuffer size + * @param mipLevel - optional mip level to set on the framebuffer - defaults to 0 + */ + FramebufferSystem.prototype.bind = function (framebuffer, frame, mipLevel) { + if (mipLevel === void 0) { mipLevel = 0; } + var gl = this.gl; + if (framebuffer) { + // TODO caching layer! + var fbo = framebuffer.glFramebuffers[this.CONTEXT_UID] || this.initFramebuffer(framebuffer); + if (this.current !== framebuffer) { + this.current = framebuffer; + gl.bindFramebuffer(gl.FRAMEBUFFER, fbo.framebuffer); + } + // make sure all textures are unbound.. + if (fbo.mipLevel !== mipLevel) { + framebuffer.dirtyId++; + framebuffer.dirtyFormat++; + fbo.mipLevel = mipLevel; + } + // now check for updates... + if (fbo.dirtyId !== framebuffer.dirtyId) { + fbo.dirtyId = framebuffer.dirtyId; + if (fbo.dirtyFormat !== framebuffer.dirtyFormat) { + fbo.dirtyFormat = framebuffer.dirtyFormat; + fbo.dirtySize = framebuffer.dirtySize; + this.updateFramebuffer(framebuffer, mipLevel); + } + else if (fbo.dirtySize !== framebuffer.dirtySize) { + fbo.dirtySize = framebuffer.dirtySize; + this.resizeFramebuffer(framebuffer); + } + } + for (var i = 0; i < framebuffer.colorTextures.length; i++) { + var tex = framebuffer.colorTextures[i]; + this.renderer.texture.unbind(tex.parentTextureArray || tex); + } + if (framebuffer.depthTexture) { + this.renderer.texture.unbind(framebuffer.depthTexture); + } + if (frame) { + var mipWidth = (frame.width >> mipLevel); + var mipHeight = (frame.height >> mipLevel); + var scale = mipWidth / frame.width; + this.setViewport(frame.x * scale, frame.y * scale, mipWidth, mipHeight); + } + else { + var mipWidth = (framebuffer.width >> mipLevel); + var mipHeight = (framebuffer.height >> mipLevel); + this.setViewport(0, 0, mipWidth, mipHeight); + } + } + else { + if (this.current) { + this.current = null; + gl.bindFramebuffer(gl.FRAMEBUFFER, null); + } + if (frame) { + this.setViewport(frame.x, frame.y, frame.width, frame.height); + } + else { + this.setViewport(0, 0, this.renderer.width, this.renderer.height); + } + } + }; + /** + * Set the WebGLRenderingContext's viewport. + * @param x - X position of viewport + * @param y - Y position of viewport + * @param width - Width of viewport + * @param height - Height of viewport + */ + FramebufferSystem.prototype.setViewport = function (x, y, width, height) { + var v = this.viewport; + x = Math.round(x); + y = Math.round(y); + width = Math.round(width); + height = Math.round(height); + if (v.width !== width || v.height !== height || v.x !== x || v.y !== y) { + v.x = x; + v.y = y; + v.width = width; + v.height = height; + this.gl.viewport(x, y, width, height); + } + }; + Object.defineProperty(FramebufferSystem.prototype, "size", { + /** + * Get the size of the current width and height. Returns object with `width` and `height` values. + * @readonly + */ + get: function () { + if (this.current) { + // TODO store temp + return { x: 0, y: 0, width: this.current.width, height: this.current.height }; + } + return { x: 0, y: 0, width: this.renderer.width, height: this.renderer.height }; + }, + enumerable: false, + configurable: true + }); + /** + * Clear the color of the context + * @param r - Red value from 0 to 1 + * @param g - Green value from 0 to 1 + * @param b - Blue value from 0 to 1 + * @param a - Alpha value from 0 to 1 + * @param {PIXI.BUFFER_BITS} [mask=BUFFER_BITS.COLOR | BUFFER_BITS.DEPTH] - Bitwise OR of masks + * that indicate the buffers to be cleared, by default COLOR and DEPTH buffers. + */ + FramebufferSystem.prototype.clear = function (r, g, b, a, mask) { + if (mask === void 0) { mask = exports.BUFFER_BITS.COLOR | exports.BUFFER_BITS.DEPTH; } + var gl = this.gl; + // TODO clear color can be set only one right? + gl.clearColor(r, g, b, a); + gl.clear(mask); + }; + /** + * Initialize framebuffer for this context + * @protected + * @param framebuffer + * @returns - created GLFramebuffer + */ + FramebufferSystem.prototype.initFramebuffer = function (framebuffer) { + var gl = this.gl; + var fbo = new GLFramebuffer(gl.createFramebuffer()); + fbo.multisample = this.detectSamples(framebuffer.multisample); + framebuffer.glFramebuffers[this.CONTEXT_UID] = fbo; + this.managedFramebuffers.push(framebuffer); + framebuffer.disposeRunner.add(this); + return fbo; + }; + /** + * Resize the framebuffer + * @param framebuffer + * @protected + */ + FramebufferSystem.prototype.resizeFramebuffer = function (framebuffer) { + var gl = this.gl; + var fbo = framebuffer.glFramebuffers[this.CONTEXT_UID]; + if (fbo.msaaBuffer) { + gl.bindRenderbuffer(gl.RENDERBUFFER, fbo.msaaBuffer); + gl.renderbufferStorageMultisample(gl.RENDERBUFFER, fbo.multisample, gl.RGBA8, framebuffer.width, framebuffer.height); + } + if (fbo.stencil) { + gl.bindRenderbuffer(gl.RENDERBUFFER, fbo.stencil); + if (fbo.msaaBuffer) { + gl.renderbufferStorageMultisample(gl.RENDERBUFFER, fbo.multisample, gl.DEPTH24_STENCIL8, framebuffer.width, framebuffer.height); + } + else { + gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, framebuffer.width, framebuffer.height); + } + } + var colorTextures = framebuffer.colorTextures; + var count = colorTextures.length; + if (!gl.drawBuffers) { + count = Math.min(count, 1); + } + for (var i = 0; i < count; i++) { + var texture = colorTextures[i]; + var parentTexture = texture.parentTextureArray || texture; + this.renderer.texture.bind(parentTexture, 0); + } + if (framebuffer.depthTexture && this.writeDepthTexture) { + this.renderer.texture.bind(framebuffer.depthTexture, 0); + } + }; + /** + * Update the framebuffer + * @param framebuffer + * @param mipLevel + * @protected + */ + FramebufferSystem.prototype.updateFramebuffer = function (framebuffer, mipLevel) { + var gl = this.gl; + var fbo = framebuffer.glFramebuffers[this.CONTEXT_UID]; + // bind the color texture + var colorTextures = framebuffer.colorTextures; + var count = colorTextures.length; + if (!gl.drawBuffers) { + count = Math.min(count, 1); + } + if (fbo.multisample > 1 && this.canMultisampleFramebuffer(framebuffer)) { + fbo.msaaBuffer = fbo.msaaBuffer || gl.createRenderbuffer(); + gl.bindRenderbuffer(gl.RENDERBUFFER, fbo.msaaBuffer); + gl.renderbufferStorageMultisample(gl.RENDERBUFFER, fbo.multisample, gl.RGBA8, framebuffer.width, framebuffer.height); + gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, fbo.msaaBuffer); + } + else if (fbo.msaaBuffer) { + gl.deleteRenderbuffer(fbo.msaaBuffer); + fbo.msaaBuffer = null; + if (fbo.blitFramebuffer) { + fbo.blitFramebuffer.dispose(); + fbo.blitFramebuffer = null; + } + } + var activeTextures = []; + for (var i = 0; i < count; i++) { + var texture = colorTextures[i]; + var parentTexture = texture.parentTextureArray || texture; + this.renderer.texture.bind(parentTexture, 0); + if (i === 0 && fbo.msaaBuffer) { + continue; + } + gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, texture.target, parentTexture._glTextures[this.CONTEXT_UID].texture, mipLevel); + activeTextures.push(gl.COLOR_ATTACHMENT0 + i); + } + if (activeTextures.length > 1) { + gl.drawBuffers(activeTextures); + } + if (framebuffer.depthTexture) { + var writeDepthTexture = this.writeDepthTexture; + if (writeDepthTexture) { + var depthTexture = framebuffer.depthTexture; + this.renderer.texture.bind(depthTexture, 0); + gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._glTextures[this.CONTEXT_UID].texture, mipLevel); + } + } + if ((framebuffer.stencil || framebuffer.depth) && !(framebuffer.depthTexture && this.writeDepthTexture)) { + fbo.stencil = fbo.stencil || gl.createRenderbuffer(); + gl.bindRenderbuffer(gl.RENDERBUFFER, fbo.stencil); + if (fbo.msaaBuffer) { + gl.renderbufferStorageMultisample(gl.RENDERBUFFER, fbo.multisample, gl.DEPTH24_STENCIL8, framebuffer.width, framebuffer.height); + } + else { + gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, framebuffer.width, framebuffer.height); + } + gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, fbo.stencil); + } + else if (fbo.stencil) { + gl.deleteRenderbuffer(fbo.stencil); + fbo.stencil = null; + } + }; + /** + * Returns true if the frame buffer can be multisampled. + * @param framebuffer + */ + FramebufferSystem.prototype.canMultisampleFramebuffer = function (framebuffer) { + return this.renderer.context.webGLVersion !== 1 + && framebuffer.colorTextures.length <= 1 && !framebuffer.depthTexture; + }; + /** + * Detects number of samples that is not more than a param but as close to it as possible + * @param samples - number of samples + * @returns - recommended number of samples + */ + FramebufferSystem.prototype.detectSamples = function (samples) { + var msaaSamples = this.msaaSamples; + var res = exports.MSAA_QUALITY.NONE; + if (samples <= 1 || msaaSamples === null) { + return res; + } + for (var i = 0; i < msaaSamples.length; i++) { + if (msaaSamples[i] <= samples) { + res = msaaSamples[i]; + break; + } + } + if (res === 1) { + res = exports.MSAA_QUALITY.NONE; + } + return res; + }; + /** + * Only works with WebGL2 + * + * blits framebuffer to another of the same or bigger size + * after that target framebuffer is bound + * + * Fails with WebGL warning if blits multisample framebuffer to different size + * @param framebuffer - by default it blits "into itself", from renderBuffer to texture. + * @param sourcePixels - source rectangle in pixels + * @param destPixels - dest rectangle in pixels, assumed to be the same as sourcePixels + */ + FramebufferSystem.prototype.blit = function (framebuffer, sourcePixels, destPixels) { + var _a = this, current = _a.current, renderer = _a.renderer, gl = _a.gl, CONTEXT_UID = _a.CONTEXT_UID; + if (renderer.context.webGLVersion !== 2) { + return; + } + if (!current) { + return; + } + var fbo = current.glFramebuffers[CONTEXT_UID]; + if (!fbo) { + return; + } + if (!framebuffer) { + if (!fbo.msaaBuffer) { + return; + } + var colorTexture = current.colorTextures[0]; + if (!colorTexture) { + return; + } + if (!fbo.blitFramebuffer) { + fbo.blitFramebuffer = new Framebuffer(current.width, current.height); + fbo.blitFramebuffer.addColorTexture(0, colorTexture); + } + framebuffer = fbo.blitFramebuffer; + if (framebuffer.colorTextures[0] !== colorTexture) { + framebuffer.colorTextures[0] = colorTexture; + framebuffer.dirtyId++; + framebuffer.dirtyFormat++; + } + if (framebuffer.width !== current.width || framebuffer.height !== current.height) { + framebuffer.width = current.width; + framebuffer.height = current.height; + framebuffer.dirtyId++; + framebuffer.dirtySize++; + } + } + if (!sourcePixels) { + sourcePixels = tempRectangle; + sourcePixels.width = current.width; + sourcePixels.height = current.height; + } + if (!destPixels) { + destPixels = sourcePixels; + } + var sameSize = sourcePixels.width === destPixels.width && sourcePixels.height === destPixels.height; + this.bind(framebuffer); + gl.bindFramebuffer(gl.READ_FRAMEBUFFER, fbo.framebuffer); + gl.blitFramebuffer(sourcePixels.left, sourcePixels.top, sourcePixels.right, sourcePixels.bottom, destPixels.left, destPixels.top, destPixels.right, destPixels.bottom, gl.COLOR_BUFFER_BIT, sameSize ? gl.NEAREST : gl.LINEAR); + }; + /** + * Disposes framebuffer. + * @param framebuffer - framebuffer that has to be disposed of + * @param contextLost - If context was lost, we suppress all delete function calls + */ + FramebufferSystem.prototype.disposeFramebuffer = function (framebuffer, contextLost) { + var fbo = framebuffer.glFramebuffers[this.CONTEXT_UID]; + var gl = this.gl; + if (!fbo) { + return; + } + delete framebuffer.glFramebuffers[this.CONTEXT_UID]; + var index = this.managedFramebuffers.indexOf(framebuffer); + if (index >= 0) { + this.managedFramebuffers.splice(index, 1); + } + framebuffer.disposeRunner.remove(this); + if (!contextLost) { + gl.deleteFramebuffer(fbo.framebuffer); + if (fbo.msaaBuffer) { + gl.deleteRenderbuffer(fbo.msaaBuffer); + } + if (fbo.stencil) { + gl.deleteRenderbuffer(fbo.stencil); + } + } + if (fbo.blitFramebuffer) { + fbo.blitFramebuffer.dispose(); + } + }; + /** + * Disposes all framebuffers, but not textures bound to them. + * @param [contextLost=false] - If context was lost, we suppress all delete function calls + */ + FramebufferSystem.prototype.disposeAll = function (contextLost) { + var list = this.managedFramebuffers; + this.managedFramebuffers = []; + for (var i = 0; i < list.length; i++) { + this.disposeFramebuffer(list[i], contextLost); + } + }; + /** + * Forcing creation of stencil buffer for current framebuffer, if it wasn't done before. + * Used by MaskSystem, when its time to use stencil mask for Graphics element. + * + * Its an alternative for public lazy `framebuffer.enableStencil`, in case we need stencil without rebind. + * @private + */ + FramebufferSystem.prototype.forceStencil = function () { + var framebuffer = this.current; + if (!framebuffer) { + return; + } + var fbo = framebuffer.glFramebuffers[this.CONTEXT_UID]; + if (!fbo || fbo.stencil) { + return; + } + framebuffer.stencil = true; + var w = framebuffer.width; + var h = framebuffer.height; + var gl = this.gl; + var stencil = gl.createRenderbuffer(); + gl.bindRenderbuffer(gl.RENDERBUFFER, stencil); + if (fbo.msaaBuffer) { + gl.renderbufferStorageMultisample(gl.RENDERBUFFER, fbo.multisample, gl.DEPTH24_STENCIL8, w, h); + } + else { + gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, w, h); + } + fbo.stencil = stencil; + gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, stencil); + }; + /** Resets framebuffer stored state, binds screen framebuffer. Should be called before renderTexture reset(). */ + FramebufferSystem.prototype.reset = function () { + this.current = this.unknownFramebuffer; + this.viewport = new Rectangle(); + }; + FramebufferSystem.prototype.destroy = function () { + this.renderer = null; + }; + return FramebufferSystem; + }()); + + var byteSizeMap = { 5126: 4, 5123: 2, 5121: 1 }; + /** + * System plugin to the renderer to manage geometry. + * @memberof PIXI + */ + var GeometrySystem = /** @class */ (function () { + /** @param renderer - The renderer this System works for. */ + function GeometrySystem(renderer) { + this.renderer = renderer; + this._activeGeometry = null; + this._activeVao = null; + this.hasVao = true; + this.hasInstance = true; + this.canUseUInt32ElementIndex = false; + this.managedGeometries = {}; + } + /** Sets up the renderer context and necessary buffers. */ + GeometrySystem.prototype.contextChange = function () { + this.disposeAll(true); + var gl = this.gl = this.renderer.gl; + var context = this.renderer.context; + this.CONTEXT_UID = this.renderer.CONTEXT_UID; + // webgl2 + if (context.webGLVersion !== 2) { + // webgl 1! + var nativeVaoExtension_1 = this.renderer.context.extensions.vertexArrayObject; + if (settings$1.PREFER_ENV === exports.ENV.WEBGL_LEGACY) { + nativeVaoExtension_1 = null; + } + if (nativeVaoExtension_1) { + gl.createVertexArray = function () { + return nativeVaoExtension_1.createVertexArrayOES(); + }; + gl.bindVertexArray = function (vao) { + return nativeVaoExtension_1.bindVertexArrayOES(vao); + }; + gl.deleteVertexArray = function (vao) { + return nativeVaoExtension_1.deleteVertexArrayOES(vao); + }; + } + else { + this.hasVao = false; + gl.createVertexArray = function () { + return null; + }; + gl.bindVertexArray = function () { + return null; + }; + gl.deleteVertexArray = function () { + return null; + }; + } + } + if (context.webGLVersion !== 2) { + var instanceExt_1 = gl.getExtension('ANGLE_instanced_arrays'); + if (instanceExt_1) { + gl.vertexAttribDivisor = function (a, b) { + return instanceExt_1.vertexAttribDivisorANGLE(a, b); + }; + gl.drawElementsInstanced = function (a, b, c, d, e) { + return instanceExt_1.drawElementsInstancedANGLE(a, b, c, d, e); + }; + gl.drawArraysInstanced = function (a, b, c, d) { + return instanceExt_1.drawArraysInstancedANGLE(a, b, c, d); + }; + } + else { + this.hasInstance = false; + } + } + this.canUseUInt32ElementIndex = context.webGLVersion === 2 || !!context.extensions.uint32ElementIndex; + }; + /** + * Binds geometry so that is can be drawn. Creating a Vao if required + * @param geometry - Instance of geometry to bind. + * @param shader - Instance of shader to use vao for. + */ + GeometrySystem.prototype.bind = function (geometry, shader) { + shader = shader || this.renderer.shader.shader; + var gl = this.gl; + // not sure the best way to address this.. + // currently different shaders require different VAOs for the same geometry + // Still mulling over the best way to solve this one.. + // will likely need to modify the shader attribute locations at run time! + var vaos = geometry.glVertexArrayObjects[this.CONTEXT_UID]; + var incRefCount = false; + if (!vaos) { + this.managedGeometries[geometry.id] = geometry; + geometry.disposeRunner.add(this); + geometry.glVertexArrayObjects[this.CONTEXT_UID] = vaos = {}; + incRefCount = true; + } + var vao = vaos[shader.program.id] || this.initGeometryVao(geometry, shader, incRefCount); + this._activeGeometry = geometry; + if (this._activeVao !== vao) { + this._activeVao = vao; + if (this.hasVao) { + gl.bindVertexArray(vao); + } + else { + this.activateVao(geometry, shader.program); + } + } + // TODO - optimise later! + // don't need to loop through if nothing changed! + // maybe look to add an 'autoupdate' to geometry? + this.updateBuffers(); + }; + /** Reset and unbind any active VAO and geometry. */ + GeometrySystem.prototype.reset = function () { + this.unbind(); + }; + /** Update buffers of the currently bound geometry. */ + GeometrySystem.prototype.updateBuffers = function () { + var geometry = this._activeGeometry; + var bufferSystem = this.renderer.buffer; + for (var i = 0; i < geometry.buffers.length; i++) { + var buffer = geometry.buffers[i]; + bufferSystem.update(buffer); + } + }; + /** + * Check compatibility between a geometry and a program + * @param geometry - Geometry instance. + * @param program - Program instance. + */ + GeometrySystem.prototype.checkCompatibility = function (geometry, program) { + // geometry must have at least all the attributes that the shader requires. + var geometryAttributes = geometry.attributes; + var shaderAttributes = program.attributeData; + for (var j in shaderAttributes) { + if (!geometryAttributes[j]) { + throw new Error("shader and geometry incompatible, geometry missing the \"" + j + "\" attribute"); + } + } + }; + /** + * Takes a geometry and program and generates a unique signature for them. + * @param geometry - To get signature from. + * @param program - To test geometry against. + * @returns - Unique signature of the geometry and program + */ + GeometrySystem.prototype.getSignature = function (geometry, program) { + var attribs = geometry.attributes; + var shaderAttributes = program.attributeData; + var strings = ['g', geometry.id]; + for (var i in attribs) { + if (shaderAttributes[i]) { + strings.push(i, shaderAttributes[i].location); + } + } + return strings.join('-'); + }; + /** + * Creates or gets Vao with the same structure as the geometry and stores it on the geometry. + * If vao is created, it is bound automatically. We use a shader to infer what and how to set up the + * attribute locations. + * @param geometry - Instance of geometry to to generate Vao for. + * @param shader - Instance of the shader. + * @param incRefCount - Increment refCount of all geometry buffers. + */ + GeometrySystem.prototype.initGeometryVao = function (geometry, shader, incRefCount) { + if (incRefCount === void 0) { incRefCount = true; } + var gl = this.gl; + var CONTEXT_UID = this.CONTEXT_UID; + var bufferSystem = this.renderer.buffer; + var program = shader.program; + if (!program.glPrograms[CONTEXT_UID]) { + this.renderer.shader.generateProgram(shader); + } + this.checkCompatibility(geometry, program); + var signature = this.getSignature(geometry, program); + var vaoObjectHash = geometry.glVertexArrayObjects[this.CONTEXT_UID]; + var vao = vaoObjectHash[signature]; + if (vao) { + // this will give us easy access to the vao + vaoObjectHash[program.id] = vao; + return vao; + } + var buffers = geometry.buffers; + var attributes = geometry.attributes; + var tempStride = {}; + var tempStart = {}; + for (var j in buffers) { + tempStride[j] = 0; + tempStart[j] = 0; + } + for (var j in attributes) { + if (!attributes[j].size && program.attributeData[j]) { + attributes[j].size = program.attributeData[j].size; + } + else if (!attributes[j].size) { + console.warn("PIXI Geometry attribute '" + j + "' size cannot be determined (likely the bound shader does not have the attribute)"); // eslint-disable-line + } + tempStride[attributes[j].buffer] += attributes[j].size * byteSizeMap[attributes[j].type]; + } + for (var j in attributes) { + var attribute = attributes[j]; + var attribSize = attribute.size; + if (attribute.stride === undefined) { + if (tempStride[attribute.buffer] === attribSize * byteSizeMap[attribute.type]) { + attribute.stride = 0; + } + else { + attribute.stride = tempStride[attribute.buffer]; + } + } + if (attribute.start === undefined) { + attribute.start = tempStart[attribute.buffer]; + tempStart[attribute.buffer] += attribSize * byteSizeMap[attribute.type]; + } + } + vao = gl.createVertexArray(); + gl.bindVertexArray(vao); + // first update - and create the buffers! + // only create a gl buffer if it actually gets + for (var i = 0; i < buffers.length; i++) { + var buffer = buffers[i]; + bufferSystem.bind(buffer); + if (incRefCount) { + buffer._glBuffers[CONTEXT_UID].refCount++; + } + } + // TODO - maybe make this a data object? + // lets wait to see if we need to first! + this.activateVao(geometry, program); + this._activeVao = vao; + // add it to the cache! + vaoObjectHash[program.id] = vao; + vaoObjectHash[signature] = vao; + return vao; + }; + /** + * Disposes geometry. + * @param geometry - Geometry with buffers. Only VAO will be disposed + * @param [contextLost=false] - If context was lost, we suppress deleteVertexArray + */ + GeometrySystem.prototype.disposeGeometry = function (geometry, contextLost) { + var _a; + if (!this.managedGeometries[geometry.id]) { + return; + } + delete this.managedGeometries[geometry.id]; + var vaos = geometry.glVertexArrayObjects[this.CONTEXT_UID]; + var gl = this.gl; + var buffers = geometry.buffers; + var bufferSystem = (_a = this.renderer) === null || _a === void 0 ? void 0 : _a.buffer; + geometry.disposeRunner.remove(this); + if (!vaos) { + return; + } + // bufferSystem may have already been destroyed.. + // if this is the case, there is no need to destroy the geometry buffers... + // they already have been! + if (bufferSystem) { + for (var i = 0; i < buffers.length; i++) { + var buf = buffers[i]._glBuffers[this.CONTEXT_UID]; + // my be null as context may have changed right before the dispose is called + if (buf) { + buf.refCount--; + if (buf.refCount === 0 && !contextLost) { + bufferSystem.dispose(buffers[i], contextLost); + } + } + } + } + if (!contextLost) { + for (var vaoId in vaos) { + // delete only signatures, everything else are copies + if (vaoId[0] === 'g') { + var vao = vaos[vaoId]; + if (this._activeVao === vao) { + this.unbind(); + } + gl.deleteVertexArray(vao); + } + } + } + delete geometry.glVertexArrayObjects[this.CONTEXT_UID]; + }; + /** + * Dispose all WebGL resources of all managed geometries. + * @param [contextLost=false] - If context was lost, we suppress `gl.delete` calls + */ + GeometrySystem.prototype.disposeAll = function (contextLost) { + var all = Object.keys(this.managedGeometries); + for (var i = 0; i < all.length; i++) { + this.disposeGeometry(this.managedGeometries[all[i]], contextLost); + } + }; + /** + * Activate vertex array object. + * @param geometry - Geometry instance. + * @param program - Shader program instance. + */ + GeometrySystem.prototype.activateVao = function (geometry, program) { + var gl = this.gl; + var CONTEXT_UID = this.CONTEXT_UID; + var bufferSystem = this.renderer.buffer; + var buffers = geometry.buffers; + var attributes = geometry.attributes; + if (geometry.indexBuffer) { + // first update the index buffer if we have one.. + bufferSystem.bind(geometry.indexBuffer); + } + var lastBuffer = null; + // add a new one! + for (var j in attributes) { + var attribute = attributes[j]; + var buffer = buffers[attribute.buffer]; + var glBuffer = buffer._glBuffers[CONTEXT_UID]; + if (program.attributeData[j]) { + if (lastBuffer !== glBuffer) { + bufferSystem.bind(buffer); + lastBuffer = glBuffer; + } + var location = program.attributeData[j].location; + // TODO introduce state again + // we can optimise this for older devices that have no VAOs + gl.enableVertexAttribArray(location); + gl.vertexAttribPointer(location, attribute.size, attribute.type || gl.FLOAT, attribute.normalized, attribute.stride, attribute.start); + if (attribute.instance) { + // TODO calculate instance count based of this... + if (this.hasInstance) { + gl.vertexAttribDivisor(location, 1); + } + else { + throw new Error('geometry error, GPU Instancing is not supported on this device'); + } + } + } + } + }; + /** + * Draws the currently bound geometry. + * @param type - The type primitive to render. + * @param size - The number of elements to be rendered. If not specified, all vertices after the + * starting vertex will be drawn. + * @param start - The starting vertex in the geometry to start drawing from. If not specified, + * drawing will start from the first vertex. + * @param instanceCount - The number of instances of the set of elements to execute. If not specified, + * all instances will be drawn. + */ + GeometrySystem.prototype.draw = function (type, size, start, instanceCount) { + var gl = this.gl; + var geometry = this._activeGeometry; + // TODO.. this should not change so maybe cache the function? + if (geometry.indexBuffer) { + var byteSize = geometry.indexBuffer.data.BYTES_PER_ELEMENT; + var glType = byteSize === 2 ? gl.UNSIGNED_SHORT : gl.UNSIGNED_INT; + if (byteSize === 2 || (byteSize === 4 && this.canUseUInt32ElementIndex)) { + if (geometry.instanced) { + /* eslint-disable max-len */ + gl.drawElementsInstanced(type, size || geometry.indexBuffer.data.length, glType, (start || 0) * byteSize, instanceCount || 1); + /* eslint-enable max-len */ + } + else { + /* eslint-disable max-len */ + gl.drawElements(type, size || geometry.indexBuffer.data.length, glType, (start || 0) * byteSize); + /* eslint-enable max-len */ + } + } + else { + console.warn('unsupported index buffer type: uint32'); + } + } + else if (geometry.instanced) { + // TODO need a better way to calculate size.. + gl.drawArraysInstanced(type, start, size || geometry.getSize(), instanceCount || 1); + } + else { + gl.drawArrays(type, start, size || geometry.getSize()); + } + return this; + }; + /** Unbind/reset everything. */ + GeometrySystem.prototype.unbind = function () { + this.gl.bindVertexArray(null); + this._activeVao = null; + this._activeGeometry = null; + }; + GeometrySystem.prototype.destroy = function () { + this.renderer = null; + }; + return GeometrySystem; + }()); + + /** + * Component for masked elements. + * + * Holds mask mode and temporary data about current mask. + * @memberof PIXI + */ + var MaskData = /** @class */ (function () { + /** + * Create MaskData + * @param {PIXI.DisplayObject} [maskObject=null] - object that describes the mask + */ + function MaskData(maskObject) { + if (maskObject === void 0) { maskObject = null; } + this.type = exports.MASK_TYPES.NONE; + this.autoDetect = true; + this.maskObject = maskObject || null; + this.pooled = false; + this.isMaskData = true; + this.resolution = null; + this.multisample = settings$1.FILTER_MULTISAMPLE; + this.enabled = true; + this.colorMask = 0xf; + this._filters = null; + this._stencilCounter = 0; + this._scissorCounter = 0; + this._scissorRect = null; + this._scissorRectLocal = null; + this._colorMask = 0xf; + this._target = null; + } + Object.defineProperty(MaskData.prototype, "filter", { + /** + * The sprite mask filter. + * If set to `null`, the default sprite mask filter is used. + * @default null + */ + get: function () { + return this._filters ? this._filters[0] : null; + }, + set: function (value) { + if (value) { + if (this._filters) { + this._filters[0] = value; + } + else { + this._filters = [value]; + } + } + else { + this._filters = null; + } + }, + enumerable: false, + configurable: true + }); + /** Resets the mask data after popMask(). */ + MaskData.prototype.reset = function () { + if (this.pooled) { + this.maskObject = null; + this.type = exports.MASK_TYPES.NONE; + this.autoDetect = true; + } + this._target = null; + this._scissorRectLocal = null; + }; + /** + * Copies counters from maskData above, called from pushMask(). + * @param maskAbove + */ + MaskData.prototype.copyCountersOrReset = function (maskAbove) { + if (maskAbove) { + this._stencilCounter = maskAbove._stencilCounter; + this._scissorCounter = maskAbove._scissorCounter; + this._scissorRect = maskAbove._scissorRect; + } + else { + this._stencilCounter = 0; + this._scissorCounter = 0; + this._scissorRect = null; + } + }; + return MaskData; + }()); + + /** + * @private + * @param {WebGLRenderingContext} gl - The current WebGL context {WebGLProgram} + * @param {number} type - the type, can be either VERTEX_SHADER or FRAGMENT_SHADER + * @param {string} src - The vertex shader source as an array of strings. + * @returns {WebGLShader} the shader + */ + function compileShader(gl, type, src) { + var shader = gl.createShader(type); + gl.shaderSource(shader, src); + gl.compileShader(shader); + return shader; + } + + /** + * will log a shader error highlighting the lines with the error + * also will add numbers along the side. + * @param gl - the WebGLContext + * @param shader - the shader to log errors for + */ + function logPrettyShaderError(gl, shader) { + var shaderSrc = gl.getShaderSource(shader) + .split('\n') + .map(function (line, index) { return index + ": " + line; }); + var shaderLog = gl.getShaderInfoLog(shader); + var splitShader = shaderLog.split('\n'); + var dedupe = {}; + var lineNumbers = splitShader.map(function (line) { return parseFloat(line.replace(/^ERROR\: 0\:([\d]+)\:.*$/, '$1')); }) + .filter(function (n) { + if (n && !dedupe[n]) { + dedupe[n] = true; + return true; + } + return false; + }); + var logArgs = ['']; + lineNumbers.forEach(function (number) { + shaderSrc[number - 1] = "%c" + shaderSrc[number - 1] + "%c"; + logArgs.push('background: #FF0000; color:#FFFFFF; font-size: 10px', 'font-size: 10px'); + }); + var fragmentSourceToLog = shaderSrc + .join('\n'); + logArgs[0] = fragmentSourceToLog; + console.error(shaderLog); + // eslint-disable-next-line no-console + console.groupCollapsed('click to view full shader code'); + console.warn.apply(console, logArgs); + // eslint-disable-next-line no-console + console.groupEnd(); + } + /** + * + * logs out any program errors + * @param gl - The current WebGL context + * @param program - the WebGL program to display errors for + * @param vertexShader - the fragment WebGL shader program + * @param fragmentShader - the vertex WebGL shader program + */ + function logProgramError(gl, program, vertexShader, fragmentShader) { + // if linking fails, then log and cleanup + if (!gl.getProgramParameter(program, gl.LINK_STATUS)) { + if (!gl.getShaderParameter(vertexShader, gl.COMPILE_STATUS)) { + logPrettyShaderError(gl, vertexShader); + } + if (!gl.getShaderParameter(fragmentShader, gl.COMPILE_STATUS)) { + logPrettyShaderError(gl, fragmentShader); + } + console.error('PixiJS Error: Could not initialize shader.'); + // if there is a program info log, log it + if (gl.getProgramInfoLog(program) !== '') { + console.warn('PixiJS Warning: gl.getProgramInfoLog()', gl.getProgramInfoLog(program)); + } + } + } + + function booleanArray(size) { + var array = new Array(size); + for (var i = 0; i < array.length; i++) { + array[i] = false; + } + return array; + } + /** + * @method defaultValue + * @memberof PIXI.glCore.shader + * @param {string} type - Type of value + * @param {number} size + * @private + */ + function defaultValue(type, size) { + switch (type) { + case 'float': + return 0; + case 'vec2': + return new Float32Array(2 * size); + case 'vec3': + return new Float32Array(3 * size); + case 'vec4': + return new Float32Array(4 * size); + case 'int': + case 'uint': + case 'sampler2D': + case 'sampler2DArray': + return 0; + case 'ivec2': + return new Int32Array(2 * size); + case 'ivec3': + return new Int32Array(3 * size); + case 'ivec4': + return new Int32Array(4 * size); + case 'uvec2': + return new Uint32Array(2 * size); + case 'uvec3': + return new Uint32Array(3 * size); + case 'uvec4': + return new Uint32Array(4 * size); + case 'bool': + return false; + case 'bvec2': + return booleanArray(2 * size); + case 'bvec3': + return booleanArray(3 * size); + case 'bvec4': + return booleanArray(4 * size); + case 'mat2': + return new Float32Array([1, 0, + 0, 1]); + case 'mat3': + return new Float32Array([1, 0, 0, + 0, 1, 0, + 0, 0, 1]); + case 'mat4': + return new Float32Array([1, 0, 0, 0, + 0, 1, 0, 0, + 0, 0, 1, 0, + 0, 0, 0, 1]); + } + return null; + } + + var unknownContext = {}; + var context = unknownContext; + /** + * returns a little WebGL context to use for program inspection. + * @static + * @private + * @returns {WebGLRenderingContext} a gl context to test with + */ + function getTestContext() { + if (context === unknownContext || (context && context.isContextLost())) { + var canvas = settings$1.ADAPTER.createCanvas(); + var gl = void 0; + if (settings$1.PREFER_ENV >= exports.ENV.WEBGL2) { + gl = canvas.getContext('webgl2', {}); + } + if (!gl) { + gl = (canvas.getContext('webgl', {}) + || canvas.getContext('experimental-webgl', {})); + if (!gl) { + // fail, not able to get a context + gl = null; + } + else { + // for shader testing.. + gl.getExtension('WEBGL_draw_buffers'); + } + } + context = gl; + } + return context; + } + + var maxFragmentPrecision; + function getMaxFragmentPrecision() { + if (!maxFragmentPrecision) { + maxFragmentPrecision = exports.PRECISION.MEDIUM; + var gl = getTestContext(); + if (gl) { + if (gl.getShaderPrecisionFormat) { + var shaderFragment = gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.HIGH_FLOAT); + maxFragmentPrecision = shaderFragment.precision ? exports.PRECISION.HIGH : exports.PRECISION.MEDIUM; + } + } + } + return maxFragmentPrecision; + } + + /** + * Sets the float precision on the shader, ensuring the device supports the request precision. + * If the precision is already present, it just ensures that the device is able to handle it. + * @private + * @param {string} src - The shader source + * @param {PIXI.PRECISION} requestedPrecision - The request float precision of the shader. + * @param {PIXI.PRECISION} maxSupportedPrecision - The maximum precision the shader supports. + * @returns {string} modified shader source + */ + function setPrecision(src, requestedPrecision, maxSupportedPrecision) { + if (src.substring(0, 9) !== 'precision') { + // no precision supplied, so PixiJS will add the requested level. + var precision = requestedPrecision; + // If highp is requested but not supported, downgrade precision to a level all devices support. + if (requestedPrecision === exports.PRECISION.HIGH && maxSupportedPrecision !== exports.PRECISION.HIGH) { + precision = exports.PRECISION.MEDIUM; + } + return "precision " + precision + " float;\n" + src; + } + else if (maxSupportedPrecision !== exports.PRECISION.HIGH && src.substring(0, 15) === 'precision highp') { + // precision was supplied, but at a level this device does not support, so downgrading to mediump. + return src.replace('precision highp', 'precision mediump'); + } + return src; + } + + var GLSL_TO_SIZE = { + float: 1, + vec2: 2, + vec3: 3, + vec4: 4, + int: 1, + ivec2: 2, + ivec3: 3, + ivec4: 4, + uint: 1, + uvec2: 2, + uvec3: 3, + uvec4: 4, + bool: 1, + bvec2: 2, + bvec3: 3, + bvec4: 4, + mat2: 4, + mat3: 9, + mat4: 16, + sampler2D: 1, + }; + /** + * @private + * @method mapSize + * @memberof PIXI.glCore.shader + * @param {string} type + */ + function mapSize(type) { + return GLSL_TO_SIZE[type]; + } + + var GL_TABLE = null; + var GL_TO_GLSL_TYPES = { + FLOAT: 'float', + FLOAT_VEC2: 'vec2', + FLOAT_VEC3: 'vec3', + FLOAT_VEC4: 'vec4', + INT: 'int', + INT_VEC2: 'ivec2', + INT_VEC3: 'ivec3', + INT_VEC4: 'ivec4', + UNSIGNED_INT: 'uint', + UNSIGNED_INT_VEC2: 'uvec2', + UNSIGNED_INT_VEC3: 'uvec3', + UNSIGNED_INT_VEC4: 'uvec4', + BOOL: 'bool', + BOOL_VEC2: 'bvec2', + BOOL_VEC3: 'bvec3', + BOOL_VEC4: 'bvec4', + FLOAT_MAT2: 'mat2', + FLOAT_MAT3: 'mat3', + FLOAT_MAT4: 'mat4', + SAMPLER_2D: 'sampler2D', + INT_SAMPLER_2D: 'sampler2D', + UNSIGNED_INT_SAMPLER_2D: 'sampler2D', + SAMPLER_CUBE: 'samplerCube', + INT_SAMPLER_CUBE: 'samplerCube', + UNSIGNED_INT_SAMPLER_CUBE: 'samplerCube', + SAMPLER_2D_ARRAY: 'sampler2DArray', + INT_SAMPLER_2D_ARRAY: 'sampler2DArray', + UNSIGNED_INT_SAMPLER_2D_ARRAY: 'sampler2DArray', + }; + // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types + function mapType(gl, type) { + if (!GL_TABLE) { + var typeNames = Object.keys(GL_TO_GLSL_TYPES); + GL_TABLE = {}; + for (var i = 0; i < typeNames.length; ++i) { + var tn = typeNames[i]; + GL_TABLE[gl[tn]] = GL_TO_GLSL_TYPES[tn]; + } + } + return GL_TABLE[type]; + } + + /* eslint-disable @typescript-eslint/explicit-module-boundary-types */ + // Parsers, each one of these will take a look at the type of shader property and uniform. + // if they pass the test function then the code function is called that returns a the shader upload code for that uniform. + // Shader upload code is automagically generated with these parsers. + // If no parser is valid then the default upload functions are used. + // exposing Parsers means that custom upload logic can be added to pixi's shaders. + // A good example would be a pixi rectangle can be directly set on a uniform. + // If the shader sees it it knows how to upload the rectangle structure as a vec4 + // format is as follows: + // + // { + // test: (data, uniform) => {} <--- test is this code should be used for this uniform + // code: (name, uniform) => {} <--- returns the string of the piece of code that uploads the uniform + // codeUbo: (name, uniform) => {} <--- returns the string of the piece of code that uploads the + // uniform to a uniform buffer + // } + var uniformParsers = [ + // a float cache layer + { + test: function (data) { + return data.type === 'float' && data.size === 1; + }, + code: function (name) { + return "\n if(uv[\"" + name + "\"] !== ud[\"" + name + "\"].value)\n {\n ud[\"" + name + "\"].value = uv[\"" + name + "\"]\n gl.uniform1f(ud[\"" + name + "\"].location, uv[\"" + name + "\"])\n }\n "; + }, + }, + // handling samplers + { + test: function (data, uniform) { + // eslint-disable-next-line max-len,no-eq-null,eqeqeq + return (data.type === 'sampler2D' || data.type === 'samplerCube' || data.type === 'sampler2DArray') && data.size === 1 && !data.isArray && (uniform == null || uniform.castToBaseTexture !== undefined); + }, + code: function (name) { return "t = syncData.textureCount++;\n\n renderer.texture.bind(uv[\"" + name + "\"], t);\n\n if(ud[\"" + name + "\"].value !== t)\n {\n ud[\"" + name + "\"].value = t;\n gl.uniform1i(ud[\"" + name + "\"].location, t);\n; // eslint-disable-line max-len\n }"; }, + }, + // uploading pixi matrix object to mat3 + { + test: function (data, uniform) { + return data.type === 'mat3' && data.size === 1 && uniform.a !== undefined; + }, + code: function (name) { + // TODO and some smart caching dirty ids here! + return "\n gl.uniformMatrix3fv(ud[\"" + name + "\"].location, false, uv[\"" + name + "\"].toArray(true));\n "; + }, + codeUbo: function (name) { + return "\n var " + name + "_matrix = uv." + name + ".toArray(true);\n\n data[offset] = " + name + "_matrix[0];\n data[offset+1] = " + name + "_matrix[1];\n data[offset+2] = " + name + "_matrix[2];\n \n data[offset + 4] = " + name + "_matrix[3];\n data[offset + 5] = " + name + "_matrix[4];\n data[offset + 6] = " + name + "_matrix[5];\n \n data[offset + 8] = " + name + "_matrix[6];\n data[offset + 9] = " + name + "_matrix[7];\n data[offset + 10] = " + name + "_matrix[8];\n "; + }, + }, + // uploading a pixi point as a vec2 with caching layer + { + test: function (data, uniform) { + return data.type === 'vec2' && data.size === 1 && uniform.x !== undefined; + }, + code: function (name) { + return "\n cv = ud[\"" + name + "\"].value;\n v = uv[\"" + name + "\"];\n\n if(cv[0] !== v.x || cv[1] !== v.y)\n {\n cv[0] = v.x;\n cv[1] = v.y;\n gl.uniform2f(ud[\"" + name + "\"].location, v.x, v.y);\n }"; + }, + codeUbo: function (name) { + return "\n v = uv." + name + ";\n\n data[offset] = v.x;\n data[offset+1] = v.y;\n "; + } + }, + // caching layer for a vec2 + { + test: function (data) { + return data.type === 'vec2' && data.size === 1; + }, + code: function (name) { + return "\n cv = ud[\"" + name + "\"].value;\n v = uv[\"" + name + "\"];\n\n if(cv[0] !== v[0] || cv[1] !== v[1])\n {\n cv[0] = v[0];\n cv[1] = v[1];\n gl.uniform2f(ud[\"" + name + "\"].location, v[0], v[1]);\n }\n "; + }, + }, + // upload a pixi rectangle as a vec4 with caching layer + { + test: function (data, uniform) { + return data.type === 'vec4' && data.size === 1 && uniform.width !== undefined; + }, + code: function (name) { + return "\n cv = ud[\"" + name + "\"].value;\n v = uv[\"" + name + "\"];\n\n if(cv[0] !== v.x || cv[1] !== v.y || cv[2] !== v.width || cv[3] !== v.height)\n {\n cv[0] = v.x;\n cv[1] = v.y;\n cv[2] = v.width;\n cv[3] = v.height;\n gl.uniform4f(ud[\"" + name + "\"].location, v.x, v.y, v.width, v.height)\n }"; + }, + codeUbo: function (name) { + return "\n v = uv." + name + ";\n\n data[offset] = v.x;\n data[offset+1] = v.y;\n data[offset+2] = v.width;\n data[offset+3] = v.height;\n "; + } + }, + // a caching layer for vec4 uploading + { + test: function (data) { + return data.type === 'vec4' && data.size === 1; + }, + code: function (name) { + return "\n cv = ud[\"" + name + "\"].value;\n v = uv[\"" + name + "\"];\n\n if(cv[0] !== v[0] || cv[1] !== v[1] || cv[2] !== v[2] || cv[3] !== v[3])\n {\n cv[0] = v[0];\n cv[1] = v[1];\n cv[2] = v[2];\n cv[3] = v[3];\n\n gl.uniform4f(ud[\"" + name + "\"].location, v[0], v[1], v[2], v[3])\n }"; + }, + } ]; + + // cu = Cached value's uniform data field + // cv = Cached value + // v = value to upload + // ud = uniformData + // uv = uniformValue + // l = location + var GLSL_TO_SINGLE_SETTERS_CACHED = { + float: "\n if (cv !== v)\n {\n cu.value = v;\n gl.uniform1f(location, v);\n }", + vec2: "\n if (cv[0] !== v[0] || cv[1] !== v[1])\n {\n cv[0] = v[0];\n cv[1] = v[1];\n\n gl.uniform2f(location, v[0], v[1])\n }", + vec3: "\n if (cv[0] !== v[0] || cv[1] !== v[1] || cv[2] !== v[2])\n {\n cv[0] = v[0];\n cv[1] = v[1];\n cv[2] = v[2];\n\n gl.uniform3f(location, v[0], v[1], v[2])\n }", + vec4: "\n if (cv[0] !== v[0] || cv[1] !== v[1] || cv[2] !== v[2] || cv[3] !== v[3])\n {\n cv[0] = v[0];\n cv[1] = v[1];\n cv[2] = v[2];\n cv[3] = v[3];\n\n gl.uniform4f(location, v[0], v[1], v[2], v[3]);\n }", + int: "\n if (cv !== v)\n {\n cu.value = v;\n\n gl.uniform1i(location, v);\n }", + ivec2: "\n if (cv[0] !== v[0] || cv[1] !== v[1])\n {\n cv[0] = v[0];\n cv[1] = v[1];\n\n gl.uniform2i(location, v[0], v[1]);\n }", + ivec3: "\n if (cv[0] !== v[0] || cv[1] !== v[1] || cv[2] !== v[2])\n {\n cv[0] = v[0];\n cv[1] = v[1];\n cv[2] = v[2];\n\n gl.uniform3i(location, v[0], v[1], v[2]);\n }", + ivec4: "\n if (cv[0] !== v[0] || cv[1] !== v[1] || cv[2] !== v[2] || cv[3] !== v[3])\n {\n cv[0] = v[0];\n cv[1] = v[1];\n cv[2] = v[2];\n cv[3] = v[3];\n\n gl.uniform4i(location, v[0], v[1], v[2], v[3]);\n }", + uint: "\n if (cv !== v)\n {\n cu.value = v;\n\n gl.uniform1ui(location, v);\n }", + uvec2: "\n if (cv[0] !== v[0] || cv[1] !== v[1])\n {\n cv[0] = v[0];\n cv[1] = v[1];\n\n gl.uniform2ui(location, v[0], v[1]);\n }", + uvec3: "\n if (cv[0] !== v[0] || cv[1] !== v[1] || cv[2] !== v[2])\n {\n cv[0] = v[0];\n cv[1] = v[1];\n cv[2] = v[2];\n\n gl.uniform3ui(location, v[0], v[1], v[2]);\n }", + uvec4: "\n if (cv[0] !== v[0] || cv[1] !== v[1] || cv[2] !== v[2] || cv[3] !== v[3])\n {\n cv[0] = v[0];\n cv[1] = v[1];\n cv[2] = v[2];\n cv[3] = v[3];\n\n gl.uniform4ui(location, v[0], v[1], v[2], v[3]);\n }", + bool: "\n if (cv !== v)\n {\n cu.value = v;\n gl.uniform1i(location, v);\n }", + bvec2: "\n if (cv[0] != v[0] || cv[1] != v[1])\n {\n cv[0] = v[0];\n cv[1] = v[1];\n\n gl.uniform2i(location, v[0], v[1]);\n }", + bvec3: "\n if (cv[0] !== v[0] || cv[1] !== v[1] || cv[2] !== v[2])\n {\n cv[0] = v[0];\n cv[1] = v[1];\n cv[2] = v[2];\n\n gl.uniform3i(location, v[0], v[1], v[2]);\n }", + bvec4: "\n if (cv[0] !== v[0] || cv[1] !== v[1] || cv[2] !== v[2] || cv[3] !== v[3])\n {\n cv[0] = v[0];\n cv[1] = v[1];\n cv[2] = v[2];\n cv[3] = v[3];\n\n gl.uniform4i(location, v[0], v[1], v[2], v[3]);\n }", + mat2: 'gl.uniformMatrix2fv(location, false, v)', + mat3: 'gl.uniformMatrix3fv(location, false, v)', + mat4: 'gl.uniformMatrix4fv(location, false, v)', + sampler2D: "\n if (cv !== v)\n {\n cu.value = v;\n\n gl.uniform1i(location, v);\n }", + samplerCube: "\n if (cv !== v)\n {\n cu.value = v;\n\n gl.uniform1i(location, v);\n }", + sampler2DArray: "\n if (cv !== v)\n {\n cu.value = v;\n\n gl.uniform1i(location, v);\n }", + }; + var GLSL_TO_ARRAY_SETTERS = { + float: "gl.uniform1fv(location, v)", + vec2: "gl.uniform2fv(location, v)", + vec3: "gl.uniform3fv(location, v)", + vec4: 'gl.uniform4fv(location, v)', + mat4: 'gl.uniformMatrix4fv(location, false, v)', + mat3: 'gl.uniformMatrix3fv(location, false, v)', + mat2: 'gl.uniformMatrix2fv(location, false, v)', + int: 'gl.uniform1iv(location, v)', + ivec2: 'gl.uniform2iv(location, v)', + ivec3: 'gl.uniform3iv(location, v)', + ivec4: 'gl.uniform4iv(location, v)', + uint: 'gl.uniform1uiv(location, v)', + uvec2: 'gl.uniform2uiv(location, v)', + uvec3: 'gl.uniform3uiv(location, v)', + uvec4: 'gl.uniform4uiv(location, v)', + bool: 'gl.uniform1iv(location, v)', + bvec2: 'gl.uniform2iv(location, v)', + bvec3: 'gl.uniform3iv(location, v)', + bvec4: 'gl.uniform4iv(location, v)', + sampler2D: 'gl.uniform1iv(location, v)', + samplerCube: 'gl.uniform1iv(location, v)', + sampler2DArray: 'gl.uniform1iv(location, v)', + }; + function generateUniformsSync(group, uniformData) { + var _a; + var funcFragments = ["\n var v = null;\n var cv = null;\n var cu = null;\n var t = 0;\n var gl = renderer.gl;\n "]; + for (var i in group.uniforms) { + var data = uniformData[i]; + if (!data) { + if ((_a = group.uniforms[i]) === null || _a === void 0 ? void 0 : _a.group) { + if (group.uniforms[i].ubo) { + funcFragments.push("\n renderer.shader.syncUniformBufferGroup(uv." + i + ", '" + i + "');\n "); + } + else { + funcFragments.push("\n renderer.shader.syncUniformGroup(uv." + i + ", syncData);\n "); + } + } + continue; + } + var uniform = group.uniforms[i]; + var parsed = false; + for (var j = 0; j < uniformParsers.length; j++) { + if (uniformParsers[j].test(data, uniform)) { + funcFragments.push(uniformParsers[j].code(i, uniform)); + parsed = true; + break; + } + } + if (!parsed) { + var templateType = (data.size === 1) ? GLSL_TO_SINGLE_SETTERS_CACHED : GLSL_TO_ARRAY_SETTERS; + var template = templateType[data.type].replace('location', "ud[\"" + i + "\"].location"); + funcFragments.push("\n cu = ud[\"" + i + "\"];\n cv = cu.value;\n v = uv[\"" + i + "\"];\n " + template + ";"); + } + } + /* + * the introduction of syncData is to solve an issue where textures in uniform groups are not set correctly + * the texture count was always starting from 0 in each group. This needs to increment each time a texture is used + * no matter which group is being used + * + */ + // eslint-disable-next-line no-new-func + return new Function('ud', 'uv', 'renderer', 'syncData', funcFragments.join('\n')); + } + + var fragTemplate$1 = [ + 'precision mediump float;', + 'void main(void){', + 'float test = 0.1;', + '%forloop%', + 'gl_FragColor = vec4(0.0);', + '}' ].join('\n'); + function generateIfTestSrc(maxIfs) { + var src = ''; + for (var i = 0; i < maxIfs; ++i) { + if (i > 0) { + src += '\nelse '; + } + if (i < maxIfs - 1) { + src += "if(test == " + i + ".0){}"; + } + } + return src; + } + function checkMaxIfStatementsInShader(maxIfs, gl) { + if (maxIfs === 0) { + throw new Error('Invalid value of `0` passed to `checkMaxIfStatementsInShader`'); + } + var shader = gl.createShader(gl.FRAGMENT_SHADER); + while (true) // eslint-disable-line no-constant-condition + { + var fragmentSrc = fragTemplate$1.replace(/%forloop%/gi, generateIfTestSrc(maxIfs)); + gl.shaderSource(shader, fragmentSrc); + gl.compileShader(shader); + if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) { + maxIfs = (maxIfs / 2) | 0; + } + else { + // valid! + break; + } + } + return maxIfs; + } + + // Cache the result to prevent running this over and over + var unsafeEval; + /** + * Not all platforms allow to generate function code (e.g., `new Function`). + * this provides the platform-level detection. + * @private + * @returns {boolean} `true` if `new Function` is supported. + */ + function unsafeEvalSupported() { + if (typeof unsafeEval === 'boolean') { + return unsafeEval; + } + try { + /* eslint-disable no-new-func */ + var func = new Function('param1', 'param2', 'param3', 'return param1[param2] === param3;'); + /* eslint-enable no-new-func */ + unsafeEval = func({ a: 'b' }, 'a', 'b') === true; + } + catch (e) { + unsafeEval = false; + } + return unsafeEval; + } + + var defaultFragment$2 = "varying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\n\nvoid main(void){\n gl_FragColor *= texture2D(uSampler, vTextureCoord);\n}"; + + var defaultVertex$3 = "attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void){\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n vTextureCoord = aTextureCoord;\n}\n"; + + var UID$1 = 0; + var nameCache = {}; + /** + * Helper class to create a shader program. + * @memberof PIXI + */ + var Program = /** @class */ (function () { + /** + * @param vertexSrc - The source of the vertex shader. + * @param fragmentSrc - The source of the fragment shader. + * @param name - Name for shader + */ + function Program(vertexSrc, fragmentSrc, name) { + if (name === void 0) { name = 'pixi-shader'; } + this.id = UID$1++; + this.vertexSrc = vertexSrc || Program.defaultVertexSrc; + this.fragmentSrc = fragmentSrc || Program.defaultFragmentSrc; + this.vertexSrc = this.vertexSrc.trim(); + this.fragmentSrc = this.fragmentSrc.trim(); + if (this.vertexSrc.substring(0, 8) !== '#version') { + name = name.replace(/\s+/g, '-'); + if (nameCache[name]) { + nameCache[name]++; + name += "-" + nameCache[name]; + } + else { + nameCache[name] = 1; + } + this.vertexSrc = "#define SHADER_NAME " + name + "\n" + this.vertexSrc; + this.fragmentSrc = "#define SHADER_NAME " + name + "\n" + this.fragmentSrc; + this.vertexSrc = setPrecision(this.vertexSrc, settings$1.PRECISION_VERTEX, exports.PRECISION.HIGH); + this.fragmentSrc = setPrecision(this.fragmentSrc, settings$1.PRECISION_FRAGMENT, getMaxFragmentPrecision()); + } + // currently this does not extract structs only default types + // this is where we store shader references.. + this.glPrograms = {}; + this.syncUniforms = null; + } + Object.defineProperty(Program, "defaultVertexSrc", { + /** + * The default vertex shader source. + * @constant + */ + get: function () { + return defaultVertex$3; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(Program, "defaultFragmentSrc", { + /** + * The default fragment shader source. + * @constant + */ + get: function () { + return defaultFragment$2; + }, + enumerable: false, + configurable: true + }); + /** + * A short hand function to create a program based of a vertex and fragment shader. + * + * This method will also check to see if there is a cached program. + * @param vertexSrc - The source of the vertex shader. + * @param fragmentSrc - The source of the fragment shader. + * @param name - Name for shader + * @returns A shiny new PixiJS shader program! + */ + Program.from = function (vertexSrc, fragmentSrc, name) { + var key = vertexSrc + fragmentSrc; + var program = ProgramCache[key]; + if (!program) { + ProgramCache[key] = program = new Program(vertexSrc, fragmentSrc, name); + } + return program; + }; + return Program; + }()); + + /** + * A helper class for shaders. + * @memberof PIXI + */ + var Shader = /** @class */ (function () { + /** + * @param program - The program the shader will use. + * @param uniforms - Custom uniforms to use to augment the built-in ones. + */ + function Shader(program, uniforms) { + /** + * Used internally to bind uniform buffer objects. + * @ignore + */ + this.uniformBindCount = 0; + this.program = program; + // lets see whats been passed in + // uniforms should be converted to a uniform group + if (uniforms) { + if (uniforms instanceof UniformGroup) { + this.uniformGroup = uniforms; + } + else { + this.uniformGroup = new UniformGroup(uniforms); + } + } + else { + this.uniformGroup = new UniformGroup({}); + } + } + // TODO move to shader system.. + Shader.prototype.checkUniformExists = function (name, group) { + if (group.uniforms[name]) { + return true; + } + for (var i in group.uniforms) { + var uniform = group.uniforms[i]; + if (uniform.group) { + if (this.checkUniformExists(name, uniform)) { + return true; + } + } + } + return false; + }; + Shader.prototype.destroy = function () { + // usage count on programs? + // remove if not used! + this.uniformGroup = null; + }; + Object.defineProperty(Shader.prototype, "uniforms", { + /** + * Shader uniform values, shortcut for `uniformGroup.uniforms`. + * @readonly + */ + get: function () { + return this.uniformGroup.uniforms; + }, + enumerable: false, + configurable: true + }); + /** + * A short hand function to create a shader based of a vertex and fragment shader. + * @param vertexSrc - The source of the vertex shader. + * @param fragmentSrc - The source of the fragment shader. + * @param uniforms - Custom uniforms to use to augment the built-in ones. + * @returns A shiny new PixiJS shader! + */ + Shader.from = function (vertexSrc, fragmentSrc, uniforms) { + var program = Program.from(vertexSrc, fragmentSrc); + return new Shader(program, uniforms); + }; + return Shader; + }()); + + /* eslint-disable max-len */ + var BLEND$1 = 0; + var OFFSET$1 = 1; + var CULLING$1 = 2; + var DEPTH_TEST$1 = 3; + var WINDING$1 = 4; + var DEPTH_MASK$1 = 5; + /** + * This is a WebGL state, and is is passed to {@link PIXI.StateSystem}. + * + * Each mesh rendered may require WebGL to be in a different state. + * For example you may want different blend mode or to enable polygon offsets + * @memberof PIXI + */ + var State = /** @class */ (function () { + function State() { + this.data = 0; + this.blendMode = exports.BLEND_MODES.NORMAL; + this.polygonOffset = 0; + this.blend = true; + this.depthMask = true; + // this.depthTest = true; + } + Object.defineProperty(State.prototype, "blend", { + /** + * Activates blending of the computed fragment color values. + * @default true + */ + get: function () { + return !!(this.data & (1 << BLEND$1)); + }, + set: function (value) { + if (!!(this.data & (1 << BLEND$1)) !== value) { + this.data ^= (1 << BLEND$1); + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(State.prototype, "offsets", { + /** + * Activates adding an offset to depth values of polygon's fragments + * @default false + */ + get: function () { + return !!(this.data & (1 << OFFSET$1)); + }, + set: function (value) { + if (!!(this.data & (1 << OFFSET$1)) !== value) { + this.data ^= (1 << OFFSET$1); + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(State.prototype, "culling", { + /** + * Activates culling of polygons. + * @default false + */ + get: function () { + return !!(this.data & (1 << CULLING$1)); + }, + set: function (value) { + if (!!(this.data & (1 << CULLING$1)) !== value) { + this.data ^= (1 << CULLING$1); + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(State.prototype, "depthTest", { + /** + * Activates depth comparisons and updates to the depth buffer. + * @default false + */ + get: function () { + return !!(this.data & (1 << DEPTH_TEST$1)); + }, + set: function (value) { + if (!!(this.data & (1 << DEPTH_TEST$1)) !== value) { + this.data ^= (1 << DEPTH_TEST$1); + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(State.prototype, "depthMask", { + /** + * Enables or disables writing to the depth buffer. + * @default true + */ + get: function () { + return !!(this.data & (1 << DEPTH_MASK$1)); + }, + set: function (value) { + if (!!(this.data & (1 << DEPTH_MASK$1)) !== value) { + this.data ^= (1 << DEPTH_MASK$1); + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(State.prototype, "clockwiseFrontFace", { + /** + * Specifies whether or not front or back-facing polygons can be culled. + * @default false + */ + get: function () { + return !!(this.data & (1 << WINDING$1)); + }, + set: function (value) { + if (!!(this.data & (1 << WINDING$1)) !== value) { + this.data ^= (1 << WINDING$1); + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(State.prototype, "blendMode", { + /** + * The blend mode to be applied when this state is set. Apply a value of `PIXI.BLEND_MODES.NORMAL` to reset the blend mode. + * Setting this mode to anything other than NO_BLEND will automatically switch blending on. + * @default PIXI.BLEND_MODES.NORMAL + */ + get: function () { + return this._blendMode; + }, + set: function (value) { + this.blend = (value !== exports.BLEND_MODES.NONE); + this._blendMode = value; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(State.prototype, "polygonOffset", { + /** + * The polygon offset. Setting this property to anything other than 0 will automatically enable polygon offset fill. + * @default 0 + */ + get: function () { + return this._polygonOffset; + }, + set: function (value) { + this.offsets = !!value; + this._polygonOffset = value; + }, + enumerable: false, + configurable: true + }); + State.prototype.toString = function () { + return "[@pixi/core:State " + + ("blendMode=" + this.blendMode + " ") + + ("clockwiseFrontFace=" + this.clockwiseFrontFace + " ") + + ("culling=" + this.culling + " ") + + ("depthMask=" + this.depthMask + " ") + + ("polygonOffset=" + this.polygonOffset) + + "]"; + }; + State.for2d = function () { + var state = new State(); + state.depthTest = false; + state.blend = true; + return state; + }; + return State; + }()); + + var defaultFragment$1 = "varying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\n\nvoid main(void){\n gl_FragColor = texture2D(uSampler, vTextureCoord);\n}\n"; + + var defaultVertex$2 = "attribute vec2 aVertexPosition;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 vTextureCoord;\n\nuniform vec4 inputSize;\nuniform vec4 outputFrame;\n\nvec4 filterVertexPosition( void )\n{\n vec2 position = aVertexPosition * max(outputFrame.zw, vec2(0.)) + outputFrame.xy;\n\n return vec4((projectionMatrix * vec3(position, 1.0)).xy, 0.0, 1.0);\n}\n\nvec2 filterTextureCoord( void )\n{\n return aVertexPosition * (outputFrame.zw * inputSize.zw);\n}\n\nvoid main(void)\n{\n gl_Position = filterVertexPosition();\n vTextureCoord = filterTextureCoord();\n}\n"; + + /** + * A filter is a special shader that applies post-processing effects to an input texture and writes into an output + * render-target. + * + * {@link http://pixijs.io/examples/#/filters/blur-filter.js Example} of the + * {@link PIXI.filters.BlurFilter BlurFilter}. + * + * ### Usage + * Filters can be applied to any DisplayObject or Container. + * PixiJS' `FilterSystem` renders the container into temporary Framebuffer, + * then filter renders it to the screen. + * Multiple filters can be added to the `filters` array property and stacked on each other. + * + * ``` + * const filter = new PIXI.Filter(myShaderVert, myShaderFrag, { myUniform: 0.5 }); + * const container = new PIXI.Container(); + * container.filters = [filter]; + * ``` + * + * ### Previous Version Differences + * + * In PixiJS **v3**, a filter was always applied to _whole screen_. + * + * In PixiJS **v4**, a filter can be applied _only part of the screen_. + * Developers had to create a set of uniforms to deal with coordinates. + * + * In PixiJS **v5** combines _both approaches_. + * Developers can use normal coordinates of v3 and then allow filter to use partial Framebuffers, + * bringing those extra uniforms into account. + * + * Also be aware that we have changed default vertex shader, please consult + * {@link https://github.com/pixijs/pixi.js/wiki/v5-Creating-filters Wiki}. + * + * ### Frames + * + * The following table summarizes the coordinate spaces used in the filtering pipeline: + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
Coordinate SpaceDescription
Texture Coordinates + * The texture (or UV) coordinates in the input base-texture's space. These are normalized into the (0,1) range along + * both axes. + *
World Space + * A point in the same space as the world bounds of any display-object (i.e. in the scene graph's space). + *
Physical Pixels + * This is base-texture's space with the origin on the top-left. You can calculate these by multiplying the texture + * coordinates by the dimensions of the texture. + *
+ * + * ### Built-in Uniforms + * + * PixiJS viewport uses screen (CSS) coordinates, `(0, 0, renderer.screen.width, renderer.screen.height)`, + * and `projectionMatrix` uniform maps it to the gl viewport. + * + * **uSampler** + * + * The most important uniform is the input texture that container was rendered into. + * _Important note: as with all Framebuffers in PixiJS, both input and output are + * premultiplied by alpha._ + * + * By default, input normalized coordinates are passed to fragment shader with `vTextureCoord`. + * Use it to sample the input. + * + * ``` + * const fragment = ` + * varying vec2 vTextureCoord; + * uniform sampler2D uSampler; + * void main(void) + * { + * gl_FragColor = texture2D(uSampler, vTextureCoord); + * } + * `; + * + * const myFilter = new PIXI.Filter(null, fragment); + * ``` + * + * This filter is just one uniform less than {@link PIXI.filters.AlphaFilter AlphaFilter}. + * + * **outputFrame** + * + * The `outputFrame` holds the rectangle where filter is applied in screen (CSS) coordinates. + * It's the same as `renderer.screen` for a fullscreen filter. + * Only a part of `outputFrame.zw` size of temporary Framebuffer is used, + * `(0, 0, outputFrame.width, outputFrame.height)`, + * + * Filters uses this quad to normalized (0-1) space, its passed into `aVertexPosition` attribute. + * To calculate vertex position in screen space using normalized (0-1) space: + * + * ``` + * vec4 filterVertexPosition( void ) + * { + * vec2 position = aVertexPosition * max(outputFrame.zw, vec2(0.)) + outputFrame.xy; + * return vec4((projectionMatrix * vec3(position, 1.0)).xy, 0.0, 1.0); + * } + * ``` + * + * **inputSize** + * + * Temporary framebuffer is different, it can be either the size of screen, either power-of-two. + * The `inputSize.xy` are size of temporary framebuffer that holds input. + * The `inputSize.zw` is inverted, it's a shortcut to evade division inside the shader. + * + * Set `inputSize.xy = outputFrame.zw` for a fullscreen filter. + * + * To calculate input normalized coordinate, you have to map it to filter normalized space. + * Multiply by `outputFrame.zw` to get input coordinate. + * Divide by `inputSize.xy` to get input normalized coordinate. + * + * ``` + * vec2 filterTextureCoord( void ) + * { + * return aVertexPosition * (outputFrame.zw * inputSize.zw); // same as /inputSize.xy + * } + * ``` + * **resolution** + * + * The `resolution` is the ratio of screen (CSS) pixels to real pixels. + * + * **inputPixel** + * + * `inputPixel.xy` is the size of framebuffer in real pixels, same as `inputSize.xy * resolution` + * `inputPixel.zw` is inverted `inputPixel.xy`. + * + * It's handy for filters that use neighbour pixels, like {@link PIXI.filters.FXAAFilter FXAAFilter}. + * + * **inputClamp** + * + * If you try to get info from outside of used part of Framebuffer - you'll get undefined behaviour. + * For displacements, coordinates has to be clamped. + * + * The `inputClamp.xy` is left-top pixel center, you may ignore it, because we use left-top part of Framebuffer + * `inputClamp.zw` is bottom-right pixel center. + * + * ``` + * vec4 color = texture2D(uSampler, clamp(modifiedTextureCoord, inputClamp.xy, inputClamp.zw)) + * ``` + * OR + * ``` + * vec4 color = texture2D(uSampler, min(modifigedTextureCoord, inputClamp.zw)) + * ``` + * + * ### Additional Information + * + * Complete documentation on Filter usage is located in the + * {@link https://github.com/pixijs/pixi.js/wiki/v5-Creating-filters Wiki}. + * + * Since PixiJS only had a handful of built-in filters, additional filters can be downloaded + * {@link https://github.com/pixijs/pixi-filters here} from the PixiJS Filters repository. + * @memberof PIXI + */ + var Filter = /** @class */ (function (_super) { + __extends$i(Filter, _super); + /** + * @param vertexSrc - The source of the vertex shader. + * @param fragmentSrc - The source of the fragment shader. + * @param uniforms - Custom uniforms to use to augment the built-in ones. + */ + function Filter(vertexSrc, fragmentSrc, uniforms) { + var _this = this; + var program = Program.from(vertexSrc || Filter.defaultVertexSrc, fragmentSrc || Filter.defaultFragmentSrc); + _this = _super.call(this, program, uniforms) || this; + _this.padding = 0; + _this.resolution = settings$1.FILTER_RESOLUTION; + _this.multisample = settings$1.FILTER_MULTISAMPLE; + _this.enabled = true; + _this.autoFit = true; + _this.state = new State(); + return _this; + } + /** + * Applies the filter + * @param {PIXI.FilterSystem} filterManager - The renderer to retrieve the filter from + * @param {PIXI.RenderTexture} input - The input render target. + * @param {PIXI.RenderTexture} output - The target to output to. + * @param {PIXI.CLEAR_MODES} [clearMode] - Should the output be cleared before rendering to it. + * @param {object} [_currentState] - It's current state of filter. + * There are some useful properties in the currentState : + * target, filters, sourceFrame, destinationFrame, renderTarget, resolution + */ + Filter.prototype.apply = function (filterManager, input, output, clearMode, _currentState) { + // do as you please! + filterManager.applyFilter(this, input, output, clearMode); + // or just do a regular render.. + }; + Object.defineProperty(Filter.prototype, "blendMode", { + /** + * Sets the blend mode of the filter. + * @default PIXI.BLEND_MODES.NORMAL + */ + get: function () { + return this.state.blendMode; + }, + set: function (value) { + this.state.blendMode = value; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(Filter.prototype, "resolution", { + /** + * The resolution of the filter. Setting this to be lower will lower the quality but + * increase the performance of the filter. + */ + get: function () { + return this._resolution; + }, + set: function (value) { + this._resolution = value; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(Filter, "defaultVertexSrc", { + /** + * The default vertex shader source + * @constant + */ + get: function () { + return defaultVertex$2; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(Filter, "defaultFragmentSrc", { + /** + * The default fragment shader source + * @constant + */ + get: function () { + return defaultFragment$1; + }, + enumerable: false, + configurable: true + }); + return Filter; + }(Shader)); + + var vertex$4 = "attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\nuniform mat3 otherMatrix;\n\nvarying vec2 vMaskCoord;\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n vTextureCoord = aTextureCoord;\n vMaskCoord = ( otherMatrix * vec3( aTextureCoord, 1.0) ).xy;\n}\n"; + + var fragment$7 = "varying vec2 vMaskCoord;\nvarying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\nuniform sampler2D mask;\nuniform float alpha;\nuniform float npmAlpha;\nuniform vec4 maskClamp;\n\nvoid main(void)\n{\n float clip = step(3.5,\n step(maskClamp.x, vMaskCoord.x) +\n step(maskClamp.y, vMaskCoord.y) +\n step(vMaskCoord.x, maskClamp.z) +\n step(vMaskCoord.y, maskClamp.w));\n\n vec4 original = texture2D(uSampler, vTextureCoord);\n vec4 masky = texture2D(mask, vMaskCoord);\n float alphaMul = 1.0 - npmAlpha * (1.0 - masky.a);\n\n original *= (alphaMul * masky.r * alpha * clip);\n\n gl_FragColor = original;\n}\n"; + + var tempMat$1 = new Matrix(); + /** + * Class controls uv mapping from Texture normal space to BaseTexture normal space. + * + * Takes `trim` and `rotate` into account. May contain clamp settings for Meshes and TilingSprite. + * + * Can be used in Texture `uvMatrix` field, or separately, you can use different clamp settings on the same texture. + * If you want to add support for texture region of certain feature or filter, that's what you're looking for. + * + * Takes track of Texture changes through `_lastTextureID` private field. + * Use `update()` method call to track it from outside. + * @see PIXI.Texture + * @see PIXI.Mesh + * @see PIXI.TilingSprite + * @memberof PIXI + */ + var TextureMatrix = /** @class */ (function () { + /** + * @param texture - observed texture + * @param clampMargin - Changes frame clamping, 0.5 by default. Use -0.5 for extra border. + */ + function TextureMatrix(texture, clampMargin) { + this._texture = texture; + this.mapCoord = new Matrix(); + this.uClampFrame = new Float32Array(4); + this.uClampOffset = new Float32Array(2); + this._textureID = -1; + this._updateID = 0; + this.clampOffset = 0; + this.clampMargin = (typeof clampMargin === 'undefined') ? 0.5 : clampMargin; + this.isSimple = false; + } + Object.defineProperty(TextureMatrix.prototype, "texture", { + /** Texture property. */ + get: function () { + return this._texture; + }, + set: function (value) { + this._texture = value; + this._textureID = -1; + }, + enumerable: false, + configurable: true + }); + /** + * Multiplies uvs array to transform + * @param uvs - mesh uvs + * @param [out=uvs] - output + * @returns - output + */ + TextureMatrix.prototype.multiplyUvs = function (uvs, out) { + if (out === undefined) { + out = uvs; + } + var mat = this.mapCoord; + for (var i = 0; i < uvs.length; i += 2) { + var x = uvs[i]; + var y = uvs[i + 1]; + out[i] = (x * mat.a) + (y * mat.c) + mat.tx; + out[i + 1] = (x * mat.b) + (y * mat.d) + mat.ty; + } + return out; + }; + /** + * Updates matrices if texture was changed. + * @param [forceUpdate=false] - if true, matrices will be updated any case + * @returns - Whether or not it was updated + */ + TextureMatrix.prototype.update = function (forceUpdate) { + var tex = this._texture; + if (!tex || !tex.valid) { + return false; + } + if (!forceUpdate + && this._textureID === tex._updateID) { + return false; + } + this._textureID = tex._updateID; + this._updateID++; + var uvs = tex._uvs; + this.mapCoord.set(uvs.x1 - uvs.x0, uvs.y1 - uvs.y0, uvs.x3 - uvs.x0, uvs.y3 - uvs.y0, uvs.x0, uvs.y0); + var orig = tex.orig; + var trim = tex.trim; + if (trim) { + tempMat$1.set(orig.width / trim.width, 0, 0, orig.height / trim.height, -trim.x / trim.width, -trim.y / trim.height); + this.mapCoord.append(tempMat$1); + } + var texBase = tex.baseTexture; + var frame = this.uClampFrame; + var margin = this.clampMargin / texBase.resolution; + var offset = this.clampOffset; + frame[0] = (tex._frame.x + margin + offset) / texBase.width; + frame[1] = (tex._frame.y + margin + offset) / texBase.height; + frame[2] = (tex._frame.x + tex._frame.width - margin + offset) / texBase.width; + frame[3] = (tex._frame.y + tex._frame.height - margin + offset) / texBase.height; + this.uClampOffset[0] = offset / texBase.realWidth; + this.uClampOffset[1] = offset / texBase.realHeight; + this.isSimple = tex._frame.width === texBase.width + && tex._frame.height === texBase.height + && tex.rotate === 0; + return true; + }; + return TextureMatrix; + }()); + + /** + * This handles a Sprite acting as a mask, as opposed to a Graphic. + * + * WebGL only. + * @memberof PIXI + */ + var SpriteMaskFilter = /** @class */ (function (_super) { + __extends$i(SpriteMaskFilter, _super); + /** @ignore */ + function SpriteMaskFilter(vertexSrc, fragmentSrc, uniforms) { + var _this = this; + var sprite = null; + if (typeof vertexSrc !== 'string' && fragmentSrc === undefined && uniforms === undefined) { + sprite = vertexSrc; + vertexSrc = undefined; + fragmentSrc = undefined; + uniforms = undefined; + } + _this = _super.call(this, vertexSrc || vertex$4, fragmentSrc || fragment$7, uniforms) || this; + _this.maskSprite = sprite; + _this.maskMatrix = new Matrix(); + return _this; + } + Object.defineProperty(SpriteMaskFilter.prototype, "maskSprite", { + /** + * Sprite mask + * @type {PIXI.DisplayObject} + */ + get: function () { + return this._maskSprite; + }, + set: function (value) { + this._maskSprite = value; + if (this._maskSprite) { + this._maskSprite.renderable = false; + } + }, + enumerable: false, + configurable: true + }); + /** + * Applies the filter + * @param filterManager - The renderer to retrieve the filter from + * @param input - The input render target. + * @param output - The target to output to. + * @param clearMode - Should the output be cleared before rendering to it. + */ + SpriteMaskFilter.prototype.apply = function (filterManager, input, output, clearMode) { + var maskSprite = this._maskSprite; + var tex = maskSprite._texture; + if (!tex.valid) { + return; + } + if (!tex.uvMatrix) { + // margin = 0.0, let it bleed a bit, shader code becomes easier + // assuming that atlas textures were made with 1-pixel padding + tex.uvMatrix = new TextureMatrix(tex, 0.0); + } + tex.uvMatrix.update(); + this.uniforms.npmAlpha = tex.baseTexture.alphaMode ? 0.0 : 1.0; + this.uniforms.mask = tex; + // get _normalized sprite texture coords_ and convert them to _normalized atlas texture coords_ with `prepend` + this.uniforms.otherMatrix = filterManager.calculateSpriteMatrix(this.maskMatrix, maskSprite) + .prepend(tex.uvMatrix.mapCoord); + this.uniforms.alpha = maskSprite.worldAlpha; + this.uniforms.maskClamp = tex.uvMatrix.uClampFrame; + filterManager.applyFilter(this, input, output, clearMode); + }; + return SpriteMaskFilter; + }(Filter)); + + /** + * System plugin to the renderer to manage masks. + * + * There are three built-in types of masking: + * **Scissor Masking**: Scissor masking discards pixels that are outside of a rectangle called the scissor box. It is + * the most performant as the scissor test is inexpensive. However, it can only be used when the mask is rectangular. + * **Stencil Masking**: Stencil masking discards pixels that don't overlap with the pixels rendered into the stencil + * buffer. It is the next fastest option as it does not require rendering into a separate framebuffer. However, it does + * cause the mask to be rendered **twice** for each masking operation; hence, minimize the rendering cost of your masks. + * **Sprite Mask Filtering**: Sprite mask filtering discards pixels based on the red channel of the sprite-mask's + * texture. (Generally, the masking texture is grayscale). Using advanced techniques, you might be able to embed this + * type of masking in a custom shader - and hence, bypassing the masking system fully for performance wins. + * + * The best type of masking is auto-detected when you `push` one. To use scissor masking, you must pass in a `Graphics` + * object with just a rectangle drawn. + * + * ## Mask Stacks + * + * In the scene graph, masks can be applied recursively, i.e. a mask can be applied during a masking operation. The mask + * stack stores the currently applied masks in order. Each {@link PIXI.BaseRenderTexture} holds its own mask stack, i.e. + * when you switch render-textures, the old masks only applied when you switch back to rendering to the old render-target. + * @memberof PIXI + */ + var MaskSystem = /** @class */ (function () { + /** + * @param renderer - The renderer this System works for. + */ + function MaskSystem(renderer) { + this.renderer = renderer; + this.enableScissor = true; + this.alphaMaskPool = []; + this.maskDataPool = []; + this.maskStack = []; + this.alphaMaskIndex = 0; + } + /** + * Changes the mask stack that is used by this System. + * @param maskStack - The mask stack + */ + MaskSystem.prototype.setMaskStack = function (maskStack) { + this.maskStack = maskStack; + this.renderer.scissor.setMaskStack(maskStack); + this.renderer.stencil.setMaskStack(maskStack); + }; + /** + * Enables the mask and appends it to the current mask stack. + * + * NOTE: The batch renderer should be flushed beforehand to prevent pending renders from being masked. + * @param {PIXI.DisplayObject} target - Display Object to push the mask to + * @param {PIXI.MaskData|PIXI.Sprite|PIXI.Graphics|PIXI.DisplayObject} maskDataOrTarget - The masking data. + */ + MaskSystem.prototype.push = function (target, maskDataOrTarget) { + var maskData = maskDataOrTarget; + if (!maskData.isMaskData) { + var d = this.maskDataPool.pop() || new MaskData(); + d.pooled = true; + d.maskObject = maskDataOrTarget; + maskData = d; + } + var maskAbove = this.maskStack.length !== 0 ? this.maskStack[this.maskStack.length - 1] : null; + maskData.copyCountersOrReset(maskAbove); + maskData._colorMask = maskAbove ? maskAbove._colorMask : 0xf; + if (maskData.autoDetect) { + this.detect(maskData); + } + maskData._target = target; + if (maskData.type !== exports.MASK_TYPES.SPRITE) { + this.maskStack.push(maskData); + } + if (maskData.enabled) { + switch (maskData.type) { + case exports.MASK_TYPES.SCISSOR: + this.renderer.scissor.push(maskData); + break; + case exports.MASK_TYPES.STENCIL: + this.renderer.stencil.push(maskData); + break; + case exports.MASK_TYPES.SPRITE: + maskData.copyCountersOrReset(null); + this.pushSpriteMask(maskData); + break; + case exports.MASK_TYPES.COLOR: + this.pushColorMask(maskData); + break; + } + } + if (maskData.type === exports.MASK_TYPES.SPRITE) { + this.maskStack.push(maskData); + } + }; + /** + * Removes the last mask from the mask stack and doesn't return it. + * + * NOTE: The batch renderer should be flushed beforehand to render the masked contents before the mask is removed. + * @param {PIXI.IMaskTarget} target - Display Object to pop the mask from + */ + MaskSystem.prototype.pop = function (target) { + var maskData = this.maskStack.pop(); + if (!maskData || maskData._target !== target) { + // TODO: add an assert when we have it + return; + } + if (maskData.enabled) { + switch (maskData.type) { + case exports.MASK_TYPES.SCISSOR: + this.renderer.scissor.pop(maskData); + break; + case exports.MASK_TYPES.STENCIL: + this.renderer.stencil.pop(maskData.maskObject); + break; + case exports.MASK_TYPES.SPRITE: + this.popSpriteMask(maskData); + break; + case exports.MASK_TYPES.COLOR: + this.popColorMask(maskData); + break; + } + } + maskData.reset(); + if (maskData.pooled) { + this.maskDataPool.push(maskData); + } + if (this.maskStack.length !== 0) { + var maskCurrent = this.maskStack[this.maskStack.length - 1]; + if (maskCurrent.type === exports.MASK_TYPES.SPRITE && maskCurrent._filters) { + maskCurrent._filters[0].maskSprite = maskCurrent.maskObject; + } + } + }; + /** + * Sets type of MaskData based on its maskObject. + * @param maskData + */ + MaskSystem.prototype.detect = function (maskData) { + var maskObject = maskData.maskObject; + if (!maskObject) { + maskData.type = exports.MASK_TYPES.COLOR; + } + else if (maskObject.isSprite) { + maskData.type = exports.MASK_TYPES.SPRITE; + } + else if (this.enableScissor && this.renderer.scissor.testScissor(maskData)) { + maskData.type = exports.MASK_TYPES.SCISSOR; + } + else { + maskData.type = exports.MASK_TYPES.STENCIL; + } + }; + /** + * Applies the Mask and adds it to the current filter stack. + * @param maskData - Sprite to be used as the mask. + */ + MaskSystem.prototype.pushSpriteMask = function (maskData) { + var _a, _b; + var maskObject = maskData.maskObject; + var target = maskData._target; + var alphaMaskFilter = maskData._filters; + if (!alphaMaskFilter) { + alphaMaskFilter = this.alphaMaskPool[this.alphaMaskIndex]; + if (!alphaMaskFilter) { + alphaMaskFilter = this.alphaMaskPool[this.alphaMaskIndex] = [new SpriteMaskFilter()]; + } + } + var renderer = this.renderer; + var renderTextureSystem = renderer.renderTexture; + var resolution; + var multisample; + if (renderTextureSystem.current) { + var renderTexture = renderTextureSystem.current; + resolution = maskData.resolution || renderTexture.resolution; + multisample = (_a = maskData.multisample) !== null && _a !== void 0 ? _a : renderTexture.multisample; + } + else { + resolution = maskData.resolution || renderer.resolution; + multisample = (_b = maskData.multisample) !== null && _b !== void 0 ? _b : renderer.multisample; + } + alphaMaskFilter[0].resolution = resolution; + alphaMaskFilter[0].multisample = multisample; + alphaMaskFilter[0].maskSprite = maskObject; + var stashFilterArea = target.filterArea; + target.filterArea = maskObject.getBounds(true); + renderer.filter.push(target, alphaMaskFilter); + target.filterArea = stashFilterArea; + if (!maskData._filters) { + this.alphaMaskIndex++; + } + }; + /** + * Removes the last filter from the filter stack and doesn't return it. + * @param maskData - Sprite to be used as the mask. + */ + MaskSystem.prototype.popSpriteMask = function (maskData) { + this.renderer.filter.pop(); + if (maskData._filters) { + maskData._filters[0].maskSprite = null; + } + else { + this.alphaMaskIndex--; + this.alphaMaskPool[this.alphaMaskIndex][0].maskSprite = null; + } + }; + /** + * Pushes the color mask. + * @param maskData - The mask data + */ + MaskSystem.prototype.pushColorMask = function (maskData) { + var currColorMask = maskData._colorMask; + var nextColorMask = maskData._colorMask = currColorMask & maskData.colorMask; + if (nextColorMask !== currColorMask) { + this.renderer.gl.colorMask((nextColorMask & 0x1) !== 0, (nextColorMask & 0x2) !== 0, (nextColorMask & 0x4) !== 0, (nextColorMask & 0x8) !== 0); + } + }; + /** + * Pops the color mask. + * @param maskData - The mask data + */ + MaskSystem.prototype.popColorMask = function (maskData) { + var currColorMask = maskData._colorMask; + var nextColorMask = this.maskStack.length > 0 + ? this.maskStack[this.maskStack.length - 1]._colorMask : 0xf; + if (nextColorMask !== currColorMask) { + this.renderer.gl.colorMask((nextColorMask & 0x1) !== 0, (nextColorMask & 0x2) !== 0, (nextColorMask & 0x4) !== 0, (nextColorMask & 0x8) !== 0); + } + }; + MaskSystem.prototype.destroy = function () { + this.renderer = null; + }; + return MaskSystem; + }()); + + /** + * System plugin to the renderer to manage specific types of masking operations. + * @memberof PIXI + */ + var AbstractMaskSystem = /** @class */ (function () { + /** + * @param renderer - The renderer this System works for. + */ + function AbstractMaskSystem(renderer) { + this.renderer = renderer; + this.maskStack = []; + this.glConst = 0; + } + /** Gets count of masks of certain type. */ + AbstractMaskSystem.prototype.getStackLength = function () { + return this.maskStack.length; + }; + /** + * Changes the mask stack that is used by this System. + * @param {PIXI.MaskData[]} maskStack - The mask stack + */ + AbstractMaskSystem.prototype.setMaskStack = function (maskStack) { + var gl = this.renderer.gl; + var curStackLen = this.getStackLength(); + this.maskStack = maskStack; + var newStackLen = this.getStackLength(); + if (newStackLen !== curStackLen) { + if (newStackLen === 0) { + gl.disable(this.glConst); + } + else { + gl.enable(this.glConst); + this._useCurrent(); + } + } + }; + /** + * Setup renderer to use the current mask data. + * @private + */ + AbstractMaskSystem.prototype._useCurrent = function () { + // OVERWRITE; + }; + /** Destroys the mask stack. */ + AbstractMaskSystem.prototype.destroy = function () { + this.renderer = null; + this.maskStack = null; + }; + return AbstractMaskSystem; + }()); + + var tempMatrix$1 = new Matrix(); + var rectPool = []; + /** + * System plugin to the renderer to manage scissor masking. + * + * Scissor masking discards pixels outside of a rectangle called the scissor box. The scissor box is in the framebuffer + * viewport's space; however, the mask's rectangle is projected from world-space to viewport space automatically + * by this system. + * @memberof PIXI + */ + var ScissorSystem = /** @class */ (function (_super) { + __extends$i(ScissorSystem, _super); + /** + * @param {PIXI.Renderer} renderer - The renderer this System works for. + */ + function ScissorSystem(renderer) { + var _this = _super.call(this, renderer) || this; + _this.glConst = settings$1.ADAPTER.getWebGLRenderingContext().SCISSOR_TEST; + return _this; + } + ScissorSystem.prototype.getStackLength = function () { + var maskData = this.maskStack[this.maskStack.length - 1]; + if (maskData) { + return maskData._scissorCounter; + } + return 0; + }; + /** + * evaluates _boundsTransformed, _scissorRect for MaskData + * @param maskData + */ + ScissorSystem.prototype.calcScissorRect = function (maskData) { + var _a; + if (maskData._scissorRectLocal) { + return; + } + var prevData = maskData._scissorRect; + var maskObject = maskData.maskObject; + var renderer = this.renderer; + var renderTextureSystem = renderer.renderTexture; + var rect = maskObject.getBounds(true, (_a = rectPool.pop()) !== null && _a !== void 0 ? _a : new Rectangle()); + this.roundFrameToPixels(rect, renderTextureSystem.current ? renderTextureSystem.current.resolution : renderer.resolution, renderTextureSystem.sourceFrame, renderTextureSystem.destinationFrame, renderer.projection.transform); + if (prevData) { + rect.fit(prevData); + } + maskData._scissorRectLocal = rect; + }; + ScissorSystem.isMatrixRotated = function (matrix) { + if (!matrix) { + return false; + } + var a = matrix.a, b = matrix.b, c = matrix.c, d = matrix.d; + // Skip if skew/rotation present in matrix, except for multiple of 90° rotation. If rotation + // is a multiple of 90°, then either pair of (b,c) or (a,d) will be (0,0). + return ((Math.abs(b) > 1e-4 || Math.abs(c) > 1e-4) + && (Math.abs(a) > 1e-4 || Math.abs(d) > 1e-4)); + }; + /** + * Test, whether the object can be scissor mask with current renderer projection. + * Calls "calcScissorRect()" if its true. + * @param maskData - mask data + * @returns whether Whether the object can be scissor mask + */ + ScissorSystem.prototype.testScissor = function (maskData) { + var maskObject = maskData.maskObject; + if (!maskObject.isFastRect || !maskObject.isFastRect()) { + return false; + } + if (ScissorSystem.isMatrixRotated(maskObject.worldTransform)) { + return false; + } + if (ScissorSystem.isMatrixRotated(this.renderer.projection.transform)) { + return false; + } + this.calcScissorRect(maskData); + var rect = maskData._scissorRectLocal; + return rect.width > 0 && rect.height > 0; + }; + ScissorSystem.prototype.roundFrameToPixels = function (frame, resolution, bindingSourceFrame, bindingDestinationFrame, transform) { + if (ScissorSystem.isMatrixRotated(transform)) { + return; + } + transform = transform ? tempMatrix$1.copyFrom(transform) : tempMatrix$1.identity(); + // Get forward transform from world space to screen space + transform + .translate(-bindingSourceFrame.x, -bindingSourceFrame.y) + .scale(bindingDestinationFrame.width / bindingSourceFrame.width, bindingDestinationFrame.height / bindingSourceFrame.height) + .translate(bindingDestinationFrame.x, bindingDestinationFrame.y); + // Convert frame to screen space + this.renderer.filter.transformAABB(transform, frame); + frame.fit(bindingDestinationFrame); + frame.x = Math.round(frame.x * resolution); + frame.y = Math.round(frame.y * resolution); + frame.width = Math.round(frame.width * resolution); + frame.height = Math.round(frame.height * resolution); + }; + /** + * Applies the Mask and adds it to the current stencil stack. + * @author alvin + * @param maskData - The mask data. + */ + ScissorSystem.prototype.push = function (maskData) { + if (!maskData._scissorRectLocal) { + this.calcScissorRect(maskData); + } + var gl = this.renderer.gl; + if (!maskData._scissorRect) { + gl.enable(gl.SCISSOR_TEST); + } + maskData._scissorCounter++; + maskData._scissorRect = maskData._scissorRectLocal; + this._useCurrent(); + }; + /** + * This should be called after a mask is popped off the mask stack. It will rebind the scissor box to be latest with the + * last mask in the stack. + * + * This can also be called when you directly modify the scissor box and want to restore PixiJS state. + * @param maskData - The mask data. + */ + ScissorSystem.prototype.pop = function (maskData) { + var gl = this.renderer.gl; + if (maskData) { + rectPool.push(maskData._scissorRectLocal); + } + if (this.getStackLength() > 0) { + this._useCurrent(); + } + else { + gl.disable(gl.SCISSOR_TEST); + } + }; + /** + * Setup renderer to use the current scissor data. + * @private + */ + ScissorSystem.prototype._useCurrent = function () { + var rect = this.maskStack[this.maskStack.length - 1]._scissorRect; + var y; + if (this.renderer.renderTexture.current) { + y = rect.y; + } + else { + // flipY. In future we'll have it over renderTextures as an option + y = this.renderer.height - rect.height - rect.y; + } + this.renderer.gl.scissor(rect.x, y, rect.width, rect.height); + }; + return ScissorSystem; + }(AbstractMaskSystem)); + + /** + * System plugin to the renderer to manage stencils (used for masks). + * @memberof PIXI + */ + var StencilSystem = /** @class */ (function (_super) { + __extends$i(StencilSystem, _super); + /** + * @param renderer - The renderer this System works for. + */ + function StencilSystem(renderer) { + var _this = _super.call(this, renderer) || this; + _this.glConst = settings$1.ADAPTER.getWebGLRenderingContext().STENCIL_TEST; + return _this; + } + StencilSystem.prototype.getStackLength = function () { + var maskData = this.maskStack[this.maskStack.length - 1]; + if (maskData) { + return maskData._stencilCounter; + } + return 0; + }; + /** + * Applies the Mask and adds it to the current stencil stack. + * @param maskData - The mask data + */ + StencilSystem.prototype.push = function (maskData) { + var maskObject = maskData.maskObject; + var gl = this.renderer.gl; + var prevMaskCount = maskData._stencilCounter; + if (prevMaskCount === 0) { + // force use stencil texture in current framebuffer + this.renderer.framebuffer.forceStencil(); + gl.clearStencil(0); + gl.clear(gl.STENCIL_BUFFER_BIT); + gl.enable(gl.STENCIL_TEST); + } + maskData._stencilCounter++; + var colorMask = maskData._colorMask; + if (colorMask !== 0) { + maskData._colorMask = 0; + gl.colorMask(false, false, false, false); + } + // Increment the reference stencil value where the new mask overlaps with the old ones. + gl.stencilFunc(gl.EQUAL, prevMaskCount, 0xFFFFFFFF); + gl.stencilOp(gl.KEEP, gl.KEEP, gl.INCR); + maskObject.renderable = true; + maskObject.render(this.renderer); + this.renderer.batch.flush(); + maskObject.renderable = false; + if (colorMask !== 0) { + maskData._colorMask = colorMask; + gl.colorMask((colorMask & 1) !== 0, (colorMask & 2) !== 0, (colorMask & 4) !== 0, (colorMask & 8) !== 0); + } + this._useCurrent(); + }; + /** + * Pops stencil mask. MaskData is already removed from stack + * @param {PIXI.DisplayObject} maskObject - object of popped mask data + */ + StencilSystem.prototype.pop = function (maskObject) { + var gl = this.renderer.gl; + if (this.getStackLength() === 0) { + // the stack is empty! + gl.disable(gl.STENCIL_TEST); + } + else { + var maskData = this.maskStack.length !== 0 ? this.maskStack[this.maskStack.length - 1] : null; + var colorMask = maskData ? maskData._colorMask : 0xf; + if (colorMask !== 0) { + maskData._colorMask = 0; + gl.colorMask(false, false, false, false); + } + // Decrement the reference stencil value where the popped mask overlaps with the other ones + gl.stencilOp(gl.KEEP, gl.KEEP, gl.DECR); + maskObject.renderable = true; + maskObject.render(this.renderer); + this.renderer.batch.flush(); + maskObject.renderable = false; + if (colorMask !== 0) { + maskData._colorMask = colorMask; + gl.colorMask((colorMask & 0x1) !== 0, (colorMask & 0x2) !== 0, (colorMask & 0x4) !== 0, (colorMask & 0x8) !== 0); + } + this._useCurrent(); + } + }; + /** + * Setup renderer to use the current stencil data. + * @private + */ + StencilSystem.prototype._useCurrent = function () { + var gl = this.renderer.gl; + gl.stencilFunc(gl.EQUAL, this.getStackLength(), 0xFFFFFFFF); + gl.stencilOp(gl.KEEP, gl.KEEP, gl.KEEP); + }; + return StencilSystem; + }(AbstractMaskSystem)); + + /** + * System plugin to the renderer to manage the projection matrix. + * + * The `projectionMatrix` is a global uniform provided to all shaders. It is used to transform points in world space to + * normalized device coordinates. + * @memberof PIXI + */ + var ProjectionSystem = /** @class */ (function () { + /** @param renderer - The renderer this System works for. */ + function ProjectionSystem(renderer) { + this.renderer = renderer; + this.destinationFrame = null; + this.sourceFrame = null; + this.defaultFrame = null; + this.projectionMatrix = new Matrix(); + this.transform = null; + } + /** + * Updates the projection-matrix based on the sourceFrame → destinationFrame mapping provided. + * + * NOTE: It is expected you call `renderer.framebuffer.setViewport(destinationFrame)` after this. This is because + * the framebuffer viewport converts shader vertex output in normalized device coordinates to window coordinates. + * + * NOTE-2: {@link RenderTextureSystem#bind} updates the projection-matrix when you bind a render-texture. It is expected + * that you dirty the current bindings when calling this manually. + * @param destinationFrame - The rectangle in the render-target to render the contents into. If rendering to the canvas, + * the origin is on the top-left; if rendering to a render-texture, the origin is on the bottom-left. + * @param sourceFrame - The rectangle in world space that contains the contents being rendered. + * @param resolution - The resolution of the render-target, which is the ratio of + * world-space (or CSS) pixels to physical pixels. + * @param root - Whether the render-target is the screen. This is required because rendering to textures + * is y-flipped (i.e. upside down relative to the screen). + */ + ProjectionSystem.prototype.update = function (destinationFrame, sourceFrame, resolution, root) { + this.destinationFrame = destinationFrame || this.destinationFrame || this.defaultFrame; + this.sourceFrame = sourceFrame || this.sourceFrame || destinationFrame; + // Calculate object-space to clip-space projection + this.calculateProjection(this.destinationFrame, this.sourceFrame, resolution, root); + if (this.transform) { + this.projectionMatrix.append(this.transform); + } + var renderer = this.renderer; + renderer.globalUniforms.uniforms.projectionMatrix = this.projectionMatrix; + renderer.globalUniforms.update(); + // this will work for now + // but would be sweet to stick and even on the global uniforms.. + if (renderer.shader.shader) { + renderer.shader.syncUniformGroup(renderer.shader.shader.uniforms.globals); + } + }; + /** + * Calculates the `projectionMatrix` to map points inside `sourceFrame` to inside `destinationFrame`. + * @param _destinationFrame - The destination frame in the render-target. + * @param sourceFrame - The source frame in world space. + * @param _resolution - The render-target's resolution, i.e. ratio of CSS to physical pixels. + * @param root - Whether rendering into the screen. Otherwise, if rendering to a framebuffer, the projection + * is y-flipped. + */ + ProjectionSystem.prototype.calculateProjection = function (_destinationFrame, sourceFrame, _resolution, root) { + var pm = this.projectionMatrix; + var sign = !root ? 1 : -1; + pm.identity(); + pm.a = (1 / sourceFrame.width * 2); + pm.d = sign * (1 / sourceFrame.height * 2); + pm.tx = -1 - (sourceFrame.x * pm.a); + pm.ty = -sign - (sourceFrame.y * pm.d); + }; + /** + * Sets the transform of the active render target to the given matrix. + * @param _matrix - The transformation matrix + */ + ProjectionSystem.prototype.setTransform = function (_matrix) { + // this._activeRenderTarget.transform = matrix; + }; + ProjectionSystem.prototype.destroy = function () { + this.renderer = null; + }; + return ProjectionSystem; + }()); + + // Temporary rectangle for assigned sourceFrame or destinationFrame + var tempRect = new Rectangle(); + // Temporary rectangle for renderTexture destinationFrame + var tempRect2 = new Rectangle(); + /* eslint-disable max-len */ + /** + * System plugin to the renderer to manage render textures. + * + * Should be added after FramebufferSystem + * + * ### Frames + * + * The `RenderTextureSystem` holds a sourceFrame → destinationFrame projection. The following table explains the different + * coordinate spaces used: + * + * | Frame | Description | Coordinate System | + * | ---------------------- | ---------------------------------------------------------------- | ------------------------------------------------------- | + * | sourceFrame | The rectangle inside of which display-objects are being rendered | **World Space**: The origin on the top-left | + * | destinationFrame | The rectangle in the render-target (canvas or texture) into which contents should be rendered | If rendering to the canvas, this is in screen space and the origin is on the top-left. If rendering to a render-texture, this is in its base-texture's space with the origin on the bottom-left. | + * | viewportFrame | The framebuffer viewport corresponding to the destination-frame | **Window Coordinates**: The origin is always on the bottom-left. | + * @memberof PIXI + */ + var RenderTextureSystem = /** @class */ (function () { + /** + * @param renderer - The renderer this System works for. + */ + function RenderTextureSystem(renderer) { + this.renderer = renderer; + this.clearColor = renderer._backgroundColorRgba; + this.defaultMaskStack = []; + this.current = null; + this.sourceFrame = new Rectangle(); + this.destinationFrame = new Rectangle(); + this.viewportFrame = new Rectangle(); + } + /** + * Bind the current render texture. + * @param renderTexture - RenderTexture to bind, by default its `null` - the screen. + * @param sourceFrame - Part of world that is mapped to the renderTexture. + * @param destinationFrame - Part of renderTexture, by default it has the same size as sourceFrame. + */ + RenderTextureSystem.prototype.bind = function (renderTexture, sourceFrame, destinationFrame) { + if (renderTexture === void 0) { renderTexture = null; } + var renderer = this.renderer; + this.current = renderTexture; + var baseTexture; + var framebuffer; + var resolution; + if (renderTexture) { + baseTexture = renderTexture.baseTexture; + resolution = baseTexture.resolution; + if (!sourceFrame) { + tempRect.width = renderTexture.frame.width; + tempRect.height = renderTexture.frame.height; + sourceFrame = tempRect; + } + if (!destinationFrame) { + tempRect2.x = renderTexture.frame.x; + tempRect2.y = renderTexture.frame.y; + tempRect2.width = sourceFrame.width; + tempRect2.height = sourceFrame.height; + destinationFrame = tempRect2; + } + framebuffer = baseTexture.framebuffer; + } + else { + resolution = renderer.resolution; + if (!sourceFrame) { + tempRect.width = renderer.screen.width; + tempRect.height = renderer.screen.height; + sourceFrame = tempRect; + } + if (!destinationFrame) { + destinationFrame = tempRect; + destinationFrame.width = sourceFrame.width; + destinationFrame.height = sourceFrame.height; + } + } + var viewportFrame = this.viewportFrame; + viewportFrame.x = destinationFrame.x * resolution; + viewportFrame.y = destinationFrame.y * resolution; + viewportFrame.width = destinationFrame.width * resolution; + viewportFrame.height = destinationFrame.height * resolution; + if (!renderTexture) { + viewportFrame.y = renderer.view.height - (viewportFrame.y + viewportFrame.height); + } + viewportFrame.ceil(); + this.renderer.framebuffer.bind(framebuffer, viewportFrame); + this.renderer.projection.update(destinationFrame, sourceFrame, resolution, !framebuffer); + if (renderTexture) { + this.renderer.mask.setMaskStack(baseTexture.maskStack); + } + else { + this.renderer.mask.setMaskStack(this.defaultMaskStack); + } + this.sourceFrame.copyFrom(sourceFrame); + this.destinationFrame.copyFrom(destinationFrame); + }; + /** + * Erases the render texture and fills the drawing area with a colour. + * @param clearColor - The color as rgba, default to use the renderer backgroundColor + * @param [mask=BUFFER_BITS.COLOR | BUFFER_BITS.DEPTH] - Bitwise OR of masks + * that indicate the buffers to be cleared, by default COLOR and DEPTH buffers. + */ + RenderTextureSystem.prototype.clear = function (clearColor, mask) { + if (this.current) { + clearColor = clearColor || this.current.baseTexture.clearColor; + } + else { + clearColor = clearColor || this.clearColor; + } + var destinationFrame = this.destinationFrame; + var baseFrame = this.current ? this.current.baseTexture : this.renderer.screen; + var clearMask = destinationFrame.width !== baseFrame.width || destinationFrame.height !== baseFrame.height; + if (clearMask) { + var _a = this.viewportFrame, x = _a.x, y = _a.y, width = _a.width, height = _a.height; + x = Math.round(x); + y = Math.round(y); + width = Math.round(width); + height = Math.round(height); + // TODO: ScissorSystem should cache whether the scissor test is enabled or not. + this.renderer.gl.enable(this.renderer.gl.SCISSOR_TEST); + this.renderer.gl.scissor(x, y, width, height); + } + this.renderer.framebuffer.clear(clearColor[0], clearColor[1], clearColor[2], clearColor[3], mask); + if (clearMask) { + // Restore the scissor box + this.renderer.scissor.pop(); + } + }; + RenderTextureSystem.prototype.resize = function () { + // resize the root only! + this.bind(null); + }; + /** Resets render-texture state. */ + RenderTextureSystem.prototype.reset = function () { + this.bind(null); + }; + RenderTextureSystem.prototype.destroy = function () { + this.renderer = null; + }; + return RenderTextureSystem; + }()); + + function uboUpdate(_ud, _uv, _renderer, _syncData, buffer) { + _renderer.buffer.update(buffer); + } + // cv = CachedValue + // v = value + // ud = uniformData + // uv = uniformValue + // l = location + var UBO_TO_SINGLE_SETTERS = { + float: "\n data[offset] = v;\n ", + vec2: "\n data[offset] = v[0];\n data[offset+1] = v[1];\n ", + vec3: "\n data[offset] = v[0];\n data[offset+1] = v[1];\n data[offset+2] = v[2];\n\n ", + vec4: "\n data[offset] = v[0];\n data[offset+1] = v[1];\n data[offset+2] = v[2];\n data[offset+3] = v[3];\n ", + mat2: "\n data[offset] = v[0];\n data[offset+1] = v[1];\n\n data[offset+4] = v[2];\n data[offset+5] = v[3];\n ", + mat3: "\n data[offset] = v[0];\n data[offset+1] = v[1];\n data[offset+2] = v[2];\n\n data[offset + 4] = v[3];\n data[offset + 5] = v[4];\n data[offset + 6] = v[5];\n\n data[offset + 8] = v[6];\n data[offset + 9] = v[7];\n data[offset + 10] = v[8];\n ", + mat4: "\n for(var i = 0; i < 16; i++)\n {\n data[offset + i] = v[i];\n }\n " + }; + var GLSL_TO_STD40_SIZE = { + float: 4, + vec2: 8, + vec3: 12, + vec4: 16, + int: 4, + ivec2: 8, + ivec3: 12, + ivec4: 16, + uint: 4, + uvec2: 8, + uvec3: 12, + uvec4: 16, + bool: 4, + bvec2: 8, + bvec3: 12, + bvec4: 16, + mat2: 16 * 2, + mat3: 16 * 3, + mat4: 16 * 4, + }; + /** + * logic originally from here: https://github.com/sketchpunk/FunWithWebGL2/blob/master/lesson_022/Shaders.js + * rewrote it, but this was a great starting point to get a solid understanding of whats going on :) + * @ignore + * @param uniformData + */ + function createUBOElements(uniformData) { + var uboElements = uniformData.map(function (data) { + return ({ + data: data, + offset: 0, + dataLen: 0, + dirty: 0 + }); + }); + var size = 0; + var chunkSize = 0; + var offset = 0; + for (var i = 0; i < uboElements.length; i++) { + var uboElement = uboElements[i]; + size = GLSL_TO_STD40_SIZE[uboElement.data.type]; + if (uboElement.data.size > 1) { + size = Math.max(size, 16) * uboElement.data.size; + } + uboElement.dataLen = size; + // add some size offset.. + // must align to the nearest 16 bytes or internally nearest round size + if (chunkSize % size !== 0 && chunkSize < 16) { + // diff required to line up.. + var lineUpValue = (chunkSize % size) % 16; + chunkSize += lineUpValue; + offset += lineUpValue; + } + if ((chunkSize + size) > 16) { + offset = Math.ceil(offset / 16) * 16; + uboElement.offset = offset; + offset += size; + chunkSize = size; + } + else { + uboElement.offset = offset; + chunkSize += size; + offset += size; + } + } + offset = Math.ceil(offset / 16) * 16; + return { uboElements: uboElements, size: offset }; + } + function getUBOData(uniforms, uniformData) { + var usedUniformDatas = []; + // build.. + for (var i in uniforms) { + if (uniformData[i]) { + usedUniformDatas.push(uniformData[i]); + } + } + // sort them out by index! + usedUniformDatas.sort(function (a, b) { return a.index - b.index; }); + return usedUniformDatas; + } + function generateUniformBufferSync(group, uniformData) { + if (!group.autoManage) { + // if the group is nott automatically managed, we don't need to generate a special function for it... + return { size: 0, syncFunc: uboUpdate }; + } + var usedUniformDatas = getUBOData(group.uniforms, uniformData); + var _a = createUBOElements(usedUniformDatas), uboElements = _a.uboElements, size = _a.size; + var funcFragments = ["\n var v = null;\n var v2 = null;\n var cv = null;\n var t = 0;\n var gl = renderer.gl\n var index = 0;\n var data = buffer.data;\n "]; + for (var i = 0; i < uboElements.length; i++) { + var uboElement = uboElements[i]; + var uniform = group.uniforms[uboElement.data.name]; + var name = uboElement.data.name; + var parsed = false; + for (var j = 0; j < uniformParsers.length; j++) { + var uniformParser = uniformParsers[j]; + if (uniformParser.codeUbo && uniformParser.test(uboElement.data, uniform)) { + funcFragments.push("offset = " + uboElement.offset / 4 + ";", uniformParsers[j].codeUbo(uboElement.data.name, uniform)); + parsed = true; + break; + } + } + if (!parsed) { + if (uboElement.data.size > 1) { + var size_1 = mapSize(uboElement.data.type); + var rowSize = Math.max(GLSL_TO_STD40_SIZE[uboElement.data.type] / 16, 1); + var elementSize = size_1 / rowSize; + var remainder = (4 - (elementSize % 4)) % 4; + funcFragments.push("\n cv = ud." + name + ".value;\n v = uv." + name + ";\n offset = " + uboElement.offset / 4 + ";\n\n t = 0;\n\n for(var i=0; i < " + uboElement.data.size * rowSize + "; i++)\n {\n for(var j = 0; j < " + elementSize + "; j++)\n {\n data[offset++] = v[t++];\n }\n offset += " + remainder + ";\n }\n\n "); + } + else { + var template = UBO_TO_SINGLE_SETTERS[uboElement.data.type]; + funcFragments.push("\n cv = ud." + name + ".value;\n v = uv." + name + ";\n offset = " + uboElement.offset / 4 + ";\n " + template + ";\n "); + } + } + } + funcFragments.push("\n renderer.buffer.update(buffer);\n "); + return { + size: size, + // eslint-disable-next-line no-new-func + syncFunc: new Function('ud', 'uv', 'renderer', 'syncData', 'buffer', funcFragments.join('\n')) + }; + } + + /** + * @private + */ + var IGLUniformData = /** @class */ (function () { + function IGLUniformData() { + } + return IGLUniformData; + }()); + /** + * Helper class to create a WebGL Program + * @memberof PIXI + */ + var GLProgram = /** @class */ (function () { + /** + * Makes a new Pixi program. + * @param program - webgl program + * @param uniformData - uniforms + */ + function GLProgram(program, uniformData) { + this.program = program; + this.uniformData = uniformData; + this.uniformGroups = {}; + this.uniformDirtyGroups = {}; + this.uniformBufferBindings = {}; + } + /** Destroys this program. */ + GLProgram.prototype.destroy = function () { + this.uniformData = null; + this.uniformGroups = null; + this.uniformDirtyGroups = null; + this.uniformBufferBindings = null; + this.program = null; + }; + return GLProgram; + }()); + + /** + * returns the attribute data from the program + * @private + * @param {WebGLProgram} [program] - the WebGL program + * @param {WebGLRenderingContext} [gl] - the WebGL context + * @returns {object} the attribute data for this program + */ + function getAttributeData(program, gl) { + var attributes = {}; + var totalAttributes = gl.getProgramParameter(program, gl.ACTIVE_ATTRIBUTES); + for (var i = 0; i < totalAttributes; i++) { + var attribData = gl.getActiveAttrib(program, i); + if (attribData.name.indexOf('gl_') === 0) { + continue; + } + var type = mapType(gl, attribData.type); + var data = { + type: type, + name: attribData.name, + size: mapSize(type), + location: gl.getAttribLocation(program, attribData.name), + }; + attributes[attribData.name] = data; + } + return attributes; + } + + /** + * returns the uniform data from the program + * @private + * @param program - the webgl program + * @param gl - the WebGL context + * @returns {object} the uniform data for this program + */ + function getUniformData(program, gl) { + var uniforms = {}; + var totalUniforms = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS); + for (var i = 0; i < totalUniforms; i++) { + var uniformData = gl.getActiveUniform(program, i); + var name = uniformData.name.replace(/\[.*?\]$/, ''); + var isArray = !!(uniformData.name.match(/\[.*?\]$/)); + var type = mapType(gl, uniformData.type); + uniforms[name] = { + name: name, + index: i, + type: type, + size: uniformData.size, + isArray: isArray, + value: defaultValue(type, uniformData.size), + }; + } + return uniforms; + } + + /** + * generates a WebGL Program object from a high level Pixi Program. + * @param gl - a rendering context on which to generate the program + * @param program - the high level Pixi Program. + */ + function generateProgram(gl, program) { + var glVertShader = compileShader(gl, gl.VERTEX_SHADER, program.vertexSrc); + var glFragShader = compileShader(gl, gl.FRAGMENT_SHADER, program.fragmentSrc); + var webGLProgram = gl.createProgram(); + gl.attachShader(webGLProgram, glVertShader); + gl.attachShader(webGLProgram, glFragShader); + gl.linkProgram(webGLProgram); + if (!gl.getProgramParameter(webGLProgram, gl.LINK_STATUS)) { + logProgramError(gl, webGLProgram, glVertShader, glFragShader); + } + program.attributeData = getAttributeData(webGLProgram, gl); + program.uniformData = getUniformData(webGLProgram, gl); + // GLSL 1.00: bind attributes sorted by name in ascending order + // GLSL 3.00: don't change the attribute locations that where chosen by the compiler + // or assigned by the layout specifier in the shader source code + if (!(/^[ \t]*#[ \t]*version[ \t]+300[ \t]+es[ \t]*$/m).test(program.vertexSrc)) { + var keys = Object.keys(program.attributeData); + keys.sort(function (a, b) { return (a > b) ? 1 : -1; }); // eslint-disable-line no-confusing-arrow + for (var i = 0; i < keys.length; i++) { + program.attributeData[keys[i]].location = i; + gl.bindAttribLocation(webGLProgram, i, keys[i]); + } + gl.linkProgram(webGLProgram); + } + gl.deleteShader(glVertShader); + gl.deleteShader(glFragShader); + var uniformData = {}; + for (var i in program.uniformData) { + var data = program.uniformData[i]; + uniformData[i] = { + location: gl.getUniformLocation(webGLProgram, i), + value: defaultValue(data.type, data.size), + }; + } + var glProgram = new GLProgram(webGLProgram, uniformData); + return glProgram; + } + + var UID = 0; + // default sync data so we don't create a new one each time! + var defaultSyncData = { textureCount: 0, uboCount: 0 }; + /** + * System plugin to the renderer to manage shaders. + * @memberof PIXI + */ + var ShaderSystem = /** @class */ (function () { + /** @param renderer - The renderer this System works for. */ + function ShaderSystem(renderer) { + this.destroyed = false; + this.renderer = renderer; + // Validation check that this environment support `new Function` + this.systemCheck(); + this.gl = null; + this.shader = null; + this.program = null; + this.cache = {}; + this._uboCache = {}; + this.id = UID++; + } + /** + * Overrideable function by `@pixi/unsafe-eval` to silence + * throwing an error if platform doesn't support unsafe-evals. + * @private + */ + ShaderSystem.prototype.systemCheck = function () { + if (!unsafeEvalSupported()) { + throw new Error('Current environment does not allow unsafe-eval, ' + + 'please use @pixi/unsafe-eval module to enable support.'); + } + }; + ShaderSystem.prototype.contextChange = function (gl) { + this.gl = gl; + this.reset(); + }; + /** + * Changes the current shader to the one given in parameter. + * @param shader - the new shader + * @param dontSync - false if the shader should automatically sync its uniforms. + * @returns the glProgram that belongs to the shader. + */ + ShaderSystem.prototype.bind = function (shader, dontSync) { + shader.uniforms.globals = this.renderer.globalUniforms; + var program = shader.program; + var glProgram = program.glPrograms[this.renderer.CONTEXT_UID] || this.generateProgram(shader); + this.shader = shader; + // TODO - some current Pixi plugins bypass this.. so it not safe to use yet.. + if (this.program !== program) { + this.program = program; + this.gl.useProgram(glProgram.program); + } + if (!dontSync) { + defaultSyncData.textureCount = 0; + defaultSyncData.uboCount = 0; + this.syncUniformGroup(shader.uniformGroup, defaultSyncData); + } + return glProgram; + }; + /** + * Uploads the uniforms values to the currently bound shader. + * @param uniforms - the uniforms values that be applied to the current shader + */ + ShaderSystem.prototype.setUniforms = function (uniforms) { + var shader = this.shader.program; + var glProgram = shader.glPrograms[this.renderer.CONTEXT_UID]; + shader.syncUniforms(glProgram.uniformData, uniforms, this.renderer); + }; + /* eslint-disable @typescript-eslint/explicit-module-boundary-types */ + /** + * Syncs uniforms on the group + * @param group - the uniform group to sync + * @param syncData - this is data that is passed to the sync function and any nested sync functions + */ + ShaderSystem.prototype.syncUniformGroup = function (group, syncData) { + var glProgram = this.getGlProgram(); + if (!group.static || group.dirtyId !== glProgram.uniformDirtyGroups[group.id]) { + glProgram.uniformDirtyGroups[group.id] = group.dirtyId; + this.syncUniforms(group, glProgram, syncData); + } + }; + /** + * Overrideable by the @pixi/unsafe-eval package to use static syncUniforms instead. + * @param group + * @param glProgram + * @param syncData + */ + ShaderSystem.prototype.syncUniforms = function (group, glProgram, syncData) { + var syncFunc = group.syncUniforms[this.shader.program.id] || this.createSyncGroups(group); + syncFunc(glProgram.uniformData, group.uniforms, this.renderer, syncData); + }; + ShaderSystem.prototype.createSyncGroups = function (group) { + var id = this.getSignature(group, this.shader.program.uniformData, 'u'); + if (!this.cache[id]) { + this.cache[id] = generateUniformsSync(group, this.shader.program.uniformData); + } + group.syncUniforms[this.shader.program.id] = this.cache[id]; + return group.syncUniforms[this.shader.program.id]; + }; + /** + * Syncs uniform buffers + * @param group - the uniform buffer group to sync + * @param name - the name of the uniform buffer + */ + ShaderSystem.prototype.syncUniformBufferGroup = function (group, name) { + var glProgram = this.getGlProgram(); + if (!group.static || group.dirtyId !== 0 || !glProgram.uniformGroups[group.id]) { + group.dirtyId = 0; + var syncFunc = glProgram.uniformGroups[group.id] + || this.createSyncBufferGroup(group, glProgram, name); + // TODO wrap update in a cache?? + group.buffer.update(); + syncFunc(glProgram.uniformData, group.uniforms, this.renderer, defaultSyncData, group.buffer); + } + this.renderer.buffer.bindBufferBase(group.buffer, glProgram.uniformBufferBindings[name]); + }; + /** + * Will create a function that uploads a uniform buffer using the STD140 standard. + * The upload function will then be cached for future calls + * If a group is manually managed, then a simple upload function is generated + * @param group - the uniform buffer group to sync + * @param glProgram - the gl program to attach the uniform bindings to + * @param name - the name of the uniform buffer (must exist on the shader) + */ + ShaderSystem.prototype.createSyncBufferGroup = function (group, glProgram, name) { + var gl = this.renderer.gl; + this.renderer.buffer.bind(group.buffer); + // bind them... + var uniformBlockIndex = this.gl.getUniformBlockIndex(glProgram.program, name); + glProgram.uniformBufferBindings[name] = this.shader.uniformBindCount; + gl.uniformBlockBinding(glProgram.program, uniformBlockIndex, this.shader.uniformBindCount); + this.shader.uniformBindCount++; + var id = this.getSignature(group, this.shader.program.uniformData, 'ubo'); + var uboData = this._uboCache[id]; + if (!uboData) { + uboData = this._uboCache[id] = generateUniformBufferSync(group, this.shader.program.uniformData); + } + if (group.autoManage) { + var data = new Float32Array(uboData.size / 4); + group.buffer.update(data); + } + glProgram.uniformGroups[group.id] = uboData.syncFunc; + return glProgram.uniformGroups[group.id]; + }; + /** + * Takes a uniform group and data and generates a unique signature for them. + * @param group - The uniform group to get signature of + * @param group.uniforms + * @param uniformData - Uniform information generated by the shader + * @param preFix + * @returns Unique signature of the uniform group + */ + ShaderSystem.prototype.getSignature = function (group, uniformData, preFix) { + var uniforms = group.uniforms; + var strings = [preFix + "-"]; + for (var i in uniforms) { + strings.push(i); + if (uniformData[i]) { + strings.push(uniformData[i].type); + } + } + return strings.join('-'); + }; + /** + * Returns the underlying GLShade rof the currently bound shader. + * + * This can be handy for when you to have a little more control over the setting of your uniforms. + * @returns The glProgram for the currently bound Shader for this context + */ + ShaderSystem.prototype.getGlProgram = function () { + if (this.shader) { + return this.shader.program.glPrograms[this.renderer.CONTEXT_UID]; + } + return null; + }; + /** + * Generates a glProgram version of the Shader provided. + * @param shader - The shader that the glProgram will be based on. + * @returns A shiny new glProgram! + */ + ShaderSystem.prototype.generateProgram = function (shader) { + var gl = this.gl; + var program = shader.program; + var glProgram = generateProgram(gl, program); + program.glPrograms[this.renderer.CONTEXT_UID] = glProgram; + return glProgram; + }; + /** Resets ShaderSystem state, does not affect WebGL state. */ + ShaderSystem.prototype.reset = function () { + this.program = null; + this.shader = null; + }; + /** Destroys this System and removes all its textures. */ + ShaderSystem.prototype.destroy = function () { + this.renderer = null; + // TODO implement destroy method for ShaderSystem + this.destroyed = true; + }; + return ShaderSystem; + }()); + + /** + * Maps gl blend combinations to WebGL. + * @memberof PIXI + * @function mapWebGLBlendModesToPixi + * @private + * @param {WebGLRenderingContext} gl - The rendering context. + * @param {number[][]} [array=[]] - The array to output into. + * @returns {number[][]} Mapped modes. + */ + function mapWebGLBlendModesToPixi(gl, array) { + if (array === void 0) { array = []; } + // TODO - premultiply alpha would be different. + // add a boolean for that! + array[exports.BLEND_MODES.NORMAL] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[exports.BLEND_MODES.ADD] = [gl.ONE, gl.ONE]; + array[exports.BLEND_MODES.MULTIPLY] = [gl.DST_COLOR, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[exports.BLEND_MODES.SCREEN] = [gl.ONE, gl.ONE_MINUS_SRC_COLOR, gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[exports.BLEND_MODES.OVERLAY] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[exports.BLEND_MODES.DARKEN] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[exports.BLEND_MODES.LIGHTEN] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[exports.BLEND_MODES.COLOR_DODGE] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[exports.BLEND_MODES.COLOR_BURN] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[exports.BLEND_MODES.HARD_LIGHT] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[exports.BLEND_MODES.SOFT_LIGHT] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[exports.BLEND_MODES.DIFFERENCE] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[exports.BLEND_MODES.EXCLUSION] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[exports.BLEND_MODES.HUE] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[exports.BLEND_MODES.SATURATION] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[exports.BLEND_MODES.COLOR] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[exports.BLEND_MODES.LUMINOSITY] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[exports.BLEND_MODES.NONE] = [0, 0]; + // not-premultiplied blend modes + array[exports.BLEND_MODES.NORMAL_NPM] = [gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + array[exports.BLEND_MODES.ADD_NPM] = [gl.SRC_ALPHA, gl.ONE, gl.ONE, gl.ONE]; + array[exports.BLEND_MODES.SCREEN_NPM] = [gl.SRC_ALPHA, gl.ONE_MINUS_SRC_COLOR, gl.ONE, gl.ONE_MINUS_SRC_ALPHA]; + // composite operations + array[exports.BLEND_MODES.SRC_IN] = [gl.DST_ALPHA, gl.ZERO]; + array[exports.BLEND_MODES.SRC_OUT] = [gl.ONE_MINUS_DST_ALPHA, gl.ZERO]; + array[exports.BLEND_MODES.SRC_ATOP] = [gl.DST_ALPHA, gl.ONE_MINUS_SRC_ALPHA]; + array[exports.BLEND_MODES.DST_OVER] = [gl.ONE_MINUS_DST_ALPHA, gl.ONE]; + array[exports.BLEND_MODES.DST_IN] = [gl.ZERO, gl.SRC_ALPHA]; + array[exports.BLEND_MODES.DST_OUT] = [gl.ZERO, gl.ONE_MINUS_SRC_ALPHA]; + array[exports.BLEND_MODES.DST_ATOP] = [gl.ONE_MINUS_DST_ALPHA, gl.SRC_ALPHA]; + array[exports.BLEND_MODES.XOR] = [gl.ONE_MINUS_DST_ALPHA, gl.ONE_MINUS_SRC_ALPHA]; + // SUBTRACT from flash + array[exports.BLEND_MODES.SUBTRACT] = [gl.ONE, gl.ONE, gl.ONE, gl.ONE, gl.FUNC_REVERSE_SUBTRACT, gl.FUNC_ADD]; + return array; + } + + var BLEND = 0; + var OFFSET = 1; + var CULLING = 2; + var DEPTH_TEST = 3; + var WINDING = 4; + var DEPTH_MASK = 5; + /** + * System plugin to the renderer to manage WebGL state machines. + * @memberof PIXI + */ + var StateSystem = /** @class */ (function () { + function StateSystem() { + this.gl = null; + this.stateId = 0; + this.polygonOffset = 0; + this.blendMode = exports.BLEND_MODES.NONE; + this._blendEq = false; + // map functions for when we set state.. + this.map = []; + this.map[BLEND] = this.setBlend; + this.map[OFFSET] = this.setOffset; + this.map[CULLING] = this.setCullFace; + this.map[DEPTH_TEST] = this.setDepthTest; + this.map[WINDING] = this.setFrontFace; + this.map[DEPTH_MASK] = this.setDepthMask; + this.checks = []; + this.defaultState = new State(); + this.defaultState.blend = true; + } + StateSystem.prototype.contextChange = function (gl) { + this.gl = gl; + this.blendModes = mapWebGLBlendModesToPixi(gl); + this.set(this.defaultState); + this.reset(); + }; + /** + * Sets the current state + * @param {*} state - The state to set. + */ + StateSystem.prototype.set = function (state) { + state = state || this.defaultState; + // TODO maybe to an object check? ( this.state === state )? + if (this.stateId !== state.data) { + var diff = this.stateId ^ state.data; + var i = 0; + // order from least to most common + while (diff) { + if (diff & 1) { + // state change! + this.map[i].call(this, !!(state.data & (1 << i))); + } + diff = diff >> 1; + i++; + } + this.stateId = state.data; + } + // based on the above settings we check for specific modes.. + // for example if blend is active we check and set the blend modes + // or of polygon offset is active we check the poly depth. + for (var i = 0; i < this.checks.length; i++) { + this.checks[i](this, state); + } + }; + /** + * Sets the state, when previous state is unknown. + * @param {*} state - The state to set + */ + StateSystem.prototype.forceState = function (state) { + state = state || this.defaultState; + for (var i = 0; i < this.map.length; i++) { + this.map[i].call(this, !!(state.data & (1 << i))); + } + for (var i = 0; i < this.checks.length; i++) { + this.checks[i](this, state); + } + this.stateId = state.data; + }; + /** + * Sets whether to enable or disable blending. + * @param value - Turn on or off WebGl blending. + */ + StateSystem.prototype.setBlend = function (value) { + this.updateCheck(StateSystem.checkBlendMode, value); + this.gl[value ? 'enable' : 'disable'](this.gl.BLEND); + }; + /** + * Sets whether to enable or disable polygon offset fill. + * @param value - Turn on or off webgl polygon offset testing. + */ + StateSystem.prototype.setOffset = function (value) { + this.updateCheck(StateSystem.checkPolygonOffset, value); + this.gl[value ? 'enable' : 'disable'](this.gl.POLYGON_OFFSET_FILL); + }; + /** + * Sets whether to enable or disable depth test. + * @param value - Turn on or off webgl depth testing. + */ + StateSystem.prototype.setDepthTest = function (value) { + this.gl[value ? 'enable' : 'disable'](this.gl.DEPTH_TEST); + }; + /** + * Sets whether to enable or disable depth mask. + * @param value - Turn on or off webgl depth mask. + */ + StateSystem.prototype.setDepthMask = function (value) { + this.gl.depthMask(value); + }; + /** + * Sets whether to enable or disable cull face. + * @param {boolean} value - Turn on or off webgl cull face. + */ + StateSystem.prototype.setCullFace = function (value) { + this.gl[value ? 'enable' : 'disable'](this.gl.CULL_FACE); + }; + /** + * Sets the gl front face. + * @param {boolean} value - true is clockwise and false is counter-clockwise + */ + StateSystem.prototype.setFrontFace = function (value) { + this.gl.frontFace(this.gl[value ? 'CW' : 'CCW']); + }; + /** + * Sets the blend mode. + * @param {number} value - The blend mode to set to. + */ + StateSystem.prototype.setBlendMode = function (value) { + if (value === this.blendMode) { + return; + } + this.blendMode = value; + var mode = this.blendModes[value]; + var gl = this.gl; + if (mode.length === 2) { + gl.blendFunc(mode[0], mode[1]); + } + else { + gl.blendFuncSeparate(mode[0], mode[1], mode[2], mode[3]); + } + if (mode.length === 6) { + this._blendEq = true; + gl.blendEquationSeparate(mode[4], mode[5]); + } + else if (this._blendEq) { + this._blendEq = false; + gl.blendEquationSeparate(gl.FUNC_ADD, gl.FUNC_ADD); + } + }; + /** + * Sets the polygon offset. + * @param {number} value - the polygon offset + * @param {number} scale - the polygon offset scale + */ + StateSystem.prototype.setPolygonOffset = function (value, scale) { + this.gl.polygonOffset(value, scale); + }; + // used + /** Resets all the logic and disables the VAOs. */ + StateSystem.prototype.reset = function () { + this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL, false); + this.forceState(this.defaultState); + this._blendEq = true; + this.blendMode = -1; + this.setBlendMode(0); + }; + /** + * Checks to see which updates should be checked based on which settings have been activated. + * + * For example, if blend is enabled then we should check the blend modes each time the state is changed + * or if polygon fill is activated then we need to check if the polygon offset changes. + * The idea is that we only check what we have too. + * @param func - the checking function to add or remove + * @param value - should the check function be added or removed. + */ + StateSystem.prototype.updateCheck = function (func, value) { + var index = this.checks.indexOf(func); + if (value && index === -1) { + this.checks.push(func); + } + else if (!value && index !== -1) { + this.checks.splice(index, 1); + } + }; + /** + * A private little wrapper function that we call to check the blend mode. + * @param system - the System to perform the state check on + * @param state - the state that the blendMode will pulled from + */ + StateSystem.checkBlendMode = function (system, state) { + system.setBlendMode(state.blendMode); + }; + /** + * A private little wrapper function that we call to check the polygon offset. + * @param system - the System to perform the state check on + * @param state - the state that the blendMode will pulled from + */ + StateSystem.checkPolygonOffset = function (system, state) { + system.setPolygonOffset(1, state.polygonOffset); + }; + /** + * @ignore + */ + StateSystem.prototype.destroy = function () { + this.gl = null; + }; + return StateSystem; + }()); + + /** + * System plugin to the renderer to manage texture garbage collection on the GPU, + * ensuring that it does not get clogged up with textures that are no longer being used. + * @memberof PIXI + */ + var TextureGCSystem = /** @class */ (function () { + /** @param renderer - The renderer this System works for. */ + function TextureGCSystem(renderer) { + this.renderer = renderer; + this.count = 0; + this.checkCount = 0; + this.maxIdle = settings$1.GC_MAX_IDLE; + this.checkCountMax = settings$1.GC_MAX_CHECK_COUNT; + this.mode = settings$1.GC_MODE; + } + /** + * Checks to see when the last time a texture was used + * if the texture has not been used for a specified amount of time it will be removed from the GPU + */ + TextureGCSystem.prototype.postrender = function () { + if (!this.renderer.renderingToScreen) { + return; + } + this.count++; + if (this.mode === exports.GC_MODES.MANUAL) { + return; + } + this.checkCount++; + if (this.checkCount > this.checkCountMax) { + this.checkCount = 0; + this.run(); + } + }; + /** + * Checks to see when the last time a texture was used + * if the texture has not been used for a specified amount of time it will be removed from the GPU + */ + TextureGCSystem.prototype.run = function () { + var tm = this.renderer.texture; + var managedTextures = tm.managedTextures; + var wasRemoved = false; + for (var i = 0; i < managedTextures.length; i++) { + var texture = managedTextures[i]; + // only supports non generated textures at the moment! + if (!texture.framebuffer && this.count - texture.touched > this.maxIdle) { + tm.destroyTexture(texture, true); + managedTextures[i] = null; + wasRemoved = true; + } + } + if (wasRemoved) { + var j = 0; + for (var i = 0; i < managedTextures.length; i++) { + if (managedTextures[i] !== null) { + managedTextures[j++] = managedTextures[i]; + } + } + managedTextures.length = j; + } + }; + /** + * Removes all the textures within the specified displayObject and its children from the GPU + * @param {PIXI.DisplayObject} displayObject - the displayObject to remove the textures from. + */ + TextureGCSystem.prototype.unload = function (displayObject) { + var tm = this.renderer.texture; + var texture = displayObject._texture; + // only destroy non generated textures + if (texture && !texture.framebuffer) { + tm.destroyTexture(texture); + } + for (var i = displayObject.children.length - 1; i >= 0; i--) { + this.unload(displayObject.children[i]); + } + }; + TextureGCSystem.prototype.destroy = function () { + this.renderer = null; + }; + return TextureGCSystem; + }()); + + /** + * Returns a lookup table that maps each type-format pair to a compatible internal format. + * @memberof PIXI + * @function mapTypeAndFormatToInternalFormat + * @private + * @param {WebGLRenderingContext} gl - The rendering context. + * @returns Lookup table. + */ + function mapTypeAndFormatToInternalFormat(gl) { + var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x; + var table; + if ('WebGL2RenderingContext' in globalThis && gl instanceof globalThis.WebGL2RenderingContext) { + table = (_a = {}, + _a[exports.TYPES.UNSIGNED_BYTE] = (_b = {}, + _b[exports.FORMATS.RGBA] = gl.RGBA8, + _b[exports.FORMATS.RGB] = gl.RGB8, + _b[exports.FORMATS.RG] = gl.RG8, + _b[exports.FORMATS.RED] = gl.R8, + _b[exports.FORMATS.RGBA_INTEGER] = gl.RGBA8UI, + _b[exports.FORMATS.RGB_INTEGER] = gl.RGB8UI, + _b[exports.FORMATS.RG_INTEGER] = gl.RG8UI, + _b[exports.FORMATS.RED_INTEGER] = gl.R8UI, + _b[exports.FORMATS.ALPHA] = gl.ALPHA, + _b[exports.FORMATS.LUMINANCE] = gl.LUMINANCE, + _b[exports.FORMATS.LUMINANCE_ALPHA] = gl.LUMINANCE_ALPHA, + _b), + _a[exports.TYPES.BYTE] = (_c = {}, + _c[exports.FORMATS.RGBA] = gl.RGBA8_SNORM, + _c[exports.FORMATS.RGB] = gl.RGB8_SNORM, + _c[exports.FORMATS.RG] = gl.RG8_SNORM, + _c[exports.FORMATS.RED] = gl.R8_SNORM, + _c[exports.FORMATS.RGBA_INTEGER] = gl.RGBA8I, + _c[exports.FORMATS.RGB_INTEGER] = gl.RGB8I, + _c[exports.FORMATS.RG_INTEGER] = gl.RG8I, + _c[exports.FORMATS.RED_INTEGER] = gl.R8I, + _c), + _a[exports.TYPES.UNSIGNED_SHORT] = (_d = {}, + _d[exports.FORMATS.RGBA_INTEGER] = gl.RGBA16UI, + _d[exports.FORMATS.RGB_INTEGER] = gl.RGB16UI, + _d[exports.FORMATS.RG_INTEGER] = gl.RG16UI, + _d[exports.FORMATS.RED_INTEGER] = gl.R16UI, + _d[exports.FORMATS.DEPTH_COMPONENT] = gl.DEPTH_COMPONENT16, + _d), + _a[exports.TYPES.SHORT] = (_e = {}, + _e[exports.FORMATS.RGBA_INTEGER] = gl.RGBA16I, + _e[exports.FORMATS.RGB_INTEGER] = gl.RGB16I, + _e[exports.FORMATS.RG_INTEGER] = gl.RG16I, + _e[exports.FORMATS.RED_INTEGER] = gl.R16I, + _e), + _a[exports.TYPES.UNSIGNED_INT] = (_f = {}, + _f[exports.FORMATS.RGBA_INTEGER] = gl.RGBA32UI, + _f[exports.FORMATS.RGB_INTEGER] = gl.RGB32UI, + _f[exports.FORMATS.RG_INTEGER] = gl.RG32UI, + _f[exports.FORMATS.RED_INTEGER] = gl.R32UI, + _f[exports.FORMATS.DEPTH_COMPONENT] = gl.DEPTH_COMPONENT24, + _f), + _a[exports.TYPES.INT] = (_g = {}, + _g[exports.FORMATS.RGBA_INTEGER] = gl.RGBA32I, + _g[exports.FORMATS.RGB_INTEGER] = gl.RGB32I, + _g[exports.FORMATS.RG_INTEGER] = gl.RG32I, + _g[exports.FORMATS.RED_INTEGER] = gl.R32I, + _g), + _a[exports.TYPES.FLOAT] = (_h = {}, + _h[exports.FORMATS.RGBA] = gl.RGBA32F, + _h[exports.FORMATS.RGB] = gl.RGB32F, + _h[exports.FORMATS.RG] = gl.RG32F, + _h[exports.FORMATS.RED] = gl.R32F, + _h[exports.FORMATS.DEPTH_COMPONENT] = gl.DEPTH_COMPONENT32F, + _h), + _a[exports.TYPES.HALF_FLOAT] = (_j = {}, + _j[exports.FORMATS.RGBA] = gl.RGBA16F, + _j[exports.FORMATS.RGB] = gl.RGB16F, + _j[exports.FORMATS.RG] = gl.RG16F, + _j[exports.FORMATS.RED] = gl.R16F, + _j), + _a[exports.TYPES.UNSIGNED_SHORT_5_6_5] = (_k = {}, + _k[exports.FORMATS.RGB] = gl.RGB565, + _k), + _a[exports.TYPES.UNSIGNED_SHORT_4_4_4_4] = (_l = {}, + _l[exports.FORMATS.RGBA] = gl.RGBA4, + _l), + _a[exports.TYPES.UNSIGNED_SHORT_5_5_5_1] = (_m = {}, + _m[exports.FORMATS.RGBA] = gl.RGB5_A1, + _m), + _a[exports.TYPES.UNSIGNED_INT_2_10_10_10_REV] = (_o = {}, + _o[exports.FORMATS.RGBA] = gl.RGB10_A2, + _o[exports.FORMATS.RGBA_INTEGER] = gl.RGB10_A2UI, + _o), + _a[exports.TYPES.UNSIGNED_INT_10F_11F_11F_REV] = (_p = {}, + _p[exports.FORMATS.RGB] = gl.R11F_G11F_B10F, + _p), + _a[exports.TYPES.UNSIGNED_INT_5_9_9_9_REV] = (_q = {}, + _q[exports.FORMATS.RGB] = gl.RGB9_E5, + _q), + _a[exports.TYPES.UNSIGNED_INT_24_8] = (_r = {}, + _r[exports.FORMATS.DEPTH_STENCIL] = gl.DEPTH24_STENCIL8, + _r), + _a[exports.TYPES.FLOAT_32_UNSIGNED_INT_24_8_REV] = (_s = {}, + _s[exports.FORMATS.DEPTH_STENCIL] = gl.DEPTH32F_STENCIL8, + _s), + _a); + } + else { + table = (_t = {}, + _t[exports.TYPES.UNSIGNED_BYTE] = (_u = {}, + _u[exports.FORMATS.RGBA] = gl.RGBA, + _u[exports.FORMATS.RGB] = gl.RGB, + _u[exports.FORMATS.ALPHA] = gl.ALPHA, + _u[exports.FORMATS.LUMINANCE] = gl.LUMINANCE, + _u[exports.FORMATS.LUMINANCE_ALPHA] = gl.LUMINANCE_ALPHA, + _u), + _t[exports.TYPES.UNSIGNED_SHORT_5_6_5] = (_v = {}, + _v[exports.FORMATS.RGB] = gl.RGB, + _v), + _t[exports.TYPES.UNSIGNED_SHORT_4_4_4_4] = (_w = {}, + _w[exports.FORMATS.RGBA] = gl.RGBA, + _w), + _t[exports.TYPES.UNSIGNED_SHORT_5_5_5_1] = (_x = {}, + _x[exports.FORMATS.RGBA] = gl.RGBA, + _x), + _t); + } + return table; + } + + /** + * Internal texture for WebGL context. + * @memberof PIXI + */ + var GLTexture = /** @class */ (function () { + function GLTexture(texture) { + this.texture = texture; + this.width = -1; + this.height = -1; + this.dirtyId = -1; + this.dirtyStyleId = -1; + this.mipmap = false; + this.wrapMode = 33071; + this.type = exports.TYPES.UNSIGNED_BYTE; + this.internalFormat = exports.FORMATS.RGBA; + this.samplerType = 0; + } + return GLTexture; + }()); + + /** + * System plugin to the renderer to manage textures. + * @memberof PIXI + */ + var TextureSystem = /** @class */ (function () { + /** + * @param renderer - The renderer this system works for. + */ + function TextureSystem(renderer) { + this.renderer = renderer; + // TODO set to max textures... + this.boundTextures = []; + this.currentLocation = -1; + this.managedTextures = []; + this._unknownBoundTextures = false; + this.unknownTexture = new BaseTexture(); + this.hasIntegerTextures = false; + } + /** Sets up the renderer context and necessary buffers. */ + TextureSystem.prototype.contextChange = function () { + var gl = this.gl = this.renderer.gl; + this.CONTEXT_UID = this.renderer.CONTEXT_UID; + this.webGLVersion = this.renderer.context.webGLVersion; + this.internalFormats = mapTypeAndFormatToInternalFormat(gl); + var maxTextures = gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS); + this.boundTextures.length = maxTextures; + for (var i = 0; i < maxTextures; i++) { + this.boundTextures[i] = null; + } + // TODO move this.. to a nice make empty textures class.. + this.emptyTextures = {}; + var emptyTexture2D = new GLTexture(gl.createTexture()); + gl.bindTexture(gl.TEXTURE_2D, emptyTexture2D.texture); + gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, new Uint8Array(4)); + this.emptyTextures[gl.TEXTURE_2D] = emptyTexture2D; + this.emptyTextures[gl.TEXTURE_CUBE_MAP] = new GLTexture(gl.createTexture()); + gl.bindTexture(gl.TEXTURE_CUBE_MAP, this.emptyTextures[gl.TEXTURE_CUBE_MAP].texture); + for (var i = 0; i < 6; i++) { + gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, null); + } + gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR); + gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR); + for (var i = 0; i < this.boundTextures.length; i++) { + this.bind(null, i); + } + }; + /** + * Bind a texture to a specific location + * + * If you want to unbind something, please use `unbind(texture)` instead of `bind(null, textureLocation)` + * @param texture - Texture to bind + * @param [location=0] - Location to bind at + */ + TextureSystem.prototype.bind = function (texture, location) { + if (location === void 0) { location = 0; } + var gl = this.gl; + texture = texture === null || texture === void 0 ? void 0 : texture.castToBaseTexture(); + // cannot bind partial texture + // TODO: report a warning + if (texture && texture.valid && !texture.parentTextureArray) { + texture.touched = this.renderer.textureGC.count; + var glTexture = texture._glTextures[this.CONTEXT_UID] || this.initTexture(texture); + if (this.boundTextures[location] !== texture) { + if (this.currentLocation !== location) { + this.currentLocation = location; + gl.activeTexture(gl.TEXTURE0 + location); + } + gl.bindTexture(texture.target, glTexture.texture); + } + if (glTexture.dirtyId !== texture.dirtyId) { + if (this.currentLocation !== location) { + this.currentLocation = location; + gl.activeTexture(gl.TEXTURE0 + location); + } + this.updateTexture(texture); + } + this.boundTextures[location] = texture; + } + else { + if (this.currentLocation !== location) { + this.currentLocation = location; + gl.activeTexture(gl.TEXTURE0 + location); + } + gl.bindTexture(gl.TEXTURE_2D, this.emptyTextures[gl.TEXTURE_2D].texture); + this.boundTextures[location] = null; + } + }; + /** Resets texture location and bound textures Actual `bind(null, i)` calls will be performed at next `unbind()` call */ + TextureSystem.prototype.reset = function () { + this._unknownBoundTextures = true; + this.hasIntegerTextures = false; + this.currentLocation = -1; + for (var i = 0; i < this.boundTextures.length; i++) { + this.boundTextures[i] = this.unknownTexture; + } + }; + /** + * Unbind a texture. + * @param texture - Texture to bind + */ + TextureSystem.prototype.unbind = function (texture) { + var _a = this, gl = _a.gl, boundTextures = _a.boundTextures; + if (this._unknownBoundTextures) { + this._unknownBoundTextures = false; + // someone changed webGL state, + // we have to be sure that our texture does not appear in multi-texture renderer samplers + for (var i = 0; i < boundTextures.length; i++) { + if (boundTextures[i] === this.unknownTexture) { + this.bind(null, i); + } + } + } + for (var i = 0; i < boundTextures.length; i++) { + if (boundTextures[i] === texture) { + if (this.currentLocation !== i) { + gl.activeTexture(gl.TEXTURE0 + i); + this.currentLocation = i; + } + gl.bindTexture(texture.target, this.emptyTextures[texture.target].texture); + boundTextures[i] = null; + } + } + }; + /** + * Ensures that current boundTextures all have FLOAT sampler type, + * see {@link PIXI.SAMPLER_TYPES} for explanation. + * @param maxTextures - number of locations to check + */ + TextureSystem.prototype.ensureSamplerType = function (maxTextures) { + var _a = this, boundTextures = _a.boundTextures, hasIntegerTextures = _a.hasIntegerTextures, CONTEXT_UID = _a.CONTEXT_UID; + if (!hasIntegerTextures) { + return; + } + for (var i = maxTextures - 1; i >= 0; --i) { + var tex = boundTextures[i]; + if (tex) { + var glTexture = tex._glTextures[CONTEXT_UID]; + if (glTexture.samplerType !== exports.SAMPLER_TYPES.FLOAT) { + this.renderer.texture.unbind(tex); + } + } + } + }; + /** + * Initialize a texture + * @private + * @param texture - Texture to initialize + */ + TextureSystem.prototype.initTexture = function (texture) { + var glTexture = new GLTexture(this.gl.createTexture()); + // guarantee an update.. + glTexture.dirtyId = -1; + texture._glTextures[this.CONTEXT_UID] = glTexture; + this.managedTextures.push(texture); + texture.on('dispose', this.destroyTexture, this); + return glTexture; + }; + TextureSystem.prototype.initTextureType = function (texture, glTexture) { + var _a, _b; + glTexture.internalFormat = (_b = (_a = this.internalFormats[texture.type]) === null || _a === void 0 ? void 0 : _a[texture.format]) !== null && _b !== void 0 ? _b : texture.format; + if (this.webGLVersion === 2 && texture.type === exports.TYPES.HALF_FLOAT) { + // TYPES.HALF_FLOAT is WebGL1 HALF_FLOAT_OES + // we have to convert it to WebGL HALF_FLOAT + glTexture.type = this.gl.HALF_FLOAT; + } + else { + glTexture.type = texture.type; + } + }; + /** + * Update a texture + * @private + * @param {PIXI.BaseTexture} texture - Texture to initialize + */ + TextureSystem.prototype.updateTexture = function (texture) { + var glTexture = texture._glTextures[this.CONTEXT_UID]; + if (!glTexture) { + return; + } + var renderer = this.renderer; + this.initTextureType(texture, glTexture); + if (texture.resource && texture.resource.upload(renderer, texture, glTexture)) { + // texture is uploaded, dont do anything! + if (glTexture.samplerType !== exports.SAMPLER_TYPES.FLOAT) { + this.hasIntegerTextures = true; + } + } + else { + // default, renderTexture-like logic + var width = texture.realWidth; + var height = texture.realHeight; + var gl = renderer.gl; + if (glTexture.width !== width + || glTexture.height !== height + || glTexture.dirtyId < 0) { + glTexture.width = width; + glTexture.height = height; + gl.texImage2D(texture.target, 0, glTexture.internalFormat, width, height, 0, texture.format, glTexture.type, null); + } + } + // lets only update what changes.. + if (texture.dirtyStyleId !== glTexture.dirtyStyleId) { + this.updateTextureStyle(texture); + } + glTexture.dirtyId = texture.dirtyId; + }; + /** + * Deletes the texture from WebGL + * @private + * @param texture - the texture to destroy + * @param [skipRemove=false] - Whether to skip removing the texture from the TextureManager. + */ + TextureSystem.prototype.destroyTexture = function (texture, skipRemove) { + var gl = this.gl; + texture = texture.castToBaseTexture(); + if (texture._glTextures[this.CONTEXT_UID]) { + this.unbind(texture); + gl.deleteTexture(texture._glTextures[this.CONTEXT_UID].texture); + texture.off('dispose', this.destroyTexture, this); + delete texture._glTextures[this.CONTEXT_UID]; + if (!skipRemove) { + var i = this.managedTextures.indexOf(texture); + if (i !== -1) { + removeItems(this.managedTextures, i, 1); + } + } + } + }; + /** + * Update texture style such as mipmap flag + * @private + * @param {PIXI.BaseTexture} texture - Texture to update + */ + TextureSystem.prototype.updateTextureStyle = function (texture) { + var glTexture = texture._glTextures[this.CONTEXT_UID]; + if (!glTexture) { + return; + } + if ((texture.mipmap === exports.MIPMAP_MODES.POW2 || this.webGLVersion !== 2) && !texture.isPowerOfTwo) { + glTexture.mipmap = false; + } + else { + glTexture.mipmap = texture.mipmap >= 1; + } + if (this.webGLVersion !== 2 && !texture.isPowerOfTwo) { + glTexture.wrapMode = exports.WRAP_MODES.CLAMP; + } + else { + glTexture.wrapMode = texture.wrapMode; + } + if (texture.resource && texture.resource.style(this.renderer, texture, glTexture)) { ; } + else { + this.setStyle(texture, glTexture); + } + glTexture.dirtyStyleId = texture.dirtyStyleId; + }; + /** + * Set style for texture + * @private + * @param texture - Texture to update + * @param glTexture + */ + TextureSystem.prototype.setStyle = function (texture, glTexture) { + var gl = this.gl; + if (glTexture.mipmap && texture.mipmap !== exports.MIPMAP_MODES.ON_MANUAL) { + gl.generateMipmap(texture.target); + } + gl.texParameteri(texture.target, gl.TEXTURE_WRAP_S, glTexture.wrapMode); + gl.texParameteri(texture.target, gl.TEXTURE_WRAP_T, glTexture.wrapMode); + if (glTexture.mipmap) { + /* eslint-disable max-len */ + gl.texParameteri(texture.target, gl.TEXTURE_MIN_FILTER, texture.scaleMode === exports.SCALE_MODES.LINEAR ? gl.LINEAR_MIPMAP_LINEAR : gl.NEAREST_MIPMAP_NEAREST); + /* eslint-disable max-len */ + var anisotropicExt = this.renderer.context.extensions.anisotropicFiltering; + if (anisotropicExt && texture.anisotropicLevel > 0 && texture.scaleMode === exports.SCALE_MODES.LINEAR) { + var level = Math.min(texture.anisotropicLevel, gl.getParameter(anisotropicExt.MAX_TEXTURE_MAX_ANISOTROPY_EXT)); + gl.texParameterf(texture.target, anisotropicExt.TEXTURE_MAX_ANISOTROPY_EXT, level); + } + } + else { + gl.texParameteri(texture.target, gl.TEXTURE_MIN_FILTER, texture.scaleMode === exports.SCALE_MODES.LINEAR ? gl.LINEAR : gl.NEAREST); + } + gl.texParameteri(texture.target, gl.TEXTURE_MAG_FILTER, texture.scaleMode === exports.SCALE_MODES.LINEAR ? gl.LINEAR : gl.NEAREST); + }; + TextureSystem.prototype.destroy = function () { + this.renderer = null; + }; + return TextureSystem; + }()); + + var _systems = { + __proto__: null, + FilterSystem: FilterSystem, + BatchSystem: BatchSystem, + ContextSystem: ContextSystem, + FramebufferSystem: FramebufferSystem, + GeometrySystem: GeometrySystem, + MaskSystem: MaskSystem, + ScissorSystem: ScissorSystem, + StencilSystem: StencilSystem, + ProjectionSystem: ProjectionSystem, + RenderTextureSystem: RenderTextureSystem, + ShaderSystem: ShaderSystem, + StateSystem: StateSystem, + TextureGCSystem: TextureGCSystem, + TextureSystem: TextureSystem + }; + + var tempMatrix = new Matrix(); + /** + * The AbstractRenderer is the base for a PixiJS Renderer. It is extended by the {@link PIXI.CanvasRenderer} + * and {@link PIXI.Renderer} which can be used for rendering a PixiJS scene. + * @abstract + * @class + * @extends PIXI.utils.EventEmitter + * @memberof PIXI + */ + var AbstractRenderer = /** @class */ (function (_super) { + __extends$i(AbstractRenderer, _super); + /** + * @param type - The renderer type. + * @param [options] - The optional renderer parameters. + * @param {number} [options.width=800] - The width of the screen. + * @param {number} [options.height=600] - The height of the screen. + * @param {HTMLCanvasElement} [options.view] - The canvas to use as a view, optional. + * @param {boolean} [options.useContextAlpha=true] - Pass-through value for canvas' context `alpha` property. + * If you want to set transparency, please use `backgroundAlpha`. This option is for cases where the + * canvas needs to be opaque, possibly for performance reasons on some older devices. + * @param {boolean} [options.autoDensity=false] - Resizes renderer view in CSS pixels to allow for + * resolutions other than 1. + * @param {boolean} [options.antialias=false] - Sets antialias + * @param {number} [options.resolution=PIXI.settings.RESOLUTION] - The resolution / device pixel ratio of the renderer. + * @param {boolean} [options.preserveDrawingBuffer=false] - Enables drawing buffer preservation, + * enable this if you need to call toDataUrl on the WebGL context. + * @param {boolean} [options.clearBeforeRender=true] - This sets if the renderer will clear the canvas or + * not before the new render pass. + * @param {number} [options.backgroundColor=0x000000] - The background color of the rendered area + * (shown if not transparent). + * @param {number} [options.backgroundAlpha=1] - Value from 0 (fully transparent) to 1 (fully opaque). + */ + function AbstractRenderer(type, options) { + if (type === void 0) { type = exports.RENDERER_TYPE.UNKNOWN; } + var _this = _super.call(this) || this; + // Add the default render options + options = Object.assign({}, settings$1.RENDER_OPTIONS, options); + /** + * The supplied constructor options. + * @member {object} + * @readonly + */ + _this.options = options; + /** + * The type of the renderer. + * @member {number} + * @default PIXI.RENDERER_TYPE.UNKNOWN + * @see PIXI.RENDERER_TYPE + */ + _this.type = type; + /** + * Measurements of the screen. (0, 0, screenWidth, screenHeight). + * + * Its safe to use as filterArea or hitArea for the whole stage. + * @member {PIXI.Rectangle} + */ + _this.screen = new Rectangle(0, 0, options.width, options.height); + /** + * The canvas element that everything is drawn to. + * @member {HTMLCanvasElement} + */ + _this.view = options.view || settings$1.ADAPTER.createCanvas(); + /** + * The resolution / device pixel ratio of the renderer. + * @member {number} + * @default PIXI.settings.RESOLUTION + */ + _this.resolution = options.resolution || settings$1.RESOLUTION; + /** + * Pass-thru setting for the canvas' context `alpha` property. This is typically + * not something you need to fiddle with. If you want transparency, use `backgroundAlpha`. + * @member {boolean} + */ + _this.useContextAlpha = options.useContextAlpha; + /** + * Whether CSS dimensions of canvas view should be resized to screen dimensions automatically. + * @member {boolean} + */ + _this.autoDensity = !!options.autoDensity; + /** + * The value of the preserveDrawingBuffer flag affects whether or not the contents of + * the stencil buffer is retained after rendering. + * @member {boolean} + */ + _this.preserveDrawingBuffer = options.preserveDrawingBuffer; + /** + * This sets if the CanvasRenderer will clear the canvas or not before the new render pass. + * If the scene is NOT transparent PixiJS will use a canvas sized fillRect operation every + * frame to set the canvas background color. If the scene is transparent PixiJS will use clearRect + * to clear the canvas every frame. Disable this by setting this to false. For example, if + * your game has a canvas filling background image you often don't need this set. + * @member {boolean} + * @default + */ + _this.clearBeforeRender = options.clearBeforeRender; + /** + * The background color as a number. + * @member {number} + * @protected + */ + _this._backgroundColor = 0x000000; + /** + * The background color as an [R, G, B, A] array. + * @member {number[]} + * @protected + */ + _this._backgroundColorRgba = [0, 0, 0, 1]; + /** + * The background color as a string. + * @member {string} + * @protected + */ + _this._backgroundColorString = '#000000'; + _this.backgroundColor = options.backgroundColor || _this._backgroundColor; // run bg color setter + _this.backgroundAlpha = options.backgroundAlpha; + // @deprecated + if (options.transparent !== undefined) { + deprecation$1('6.0.0', 'Option transparent is deprecated, please use backgroundAlpha instead.'); + _this.useContextAlpha = options.transparent; + _this.backgroundAlpha = options.transparent ? 0 : 1; + } + /** + * The last root object that the renderer tried to render. + * @member {PIXI.DisplayObject} + * @protected + */ + _this._lastObjectRendered = null; + /** + * Collection of plugins. + * @readonly + * @member {object} + */ + _this.plugins = {}; + return _this; + } + /** + * Initialize the plugins. + * @protected + * @param {object} staticMap - The dictionary of statically saved plugins. + */ + AbstractRenderer.prototype.initPlugins = function (staticMap) { + for (var o in staticMap) { + this.plugins[o] = new (staticMap[o])(this); + } + }; + Object.defineProperty(AbstractRenderer.prototype, "width", { + /** + * Same as view.width, actual number of pixels in the canvas by horizontal. + * @member {number} + * @readonly + * @default 800 + */ + get: function () { + return this.view.width; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(AbstractRenderer.prototype, "height", { + /** + * Same as view.height, actual number of pixels in the canvas by vertical. + * @member {number} + * @readonly + * @default 600 + */ + get: function () { + return this.view.height; + }, + enumerable: false, + configurable: true + }); + /** + * Resizes the screen and canvas as close as possible to the specified width and height. + * Canvas dimensions are multiplied by resolution and rounded to the nearest integers. + * The new canvas dimensions divided by the resolution become the new screen dimensions. + * @param desiredScreenWidth - The desired width of the screen. + * @param desiredScreenHeight - The desired height of the screen. + */ + AbstractRenderer.prototype.resize = function (desiredScreenWidth, desiredScreenHeight) { + this.view.width = Math.round(desiredScreenWidth * this.resolution); + this.view.height = Math.round(desiredScreenHeight * this.resolution); + var screenWidth = this.view.width / this.resolution; + var screenHeight = this.view.height / this.resolution; + this.screen.width = screenWidth; + this.screen.height = screenHeight; + if (this.autoDensity) { + this.view.style.width = screenWidth + "px"; + this.view.style.height = screenHeight + "px"; + } + /** + * Fired after view has been resized. + * @event PIXI.Renderer#resize + * @param {number} screenWidth - The new width of the screen. + * @param {number} screenHeight - The new height of the screen. + */ + this.emit('resize', screenWidth, screenHeight); + }; + /** + * @ignore + */ + AbstractRenderer.prototype.generateTexture = function (displayObject, options, resolution, region) { + if (options === void 0) { options = {}; } + // @deprecated parameters spread, use options instead + if (typeof options === 'number') { + deprecation$1('6.1.0', 'generateTexture options (scaleMode, resolution, region) are now object options.'); + options = { scaleMode: options, resolution: resolution, region: region }; + } + var manualRegion = options.region, textureOptions = __rest(options, ["region"]); + region = manualRegion || displayObject.getLocalBounds(null, true); + // minimum texture size is 1x1, 0x0 will throw an error + if (region.width === 0) + { region.width = 1; } + if (region.height === 0) + { region.height = 1; } + var renderTexture = RenderTexture.create(__assign({ width: region.width, height: region.height }, textureOptions)); + tempMatrix.tx = -region.x; + tempMatrix.ty = -region.y; + this.render(displayObject, { + renderTexture: renderTexture, + clear: false, + transform: tempMatrix, + skipUpdateTransform: !!displayObject.parent + }); + return renderTexture; + }; + /** + * Removes everything from the renderer and optionally removes the Canvas DOM element. + * @param [removeView=false] - Removes the Canvas element from the DOM. + */ + AbstractRenderer.prototype.destroy = function (removeView) { + for (var o in this.plugins) { + this.plugins[o].destroy(); + this.plugins[o] = null; + } + if (removeView && this.view.parentNode) { + this.view.parentNode.removeChild(this.view); + } + var thisAny = this; + // null-ing all objects, that's a tradition! + thisAny.plugins = null; + thisAny.type = exports.RENDERER_TYPE.UNKNOWN; + thisAny.view = null; + thisAny.screen = null; + thisAny._tempDisplayObjectParent = null; + thisAny.options = null; + this._backgroundColorRgba = null; + this._backgroundColorString = null; + this._lastObjectRendered = null; + }; + Object.defineProperty(AbstractRenderer.prototype, "backgroundColor", { + /** + * The background color to fill if not transparent + * @member {number} + */ + get: function () { + return this._backgroundColor; + }, + set: function (value) { + this._backgroundColor = value; + this._backgroundColorString = hex2string(value); + hex2rgb(value, this._backgroundColorRgba); + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(AbstractRenderer.prototype, "backgroundAlpha", { + /** + * The background color alpha. Setting this to 0 will make the canvas transparent. + * @member {number} + */ + get: function () { + return this._backgroundColorRgba[3]; + }, + set: function (value) { + this._backgroundColorRgba[3] = value; + }, + enumerable: false, + configurable: true + }); + return AbstractRenderer; + }(eventemitter3)); + + var GLBuffer = /** @class */ (function () { + function GLBuffer(buffer) { + this.buffer = buffer || null; + this.updateID = -1; + this.byteLength = -1; + this.refCount = 0; + } + return GLBuffer; + }()); + + /** + * System plugin to the renderer to manage buffers. + * + * WebGL uses Buffers as a way to store objects to the GPU. + * This system makes working with them a lot easier. + * + * Buffers are used in three main places in WebGL + * - geometry information + * - Uniform information (via uniform buffer objects - a WebGL 2 only feature) + * - Transform feedback information. (WebGL 2 only feature) + * + * This system will handle the binding of buffers to the GPU as well as uploading + * them. With this system, you never need to work directly with GPU buffers, but instead work with + * the PIXI.Buffer class. + * @class + * @memberof PIXI + */ + var BufferSystem = /** @class */ (function () { + /** + * @param {PIXI.Renderer} renderer - The renderer this System works for. + */ + function BufferSystem(renderer) { + this.renderer = renderer; + this.managedBuffers = {}; + this.boundBufferBases = {}; + } + /** + * @ignore + */ + BufferSystem.prototype.destroy = function () { + this.renderer = null; + }; + /** Sets up the renderer context and necessary buffers. */ + BufferSystem.prototype.contextChange = function () { + this.disposeAll(true); + this.gl = this.renderer.gl; + // TODO fill out... + this.CONTEXT_UID = this.renderer.CONTEXT_UID; + }; + /** + * This binds specified buffer. On first run, it will create the webGL buffers for the context too + * @param buffer - the buffer to bind to the renderer + */ + BufferSystem.prototype.bind = function (buffer) { + var _a = this, gl = _a.gl, CONTEXT_UID = _a.CONTEXT_UID; + var glBuffer = buffer._glBuffers[CONTEXT_UID] || this.createGLBuffer(buffer); + gl.bindBuffer(buffer.type, glBuffer.buffer); + }; + /** + * Binds an uniform buffer to at the given index. + * + * A cache is used so a buffer will not be bound again if already bound. + * @param buffer - the buffer to bind + * @param index - the base index to bind it to. + */ + BufferSystem.prototype.bindBufferBase = function (buffer, index) { + var _a = this, gl = _a.gl, CONTEXT_UID = _a.CONTEXT_UID; + if (this.boundBufferBases[index] !== buffer) { + var glBuffer = buffer._glBuffers[CONTEXT_UID] || this.createGLBuffer(buffer); + this.boundBufferBases[index] = buffer; + gl.bindBufferBase(gl.UNIFORM_BUFFER, index, glBuffer.buffer); + } + }; + /** + * Binds a buffer whilst also binding its range. + * This will make the buffer start from the offset supplied rather than 0 when it is read. + * @param buffer - the buffer to bind + * @param index - the base index to bind at, defaults to 0 + * @param offset - the offset to bind at (this is blocks of 256). 0 = 0, 1 = 256, 2 = 512 etc + */ + BufferSystem.prototype.bindBufferRange = function (buffer, index, offset) { + var _a = this, gl = _a.gl, CONTEXT_UID = _a.CONTEXT_UID; + offset = offset || 0; + var glBuffer = buffer._glBuffers[CONTEXT_UID] || this.createGLBuffer(buffer); + gl.bindBufferRange(gl.UNIFORM_BUFFER, index || 0, glBuffer.buffer, offset * 256, 256); + }; + /** + * Will ensure the data in the buffer is uploaded to the GPU. + * @param {PIXI.Buffer} buffer - the buffer to update + */ + BufferSystem.prototype.update = function (buffer) { + var _a = this, gl = _a.gl, CONTEXT_UID = _a.CONTEXT_UID; + var glBuffer = buffer._glBuffers[CONTEXT_UID]; + if (buffer._updateID === glBuffer.updateID) { + return; + } + glBuffer.updateID = buffer._updateID; + gl.bindBuffer(buffer.type, glBuffer.buffer); + if (glBuffer.byteLength >= buffer.data.byteLength) { + // offset is always zero for now! + gl.bufferSubData(buffer.type, 0, buffer.data); + } + else { + var drawType = buffer.static ? gl.STATIC_DRAW : gl.DYNAMIC_DRAW; + glBuffer.byteLength = buffer.data.byteLength; + gl.bufferData(buffer.type, buffer.data, drawType); + } + }; + /** + * Disposes buffer + * @param {PIXI.Buffer} buffer - buffer with data + * @param {boolean} [contextLost=false] - If context was lost, we suppress deleteVertexArray + */ + BufferSystem.prototype.dispose = function (buffer, contextLost) { + if (!this.managedBuffers[buffer.id]) { + return; + } + delete this.managedBuffers[buffer.id]; + var glBuffer = buffer._glBuffers[this.CONTEXT_UID]; + var gl = this.gl; + buffer.disposeRunner.remove(this); + if (!glBuffer) { + return; + } + if (!contextLost) { + gl.deleteBuffer(glBuffer.buffer); + } + delete buffer._glBuffers[this.CONTEXT_UID]; + }; + /** + * dispose all WebGL resources of all managed buffers + * @param {boolean} [contextLost=false] - If context was lost, we suppress `gl.delete` calls + */ + BufferSystem.prototype.disposeAll = function (contextLost) { + var all = Object.keys(this.managedBuffers); + for (var i = 0; i < all.length; i++) { + this.dispose(this.managedBuffers[all[i]], contextLost); + } + }; + /** + * creates and attaches a GLBuffer object tied to the current context. + * @param buffer + * @protected + */ + BufferSystem.prototype.createGLBuffer = function (buffer) { + var _a = this, CONTEXT_UID = _a.CONTEXT_UID, gl = _a.gl; + buffer._glBuffers[CONTEXT_UID] = new GLBuffer(gl.createBuffer()); + this.managedBuffers[buffer.id] = buffer; + buffer.disposeRunner.add(this); + return buffer._glBuffers[CONTEXT_UID]; + }; + return BufferSystem; + }()); + + /** + * The Renderer draws the scene and all its content onto a WebGL enabled canvas. + * + * This renderer should be used for browsers that support WebGL. + * + * This renderer works by automatically managing WebGLBatchesm, so no need for Sprite Batches or Sprite Clouds. + * Don't forget to add the view to your DOM or you will not see anything! + * + * Renderer is composed of systems that manage specific tasks. The following systems are added by default + * whenever you create a renderer: + * + * | System | Description | + * | ------------------------------------ | ----------------------------------------------------------------------------- | + * | {@link PIXI.BatchSystem} | This manages object renderers that defer rendering until a flush. | + * | {@link PIXI.ContextSystem} | This manages the WebGL context and extensions. | + * | {@link PIXI.EventSystem} | This manages UI events. | + * | {@link PIXI.FilterSystem} | This manages the filtering pipeline for post-processing effects. | + * | {@link PIXI.FramebufferSystem} | This manages framebuffers, which are used for offscreen rendering. | + * | {@link PIXI.GeometrySystem} | This manages geometries & buffers, which are used to draw object meshes. | + * | {@link PIXI.MaskSystem} | This manages masking operations. | + * | {@link PIXI.ProjectionSystem} | This manages the `projectionMatrix`, used by shaders to get NDC coordinates. | + * | {@link PIXI.RenderTextureSystem} | This manages render-textures, which are an abstraction over framebuffers. | + * | {@link PIXI.ScissorSystem} | This handles scissor masking, and is used internally by {@link MaskSystem} | + * | {@link PIXI.ShaderSystem} | This manages shaders, programs that run on the GPU to calculate 'em pixels. | + * | {@link PIXI.StateSystem} | This manages the WebGL state variables like blend mode, depth testing, etc. | + * | {@link PIXI.StencilSystem} | This handles stencil masking, and is used internally by {@link MaskSystem} | + * | {@link PIXI.TextureSystem} | This manages textures and their resources on the GPU. | + * | {@link PIXI.TextureGCSystem} | This will automatically remove textures from the GPU if they are not used. | + * + * The breadth of the API surface provided by the renderer is contained within these systems. + * @memberof PIXI + */ + var Renderer = /** @class */ (function (_super) { + __extends$i(Renderer, _super); + /** + * @param [options] - The optional renderer parameters. + * @param {number} [options.width=800] - The width of the screen. + * @param {number} [options.height=600] - The height of the screen. + * @param {HTMLCanvasElement} [options.view] - The canvas to use as a view, optional. + * @param {boolean} [options.useContextAlpha=true] - Pass-through value for canvas' context `alpha` property. + * If you want to set transparency, please use `backgroundAlpha`. This option is for cases where the + * canvas needs to be opaque, possibly for performance reasons on some older devices. + * @param {boolean} [options.autoDensity=false] - Resizes renderer view in CSS pixels to allow for + * resolutions other than 1. + * @param {boolean} [options.antialias=false] - Sets antialias. If not available natively then FXAA + * antialiasing is used. + * @param {number} [options.resolution=PIXI.settings.RESOLUTION] - The resolution / device pixel ratio of the renderer. + * @param {boolean} [options.clearBeforeRender=true] - This sets if the renderer will clear + * the canvas or not before the new render pass. If you wish to set this to false, you *must* set + * preserveDrawingBuffer to `true`. + * @param {boolean} [options.preserveDrawingBuffer=false] - Enables drawing buffer preservation, + * enable this if you need to call toDataUrl on the WebGL context. + * @param {number} [options.backgroundColor=0x000000] - The background color of the rendered area + * (shown if not transparent). + * @param {number} [options.backgroundAlpha=1] - Value from 0 (fully transparent) to 1 (fully opaque). + * @param {string} [options.powerPreference] - Parameter passed to WebGL context, set to "high-performance" + * for devices with dual graphics card. + * @param {object} [options.context] - If WebGL context already exists, all parameters must be taken from it. + */ + function Renderer(options) { + var _this = _super.call(this, exports.RENDERER_TYPE.WEBGL, options) || this; + // the options will have been modified here in the super constructor with pixi's default settings.. + options = _this.options; + _this.gl = null; + _this.CONTEXT_UID = 0; + _this.runners = { + destroy: new Runner('destroy'), + contextChange: new Runner('contextChange'), + reset: new Runner('reset'), + update: new Runner('update'), + postrender: new Runner('postrender'), + prerender: new Runner('prerender'), + resize: new Runner('resize'), + }; + _this.runners.contextChange.add(_this); + _this.globalUniforms = new UniformGroup({ + projectionMatrix: new Matrix(), + }, true); + _this.addSystem(MaskSystem, 'mask') + .addSystem(ContextSystem, 'context') + .addSystem(StateSystem, 'state') + .addSystem(ShaderSystem, 'shader') + .addSystem(TextureSystem, 'texture') + .addSystem(BufferSystem, 'buffer') + .addSystem(GeometrySystem, 'geometry') + .addSystem(FramebufferSystem, 'framebuffer') + .addSystem(ScissorSystem, 'scissor') + .addSystem(StencilSystem, 'stencil') + .addSystem(ProjectionSystem, 'projection') + .addSystem(TextureGCSystem, 'textureGC') + .addSystem(FilterSystem, 'filter') + .addSystem(RenderTextureSystem, 'renderTexture') + .addSystem(BatchSystem, 'batch'); + _this.initPlugins(Renderer.__plugins); + _this.multisample = undefined; + /* + * The options passed in to create a new WebGL context. + */ + if (options.context) { + _this.context.initFromContext(options.context); + } + else { + _this.context.initFromOptions({ + alpha: !!_this.useContextAlpha, + antialias: options.antialias, + premultipliedAlpha: _this.useContextAlpha && _this.useContextAlpha !== 'notMultiplied', + stencil: true, + preserveDrawingBuffer: options.preserveDrawingBuffer, + powerPreference: _this.options.powerPreference, + }); + } + _this.renderingToScreen = true; + sayHello(_this.context.webGLVersion === 2 ? 'WebGL 2' : 'WebGL 1'); + _this.resize(_this.options.width, _this.options.height); + return _this; + } + /** + * Create renderer if WebGL is available. Overrideable + * by the **@pixi/canvas-renderer** package to allow fallback. + * throws error if WebGL is not available. + * @param options + * @private + */ + Renderer.create = function (options) { + if (isWebGLSupported()) { + return new Renderer(options); + } + throw new Error('WebGL unsupported in this browser, use "pixi.js-legacy" for fallback canvas2d support.'); + }; + Renderer.prototype.contextChange = function () { + var gl = this.gl; + var samples; + if (this.context.webGLVersion === 1) { + var framebuffer = gl.getParameter(gl.FRAMEBUFFER_BINDING); + gl.bindFramebuffer(gl.FRAMEBUFFER, null); + samples = gl.getParameter(gl.SAMPLES); + gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer); + } + else { + var framebuffer = gl.getParameter(gl.DRAW_FRAMEBUFFER_BINDING); + gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, null); + samples = gl.getParameter(gl.SAMPLES); + gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, framebuffer); + } + if (samples >= exports.MSAA_QUALITY.HIGH) { + this.multisample = exports.MSAA_QUALITY.HIGH; + } + else if (samples >= exports.MSAA_QUALITY.MEDIUM) { + this.multisample = exports.MSAA_QUALITY.MEDIUM; + } + else if (samples >= exports.MSAA_QUALITY.LOW) { + this.multisample = exports.MSAA_QUALITY.LOW; + } + else { + this.multisample = exports.MSAA_QUALITY.NONE; + } + }; + /** + * Add a new system to the renderer. + * @param ClassRef - Class reference + * @param name - Property name for system, if not specified + * will use a static `name` property on the class itself. This + * name will be assigned as s property on the Renderer so make + * sure it doesn't collide with properties on Renderer. + * @returns Return instance of renderer + */ + Renderer.prototype.addSystem = function (ClassRef, name) { + var system = new ClassRef(this); + if (this[name]) { + throw new Error("Whoops! The name \"" + name + "\" is already in use"); + } + this[name] = system; + for (var i in this.runners) { + this.runners[i].add(system); + } + /** + * Fired after rendering finishes. + * @event PIXI.Renderer#postrender + */ + /** + * Fired before rendering starts. + * @event PIXI.Renderer#prerender + */ + /** + * Fired when the WebGL context is set. + * @event PIXI.Renderer#context + * @param {WebGLRenderingContext} gl - WebGL context. + */ + return this; + }; + /** + * @ignore + */ + Renderer.prototype.render = function (displayObject, options) { + var renderTexture; + var clear; + var transform; + var skipUpdateTransform; + if (options) { + if (options instanceof RenderTexture) { + deprecation$1('6.0.0', 'Renderer#render arguments changed, use options instead.'); + /* eslint-disable prefer-rest-params */ + renderTexture = options; + clear = arguments[2]; + transform = arguments[3]; + skipUpdateTransform = arguments[4]; + /* eslint-enable prefer-rest-params */ + } + else { + renderTexture = options.renderTexture; + clear = options.clear; + transform = options.transform; + skipUpdateTransform = options.skipUpdateTransform; + } + } + // can be handy to know! + this.renderingToScreen = !renderTexture; + this.runners.prerender.emit(); + this.emit('prerender'); + // apply a transform at a GPU level + this.projection.transform = transform; + // no point rendering if our context has been blown up! + if (this.context.isLost) { + return; + } + if (!renderTexture) { + this._lastObjectRendered = displayObject; + } + if (!skipUpdateTransform) { + // update the scene graph + var cacheParent = displayObject.enableTempParent(); + displayObject.updateTransform(); + displayObject.disableTempParent(cacheParent); + // displayObject.hitArea = //TODO add a temp hit area + } + this.renderTexture.bind(renderTexture); + this.batch.currentRenderer.start(); + if (clear !== undefined ? clear : this.clearBeforeRender) { + this.renderTexture.clear(); + } + displayObject.render(this); + // apply transform.. + this.batch.currentRenderer.flush(); + if (renderTexture) { + renderTexture.baseTexture.update(); + } + this.runners.postrender.emit(); + // reset transform after render + this.projection.transform = null; + this.emit('postrender'); + }; + /** + * @override + * @ignore + */ + Renderer.prototype.generateTexture = function (displayObject, options, resolution, region) { + if (options === void 0) { options = {}; } + var renderTexture = _super.prototype.generateTexture.call(this, displayObject, options, resolution, region); + this.framebuffer.blit(); + return renderTexture; + }; + /** + * Resizes the WebGL view to the specified width and height. + * @param desiredScreenWidth - The desired width of the screen. + * @param desiredScreenHeight - The desired height of the screen. + */ + Renderer.prototype.resize = function (desiredScreenWidth, desiredScreenHeight) { + _super.prototype.resize.call(this, desiredScreenWidth, desiredScreenHeight); + this.runners.resize.emit(this.screen.height, this.screen.width); + }; + /** + * Resets the WebGL state so you can render things however you fancy! + * @returns Returns itself. + */ + Renderer.prototype.reset = function () { + this.runners.reset.emit(); + return this; + }; + /** Clear the frame buffer. */ + Renderer.prototype.clear = function () { + this.renderTexture.bind(); + this.renderTexture.clear(); + }; + /** + * Removes everything from the renderer (event listeners, spritebatch, etc...) + * @param [removeView=false] - Removes the Canvas element from the DOM. + * See: https://github.com/pixijs/pixi.js/issues/2233 + */ + Renderer.prototype.destroy = function (removeView) { + this.runners.destroy.emit(); + for (var r in this.runners) { + this.runners[r].destroy(); + } + // call base destroy + _super.prototype.destroy.call(this, removeView); + // TODO nullify all the managers.. + this.gl = null; + }; + Object.defineProperty(Renderer.prototype, "extract", { + /** + * Please use `plugins.extract` instead. + * @member {PIXI.Extract} extract + * @deprecated since 6.0.0 + * @readonly + */ + get: function () { + deprecation$1('6.0.0', 'Renderer#extract has been deprecated, please use Renderer#plugins.extract instead.'); + return this.plugins.extract; + }, + enumerable: false, + configurable: true + }); + /** + * Use the {@link PIXI.extensions.add} API to register plugins. + * @deprecated since 6.5.0 + * @param pluginName - The name of the plugin. + * @param ctor - The constructor function or class for the plugin. + */ + Renderer.registerPlugin = function (pluginName, ctor) { + deprecation$1('6.5.0', 'Renderer.registerPlugin() has been deprecated, please use extensions.add() instead.'); + extensions.add({ + name: pluginName, + type: exports.ExtensionType.RendererPlugin, + ref: ctor, + }); + }; + /** + * Collection of installed plugins. These are included by default in PIXI, but can be excluded + * by creating a custom build. Consult the README for more information about creating custom + * builds and excluding plugins. + * @readonly + * @property {PIXI.AccessibilityManager} accessibility Support tabbing interactive elements. + * @property {PIXI.Extract} extract Extract image data from renderer. + * @property {PIXI.InteractionManager} interaction Handles mouse, touch and pointer events. + * @property {PIXI.ParticleRenderer} particle Renderer for ParticleContainer objects. + * @property {PIXI.Prepare} prepare Pre-render display objects. + * @property {PIXI.BatchRenderer} batch Batching of Sprite, Graphics and Mesh objects. + * @property {PIXI.TilingSpriteRenderer} tilingSprite Renderer for TilingSprite objects. + */ + Renderer.__plugins = {}; + return Renderer; + }(AbstractRenderer)); + // Handle registration of extensions + extensions.handleByMap(exports.ExtensionType.RendererPlugin, Renderer.__plugins); + + /** + * This helper function will automatically detect which renderer you should be using. + * WebGL is the preferred renderer as it is a lot faster. If WebGL is not supported by + * the browser then this function will return a canvas renderer + * @memberof PIXI + * @function autoDetectRenderer + * @param {object} [options] - The optional renderer parameters + * @param {number} [options.width=800] - the width of the renderers view + * @param {number} [options.height=600] - the height of the renderers view + * @param {HTMLCanvasElement} [options.view] - the canvas to use as a view, optional + * @param {boolean} [options.useContextAlpha=true] - Pass-through value for canvas' context `alpha` property. + * If you want to set transparency, please use `backgroundAlpha`. This option is for cases where the + * canvas needs to be opaque, possibly for performance reasons on some older devices. + * @param {boolean} [options.autoDensity=false] - Resizes renderer view in CSS pixels to allow for + * resolutions other than 1 + * @param {boolean} [options.antialias=false] - sets antialias + * @param {boolean} [options.preserveDrawingBuffer=false] - enables drawing buffer preservation, enable this if you + * need to call toDataUrl on the webgl context + * @param {number} [options.backgroundColor=0x000000] - The background color of the rendered area + * (shown if not transparent). + * @param {number} [options.backgroundAlpha=1] - Value from 0 (fully transparent) to 1 (fully opaque). + * @param {boolean} [options.clearBeforeRender=true] - This sets if the renderer will clear the canvas or + * not before the new render pass. + * @param {number} [options.resolution=PIXI.settings.RESOLUTION] - The resolution / device pixel ratio of the renderer. + * @param {boolean} [options.forceCanvas=false] - prevents selection of WebGL renderer, even if such is present, this + * option only is available when using **pixi.js-legacy** or **@pixi/canvas-renderer** modules, otherwise + * it is ignored. + * @param {string} [options.powerPreference] - Parameter passed to webgl context, set to "high-performance" + * for devices with dual graphics card **webgl only** + * @returns {PIXI.Renderer|PIXI.CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer + */ + function autoDetectRenderer(options) { + return Renderer.create(options); + } + + var $defaultVertex = "attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n vTextureCoord = aTextureCoord;\n}"; + + var $defaultFilterVertex = "attribute vec2 aVertexPosition;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 vTextureCoord;\n\nuniform vec4 inputSize;\nuniform vec4 outputFrame;\n\nvec4 filterVertexPosition( void )\n{\n vec2 position = aVertexPosition * max(outputFrame.zw, vec2(0.)) + outputFrame.xy;\n\n return vec4((projectionMatrix * vec3(position, 1.0)).xy, 0.0, 1.0);\n}\n\nvec2 filterTextureCoord( void )\n{\n return aVertexPosition * (outputFrame.zw * inputSize.zw);\n}\n\nvoid main(void)\n{\n gl_Position = filterVertexPosition();\n vTextureCoord = filterTextureCoord();\n}\n"; + + /** + * Default vertex shader + * @memberof PIXI + * @member {string} defaultVertex + */ + /** + * Default filter vertex shader + * @memberof PIXI + * @member {string} defaultFilterVertex + */ + // NOTE: This black magic is so that @microsoft/api-extractor does not complain! This explicitly specifies the types + // of defaultVertex, defaultFilterVertex. + var defaultVertex$1 = $defaultVertex; + var defaultFilterVertex = $defaultFilterVertex; + + /** + * Use the ISystem interface instead. + * @deprecated since 6.1.0 + * @memberof PIXI + */ + var System = /** @class */ (function () { + /** + * @param renderer - Reference to Renderer + */ + function System(renderer) { + deprecation$1('6.1.0', 'System class is deprecated, implemement ISystem interface instead.'); + this.renderer = renderer; + } + /** Destroy and don't use after this. */ + System.prototype.destroy = function () { + this.renderer = null; + }; + return System; + }()); + + /** + * Used by the batcher to draw batches. + * Each one of these contains all information required to draw a bound geometry. + * @memberof PIXI + */ + var BatchDrawCall = /** @class */ (function () { + function BatchDrawCall() { + this.texArray = null; + this.blend = 0; + this.type = exports.DRAW_MODES.TRIANGLES; + this.start = 0; + this.size = 0; + this.data = null; + } + return BatchDrawCall; + }()); + + /** + * Used by the batcher to build texture batches. + * Holds list of textures and their respective locations. + * @memberof PIXI + */ + var BatchTextureArray = /** @class */ (function () { + function BatchTextureArray() { + this.elements = []; + this.ids = []; + this.count = 0; + } + BatchTextureArray.prototype.clear = function () { + for (var i = 0; i < this.count; i++) { + this.elements[i] = null; + } + this.count = 0; + }; + return BatchTextureArray; + }()); + + /** + * Flexible wrapper around `ArrayBuffer` that also provides typed array views on demand. + * @memberof PIXI + */ + var ViewableBuffer = /** @class */ (function () { + function ViewableBuffer(sizeOrBuffer) { + if (typeof sizeOrBuffer === 'number') { + this.rawBinaryData = new ArrayBuffer(sizeOrBuffer); + } + else if (sizeOrBuffer instanceof Uint8Array) { + this.rawBinaryData = sizeOrBuffer.buffer; + } + else { + this.rawBinaryData = sizeOrBuffer; + } + this.uint32View = new Uint32Array(this.rawBinaryData); + this.float32View = new Float32Array(this.rawBinaryData); + } + Object.defineProperty(ViewableBuffer.prototype, "int8View", { + /** View on the raw binary data as a `Int8Array`. */ + get: function () { + if (!this._int8View) { + this._int8View = new Int8Array(this.rawBinaryData); + } + return this._int8View; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(ViewableBuffer.prototype, "uint8View", { + /** View on the raw binary data as a `Uint8Array`. */ + get: function () { + if (!this._uint8View) { + this._uint8View = new Uint8Array(this.rawBinaryData); + } + return this._uint8View; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(ViewableBuffer.prototype, "int16View", { + /** View on the raw binary data as a `Int16Array`. */ + get: function () { + if (!this._int16View) { + this._int16View = new Int16Array(this.rawBinaryData); + } + return this._int16View; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(ViewableBuffer.prototype, "uint16View", { + /** View on the raw binary data as a `Uint16Array`. */ + get: function () { + if (!this._uint16View) { + this._uint16View = new Uint16Array(this.rawBinaryData); + } + return this._uint16View; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(ViewableBuffer.prototype, "int32View", { + /** View on the raw binary data as a `Int32Array`. */ + get: function () { + if (!this._int32View) { + this._int32View = new Int32Array(this.rawBinaryData); + } + return this._int32View; + }, + enumerable: false, + configurable: true + }); + /** + * Returns the view of the given type. + * @param type - One of `int8`, `uint8`, `int16`, + * `uint16`, `int32`, `uint32`, and `float32`. + * @returns - typed array of given type + */ + ViewableBuffer.prototype.view = function (type) { + return this[type + "View"]; + }; + /** Destroys all buffer references. Do not use after calling this. */ + ViewableBuffer.prototype.destroy = function () { + this.rawBinaryData = null; + this._int8View = null; + this._uint8View = null; + this._int16View = null; + this._uint16View = null; + this._int32View = null; + this.uint32View = null; + this.float32View = null; + }; + ViewableBuffer.sizeOf = function (type) { + switch (type) { + case 'int8': + case 'uint8': + return 1; + case 'int16': + case 'uint16': + return 2; + case 'int32': + case 'uint32': + case 'float32': + return 4; + default: + throw new Error(type + " isn't a valid view type"); + } + }; + return ViewableBuffer; + }()); + + /** + * Renderer dedicated to drawing and batching sprites. + * + * This is the default batch renderer. It buffers objects + * with texture-based geometries and renders them in + * batches. It uploads multiple textures to the GPU to + * reduce to the number of draw calls. + * @memberof PIXI + */ + var AbstractBatchRenderer = /** @class */ (function (_super) { + __extends$i(AbstractBatchRenderer, _super); + /** + * This will hook onto the renderer's `contextChange` + * and `prerender` signals. + * @param {PIXI.Renderer} renderer - The renderer this works for. + */ + function AbstractBatchRenderer(renderer) { + var _this = _super.call(this, renderer) || this; + _this.shaderGenerator = null; + _this.geometryClass = null; + _this.vertexSize = null; + _this.state = State.for2d(); + _this.size = settings$1.SPRITE_BATCH_SIZE * 4; + _this._vertexCount = 0; + _this._indexCount = 0; + _this._bufferedElements = []; + _this._bufferedTextures = []; + _this._bufferSize = 0; + _this._shader = null; + _this._packedGeometries = []; + _this._packedGeometryPoolSize = 2; + _this._flushId = 0; + _this._aBuffers = {}; + _this._iBuffers = {}; + _this.MAX_TEXTURES = 1; + _this.renderer.on('prerender', _this.onPrerender, _this); + renderer.runners.contextChange.add(_this); + _this._dcIndex = 0; + _this._aIndex = 0; + _this._iIndex = 0; + _this._attributeBuffer = null; + _this._indexBuffer = null; + _this._tempBoundTextures = []; + return _this; + } + /** + * Handles the `contextChange` signal. + * + * It calculates `this.MAX_TEXTURES` and allocating the packed-geometry object pool. + */ + AbstractBatchRenderer.prototype.contextChange = function () { + var gl = this.renderer.gl; + if (settings$1.PREFER_ENV === exports.ENV.WEBGL_LEGACY) { + this.MAX_TEXTURES = 1; + } + else { + // step 1: first check max textures the GPU can handle. + this.MAX_TEXTURES = Math.min(gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS), settings$1.SPRITE_MAX_TEXTURES); + // step 2: check the maximum number of if statements the shader can have too.. + this.MAX_TEXTURES = checkMaxIfStatementsInShader(this.MAX_TEXTURES, gl); + } + this._shader = this.shaderGenerator.generateShader(this.MAX_TEXTURES); + // we use the second shader as the first one depending on your browser + // may omit aTextureId as it is not used by the shader so is optimized out. + for (var i = 0; i < this._packedGeometryPoolSize; i++) { + /* eslint-disable max-len */ + this._packedGeometries[i] = new (this.geometryClass)(); + } + this.initFlushBuffers(); + }; + /** Makes sure that static and dynamic flush pooled objects have correct dimensions. */ + AbstractBatchRenderer.prototype.initFlushBuffers = function () { + var _drawCallPool = AbstractBatchRenderer._drawCallPool, _textureArrayPool = AbstractBatchRenderer._textureArrayPool; + // max draw calls + var MAX_SPRITES = this.size / 4; + // max texture arrays + var MAX_TA = Math.floor(MAX_SPRITES / this.MAX_TEXTURES) + 1; + while (_drawCallPool.length < MAX_SPRITES) { + _drawCallPool.push(new BatchDrawCall()); + } + while (_textureArrayPool.length < MAX_TA) { + _textureArrayPool.push(new BatchTextureArray()); + } + for (var i = 0; i < this.MAX_TEXTURES; i++) { + this._tempBoundTextures[i] = null; + } + }; + /** Handles the `prerender` signal. It ensures that flushes start from the first geometry object again. */ + AbstractBatchRenderer.prototype.onPrerender = function () { + this._flushId = 0; + }; + /** + * Buffers the "batchable" object. It need not be rendered immediately. + * @param {PIXI.DisplayObject} element - the element to render when + * using this renderer + */ + AbstractBatchRenderer.prototype.render = function (element) { + if (!element._texture.valid) { + return; + } + if (this._vertexCount + (element.vertexData.length / 2) > this.size) { + this.flush(); + } + this._vertexCount += element.vertexData.length / 2; + this._indexCount += element.indices.length; + this._bufferedTextures[this._bufferSize] = element._texture.baseTexture; + this._bufferedElements[this._bufferSize++] = element; + }; + AbstractBatchRenderer.prototype.buildTexturesAndDrawCalls = function () { + var _a = this, textures = _a._bufferedTextures, MAX_TEXTURES = _a.MAX_TEXTURES; + var textureArrays = AbstractBatchRenderer._textureArrayPool; + var batch = this.renderer.batch; + var boundTextures = this._tempBoundTextures; + var touch = this.renderer.textureGC.count; + var TICK = ++BaseTexture._globalBatch; + var countTexArrays = 0; + var texArray = textureArrays[0]; + var start = 0; + batch.copyBoundTextures(boundTextures, MAX_TEXTURES); + for (var i = 0; i < this._bufferSize; ++i) { + var tex = textures[i]; + textures[i] = null; + if (tex._batchEnabled === TICK) { + continue; + } + if (texArray.count >= MAX_TEXTURES) { + batch.boundArray(texArray, boundTextures, TICK, MAX_TEXTURES); + this.buildDrawCalls(texArray, start, i); + start = i; + texArray = textureArrays[++countTexArrays]; + ++TICK; + } + tex._batchEnabled = TICK; + tex.touched = touch; + texArray.elements[texArray.count++] = tex; + } + if (texArray.count > 0) { + batch.boundArray(texArray, boundTextures, TICK, MAX_TEXTURES); + this.buildDrawCalls(texArray, start, this._bufferSize); + ++countTexArrays; + ++TICK; + } + // Clean-up + for (var i = 0; i < boundTextures.length; i++) { + boundTextures[i] = null; + } + BaseTexture._globalBatch = TICK; + }; + /** + * Populating drawcalls for rendering + * @param texArray + * @param start + * @param finish + */ + AbstractBatchRenderer.prototype.buildDrawCalls = function (texArray, start, finish) { + var _a = this, elements = _a._bufferedElements, _attributeBuffer = _a._attributeBuffer, _indexBuffer = _a._indexBuffer, vertexSize = _a.vertexSize; + var drawCalls = AbstractBatchRenderer._drawCallPool; + var dcIndex = this._dcIndex; + var aIndex = this._aIndex; + var iIndex = this._iIndex; + var drawCall = drawCalls[dcIndex]; + drawCall.start = this._iIndex; + drawCall.texArray = texArray; + for (var i = start; i < finish; ++i) { + var sprite = elements[i]; + var tex = sprite._texture.baseTexture; + var spriteBlendMode = premultiplyBlendMode[tex.alphaMode ? 1 : 0][sprite.blendMode]; + elements[i] = null; + if (start < i && drawCall.blend !== spriteBlendMode) { + drawCall.size = iIndex - drawCall.start; + start = i; + drawCall = drawCalls[++dcIndex]; + drawCall.texArray = texArray; + drawCall.start = iIndex; + } + this.packInterleavedGeometry(sprite, _attributeBuffer, _indexBuffer, aIndex, iIndex); + aIndex += sprite.vertexData.length / 2 * vertexSize; + iIndex += sprite.indices.length; + drawCall.blend = spriteBlendMode; + } + if (start < finish) { + drawCall.size = iIndex - drawCall.start; + ++dcIndex; + } + this._dcIndex = dcIndex; + this._aIndex = aIndex; + this._iIndex = iIndex; + }; + /** + * Bind textures for current rendering + * @param texArray + */ + AbstractBatchRenderer.prototype.bindAndClearTexArray = function (texArray) { + var textureSystem = this.renderer.texture; + for (var j = 0; j < texArray.count; j++) { + textureSystem.bind(texArray.elements[j], texArray.ids[j]); + texArray.elements[j] = null; + } + texArray.count = 0; + }; + AbstractBatchRenderer.prototype.updateGeometry = function () { + var _a = this, packedGeometries = _a._packedGeometries, attributeBuffer = _a._attributeBuffer, indexBuffer = _a._indexBuffer; + if (!settings$1.CAN_UPLOAD_SAME_BUFFER) { /* Usually on iOS devices, where the browser doesn't + like uploads to the same buffer in a single frame. */ + if (this._packedGeometryPoolSize <= this._flushId) { + this._packedGeometryPoolSize++; + packedGeometries[this._flushId] = new (this.geometryClass)(); + } + packedGeometries[this._flushId]._buffer.update(attributeBuffer.rawBinaryData); + packedGeometries[this._flushId]._indexBuffer.update(indexBuffer); + this.renderer.geometry.bind(packedGeometries[this._flushId]); + this.renderer.geometry.updateBuffers(); + this._flushId++; + } + else { + // lets use the faster option, always use buffer number 0 + packedGeometries[this._flushId]._buffer.update(attributeBuffer.rawBinaryData); + packedGeometries[this._flushId]._indexBuffer.update(indexBuffer); + this.renderer.geometry.updateBuffers(); + } + }; + AbstractBatchRenderer.prototype.drawBatches = function () { + var dcCount = this._dcIndex; + var _a = this.renderer, gl = _a.gl, stateSystem = _a.state; + var drawCalls = AbstractBatchRenderer._drawCallPool; + var curTexArray = null; + // Upload textures and do the draw calls + for (var i = 0; i < dcCount; i++) { + var _b = drawCalls[i], texArray = _b.texArray, type = _b.type, size = _b.size, start = _b.start, blend = _b.blend; + if (curTexArray !== texArray) { + curTexArray = texArray; + this.bindAndClearTexArray(texArray); + } + this.state.blendMode = blend; + stateSystem.set(this.state); + gl.drawElements(type, size, gl.UNSIGNED_SHORT, start * 2); + } + }; + /** Renders the content _now_ and empties the current batch. */ + AbstractBatchRenderer.prototype.flush = function () { + if (this._vertexCount === 0) { + return; + } + this._attributeBuffer = this.getAttributeBuffer(this._vertexCount); + this._indexBuffer = this.getIndexBuffer(this._indexCount); + this._aIndex = 0; + this._iIndex = 0; + this._dcIndex = 0; + this.buildTexturesAndDrawCalls(); + this.updateGeometry(); + this.drawBatches(); + // reset elements buffer for the next flush + this._bufferSize = 0; + this._vertexCount = 0; + this._indexCount = 0; + }; + /** Starts a new sprite batch. */ + AbstractBatchRenderer.prototype.start = function () { + this.renderer.state.set(this.state); + this.renderer.texture.ensureSamplerType(this.MAX_TEXTURES); + this.renderer.shader.bind(this._shader); + if (settings$1.CAN_UPLOAD_SAME_BUFFER) { + // bind buffer #0, we don't need others + this.renderer.geometry.bind(this._packedGeometries[this._flushId]); + } + }; + /** Stops and flushes the current batch. */ + AbstractBatchRenderer.prototype.stop = function () { + this.flush(); + }; + /** Destroys this `AbstractBatchRenderer`. It cannot be used again. */ + AbstractBatchRenderer.prototype.destroy = function () { + for (var i = 0; i < this._packedGeometryPoolSize; i++) { + if (this._packedGeometries[i]) { + this._packedGeometries[i].destroy(); + } + } + this.renderer.off('prerender', this.onPrerender, this); + this._aBuffers = null; + this._iBuffers = null; + this._packedGeometries = null; + this._attributeBuffer = null; + this._indexBuffer = null; + if (this._shader) { + this._shader.destroy(); + this._shader = null; + } + _super.prototype.destroy.call(this); + }; + /** + * Fetches an attribute buffer from `this._aBuffers` that can hold atleast `size` floats. + * @param size - minimum capacity required + * @returns - buffer than can hold atleast `size` floats + */ + AbstractBatchRenderer.prototype.getAttributeBuffer = function (size) { + // 8 vertices is enough for 2 quads + var roundedP2 = nextPow2(Math.ceil(size / 8)); + var roundedSizeIndex = log2(roundedP2); + var roundedSize = roundedP2 * 8; + if (this._aBuffers.length <= roundedSizeIndex) { + this._iBuffers.length = roundedSizeIndex + 1; + } + var buffer = this._aBuffers[roundedSize]; + if (!buffer) { + this._aBuffers[roundedSize] = buffer = new ViewableBuffer(roundedSize * this.vertexSize * 4); + } + return buffer; + }; + /** + * Fetches an index buffer from `this._iBuffers` that can + * have at least `size` capacity. + * @param size - minimum required capacity + * @returns - buffer that can fit `size` indices. + */ + AbstractBatchRenderer.prototype.getIndexBuffer = function (size) { + // 12 indices is enough for 2 quads + var roundedP2 = nextPow2(Math.ceil(size / 12)); + var roundedSizeIndex = log2(roundedP2); + var roundedSize = roundedP2 * 12; + if (this._iBuffers.length <= roundedSizeIndex) { + this._iBuffers.length = roundedSizeIndex + 1; + } + var buffer = this._iBuffers[roundedSizeIndex]; + if (!buffer) { + this._iBuffers[roundedSizeIndex] = buffer = new Uint16Array(roundedSize); + } + return buffer; + }; + /** + * Takes the four batching parameters of `element`, interleaves + * and pushes them into the batching attribute/index buffers given. + * + * It uses these properties: `vertexData` `uvs`, `textureId` and + * `indicies`. It also uses the "tint" of the base-texture, if + * present. + * @param {PIXI.DisplayObject} element - element being rendered + * @param attributeBuffer - attribute buffer. + * @param indexBuffer - index buffer + * @param aIndex - number of floats already in the attribute buffer + * @param iIndex - number of indices already in `indexBuffer` + */ + AbstractBatchRenderer.prototype.packInterleavedGeometry = function (element, attributeBuffer, indexBuffer, aIndex, iIndex) { + var uint32View = attributeBuffer.uint32View, float32View = attributeBuffer.float32View; + var packedVertices = aIndex / this.vertexSize; + var uvs = element.uvs; + var indicies = element.indices; + var vertexData = element.vertexData; + var textureId = element._texture.baseTexture._batchLocation; + var alpha = Math.min(element.worldAlpha, 1.0); + var argb = (alpha < 1.0 + && element._texture.baseTexture.alphaMode) + ? premultiplyTint(element._tintRGB, alpha) + : element._tintRGB + (alpha * 255 << 24); + // lets not worry about tint! for now.. + for (var i = 0; i < vertexData.length; i += 2) { + float32View[aIndex++] = vertexData[i]; + float32View[aIndex++] = vertexData[i + 1]; + float32View[aIndex++] = uvs[i]; + float32View[aIndex++] = uvs[i + 1]; + uint32View[aIndex++] = argb; + float32View[aIndex++] = textureId; + } + for (var i = 0; i < indicies.length; i++) { + indexBuffer[iIndex++] = packedVertices + indicies[i]; + } + }; + /** + * Pool of `BatchDrawCall` objects that `flush` used + * to create "batches" of the objects being rendered. + * + * These are never re-allocated again. + * Shared between all batch renderers because it can be only one "flush" working at the moment. + * @member {PIXI.BatchDrawCall[]} + */ + AbstractBatchRenderer._drawCallPool = []; + /** + * Pool of `BatchDrawCall` objects that `flush` used + * to create "batches" of the objects being rendered. + * + * These are never re-allocated again. + * Shared between all batch renderers because it can be only one "flush" working at the moment. + * @member {PIXI.BatchTextureArray[]} + */ + AbstractBatchRenderer._textureArrayPool = []; + return AbstractBatchRenderer; + }(ObjectRenderer)); + + /** + * Helper that generates batching multi-texture shader. Use it with your new BatchRenderer + * @memberof PIXI + */ + var BatchShaderGenerator = /** @class */ (function () { + /** + * @param vertexSrc - Vertex shader + * @param fragTemplate - Fragment shader template + */ + function BatchShaderGenerator(vertexSrc, fragTemplate) { + this.vertexSrc = vertexSrc; + this.fragTemplate = fragTemplate; + this.programCache = {}; + this.defaultGroupCache = {}; + if (fragTemplate.indexOf('%count%') < 0) { + throw new Error('Fragment template must contain "%count%".'); + } + if (fragTemplate.indexOf('%forloop%') < 0) { + throw new Error('Fragment template must contain "%forloop%".'); + } + } + BatchShaderGenerator.prototype.generateShader = function (maxTextures) { + if (!this.programCache[maxTextures]) { + var sampleValues = new Int32Array(maxTextures); + for (var i = 0; i < maxTextures; i++) { + sampleValues[i] = i; + } + this.defaultGroupCache[maxTextures] = UniformGroup.from({ uSamplers: sampleValues }, true); + var fragmentSrc = this.fragTemplate; + fragmentSrc = fragmentSrc.replace(/%count%/gi, "" + maxTextures); + fragmentSrc = fragmentSrc.replace(/%forloop%/gi, this.generateSampleSrc(maxTextures)); + this.programCache[maxTextures] = new Program(this.vertexSrc, fragmentSrc); + } + var uniforms = { + tint: new Float32Array([1, 1, 1, 1]), + translationMatrix: new Matrix(), + default: this.defaultGroupCache[maxTextures], + }; + return new Shader(this.programCache[maxTextures], uniforms); + }; + BatchShaderGenerator.prototype.generateSampleSrc = function (maxTextures) { + var src = ''; + src += '\n'; + src += '\n'; + for (var i = 0; i < maxTextures; i++) { + if (i > 0) { + src += '\nelse '; + } + if (i < maxTextures - 1) { + src += "if(vTextureId < " + i + ".5)"; + } + src += '\n{'; + src += "\n\tcolor = texture2D(uSamplers[" + i + "], vTextureCoord);"; + src += '\n}'; + } + src += '\n'; + src += '\n'; + return src; + }; + return BatchShaderGenerator; + }()); + + /** + * Geometry used to batch standard PIXI content (e.g. Mesh, Sprite, Graphics objects). + * @memberof PIXI + */ + var BatchGeometry = /** @class */ (function (_super) { + __extends$i(BatchGeometry, _super); + /** + * @param {boolean} [_static=false] - Optimization flag, where `false` + * is updated every frame, `true` doesn't change frame-to-frame. + */ + function BatchGeometry(_static) { + if (_static === void 0) { _static = false; } + var _this = _super.call(this) || this; + _this._buffer = new Buffer(null, _static, false); + _this._indexBuffer = new Buffer(null, _static, true); + _this.addAttribute('aVertexPosition', _this._buffer, 2, false, exports.TYPES.FLOAT) + .addAttribute('aTextureCoord', _this._buffer, 2, false, exports.TYPES.FLOAT) + .addAttribute('aColor', _this._buffer, 4, true, exports.TYPES.UNSIGNED_BYTE) + .addAttribute('aTextureId', _this._buffer, 1, true, exports.TYPES.FLOAT) + .addIndex(_this._indexBuffer); + return _this; + } + return BatchGeometry; + }(Geometry)); + + var defaultVertex = "precision highp float;\nattribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\nattribute vec4 aColor;\nattribute float aTextureId;\n\nuniform mat3 projectionMatrix;\nuniform mat3 translationMatrix;\nuniform vec4 tint;\n\nvarying vec2 vTextureCoord;\nvarying vec4 vColor;\nvarying float vTextureId;\n\nvoid main(void){\n gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n vTextureCoord = aTextureCoord;\n vTextureId = aTextureId;\n vColor = aColor * tint;\n}\n"; + + var defaultFragment = "varying vec2 vTextureCoord;\nvarying vec4 vColor;\nvarying float vTextureId;\nuniform sampler2D uSamplers[%count%];\n\nvoid main(void){\n vec4 color;\n %forloop%\n gl_FragColor = color * vColor;\n}\n"; + + /** @memberof PIXI */ + var BatchPluginFactory = /** @class */ (function () { + function BatchPluginFactory() { + } + /** + * Create a new BatchRenderer plugin for Renderer. this convenience can provide an easy way + * to extend BatchRenderer with all the necessary pieces. + * @example + * const fragment = ` + * varying vec2 vTextureCoord; + * varying vec4 vColor; + * varying float vTextureId; + * uniform sampler2D uSamplers[%count%]; + * + * void main(void){ + * vec4 color; + * %forloop% + * gl_FragColor = vColor * vec4(color.a - color.rgb, color.a); + * } + * `; + * const InvertBatchRenderer = PIXI.BatchPluginFactory.create({ fragment }); + * PIXI.extensions.add({ + * name: 'invert', + * ref: InvertBatchRenderer, + * type: PIXI.ExtensionType.RendererPlugin, + * }); + * const sprite = new PIXI.Sprite(); + * sprite.pluginName = 'invert'; + * @param {object} [options] + * @param {string} [options.vertex=PIXI.BatchPluginFactory.defaultVertexSrc] - Vertex shader source + * @param {string} [options.fragment=PIXI.BatchPluginFactory.defaultFragmentTemplate] - Fragment shader template + * @param {number} [options.vertexSize=6] - Vertex size + * @param {object} [options.geometryClass=PIXI.BatchGeometry] + * @returns {*} New batch renderer plugin + */ + BatchPluginFactory.create = function (options) { + var _a = Object.assign({ + vertex: defaultVertex, + fragment: defaultFragment, + geometryClass: BatchGeometry, + vertexSize: 6, + }, options), vertex = _a.vertex, fragment = _a.fragment, vertexSize = _a.vertexSize, geometryClass = _a.geometryClass; + return /** @class */ (function (_super) { + __extends$i(BatchPlugin, _super); + function BatchPlugin(renderer) { + var _this = _super.call(this, renderer) || this; + _this.shaderGenerator = new BatchShaderGenerator(vertex, fragment); + _this.geometryClass = geometryClass; + _this.vertexSize = vertexSize; + return _this; + } + return BatchPlugin; + }(AbstractBatchRenderer)); + }; + Object.defineProperty(BatchPluginFactory, "defaultVertexSrc", { + /** + * The default vertex shader source + * @readonly + */ + get: function () { + return defaultVertex; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(BatchPluginFactory, "defaultFragmentTemplate", { + /** + * The default fragment shader source + * @readonly + */ + get: function () { + return defaultFragment; + }, + enumerable: false, + configurable: true + }); + return BatchPluginFactory; + }()); + // Setup the default BatchRenderer plugin, this is what + // we'll actually export at the root level + var BatchRenderer = BatchPluginFactory.create(); + Object.assign(BatchRenderer, { + extension: { + name: 'batch', + type: exports.ExtensionType.RendererPlugin, + }, + }); + + /** + * @memberof PIXI + * @namespace resources + * @see PIXI + * @deprecated since 6.0.0 + */ + var resources = {}; + var _loop_1 = function (name) { + Object.defineProperty(resources, name, { + get: function () { + deprecation$1('6.0.0', "PIXI.systems." + name + " has moved to PIXI." + name); + return _resources[name]; + }, + }); + }; + for (var name in _resources) { + _loop_1(name); + } + /** + * @memberof PIXI + * @namespace systems + * @see PIXI + * @deprecated since 6.0.0 + */ + var systems = {}; + var _loop_2 = function (name) { + Object.defineProperty(systems, name, { + get: function () { + deprecation$1('6.0.0', "PIXI.resources." + name + " has moved to PIXI." + name); + return _systems[name]; + }, + }); + }; + for (var name in _systems) { + _loop_2(name); + } + + /** + * @namespace PIXI + */ + /** + * String of the current PIXI version. + * @memberof PIXI + */ + var VERSION = '6.5.3'; + + /*! + * @pixi/accessibility - v6.5.3 + * Compiled Fri, 09 Sep 2022 13:55:20 UTC + * + * @pixi/accessibility is licensed under the MIT License. + * http://www.opensource.org/licenses/mit-license + */ + + /** + * Default property values of accessible objects + * used by {@link PIXI.AccessibilityManager}. + * @private + * @function accessibleTarget + * @memberof PIXI + * @type {object} + * @example + * function MyObject() {} + * + * Object.assign( + * MyObject.prototype, + * PIXI.accessibleTarget + * ); + */ + var accessibleTarget = { + /** + * Flag for if the object is accessible. If true AccessibilityManager will overlay a + * shadow div with attributes set + * @member {boolean} + * @memberof PIXI.DisplayObject# + */ + accessible: false, + /** + * Sets the title attribute of the shadow div + * If accessibleTitle AND accessibleHint has not been this will default to 'displayObject [tabIndex]' + * @member {?string} + * @memberof PIXI.DisplayObject# + */ + accessibleTitle: null, + /** + * Sets the aria-label attribute of the shadow div + * @member {string} + * @memberof PIXI.DisplayObject# + */ + accessibleHint: null, + /** + * @member {number} + * @memberof PIXI.DisplayObject# + * @private + * @todo Needs docs. + */ + tabIndex: 0, + /** + * @member {boolean} + * @memberof PIXI.DisplayObject# + * @todo Needs docs. + */ + _accessibleActive: false, + /** + * @member {boolean} + * @memberof PIXI.DisplayObject# + * @todo Needs docs. + */ + _accessibleDiv: null, + /** + * Specify the type of div the accessible layer is. Screen readers treat the element differently + * depending on this type. Defaults to button. + * @member {string} + * @memberof PIXI.DisplayObject# + * @default 'button' + */ + accessibleType: 'button', + /** + * Specify the pointer-events the accessible div will use + * Defaults to auto. + * @member {string} + * @memberof PIXI.DisplayObject# + * @default 'auto' + */ + accessiblePointerEvents: 'auto', + /** + * Setting to false will prevent any children inside this container to + * be accessible. Defaults to true. + * @member {boolean} + * @memberof PIXI.DisplayObject# + * @default true + */ + accessibleChildren: true, + renderId: -1, + }; + + // add some extra variables to the container.. + DisplayObject.mixin(accessibleTarget); + var KEY_CODE_TAB = 9; + var DIV_TOUCH_SIZE = 100; + var DIV_TOUCH_POS_X = 0; + var DIV_TOUCH_POS_Y = 0; + var DIV_TOUCH_ZINDEX = 2; + var DIV_HOOK_SIZE = 1; + var DIV_HOOK_POS_X = -1000; + var DIV_HOOK_POS_Y = -1000; + var DIV_HOOK_ZINDEX = 2; + /** + * The Accessibility manager recreates the ability to tab and have content read by screen readers. + * This is very important as it can possibly help people with disabilities access PixiJS content. + * + * A DisplayObject can be made accessible just like it can be made interactive. This manager will map the + * events as if the mouse was being used, minimizing the effort required to implement. + * + * An instance of this class is automatically created by default, and can be found at `renderer.plugins.accessibility` + * @class + * @memberof PIXI + */ + var AccessibilityManager = /** @class */ (function () { + /** + * @param {PIXI.CanvasRenderer|PIXI.Renderer} renderer - A reference to the current renderer + */ + function AccessibilityManager(renderer) { + /** Setting this to true will visually show the divs. */ + this.debug = false; + /** Internal variable, see isActive getter. */ + this._isActive = false; + /** Internal variable, see isMobileAccessibility getter. */ + this._isMobileAccessibility = false; + /** A simple pool for storing divs. */ + this.pool = []; + /** This is a tick used to check if an object is no longer being rendered. */ + this.renderId = 0; + /** The array of currently active accessible items. */ + this.children = []; + /** Count to throttle div updates on android devices. */ + this.androidUpdateCount = 0; + /** The frequency to update the div elements. */ + this.androidUpdateFrequency = 500; // 2fps + this._hookDiv = null; + if (isMobile$2.tablet || isMobile$2.phone) { + this.createTouchHook(); + } + // first we create a div that will sit over the PixiJS element. This is where the div overlays will go. + var div = document.createElement('div'); + div.style.width = DIV_TOUCH_SIZE + "px"; + div.style.height = DIV_TOUCH_SIZE + "px"; + div.style.position = 'absolute'; + div.style.top = DIV_TOUCH_POS_X + "px"; + div.style.left = DIV_TOUCH_POS_Y + "px"; + div.style.zIndex = DIV_TOUCH_ZINDEX.toString(); + this.div = div; + this.renderer = renderer; + /** + * pre-bind the functions + * @type {Function} + * @private + */ + this._onKeyDown = this._onKeyDown.bind(this); + /** + * pre-bind the functions + * @type {Function} + * @private + */ + this._onMouseMove = this._onMouseMove.bind(this); + // let listen for tab.. once pressed we can fire up and show the accessibility layer + globalThis.addEventListener('keydown', this._onKeyDown, false); + } + Object.defineProperty(AccessibilityManager.prototype, "isActive", { + /** + * Value of `true` if accessibility is currently active and accessibility layers are showing. + * @member {boolean} + * @readonly + */ + get: function () { + return this._isActive; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(AccessibilityManager.prototype, "isMobileAccessibility", { + /** + * Value of `true` if accessibility is enabled for touch devices. + * @member {boolean} + * @readonly + */ + get: function () { + return this._isMobileAccessibility; + }, + enumerable: false, + configurable: true + }); + /** + * Creates the touch hooks. + * @private + */ + AccessibilityManager.prototype.createTouchHook = function () { + var _this = this; + var hookDiv = document.createElement('button'); + hookDiv.style.width = DIV_HOOK_SIZE + "px"; + hookDiv.style.height = DIV_HOOK_SIZE + "px"; + hookDiv.style.position = 'absolute'; + hookDiv.style.top = DIV_HOOK_POS_X + "px"; + hookDiv.style.left = DIV_HOOK_POS_Y + "px"; + hookDiv.style.zIndex = DIV_HOOK_ZINDEX.toString(); + hookDiv.style.backgroundColor = '#FF0000'; + hookDiv.title = 'select to enable accessibility for this content'; + hookDiv.addEventListener('focus', function () { + _this._isMobileAccessibility = true; + _this.activate(); + _this.destroyTouchHook(); + }); + document.body.appendChild(hookDiv); + this._hookDiv = hookDiv; + }; + /** + * Destroys the touch hooks. + * @private + */ + AccessibilityManager.prototype.destroyTouchHook = function () { + if (!this._hookDiv) { + return; + } + document.body.removeChild(this._hookDiv); + this._hookDiv = null; + }; + /** + * Activating will cause the Accessibility layer to be shown. + * This is called when a user presses the tab key. + * @private + */ + AccessibilityManager.prototype.activate = function () { + var _a; + if (this._isActive) { + return; + } + this._isActive = true; + globalThis.document.addEventListener('mousemove', this._onMouseMove, true); + globalThis.removeEventListener('keydown', this._onKeyDown, false); + this.renderer.on('postrender', this.update, this); + (_a = this.renderer.view.parentNode) === null || _a === void 0 ? void 0 : _a.appendChild(this.div); + }; + /** + * Deactivating will cause the Accessibility layer to be hidden. + * This is called when a user moves the mouse. + * @private + */ + AccessibilityManager.prototype.deactivate = function () { + var _a; + if (!this._isActive || this._isMobileAccessibility) { + return; + } + this._isActive = false; + globalThis.document.removeEventListener('mousemove', this._onMouseMove, true); + globalThis.addEventListener('keydown', this._onKeyDown, false); + this.renderer.off('postrender', this.update); + (_a = this.div.parentNode) === null || _a === void 0 ? void 0 : _a.removeChild(this.div); + }; + /** + * This recursive function will run through the scene graph and add any new accessible objects to the DOM layer. + * @private + * @param {PIXI.Container} displayObject - The DisplayObject to check. + */ + AccessibilityManager.prototype.updateAccessibleObjects = function (displayObject) { + if (!displayObject.visible || !displayObject.accessibleChildren) { + return; + } + if (displayObject.accessible && displayObject.interactive) { + if (!displayObject._accessibleActive) { + this.addChild(displayObject); + } + displayObject.renderId = this.renderId; + } + var children = displayObject.children; + if (children) { + for (var i = 0; i < children.length; i++) { + this.updateAccessibleObjects(children[i]); + } + } + }; + /** + * Before each render this function will ensure that all divs are mapped correctly to their DisplayObjects. + * @private + */ + AccessibilityManager.prototype.update = function () { + /* On Android default web browser, tab order seems to be calculated by position rather than tabIndex, + * moving buttons can cause focus to flicker between two buttons making it hard/impossible to navigate, + * so I am just running update every half a second, seems to fix it. + */ + var now = performance.now(); + if (isMobile$2.android.device && now < this.androidUpdateCount) { + return; + } + this.androidUpdateCount = now + this.androidUpdateFrequency; + if (!this.renderer.renderingToScreen) { + return; + } + // update children... + if (this.renderer._lastObjectRendered) { + this.updateAccessibleObjects(this.renderer._lastObjectRendered); + } + var _a = this.renderer.view.getBoundingClientRect(), left = _a.left, top = _a.top, width = _a.width, height = _a.height; + var _b = this.renderer, viewWidth = _b.width, viewHeight = _b.height, resolution = _b.resolution; + var sx = (width / viewWidth) * resolution; + var sy = (height / viewHeight) * resolution; + var div = this.div; + div.style.left = left + "px"; + div.style.top = top + "px"; + div.style.width = viewWidth + "px"; + div.style.height = viewHeight + "px"; + for (var i = 0; i < this.children.length; i++) { + var child = this.children[i]; + if (child.renderId !== this.renderId) { + child._accessibleActive = false; + removeItems(this.children, i, 1); + this.div.removeChild(child._accessibleDiv); + this.pool.push(child._accessibleDiv); + child._accessibleDiv = null; + i--; + } + else { + // map div to display.. + div = child._accessibleDiv; + var hitArea = child.hitArea; + var wt = child.worldTransform; + if (child.hitArea) { + div.style.left = (wt.tx + (hitArea.x * wt.a)) * sx + "px"; + div.style.top = (wt.ty + (hitArea.y * wt.d)) * sy + "px"; + div.style.width = hitArea.width * wt.a * sx + "px"; + div.style.height = hitArea.height * wt.d * sy + "px"; + } + else { + hitArea = child.getBounds(); + this.capHitArea(hitArea); + div.style.left = hitArea.x * sx + "px"; + div.style.top = hitArea.y * sy + "px"; + div.style.width = hitArea.width * sx + "px"; + div.style.height = hitArea.height * sy + "px"; + // update button titles and hints if they exist and they've changed + if (div.title !== child.accessibleTitle && child.accessibleTitle !== null) { + div.title = child.accessibleTitle; + } + if (div.getAttribute('aria-label') !== child.accessibleHint + && child.accessibleHint !== null) { + div.setAttribute('aria-label', child.accessibleHint); + } + } + // the title or index may have changed, if so lets update it! + if (child.accessibleTitle !== div.title || child.tabIndex !== div.tabIndex) { + div.title = child.accessibleTitle; + div.tabIndex = child.tabIndex; + if (this.debug) + { this.updateDebugHTML(div); } + } + } + } + // increment the render id.. + this.renderId++; + }; + /** + * private function that will visually add the information to the + * accessability div + * @param {HTMLElement} div - + */ + AccessibilityManager.prototype.updateDebugHTML = function (div) { + div.innerHTML = "type: " + div.type + "
title : " + div.title + "
tabIndex: " + div.tabIndex; + }; + /** + * Adjust the hit area based on the bounds of a display object + * @param {PIXI.Rectangle} hitArea - Bounds of the child + */ + AccessibilityManager.prototype.capHitArea = function (hitArea) { + if (hitArea.x < 0) { + hitArea.width += hitArea.x; + hitArea.x = 0; + } + if (hitArea.y < 0) { + hitArea.height += hitArea.y; + hitArea.y = 0; + } + var _a = this.renderer, viewWidth = _a.width, viewHeight = _a.height; + if (hitArea.x + hitArea.width > viewWidth) { + hitArea.width = viewWidth - hitArea.x; + } + if (hitArea.y + hitArea.height > viewHeight) { + hitArea.height = viewHeight - hitArea.y; + } + }; + /** + * Adds a DisplayObject to the accessibility manager + * @private + * @param {PIXI.DisplayObject} displayObject - The child to make accessible. + */ + AccessibilityManager.prototype.addChild = function (displayObject) { + // this.activate(); + var div = this.pool.pop(); + if (!div) { + div = document.createElement('button'); + div.style.width = DIV_TOUCH_SIZE + "px"; + div.style.height = DIV_TOUCH_SIZE + "px"; + div.style.backgroundColor = this.debug ? 'rgba(255,255,255,0.5)' : 'transparent'; + div.style.position = 'absolute'; + div.style.zIndex = DIV_TOUCH_ZINDEX.toString(); + div.style.borderStyle = 'none'; + // ARIA attributes ensure that button title and hint updates are announced properly + if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1) { + // Chrome doesn't need aria-live to work as intended; in fact it just gets more confused. + div.setAttribute('aria-live', 'off'); + } + else { + div.setAttribute('aria-live', 'polite'); + } + if (navigator.userAgent.match(/rv:.*Gecko\//)) { + // FireFox needs this to announce only the new button name + div.setAttribute('aria-relevant', 'additions'); + } + else { + // required by IE, other browsers don't much care + div.setAttribute('aria-relevant', 'text'); + } + div.addEventListener('click', this._onClick.bind(this)); + div.addEventListener('focus', this._onFocus.bind(this)); + div.addEventListener('focusout', this._onFocusOut.bind(this)); + } + // set pointer events + div.style.pointerEvents = displayObject.accessiblePointerEvents; + // set the type, this defaults to button! + div.type = displayObject.accessibleType; + if (displayObject.accessibleTitle && displayObject.accessibleTitle !== null) { + div.title = displayObject.accessibleTitle; + } + else if (!displayObject.accessibleHint + || displayObject.accessibleHint === null) { + div.title = "displayObject " + displayObject.tabIndex; + } + if (displayObject.accessibleHint + && displayObject.accessibleHint !== null) { + div.setAttribute('aria-label', displayObject.accessibleHint); + } + if (this.debug) + { this.updateDebugHTML(div); } + displayObject._accessibleActive = true; + displayObject._accessibleDiv = div; + div.displayObject = displayObject; + this.children.push(displayObject); + this.div.appendChild(displayObject._accessibleDiv); + displayObject._accessibleDiv.tabIndex = displayObject.tabIndex; + }; + /** + * Maps the div button press to pixi's InteractionManager (click) + * @private + * @param {MouseEvent} e - The click event. + */ + AccessibilityManager.prototype._onClick = function (e) { + var interactionManager = this.renderer.plugins.interaction; + var displayObject = e.target.displayObject; + var eventData = interactionManager.eventData; + interactionManager.dispatchEvent(displayObject, 'click', eventData); + interactionManager.dispatchEvent(displayObject, 'pointertap', eventData); + interactionManager.dispatchEvent(displayObject, 'tap', eventData); + }; + /** + * Maps the div focus events to pixi's InteractionManager (mouseover) + * @private + * @param {FocusEvent} e - The focus event. + */ + AccessibilityManager.prototype._onFocus = function (e) { + if (!e.target.getAttribute('aria-live')) { + e.target.setAttribute('aria-live', 'assertive'); + } + var interactionManager = this.renderer.plugins.interaction; + var displayObject = e.target.displayObject; + var eventData = interactionManager.eventData; + interactionManager.dispatchEvent(displayObject, 'mouseover', eventData); + }; + /** + * Maps the div focus events to pixi's InteractionManager (mouseout) + * @private + * @param {FocusEvent} e - The focusout event. + */ + AccessibilityManager.prototype._onFocusOut = function (e) { + if (!e.target.getAttribute('aria-live')) { + e.target.setAttribute('aria-live', 'polite'); + } + var interactionManager = this.renderer.plugins.interaction; + var displayObject = e.target.displayObject; + var eventData = interactionManager.eventData; + interactionManager.dispatchEvent(displayObject, 'mouseout', eventData); + }; + /** + * Is called when a key is pressed + * @private + * @param {KeyboardEvent} e - The keydown event. + */ + AccessibilityManager.prototype._onKeyDown = function (e) { + if (e.keyCode !== KEY_CODE_TAB) { + return; + } + this.activate(); + }; + /** + * Is called when the mouse moves across the renderer element + * @private + * @param {MouseEvent} e - The mouse event. + */ + AccessibilityManager.prototype._onMouseMove = function (e) { + if (e.movementX === 0 && e.movementY === 0) { + return; + } + this.deactivate(); + }; + /** Destroys the accessibility manager */ + AccessibilityManager.prototype.destroy = function () { + this.destroyTouchHook(); + this.div = null; + globalThis.document.removeEventListener('mousemove', this._onMouseMove, true); + globalThis.removeEventListener('keydown', this._onKeyDown); + this.pool = null; + this.children = null; + this.renderer = null; + }; + /** @ignore */ + AccessibilityManager.extension = { + name: 'accessibility', + type: [ + exports.ExtensionType.RendererPlugin, + exports.ExtensionType.CanvasRendererPlugin ], + }; + return AccessibilityManager; + }()); + + /*! + * @pixi/interaction - v6.5.3 + * Compiled Fri, 09 Sep 2022 13:55:20 UTC + * + * @pixi/interaction is licensed under the MIT License. + * http://www.opensource.org/licenses/mit-license + */ + + /** + * Holds all information related to an Interaction event + * @memberof PIXI + */ + var InteractionData = /** @class */ (function () { + function InteractionData() { + /** + * Pressure applied by the pointing device during the event. A Touch's force property + * will be represented by this value. + * @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/pressure + */ + this.pressure = 0; + /** + * From TouchEvents (not PointerEvents triggered by touches), the rotationAngle of the Touch. + * @see https://developer.mozilla.org/en-US/docs/Web/API/Touch/rotationAngle + */ + this.rotationAngle = 0; + /** + * Twist of a stylus pointer. + * @see https://w3c.github.io/pointerevents/#pointerevent-interface + */ + this.twist = 0; + /** + * Barrel pressure on a stylus pointer. + * @see https://w3c.github.io/pointerevents/#pointerevent-interface + */ + this.tangentialPressure = 0; + this.global = new Point(); + this.target = null; + this.originalEvent = null; + this.identifier = null; + this.isPrimary = false; + this.button = 0; + this.buttons = 0; + this.width = 0; + this.height = 0; + this.tiltX = 0; + this.tiltY = 0; + this.pointerType = null; + this.pressure = 0; + this.rotationAngle = 0; + this.twist = 0; + this.tangentialPressure = 0; + } + Object.defineProperty(InteractionData.prototype, "pointerId", { + /** + * The unique identifier of the pointer. It will be the same as `identifier`. + * @readonly + * @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/pointerId + */ + get: function () { + return this.identifier; + }, + enumerable: false, + configurable: true + }); + /** + * This will return the local coordinates of the specified displayObject for this InteractionData + * @param displayObject - The DisplayObject that you would like the local + * coords off + * @param point - A Point object in which to store the value, optional (otherwise + * will create a new point) + * @param globalPos - A Point object containing your custom global coords, optional + * (otherwise will use the current global coords) + * @returns - A point containing the coordinates of the InteractionData position relative + * to the DisplayObject + */ + InteractionData.prototype.getLocalPosition = function (displayObject, point, globalPos) { + return displayObject.worldTransform.applyInverse(globalPos || this.global, point); + }; + /** + * Copies properties from normalized event data. + * @param {Touch|MouseEvent|PointerEvent} event - The normalized event data + */ + InteractionData.prototype.copyEvent = function (event) { + // isPrimary should only change on touchstart/pointerdown, so we don't want to overwrite + // it with "false" on later events when our shim for it on touch events might not be + // accurate + if ('isPrimary' in event && event.isPrimary) { + this.isPrimary = true; + } + this.button = 'button' in event && event.button; + // event.buttons is not available in all browsers (ie. Safari), but it does have a non-standard + // event.which property instead, which conveys the same information. + var buttons = 'buttons' in event && event.buttons; + this.buttons = Number.isInteger(buttons) ? buttons : 'which' in event && event.which; + this.width = 'width' in event && event.width; + this.height = 'height' in event && event.height; + this.tiltX = 'tiltX' in event && event.tiltX; + this.tiltY = 'tiltY' in event && event.tiltY; + this.pointerType = 'pointerType' in event && event.pointerType; + this.pressure = 'pressure' in event && event.pressure; + this.rotationAngle = 'rotationAngle' in event && event.rotationAngle; + this.twist = ('twist' in event && event.twist) || 0; + this.tangentialPressure = ('tangentialPressure' in event && event.tangentialPressure) || 0; + }; + /** Resets the data for pooling. */ + InteractionData.prototype.reset = function () { + // isPrimary is the only property that we really need to reset - everything else is + // guaranteed to be overwritten + this.isPrimary = false; + }; + return InteractionData; + }()); + + /*! ***************************************************************************** + Copyright (c) Microsoft Corporation. - var extendStatics$7 = function(d, b) { - extendStatics$7 = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) { if (b.hasOwnProperty(p)) { d[p] = b[p]; } } }; - return extendStatics$7(d, b); - }; + Permission to use, copy, modify, and/or distribute this software for any + purpose with or without fee is hereby granted. - function __extends$7(d, b) { - extendStatics$7(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - } - - /** - * Constants that define the type of gradient on text. - * - * @static - * @constant - * @name TEXT_GRADIENT - * @memberof PIXI - * @type {object} - * @property {number} LINEAR_VERTICAL Vertical gradient - * @property {number} LINEAR_HORIZONTAL Linear gradient - */ - - (function (TEXT_GRADIENT) { - TEXT_GRADIENT[TEXT_GRADIENT["LINEAR_VERTICAL"] = 0] = "LINEAR_VERTICAL"; - TEXT_GRADIENT[TEXT_GRADIENT["LINEAR_HORIZONTAL"] = 1] = "LINEAR_HORIZONTAL"; - })(exports.TEXT_GRADIENT || (exports.TEXT_GRADIENT = {})); - - // disabling eslint for now, going to rewrite this in v5 - var defaultStyle = { - align: 'left', - breakWords: false, - dropShadow: false, - dropShadowAlpha: 1, - dropShadowAngle: Math.PI / 6, - dropShadowBlur: 0, - dropShadowColor: 'black', - dropShadowDistance: 5, - fill: 'black', - fillGradientType: exports.TEXT_GRADIENT.LINEAR_VERTICAL, - fillGradientStops: [], - fontFamily: 'Arial', - fontSize: 26, - fontStyle: 'normal', - fontVariant: 'normal', - fontWeight: 'normal', - letterSpacing: 0, - lineHeight: 0, - lineJoin: 'miter', - miterLimit: 10, - padding: 0, - stroke: 'black', - strokeThickness: 0, - textBaseline: 'alphabetic', - trim: false, - whiteSpace: 'pre', - wordWrap: false, - wordWrapWidth: 100, - leading: 0, - }; - var genericFontFamilies = [ - 'serif', - 'sans-serif', - 'monospace', - 'cursive', - 'fantasy', - 'system-ui' ]; - /** - * A TextStyle Object contains information to decorate a Text objects. - * - * An instance can be shared between multiple Text objects; then changing the style will update all text objects using it. - * - * A tool can be used to generate a text style [here](https://pixijs.io/pixi-text-style). - * - * @class - * @memberof PIXI - */ - var TextStyle = /** @class */ (function () { - /** - * @param {object} [style] - The style parameters - * @param {string} [style.align='left'] - Alignment for multiline text ('left', 'center' or 'right'), - * does not affect single line text - * @param {boolean} [style.breakWords=false] - Indicates if lines can be wrapped within words, it - * needs wordWrap to be set to true - * @param {boolean} [style.dropShadow=false] - Set a drop shadow for the text - * @param {number} [style.dropShadowAlpha=1] - Set alpha for the drop shadow - * @param {number} [style.dropShadowAngle=Math.PI/6] - Set a angle of the drop shadow - * @param {number} [style.dropShadowBlur=0] - Set a shadow blur radius - * @param {string|number} [style.dropShadowColor='black'] - A fill style to be used on the dropshadow e.g 'red', '#00FF00' - * @param {number} [style.dropShadowDistance=5] - Set a distance of the drop shadow - * @param {string|string[]|number|number[]|CanvasGradient|CanvasPattern} [style.fill='black'] - A canvas - * fillstyle that will be used on the text e.g 'red', '#00FF00'. Can be an array to create a gradient - * eg ['#000000','#FFFFFF'] - * {@link https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/fillStyle|MDN} - * @param {number} [style.fillGradientType=PIXI.TEXT_GRADIENT.LINEAR_VERTICAL] - If fill is an array of colours - * to create a gradient, this can change the type/direction of the gradient. See {@link PIXI.TEXT_GRADIENT} - * @param {number[]} [style.fillGradientStops] - If fill is an array of colours to create a gradient, this array can set - * the stop points (numbers between 0 and 1) for the color, overriding the default behaviour of evenly spacing them. - * @param {string|string[]} [style.fontFamily='Arial'] - The font family - * @param {number|string} [style.fontSize=26] - The font size (as a number it converts to px, but as a string, - * equivalents are '26px','20pt','160%' or '1.6em') - * @param {string} [style.fontStyle='normal'] - The font style ('normal', 'italic' or 'oblique') - * @param {string} [style.fontVariant='normal'] - The font variant ('normal' or 'small-caps') - * @param {string} [style.fontWeight='normal'] - The font weight ('normal', 'bold', 'bolder', 'lighter' and '100', - * '200', '300', '400', '500', '600', '700', '800' or '900') - * @param {number} [style.leading=0] - The space between lines - * @param {number} [style.letterSpacing=0] - The amount of spacing between letters, default is 0 - * @param {number} [style.lineHeight] - The line height, a number that represents the vertical space that a letter uses - * @param {string} [style.lineJoin='miter'] - The lineJoin property sets the type of corner created, it can resolve - * spiked text issues. Possible values "miter" (creates a sharp corner), "round" (creates a round corner) or "bevel" - * (creates a squared corner). - * @param {number} [style.miterLimit=10] - The miter limit to use when using the 'miter' lineJoin mode. This can reduce - * or increase the spikiness of rendered text. - * @param {number} [style.padding=0] - Occasionally some fonts are cropped. Adding some padding will prevent this from - * happening by adding padding to all sides of the text. - * @param {string|number} [style.stroke='black'] - A canvas fillstyle that will be used on the text stroke - * e.g 'blue', '#FCFF00' - * @param {number} [style.strokeThickness=0] - A number that represents the thickness of the stroke. - * Default is 0 (no stroke) - * @param {boolean} [style.trim=false] - Trim transparent borders - * @param {string} [style.textBaseline='alphabetic'] - The baseline of the text that is rendered. - * @param {string} [style.whiteSpace='pre'] - Determines whether newlines & spaces are collapsed or preserved "normal" - * (collapse, collapse), "pre" (preserve, preserve) | "pre-line" (preserve, collapse). It needs wordWrap to be set to true - * @param {boolean} [style.wordWrap=false] - Indicates if word wrap should be used - * @param {number} [style.wordWrapWidth=100] - The width at which text will wrap, it needs wordWrap to be set to true - */ - function TextStyle(style) { - this.styleID = 0; - this.reset(); - deepCopyProperties(this, style, style); - } - /** - * Creates a new TextStyle object with the same values as this one. - * Note that the only the properties of the object are cloned. - * - * @return {PIXI.TextStyle} New cloned TextStyle object - */ - TextStyle.prototype.clone = function () { - var clonedProperties = {}; - deepCopyProperties(clonedProperties, this, defaultStyle); - return new TextStyle(clonedProperties); - }; - /** - * Resets all properties to the defaults specified in TextStyle.prototype._default - */ - TextStyle.prototype.reset = function () { - deepCopyProperties(this, defaultStyle, defaultStyle); - }; - Object.defineProperty(TextStyle.prototype, "align", { - /** - * Alignment for multiline text ('left', 'center' or 'right'), does not affect single line text - * - * @member {string} - */ - get: function () { - return this._align; - }, - set: function (align) { - if (this._align !== align) { - this._align = align; - this.styleID++; - } - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(TextStyle.prototype, "breakWords", { - /** - * Indicates if lines can be wrapped within words, it needs wordWrap to be set to true - * - * @member {boolean} - */ - get: function () { - return this._breakWords; - }, - set: function (breakWords) { - if (this._breakWords !== breakWords) { - this._breakWords = breakWords; - this.styleID++; - } - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(TextStyle.prototype, "dropShadow", { - /** - * Set a drop shadow for the text - * - * @member {boolean} - */ - get: function () { - return this._dropShadow; - }, - set: function (dropShadow) { - if (this._dropShadow !== dropShadow) { - this._dropShadow = dropShadow; - this.styleID++; - } - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(TextStyle.prototype, "dropShadowAlpha", { - /** - * Set alpha for the drop shadow - * - * @member {number} - */ - get: function () { - return this._dropShadowAlpha; - }, - set: function (dropShadowAlpha) { - if (this._dropShadowAlpha !== dropShadowAlpha) { - this._dropShadowAlpha = dropShadowAlpha; - this.styleID++; - } - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(TextStyle.prototype, "dropShadowAngle", { - /** - * Set a angle of the drop shadow - * - * @member {number} - */ - get: function () { - return this._dropShadowAngle; - }, - set: function (dropShadowAngle) { - if (this._dropShadowAngle !== dropShadowAngle) { - this._dropShadowAngle = dropShadowAngle; - this.styleID++; - } - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(TextStyle.prototype, "dropShadowBlur", { - /** - * Set a shadow blur radius - * - * @member {number} - */ - get: function () { - return this._dropShadowBlur; - }, - set: function (dropShadowBlur) { - if (this._dropShadowBlur !== dropShadowBlur) { - this._dropShadowBlur = dropShadowBlur; - this.styleID++; - } - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(TextStyle.prototype, "dropShadowColor", { - /** - * A fill style to be used on the dropshadow e.g 'red', '#00FF00' - * - * @member {string|number} - */ - get: function () { - return this._dropShadowColor; - }, - set: function (dropShadowColor) { - var outputColor = getColor(dropShadowColor); - if (this._dropShadowColor !== outputColor) { - this._dropShadowColor = outputColor; - this.styleID++; - } - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(TextStyle.prototype, "dropShadowDistance", { - /** - * Set a distance of the drop shadow - * - * @member {number} - */ - get: function () { - return this._dropShadowDistance; - }, - set: function (dropShadowDistance) { - if (this._dropShadowDistance !== dropShadowDistance) { - this._dropShadowDistance = dropShadowDistance; - this.styleID++; - } - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(TextStyle.prototype, "fill", { - /** - * A canvas fillstyle that will be used on the text e.g 'red', '#00FF00'. - * Can be an array to create a gradient eg ['#000000','#FFFFFF'] - * {@link https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/fillStyle|MDN} - * - * @member {string|string[]|number|number[]|CanvasGradient|CanvasPattern} - */ - get: function () { - return this._fill; - }, - set: function (fill) { - // TODO: Can't have different types for getter and setter. The getter shouldn't have the number type as - // the setter converts to string. See this thread for more details: - // https://github.com/microsoft/TypeScript/issues/2521 - // TODO: Not sure if getColor works properly with CanvasGradient and/or CanvasPattern, can't pass in - // without casting here. - var outputColor = getColor(fill); - if (this._fill !== outputColor) { - this._fill = outputColor; - this.styleID++; - } - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(TextStyle.prototype, "fillGradientType", { - /** - * If fill is an array of colours to create a gradient, this can change the type/direction of the gradient. - * See {@link PIXI.TEXT_GRADIENT} - * - * @member {number} - */ - get: function () { - return this._fillGradientType; - }, - set: function (fillGradientType) { - if (this._fillGradientType !== fillGradientType) { - this._fillGradientType = fillGradientType; - this.styleID++; - } - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(TextStyle.prototype, "fillGradientStops", { - /** - * If fill is an array of colours to create a gradient, this array can set the stop points - * (numbers between 0 and 1) for the color, overriding the default behaviour of evenly spacing them. - * - * @member {number[]} - */ - get: function () { - return this._fillGradientStops; - }, - set: function (fillGradientStops) { - if (!areArraysEqual(this._fillGradientStops, fillGradientStops)) { - this._fillGradientStops = fillGradientStops; - this.styleID++; - } - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(TextStyle.prototype, "fontFamily", { - /** - * The font family - * - * @member {string|string[]} - */ - get: function () { - return this._fontFamily; - }, - set: function (fontFamily) { - if (this.fontFamily !== fontFamily) { - this._fontFamily = fontFamily; - this.styleID++; - } - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(TextStyle.prototype, "fontSize", { - /** - * The font size - * (as a number it converts to px, but as a string, equivalents are '26px','20pt','160%' or '1.6em') - * - * @member {number|string} - */ - get: function () { - return this._fontSize; - }, - set: function (fontSize) { - if (this._fontSize !== fontSize) { - this._fontSize = fontSize; - this.styleID++; - } - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(TextStyle.prototype, "fontStyle", { - /** - * The font style - * ('normal', 'italic' or 'oblique') - * - * @member {string} - */ - get: function () { - return this._fontStyle; - }, - set: function (fontStyle) { - if (this._fontStyle !== fontStyle) { - this._fontStyle = fontStyle; - this.styleID++; - } - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(TextStyle.prototype, "fontVariant", { - /** - * The font variant - * ('normal' or 'small-caps') - * - * @member {string} - */ - get: function () { - return this._fontVariant; - }, - set: function (fontVariant) { - if (this._fontVariant !== fontVariant) { - this._fontVariant = fontVariant; - this.styleID++; - } - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(TextStyle.prototype, "fontWeight", { - /** - * The font weight - * ('normal', 'bold', 'bolder', 'lighter' and '100', '200', '300', '400', '500', '600', '700', 800' or '900') - * - * @member {string} - */ - get: function () { - return this._fontWeight; - }, - set: function (fontWeight) { - if (this._fontWeight !== fontWeight) { - this._fontWeight = fontWeight; - this.styleID++; - } - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(TextStyle.prototype, "letterSpacing", { - /** - * The amount of spacing between letters, default is 0 - * - * @member {number} - */ - get: function () { - return this._letterSpacing; - }, - set: function (letterSpacing) { - if (this._letterSpacing !== letterSpacing) { - this._letterSpacing = letterSpacing; - this.styleID++; - } - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(TextStyle.prototype, "lineHeight", { - /** - * The line height, a number that represents the vertical space that a letter uses - * - * @member {number} - */ - get: function () { - return this._lineHeight; - }, - set: function (lineHeight) { - if (this._lineHeight !== lineHeight) { - this._lineHeight = lineHeight; - this.styleID++; - } - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(TextStyle.prototype, "leading", { - /** - * The space between lines - * - * @member {number} - */ - get: function () { - return this._leading; - }, - set: function (leading) { - if (this._leading !== leading) { - this._leading = leading; - this.styleID++; - } - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(TextStyle.prototype, "lineJoin", { - /** - * The lineJoin property sets the type of corner created, it can resolve spiked text issues. - * Default is 'miter' (creates a sharp corner). - * - * @member {string} - */ - get: function () { - return this._lineJoin; - }, - set: function (lineJoin) { - if (this._lineJoin !== lineJoin) { - this._lineJoin = lineJoin; - this.styleID++; - } - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(TextStyle.prototype, "miterLimit", { - /** - * The miter limit to use when using the 'miter' lineJoin mode - * This can reduce or increase the spikiness of rendered text. - * - * @member {number} - */ - get: function () { - return this._miterLimit; - }, - set: function (miterLimit) { - if (this._miterLimit !== miterLimit) { - this._miterLimit = miterLimit; - this.styleID++; - } - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(TextStyle.prototype, "padding", { - /** - * Occasionally some fonts are cropped. Adding some padding will prevent this from happening - * by adding padding to all sides of the text. - * - * @member {number} - */ - get: function () { - return this._padding; - }, - set: function (padding) { - if (this._padding !== padding) { - this._padding = padding; - this.styleID++; - } - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(TextStyle.prototype, "stroke", { - /** - * A canvas fillstyle that will be used on the text stroke - * e.g 'blue', '#FCFF00' - * - * @member {string|number} - */ - get: function () { - return this._stroke; - }, - set: function (stroke) { - // TODO: Can't have different types for getter and setter. The getter shouldn't have the number type as - // the setter converts to string. See this thread for more details: - // https://github.com/microsoft/TypeScript/issues/2521 - var outputColor = getColor(stroke); - if (this._stroke !== outputColor) { - this._stroke = outputColor; - this.styleID++; - } - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(TextStyle.prototype, "strokeThickness", { - /** - * A number that represents the thickness of the stroke. - * Default is 0 (no stroke) - * - * @member {number} - */ - get: function () { - return this._strokeThickness; - }, - set: function (strokeThickness) { - if (this._strokeThickness !== strokeThickness) { - this._strokeThickness = strokeThickness; - this.styleID++; - } - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(TextStyle.prototype, "textBaseline", { - /** - * The baseline of the text that is rendered. - * - * @member {string} - */ - get: function () { - return this._textBaseline; - }, - set: function (textBaseline) { - if (this._textBaseline !== textBaseline) { - this._textBaseline = textBaseline; - this.styleID++; - } - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(TextStyle.prototype, "trim", { - /** - * Trim transparent borders - * - * @member {boolean} - */ - get: function () { - return this._trim; - }, - set: function (trim) { - if (this._trim !== trim) { - this._trim = trim; - this.styleID++; - } - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(TextStyle.prototype, "whiteSpace", { - /** - * How newlines and spaces should be handled. - * Default is 'pre' (preserve, preserve). - * - * value | New lines | Spaces - * --- | --- | --- - * 'normal' | Collapse | Collapse - * 'pre' | Preserve | Preserve - * 'pre-line' | Preserve | Collapse - * - * @member {string} - */ - get: function () { - return this._whiteSpace; - }, - set: function (whiteSpace) { - if (this._whiteSpace !== whiteSpace) { - this._whiteSpace = whiteSpace; - this.styleID++; - } - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(TextStyle.prototype, "wordWrap", { - /** - * Indicates if word wrap should be used - * - * @member {boolean} - */ - get: function () { - return this._wordWrap; - }, - set: function (wordWrap) { - if (this._wordWrap !== wordWrap) { - this._wordWrap = wordWrap; - this.styleID++; - } - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(TextStyle.prototype, "wordWrapWidth", { - /** - * The width at which text will wrap, it needs wordWrap to be set to true - * - * @member {number} - */ - get: function () { - return this._wordWrapWidth; - }, - set: function (wordWrapWidth) { - if (this._wordWrapWidth !== wordWrapWidth) { - this._wordWrapWidth = wordWrapWidth; - this.styleID++; - } - }, - enumerable: false, - configurable: true - }); - /** - * Generates a font style string to use for `TextMetrics.measureFont()`. - * - * @return {string} Font style string, for passing to `TextMetrics.measureFont()` - */ - TextStyle.prototype.toFontString = function () { - // build canvas api font setting from individual components. Convert a numeric this.fontSize to px - var fontSizeString = (typeof this.fontSize === 'number') ? this.fontSize + "px" : this.fontSize; - // Clean-up fontFamily property by quoting each font name - // this will support font names with spaces - var fontFamilies = this.fontFamily; - if (!Array.isArray(this.fontFamily)) { - fontFamilies = this.fontFamily.split(','); - } - for (var i = fontFamilies.length - 1; i >= 0; i--) { - // Trim any extra white-space - var fontFamily = fontFamilies[i].trim(); - // Check if font already contains strings - if (!(/([\"\'])[^\'\"]+\1/).test(fontFamily) && genericFontFamilies.indexOf(fontFamily) < 0) { - fontFamily = "\"" + fontFamily + "\""; - } - fontFamilies[i] = fontFamily; - } - return this.fontStyle + " " + this.fontVariant + " " + this.fontWeight + " " + fontSizeString + " " + fontFamilies.join(','); - }; - return TextStyle; - }()); - /** - * Utility function to convert hexadecimal colors to strings, and simply return the color if it's a string. - * @private - * @param {string|number} color - * @return {string} The color as a string. - */ - function getSingleColor(color) { - if (typeof color === 'number') { - return hex2string(color); - } - else if (typeof color === 'string') { - if (color.indexOf('0x') === 0) { - color = color.replace('0x', '#'); - } - } - return color; - } - function getColor(color) { - if (!Array.isArray(color)) { - return getSingleColor(color); - } - else { - for (var i = 0; i < color.length; ++i) { - color[i] = getSingleColor(color[i]); - } - return color; - } - } - /** - * Utility function to convert hexadecimal colors to strings, and simply return the color if it's a string. - * This version can also convert array of colors - * @private - * @param {Array} array1 - First array to compare - * @param {Array} array2 - Second array to compare - * @return {boolean} Do the arrays contain the same values in the same order - */ - function areArraysEqual(array1, array2) { - if (!Array.isArray(array1) || !Array.isArray(array2)) { - return false; - } - if (array1.length !== array2.length) { - return false; - } - for (var i = 0; i < array1.length; ++i) { - if (array1[i] !== array2[i]) { - return false; - } - } - return true; - } - /** - * Utility function to ensure that object properties are copied by value, and not by reference - * @private - * @param {Object} target - Target object to copy properties into - * @param {Object} source - Source object for the properties to copy - * @param {string} propertyObj - Object containing properties names we want to loop over - */ - function deepCopyProperties(target, source, propertyObj) { - for (var prop in propertyObj) { - if (Array.isArray(source[prop])) { - target[prop] = source[prop].slice(); - } - else { - target[prop] = source[prop]; - } - } - } - - /** - * The TextMetrics object represents the measurement of a block of text with a specified style. - * - * ```js - * let style = new PIXI.TextStyle({fontFamily : 'Arial', fontSize: 24, fill : 0xff1010, align : 'center'}) - * let textMetrics = PIXI.TextMetrics.measureText('Your text', style) - * ``` - * - * @class - * @memberof PIXI - */ - var TextMetrics = /** @class */ (function () { - /** - * @param {string} text - the text that was measured - * @param {PIXI.TextStyle} style - the style that was measured - * @param {number} width - the measured width of the text - * @param {number} height - the measured height of the text - * @param {string[]} lines - an array of the lines of text broken by new lines and wrapping if specified in style - * @param {number[]} lineWidths - an array of the line widths for each line matched to `lines` - * @param {number} lineHeight - the measured line height for this style - * @param {number} maxLineWidth - the maximum line width for all measured lines - * @param {Object} fontProperties - the font properties object from TextMetrics.measureFont - */ - function TextMetrics(text, style, width, height, lines, lineWidths, lineHeight, maxLineWidth, fontProperties) { - /** - * The text that was measured - * - * @member {string} - */ - this.text = text; - /** - * The style that was measured - * - * @member {PIXI.TextStyle} - */ - this.style = style; - /** - * The measured width of the text - * - * @member {number} - */ - this.width = width; - /** - * The measured height of the text - * - * @member {number} - */ - this.height = height; - /** - * An array of lines of the text broken by new lines and wrapping is specified in style - * - * @member {string[]} - */ - this.lines = lines; - /** - * An array of the line widths for each line matched to `lines` - * - * @member {number[]} - */ - this.lineWidths = lineWidths; - /** - * The measured line height for this style - * - * @member {number} - */ - this.lineHeight = lineHeight; - /** - * The maximum line width for all measured lines - * - * @member {number} - */ - this.maxLineWidth = maxLineWidth; - /** - * The font properties object from TextMetrics.measureFont - * - * @member {PIXI.IFontMetrics} - */ - this.fontProperties = fontProperties; - } - /** - * Measures the supplied string of text and returns a Rectangle. - * - * @param {string} text - the text to measure. - * @param {PIXI.TextStyle} style - the text style to use for measuring - * @param {boolean} [wordWrap] - optional override for if word-wrap should be applied to the text. - * @param {HTMLCanvasElement} [canvas] - optional specification of the canvas to use for measuring. - * @return {PIXI.TextMetrics} measured width and height of the text. - */ - TextMetrics.measureText = function (text, style, wordWrap, canvas) { - if (canvas === void 0) { canvas = TextMetrics._canvas; } - wordWrap = (wordWrap === undefined || wordWrap === null) ? style.wordWrap : wordWrap; - var font = style.toFontString(); - var fontProperties = TextMetrics.measureFont(font); - // fallback in case UA disallow canvas data extraction - // (toDataURI, getImageData functions) - if (fontProperties.fontSize === 0) { - fontProperties.fontSize = style.fontSize; - fontProperties.ascent = style.fontSize; - } - var context = canvas.getContext('2d'); - context.font = font; - var outputText = wordWrap ? TextMetrics.wordWrap(text, style, canvas) : text; - var lines = outputText.split(/(?:\r\n|\r|\n)/); - var lineWidths = new Array(lines.length); - var maxLineWidth = 0; - for (var i = 0; i < lines.length; i++) { - var lineWidth = context.measureText(lines[i]).width + ((lines[i].length - 1) * style.letterSpacing); - lineWidths[i] = lineWidth; - maxLineWidth = Math.max(maxLineWidth, lineWidth); - } - var width = maxLineWidth + style.strokeThickness; - if (style.dropShadow) { - width += style.dropShadowDistance; - } - var lineHeight = style.lineHeight || fontProperties.fontSize + style.strokeThickness; - var height = Math.max(lineHeight, fontProperties.fontSize + style.strokeThickness) - + ((lines.length - 1) * (lineHeight + style.leading)); - if (style.dropShadow) { - height += style.dropShadowDistance; - } - return new TextMetrics(text, style, width, height, lines, lineWidths, lineHeight + style.leading, maxLineWidth, fontProperties); - }; - /** - * Applies newlines to a string to have it optimally fit into the horizontal - * bounds set by the Text object's wordWrapWidth property. - * - * @private - * @param {string} text - String to apply word wrapping to - * @param {PIXI.TextStyle} style - the style to use when wrapping - * @param {HTMLCanvasElement} [canvas] - optional specification of the canvas to use for measuring. - * @return {string} New string with new lines applied where required - */ - TextMetrics.wordWrap = function (text, style, canvas) { - if (canvas === void 0) { canvas = TextMetrics._canvas; } - var context = canvas.getContext('2d'); - var width = 0; - var line = ''; - var lines = ''; - var cache = {}; - var letterSpacing = style.letterSpacing, whiteSpace = style.whiteSpace; - // How to handle whitespaces - var collapseSpaces = TextMetrics.collapseSpaces(whiteSpace); - var collapseNewlines = TextMetrics.collapseNewlines(whiteSpace); - // whether or not spaces may be added to the beginning of lines - var canPrependSpaces = !collapseSpaces; - // There is letterSpacing after every char except the last one - // t_h_i_s_' '_i_s_' '_a_n_' '_e_x_a_m_p_l_e_' '_! - // so for convenience the above needs to be compared to width + 1 extra letterSpace - // t_h_i_s_' '_i_s_' '_a_n_' '_e_x_a_m_p_l_e_' '_!_ - // ________________________________________________ - // And then the final space is simply no appended to each line - var wordWrapWidth = style.wordWrapWidth + letterSpacing; - // break text into words, spaces and newline chars - var tokens = TextMetrics.tokenize(text); - for (var i = 0; i < tokens.length; i++) { - // get the word, space or newlineChar - var token = tokens[i]; - // if word is a new line - if (TextMetrics.isNewline(token)) { - // keep the new line - if (!collapseNewlines) { - lines += TextMetrics.addLine(line); - canPrependSpaces = !collapseSpaces; - line = ''; - width = 0; - continue; - } - // if we should collapse new lines - // we simply convert it into a space - token = ' '; - } - // if we should collapse repeated whitespaces - if (collapseSpaces) { - // check both this and the last tokens for spaces - var currIsBreakingSpace = TextMetrics.isBreakingSpace(token); - var lastIsBreakingSpace = TextMetrics.isBreakingSpace(line[line.length - 1]); - if (currIsBreakingSpace && lastIsBreakingSpace) { - continue; - } - } - // get word width from cache if possible - var tokenWidth = TextMetrics.getFromCache(token, letterSpacing, cache, context); - // word is longer than desired bounds - if (tokenWidth > wordWrapWidth) { - // if we are not already at the beginning of a line - if (line !== '') { - // start newlines for overflow words - lines += TextMetrics.addLine(line); - line = ''; - width = 0; - } - // break large word over multiple lines - if (TextMetrics.canBreakWords(token, style.breakWords)) { - // break word into characters - var characters = TextMetrics.wordWrapSplit(token); - // loop the characters - for (var j = 0; j < characters.length; j++) { - var char = characters[j]; - var k = 1; - // we are not at the end of the token - while (characters[j + k]) { - var nextChar = characters[j + k]; - var lastChar = char[char.length - 1]; - // should not split chars - if (!TextMetrics.canBreakChars(lastChar, nextChar, token, j, style.breakWords)) { - // combine chars & move forward one - char += nextChar; - } - else { - break; - } - k++; - } - j += char.length - 1; - var characterWidth = TextMetrics.getFromCache(char, letterSpacing, cache, context); - if (characterWidth + width > wordWrapWidth) { - lines += TextMetrics.addLine(line); - canPrependSpaces = false; - line = ''; - width = 0; - } - line += char; - width += characterWidth; - } - } - // run word out of the bounds - else { - // if there are words in this line already - // finish that line and start a new one - if (line.length > 0) { - lines += TextMetrics.addLine(line); - line = ''; - width = 0; - } - var isLastToken = i === tokens.length - 1; - // give it its own line if it's not the end - lines += TextMetrics.addLine(token, !isLastToken); - canPrependSpaces = false; - line = ''; - width = 0; - } - } - // word could fit - else { - // word won't fit because of existing words - // start a new line - if (tokenWidth + width > wordWrapWidth) { - // if its a space we don't want it - canPrependSpaces = false; - // add a new line - lines += TextMetrics.addLine(line); - // start a new line - line = ''; - width = 0; - } - // don't add spaces to the beginning of lines - if (line.length > 0 || !TextMetrics.isBreakingSpace(token) || canPrependSpaces) { - // add the word to the current line - line += token; - // update width counter - width += tokenWidth; - } - } - } - lines += TextMetrics.addLine(line, false); - return lines; - }; - /** - * Convienience function for logging each line added during the wordWrap - * method - * - * @private - * @param {string} line - The line of text to add - * @param {boolean} newLine - Add new line character to end - * @return {string} A formatted line - */ - TextMetrics.addLine = function (line, newLine) { - if (newLine === void 0) { newLine = true; } - line = TextMetrics.trimRight(line); - line = (newLine) ? line + "\n" : line; - return line; - }; - /** - * Gets & sets the widths of calculated characters in a cache object - * - * @private - * @param {string} key - The key - * @param {number} letterSpacing - The letter spacing - * @param {object} cache - The cache - * @param {CanvasRenderingContext2D} context - The canvas context - * @return {number} The from cache. - */ - TextMetrics.getFromCache = function (key, letterSpacing, cache, context) { - var width = cache[key]; - if (width === undefined) { - var spacing = ((key.length) * letterSpacing); - width = context.measureText(key).width + spacing; - cache[key] = width; - } - return width; - }; - /** - * Determines whether we should collapse breaking spaces - * - * @private - * @param {string} whiteSpace - The TextStyle property whiteSpace - * @return {boolean} should collapse - */ - TextMetrics.collapseSpaces = function (whiteSpace) { - return (whiteSpace === 'normal' || whiteSpace === 'pre-line'); - }; - /** - * Determines whether we should collapse newLine chars - * - * @private - * @param {string} whiteSpace - The white space - * @return {boolean} should collapse - */ - TextMetrics.collapseNewlines = function (whiteSpace) { - return (whiteSpace === 'normal'); - }; - /** - * trims breaking whitespaces from string - * - * @private - * @param {string} text - The text - * @return {string} trimmed string - */ - TextMetrics.trimRight = function (text) { - if (typeof text !== 'string') { - return ''; - } - for (var i = text.length - 1; i >= 0; i--) { - var char = text[i]; - if (!TextMetrics.isBreakingSpace(char)) { - break; - } - text = text.slice(0, -1); - } - return text; - }; - /** - * Determines if char is a newline. - * - * @private - * @param {string} char - The character - * @return {boolean} True if newline, False otherwise. - */ - TextMetrics.isNewline = function (char) { - if (typeof char !== 'string') { - return false; - } - return (TextMetrics._newlines.indexOf(char.charCodeAt(0)) >= 0); - }; - /** - * Determines if char is a breaking whitespace. - * - * @private - * @param {string} char - The character - * @return {boolean} True if whitespace, False otherwise. - */ - TextMetrics.isBreakingSpace = function (char) { - if (typeof char !== 'string') { - return false; - } - return (TextMetrics._breakingSpaces.indexOf(char.charCodeAt(0)) >= 0); - }; - /** - * Splits a string into words, breaking-spaces and newLine characters - * - * @private - * @param {string} text - The text - * @return {string[]} A tokenized array - */ - TextMetrics.tokenize = function (text) { - var tokens = []; - var token = ''; - if (typeof text !== 'string') { - return tokens; - } - for (var i = 0; i < text.length; i++) { - var char = text[i]; - if (TextMetrics.isBreakingSpace(char) || TextMetrics.isNewline(char)) { - if (token !== '') { - tokens.push(token); - token = ''; - } - tokens.push(char); - continue; - } - token += char; - } - if (token !== '') { - tokens.push(token); - } - return tokens; - }; - /** - * Overridable helper method used internally by TextMetrics, exposed to allow customizing the class's behavior. - * - * It allows one to customise which words should break - * Examples are if the token is CJK or numbers. - * It must return a boolean. - * - * @param {string} token - The token - * @param {boolean} breakWords - The style attr break words - * @return {boolean} whether to break word or not - */ - TextMetrics.canBreakWords = function (_token, breakWords) { - return breakWords; - }; - /** - * Overridable helper method used internally by TextMetrics, exposed to allow customizing the class's behavior. - * - * It allows one to determine whether a pair of characters - * should be broken by newlines - * For example certain characters in CJK langs or numbers. - * It must return a boolean. - * - * @param {string} char - The character - * @param {string} nextChar - The next character - * @param {string} token - The token/word the characters are from - * @param {number} index - The index in the token of the char - * @param {boolean} breakWords - The style attr break words - * @return {boolean} whether to break word or not - */ - TextMetrics.canBreakChars = function (_char, _nextChar, _token, _index, _breakWords) { - return true; - }; - /** - * Overridable helper method used internally by TextMetrics, exposed to allow customizing the class's behavior. - * - * It is called when a token (usually a word) has to be split into separate pieces - * in order to determine the point to break a word. - * It must return an array of characters. - * - * @example - * // Correctly splits emojis, eg "🤪🤪" will result in two element array, each with one emoji. - * TextMetrics.wordWrapSplit = (token) => [...token]; - * - * @param {string} token - The token to split - * @return {string[]} The characters of the token - */ - TextMetrics.wordWrapSplit = function (token) { - return token.split(''); - }; - /** - * Calculates the ascent, descent and fontSize of a given font-style - * - * @static - * @param {string} font - String representing the style of the font - * @return {PIXI.IFontMetrics} Font properties object - */ - TextMetrics.measureFont = function (font) { - // as this method is used for preparing assets, don't recalculate things if we don't need to - if (TextMetrics._fonts[font]) { - return TextMetrics._fonts[font]; - } - var properties = { - ascent: 0, - descent: 0, - fontSize: 0, - }; - var canvas = TextMetrics._canvas; - var context = TextMetrics._context; - context.font = font; - var metricsString = TextMetrics.METRICS_STRING + TextMetrics.BASELINE_SYMBOL; - var width = Math.ceil(context.measureText(metricsString).width); - var baseline = Math.ceil(context.measureText(TextMetrics.BASELINE_SYMBOL).width); - var height = 2 * baseline; - baseline = baseline * TextMetrics.BASELINE_MULTIPLIER | 0; - canvas.width = width; - canvas.height = height; - context.fillStyle = '#f00'; - context.fillRect(0, 0, width, height); - context.font = font; - context.textBaseline = 'alphabetic'; - context.fillStyle = '#000'; - context.fillText(metricsString, 0, baseline); - var imagedata = context.getImageData(0, 0, width, height).data; - var pixels = imagedata.length; - var line = width * 4; - var i = 0; - var idx = 0; - var stop = false; - // ascent. scan from top to bottom until we find a non red pixel - for (i = 0; i < baseline; ++i) { - for (var j = 0; j < line; j += 4) { - if (imagedata[idx + j] !== 255) { - stop = true; - break; - } - } - if (!stop) { - idx += line; - } - else { - break; - } - } - properties.ascent = baseline - i; - idx = pixels - line; - stop = false; - // descent. scan from bottom to top until we find a non red pixel - for (i = height; i > baseline; --i) { - for (var j = 0; j < line; j += 4) { - if (imagedata[idx + j] !== 255) { - stop = true; - break; - } - } - if (!stop) { - idx -= line; - } - else { - break; - } - } - properties.descent = i - baseline; - properties.fontSize = properties.ascent + properties.descent; - TextMetrics._fonts[font] = properties; - return properties; - }; - /** - * Clear font metrics in metrics cache. - * - * @static - * @param {string} [font] - font name. If font name not set then clear cache for all fonts. - */ - TextMetrics.clearMetrics = function (font) { - if (font === void 0) { font = ''; } - if (font) { - delete TextMetrics._fonts[font]; - } - else { - TextMetrics._fonts = {}; - } - }; - return TextMetrics; - }()); - /** - * Internal return object for {@link PIXI.TextMetrics.measureFont `TextMetrics.measureFont`}. - * - * @typedef {object} FontMetrics - * @property {number} ascent - The ascent distance - * @property {number} descent - The descent distance - * @property {number} fontSize - Font size from ascent to descent - * @memberof PIXI.TextMetrics - * @private - */ - var canvas = (function () { - try { - // OffscreenCanvas2D measureText can be up to 40% faster. - var c = new OffscreenCanvas(0, 0); - var context = c.getContext('2d'); - if (context && context.measureText) { - return c; - } - return document.createElement('canvas'); - } - catch (ex) { - return document.createElement('canvas'); - } - })(); - canvas.width = canvas.height = 10; - /** - * Cached canvas element for measuring text - * - * @memberof PIXI.TextMetrics - * @type {HTMLCanvasElement} - * @private - */ - TextMetrics._canvas = canvas; - /** - * Cache for context to use. - * - * @memberof PIXI.TextMetrics - * @type {CanvasRenderingContext2D} - * @private - */ - TextMetrics._context = canvas.getContext('2d'); - /** - * Cache of {@see PIXI.TextMetrics.FontMetrics} objects. - * - * @memberof PIXI.TextMetrics - * @type {Object} - * @private - */ - TextMetrics._fonts = {}; - /** - * String used for calculate font metrics. - * These characters are all tall to help calculate the height required for text. - * - * @static - * @memberof PIXI.TextMetrics - * @name METRICS_STRING - * @type {string} - * @default |ÉqÅ - */ - TextMetrics.METRICS_STRING = '|ÉqÅ'; - /** - * Baseline symbol for calculate font metrics. - * - * @static - * @memberof PIXI.TextMetrics - * @name BASELINE_SYMBOL - * @type {string} - * @default M - */ - TextMetrics.BASELINE_SYMBOL = 'M'; - /** - * Baseline multiplier for calculate font metrics. - * - * @static - * @memberof PIXI.TextMetrics - * @name BASELINE_MULTIPLIER - * @type {number} - * @default 1.4 - */ - TextMetrics.BASELINE_MULTIPLIER = 1.4; - /** - * Cache of new line chars. - * - * @memberof PIXI.TextMetrics - * @type {number[]} - * @private - */ - TextMetrics._newlines = [ - 0x000A, - 0x000D ]; - /** - * Cache of breaking spaces. - * - * @memberof PIXI.TextMetrics - * @type {number[]} - * @private - */ - TextMetrics._breakingSpaces = [ - 0x0009, - 0x0020, - 0x2000, - 0x2001, - 0x2002, - 0x2003, - 0x2004, - 0x2005, - 0x2006, - 0x2008, - 0x2009, - 0x200A, - 0x205F, - 0x3000 ]; - /** - * A number, or a string containing a number. - * - * @memberof PIXI - * @typedef IFontMetrics - * @property {number} ascent - Font ascent - * @property {number} descent - Font descent - * @property {number} fontSize - Font size - */ - - var defaultDestroyOptions = { - texture: true, - children: false, - baseTexture: true, - }; - /** - * A Text Object will create a line or multiple lines of text. - * - * The text is created using the [Canvas API](https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API). - * - * The primary advantage of this class over BitmapText is that you have great control over the style of the next, - * which you can change at runtime. - * - * The primary disadvantages is that each piece of text has it's own texture, which can use more memory. - * When text changes, this texture has to be re-generated and re-uploaded to the GPU, taking up time. - * - * To split a line you can use '\n' in your text string, or, on the `style` object, - * change its `wordWrap` property to true and and give the `wordWrapWidth` property a value. - * - * A Text can be created directly from a string and a style object, - * which can be generated [here](https://pixijs.io/pixi-text-style). - * - * ```js - * let text = new PIXI.Text('This is a PixiJS text',{fontFamily : 'Arial', fontSize: 24, fill : 0xff1010, align : 'center'}); - * ``` - * - * @class - * @extends PIXI.Sprite - * @memberof PIXI - */ - var Text = /** @class */ (function (_super) { - __extends$7(Text, _super); - /** - * @param {string} text - The string that you would like the text to display - * @param {object|PIXI.TextStyle} [style] - The style parameters - * @param {HTMLCanvasElement} [canvas] - The canvas element for drawing text - */ - function Text(text, style, canvas) { - var _this = this; - var ownCanvas = false; - if (!canvas) { - canvas = document.createElement('canvas'); - ownCanvas = true; - } - canvas.width = 3; - canvas.height = 3; - var texture = Texture.from(canvas); - texture.orig = new Rectangle(); - texture.trim = new Rectangle(); - _this = _super.call(this, texture) || this; - /** - * Keep track if this Text object created it's own canvas - * element (`true`) or uses the constructor argument (`false`). - * Used to workaround a GC issues with Safari < 13 when - * destroying Text. See `destroy` for more info. - * - * @member {boolean} - * @private - */ - _this._ownCanvas = ownCanvas; - /** - * The canvas element that everything is drawn to - * - * @member {HTMLCanvasElement} - */ - _this.canvas = canvas; - /** - * The canvas 2d context that everything is drawn with - * @member {CanvasRenderingContext2D} - */ - _this.context = _this.canvas.getContext('2d'); - /** - * The resolution / device pixel ratio of the canvas. - * This is set to automatically match the renderer resolution by default, but can be overridden by setting manually. - * @member {number} - * @default 1 - */ - _this._resolution = settings.RESOLUTION; - _this._autoResolution = true; - /** - * Private tracker for the current text. - * - * @member {string} - * @private - */ - _this._text = null; - /** - * Private tracker for the current style. - * - * @member {object} - * @private - */ - _this._style = null; - /** - * Private listener to track style changes. - * - * @member {Function} - * @private - */ - _this._styleListener = null; - /** - * Private tracker for the current font. - * - * @member {string} - * @private - */ - _this._font = ''; - _this.text = text; - _this.style = style; - _this.localStyleID = -1; - return _this; - } - /** - * Renders text to its canvas, and updates its texture. - * By default this is used internally to ensure the texture is correct before rendering, - * but it can be used called externally, for example from this class to 'pre-generate' the texture from a piece of text, - * and then shared across multiple Sprites. - * - * @param {boolean} respectDirty - Whether to abort updating the text if the Text isn't dirty and the function is called. - */ - Text.prototype.updateText = function (respectDirty) { - var style = this._style; - // check if style has changed.. - if (this.localStyleID !== style.styleID) { - this.dirty = true; - this.localStyleID = style.styleID; - } - if (!this.dirty && respectDirty) { - return; - } - this._font = this._style.toFontString(); - var context = this.context; - var measured = TextMetrics.measureText(this._text || ' ', this._style, this._style.wordWrap, this.canvas); - var width = measured.width; - var height = measured.height; - var lines = measured.lines; - var lineHeight = measured.lineHeight; - var lineWidths = measured.lineWidths; - var maxLineWidth = measured.maxLineWidth; - var fontProperties = measured.fontProperties; - this.canvas.width = Math.ceil((Math.max(1, width) + (style.padding * 2)) * this._resolution); - this.canvas.height = Math.ceil((Math.max(1, height) + (style.padding * 2)) * this._resolution); - context.scale(this._resolution, this._resolution); - context.clearRect(0, 0, this.canvas.width, this.canvas.height); - context.font = this._font; - context.lineWidth = style.strokeThickness; - context.textBaseline = style.textBaseline; - context.lineJoin = style.lineJoin; - context.miterLimit = style.miterLimit; - var linePositionX; - var linePositionY; - // require 2 passes if a shadow; the first to draw the drop shadow, the second to draw the text - var passesCount = style.dropShadow ? 2 : 1; - // For v4, we drew text at the colours of the drop shadow underneath the normal text. This gave the correct zIndex, - // but features such as alpha and shadowblur did not look right at all, since we were using actual text as a shadow. - // - // For v5.0.0, we moved over to just use the canvas API for drop shadows, which made them look much nicer and more - // visually please, but now because the stroke is drawn and then the fill, drop shadows would appear on both the fill - // and the stroke; and fill drop shadows would appear over the top of the stroke. - // - // For v5.1.1, the new route is to revert to v4 style of drawing text first to get the drop shadows underneath normal - // text, but instead drawing text in the correct location, we'll draw it off screen (-paddingY), and then adjust the - // drop shadow so only that appears on screen (+paddingY). Now we'll have the correct draw order of the shadow - // beneath the text, whilst also having the proper text shadow styling. - for (var i = 0; i < passesCount; ++i) { - var isShadowPass = style.dropShadow && i === 0; - var dsOffsetText = isShadowPass ? height * 2 : 0; // we only want the drop shadow, so put text way off-screen - var dsOffsetShadow = dsOffsetText * this.resolution; - if (isShadowPass) { - // On Safari, text with gradient and drop shadows together do not position correctly - // if the scale of the canvas is not 1: https://bugs.webkit.org/show_bug.cgi?id=197689 - // Therefore we'll set the styles to be a plain black whilst generating this drop shadow - context.fillStyle = 'black'; - context.strokeStyle = 'black'; - var dropShadowColor = style.dropShadowColor; - var rgb = hex2rgb(typeof dropShadowColor === 'number' ? dropShadowColor : string2hex(dropShadowColor)); - context.shadowColor = "rgba(" + rgb[0] * 255 + "," + rgb[1] * 255 + "," + rgb[2] * 255 + "," + style.dropShadowAlpha + ")"; - context.shadowBlur = style.dropShadowBlur; - context.shadowOffsetX = Math.cos(style.dropShadowAngle) * style.dropShadowDistance; - context.shadowOffsetY = (Math.sin(style.dropShadowAngle) * style.dropShadowDistance) + dsOffsetShadow; - } - else { - // set canvas text styles - context.fillStyle = this._generateFillStyle(style, lines, measured); - // TODO: Can't have different types for getter and setter. The getter shouldn't have the number type as - // the setter converts to string. See this thread for more details: - // https://github.com/microsoft/TypeScript/issues/2521 - context.strokeStyle = style.stroke; - context.shadowColor = '0'; - context.shadowBlur = 0; - context.shadowOffsetX = 0; - context.shadowOffsetY = 0; - } - // draw lines line by line - for (var i_1 = 0; i_1 < lines.length; i_1++) { - linePositionX = style.strokeThickness / 2; - linePositionY = ((style.strokeThickness / 2) + (i_1 * lineHeight)) + fontProperties.ascent; - if (style.align === 'right') { - linePositionX += maxLineWidth - lineWidths[i_1]; - } - else if (style.align === 'center') { - linePositionX += (maxLineWidth - lineWidths[i_1]) / 2; - } - if (style.stroke && style.strokeThickness) { - this.drawLetterSpacing(lines[i_1], linePositionX + style.padding, linePositionY + style.padding - dsOffsetText, true); - } - if (style.fill) { - this.drawLetterSpacing(lines[i_1], linePositionX + style.padding, linePositionY + style.padding - dsOffsetText); - } - } - } - this.updateTexture(); - }; - /** - * Render the text with letter-spacing. - * @param {string} text - The text to draw - * @param {number} x - Horizontal position to draw the text - * @param {number} y - Vertical position to draw the text - * @param {boolean} [isStroke=false] - Is this drawing for the outside stroke of the - * text? If not, it's for the inside fill - * @private - */ - Text.prototype.drawLetterSpacing = function (text, x, y, isStroke) { - if (isStroke === void 0) { isStroke = false; } - var style = this._style; - // letterSpacing of 0 means normal - var letterSpacing = style.letterSpacing; - if (letterSpacing === 0) { - if (isStroke) { - this.context.strokeText(text, x, y); - } - else { - this.context.fillText(text, x, y); - } - return; - } - var currentPosition = x; - // Using Array.from correctly splits characters whilst keeping emoji together. - // This is not supported on IE as it requires ES6, so regular text splitting occurs. - // This also doesn't account for emoji that are multiple emoji put together to make something else. - // Handling all of this would require a big library itself. - // https://medium.com/@giltayar/iterating-over-emoji-characters-the-es6-way-f06e4589516 - // https://github.com/orling/grapheme-splitter - var stringArray = Array.from ? Array.from(text) : text.split(''); - var previousWidth = this.context.measureText(text).width; - var currentWidth = 0; - for (var i = 0; i < stringArray.length; ++i) { - var currentChar = stringArray[i]; - if (isStroke) { - this.context.strokeText(currentChar, currentPosition, y); - } - else { - this.context.fillText(currentChar, currentPosition, y); - } - currentWidth = this.context.measureText(text.substring(i + 1)).width; - currentPosition += previousWidth - currentWidth + letterSpacing; - previousWidth = currentWidth; - } - }; - /** - * Updates texture size based on canvas size - * - * @private - */ - Text.prototype.updateTexture = function () { - var canvas = this.canvas; - if (this._style.trim) { - var trimmed = trimCanvas(canvas); - if (trimmed.data) { - canvas.width = trimmed.width; - canvas.height = trimmed.height; - this.context.putImageData(trimmed.data, 0, 0); - } - } - var texture = this._texture; - var style = this._style; - var padding = style.trim ? 0 : style.padding; - var baseTexture = texture.baseTexture; - texture.trim.width = texture._frame.width = Math.ceil(canvas.width / this._resolution); - texture.trim.height = texture._frame.height = Math.ceil(canvas.height / this._resolution); - texture.trim.x = -padding; - texture.trim.y = -padding; - texture.orig.width = texture._frame.width - (padding * 2); - texture.orig.height = texture._frame.height - (padding * 2); - // call sprite onTextureUpdate to update scale if _width or _height were set - this._onTextureUpdate(); - baseTexture.setRealSize(canvas.width, canvas.height, this._resolution); - // Recursively updates transform of all objects from the root to this one - this._recursivePostUpdateTransform(); - this.dirty = false; - }; - /** - * Renders the object using the WebGL renderer - * - * @protected - * @param {PIXI.Renderer} renderer - The renderer - */ - Text.prototype._render = function (renderer) { - if (this._autoResolution && this._resolution !== renderer.resolution) { - this._resolution = renderer.resolution; - this.dirty = true; - } - this.updateText(true); - _super.prototype._render.call(this, renderer); - }; - /** - * Gets the local bounds of the text object. - * - * @param {PIXI.Rectangle} rect - The output rectangle. - * @return {PIXI.Rectangle} The bounds. - */ - Text.prototype.getLocalBounds = function (rect) { - this.updateText(true); - return _super.prototype.getLocalBounds.call(this, rect); - }; - /** - * calculates the bounds of the Text as a rectangle. The bounds calculation takes the worldTransform into account. - * @protected - */ - Text.prototype._calculateBounds = function () { - this.updateText(true); - this.calculateVertices(); - // if we have already done this on THIS frame. - this._bounds.addQuad(this.vertexData); - }; - /** - * Generates the fill style. Can automatically generate a gradient based on the fill style being an array - * - * @private - * @param {object} style - The style. - * @param {string[]} lines - The lines of text. - * @return {string|number|CanvasGradient} The fill style - */ - Text.prototype._generateFillStyle = function (style, lines, metrics) { - // TODO: Can't have different types for getter and setter. The getter shouldn't have the number type as - // the setter converts to string. See this thread for more details: - // https://github.com/microsoft/TypeScript/issues/2521 - var fillStyle = style.fill; - if (!Array.isArray(fillStyle)) { - return fillStyle; - } - else if (fillStyle.length === 1) { - return fillStyle[0]; - } - // the gradient will be evenly spaced out according to how large the array is. - // ['#FF0000', '#00FF00', '#0000FF'] would created stops at 0.25, 0.5 and 0.75 - var gradient; - // a dropshadow will enlarge the canvas and result in the gradient being - // generated with the incorrect dimensions - var dropShadowCorrection = (style.dropShadow) ? style.dropShadowDistance : 0; - // should also take padding into account, padding can offset the gradient - var padding = style.padding || 0; - var width = Math.ceil(this.canvas.width / this._resolution) - dropShadowCorrection - (padding * 2); - var height = Math.ceil(this.canvas.height / this._resolution) - dropShadowCorrection - (padding * 2); - // make a copy of the style settings, so we can manipulate them later - var fill = fillStyle.slice(); - var fillGradientStops = style.fillGradientStops.slice(); - // wanting to evenly distribute the fills. So an array of 4 colours should give fills of 0.25, 0.5 and 0.75 - if (!fillGradientStops.length) { - var lengthPlus1 = fill.length + 1; - for (var i = 1; i < lengthPlus1; ++i) { - fillGradientStops.push(i / lengthPlus1); - } - } - // stop the bleeding of the last gradient on the line above to the top gradient of the this line - // by hard defining the first gradient colour at point 0, and last gradient colour at point 1 - fill.unshift(fillStyle[0]); - fillGradientStops.unshift(0); - fill.push(fillStyle[fillStyle.length - 1]); - fillGradientStops.push(1); - if (style.fillGradientType === exports.TEXT_GRADIENT.LINEAR_VERTICAL) { - // start the gradient at the top center of the canvas, and end at the bottom middle of the canvas - gradient = this.context.createLinearGradient(width / 2, padding, width / 2, height + padding); - // we need to repeat the gradient so that each individual line of text has the same vertical gradient effect - // ['#FF0000', '#00FF00', '#0000FF'] over 2 lines would create stops at 0.125, 0.25, 0.375, 0.625, 0.75, 0.875 - // There's potential for floating point precision issues at the seams between gradient repeats. - // The loop below generates the stops in order, so track the last generated one to prevent - // floating point precision from making us go the teeniest bit backwards, resulting in - // the first and last colors getting swapped. - var lastIterationStop = 0; - // Actual height of the text itself, not counting spacing for lineHeight/leading/dropShadow etc - var textHeight = metrics.fontProperties.fontSize + style.strokeThickness; - // textHeight, but as a 0-1 size in global gradient stop space - var gradStopLineHeight = textHeight / height; - for (var i = 0; i < lines.length; i++) { - var thisLineTop = metrics.lineHeight * i; - for (var j = 0; j < fill.length; j++) { - // 0-1 stop point for the current line, multiplied to global space afterwards - var lineStop = 0; - if (typeof fillGradientStops[j] === 'number') { - lineStop = fillGradientStops[j]; - } - else { - lineStop = j / fill.length; - } - var globalStop = (thisLineTop / height) + (lineStop * gradStopLineHeight); - // Prevent color stop generation going backwards from floating point imprecision - var clampedStop = Math.max(lastIterationStop, globalStop); - clampedStop = Math.min(clampedStop, 1); // Cap at 1 as well for safety's sake to avoid a possible throw. - gradient.addColorStop(clampedStop, fill[j]); - lastIterationStop = clampedStop; - } - } - } - else { - // start the gradient at the center left of the canvas, and end at the center right of the canvas - gradient = this.context.createLinearGradient(padding, height / 2, width + padding, height / 2); - // can just evenly space out the gradients in this case, as multiple lines makes no difference - // to an even left to right gradient - var totalIterations = fill.length + 1; - var currentIteration = 1; - for (var i = 0; i < fill.length; i++) { - var stop = void 0; - if (typeof fillGradientStops[i] === 'number') { - stop = fillGradientStops[i]; - } - else { - stop = currentIteration / totalIterations; - } - gradient.addColorStop(stop, fill[i]); - currentIteration++; - } - } - return gradient; - }; - /** - * Destroys this text object. - * Note* Unlike a Sprite, a Text object will automatically destroy its baseTexture and texture as - * the majority of the time the texture will not be shared with any other Sprites. - * - * @param {object|boolean} [options] - Options parameter. A boolean will act as if all options - * have been set to that value - * @param {boolean} [options.children=false] - if set to true, all the children will have their - * destroy method called as well. 'options' will be passed on to those calls. - * @param {boolean} [options.texture=true] - Should it destroy the current texture of the sprite as well - * @param {boolean} [options.baseTexture=true] - Should it destroy the base texture of the sprite as well - */ - Text.prototype.destroy = function (options) { - if (typeof options === 'boolean') { - options = { children: options }; - } - options = Object.assign({}, defaultDestroyOptions, options); - _super.prototype.destroy.call(this, options); - // set canvas width and height to 0 to workaround memory leak in Safari < 13 - // https://stackoverflow.com/questions/52532614/total-canvas-memory-use-exceeds-the-maximum-limit-safari-12 - if (this._ownCanvas) { - this.canvas.height = this.canvas.width = 0; - } - // make sure to reset the the context and canvas.. dont want this hanging around in memory! - this.context = null; - this.canvas = null; - this._style = null; - }; - Object.defineProperty(Text.prototype, "width", { - /** - * The width of the Text, setting this will actually modify the scale to achieve the value set - * - * @member {number} - */ - get: function () { - this.updateText(true); - return Math.abs(this.scale.x) * this._texture.orig.width; - }, - set: function (value) { - this.updateText(true); - var s = sign$1(this.scale.x) || 1; - this.scale.x = s * value / this._texture.orig.width; - this._width = value; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(Text.prototype, "height", { - /** - * The height of the Text, setting this will actually modify the scale to achieve the value set - * - * @member {number} - */ - get: function () { - this.updateText(true); - return Math.abs(this.scale.y) * this._texture.orig.height; - }, - set: function (value) { - this.updateText(true); - var s = sign$1(this.scale.y) || 1; - this.scale.y = s * value / this._texture.orig.height; - this._height = value; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(Text.prototype, "style", { - /** - * Set the style of the text. Set up an event listener to listen for changes on the style - * object and mark the text as dirty. - * - * @member {object|PIXI.TextStyle} - */ - get: function () { - // TODO: Can't have different types for getter and setter. The getter shouldn't have the ITextStyle - // since the setter creates the TextStyle. See this thread for more details: - // https://github.com/microsoft/TypeScript/issues/2521 - return this._style; - }, - set: function (style) { - style = style || {}; - if (style instanceof TextStyle) { - this._style = style; - } - else { - this._style = new TextStyle(style); - } - this.localStyleID = -1; - this.dirty = true; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(Text.prototype, "text", { - /** - * Set the copy for the text object. To split a line you can use '\n'. - * - * @member {string} - */ - get: function () { - return this._text; - }, - set: function (text) { - text = String(text === null || text === undefined ? '' : text); - if (this._text === text) { - return; - } - this._text = text; - this.dirty = true; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(Text.prototype, "resolution", { - /** - * The resolution / device pixel ratio of the canvas. - * This is set to automatically match the renderer resolution by default, but can be overridden by setting manually. - * @member {number} - * @default 1 - */ - get: function () { - return this._resolution; - }, - set: function (value) { - this._autoResolution = false; - if (this._resolution === value) { - return; - } - this._resolution = value; - this.dirty = true; - }, - enumerable: false, - configurable: true - }); - return Text; - }(Sprite)); - - /*! - * @pixi/prepare - v5.3.3 - * Compiled Tue, 04 Aug 2020 16:23:09 UTC - * - * @pixi/prepare is licensed under the MIT License. - * http://www.opensource.org/licenses/mit-license - */ - - /** - * Default number of uploads per frame using prepare plugin. - * - * @static - * @memberof PIXI.settings - * @name UPLOADS_PER_FRAME - * @type {number} - * @default 4 - */ - settings.UPLOADS_PER_FRAME = 4; - - /*! ***************************************************************************** - Copyright (c) Microsoft Corporation. All rights reserved. - Licensed under the Apache License, Version 2.0 (the "License"); you may not use - this file except in compliance with the License. You may obtain a copy of the - License at http://www.apache.org/licenses/LICENSE-2.0 + THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH + REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY + AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, + INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM + LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR + OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR + PERFORMANCE OF THIS SOFTWARE. + ***************************************************************************** */ + /* global Reflect, Promise */ - THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED - WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, - MERCHANTABLITY OR NON-INFRINGEMENT. + var extendStatics$h = function(d, b) { + extendStatics$h = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) { if (b.hasOwnProperty(p)) { d[p] = b[p]; } } }; + return extendStatics$h(d, b); + }; - See the Apache Version 2.0 License for specific language governing permissions - and limitations under the License. - ***************************************************************************** */ - /* global Reflect, Promise */ + function __extends$h(d, b) { + extendStatics$h(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + } + + /** + * Event class that mimics native DOM events. + * @memberof PIXI + */ + var InteractionEvent = /** @class */ (function () { + function InteractionEvent() { + this.stopped = false; + this.stopsPropagatingAt = null; + this.stopPropagationHint = false; + this.target = null; + this.currentTarget = null; + this.type = null; + this.data = null; + } + /** Prevents event from reaching any objects other than the current object. */ + InteractionEvent.prototype.stopPropagation = function () { + this.stopped = true; + this.stopPropagationHint = true; + this.stopsPropagatingAt = this.currentTarget; + }; + /** Resets the event. */ + InteractionEvent.prototype.reset = function () { + this.stopped = false; + this.stopsPropagatingAt = null; + this.stopPropagationHint = false; + this.currentTarget = null; + this.target = null; + }; + return InteractionEvent; + }()); + + /** + * DisplayObjects with the {@link PIXI.interactiveTarget} mixin use this class to track interactions + * @class + * @private + * @memberof PIXI + */ + var InteractionTrackingData = /** @class */ (function () { + /** + * @param {number} pointerId - Unique pointer id of the event + * @private + */ + function InteractionTrackingData(pointerId) { + this._pointerId = pointerId; + this._flags = InteractionTrackingData.FLAGS.NONE; + } + /** + * + * @private + * @param {number} flag - The interaction flag to set + * @param {boolean} yn - Should the flag be set or unset + */ + InteractionTrackingData.prototype._doSet = function (flag, yn) { + if (yn) { + this._flags = this._flags | flag; + } + else { + this._flags = this._flags & (~flag); + } + }; + Object.defineProperty(InteractionTrackingData.prototype, "pointerId", { + /** + * Unique pointer id of the event + * @readonly + * @private + * @member {number} + */ + get: function () { + return this._pointerId; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(InteractionTrackingData.prototype, "flags", { + /** + * State of the tracking data, expressed as bit flags + * @private + * @member {number} + */ + get: function () { + return this._flags; + }, + set: function (flags) { + this._flags = flags; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(InteractionTrackingData.prototype, "none", { + /** + * Is the tracked event inactive (not over or down)? + * @private + * @member {number} + */ + get: function () { + return this._flags === InteractionTrackingData.FLAGS.NONE; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(InteractionTrackingData.prototype, "over", { + /** + * Is the tracked event over the DisplayObject? + * @private + * @member {boolean} + */ + get: function () { + return (this._flags & InteractionTrackingData.FLAGS.OVER) !== 0; + }, + set: function (yn) { + this._doSet(InteractionTrackingData.FLAGS.OVER, yn); + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(InteractionTrackingData.prototype, "rightDown", { + /** + * Did the right mouse button come down in the DisplayObject? + * @private + * @member {boolean} + */ + get: function () { + return (this._flags & InteractionTrackingData.FLAGS.RIGHT_DOWN) !== 0; + }, + set: function (yn) { + this._doSet(InteractionTrackingData.FLAGS.RIGHT_DOWN, yn); + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(InteractionTrackingData.prototype, "leftDown", { + /** + * Did the left mouse button come down in the DisplayObject? + * @private + * @member {boolean} + */ + get: function () { + return (this._flags & InteractionTrackingData.FLAGS.LEFT_DOWN) !== 0; + }, + set: function (yn) { + this._doSet(InteractionTrackingData.FLAGS.LEFT_DOWN, yn); + }, + enumerable: false, + configurable: true + }); + InteractionTrackingData.FLAGS = Object.freeze({ + NONE: 0, + OVER: 1 << 0, + LEFT_DOWN: 1 << 1, + RIGHT_DOWN: 1 << 2, + }); + return InteractionTrackingData; + }()); + + /** + * Strategy how to search through stage tree for interactive objects + * @memberof PIXI + */ + var TreeSearch = /** @class */ (function () { + function TreeSearch() { + this._tempPoint = new Point(); + } + /** + * Recursive implementation for findHit + * @private + * @param interactionEvent - event containing the point that + * is tested for collision + * @param displayObject - the displayObject + * that will be hit test (recursively crawls its children) + * @param func - the function that will be called on each interactive object. The + * interactionEvent, displayObject and hit will be passed to the function + * @param hitTest - this indicates if the objects inside should be hit test against the point + * @param interactive - Whether the displayObject is interactive + * @returns - Returns true if the displayObject hit the point + */ + TreeSearch.prototype.recursiveFindHit = function (interactionEvent, displayObject, func, hitTest, interactive) { + var _a; + if (!displayObject || !displayObject.visible) { + return false; + } + var point = interactionEvent.data.global; + // Took a little while to rework this function correctly! But now it is done and nice and optimized! ^_^ + // + // This function will now loop through all objects and then only hit test the objects it HAS + // to, not all of them. MUCH faster.. + // An object will be hit test if the following is true: + // + // 1: It is interactive. + // 2: It belongs to a parent that is interactive AND one of the parents children have not already been hit. + // + // As another little optimization once an interactive object has been hit we can carry on + // through the scenegraph, but we know that there will be no more hits! So we can avoid extra hit tests + // A final optimization is that an object is not hit test directly if a child has already been hit. + interactive = displayObject.interactive || interactive; + var hit = false; + var interactiveParent = interactive; + // Flag here can set to false if the event is outside the parents hitArea or mask + var hitTestChildren = true; + // If there is a hitArea, no need to test against anything else if the pointer is not within the hitArea + // There is also no longer a need to hitTest children. + if (displayObject.hitArea) { + if (hitTest) { + displayObject.worldTransform.applyInverse(point, this._tempPoint); + if (!displayObject.hitArea.contains(this._tempPoint.x, this._tempPoint.y)) { + hitTest = false; + hitTestChildren = false; + } + else { + hit = true; + } + } + interactiveParent = false; + } + // If there is a mask, no need to hitTest against anything else if the pointer is not within the mask. + // We still want to hitTestChildren, however, to ensure a mouseout can still be generated. + // https://github.com/pixijs/pixi.js/issues/5135 + else if (displayObject._mask) { + if (hitTest) { + var maskObject = (displayObject._mask.isMaskData + ? displayObject._mask.maskObject : displayObject._mask); + if (maskObject && !((_a = maskObject.containsPoint) === null || _a === void 0 ? void 0 : _a.call(maskObject, point))) { + hitTest = false; + } + } + } + // ** FREE TIP **! If an object is not interactive or has no buttons in it + // (such as a game scene!) set interactiveChildren to false for that displayObject. + // This will allow PixiJS to completely ignore and bypass checking the displayObjects children. + if (hitTestChildren && displayObject.interactiveChildren && displayObject.children) { + var children = displayObject.children; + for (var i = children.length - 1; i >= 0; i--) { + var child = children[i]; + // time to get recursive.. if this function will return if something is hit.. + var childHit = this.recursiveFindHit(interactionEvent, child, func, hitTest, interactiveParent); + if (childHit) { + // its a good idea to check if a child has lost its parent. + // this means it has been removed whilst looping so its best + if (!child.parent) { + continue; + } + // we no longer need to hit test any more objects in this container as we we + // now know the parent has been hit + interactiveParent = false; + // If the child is interactive , that means that the object hit was actually + // interactive and not just the child of an interactive object. + // This means we no longer need to hit test anything else. We still need to run + // through all objects, but we don't need to perform any hit tests. + if (childHit) { + if (interactionEvent.target) { + hitTest = false; + } + hit = true; + } + } + } + } + // no point running this if the item is not interactive or does not have an interactive parent. + if (interactive) { + // if we are hit testing (as in we have no hit any objects yet) + // We also don't need to worry about hit testing if once of the displayObjects children + // has already been hit - but only if it was interactive, otherwise we need to keep + // looking for an interactive child, just in case we hit one + if (hitTest && !interactionEvent.target) { + // already tested against hitArea if it is defined + if (!displayObject.hitArea && displayObject.containsPoint) { + if (displayObject.containsPoint(point)) { + hit = true; + } + } + } + if (displayObject.interactive) { + if (hit && !interactionEvent.target) { + interactionEvent.target = displayObject; + } + if (func) { + func(interactionEvent, displayObject, !!hit); + } + } + } + return hit; + }; + /** + * This function is provides a neat way of crawling through the scene graph and running a + * specified function on all interactive objects it finds. It will also take care of hit + * testing the interactive objects and passes the hit across in the function. + * @private + * @param interactionEvent - event containing the point that + * is tested for collision + * @param displayObject - the displayObject + * that will be hit test (recursively crawls its children) + * @param func - the function that will be called on each interactive object. The + * interactionEvent, displayObject and hit will be passed to the function + * @param hitTest - this indicates if the objects inside should be hit test against the point + * @returns - Returns true if the displayObject hit the point + */ + TreeSearch.prototype.findHit = function (interactionEvent, displayObject, func, hitTest) { + this.recursiveFindHit(interactionEvent, displayObject, func, hitTest, false); + }; + return TreeSearch; + }()); + + /** + * Interface for classes that represent a hit area. + * + * It is implemented by the following classes: + * - {@link PIXI.Circle} + * - {@link PIXI.Ellipse} + * - {@link PIXI.Polygon} + * - {@link PIXI.RoundedRectangle} + * @interface IHitArea + * @memberof PIXI + */ + /** + * Checks whether the x and y coordinates given are contained within this area + * @method + * @name contains + * @memberof PIXI.IHitArea# + * @param {number} x - The X coordinate of the point to test + * @param {number} y - The Y coordinate of the point to test + * @returns {boolean} Whether the x/y coordinates are within this area + */ + /** + * Default property values of interactive objects + * Used by {@link PIXI.InteractionManager} to automatically give all DisplayObjects these properties + * @private + * @name interactiveTarget + * @type {object} + * @memberof PIXI + * @example + * function MyObject() {} + * + * Object.assign( + * DisplayObject.prototype, + * PIXI.interactiveTarget + * ); + */ + var interactiveTarget = { + interactive: false, + interactiveChildren: true, + hitArea: null, + /** + * If enabled, the mouse cursor use the pointer behavior when hovered over the displayObject if it is interactive + * Setting this changes the 'cursor' property to `'pointer'`. + * @example + * const sprite = new PIXI.Sprite(texture); + * sprite.interactive = true; + * sprite.buttonMode = true; + * @member {boolean} + * @memberof PIXI.DisplayObject# + */ + get buttonMode() { + return this.cursor === 'pointer'; + }, + set buttonMode(value) { + if (value) { + this.cursor = 'pointer'; + } + else if (this.cursor === 'pointer') { + this.cursor = null; + } + }, + /** + * This defines what cursor mode is used when the mouse cursor + * is hovered over the displayObject. + * @example + * const sprite = new PIXI.Sprite(texture); + * sprite.interactive = true; + * sprite.cursor = 'wait'; + * @see https://developer.mozilla.org/en/docs/Web/CSS/cursor + * @member {string} + * @memberof PIXI.DisplayObject# + */ + cursor: null, + /** + * Internal set of all active pointers, by identifier + * @member {Map} + * @memberof PIXI.DisplayObject# + * @private + */ + get trackedPointers() { + if (this._trackedPointers === undefined) + { this._trackedPointers = {}; } + return this._trackedPointers; + }, + /** + * Map of all tracked pointers, by identifier. Use trackedPointers to access. + * @private + * @type {Map} + */ + _trackedPointers: undefined, + }; + + // Mix interactiveTarget into DisplayObject.prototype + DisplayObject.mixin(interactiveTarget); + var MOUSE_POINTER_ID = 1; + // helpers for hitTest() - only used inside hitTest() + var hitTestEvent = { + target: null, + data: { + global: null, + }, + }; + /** + * The interaction manager deals with mouse, touch and pointer events. + * + * Any DisplayObject can be interactive if its `interactive` property is set to true. + * + * This manager also supports multitouch. + * + * An instance of this class is automatically created by default, and can be found at `renderer.plugins.interaction` + * @memberof PIXI + */ + var InteractionManager = /** @class */ (function (_super) { + __extends$h(InteractionManager, _super); + /** + * @param {PIXI.CanvasRenderer|PIXI.Renderer} renderer - A reference to the current renderer + * @param options - The options for the manager. + * @param {boolean} [options.autoPreventDefault=true] - Should the manager automatically prevent default browser actions. + * @param {number} [options.interactionFrequency=10] - Maximum frequency (ms) at pointer over/out states will be checked. + * @param {number} [options.useSystemTicker=true] - Whether to add {@link tickerUpdate} to {@link PIXI.Ticker.system}. + */ + function InteractionManager(renderer, options) { + var _this = _super.call(this) || this; + options = options || {}; + _this.renderer = renderer; + _this.autoPreventDefault = options.autoPreventDefault !== undefined ? options.autoPreventDefault : true; + _this.interactionFrequency = options.interactionFrequency || 10; + _this.mouse = new InteractionData(); + _this.mouse.identifier = MOUSE_POINTER_ID; + // setting the mouse to start off far off screen will mean that mouse over does + // not get called before we even move the mouse. + _this.mouse.global.set(-999999); + _this.activeInteractionData = {}; + _this.activeInteractionData[MOUSE_POINTER_ID] = _this.mouse; + _this.interactionDataPool = []; + _this.eventData = new InteractionEvent(); + _this.interactionDOMElement = null; + _this.moveWhenInside = false; + _this.eventsAdded = false; + _this.tickerAdded = false; + _this.mouseOverRenderer = !('PointerEvent' in globalThis); + _this.supportsTouchEvents = 'ontouchstart' in globalThis; + _this.supportsPointerEvents = !!globalThis.PointerEvent; + // this will make it so that you don't have to call bind all the time + _this.onPointerUp = _this.onPointerUp.bind(_this); + _this.processPointerUp = _this.processPointerUp.bind(_this); + _this.onPointerCancel = _this.onPointerCancel.bind(_this); + _this.processPointerCancel = _this.processPointerCancel.bind(_this); + _this.onPointerDown = _this.onPointerDown.bind(_this); + _this.processPointerDown = _this.processPointerDown.bind(_this); + _this.onPointerMove = _this.onPointerMove.bind(_this); + _this.processPointerMove = _this.processPointerMove.bind(_this); + _this.onPointerOut = _this.onPointerOut.bind(_this); + _this.processPointerOverOut = _this.processPointerOverOut.bind(_this); + _this.onPointerOver = _this.onPointerOver.bind(_this); + _this.cursorStyles = { + default: 'inherit', + pointer: 'pointer', + }; + _this.currentCursorMode = null; + _this.cursor = null; + _this.resolution = 1; + _this.delayedEvents = []; + _this.search = new TreeSearch(); + _this._tempDisplayObject = new TemporaryDisplayObject(); + _this._eventListenerOptions = { capture: true, passive: false }; + /** + * Fired when a pointer device button (usually a mouse left-button) is pressed on the display + * object. + * @event PIXI.InteractionManager#mousedown + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when a pointer device secondary button (usually a mouse right-button) is pressed + * on the display object. + * @event PIXI.InteractionManager#rightdown + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when a pointer device button (usually a mouse left-button) is released over the display + * object. + * @event PIXI.InteractionManager#mouseup + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when a pointer device secondary button (usually a mouse right-button) is released + * over the display object. + * @event PIXI.InteractionManager#rightup + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when a pointer device button (usually a mouse left-button) is pressed and released on + * the display object. + * @event PIXI.InteractionManager#click + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when a pointer device secondary button (usually a mouse right-button) is pressed + * and released on the display object. + * @event PIXI.InteractionManager#rightclick + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when a pointer device button (usually a mouse left-button) is released outside the + * display object that initially registered a + * [mousedown]{@link PIXI.InteractionManager#event:mousedown}. + * @event PIXI.InteractionManager#mouseupoutside + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when a pointer device secondary button (usually a mouse right-button) is released + * outside the display object that initially registered a + * [rightdown]{@link PIXI.InteractionManager#event:rightdown}. + * @event PIXI.InteractionManager#rightupoutside + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when a pointer device (usually a mouse) is moved while over the display object + * @event PIXI.InteractionManager#mousemove + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when a pointer device (usually a mouse) is moved onto the display object + * @event PIXI.InteractionManager#mouseover + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when a pointer device (usually a mouse) is moved off the display object + * @event PIXI.InteractionManager#mouseout + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when a pointer device button is pressed on the display object. + * @event PIXI.InteractionManager#pointerdown + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when a pointer device button is released over the display object. + * Not always fired when some buttons are held down while others are released. In those cases, + * use [mousedown]{@link PIXI.InteractionManager#event:mousedown} and + * [mouseup]{@link PIXI.InteractionManager#event:mouseup} instead. + * @event PIXI.InteractionManager#pointerup + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when the operating system cancels a pointer event + * @event PIXI.InteractionManager#pointercancel + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when a pointer device button is pressed and released on the display object. + * @event PIXI.InteractionManager#pointertap + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when a pointer device button is released outside the display object that initially + * registered a [pointerdown]{@link PIXI.InteractionManager#event:pointerdown}. + * @event PIXI.InteractionManager#pointerupoutside + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when a pointer device is moved while over the display object + * @event PIXI.InteractionManager#pointermove + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when a pointer device is moved onto the display object + * @event PIXI.InteractionManager#pointerover + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when a pointer device is moved off the display object + * @event PIXI.InteractionManager#pointerout + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when a touch point is placed on the display object. + * @event PIXI.InteractionManager#touchstart + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when a touch point is removed from the display object. + * @event PIXI.InteractionManager#touchend + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when the operating system cancels a touch + * @event PIXI.InteractionManager#touchcancel + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when a touch point is placed and removed from the display object. + * @event PIXI.InteractionManager#tap + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when a touch point is removed outside of the display object that initially + * registered a [touchstart]{@link PIXI.InteractionManager#event:touchstart}. + * @event PIXI.InteractionManager#touchendoutside + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when a touch point is moved along the display object. + * @event PIXI.InteractionManager#touchmove + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when a pointer device button (usually a mouse left-button) is pressed on the display. + * object. DisplayObject's `interactive` property must be set to `true` to fire event. + * + * This comes from the @pixi/interaction package. + * @event PIXI.DisplayObject#mousedown + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when a pointer device secondary button (usually a mouse right-button) is pressed + * on the display object. DisplayObject's `interactive` property must be set to `true` to fire event. + * + * This comes from the @pixi/interaction package. + * @event PIXI.DisplayObject#rightdown + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when a pointer device button (usually a mouse left-button) is released over the display + * object. DisplayObject's `interactive` property must be set to `true` to fire event. + * + * This comes from the @pixi/interaction package. + * @event PIXI.DisplayObject#mouseup + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when a pointer device secondary button (usually a mouse right-button) is released + * over the display object. DisplayObject's `interactive` property must be set to `true` to fire event. + * + * This comes from the @pixi/interaction package. + * @event PIXI.DisplayObject#rightup + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when a pointer device button (usually a mouse left-button) is pressed and released on + * the display object. DisplayObject's `interactive` property must be set to `true` to fire event. + * + * This comes from the @pixi/interaction package. + * @event PIXI.DisplayObject#click + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when a pointer device secondary button (usually a mouse right-button) is pressed + * and released on the display object. DisplayObject's `interactive` property must be set to `true` to fire event. + * + * This comes from the @pixi/interaction package. + * @event PIXI.DisplayObject#rightclick + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when a pointer device button (usually a mouse left-button) is released outside the + * display object that initially registered a + * [mousedown]{@link PIXI.DisplayObject#event:mousedown}. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * This comes from the @pixi/interaction package. + * @event PIXI.DisplayObject#mouseupoutside + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when a pointer device secondary button (usually a mouse right-button) is released + * outside the display object that initially registered a + * [rightdown]{@link PIXI.DisplayObject#event:rightdown}. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * This comes from the @pixi/interaction package. + * @event PIXI.DisplayObject#rightupoutside + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when a pointer device (usually a mouse) is moved while over the display object. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * This comes from the @pixi/interaction package. + * @event PIXI.DisplayObject#mousemove + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when a pointer device (usually a mouse) is moved onto the display object. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * This comes from the @pixi/interaction package. + * @event PIXI.DisplayObject#mouseover + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when a pointer device (usually a mouse) is moved off the display object. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * This comes from the @pixi/interaction package. + * @event PIXI.DisplayObject#mouseout + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when a pointer device button is pressed on the display object. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * This comes from the @pixi/interaction package. + * @event PIXI.DisplayObject#pointerdown + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when a pointer device button is released over the display object. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * This comes from the @pixi/interaction package. + * @event PIXI.DisplayObject#pointerup + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when the operating system cancels a pointer event. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * This comes from the @pixi/interaction package. + * @event PIXI.DisplayObject#pointercancel + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when a pointer device button is pressed and released on the display object. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * This comes from the @pixi/interaction package. + * @event PIXI.DisplayObject#pointertap + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when a pointer device button is released outside the display object that initially + * registered a [pointerdown]{@link PIXI.DisplayObject#event:pointerdown}. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * This comes from the @pixi/interaction package. + * @event PIXI.DisplayObject#pointerupoutside + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when a pointer device is moved while over the display object. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * This comes from the @pixi/interaction package. + * @event PIXI.DisplayObject#pointermove + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when a pointer device is moved onto the display object. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * This comes from the @pixi/interaction package. + * @event PIXI.DisplayObject#pointerover + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when a pointer device is moved off the display object. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * This comes from the @pixi/interaction package. + * @event PIXI.DisplayObject#pointerout + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when a touch point is placed on the display object. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * This comes from the @pixi/interaction package. + * @event PIXI.DisplayObject#touchstart + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when a touch point is removed from the display object. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * This comes from the @pixi/interaction package. + * @event PIXI.DisplayObject#touchend + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when the operating system cancels a touch. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * This comes from the @pixi/interaction package. + * @event PIXI.DisplayObject#touchcancel + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when a touch point is placed and removed from the display object. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * This comes from the @pixi/interaction package. + * @event PIXI.DisplayObject#tap + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when a touch point is removed outside of the display object that initially + * registered a [touchstart]{@link PIXI.DisplayObject#event:touchstart}. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * This comes from the @pixi/interaction package. + * @event PIXI.DisplayObject#touchendoutside + * @param {PIXI.InteractionEvent} event - Interaction event + */ + /** + * Fired when a touch point is moved along the display object. + * DisplayObject's `interactive` property must be set to `true` to fire event. + * + * This comes from the @pixi/interaction package. + * @event PIXI.DisplayObject#touchmove + * @param {PIXI.InteractionEvent} event - Interaction event + */ + _this._useSystemTicker = options.useSystemTicker !== undefined ? options.useSystemTicker : true; + _this.setTargetElement(_this.renderer.view, _this.renderer.resolution); + return _this; + } + Object.defineProperty(InteractionManager.prototype, "useSystemTicker", { + /** + * Should the InteractionManager automatically add {@link tickerUpdate} to {@link PIXI.Ticker.system}. + * @default true + */ + get: function () { + return this._useSystemTicker; + }, + set: function (useSystemTicker) { + this._useSystemTicker = useSystemTicker; + if (useSystemTicker) { + this.addTickerListener(); + } + else { + this.removeTickerListener(); + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(InteractionManager.prototype, "lastObjectRendered", { + /** + * Last rendered object or temp object. + * @readonly + * @protected + */ + get: function () { + return this.renderer._lastObjectRendered || this._tempDisplayObject; + }, + enumerable: false, + configurable: true + }); + /** + * Hit tests a point against the display tree, returning the first interactive object that is hit. + * @param globalPoint - A point to hit test with, in global space. + * @param root - The root display object to start from. If omitted, defaults + * to the last rendered root of the associated renderer. + * @returns - The hit display object, if any. + */ + InteractionManager.prototype.hitTest = function (globalPoint, root) { + // clear the target for our hit test + hitTestEvent.target = null; + // assign the global point + hitTestEvent.data.global = globalPoint; + // ensure safety of the root + if (!root) { + root = this.lastObjectRendered; + } + // run the hit test + this.processInteractive(hitTestEvent, root, null, true); + // return our found object - it'll be null if we didn't hit anything + return hitTestEvent.target; + }; + /** + * Sets the DOM element which will receive mouse/touch events. This is useful for when you have + * other DOM elements on top of the renderers Canvas element. With this you'll be bale to delegate + * another DOM element to receive those events. + * @param element - the DOM element which will receive mouse and touch events. + * @param resolution - The resolution / device pixel ratio of the new element (relative to the canvas). + */ + InteractionManager.prototype.setTargetElement = function (element, resolution) { + if (resolution === void 0) { resolution = 1; } + this.removeTickerListener(); + this.removeEvents(); + this.interactionDOMElement = element; + this.resolution = resolution; + this.addEvents(); + this.addTickerListener(); + }; + /** Adds the ticker listener. */ + InteractionManager.prototype.addTickerListener = function () { + if (this.tickerAdded || !this.interactionDOMElement || !this._useSystemTicker) { + return; + } + Ticker.system.add(this.tickerUpdate, this, exports.UPDATE_PRIORITY.INTERACTION); + this.tickerAdded = true; + }; + /** Removes the ticker listener. */ + InteractionManager.prototype.removeTickerListener = function () { + if (!this.tickerAdded) { + return; + } + Ticker.system.remove(this.tickerUpdate, this); + this.tickerAdded = false; + }; + /** Registers all the DOM events. */ + InteractionManager.prototype.addEvents = function () { + if (this.eventsAdded || !this.interactionDOMElement) { + return; + } + var style = this.interactionDOMElement.style; + if (globalThis.navigator.msPointerEnabled) { + style.msContentZooming = 'none'; + style.msTouchAction = 'none'; + } + else if (this.supportsPointerEvents) { + style.touchAction = 'none'; + } + /* + * These events are added first, so that if pointer events are normalized, they are fired + * in the same order as non-normalized events. ie. pointer event 1st, mouse / touch 2nd + */ + if (this.supportsPointerEvents) { + globalThis.document.addEventListener('pointermove', this.onPointerMove, this._eventListenerOptions); + this.interactionDOMElement.addEventListener('pointerdown', this.onPointerDown, this._eventListenerOptions); + // pointerout is fired in addition to pointerup (for touch events) and pointercancel + // we already handle those, so for the purposes of what we do in onPointerOut, we only + // care about the pointerleave event + this.interactionDOMElement.addEventListener('pointerleave', this.onPointerOut, this._eventListenerOptions); + this.interactionDOMElement.addEventListener('pointerover', this.onPointerOver, this._eventListenerOptions); + globalThis.addEventListener('pointercancel', this.onPointerCancel, this._eventListenerOptions); + globalThis.addEventListener('pointerup', this.onPointerUp, this._eventListenerOptions); + } + else { + globalThis.document.addEventListener('mousemove', this.onPointerMove, this._eventListenerOptions); + this.interactionDOMElement.addEventListener('mousedown', this.onPointerDown, this._eventListenerOptions); + this.interactionDOMElement.addEventListener('mouseout', this.onPointerOut, this._eventListenerOptions); + this.interactionDOMElement.addEventListener('mouseover', this.onPointerOver, this._eventListenerOptions); + globalThis.addEventListener('mouseup', this.onPointerUp, this._eventListenerOptions); + } + // always look directly for touch events so that we can provide original data + // In a future version we should change this to being just a fallback and rely solely on + // PointerEvents whenever available + if (this.supportsTouchEvents) { + this.interactionDOMElement.addEventListener('touchstart', this.onPointerDown, this._eventListenerOptions); + this.interactionDOMElement.addEventListener('touchcancel', this.onPointerCancel, this._eventListenerOptions); + this.interactionDOMElement.addEventListener('touchend', this.onPointerUp, this._eventListenerOptions); + this.interactionDOMElement.addEventListener('touchmove', this.onPointerMove, this._eventListenerOptions); + } + this.eventsAdded = true; + }; + /** Removes all the DOM events that were previously registered. */ + InteractionManager.prototype.removeEvents = function () { + if (!this.eventsAdded || !this.interactionDOMElement) { + return; + } + var style = this.interactionDOMElement.style; + if (globalThis.navigator.msPointerEnabled) { + style.msContentZooming = ''; + style.msTouchAction = ''; + } + else if (this.supportsPointerEvents) { + style.touchAction = ''; + } + if (this.supportsPointerEvents) { + globalThis.document.removeEventListener('pointermove', this.onPointerMove, this._eventListenerOptions); + this.interactionDOMElement.removeEventListener('pointerdown', this.onPointerDown, this._eventListenerOptions); + this.interactionDOMElement.removeEventListener('pointerleave', this.onPointerOut, this._eventListenerOptions); + this.interactionDOMElement.removeEventListener('pointerover', this.onPointerOver, this._eventListenerOptions); + globalThis.removeEventListener('pointercancel', this.onPointerCancel, this._eventListenerOptions); + globalThis.removeEventListener('pointerup', this.onPointerUp, this._eventListenerOptions); + } + else { + globalThis.document.removeEventListener('mousemove', this.onPointerMove, this._eventListenerOptions); + this.interactionDOMElement.removeEventListener('mousedown', this.onPointerDown, this._eventListenerOptions); + this.interactionDOMElement.removeEventListener('mouseout', this.onPointerOut, this._eventListenerOptions); + this.interactionDOMElement.removeEventListener('mouseover', this.onPointerOver, this._eventListenerOptions); + globalThis.removeEventListener('mouseup', this.onPointerUp, this._eventListenerOptions); + } + if (this.supportsTouchEvents) { + this.interactionDOMElement.removeEventListener('touchstart', this.onPointerDown, this._eventListenerOptions); + this.interactionDOMElement.removeEventListener('touchcancel', this.onPointerCancel, this._eventListenerOptions); + this.interactionDOMElement.removeEventListener('touchend', this.onPointerUp, this._eventListenerOptions); + this.interactionDOMElement.removeEventListener('touchmove', this.onPointerMove, this._eventListenerOptions); + } + this.interactionDOMElement = null; + this.eventsAdded = false; + }; + /** + * Updates the state of interactive objects if at least {@link interactionFrequency} + * milliseconds have passed since the last invocation. + * + * Invoked by a throttled ticker update from {@link PIXI.Ticker.system}. + * @param deltaTime - time delta since the last call + */ + InteractionManager.prototype.tickerUpdate = function (deltaTime) { + this._deltaTime += deltaTime; + if (this._deltaTime < this.interactionFrequency) { + return; + } + this._deltaTime = 0; + this.update(); + }; + /** Updates the state of interactive objects. */ + InteractionManager.prototype.update = function () { + if (!this.interactionDOMElement) { + return; + } + // if the user move the mouse this check has already been done using the mouse move! + if (this._didMove) { + this._didMove = false; + return; + } + this.cursor = null; + // Resets the flag as set by a stopPropagation call. This flag is usually reset by a user interaction of any kind, + // but there was a scenario of a display object moving under a static mouse cursor. + // In this case, mouseover and mouseevents would not pass the flag test in dispatchEvent function + for (var k in this.activeInteractionData) { + // eslint-disable-next-line no-prototype-builtins + if (this.activeInteractionData.hasOwnProperty(k)) { + var interactionData = this.activeInteractionData[k]; + if (interactionData.originalEvent && interactionData.pointerType !== 'touch') { + var interactionEvent = this.configureInteractionEventForDOMEvent(this.eventData, interactionData.originalEvent, interactionData); + this.processInteractive(interactionEvent, this.lastObjectRendered, this.processPointerOverOut, true); + } + } + } + this.setCursorMode(this.cursor); + }; + /** + * Sets the current cursor mode, handling any callbacks or CSS style changes. + * @param mode - cursor mode, a key from the cursorStyles dictionary + */ + InteractionManager.prototype.setCursorMode = function (mode) { + mode = mode || 'default'; + var applyStyles = true; + // offscreen canvas does not support setting styles, but cursor modes can be functions, + // in order to handle pixi rendered cursors, so we can't bail + if (globalThis.OffscreenCanvas && this.interactionDOMElement instanceof OffscreenCanvas) { + applyStyles = false; + } + // if the mode didn't actually change, bail early + if (this.currentCursorMode === mode) { + return; + } + this.currentCursorMode = mode; + var style = this.cursorStyles[mode]; + // only do things if there is a cursor style for it + if (style) { + switch (typeof style) { + case 'string': + // string styles are handled as cursor CSS + if (applyStyles) { + this.interactionDOMElement.style.cursor = style; + } + break; + case 'function': + // functions are just called, and passed the cursor mode + style(mode); + break; + case 'object': + // if it is an object, assume that it is a dictionary of CSS styles, + // apply it to the interactionDOMElement + if (applyStyles) { + Object.assign(this.interactionDOMElement.style, style); + } + break; + } + } + else if (applyStyles && typeof mode === 'string' && !Object.prototype.hasOwnProperty.call(this.cursorStyles, mode)) { + // if it mode is a string (not a Symbol) and cursorStyles doesn't have any entry + // for the mode, then assume that the dev wants it to be CSS for the cursor. + this.interactionDOMElement.style.cursor = mode; + } + }; + /** + * Dispatches an event on the display object that was interacted with. + * @param displayObject - the display object in question + * @param eventString - the name of the event (e.g, mousedown) + * @param eventData - the event data object + */ + InteractionManager.prototype.dispatchEvent = function (displayObject, eventString, eventData) { + // Even if the event was stopped, at least dispatch any remaining events + // for the same display object. + if (!eventData.stopPropagationHint || displayObject === eventData.stopsPropagatingAt) { + eventData.currentTarget = displayObject; + eventData.type = eventString; + displayObject.emit(eventString, eventData); + if (displayObject[eventString]) { + displayObject[eventString](eventData); + } + } + }; + /** + * Puts a event on a queue to be dispatched later. This is used to guarantee correct + * ordering of over/out events. + * @param displayObject - the display object in question + * @param eventString - the name of the event (e.g, mousedown) + * @param eventData - the event data object + */ + InteractionManager.prototype.delayDispatchEvent = function (displayObject, eventString, eventData) { + this.delayedEvents.push({ displayObject: displayObject, eventString: eventString, eventData: eventData }); + }; + /** + * Maps x and y coords from a DOM object and maps them correctly to the PixiJS view. The + * resulting value is stored in the point. This takes into account the fact that the DOM + * element could be scaled and positioned anywhere on the screen. + * @param point - the point that the result will be stored in + * @param x - the x coord of the position to map + * @param y - the y coord of the position to map + */ + InteractionManager.prototype.mapPositionToPoint = function (point, x, y) { + var rect; + // IE 11 fix + if (!this.interactionDOMElement.parentElement) { + rect = { + x: 0, + y: 0, + width: this.interactionDOMElement.width, + height: this.interactionDOMElement.height, + left: 0, + top: 0 + }; + } + else { + rect = this.interactionDOMElement.getBoundingClientRect(); + } + var resolutionMultiplier = 1.0 / this.resolution; + point.x = ((x - rect.left) * (this.interactionDOMElement.width / rect.width)) * resolutionMultiplier; + point.y = ((y - rect.top) * (this.interactionDOMElement.height / rect.height)) * resolutionMultiplier; + }; + /** + * This function is provides a neat way of crawling through the scene graph and running a + * specified function on all interactive objects it finds. It will also take care of hit + * testing the interactive objects and passes the hit across in the function. + * @protected + * @param interactionEvent - event containing the point that + * is tested for collision + * @param displayObject - the displayObject + * that will be hit test (recursively crawls its children) + * @param func - the function that will be called on each interactive object. The + * interactionEvent, displayObject and hit will be passed to the function + * @param hitTest - indicates whether we want to calculate hits + * or just iterate through all interactive objects + */ + InteractionManager.prototype.processInteractive = function (interactionEvent, displayObject, func, hitTest) { + var hit = this.search.findHit(interactionEvent, displayObject, func, hitTest); + var delayedEvents = this.delayedEvents; + if (!delayedEvents.length) { + return hit; + } + // Reset the propagation hint, because we start deeper in the tree again. + interactionEvent.stopPropagationHint = false; + var delayedLen = delayedEvents.length; + this.delayedEvents = []; + for (var i = 0; i < delayedLen; i++) { + var _a = delayedEvents[i], displayObject_1 = _a.displayObject, eventString = _a.eventString, eventData = _a.eventData; + // When we reach the object we wanted to stop propagating at, + // set the propagation hint. + if (eventData.stopsPropagatingAt === displayObject_1) { + eventData.stopPropagationHint = true; + } + this.dispatchEvent(displayObject_1, eventString, eventData); + } + return hit; + }; + /** + * Is called when the pointer button is pressed down on the renderer element + * @param originalEvent - The DOM event of a pointer button being pressed down + */ + InteractionManager.prototype.onPointerDown = function (originalEvent) { + // if we support touch events, then only use those for touch events, not pointer events + if (this.supportsTouchEvents && originalEvent.pointerType === 'touch') + { return; } + var events = this.normalizeToPointerData(originalEvent); + /* + * No need to prevent default on natural pointer events, as there are no side effects + * Normalized events, however, may have the double mousedown/touchstart issue on the native android browser, + * so still need to be prevented. + */ + // Guaranteed that there will be at least one event in events, and all events must have the same pointer type + if (this.autoPreventDefault && events[0].isNormalized) { + var cancelable = originalEvent.cancelable || !('cancelable' in originalEvent); + if (cancelable) { + originalEvent.preventDefault(); + } + } + var eventLen = events.length; + for (var i = 0; i < eventLen; i++) { + var event = events[i]; + var interactionData = this.getInteractionDataForPointerId(event); + var interactionEvent = this.configureInteractionEventForDOMEvent(this.eventData, event, interactionData); + interactionEvent.data.originalEvent = originalEvent; + this.processInteractive(interactionEvent, this.lastObjectRendered, this.processPointerDown, true); + this.emit('pointerdown', interactionEvent); + if (event.pointerType === 'touch') { + this.emit('touchstart', interactionEvent); + } + // emit a mouse event for "pen" pointers, the way a browser would emit a fallback event + else if (event.pointerType === 'mouse' || event.pointerType === 'pen') { + var isRightButton = event.button === 2; + this.emit(isRightButton ? 'rightdown' : 'mousedown', this.eventData); + } + } + }; + /** + * Processes the result of the pointer down check and dispatches the event if need be + * @param interactionEvent - The interaction event wrapping the DOM event + * @param displayObject - The display object that was tested + * @param hit - the result of the hit test on the display object + */ + InteractionManager.prototype.processPointerDown = function (interactionEvent, displayObject, hit) { + var data = interactionEvent.data; + var id = interactionEvent.data.identifier; + if (hit) { + if (!displayObject.trackedPointers[id]) { + displayObject.trackedPointers[id] = new InteractionTrackingData(id); + } + this.dispatchEvent(displayObject, 'pointerdown', interactionEvent); + if (data.pointerType === 'touch') { + this.dispatchEvent(displayObject, 'touchstart', interactionEvent); + } + else if (data.pointerType === 'mouse' || data.pointerType === 'pen') { + var isRightButton = data.button === 2; + if (isRightButton) { + displayObject.trackedPointers[id].rightDown = true; + } + else { + displayObject.trackedPointers[id].leftDown = true; + } + this.dispatchEvent(displayObject, isRightButton ? 'rightdown' : 'mousedown', interactionEvent); + } + } + }; + /** + * Is called when the pointer button is released on the renderer element + * @param originalEvent - The DOM event of a pointer button being released + * @param cancelled - true if the pointer is cancelled + * @param func - Function passed to {@link processInteractive} + */ + InteractionManager.prototype.onPointerComplete = function (originalEvent, cancelled, func) { + var events = this.normalizeToPointerData(originalEvent); + var eventLen = events.length; + // if the event wasn't targeting our canvas, then consider it to be pointerupoutside + // in all cases (unless it was a pointercancel) + var target = originalEvent.target; + // if in shadow DOM use composedPath to access target + if (originalEvent.composedPath && originalEvent.composedPath().length > 0) { + target = originalEvent.composedPath()[0]; + } + var eventAppend = target !== this.interactionDOMElement ? 'outside' : ''; + for (var i = 0; i < eventLen; i++) { + var event = events[i]; + var interactionData = this.getInteractionDataForPointerId(event); + var interactionEvent = this.configureInteractionEventForDOMEvent(this.eventData, event, interactionData); + interactionEvent.data.originalEvent = originalEvent; + // perform hit testing for events targeting our canvas or cancel events + this.processInteractive(interactionEvent, this.lastObjectRendered, func, cancelled || !eventAppend); + this.emit(cancelled ? 'pointercancel' : "pointerup" + eventAppend, interactionEvent); + if (event.pointerType === 'mouse' || event.pointerType === 'pen') { + var isRightButton = event.button === 2; + this.emit(isRightButton ? "rightup" + eventAppend : "mouseup" + eventAppend, interactionEvent); + } + else if (event.pointerType === 'touch') { + this.emit(cancelled ? 'touchcancel' : "touchend" + eventAppend, interactionEvent); + this.releaseInteractionDataForPointerId(event.pointerId); + } + } + }; + /** + * Is called when the pointer button is cancelled + * @param event - The DOM event of a pointer button being released + */ + InteractionManager.prototype.onPointerCancel = function (event) { + // if we support touch events, then only use those for touch events, not pointer events + if (this.supportsTouchEvents && event.pointerType === 'touch') + { return; } + this.onPointerComplete(event, true, this.processPointerCancel); + }; + /** + * Processes the result of the pointer cancel check and dispatches the event if need be + * @param interactionEvent - The interaction event wrapping the DOM event + * @param displayObject - The display object that was tested + */ + InteractionManager.prototype.processPointerCancel = function (interactionEvent, displayObject) { + var data = interactionEvent.data; + var id = interactionEvent.data.identifier; + if (displayObject.trackedPointers[id] !== undefined) { + delete displayObject.trackedPointers[id]; + this.dispatchEvent(displayObject, 'pointercancel', interactionEvent); + if (data.pointerType === 'touch') { + this.dispatchEvent(displayObject, 'touchcancel', interactionEvent); + } + } + }; + /** + * Is called when the pointer button is released on the renderer element + * @param event - The DOM event of a pointer button being released + */ + InteractionManager.prototype.onPointerUp = function (event) { + // if we support touch events, then only use those for touch events, not pointer events + if (this.supportsTouchEvents && event.pointerType === 'touch') + { return; } + this.onPointerComplete(event, false, this.processPointerUp); + }; + /** + * Processes the result of the pointer up check and dispatches the event if need be + * @param interactionEvent - The interaction event wrapping the DOM event + * @param displayObject - The display object that was tested + * @param hit - the result of the hit test on the display object + */ + InteractionManager.prototype.processPointerUp = function (interactionEvent, displayObject, hit) { + var data = interactionEvent.data; + var id = interactionEvent.data.identifier; + var trackingData = displayObject.trackedPointers[id]; + var isTouch = data.pointerType === 'touch'; + var isMouse = (data.pointerType === 'mouse' || data.pointerType === 'pen'); + // need to track mouse down status in the mouse block so that we can emit + // event in a later block + var isMouseTap = false; + // Mouse only + if (isMouse) { + var isRightButton = data.button === 2; + var flags = InteractionTrackingData.FLAGS; + var test = isRightButton ? flags.RIGHT_DOWN : flags.LEFT_DOWN; + var isDown = trackingData !== undefined && (trackingData.flags & test); + if (hit) { + this.dispatchEvent(displayObject, isRightButton ? 'rightup' : 'mouseup', interactionEvent); + if (isDown) { + this.dispatchEvent(displayObject, isRightButton ? 'rightclick' : 'click', interactionEvent); + // because we can confirm that the mousedown happened on this object, flag for later emit of pointertap + isMouseTap = true; + } + } + else if (isDown) { + this.dispatchEvent(displayObject, isRightButton ? 'rightupoutside' : 'mouseupoutside', interactionEvent); + } + // update the down state of the tracking data + if (trackingData) { + if (isRightButton) { + trackingData.rightDown = false; + } + else { + trackingData.leftDown = false; + } + } + } + // Pointers and Touches, and Mouse + if (hit) { + this.dispatchEvent(displayObject, 'pointerup', interactionEvent); + if (isTouch) + { this.dispatchEvent(displayObject, 'touchend', interactionEvent); } + if (trackingData) { + // emit pointertap if not a mouse, or if the mouse block decided it was a tap + if (!isMouse || isMouseTap) { + this.dispatchEvent(displayObject, 'pointertap', interactionEvent); + } + if (isTouch) { + this.dispatchEvent(displayObject, 'tap', interactionEvent); + // touches are no longer over (if they ever were) when we get the touchend + // so we should ensure that we don't keep pretending that they are + trackingData.over = false; + } + } + } + else if (trackingData) { + this.dispatchEvent(displayObject, 'pointerupoutside', interactionEvent); + if (isTouch) + { this.dispatchEvent(displayObject, 'touchendoutside', interactionEvent); } + } + // Only remove the tracking data if there is no over/down state still associated with it + if (trackingData && trackingData.none) { + delete displayObject.trackedPointers[id]; + } + }; + /** + * Is called when the pointer moves across the renderer element + * @param originalEvent - The DOM event of a pointer moving + */ + InteractionManager.prototype.onPointerMove = function (originalEvent) { + // if we support touch events, then only use those for touch events, not pointer events + if (this.supportsTouchEvents && originalEvent.pointerType === 'touch') + { return; } + var events = this.normalizeToPointerData(originalEvent); + if (events[0].pointerType === 'mouse' || events[0].pointerType === 'pen') { + this._didMove = true; + this.cursor = null; + } + var eventLen = events.length; + for (var i = 0; i < eventLen; i++) { + var event = events[i]; + var interactionData = this.getInteractionDataForPointerId(event); + var interactionEvent = this.configureInteractionEventForDOMEvent(this.eventData, event, interactionData); + interactionEvent.data.originalEvent = originalEvent; + this.processInteractive(interactionEvent, this.lastObjectRendered, this.processPointerMove, true); + this.emit('pointermove', interactionEvent); + if (event.pointerType === 'touch') + { this.emit('touchmove', interactionEvent); } + if (event.pointerType === 'mouse' || event.pointerType === 'pen') + { this.emit('mousemove', interactionEvent); } + } + if (events[0].pointerType === 'mouse') { + this.setCursorMode(this.cursor); + // TODO BUG for parents interactive object (border order issue) + } + }; + /** + * Processes the result of the pointer move check and dispatches the event if need be + * @param interactionEvent - The interaction event wrapping the DOM event + * @param displayObject - The display object that was tested + * @param hit - the result of the hit test on the display object + */ + InteractionManager.prototype.processPointerMove = function (interactionEvent, displayObject, hit) { + var data = interactionEvent.data; + var isTouch = data.pointerType === 'touch'; + var isMouse = (data.pointerType === 'mouse' || data.pointerType === 'pen'); + if (isMouse) { + this.processPointerOverOut(interactionEvent, displayObject, hit); + } + if (!this.moveWhenInside || hit) { + this.dispatchEvent(displayObject, 'pointermove', interactionEvent); + if (isTouch) + { this.dispatchEvent(displayObject, 'touchmove', interactionEvent); } + if (isMouse) + { this.dispatchEvent(displayObject, 'mousemove', interactionEvent); } + } + }; + /** + * Is called when the pointer is moved out of the renderer element + * @private + * @param {PointerEvent} originalEvent - The DOM event of a pointer being moved out + */ + InteractionManager.prototype.onPointerOut = function (originalEvent) { + // if we support touch events, then only use those for touch events, not pointer events + if (this.supportsTouchEvents && originalEvent.pointerType === 'touch') + { return; } + var events = this.normalizeToPointerData(originalEvent); + // Only mouse and pointer can call onPointerOut, so events will always be length 1 + var event = events[0]; + if (event.pointerType === 'mouse') { + this.mouseOverRenderer = false; + this.setCursorMode(null); + } + var interactionData = this.getInteractionDataForPointerId(event); + var interactionEvent = this.configureInteractionEventForDOMEvent(this.eventData, event, interactionData); + interactionEvent.data.originalEvent = event; + this.processInteractive(interactionEvent, this.lastObjectRendered, this.processPointerOverOut, false); + this.emit('pointerout', interactionEvent); + if (event.pointerType === 'mouse' || event.pointerType === 'pen') { + this.emit('mouseout', interactionEvent); + } + else { + // we can get touchleave events after touchend, so we want to make sure we don't + // introduce memory leaks + this.releaseInteractionDataForPointerId(interactionData.identifier); + } + }; + /** + * Processes the result of the pointer over/out check and dispatches the event if need be. + * @param interactionEvent - The interaction event wrapping the DOM event + * @param displayObject - The display object that was tested + * @param hit - the result of the hit test on the display object + */ + InteractionManager.prototype.processPointerOverOut = function (interactionEvent, displayObject, hit) { + var data = interactionEvent.data; + var id = interactionEvent.data.identifier; + var isMouse = (data.pointerType === 'mouse' || data.pointerType === 'pen'); + var trackingData = displayObject.trackedPointers[id]; + // if we just moused over the display object, then we need to track that state + if (hit && !trackingData) { + trackingData = displayObject.trackedPointers[id] = new InteractionTrackingData(id); + } + if (trackingData === undefined) + { return; } + if (hit && this.mouseOverRenderer) { + if (!trackingData.over) { + trackingData.over = true; + this.delayDispatchEvent(displayObject, 'pointerover', interactionEvent); + if (isMouse) { + this.delayDispatchEvent(displayObject, 'mouseover', interactionEvent); + } + } + // only change the cursor if it has not already been changed (by something deeper in the + // display tree) + if (isMouse && this.cursor === null) { + this.cursor = displayObject.cursor; + } + } + else if (trackingData.over) { + trackingData.over = false; + this.dispatchEvent(displayObject, 'pointerout', this.eventData); + if (isMouse) { + this.dispatchEvent(displayObject, 'mouseout', interactionEvent); + } + // if there is no mouse down information for the pointer, then it is safe to delete + if (trackingData.none) { + delete displayObject.trackedPointers[id]; + } + } + }; + /** + * Is called when the pointer is moved into the renderer element. + * @param originalEvent - The DOM event of a pointer button being moved into the renderer view. + */ + InteractionManager.prototype.onPointerOver = function (originalEvent) { + var events = this.normalizeToPointerData(originalEvent); + // Only mouse and pointer can call onPointerOver, so events will always be length 1 + var event = events[0]; + var interactionData = this.getInteractionDataForPointerId(event); + var interactionEvent = this.configureInteractionEventForDOMEvent(this.eventData, event, interactionData); + interactionEvent.data.originalEvent = event; + if (event.pointerType === 'mouse') { + this.mouseOverRenderer = true; + } + this.emit('pointerover', interactionEvent); + if (event.pointerType === 'mouse' || event.pointerType === 'pen') { + this.emit('mouseover', interactionEvent); + } + }; + /** + * Get InteractionData for a given pointerId. Store that data as well. + * @param event - Normalized pointer event, output from normalizeToPointerData. + * @returns - Interaction data for the given pointer identifier. + */ + InteractionManager.prototype.getInteractionDataForPointerId = function (event) { + var pointerId = event.pointerId; + var interactionData; + if (pointerId === MOUSE_POINTER_ID || event.pointerType === 'mouse') { + interactionData = this.mouse; + } + else if (this.activeInteractionData[pointerId]) { + interactionData = this.activeInteractionData[pointerId]; + } + else { + interactionData = this.interactionDataPool.pop() || new InteractionData(); + interactionData.identifier = pointerId; + this.activeInteractionData[pointerId] = interactionData; + } + // copy properties from the event, so that we can make sure that touch/pointer specific + // data is available + interactionData.copyEvent(event); + return interactionData; + }; + /** + * Return unused InteractionData to the pool, for a given pointerId + * @param pointerId - Identifier from a pointer event + */ + InteractionManager.prototype.releaseInteractionDataForPointerId = function (pointerId) { + var interactionData = this.activeInteractionData[pointerId]; + if (interactionData) { + delete this.activeInteractionData[pointerId]; + interactionData.reset(); + this.interactionDataPool.push(interactionData); + } + }; + /** + * Configure an InteractionEvent to wrap a DOM PointerEvent and InteractionData + * @param interactionEvent - The event to be configured + * @param pointerEvent - The DOM event that will be paired with the InteractionEvent + * @param interactionData - The InteractionData that will be paired + * with the InteractionEvent + * @returns - the interaction event that was passed in + */ + InteractionManager.prototype.configureInteractionEventForDOMEvent = function (interactionEvent, pointerEvent, interactionData) { + interactionEvent.data = interactionData; + this.mapPositionToPoint(interactionData.global, pointerEvent.clientX, pointerEvent.clientY); + // Not really sure why this is happening, but it's how a previous version handled things + if (pointerEvent.pointerType === 'touch') { + pointerEvent.globalX = interactionData.global.x; + pointerEvent.globalY = interactionData.global.y; + } + interactionData.originalEvent = pointerEvent; + interactionEvent.reset(); + return interactionEvent; + }; + /** + * Ensures that the original event object contains all data that a regular pointer event would have + * @param {TouchEvent|MouseEvent|PointerEvent} event - The original event data from a touch or mouse event + * @returns - An array containing a single normalized pointer event, in the case of a pointer + * or mouse event, or a multiple normalized pointer events if there are multiple changed touches + */ + InteractionManager.prototype.normalizeToPointerData = function (event) { + var normalizedEvents = []; + if (this.supportsTouchEvents && event instanceof TouchEvent) { + for (var i = 0, li = event.changedTouches.length; i < li; i++) { + var touch = event.changedTouches[i]; + if (typeof touch.button === 'undefined') + { touch.button = event.touches.length ? 1 : 0; } + if (typeof touch.buttons === 'undefined') + { touch.buttons = event.touches.length ? 1 : 0; } + if (typeof touch.isPrimary === 'undefined') { + touch.isPrimary = event.touches.length === 1 && event.type === 'touchstart'; + } + if (typeof touch.width === 'undefined') + { touch.width = touch.radiusX || 1; } + if (typeof touch.height === 'undefined') + { touch.height = touch.radiusY || 1; } + if (typeof touch.tiltX === 'undefined') + { touch.tiltX = 0; } + if (typeof touch.tiltY === 'undefined') + { touch.tiltY = 0; } + if (typeof touch.pointerType === 'undefined') + { touch.pointerType = 'touch'; } + if (typeof touch.pointerId === 'undefined') + { touch.pointerId = touch.identifier || 0; } + if (typeof touch.pressure === 'undefined') + { touch.pressure = touch.force || 0.5; } + if (typeof touch.twist === 'undefined') + { touch.twist = 0; } + if (typeof touch.tangentialPressure === 'undefined') + { touch.tangentialPressure = 0; } + // TODO: Remove these, as layerX/Y is not a standard, is deprecated, has uneven + // support, and the fill ins are not quite the same + // offsetX/Y might be okay, but is not the same as clientX/Y when the canvas's top + // left is not 0,0 on the page + if (typeof touch.layerX === 'undefined') + { touch.layerX = touch.offsetX = touch.clientX; } + if (typeof touch.layerY === 'undefined') + { touch.layerY = touch.offsetY = touch.clientY; } + // mark the touch as normalized, just so that we know we did it + touch.isNormalized = true; + normalizedEvents.push(touch); + } + } + // apparently PointerEvent subclasses MouseEvent, so yay + else if (!globalThis.MouseEvent + || (event instanceof MouseEvent && (!this.supportsPointerEvents || !(event instanceof globalThis.PointerEvent)))) { + var tempEvent = event; + if (typeof tempEvent.isPrimary === 'undefined') + { tempEvent.isPrimary = true; } + if (typeof tempEvent.width === 'undefined') + { tempEvent.width = 1; } + if (typeof tempEvent.height === 'undefined') + { tempEvent.height = 1; } + if (typeof tempEvent.tiltX === 'undefined') + { tempEvent.tiltX = 0; } + if (typeof tempEvent.tiltY === 'undefined') + { tempEvent.tiltY = 0; } + if (typeof tempEvent.pointerType === 'undefined') + { tempEvent.pointerType = 'mouse'; } + if (typeof tempEvent.pointerId === 'undefined') + { tempEvent.pointerId = MOUSE_POINTER_ID; } + if (typeof tempEvent.pressure === 'undefined') + { tempEvent.pressure = 0.5; } + if (typeof tempEvent.twist === 'undefined') + { tempEvent.twist = 0; } + if (typeof tempEvent.tangentialPressure === 'undefined') + { tempEvent.tangentialPressure = 0; } + // mark the mouse event as normalized, just so that we know we did it + tempEvent.isNormalized = true; + normalizedEvents.push(tempEvent); + } + else { + normalizedEvents.push(event); + } + return normalizedEvents; + }; + /** Destroys the interaction manager. */ + InteractionManager.prototype.destroy = function () { + this.removeEvents(); + this.removeTickerListener(); + this.removeAllListeners(); + this.renderer = null; + this.mouse = null; + this.eventData = null; + this.interactionDOMElement = null; + this.onPointerDown = null; + this.processPointerDown = null; + this.onPointerUp = null; + this.processPointerUp = null; + this.onPointerCancel = null; + this.processPointerCancel = null; + this.onPointerMove = null; + this.processPointerMove = null; + this.onPointerOut = null; + this.processPointerOverOut = null; + this.onPointerOver = null; + this.search = null; + }; + /** @ignore */ + InteractionManager.extension = { + name: 'interaction', + type: [ + exports.ExtensionType.RendererPlugin, + exports.ExtensionType.CanvasRendererPlugin ], + }; + return InteractionManager; + }(eventemitter3)); + + /*! + * @pixi/extract - v6.5.3 + * Compiled Fri, 09 Sep 2022 13:55:20 UTC + * + * @pixi/extract is licensed under the MIT License. + * http://www.opensource.org/licenses/mit-license + */ + + var TEMP_RECT = new Rectangle(); + var BYTES_PER_PIXEL = 4; + /** + * This class provides renderer-specific plugins for exporting content from a renderer. + * For instance, these plugins can be used for saving an Image, Canvas element or for exporting the raw image data (pixels). + * + * Do not instantiate these plugins directly. It is available from the `renderer.plugins` property. + * See {@link PIXI.CanvasRenderer#plugins} or {@link PIXI.Renderer#plugins}. + * @example + * // Create a new app (will auto-add extract plugin to renderer) + * const app = new PIXI.Application(); + * + * // Draw a red circle + * const graphics = new PIXI.Graphics() + * .beginFill(0xFF0000) + * .drawCircle(0, 0, 50); + * + * // Render the graphics as an HTMLImageElement + * const image = app.renderer.plugins.extract.image(graphics); + * document.body.appendChild(image); + * @memberof PIXI + */ + var Extract = /** @class */ (function () { + /** + * @param renderer - A reference to the current renderer + */ + function Extract(renderer) { + this.renderer = renderer; + } + /** + * Will return a HTML Image of the target + * @param target - A displayObject or renderTexture + * to convert. If left empty will use the main renderer + * @param format - Image format, e.g. "image/jpeg" or "image/webp". + * @param quality - JPEG or Webp compression from 0 to 1. Default is 0.92. + * @returns - HTML Image of the target + */ + Extract.prototype.image = function (target, format, quality) { + var image = new Image(); + image.src = this.base64(target, format, quality); + return image; + }; + /** + * Will return a base64 encoded string of this target. It works by calling + * `Extract.getCanvas` and then running toDataURL on that. + * @param target - A displayObject or renderTexture + * to convert. If left empty will use the main renderer + * @param format - Image format, e.g. "image/jpeg" or "image/webp". + * @param quality - JPEG or Webp compression from 0 to 1. Default is 0.92. + * @returns - A base64 encoded string of the texture. + */ + Extract.prototype.base64 = function (target, format, quality) { + return this.canvas(target).toDataURL(format, quality); + }; + /** + * Creates a Canvas element, renders this target to it and then returns it. + * @param target - A displayObject or renderTexture + * to convert. If left empty will use the main renderer + * @param frame - The frame the extraction is restricted to. + * @returns - A Canvas element with the texture rendered on. + */ + Extract.prototype.canvas = function (target, frame) { + var renderer = this.renderer; + var resolution; + var flipY = false; + var renderTexture; + var generated = false; + if (target) { + if (target instanceof RenderTexture) { + renderTexture = target; + } + else { + renderTexture = this.renderer.generateTexture(target); + generated = true; + } + } + if (renderTexture) { + resolution = renderTexture.baseTexture.resolution; + frame = frame !== null && frame !== void 0 ? frame : renderTexture.frame; + flipY = false; + renderer.renderTexture.bind(renderTexture); + } + else { + resolution = renderer.resolution; + if (!frame) { + frame = TEMP_RECT; + frame.width = renderer.width; + frame.height = renderer.height; + } + flipY = true; + renderer.renderTexture.bind(null); + } + var width = Math.round(frame.width * resolution); + var height = Math.round(frame.height * resolution); + var canvasBuffer = new CanvasRenderTarget(width, height, 1); + var webglPixels = new Uint8Array(BYTES_PER_PIXEL * width * height); + // read pixels to the array + var gl = renderer.gl; + gl.readPixels(Math.round(frame.x * resolution), Math.round(frame.y * resolution), width, height, gl.RGBA, gl.UNSIGNED_BYTE, webglPixels); + // add the pixels to the canvas + var canvasData = canvasBuffer.context.getImageData(0, 0, width, height); + Extract.arrayPostDivide(webglPixels, canvasData.data); + canvasBuffer.context.putImageData(canvasData, 0, 0); + // pulling pixels + if (flipY) { + var target_1 = new CanvasRenderTarget(canvasBuffer.width, canvasBuffer.height, 1); + target_1.context.scale(1, -1); + // we can't render to itself because we should be empty before render. + target_1.context.drawImage(canvasBuffer.canvas, 0, -height); + canvasBuffer.destroy(); + canvasBuffer = target_1; + } + if (generated) { + renderTexture.destroy(true); + } + // send the canvas back.. + return canvasBuffer.canvas; + }; + /** + * Will return a one-dimensional array containing the pixel data of the entire texture in RGBA + * order, with integer values between 0 and 255 (included). + * @param target - A displayObject or renderTexture + * to convert. If left empty will use the main renderer + * @param frame - The frame the extraction is restricted to. + * @returns - One-dimensional array containing the pixel data of the entire texture + */ + Extract.prototype.pixels = function (target, frame) { + var renderer = this.renderer; + var resolution; + var renderTexture; + var generated = false; + if (target) { + if (target instanceof RenderTexture) { + renderTexture = target; + } + else { + renderTexture = this.renderer.generateTexture(target); + generated = true; + } + } + if (renderTexture) { + resolution = renderTexture.baseTexture.resolution; + frame = frame !== null && frame !== void 0 ? frame : renderTexture.frame; + renderer.renderTexture.bind(renderTexture); + } + else { + resolution = renderer.resolution; + if (!frame) { + frame = TEMP_RECT; + frame.width = renderer.width; + frame.height = renderer.height; + } + renderer.renderTexture.bind(null); + } + var width = Math.round(frame.width * resolution); + var height = Math.round(frame.height * resolution); + var webglPixels = new Uint8Array(BYTES_PER_PIXEL * width * height); + // read pixels to the array + var gl = renderer.gl; + gl.readPixels(Math.round(frame.x * resolution), Math.round(frame.y * resolution), width, height, gl.RGBA, gl.UNSIGNED_BYTE, webglPixels); + if (generated) { + renderTexture.destroy(true); + } + Extract.arrayPostDivide(webglPixels, webglPixels); + return webglPixels; + }; + /** Destroys the extract. */ + Extract.prototype.destroy = function () { + this.renderer = null; + }; + /** + * Takes premultiplied pixel data and produces regular pixel data + * @private + * @param pixels - array of pixel data + * @param out - output array + */ + Extract.arrayPostDivide = function (pixels, out) { + for (var i = 0; i < pixels.length; i += 4) { + var alpha = out[i + 3] = pixels[i + 3]; + if (alpha !== 0) { + out[i] = Math.round(Math.min(pixels[i] * 255.0 / alpha, 255.0)); + out[i + 1] = Math.round(Math.min(pixels[i + 1] * 255.0 / alpha, 255.0)); + out[i + 2] = Math.round(Math.min(pixels[i + 2] * 255.0 / alpha, 255.0)); + } + else { + out[i] = pixels[i]; + out[i + 1] = pixels[i + 1]; + out[i + 2] = pixels[i + 2]; + } + } + }; + /** @ignore */ + Extract.extension = { + name: 'extract', + type: exports.ExtensionType.RendererPlugin, + }; + return Extract; + }()); + + /*! + * @pixi/loaders - v6.5.3 + * Compiled Fri, 09 Sep 2022 13:55:20 UTC + * + * @pixi/loaders is licensed under the MIT License. + * http://www.opensource.org/licenses/mit-license + */ + + /* jshint -W097 */ + /** + * @memberof PIXI + */ + var SignalBinding = /** @class */ (function () { + /** + * SignalBinding constructor. + * @constructs SignalBinding + * @param {Function} fn - Event handler to be called. + * @param {boolean} [once=false] - Should this listener be removed after dispatch + * @param {object} [thisArg] - The context of the callback function. + * @api private + */ + // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types + function SignalBinding(fn, once, thisArg) { + if (once === void 0) { once = false; } + this._fn = fn; + this._once = once; + this._thisArg = thisArg; + this._next = this._prev = this._owner = null; + } + SignalBinding.prototype.detach = function () { + if (this._owner === null) + { return false; } + this._owner.detach(this); + return true; + }; + return SignalBinding; + }()); + /** + * @param self + * @param node + * @private + */ + function _addSignalBinding(self, node) { + if (!self._head) { + self._head = node; + self._tail = node; + } + else { + self._tail._next = node; + node._prev = self._tail; + self._tail = node; + } + node._owner = self; + return node; + } + /** + * @memberof PIXI + */ + var Signal = /** @class */ (function () { + /** + * MiniSignal constructor. + * @example + * let mySignal = new Signal(); + * let binding = mySignal.add(onSignal); + * mySignal.dispatch('foo', 'bar'); + * mySignal.detach(binding); + */ + function Signal() { + this._head = this._tail = undefined; + } + /** + * Return an array of attached SignalBinding. + * @param {boolean} [exists=false] - We only need to know if there are handlers. + * @returns {PIXI.SignalBinding[] | boolean} Array of attached SignalBinding or Boolean if called with exists = true + * @api public + */ + Signal.prototype.handlers = function (exists) { + if (exists === void 0) { exists = false; } + var node = this._head; + if (exists) + { return !!node; } + var ee = []; + while (node) { + ee.push(node); + node = node._next; + } + return ee; + }; + /** + * Return true if node is a SignalBinding attached to this MiniSignal + * @param {PIXI.SignalBinding} node - Node to check. + * @returns {boolean} True if node is attache to mini-signal + */ + Signal.prototype.has = function (node) { + if (!(node instanceof SignalBinding)) { + throw new Error('MiniSignal#has(): First arg must be a SignalBinding object.'); + } + return node._owner === this; + }; + /** + * Dispaches a signal to all registered listeners. + * @param {...any} args + * @returns {boolean} Indication if we've emitted an event. + */ + Signal.prototype.dispatch = function () { + var arguments$1 = arguments; + + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments$1[_i]; + } + var node = this._head; + if (!node) + { return false; } + while (node) { + if (node._once) + { this.detach(node); } + node._fn.apply(node._thisArg, args); + node = node._next; + } + return true; + }; + /** + * Register a new listener. + * @param {Function} fn - Callback function. + * @param {object} [thisArg] - The context of the callback function. + * @returns {PIXI.SignalBinding} The SignalBinding node that was added. + */ + Signal.prototype.add = function (fn, thisArg) { + if (thisArg === void 0) { thisArg = null; } + if (typeof fn !== 'function') { + throw new Error('MiniSignal#add(): First arg must be a Function.'); + } + return _addSignalBinding(this, new SignalBinding(fn, false, thisArg)); + }; + /** + * Register a new listener that will be executed only once. + * @param {Function} fn - Callback function. + * @param {object} [thisArg] - The context of the callback function. + * @returns {PIXI.SignalBinding} The SignalBinding node that was added. + */ + Signal.prototype.once = function (fn, thisArg) { + if (thisArg === void 0) { thisArg = null; } + if (typeof fn !== 'function') { + throw new Error('MiniSignal#once(): First arg must be a Function.'); + } + return _addSignalBinding(this, new SignalBinding(fn, true, thisArg)); + }; + /** + * Remove binding object. + * @param {PIXI.SignalBinding} node - The binding node that will be removed. + * @returns {Signal} The instance on which this method was called. + @api public */ + Signal.prototype.detach = function (node) { + if (!(node instanceof SignalBinding)) { + throw new Error('MiniSignal#detach(): First arg must be a SignalBinding object.'); + } + if (node._owner !== this) + { return this; } // todo: or error? + if (node._prev) + { node._prev._next = node._next; } + if (node._next) + { node._next._prev = node._prev; } + if (node === this._head) { // first node + this._head = node._next; + if (node._next === null) { + this._tail = null; + } + } + else if (node === this._tail) { // last node + this._tail = node._prev; + this._tail._next = null; + } + node._owner = null; + return this; + }; + /** + * Detach all listeners. + * @returns {Signal} The instance on which this method was called. + */ + Signal.prototype.detachAll = function () { + var node = this._head; + if (!node) + { return this; } + this._head = this._tail = null; + while (node) { + node._owner = null; + node = node._next; + } + return this; + }; + return Signal; + }()); + + /** + * function from npm package `parseUri`, converted to TS to avoid leftpad incident + * @param {string} str + * @param [opts] - options + * @param {boolean} [opts.strictMode] - type of parser + */ + function parseUri(str, opts) { + opts = opts || {}; + var o = { + // eslint-disable-next-line max-len + key: ['source', 'protocol', 'authority', 'userInfo', 'user', 'password', 'host', 'port', 'relative', 'path', 'directory', 'file', 'query', 'anchor'], + q: { + name: 'queryKey', + parser: /(?:^|&)([^&=]*)=?([^&]*)/g + }, + parser: { + // eslint-disable-next-line max-len + strict: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/, + // eslint-disable-next-line max-len + loose: /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/ + } + }; + var m = o.parser[opts.strictMode ? 'strict' : 'loose'].exec(str); + var uri = {}; + var i = 14; + while (i--) + { uri[o.key[i]] = m[i] || ''; } + uri[o.q.name] = {}; + uri[o.key[12]].replace(o.q.parser, function (_t0, t1, t2) { + if (t1) + { uri[o.q.name][t1] = t2; } + }); + return uri; + } + + // tests if CORS is supported in XHR, if not we need to use XDR + var useXdr; + var tempAnchor = null; + // some status constants + var STATUS_NONE = 0; + var STATUS_OK = 200; + var STATUS_EMPTY = 204; + var STATUS_IE_BUG_EMPTY = 1223; + var STATUS_TYPE_OK = 2; + // noop + function _noop$1() { } + /** + * Quick helper to set a value on one of the extension maps. Ensures there is no + * dot at the start of the extension. + * @ignore + * @param map - The map to set on. + * @param extname - The extension (or key) to set. + * @param val - The value to set. + */ + function setExtMap(map, extname, val) { + if (extname && extname.indexOf('.') === 0) { + extname = extname.substring(1); + } + if (!extname) { + return; + } + map[extname] = val; + } + /** + * Quick helper to get string xhr type. + * @ignore + * @param xhr - The request to check. + * @returns The type. + */ + function reqType(xhr) { + return xhr.toString().replace('object ', ''); + } + /** + * Manages the state and loading of a resource and all child resources. + * + * Can be extended in `GlobalMixins.LoaderResource`. + * @memberof PIXI + */ + exports.LoaderResource = /** @class */ (function () { + /** + * @param {string} name - The name of the resource to load. + * @param {string|string[]} url - The url for this resource, for audio/video loads you can pass + * an array of sources. + * @param {object} [options] - The options for the load. + * @param {string|boolean} [options.crossOrigin] - Is this request cross-origin? Default is to + * determine automatically. + * @param {number} [options.timeout=0] - A timeout in milliseconds for the load. If the load takes + * longer than this time it is cancelled and the load is considered a failure. If this value is + * set to `0` then there is no explicit timeout. + * @param {PIXI.LoaderResource.LOAD_TYPE} [options.loadType=LOAD_TYPE.XHR] - How should this resource + * be loaded? + * @param {PIXI.LoaderResource.XHR_RESPONSE_TYPE} [options.xhrType=XHR_RESPONSE_TYPE.DEFAULT] - How + * should the data being loaded be interpreted when using XHR? + * @param {PIXI.LoaderResource.IMetadata} [options.metadata] - Extra configuration for middleware + * and the Resource object. + */ + function LoaderResource(name, url, options) { + /** + * The `dequeue` method that will be used a storage place for the async queue dequeue method + * used privately by the loader. + * @private + * @member {Function} + */ + this._dequeue = _noop$1; + /** + * Used a storage place for the on load binding used privately by the loader. + * @private + * @member {Function} + */ + this._onLoadBinding = null; + /** + * The timer for element loads to check if they timeout. + * @private + */ + this._elementTimer = 0; + /** + * The `complete` function bound to this resource's context. + * @private + * @type {Function} + */ + this._boundComplete = null; + /** + * The `_onError` function bound to this resource's context. + * @private + * @type {Function} + */ + this._boundOnError = null; + /** + * The `_onProgress` function bound to this resource's context. + * @private + * @type {Function} + */ + this._boundOnProgress = null; + /** + * The `_onTimeout` function bound to this resource's context. + * @private + * @type {Function} + */ + this._boundOnTimeout = null; + this._boundXhrOnError = null; + this._boundXhrOnTimeout = null; + this._boundXhrOnAbort = null; + this._boundXhrOnLoad = null; + if (typeof name !== 'string' || typeof url !== 'string') { + throw new Error('Both name and url are required for constructing a resource.'); + } + options = options || {}; + this._flags = 0; + // set data url flag, needs to be set early for some _determineX checks to work. + this._setFlag(LoaderResource.STATUS_FLAGS.DATA_URL, url.indexOf('data:') === 0); + this.name = name; + this.url = url; + this.extension = this._getExtension(); + this.data = null; + this.crossOrigin = options.crossOrigin === true ? 'anonymous' : options.crossOrigin; + this.timeout = options.timeout || 0; + this.loadType = options.loadType || this._determineLoadType(); + // The type used to load the resource via XHR. If unset, determined automatically. + this.xhrType = options.xhrType; + // Extra info for middleware, and controlling specifics about how the resource loads. + // Note that if you pass in a `loadElement`, the Resource class takes ownership of it. + // Meaning it will modify it as it sees fit. + this.metadata = options.metadata || {}; + // The error that occurred while loading (if any). + this.error = null; + // The XHR object that was used to load this resource. This is only set + // when `loadType` is `LoaderResource.LOAD_TYPE.XHR`. + this.xhr = null; + // The child resources this resource owns. + this.children = []; + // The resource type. + this.type = LoaderResource.TYPE.UNKNOWN; + // The progress chunk owned by this resource. + this.progressChunk = 0; + // The `dequeue` method that will be used a storage place for the async queue dequeue method + // used privately by the loader. + this._dequeue = _noop$1; + // Used a storage place for the on load binding used privately by the loader. + this._onLoadBinding = null; + // The timer for element loads to check if they timeout. + this._elementTimer = 0; + this._boundComplete = this.complete.bind(this); + this._boundOnError = this._onError.bind(this); + this._boundOnProgress = this._onProgress.bind(this); + this._boundOnTimeout = this._onTimeout.bind(this); + // xhr callbacks + this._boundXhrOnError = this._xhrOnError.bind(this); + this._boundXhrOnTimeout = this._xhrOnTimeout.bind(this); + this._boundXhrOnAbort = this._xhrOnAbort.bind(this); + this._boundXhrOnLoad = this._xhrOnLoad.bind(this); + // Dispatched when the resource beings to load. + this.onStart = new Signal(); + // Dispatched each time progress of this resource load updates. + // Not all resources types and loader systems can support this event + // so sometimes it may not be available. If the resource + // is being loaded on a modern browser, using XHR, and the remote server + // properly sets Content-Length headers, then this will be available. + this.onProgress = new Signal(); + // Dispatched once this resource has loaded, if there was an error it will + // be in the `error` property. + this.onComplete = new Signal(); + // Dispatched after this resource has had all the *after* middleware run on it. + this.onAfterMiddleware = new Signal(); + } + /** + * Sets the load type to be used for a specific extension. + * @static + * @param {string} extname - The extension to set the type for, e.g. "png" or "fnt" + * @param {PIXI.LoaderResource.LOAD_TYPE} loadType - The load type to set it to. + */ + LoaderResource.setExtensionLoadType = function (extname, loadType) { + setExtMap(LoaderResource._loadTypeMap, extname, loadType); + }; + /** + * Sets the load type to be used for a specific extension. + * @static + * @param {string} extname - The extension to set the type for, e.g. "png" or "fnt" + * @param {PIXI.LoaderResource.XHR_RESPONSE_TYPE} xhrType - The xhr type to set it to. + */ + LoaderResource.setExtensionXhrType = function (extname, xhrType) { + setExtMap(LoaderResource._xhrTypeMap, extname, xhrType); + }; + Object.defineProperty(LoaderResource.prototype, "isDataUrl", { + /** + * When the resource starts to load. + * @memberof PIXI.LoaderResource + * @callback OnStartSignal + * @param {PIXI.Resource} resource - The resource that the event happened on. + */ + /** + * When the resource reports loading progress. + * @memberof PIXI.LoaderResource + * @callback OnProgressSignal + * @param {PIXI.Resource} resource - The resource that the event happened on. + * @param {number} percentage - The progress of the load in the range [0, 1]. + */ + /** + * When the resource finishes loading. + * @memberof PIXI.LoaderResource + * @callback OnCompleteSignal + * @param {PIXI.Resource} resource - The resource that the event happened on. + */ + /** + * @memberof PIXI.LoaderResource + * @typedef {object} IMetadata + * @property {HTMLImageElement|HTMLAudioElement|HTMLVideoElement} [loadElement=null] - The + * element to use for loading, instead of creating one. + * @property {boolean} [skipSource=false] - Skips adding source(s) to the load element. This + * is useful if you want to pass in a `loadElement` that you already added load sources to. + * @property {string|string[]} [mimeType] - The mime type to use for the source element + * of a video/audio elment. If the urls are an array, you can pass this as an array as well + * where each index is the mime type to use for the corresponding url index. + */ + /** + * Stores whether or not this url is a data url. + * @readonly + * @member {boolean} + */ + get: function () { + return this._hasFlag(LoaderResource.STATUS_FLAGS.DATA_URL); + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(LoaderResource.prototype, "isComplete", { + /** + * Describes if this resource has finished loading. Is true when the resource has completely + * loaded. + * @readonly + * @member {boolean} + */ + get: function () { + return this._hasFlag(LoaderResource.STATUS_FLAGS.COMPLETE); + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(LoaderResource.prototype, "isLoading", { + /** + * Describes if this resource is currently loading. Is true when the resource starts loading, + * and is false again when complete. + * @readonly + * @member {boolean} + */ + get: function () { + return this._hasFlag(LoaderResource.STATUS_FLAGS.LOADING); + }, + enumerable: false, + configurable: true + }); + /** Marks the resource as complete. */ + LoaderResource.prototype.complete = function () { + this._clearEvents(); + this._finish(); + }; + /** + * Aborts the loading of this resource, with an optional message. + * @param {string} message - The message to use for the error + */ + LoaderResource.prototype.abort = function (message) { + // abort can be called multiple times, ignore subsequent calls. + if (this.error) { + return; + } + // store error + this.error = new Error(message); + // clear events before calling aborts + this._clearEvents(); + // abort the actual loading + if (this.xhr) { + this.xhr.abort(); + } + else if (this.xdr) { + this.xdr.abort(); + } + else if (this.data) { + // single source + if (this.data.src) { + this.data.src = LoaderResource.EMPTY_GIF; + } + // multi-source + else { + while (this.data.firstChild) { + this.data.removeChild(this.data.firstChild); + } + } + } + // done now. + this._finish(); + }; + /** + * Kicks off loading of this resource. This method is asynchronous. + * @param {PIXI.LoaderResource.OnCompleteSignal} [cb] - Optional callback to call once the resource is loaded. + */ + LoaderResource.prototype.load = function (cb) { + var _this = this; + if (this.isLoading) { + return; + } + if (this.isComplete) { + if (cb) { + setTimeout(function () { return cb(_this); }, 1); + } + return; + } + else if (cb) { + this.onComplete.once(cb); + } + this._setFlag(LoaderResource.STATUS_FLAGS.LOADING, true); + this.onStart.dispatch(this); + // if unset, determine the value + if (this.crossOrigin === false || typeof this.crossOrigin !== 'string') { + this.crossOrigin = this._determineCrossOrigin(this.url); + } + switch (this.loadType) { + case LoaderResource.LOAD_TYPE.IMAGE: + this.type = LoaderResource.TYPE.IMAGE; + this._loadElement('image'); + break; + case LoaderResource.LOAD_TYPE.AUDIO: + this.type = LoaderResource.TYPE.AUDIO; + this._loadSourceElement('audio'); + break; + case LoaderResource.LOAD_TYPE.VIDEO: + this.type = LoaderResource.TYPE.VIDEO; + this._loadSourceElement('video'); + break; + case LoaderResource.LOAD_TYPE.XHR: + /* falls through */ + default: + if (typeof useXdr === 'undefined') { + useXdr = !!(globalThis.XDomainRequest && !('withCredentials' in (new XMLHttpRequest()))); + } + if (useXdr && this.crossOrigin) { + this._loadXdr(); + } + else { + this._loadXhr(); + } + break; + } + }; + /** + * Checks if the flag is set. + * @param flag - The flag to check. + * @returns True if the flag is set. + */ + LoaderResource.prototype._hasFlag = function (flag) { + return (this._flags & flag) !== 0; + }; + /** + * (Un)Sets the flag. + * @param flag - The flag to (un)set. + * @param value - Whether to set or (un)set the flag. + */ + LoaderResource.prototype._setFlag = function (flag, value) { + this._flags = value ? (this._flags | flag) : (this._flags & ~flag); + }; + /** Clears all the events from the underlying loading source. */ + LoaderResource.prototype._clearEvents = function () { + clearTimeout(this._elementTimer); + if (this.data && this.data.removeEventListener) { + this.data.removeEventListener('error', this._boundOnError, false); + this.data.removeEventListener('load', this._boundComplete, false); + this.data.removeEventListener('progress', this._boundOnProgress, false); + this.data.removeEventListener('canplaythrough', this._boundComplete, false); + } + if (this.xhr) { + if (this.xhr.removeEventListener) { + this.xhr.removeEventListener('error', this._boundXhrOnError, false); + this.xhr.removeEventListener('timeout', this._boundXhrOnTimeout, false); + this.xhr.removeEventListener('abort', this._boundXhrOnAbort, false); + this.xhr.removeEventListener('progress', this._boundOnProgress, false); + this.xhr.removeEventListener('load', this._boundXhrOnLoad, false); + } + else { + this.xhr.onerror = null; + this.xhr.ontimeout = null; + this.xhr.onprogress = null; + this.xhr.onload = null; + } + } + }; + /** Finalizes the load. */ + LoaderResource.prototype._finish = function () { + if (this.isComplete) { + throw new Error('Complete called again for an already completed resource.'); + } + this._setFlag(LoaderResource.STATUS_FLAGS.COMPLETE, true); + this._setFlag(LoaderResource.STATUS_FLAGS.LOADING, false); + this.onComplete.dispatch(this); + }; + /** + * Loads this resources using an element that has a single source, + * like an HTMLImageElement. + * @private + * @param type - The type of element to use. + */ + LoaderResource.prototype._loadElement = function (type) { + if (this.metadata.loadElement) { + this.data = this.metadata.loadElement; + } + else if (type === 'image' && typeof globalThis.Image !== 'undefined') { + this.data = new Image(); + } + else { + this.data = document.createElement(type); + } + if (this.crossOrigin) { + this.data.crossOrigin = this.crossOrigin; + } + if (!this.metadata.skipSource) { + this.data.src = this.url; + } + this.data.addEventListener('error', this._boundOnError, false); + this.data.addEventListener('load', this._boundComplete, false); + this.data.addEventListener('progress', this._boundOnProgress, false); + if (this.timeout) { + this._elementTimer = setTimeout(this._boundOnTimeout, this.timeout); + } + }; + /** + * Loads this resources using an element that has multiple sources, + * like an HTMLAudioElement or HTMLVideoElement. + * @param type - The type of element to use. + */ + LoaderResource.prototype._loadSourceElement = function (type) { + if (this.metadata.loadElement) { + this.data = this.metadata.loadElement; + } + else if (type === 'audio' && typeof globalThis.Audio !== 'undefined') { + this.data = new Audio(); + } + else { + this.data = document.createElement(type); + } + if (this.data === null) { + this.abort("Unsupported element: " + type); + return; + } + if (this.crossOrigin) { + this.data.crossOrigin = this.crossOrigin; + } + if (!this.metadata.skipSource) { + // support for CocoonJS Canvas+ runtime, lacks document.createElement('source') + if (navigator.isCocoonJS) { + this.data.src = Array.isArray(this.url) ? this.url[0] : this.url; + } + else if (Array.isArray(this.url)) { + var mimeTypes = this.metadata.mimeType; + for (var i = 0; i < this.url.length; ++i) { + this.data.appendChild(this._createSource(type, this.url[i], Array.isArray(mimeTypes) ? mimeTypes[i] : mimeTypes)); + } + } + else { + var mimeTypes = this.metadata.mimeType; + this.data.appendChild(this._createSource(type, this.url, Array.isArray(mimeTypes) ? mimeTypes[0] : mimeTypes)); + } + } + this.data.addEventListener('error', this._boundOnError, false); + this.data.addEventListener('load', this._boundComplete, false); + this.data.addEventListener('progress', this._boundOnProgress, false); + this.data.addEventListener('canplaythrough', this._boundComplete, false); + this.data.load(); + if (this.timeout) { + this._elementTimer = setTimeout(this._boundOnTimeout, this.timeout); + } + }; + /** Loads this resources using an XMLHttpRequest. */ + LoaderResource.prototype._loadXhr = function () { + // if unset, determine the value + if (typeof this.xhrType !== 'string') { + this.xhrType = this._determineXhrType(); + } + var xhr = this.xhr = new XMLHttpRequest(); + // send credentials when crossOrigin with credentials requested + if (this.crossOrigin === 'use-credentials') { + xhr.withCredentials = true; + } + // set the request type and url + xhr.open('GET', this.url, true); + xhr.timeout = this.timeout; + // load json as text and parse it ourselves. We do this because some browsers + // *cough* safari *cough* can't deal with it. + if (this.xhrType === LoaderResource.XHR_RESPONSE_TYPE.JSON + || this.xhrType === LoaderResource.XHR_RESPONSE_TYPE.DOCUMENT) { + xhr.responseType = LoaderResource.XHR_RESPONSE_TYPE.TEXT; + } + else { + xhr.responseType = this.xhrType; + } + xhr.addEventListener('error', this._boundXhrOnError, false); + xhr.addEventListener('timeout', this._boundXhrOnTimeout, false); + xhr.addEventListener('abort', this._boundXhrOnAbort, false); + xhr.addEventListener('progress', this._boundOnProgress, false); + xhr.addEventListener('load', this._boundXhrOnLoad, false); + xhr.send(); + }; + /** Loads this resources using an XDomainRequest. This is here because we need to support IE9 (gross). */ + LoaderResource.prototype._loadXdr = function () { + // if unset, determine the value + if (typeof this.xhrType !== 'string') { + this.xhrType = this._determineXhrType(); + } + var xdr = this.xhr = new globalThis.XDomainRequest(); // eslint-disable-line no-undef + // XDomainRequest has a few quirks. Occasionally it will abort requests + // A way to avoid this is to make sure ALL callbacks are set even if not used + // More info here: http://stackoverflow.com/questions/15786966/xdomainrequest-aborts-post-on-ie-9 + xdr.timeout = this.timeout || 5000; // XDR needs a timeout value or it breaks in IE9 + xdr.onerror = this._boundXhrOnError; + xdr.ontimeout = this._boundXhrOnTimeout; + xdr.onprogress = this._boundOnProgress; + xdr.onload = this._boundXhrOnLoad; + xdr.open('GET', this.url, true); + // Note: The xdr.send() call is wrapped in a timeout to prevent an + // issue with the interface where some requests are lost if multiple + // XDomainRequests are being sent at the same time. + // Some info here: https://github.com/photonstorm/phaser/issues/1248 + setTimeout(function () { return xdr.send(); }, 1); + }; + /** + * Creates a source used in loading via an element. + * @param type - The element type (video or audio). + * @param url - The source URL to load from. + * @param [mime] - The mime type of the video + * @returns The source element. + */ + LoaderResource.prototype._createSource = function (type, url, mime) { + if (!mime) { + mime = type + "/" + this._getExtension(url); + } + var source = document.createElement('source'); + source.src = url; + source.type = mime; + return source; + }; + /** + * Called if a load errors out. + * @param event - The error event from the element that emits it. + */ + LoaderResource.prototype._onError = function (event) { + this.abort("Failed to load element using: " + event.target.nodeName); + }; + /** + * Called if a load progress event fires for an element or xhr/xdr. + * @param event - Progress event. + */ + LoaderResource.prototype._onProgress = function (event) { + if (event && event.lengthComputable) { + this.onProgress.dispatch(this, event.loaded / event.total); + } + }; + /** Called if a timeout event fires for an element. */ + LoaderResource.prototype._onTimeout = function () { + this.abort("Load timed out."); + }; + /** Called if an error event fires for xhr/xdr. */ + LoaderResource.prototype._xhrOnError = function () { + var xhr = this.xhr; + this.abort(reqType(xhr) + " Request failed. Status: " + xhr.status + ", text: \"" + xhr.statusText + "\""); + }; + /** Called if an error event fires for xhr/xdr. */ + LoaderResource.prototype._xhrOnTimeout = function () { + var xhr = this.xhr; + this.abort(reqType(xhr) + " Request timed out."); + }; + /** Called if an abort event fires for xhr/xdr. */ + LoaderResource.prototype._xhrOnAbort = function () { + var xhr = this.xhr; + this.abort(reqType(xhr) + " Request was aborted by the user."); + }; + /** Called when data successfully loads from an xhr/xdr request. */ + LoaderResource.prototype._xhrOnLoad = function () { + var xhr = this.xhr; + var text = ''; + var status = typeof xhr.status === 'undefined' ? STATUS_OK : xhr.status; // XDR has no `.status`, assume 200. + // responseText is accessible only if responseType is '' or 'text' and on older browsers + if (xhr.responseType === '' || xhr.responseType === 'text' || typeof xhr.responseType === 'undefined') { + text = xhr.responseText; + } + // status can be 0 when using the `file://` protocol so we also check if a response is set. + // If it has a response, we assume 200; otherwise a 0 status code with no contents is an aborted request. + if (status === STATUS_NONE && (text.length > 0 || xhr.responseType === LoaderResource.XHR_RESPONSE_TYPE.BUFFER)) { + status = STATUS_OK; + } + // handle IE9 bug: http://stackoverflow.com/questions/10046972/msie-returns-status-code-of-1223-for-ajax-request + else if (status === STATUS_IE_BUG_EMPTY) { + status = STATUS_EMPTY; + } + var statusType = (status / 100) | 0; + if (statusType === STATUS_TYPE_OK) { + // if text, just return it + if (this.xhrType === LoaderResource.XHR_RESPONSE_TYPE.TEXT) { + this.data = text; + this.type = LoaderResource.TYPE.TEXT; + } + // if json, parse into json object + else if (this.xhrType === LoaderResource.XHR_RESPONSE_TYPE.JSON) { + try { + this.data = JSON.parse(text); + this.type = LoaderResource.TYPE.JSON; + } + catch (e) { + this.abort("Error trying to parse loaded json: " + e); + return; + } + } + // if xml, parse into an xml document or div element + else if (this.xhrType === LoaderResource.XHR_RESPONSE_TYPE.DOCUMENT) { + try { + if (globalThis.DOMParser) { + var domparser = new DOMParser(); + this.data = domparser.parseFromString(text, 'text/xml'); + } + else { + var div = document.createElement('div'); + div.innerHTML = text; + this.data = div; + } + this.type = LoaderResource.TYPE.XML; + } + catch (e$1) { + this.abort("Error trying to parse loaded xml: " + e$1); + return; + } + } + // other types just return the response + else { + this.data = xhr.response || text; + } + } + else { + this.abort("[" + xhr.status + "] " + xhr.statusText + ": " + xhr.responseURL); + return; + } + this.complete(); + }; + /** + * Sets the `crossOrigin` property for this resource based on if the url + * for this resource is cross-origin. If crossOrigin was manually set, this + * function does nothing. + * @private + * @param url - The url to test. + * @param [loc=globalThis.location] - The location object to test against. + * @returns The crossOrigin value to use (or empty string for none). + */ + // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types + LoaderResource.prototype._determineCrossOrigin = function (url, loc) { + // data: and javascript: urls are considered same-origin + if (url.indexOf('data:') === 0) { + return ''; + } + // A sandboxed iframe without the 'allow-same-origin' attribute will have a special + // origin designed not to match globalThis.location.origin, and will always require + // crossOrigin requests regardless of whether the location matches. + if (globalThis.origin !== globalThis.location.origin) { + return 'anonymous'; + } + // default is globalThis.location + loc = loc || globalThis.location; + if (!tempAnchor) { + tempAnchor = document.createElement('a'); + } + // let the browser determine the full href for the url of this resource and then + // parse with the node url lib, we can't use the properties of the anchor element + // because they don't work in IE9 :( + tempAnchor.href = url; + var parsedUrl = parseUri(tempAnchor.href, { strictMode: true }); + var samePort = (!parsedUrl.port && loc.port === '') || (parsedUrl.port === loc.port); + var protocol = parsedUrl.protocol ? parsedUrl.protocol + ":" : ''; + // if cross origin + if (parsedUrl.host !== loc.hostname || !samePort || protocol !== loc.protocol) { + return 'anonymous'; + } + return ''; + }; + /** + * Determines the responseType of an XHR request based on the extension of the + * resource being loaded. + * @private + * @returns {PIXI.LoaderResource.XHR_RESPONSE_TYPE} The responseType to use. + */ + LoaderResource.prototype._determineXhrType = function () { + return LoaderResource._xhrTypeMap[this.extension] || LoaderResource.XHR_RESPONSE_TYPE.TEXT; + }; + /** + * Determines the loadType of a resource based on the extension of the + * resource being loaded. + * @private + * @returns {PIXI.LoaderResource.LOAD_TYPE} The loadType to use. + */ + LoaderResource.prototype._determineLoadType = function () { + return LoaderResource._loadTypeMap[this.extension] || LoaderResource.LOAD_TYPE.XHR; + }; + /** + * Extracts the extension (sans '.') of the file being loaded by the resource. + * @param [url] - url to parse, `this.url` by default. + * @returns The extension. + */ + LoaderResource.prototype._getExtension = function (url) { + if (url === void 0) { url = this.url; } + var ext = ''; + if (this.isDataUrl) { + var slashIndex = url.indexOf('/'); + ext = url.substring(slashIndex + 1, url.indexOf(';', slashIndex)); + } + else { + var queryStart = url.indexOf('?'); + var hashStart = url.indexOf('#'); + var index = Math.min(queryStart > -1 ? queryStart : url.length, hashStart > -1 ? hashStart : url.length); + url = url.substring(0, index); + ext = url.substring(url.lastIndexOf('.') + 1); + } + return ext.toLowerCase(); + }; + /** + * Determines the mime type of an XHR request based on the responseType of + * resource being loaded. + * @param type - The type to get a mime type for. + * @private + * @returns The mime type to use. + */ + LoaderResource.prototype._getMimeFromXhrType = function (type) { + switch (type) { + case LoaderResource.XHR_RESPONSE_TYPE.BUFFER: + return 'application/octet-binary'; + case LoaderResource.XHR_RESPONSE_TYPE.BLOB: + return 'application/blob'; + case LoaderResource.XHR_RESPONSE_TYPE.DOCUMENT: + return 'application/xml'; + case LoaderResource.XHR_RESPONSE_TYPE.JSON: + return 'application/json'; + case LoaderResource.XHR_RESPONSE_TYPE.DEFAULT: + case LoaderResource.XHR_RESPONSE_TYPE.TEXT: + /* falls through */ + default: + return 'text/plain'; + } + }; + return LoaderResource; + }()); + // eslint-disable-next-line @typescript-eslint/no-namespace + (function (LoaderResource) { + (function (STATUS_FLAGS) { + /** None */ + STATUS_FLAGS[STATUS_FLAGS["NONE"] = 0] = "NONE"; + /** Data URL */ + STATUS_FLAGS[STATUS_FLAGS["DATA_URL"] = 1] = "DATA_URL"; + /** Complete */ + STATUS_FLAGS[STATUS_FLAGS["COMPLETE"] = 2] = "COMPLETE"; + /** Loading */ + STATUS_FLAGS[STATUS_FLAGS["LOADING"] = 4] = "LOADING"; + })(LoaderResource.STATUS_FLAGS || (LoaderResource.STATUS_FLAGS = {})); + (function (TYPE) { + /** Unknown */ + TYPE[TYPE["UNKNOWN"] = 0] = "UNKNOWN"; + /** JSON */ + TYPE[TYPE["JSON"] = 1] = "JSON"; + /** XML */ + TYPE[TYPE["XML"] = 2] = "XML"; + /** Image */ + TYPE[TYPE["IMAGE"] = 3] = "IMAGE"; + /** Audio */ + TYPE[TYPE["AUDIO"] = 4] = "AUDIO"; + /** Video */ + TYPE[TYPE["VIDEO"] = 5] = "VIDEO"; + /** Plain text */ + TYPE[TYPE["TEXT"] = 6] = "TEXT"; + })(LoaderResource.TYPE || (LoaderResource.TYPE = {})); + (function (LOAD_TYPE) { + /** Uses XMLHttpRequest to load the resource. */ + LOAD_TYPE[LOAD_TYPE["XHR"] = 1] = "XHR"; + /** Uses an `Image` object to load the resource. */ + LOAD_TYPE[LOAD_TYPE["IMAGE"] = 2] = "IMAGE"; + /** Uses an `Audio` object to load the resource. */ + LOAD_TYPE[LOAD_TYPE["AUDIO"] = 3] = "AUDIO"; + /** Uses a `Video` object to load the resource. */ + LOAD_TYPE[LOAD_TYPE["VIDEO"] = 4] = "VIDEO"; + })(LoaderResource.LOAD_TYPE || (LoaderResource.LOAD_TYPE = {})); + (function (XHR_RESPONSE_TYPE) { + /** string */ + XHR_RESPONSE_TYPE["DEFAULT"] = "text"; + /** ArrayBuffer */ + XHR_RESPONSE_TYPE["BUFFER"] = "arraybuffer"; + /** Blob */ + XHR_RESPONSE_TYPE["BLOB"] = "blob"; + /** Document */ + XHR_RESPONSE_TYPE["DOCUMENT"] = "document"; + /** Object */ + XHR_RESPONSE_TYPE["JSON"] = "json"; + /** String */ + XHR_RESPONSE_TYPE["TEXT"] = "text"; + })(LoaderResource.XHR_RESPONSE_TYPE || (LoaderResource.XHR_RESPONSE_TYPE = {})); + LoaderResource._loadTypeMap = { + // images + gif: LoaderResource.LOAD_TYPE.IMAGE, + png: LoaderResource.LOAD_TYPE.IMAGE, + bmp: LoaderResource.LOAD_TYPE.IMAGE, + jpg: LoaderResource.LOAD_TYPE.IMAGE, + jpeg: LoaderResource.LOAD_TYPE.IMAGE, + tif: LoaderResource.LOAD_TYPE.IMAGE, + tiff: LoaderResource.LOAD_TYPE.IMAGE, + webp: LoaderResource.LOAD_TYPE.IMAGE, + tga: LoaderResource.LOAD_TYPE.IMAGE, + svg: LoaderResource.LOAD_TYPE.IMAGE, + 'svg+xml': LoaderResource.LOAD_TYPE.IMAGE, + // audio + mp3: LoaderResource.LOAD_TYPE.AUDIO, + ogg: LoaderResource.LOAD_TYPE.AUDIO, + wav: LoaderResource.LOAD_TYPE.AUDIO, + // videos + mp4: LoaderResource.LOAD_TYPE.VIDEO, + webm: LoaderResource.LOAD_TYPE.VIDEO, + }; + LoaderResource._xhrTypeMap = { + // xml + xhtml: LoaderResource.XHR_RESPONSE_TYPE.DOCUMENT, + html: LoaderResource.XHR_RESPONSE_TYPE.DOCUMENT, + htm: LoaderResource.XHR_RESPONSE_TYPE.DOCUMENT, + xml: LoaderResource.XHR_RESPONSE_TYPE.DOCUMENT, + tmx: LoaderResource.XHR_RESPONSE_TYPE.DOCUMENT, + svg: LoaderResource.XHR_RESPONSE_TYPE.DOCUMENT, + // This was added to handle Tiled Tileset XML, but .tsx is also a TypeScript React Component. + // Since it is way less likely for people to be loading TypeScript files instead of Tiled files, + // this should probably be fine. + tsx: LoaderResource.XHR_RESPONSE_TYPE.DOCUMENT, + // images + gif: LoaderResource.XHR_RESPONSE_TYPE.BLOB, + png: LoaderResource.XHR_RESPONSE_TYPE.BLOB, + bmp: LoaderResource.XHR_RESPONSE_TYPE.BLOB, + jpg: LoaderResource.XHR_RESPONSE_TYPE.BLOB, + jpeg: LoaderResource.XHR_RESPONSE_TYPE.BLOB, + tif: LoaderResource.XHR_RESPONSE_TYPE.BLOB, + tiff: LoaderResource.XHR_RESPONSE_TYPE.BLOB, + webp: LoaderResource.XHR_RESPONSE_TYPE.BLOB, + tga: LoaderResource.XHR_RESPONSE_TYPE.BLOB, + // json + json: LoaderResource.XHR_RESPONSE_TYPE.JSON, + // text + text: LoaderResource.XHR_RESPONSE_TYPE.TEXT, + txt: LoaderResource.XHR_RESPONSE_TYPE.TEXT, + // fonts + ttf: LoaderResource.XHR_RESPONSE_TYPE.BUFFER, + otf: LoaderResource.XHR_RESPONSE_TYPE.BUFFER, + }; + // We can't set the `src` attribute to empty string, so on abort we set it to this 1px transparent gif + LoaderResource.EMPTY_GIF = 'data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw=='; + })(exports.LoaderResource || (exports.LoaderResource = {})); + + /** + * Smaller version of the async library constructs. + * @ignore + */ + function _noop() { + } + /** + * Ensures a function is only called once. + * @ignore + * @param {Function} fn - The function to wrap. + * @returns {Function} The wrapping function. + */ + function onlyOnce(fn) { + return function onceWrapper() { + var arguments$1 = arguments; + + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments$1[_i]; + } + if (fn === null) { + throw new Error('Callback was already called.'); + } + var callFn = fn; + fn = null; + callFn.apply(this, args); + }; + } + /** + * @private + * @memberof PIXI + */ + var AsyncQueueItem = /** @class */ (function () { + /** + * @param data + * @param callback + * @private + */ + function AsyncQueueItem(data, callback) { + this.data = data; + this.callback = callback; + } + return AsyncQueueItem; + }()); + /** + * @private + * @memberof PIXI + */ + var AsyncQueue = /** @class */ (function () { + /** + * @param worker + * @param concurrency + * @private + */ + function AsyncQueue(worker, concurrency) { + var _this = this; + if (concurrency === void 0) { concurrency = 1; } + this.workers = 0; + this.saturated = _noop; + this.unsaturated = _noop; + this.empty = _noop; + this.drain = _noop; + this.error = _noop; + this.started = false; + this.paused = false; + this._tasks = []; + this._insert = function (data, insertAtFront, callback) { + if (callback && typeof callback !== 'function') { + throw new Error('task callback must be a function'); + } + _this.started = true; + // eslint-disable-next-line no-eq-null,eqeqeq + if (data == null && _this.idle()) { + // call drain immediately if there are no tasks + setTimeout(function () { return _this.drain(); }, 1); + return; + } + var item = new AsyncQueueItem(data, typeof callback === 'function' ? callback : _noop); + if (insertAtFront) { + _this._tasks.unshift(item); + } + else { + _this._tasks.push(item); + } + setTimeout(_this.process, 1); + }; + this.process = function () { + while (!_this.paused && _this.workers < _this.concurrency && _this._tasks.length) { + var task = _this._tasks.shift(); + if (_this._tasks.length === 0) { + _this.empty(); + } + _this.workers += 1; + if (_this.workers === _this.concurrency) { + _this.saturated(); + } + _this._worker(task.data, onlyOnce(_this._next(task))); + } + }; + this._worker = worker; + if (concurrency === 0) { + throw new Error('Concurrency must not be zero'); + } + this.concurrency = concurrency; + this.buffer = concurrency / 4.0; + } + /** + * @param task + * @private + */ + AsyncQueue.prototype._next = function (task) { + var _this = this; + return function () { + var arguments$1 = arguments; + + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments$1[_i]; + } + _this.workers -= 1; + task.callback.apply(task, args); + // eslint-disable-next-line no-eq-null,eqeqeq + if (args[0] != null) { + _this.error(args[0], task.data); + } + if (_this.workers <= (_this.concurrency - _this.buffer)) { + _this.unsaturated(); + } + if (_this.idle()) { + _this.drain(); + } + _this.process(); + }; + }; + // That was in object + // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types + AsyncQueue.prototype.push = function (data, callback) { + this._insert(data, false, callback); + }; + AsyncQueue.prototype.kill = function () { + this.workers = 0; + this.drain = _noop; + this.started = false; + this._tasks = []; + }; + // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types + AsyncQueue.prototype.unshift = function (data, callback) { + this._insert(data, true, callback); + }; + AsyncQueue.prototype.length = function () { + return this._tasks.length; + }; + AsyncQueue.prototype.running = function () { + return this.workers; + }; + AsyncQueue.prototype.idle = function () { + return this._tasks.length + this.workers === 0; + }; + AsyncQueue.prototype.pause = function () { + if (this.paused === true) { + return; + } + this.paused = true; + }; + AsyncQueue.prototype.resume = function () { + if (this.paused === false) { + return; + } + this.paused = false; + // Need to call this.process once per concurrent + // worker to preserve full concurrency after pause + for (var w = 1; w <= this.concurrency; w++) { + this.process(); + } + }; + /** + * Iterates an array in series. + * @param {Array.<*>} array - Array to iterate. + * @param {Function} iterator - Function to call for each element. + * @param {Function} callback - Function to call when done, or on error. + * @param {boolean} [deferNext=false] - Break synchronous each loop by calling next with a setTimeout of 1. + */ + AsyncQueue.eachSeries = function (array, iterator, callback, deferNext) { + var i = 0; + var len = array.length; + function next(err) { + if (err || i === len) { + if (callback) { + callback(err); + } + return; + } + if (deferNext) { + setTimeout(function () { + iterator(array[i++], next); + }, 1); + } + else { + iterator(array[i++], next); + } + } + next(); + }; + /** + * Async queue implementation, + * @param {Function} worker - The worker function to call for each task. + * @param {number} concurrency - How many workers to run in parrallel. + * @returns {*} The async queue object. + */ + AsyncQueue.queue = function (worker, concurrency) { + return new AsyncQueue(worker, concurrency); + }; + return AsyncQueue; + }()); + + // some constants + var MAX_PROGRESS = 100; + var rgxExtractUrlHash = /(#[\w-]+)?$/; + /** + * The new loader, forked from Resource Loader by Chad Engler: https://github.com/englercj/resource-loader + * + * ```js + * const loader = PIXI.Loader.shared; // PixiJS exposes a premade instance for you to use. + * // or + * const loader = new PIXI.Loader(); // You can also create your own if you want + * + * const sprites = {}; + * + * // Chainable `add` to enqueue a resource + * loader.add('bunny', 'data/bunny.png') + * .add('spaceship', 'assets/spritesheet.json'); + * loader.add('scoreFont', 'assets/score.fnt'); + * + * // Chainable `pre` to add a middleware that runs for each resource, *before* loading that resource. + * // This is useful to implement custom caching modules (using filesystem, indexeddb, memory, etc). + * loader.pre(cachingMiddleware); + * + * // Chainable `use` to add a middleware that runs for each resource, *after* loading that resource. + * // This is useful to implement custom parsing modules (like spritesheet parsers, spine parser, etc). + * loader.use(parsingMiddleware); + * + * // The `load` method loads the queue of resources, and calls the passed in callback called once all + * // resources have loaded. + * loader.load((loader, resources) => { + * // resources is an object where the key is the name of the resource loaded and the value is the resource object. + * // They have a couple default properties: + * // - `url`: The URL that the resource was loaded from + * // - `error`: The error that happened when trying to load (if any) + * // - `data`: The raw data that was loaded + * // also may contain other properties based on the middleware that runs. + * sprites.bunny = new PIXI.TilingSprite(resources.bunny.texture); + * sprites.spaceship = new PIXI.TilingSprite(resources.spaceship.texture); + * sprites.scoreFont = new PIXI.TilingSprite(resources.scoreFont.texture); + * }); + * + * // throughout the process multiple signals can be dispatched. + * loader.onProgress.add(() => {}); // called once per loaded/errored file + * loader.onError.add(() => {}); // called once per errored file + * loader.onLoad.add(() => {}); // called once per loaded file + * loader.onComplete.add(() => {}); // called once when the queued resources all load. + * ``` + * @memberof PIXI + */ + var Loader = /** @class */ (function () { + /** + * @param baseUrl - The base url for all resources loaded by this loader. + * @param concurrency - The number of resources to load concurrently. + */ + function Loader(baseUrl, concurrency) { + var _this = this; + if (baseUrl === void 0) { baseUrl = ''; } + if (concurrency === void 0) { concurrency = 10; } + /** The progress percent of the loader going through the queue. */ + this.progress = 0; + /** Loading state of the loader, true if it is currently loading resources. */ + this.loading = false; + /** + * A querystring to append to every URL added to the loader. + * + * This should be a valid query string *without* the question-mark (`?`). The loader will + * also *not* escape values for you. Make sure to escape your parameters with + * [`encodeURIComponent`](https://mdn.io/encodeURIComponent) before assigning this property. + * @example + * const loader = new Loader(); + * + * loader.defaultQueryString = 'user=me&password=secret'; + * + * // This will request 'image.png?user=me&password=secret' + * loader.add('image.png').load(); + * + * loader.reset(); + * + * // This will request 'image.png?v=1&user=me&password=secret' + * loader.add('iamge.png?v=1').load(); + */ + this.defaultQueryString = ''; + /** The middleware to run before loading each resource. */ + this._beforeMiddleware = []; + /** The middleware to run after loading each resource. */ + this._afterMiddleware = []; + /** The tracks the resources we are currently completing parsing for. */ + this._resourcesParsing = []; + /** + * The `_loadResource` function bound with this object context. + * @param r - The resource to load + * @param d - The dequeue function + */ + this._boundLoadResource = function (r, d) { return _this._loadResource(r, d); }; + /** All the resources for this loader keyed by name. */ + this.resources = {}; + this.baseUrl = baseUrl; + this._beforeMiddleware = []; + this._afterMiddleware = []; + this._resourcesParsing = []; + this._boundLoadResource = function (r, d) { return _this._loadResource(r, d); }; + this._queue = AsyncQueue.queue(this._boundLoadResource, concurrency); + this._queue.pause(); + this.resources = {}; + this.onProgress = new Signal(); + this.onError = new Signal(); + this.onLoad = new Signal(); + this.onStart = new Signal(); + this.onComplete = new Signal(); + for (var i = 0; i < Loader._plugins.length; ++i) { + var plugin = Loader._plugins[i]; + var pre = plugin.pre, use = plugin.use; + if (pre) { + this.pre(pre); + } + if (use) { + this.use(use); + } + } + this._protected = false; + } + /** + * Same as add, params have strict order + * @private + * @param name - The name of the resource to load. + * @param url - The url for this resource, relative to the baseUrl of this loader. + * @param options - The options for the load. + * @param callback - Function to call when this specific resource completes loading. + * @returns The loader itself. + */ + Loader.prototype._add = function (name, url, options, callback) { + // if loading already you can only add resources that have a parent. + if (this.loading && (!options || !options.parentResource)) { + throw new Error('Cannot add resources while the loader is running.'); + } + // check if resource already exists. + if (this.resources[name]) { + throw new Error("Resource named \"" + name + "\" already exists."); + } + // add base url if this isn't an absolute url + url = this._prepareUrl(url); + // create the store the resource + this.resources[name] = new exports.LoaderResource(name, url, options); + if (typeof callback === 'function') { + this.resources[name].onAfterMiddleware.once(callback); + } + // if actively loading, make sure to adjust progress chunks for that parent and its children + if (this.loading) { + var parent = options.parentResource; + var incompleteChildren = []; + for (var i = 0; i < parent.children.length; ++i) { + if (!parent.children[i].isComplete) { + incompleteChildren.push(parent.children[i]); + } + } + var fullChunk = parent.progressChunk * (incompleteChildren.length + 1); // +1 for parent + var eachChunk = fullChunk / (incompleteChildren.length + 2); // +2 for parent & new child + parent.children.push(this.resources[name]); + parent.progressChunk = eachChunk; + for (var i = 0; i < incompleteChildren.length; ++i) { + incompleteChildren[i].progressChunk = eachChunk; + } + this.resources[name].progressChunk = eachChunk; + } + // add the resource to the queue + this._queue.push(this.resources[name]); + return this; + }; + /* eslint-enable require-jsdoc,valid-jsdoc */ + /** + * Sets up a middleware function that will run *before* the + * resource is loaded. + * @param fn - The middleware function to register. + * @returns The loader itself. + */ + Loader.prototype.pre = function (fn) { + this._beforeMiddleware.push(fn); + return this; + }; + /** + * Sets up a middleware function that will run *after* the + * resource is loaded. + * @param fn - The middleware function to register. + * @returns The loader itself. + */ + Loader.prototype.use = function (fn) { + this._afterMiddleware.push(fn); + return this; + }; + /** + * Resets the queue of the loader to prepare for a new load. + * @returns The loader itself. + */ + Loader.prototype.reset = function () { + this.progress = 0; + this.loading = false; + this._queue.kill(); + this._queue.pause(); + // abort all resource loads + for (var k in this.resources) { + var res = this.resources[k]; + if (res._onLoadBinding) { + res._onLoadBinding.detach(); + } + if (res.isLoading) { + res.abort('loader reset'); + } + } + this.resources = {}; + return this; + }; + /** + * Starts loading the queued resources. + * @param cb - Optional callback that will be bound to the `complete` event. + * @returns The loader itself. + */ + Loader.prototype.load = function (cb) { + deprecation$1('6.5.0', '@pixi/loaders is being replaced with @pixi/assets in the next major release.'); + // register complete callback if they pass one + if (typeof cb === 'function') { + this.onComplete.once(cb); + } + // if the queue has already started we are done here + if (this.loading) { + return this; + } + if (this._queue.idle()) { + this._onStart(); + this._onComplete(); + } + else { + // distribute progress chunks + var numTasks = this._queue._tasks.length; + var chunk = MAX_PROGRESS / numTasks; + for (var i = 0; i < this._queue._tasks.length; ++i) { + this._queue._tasks[i].data.progressChunk = chunk; + } + // notify we are starting + this._onStart(); + // start loading + this._queue.resume(); + } + return this; + }; + Object.defineProperty(Loader.prototype, "concurrency", { + /** + * The number of resources to load concurrently. + * @default 10 + */ + get: function () { + return this._queue.concurrency; + }, + set: function (concurrency) { + this._queue.concurrency = concurrency; + }, + enumerable: false, + configurable: true + }); + /** + * Prepares a url for usage based on the configuration of this object + * @param url - The url to prepare. + * @returns The prepared url. + */ + Loader.prototype._prepareUrl = function (url) { + var parsedUrl = parseUri(url, { strictMode: true }); + var result; + // absolute url, just use it as is. + if (parsedUrl.protocol || !parsedUrl.path || url.indexOf('//') === 0) { + result = url; + } + // if baseUrl doesn't end in slash and url doesn't start with slash, then add a slash inbetween + else if (this.baseUrl.length + && this.baseUrl.lastIndexOf('/') !== this.baseUrl.length - 1 + && url.charAt(0) !== '/') { + result = this.baseUrl + "/" + url; + } + else { + result = this.baseUrl + url; + } + // if we need to add a default querystring, there is a bit more work + if (this.defaultQueryString) { + var hash = rgxExtractUrlHash.exec(result)[0]; + result = result.slice(0, result.length - hash.length); + if (result.indexOf('?') !== -1) { + result += "&" + this.defaultQueryString; + } + else { + result += "?" + this.defaultQueryString; + } + result += hash; + } + return result; + }; + /** + * Loads a single resource. + * @param resource - The resource to load. + * @param dequeue - The function to call when we need to dequeue this item. + */ + Loader.prototype._loadResource = function (resource, dequeue) { + var _this = this; + resource._dequeue = dequeue; + // run before middleware + AsyncQueue.eachSeries(this._beforeMiddleware, function (fn, next) { + fn.call(_this, resource, function () { + // if the before middleware marks the resource as complete, + // break and don't process any more before middleware + next(resource.isComplete ? {} : null); + }); + }, function () { + if (resource.isComplete) { + _this._onLoad(resource); + } + else { + resource._onLoadBinding = resource.onComplete.once(_this._onLoad, _this); + resource.load(); + } + }, true); + }; + /** Called once loading has started. */ + Loader.prototype._onStart = function () { + this.progress = 0; + this.loading = true; + this.onStart.dispatch(this); + }; + /** Called once each resource has loaded. */ + Loader.prototype._onComplete = function () { + this.progress = MAX_PROGRESS; + this.loading = false; + this.onComplete.dispatch(this, this.resources); + }; + /** + * Called each time a resources is loaded. + * @param resource - The resource that was loaded + */ + Loader.prototype._onLoad = function (resource) { + var _this = this; + resource._onLoadBinding = null; + // remove this resource from the async queue, and add it to our list of resources that are being parsed + this._resourcesParsing.push(resource); + resource._dequeue(); + // run all the after middleware for this resource + AsyncQueue.eachSeries(this._afterMiddleware, function (fn, next) { + fn.call(_this, resource, next); + }, function () { + resource.onAfterMiddleware.dispatch(resource); + _this.progress = Math.min(MAX_PROGRESS, _this.progress + resource.progressChunk); + _this.onProgress.dispatch(_this, resource); + if (resource.error) { + _this.onError.dispatch(resource.error, _this, resource); + } + else { + _this.onLoad.dispatch(_this, resource); + } + _this._resourcesParsing.splice(_this._resourcesParsing.indexOf(resource), 1); + // do completion check + if (_this._queue.idle() && _this._resourcesParsing.length === 0) { + _this._onComplete(); + } + }, true); + }; + /** Destroy the loader, removes references. */ + Loader.prototype.destroy = function () { + if (!this._protected) { + this.reset(); + } + }; + Object.defineProperty(Loader, "shared", { + /** A premade instance of the loader that can be used to load resources. */ + get: function () { + var shared = Loader._shared; + if (!shared) { + shared = new Loader(); + shared._protected = true; + Loader._shared = shared; + } + return shared; + }, + enumerable: false, + configurable: true + }); + /** + * Use the {@link PIXI.extensions.add} API to register plugins. + * @deprecated since 6.5.0 + * @param plugin - The plugin to add + * @returns Reference to PIXI.Loader for chaining + */ + Loader.registerPlugin = function (plugin) { + deprecation$1('6.5.0', 'Loader.registerPlugin() is deprecated, use extensions.add() instead.'); + extensions.add({ + type: exports.ExtensionType.Loader, + ref: plugin, + }); + return Loader; + }; + Loader._plugins = []; + return Loader; + }()); + extensions.handleByList(exports.ExtensionType.Loader, Loader._plugins); + Loader.prototype.add = function add(name, url, options, callback) { + // special case of an array of objects or urls + if (Array.isArray(name)) { + for (var i = 0; i < name.length; ++i) { + this.add(name[i]); + } + return this; + } + // if an object is passed instead of params + if (typeof name === 'object') { + options = name; + callback = url || options.callback || options.onComplete; + url = options.url; + name = options.name || options.key || options.url; + } + // case where no name is passed shift all args over by one. + if (typeof url !== 'string') { + callback = options; + options = url; + url = name; + } + // now that we shifted make sure we have a proper url. + if (typeof url !== 'string') { + throw new Error('No url passed to add resource to loader.'); + } + // options are optional so people might pass a function and no options + if (typeof options === 'function') { + callback = options; + options = null; + } + return this._add(name, url, options, callback); + }; + + /** + * Application plugin for supporting loader option. Installing the LoaderPlugin + * is not necessary if using **pixi.js** or **pixi.js-legacy**. + * @example + * import {AppLoaderPlugin} from '@pixi/loaders'; + * import {extensions} from '@pixi/core'; + * extensions.add(AppLoaderPlugin); + * @memberof PIXI + */ + var AppLoaderPlugin = /** @class */ (function () { + function AppLoaderPlugin() { + } + /** + * Called on application constructor + * @param options + * @private + */ + AppLoaderPlugin.init = function (options) { + options = Object.assign({ + sharedLoader: false, + }, options); + this.loader = options.sharedLoader ? Loader.shared : new Loader(); + }; + /** + * Called when application destroyed + * @private + */ + AppLoaderPlugin.destroy = function () { + if (this.loader) { + this.loader.destroy(); + this.loader = null; + } + }; + /** @ignore */ + AppLoaderPlugin.extension = exports.ExtensionType.Application; + return AppLoaderPlugin; + }()); + + /** + * Loader plugin for handling Texture resources. + * @memberof PIXI + */ + var TextureLoader = /** @class */ (function () { + function TextureLoader() { + } + /** Handle SVG elements a text, render with SVGResource. */ + TextureLoader.add = function () { + exports.LoaderResource.setExtensionLoadType('svg', exports.LoaderResource.LOAD_TYPE.XHR); + exports.LoaderResource.setExtensionXhrType('svg', exports.LoaderResource.XHR_RESPONSE_TYPE.TEXT); + }; + /** + * Called after a resource is loaded. + * @see PIXI.Loader.loaderMiddleware + * @param resource + * @param {Function} next + */ + TextureLoader.use = function (resource, next) { + // create a new texture if the data is an Image object + if (resource.data && (resource.type === exports.LoaderResource.TYPE.IMAGE || resource.extension === 'svg')) { + var data = resource.data, url = resource.url, name = resource.name, metadata = resource.metadata; + Texture.fromLoader(data, url, name, metadata).then(function (texture) { + resource.texture = texture; + next(); + }) + // TODO: handle errors in Texture.fromLoader + // so we can pass them to the Loader + .catch(next); + } + else { + next(); + } + }; + /** @ignore */ + TextureLoader.extension = exports.ExtensionType.Loader; + return TextureLoader; + }()); + + var _keyStr = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='; + /** + * Encodes binary into base64. + * @function encodeBinary + * @param {string} input - The input data to encode. + * @returns {string} The encoded base64 string + */ + function encodeBinary(input) { + var output = ''; + var inx = 0; + while (inx < input.length) { + // Fill byte buffer array + var bytebuffer = [0, 0, 0]; + var encodedCharIndexes = [0, 0, 0, 0]; + for (var jnx = 0; jnx < bytebuffer.length; ++jnx) { + if (inx < input.length) { + // throw away high-order byte, as documented at: + // https://developer.mozilla.org/En/Using_XMLHttpRequest#Handling_binary_data + bytebuffer[jnx] = input.charCodeAt(inx++) & 0xff; + } + else { + bytebuffer[jnx] = 0; + } + } + // Get each encoded character, 6 bits at a time + // index 1: first 6 bits + encodedCharIndexes[0] = bytebuffer[0] >> 2; + // index 2: second 6 bits (2 least significant bits from input byte 1 + 4 most significant bits from byte 2) + encodedCharIndexes[1] = ((bytebuffer[0] & 0x3) << 4) | (bytebuffer[1] >> 4); + // index 3: third 6 bits (4 least significant bits from input byte 2 + 2 most significant bits from byte 3) + encodedCharIndexes[2] = ((bytebuffer[1] & 0x0f) << 2) | (bytebuffer[2] >> 6); + // index 3: forth 6 bits (6 least significant bits from input byte 3) + encodedCharIndexes[3] = bytebuffer[2] & 0x3f; + // Determine whether padding happened, and adjust accordingly + var paddingBytes = inx - (input.length - 1); + switch (paddingBytes) { + case 2: + // Set last 2 characters to padding char + encodedCharIndexes[3] = 64; + encodedCharIndexes[2] = 64; + break; + case 1: + // Set last character to padding char + encodedCharIndexes[3] = 64; + break; + } + // Now we will grab each appropriate character out of our keystring + // based on our index array and append it to the output string + for (var jnx = 0; jnx < encodedCharIndexes.length; ++jnx) { + output += _keyStr.charAt(encodedCharIndexes[jnx]); + } + } + return output; + } + + /** + * A middleware for transforming XHR loaded Blobs into more useful objects + * @ignore + * @function parsing + * @example + * import { Loader, middleware } from 'resource-loader'; + * const loader = new Loader(); + * loader.use(middleware.parsing); + * @param resource - Current Resource + * @param next - Callback when complete + */ + function parsing(resource, next) { + if (!resource.data) { + next(); + return; + } + // if this was an XHR load of a blob + if (resource.xhr && resource.xhrType === exports.LoaderResource.XHR_RESPONSE_TYPE.BLOB) { + // if there is no blob support we probably got a binary string back + if (!self.Blob || typeof resource.data === 'string') { + var type = resource.xhr.getResponseHeader('content-type'); + // this is an image, convert the binary string into a data url + if (type && type.indexOf('image') === 0) { + resource.data = new Image(); + resource.data.src = "data:" + type + ";base64," + encodeBinary(resource.xhr.responseText); + resource.type = exports.LoaderResource.TYPE.IMAGE; + // wait until the image loads and then callback + resource.data.onload = function () { + resource.data.onload = null; + next(); + }; + // next will be called on load + return; + } + } + // if content type says this is an image, then we should transform the blob into an Image object + else if (resource.data.type.indexOf('image') === 0) { + var Url_1 = globalThis.URL || globalThis.webkitURL; + var src_1 = Url_1.createObjectURL(resource.data); + resource.blob = resource.data; + resource.data = new Image(); + resource.data.src = src_1; + resource.type = exports.LoaderResource.TYPE.IMAGE; + // cleanup the no longer used blob after the image loads + // TODO: Is this correct? Will the image be invalid after revoking? + resource.data.onload = function () { + Url_1.revokeObjectURL(src_1); + resource.data.onload = null; + next(); + }; + // next will be called on load. + return; + } + } + next(); + } + + /** + * Parse any blob into more usable objects (e.g. Image). + * @memberof PIXI + */ + var ParsingLoader = /** @class */ (function () { + function ParsingLoader() { + } + /** @ignore */ + ParsingLoader.extension = exports.ExtensionType.Loader; + ParsingLoader.use = parsing; + return ParsingLoader; + }()); + + extensions.add(TextureLoader, ParsingLoader); + + /*! + * @pixi/compressed-textures - v6.5.3 + * Compiled Fri, 09 Sep 2022 13:55:20 UTC + * + * @pixi/compressed-textures is licensed under the MIT License. + * http://www.opensource.org/licenses/mit-license + */ + + var _a$2; + /** + * WebGL internal formats, including compressed texture formats provided by extensions + * @memberof PIXI + * @static + * @name INTERNAL_FORMATS + * @enum {number} + * @property {number} [COMPRESSED_RGB_S3TC_DXT1_EXT=0x83F0] - + * @property {number} [COMPRESSED_RGBA_S3TC_DXT1_EXT=0x83F1] - + * @property {number} [COMPRESSED_RGBA_S3TC_DXT3_EXT=0x83F2] - + * @property {number} [COMPRESSED_RGBA_S3TC_DXT5_EXT=0x83F3] - + * @property {number} [COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT=35917] - + * @property {number} [COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT=35918] - + * @property {number} [COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT=35919] - + * @property {number} [COMPRESSED_SRGB_S3TC_DXT1_EXT=35916] - + * @property {number} [COMPRESSED_R11_EAC=0x9270] - + * @property {number} [COMPRESSED_SIGNED_R11_EAC=0x9271] - + * @property {number} [COMPRESSED_RG11_EAC=0x9272] - + * @property {number} [COMPRESSED_SIGNED_RG11_EAC=0x9273] - + * @property {number} [COMPRESSED_RGB8_ETC2=0x9274] - + * @property {number} [COMPRESSED_RGBA8_ETC2_EAC=0x9278] - + * @property {number} [COMPRESSED_SRGB8_ETC2=0x9275] - + * @property {number} [COMPRESSED_SRGB8_ALPHA8_ETC2_EAC=0x9279] - + * @property {number} [COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2=0x9276] - + * @property {number} [COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2=0x9277] - + * @property {number} [COMPRESSED_RGB_PVRTC_4BPPV1_IMG=0x8C00] - + * @property {number} [COMPRESSED_RGBA_PVRTC_4BPPV1_IMG=0x8C02] - + * @property {number} [COMPRESSED_RGB_PVRTC_2BPPV1_IMG=0x8C01] - + * @property {number} [COMPRESSED_RGBA_PVRTC_2BPPV1_IMG=0x8C03] - + * @property {number} [COMPRESSED_RGB_ETC1_WEBGL=0x8D64] - + * @property {number} [COMPRESSED_RGB_ATC_WEBGL=0x8C92] - + * @property {number} [COMPRESSED_RGBA_ATC_EXPLICIT_ALPHA_WEBGL=0x8C92] - + * @property {number} [COMPRESSED_RGBA_ATC_INTERPOLATED_ALPHA_WEBGL=0x87EE] - + */ + exports.INTERNAL_FORMATS = void 0; + (function (INTERNAL_FORMATS) { + // WEBGL_compressed_texture_s3tc + INTERNAL_FORMATS[INTERNAL_FORMATS["COMPRESSED_RGB_S3TC_DXT1_EXT"] = 33776] = "COMPRESSED_RGB_S3TC_DXT1_EXT"; + INTERNAL_FORMATS[INTERNAL_FORMATS["COMPRESSED_RGBA_S3TC_DXT1_EXT"] = 33777] = "COMPRESSED_RGBA_S3TC_DXT1_EXT"; + INTERNAL_FORMATS[INTERNAL_FORMATS["COMPRESSED_RGBA_S3TC_DXT3_EXT"] = 33778] = "COMPRESSED_RGBA_S3TC_DXT3_EXT"; + INTERNAL_FORMATS[INTERNAL_FORMATS["COMPRESSED_RGBA_S3TC_DXT5_EXT"] = 33779] = "COMPRESSED_RGBA_S3TC_DXT5_EXT"; + // WEBGL_compressed_texture_s3tc_srgb + INTERNAL_FORMATS[INTERNAL_FORMATS["COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT"] = 35917] = "COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT"; + INTERNAL_FORMATS[INTERNAL_FORMATS["COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT"] = 35918] = "COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT"; + INTERNAL_FORMATS[INTERNAL_FORMATS["COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT"] = 35919] = "COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT"; + INTERNAL_FORMATS[INTERNAL_FORMATS["COMPRESSED_SRGB_S3TC_DXT1_EXT"] = 35916] = "COMPRESSED_SRGB_S3TC_DXT1_EXT"; + // WEBGL_compressed_texture_etc + INTERNAL_FORMATS[INTERNAL_FORMATS["COMPRESSED_R11_EAC"] = 37488] = "COMPRESSED_R11_EAC"; + INTERNAL_FORMATS[INTERNAL_FORMATS["COMPRESSED_SIGNED_R11_EAC"] = 37489] = "COMPRESSED_SIGNED_R11_EAC"; + INTERNAL_FORMATS[INTERNAL_FORMATS["COMPRESSED_RG11_EAC"] = 37490] = "COMPRESSED_RG11_EAC"; + INTERNAL_FORMATS[INTERNAL_FORMATS["COMPRESSED_SIGNED_RG11_EAC"] = 37491] = "COMPRESSED_SIGNED_RG11_EAC"; + INTERNAL_FORMATS[INTERNAL_FORMATS["COMPRESSED_RGB8_ETC2"] = 37492] = "COMPRESSED_RGB8_ETC2"; + INTERNAL_FORMATS[INTERNAL_FORMATS["COMPRESSED_RGBA8_ETC2_EAC"] = 37496] = "COMPRESSED_RGBA8_ETC2_EAC"; + INTERNAL_FORMATS[INTERNAL_FORMATS["COMPRESSED_SRGB8_ETC2"] = 37493] = "COMPRESSED_SRGB8_ETC2"; + INTERNAL_FORMATS[INTERNAL_FORMATS["COMPRESSED_SRGB8_ALPHA8_ETC2_EAC"] = 37497] = "COMPRESSED_SRGB8_ALPHA8_ETC2_EAC"; + INTERNAL_FORMATS[INTERNAL_FORMATS["COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2"] = 37494] = "COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2"; + INTERNAL_FORMATS[INTERNAL_FORMATS["COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2"] = 37495] = "COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2"; + // WEBGL_compressed_texture_pvrtc + INTERNAL_FORMATS[INTERNAL_FORMATS["COMPRESSED_RGB_PVRTC_4BPPV1_IMG"] = 35840] = "COMPRESSED_RGB_PVRTC_4BPPV1_IMG"; + INTERNAL_FORMATS[INTERNAL_FORMATS["COMPRESSED_RGBA_PVRTC_4BPPV1_IMG"] = 35842] = "COMPRESSED_RGBA_PVRTC_4BPPV1_IMG"; + INTERNAL_FORMATS[INTERNAL_FORMATS["COMPRESSED_RGB_PVRTC_2BPPV1_IMG"] = 35841] = "COMPRESSED_RGB_PVRTC_2BPPV1_IMG"; + INTERNAL_FORMATS[INTERNAL_FORMATS["COMPRESSED_RGBA_PVRTC_2BPPV1_IMG"] = 35843] = "COMPRESSED_RGBA_PVRTC_2BPPV1_IMG"; + // WEBGL_compressed_texture_etc1 + INTERNAL_FORMATS[INTERNAL_FORMATS["COMPRESSED_RGB_ETC1_WEBGL"] = 36196] = "COMPRESSED_RGB_ETC1_WEBGL"; + // WEBGL_compressed_texture_atc + INTERNAL_FORMATS[INTERNAL_FORMATS["COMPRESSED_RGB_ATC_WEBGL"] = 35986] = "COMPRESSED_RGB_ATC_WEBGL"; + INTERNAL_FORMATS[INTERNAL_FORMATS["COMPRESSED_RGBA_ATC_EXPLICIT_ALPHA_WEBGL"] = 35986] = "COMPRESSED_RGBA_ATC_EXPLICIT_ALPHA_WEBGL"; + INTERNAL_FORMATS[INTERNAL_FORMATS["COMPRESSED_RGBA_ATC_INTERPOLATED_ALPHA_WEBGL"] = 34798] = "COMPRESSED_RGBA_ATC_INTERPOLATED_ALPHA_WEBGL"; + })(exports.INTERNAL_FORMATS || (exports.INTERNAL_FORMATS = {})); + /** + * Maps the compressed texture formats in {@link PIXI.INTERNAL_FORMATS} to the number of bytes taken by + * each texel. + * @memberof PIXI + * @static + * @ignore + */ + var INTERNAL_FORMAT_TO_BYTES_PER_PIXEL = (_a$2 = {}, + // WEBGL_compressed_texture_s3tc + _a$2[exports.INTERNAL_FORMATS.COMPRESSED_RGB_S3TC_DXT1_EXT] = 0.5, + _a$2[exports.INTERNAL_FORMATS.COMPRESSED_RGBA_S3TC_DXT1_EXT] = 0.5, + _a$2[exports.INTERNAL_FORMATS.COMPRESSED_RGBA_S3TC_DXT3_EXT] = 1, + _a$2[exports.INTERNAL_FORMATS.COMPRESSED_RGBA_S3TC_DXT5_EXT] = 1, + // WEBGL_compressed_texture_s3tc + _a$2[exports.INTERNAL_FORMATS.COMPRESSED_SRGB_S3TC_DXT1_EXT] = 0.5, + _a$2[exports.INTERNAL_FORMATS.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT] = 0.5, + _a$2[exports.INTERNAL_FORMATS.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT] = 1, + _a$2[exports.INTERNAL_FORMATS.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT] = 1, + // WEBGL_compressed_texture_etc + _a$2[exports.INTERNAL_FORMATS.COMPRESSED_R11_EAC] = 0.5, + _a$2[exports.INTERNAL_FORMATS.COMPRESSED_SIGNED_R11_EAC] = 0.5, + _a$2[exports.INTERNAL_FORMATS.COMPRESSED_RG11_EAC] = 1, + _a$2[exports.INTERNAL_FORMATS.COMPRESSED_SIGNED_RG11_EAC] = 1, + _a$2[exports.INTERNAL_FORMATS.COMPRESSED_RGB8_ETC2] = 0.5, + _a$2[exports.INTERNAL_FORMATS.COMPRESSED_RGBA8_ETC2_EAC] = 1, + _a$2[exports.INTERNAL_FORMATS.COMPRESSED_SRGB8_ETC2] = 0.5, + _a$2[exports.INTERNAL_FORMATS.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC] = 1, + _a$2[exports.INTERNAL_FORMATS.COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2] = 0.5, + _a$2[exports.INTERNAL_FORMATS.COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2] = 0.5, + // WEBGL_compressed_texture_pvrtc + _a$2[exports.INTERNAL_FORMATS.COMPRESSED_RGB_PVRTC_4BPPV1_IMG] = 0.5, + _a$2[exports.INTERNAL_FORMATS.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG] = 0.5, + _a$2[exports.INTERNAL_FORMATS.COMPRESSED_RGB_PVRTC_2BPPV1_IMG] = 0.25, + _a$2[exports.INTERNAL_FORMATS.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG] = 0.25, + // WEBGL_compressed_texture_etc1 + _a$2[exports.INTERNAL_FORMATS.COMPRESSED_RGB_ETC1_WEBGL] = 0.5, + // @see https://www.khronos.org/registry/OpenGL/extensions/AMD/AMD_compressed_ATC_texture.txt + // WEBGL_compressed_texture_atc + _a$2[exports.INTERNAL_FORMATS.COMPRESSED_RGB_ATC_WEBGL] = 0.5, + _a$2[exports.INTERNAL_FORMATS.COMPRESSED_RGBA_ATC_EXPLICIT_ALPHA_WEBGL] = 1, + _a$2[exports.INTERNAL_FORMATS.COMPRESSED_RGBA_ATC_INTERPOLATED_ALPHA_WEBGL] = 1, + _a$2); + + /*! ***************************************************************************** + Copyright (c) Microsoft Corporation. - var extendStatics$8 = function(d, b) { - extendStatics$8 = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) { if (b.hasOwnProperty(p)) { d[p] = b[p]; } } }; - return extendStatics$8(d, b); - }; + Permission to use, copy, modify, and/or distribute this software for any + purpose with or without fee is hereby granted. - function __extends$8(d, b) { - extendStatics$8(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - } - - /** - * CountLimiter limits the number of items handled by a {@link PIXI.BasePrepare} to a specified - * number of items per frame. - * - * @class - * @memberof PIXI - */ - var CountLimiter = /** @class */ (function () { - /** - * @param {number} maxItemsPerFrame - The maximum number of items that can be prepared each frame. - */ - function CountLimiter(maxItemsPerFrame) { - /** - * The maximum number of items that can be prepared each frame. - * @type {number} - * @private - */ - this.maxItemsPerFrame = maxItemsPerFrame; - /** - * The number of items that can be prepared in the current frame. - * @type {number} - * @private - */ - this.itemsLeft = 0; - } - /** - * Resets any counting properties to start fresh on a new frame. - */ - CountLimiter.prototype.beginFrame = function () { - this.itemsLeft = this.maxItemsPerFrame; - }; - /** - * Checks to see if another item can be uploaded. This should only be called once per item. - * @return {boolean} If the item is allowed to be uploaded. - */ - CountLimiter.prototype.allowedToUpload = function () { - return this.itemsLeft-- > 0; - }; - return CountLimiter; - }()); - - /** - * Built-in hook to find multiple textures from objects like AnimatedSprites. - * - * @private - * @param {PIXI.DisplayObject} item - Display object to check - * @param {Array<*>} queue - Collection of items to upload - * @return {boolean} if a PIXI.Texture object was found. - */ - function findMultipleBaseTextures(item, queue) { - var result = false; - // Objects with multiple textures - if (item && item._textures && item._textures.length) { - for (var i = 0; i < item._textures.length; i++) { - if (item._textures[i] instanceof Texture) { - var baseTexture = item._textures[i].baseTexture; - if (queue.indexOf(baseTexture) === -1) { - queue.push(baseTexture); - result = true; - } - } - } - } - return result; - } - /** - * Built-in hook to find BaseTextures from Texture. - * - * @private - * @param {PIXI.Texture} item - Display object to check - * @param {Array<*>} queue - Collection of items to upload - * @return {boolean} if a PIXI.Texture object was found. - */ - function findBaseTexture(item, queue) { - if (item.baseTexture instanceof BaseTexture) { - var texture = item.baseTexture; - if (queue.indexOf(texture) === -1) { - queue.push(texture); - } - return true; - } - return false; - } - /** - * Built-in hook to find textures from objects. - * - * @private - * @param {PIXI.DisplayObject} item - Display object to check - * @param {Array<*>} queue - Collection of items to upload - * @return {boolean} if a PIXI.Texture object was found. - */ - function findTexture(item, queue) { - if (item._texture && item._texture instanceof Texture) { - var texture = item._texture.baseTexture; - if (queue.indexOf(texture) === -1) { - queue.push(texture); - } - return true; - } - return false; - } - /** - * Built-in hook to draw PIXI.Text to its texture. - * - * @private - * @param {PIXI.AbstractRenderer|PIXI.BasePrepare} helper - Not used by this upload handler - * @param {PIXI.DisplayObject} item - Item to check - * @return {boolean} If item was uploaded. - */ - function drawText(_helper, item) { - if (item instanceof Text) { - // updating text will return early if it is not dirty - item.updateText(true); - return true; - } - return false; - } - /** - * Built-in hook to calculate a text style for a PIXI.Text object. - * - * @private - * @param {PIXI.AbstractRenderer|PIXI.BasePrepare} helper - Not used by this upload handler - * @param {PIXI.DisplayObject} item - Item to check - * @return {boolean} If item was uploaded. - */ - function calculateTextStyle(_helper, item) { - if (item instanceof TextStyle) { - var font = item.toFontString(); - TextMetrics.measureFont(font); - return true; - } - return false; - } - /** - * Built-in hook to find Text objects. - * - * @private - * @param {PIXI.DisplayObject} item - Display object to check - * @param {Array<*>} queue - Collection of items to upload - * @return {boolean} if a PIXI.Text object was found. - */ - function findText(item, queue) { - if (item instanceof Text) { - // push the text style to prepare it - this can be really expensive - if (queue.indexOf(item.style) === -1) { - queue.push(item.style); - } - // also push the text object so that we can render it (to canvas/texture) if needed - if (queue.indexOf(item) === -1) { - queue.push(item); - } - // also push the Text's texture for upload to GPU - var texture = item._texture.baseTexture; - if (queue.indexOf(texture) === -1) { - queue.push(texture); - } - return true; - } - return false; - } - /** - * Built-in hook to find TextStyle objects. - * - * @private - * @param {PIXI.TextStyle} item - Display object to check - * @param {Array<*>} queue - Collection of items to upload - * @return {boolean} if a PIXI.TextStyle object was found. - */ - function findTextStyle(item, queue) { - if (item instanceof TextStyle) { - if (queue.indexOf(item) === -1) { - queue.push(item); - } - return true; - } - return false; - } - /** - * The prepare manager provides functionality to upload content to the GPU. - * - * BasePrepare handles basic queuing functionality and is extended by - * {@link PIXI.Prepare} and {@link PIXI.CanvasPrepare} - * to provide preparation capabilities specific to their respective renderers. - * - * @example - * // Create a sprite - * const sprite = PIXI.Sprite.from('something.png'); - * - * // Load object into GPU - * app.renderer.plugins.prepare.upload(sprite, () => { - * - * //Texture(s) has been uploaded to GPU - * app.stage.addChild(sprite); - * - * }) - * - * @abstract - * @class - * @memberof PIXI - */ - var BasePrepare = /** @class */ (function () { - /** - * @param {PIXI.AbstractRenderer} renderer - A reference to the current renderer - */ - function BasePrepare(renderer) { - var _this = this; - /** - * The limiter to be used to control how quickly items are prepared. - * @type {PIXI.CountLimiter|PIXI.TimeLimiter} - */ - this.limiter = new CountLimiter(settings.UPLOADS_PER_FRAME); - /** - * Reference to the renderer. - * @type {PIXI.AbstractRenderer} - * @protected - */ - this.renderer = renderer; - /** - * The only real difference between CanvasPrepare and Prepare is what they pass - * to upload hooks. That different parameter is stored here. - * @type {object} - * @protected - */ - this.uploadHookHelper = null; - /** - * Collection of items to uploads at once. - * @type {Array<*>} - * @private - */ - this.queue = []; - /** - * Collection of additional hooks for finding assets. - * @type {Array} - * @private - */ - this.addHooks = []; - /** - * Collection of additional hooks for processing assets. - * @type {Array} - * @private - */ - this.uploadHooks = []; - /** - * Callback to call after completed. - * @type {Array} - * @private - */ - this.completes = []; - /** - * If prepare is ticking (running). - * @type {boolean} - * @private - */ - this.ticking = false; - /** - * 'bound' call for prepareItems(). - * @type {Function} - * @private - */ - this.delayedTick = function () { - // unlikely, but in case we were destroyed between tick() and delayedTick() - if (!_this.queue) { - return; - } - _this.prepareItems(); - }; - // hooks to find the correct texture - this.registerFindHook(findText); - this.registerFindHook(findTextStyle); - this.registerFindHook(findMultipleBaseTextures); - this.registerFindHook(findBaseTexture); - this.registerFindHook(findTexture); - // upload hooks - this.registerUploadHook(drawText); - this.registerUploadHook(calculateTextStyle); - } - /** - * Upload all the textures and graphics to the GPU. - * - * @param {Function|PIXI.DisplayObject|PIXI.Container|PIXI.BaseTexture|PIXI.Texture|PIXI.Graphics|PIXI.Text} item - - * Either the container or display object to search for items to upload, the items to upload themselves, - * or the callback function, if items have been added using `prepare.add`. - * @param {Function} [done] - Optional callback when all queued uploads have completed - */ - BasePrepare.prototype.upload = function (item, done) { - if (typeof item === 'function') { - done = item; - item = null; - } - // If a display object, search for items - // that we could upload - if (item) { - this.add(item); - } - // Get the items for upload from the display - if (this.queue.length) { - if (done) { - this.completes.push(done); - } - if (!this.ticking) { - this.ticking = true; - Ticker.system.addOnce(this.tick, this, exports.UPDATE_PRIORITY.UTILITY); - } - } - else if (done) { - done(); - } - }; - /** - * Handle tick update - * - * @private - */ - BasePrepare.prototype.tick = function () { - setTimeout(this.delayedTick, 0); - }; - /** - * Actually prepare items. This is handled outside of the tick because it will take a while - * and we do NOT want to block the current animation frame from rendering. - * - * @private - */ - BasePrepare.prototype.prepareItems = function () { - this.limiter.beginFrame(); - // Upload the graphics - while (this.queue.length && this.limiter.allowedToUpload()) { - var item = this.queue[0]; - var uploaded = false; - if (item && !item._destroyed) { - for (var i = 0, len = this.uploadHooks.length; i < len; i++) { - if (this.uploadHooks[i](this.uploadHookHelper, item)) { - this.queue.shift(); - uploaded = true; - break; - } - } - } - if (!uploaded) { - this.queue.shift(); - } - } - // We're finished - if (!this.queue.length) { - this.ticking = false; - var completes = this.completes.slice(0); - this.completes.length = 0; - for (var i = 0, len = completes.length; i < len; i++) { - completes[i](); - } - } - else { - // if we are not finished, on the next rAF do this again - Ticker.system.addOnce(this.tick, this, exports.UPDATE_PRIORITY.UTILITY); - } - }; - /** - * Adds hooks for finding items. - * - * @param {Function} addHook - Function call that takes two parameters: `item:*, queue:Array` - * function must return `true` if it was able to add item to the queue. - * @return {this} Instance of plugin for chaining. - */ - BasePrepare.prototype.registerFindHook = function (addHook) { - if (addHook) { - this.addHooks.push(addHook); - } - return this; - }; - /** - * Adds hooks for uploading items. - * - * @param {Function} uploadHook - Function call that takes two parameters: `prepare:CanvasPrepare, item:*` and - * function must return `true` if it was able to handle upload of item. - * @return {this} Instance of plugin for chaining. - */ - BasePrepare.prototype.registerUploadHook = function (uploadHook) { - if (uploadHook) { - this.uploadHooks.push(uploadHook); - } - return this; - }; - /** - * Manually add an item to the uploading queue. - * - * @param {PIXI.DisplayObject|PIXI.Container|PIXI.BaseTexture|PIXI.Texture|PIXI.Graphics|PIXI.Text|*} item - Object to - * add to the queue - * @return {this} Instance of plugin for chaining. - */ - BasePrepare.prototype.add = function (item) { - // Add additional hooks for finding elements on special - // types of objects that - for (var i = 0, len = this.addHooks.length; i < len; i++) { - if (this.addHooks[i](item, this.queue)) { - break; - } - } - // Get children recursively - if (item instanceof Container) { - for (var i = item.children.length - 1; i >= 0; i--) { - this.add(item.children[i]); - } - } - return this; - }; - /** - * Destroys the plugin, don't use after this. - * - */ - BasePrepare.prototype.destroy = function () { - if (this.ticking) { - Ticker.system.remove(this.tick, this); - } - this.ticking = false; - this.addHooks = null; - this.uploadHooks = null; - this.renderer = null; - this.completes = null; - this.queue = null; - this.limiter = null; - this.uploadHookHelper = null; - }; - return BasePrepare; - }()); - - /** - * Built-in hook to upload PIXI.Texture objects to the GPU. - * - * @private - * @param {PIXI.Renderer} renderer - instance of the webgl renderer - * @param {PIXI.BaseTexture} item - Item to check - * @return {boolean} If item was uploaded. - */ - function uploadBaseTextures(renderer, item) { - if (item instanceof BaseTexture) { - // if the texture already has a GL texture, then the texture has been prepared or rendered - // before now. If the texture changed, then the changer should be calling texture.update() which - // reuploads the texture without need for preparing it again - if (!item._glTextures[renderer.CONTEXT_UID]) { - renderer.texture.bind(item); - } - return true; - } - return false; - } - /** - * Built-in hook to upload PIXI.Graphics to the GPU. - * - * @private - * @param {PIXI.Renderer} renderer - instance of the webgl renderer - * @param {PIXI.DisplayObject} item - Item to check - * @return {boolean} If item was uploaded. - */ - function uploadGraphics(renderer, item) { - if (!(item instanceof Graphics)) { - return false; - } - var geometry = item.geometry; - // update dirty graphics to get batches - item.finishPoly(); - geometry.updateBatches(); - var batches = geometry.batches; - // upload all textures found in styles - for (var i = 0; i < batches.length; i++) { - var texture = batches[i].style.texture; - if (texture) { - uploadBaseTextures(renderer, texture.baseTexture); - } - } - // if its not batchable - update vao for particular shader - if (!geometry.batchable) { - renderer.geometry.bind(geometry, item._resolveDirectShader(renderer)); - } - return true; - } - /** - * Built-in hook to find graphics. - * - * @private - * @param {PIXI.DisplayObject} item - Display object to check - * @param {Array<*>} queue - Collection of items to upload - * @return {boolean} if a PIXI.Graphics object was found. - */ - function findGraphics(item, queue) { - if (item instanceof Graphics) { - queue.push(item); - return true; - } - return false; - } - /** - * The prepare plugin provides renderer-specific plugins for pre-rendering DisplayObjects. These plugins are useful for - * asynchronously preparing and uploading to the GPU assets, textures, graphics waiting to be displayed. - * - * Do not instantiate this plugin directly. It is available from the `renderer.plugins` property. - * See {@link PIXI.CanvasRenderer#plugins} or {@link PIXI.Renderer#plugins}. - * @example - * // Create a new application - * const app = new PIXI.Application(); - * document.body.appendChild(app.view); - * - * // Don't start rendering right away - * app.stop(); - * - * // create a display object - * const rect = new PIXI.Graphics() - * .beginFill(0x00ff00) - * .drawRect(40, 40, 200, 200); - * - * // Add to the stage - * app.stage.addChild(rect); - * - * // Don't start rendering until the graphic is uploaded to the GPU - * app.renderer.plugins.prepare.upload(app.stage, () => { - * app.start(); - * }); - * - * @class - * @extends PIXI.BasePrepare - * @memberof PIXI - */ - var Prepare = /** @class */ (function (_super) { - __extends$8(Prepare, _super); - /** - * @param {PIXI.Renderer} renderer - A reference to the current renderer - */ - function Prepare(renderer) { - var _this = _super.call(this, renderer) || this; - _this.uploadHookHelper = _this.renderer; - // Add textures and graphics to upload - _this.registerFindHook(findGraphics); - _this.registerUploadHook(uploadBaseTextures); - _this.registerUploadHook(uploadGraphics); - return _this; - } - return Prepare; - }(BasePrepare)); - - /** - * TimeLimiter limits the number of items handled by a {@link PIXI.BasePrepare} to a specified - * number of milliseconds per frame. - * - * @class - * @memberof PIXI - */ - var TimeLimiter = /** @class */ (function () { - /** - * @param {number} maxMilliseconds - The maximum milliseconds that can be spent preparing items each frame. - */ - function TimeLimiter(maxMilliseconds) { - /** - * The maximum milliseconds that can be spent preparing items each frame. - * @type {number} - * @private - */ - this.maxMilliseconds = maxMilliseconds; - /** - * The start time of the current frame. - * @type {number} - * @private - */ - this.frameStart = 0; - } - /** - * Resets any counting properties to start fresh on a new frame. - */ - TimeLimiter.prototype.beginFrame = function () { - this.frameStart = Date.now(); - }; - /** - * Checks to see if another item can be uploaded. This should only be called once per item. - * @return {boolean} If the item is allowed to be uploaded. - */ - TimeLimiter.prototype.allowedToUpload = function () { - return Date.now() - this.frameStart < this.maxMilliseconds; - }; - return TimeLimiter; - }()); - - /*! - * @pixi/spritesheet - v5.3.3 - * Compiled Tue, 04 Aug 2020 16:23:09 UTC - * - * @pixi/spritesheet is licensed under the MIT License. - * http://www.opensource.org/licenses/mit-license - */ - - /** - * Utility class for maintaining reference to a collection - * of Textures on a single Spritesheet. - * - * To access a sprite sheet from your code pass its JSON data file to Pixi's loader: - * - * ```js - * PIXI.Loader.shared.add("images/spritesheet.json").load(setup); - * - * function setup() { - * let sheet = PIXI.Loader.shared.resources["images/spritesheet.json"].spritesheet; - * ... - * } - * ``` - * With the `sheet.textures` you can create Sprite objects,`sheet.animations` can be used to create an AnimatedSprite. - * - * Sprite sheets can be packed using tools like {@link https://codeandweb.com/texturepacker|TexturePacker}, - * {@link https://renderhjs.net/shoebox/|Shoebox} or {@link https://github.com/krzysztof-o/spritesheet.js|Spritesheet.js}. - * Default anchor points (see {@link PIXI.Texture#defaultAnchor}) and grouping of animation sprites are currently only - * supported by TexturePacker. - * - * @class - * @memberof PIXI - */ - var Spritesheet = /** @class */ (function () { - /** - * @param {PIXI.BaseTexture|PIXI.Texture} baseTexture - Reference to the source BaseTexture object. - * @param {Object} data - Spritesheet image data. - * @param {string} [resolutionFilename] - The filename to consider when determining - * the resolution of the spritesheet. If not provided, the imageUrl will - * be used on the BaseTexture. - */ - function Spritesheet(texture, data, resolutionFilename) { - if (resolutionFilename === void 0) { resolutionFilename = null; } - /** - * Reference to original source image from the Loader. This reference is retained so we - * can destroy the Texture later on. It is never used internally. - * @type {PIXI.Texture} - * @private - */ - this._texture = texture instanceof Texture ? texture : null; - /** - * Reference to ths source texture. - * @type {PIXI.BaseTexture} - */ - this.baseTexture = texture instanceof BaseTexture ? texture : this._texture.baseTexture; - /** - * A map containing all textures of the sprite sheet. - * Can be used to create a {@link PIXI.Sprite|Sprite}: - * ```js - * new PIXI.Sprite(sheet.textures["image.png"]); - * ``` - * @member {Object} - */ - this.textures = {}; - /** - * A map containing the textures for each animation. - * Can be used to create an {@link PIXI.AnimatedSprite|AnimatedSprite}: - * ```js - * new PIXI.AnimatedSprite(sheet.animations["anim_name"]) - * ``` - * @member {Object} - */ - this.animations = {}; - /** - * Reference to the original JSON data. - * @type {Object} - */ - this.data = data; - var resource = this.baseTexture.resource; - /** - * The resolution of the spritesheet. - * @type {number} - */ - this.resolution = this._updateResolution(resolutionFilename || (resource ? resource.url : null)); - /** - * Map of spritesheet frames. - * @type {Object} - * @private - */ - this._frames = this.data.frames; - /** - * Collection of frame names. - * @type {string[]} - * @private - */ - this._frameKeys = Object.keys(this._frames); - /** - * Current batch index being processed. - * @type {number} - * @private - */ - this._batchIndex = 0; - /** - * Callback when parse is completed. - * @type {Function} - * @private - */ - this._callback = null; - } - /** - * Generate the resolution from the filename or fallback - * to the meta.scale field of the JSON data. - * - * @private - * @param {string} resolutionFilename - The filename to use for resolving - * the default resolution. - * @return {number} Resolution to use for spritesheet. - */ - Spritesheet.prototype._updateResolution = function (resolutionFilename) { - if (resolutionFilename === void 0) { resolutionFilename = null; } - var scale = this.data.meta.scale; - // Use a defaultValue of `null` to check if a url-based resolution is set - var resolution = getResolutionOfUrl(resolutionFilename, null); - // No resolution found via URL - if (resolution === null) { - // Use the scale value or default to 1 - resolution = scale !== undefined ? parseFloat(scale) : 1; - } - // For non-1 resolutions, update baseTexture - if (resolution !== 1) { - this.baseTexture.setResolution(resolution); - } - return resolution; - }; - /** - * Parser spritesheet from loaded data. This is done asynchronously - * to prevent creating too many Texture within a single process. - * - * @param {Function} callback - Callback when complete returns - * a map of the Textures for this spritesheet. - */ - Spritesheet.prototype.parse = function (callback) { - this._batchIndex = 0; - this._callback = callback; - if (this._frameKeys.length <= Spritesheet.BATCH_SIZE) { - this._processFrames(0); - this._processAnimations(); - this._parseComplete(); - } - else { - this._nextBatch(); - } - }; - /** - * Process a batch of frames - * - * @private - * @param {number} initialFrameIndex - The index of frame to start. - */ - Spritesheet.prototype._processFrames = function (initialFrameIndex) { - var frameIndex = initialFrameIndex; - var maxFrames = Spritesheet.BATCH_SIZE; - while (frameIndex - initialFrameIndex < maxFrames && frameIndex < this._frameKeys.length) { - var i = this._frameKeys[frameIndex]; - var data = this._frames[i]; - var rect = data.frame; - if (rect) { - var frame = null; - var trim = null; - var sourceSize = data.trimmed !== false && data.sourceSize - ? data.sourceSize : data.frame; - var orig = new Rectangle(0, 0, Math.floor(sourceSize.w) / this.resolution, Math.floor(sourceSize.h) / this.resolution); - if (data.rotated) { - frame = new Rectangle(Math.floor(rect.x) / this.resolution, Math.floor(rect.y) / this.resolution, Math.floor(rect.h) / this.resolution, Math.floor(rect.w) / this.resolution); - } - else { - frame = new Rectangle(Math.floor(rect.x) / this.resolution, Math.floor(rect.y) / this.resolution, Math.floor(rect.w) / this.resolution, Math.floor(rect.h) / this.resolution); - } - // Check to see if the sprite is trimmed - if (data.trimmed !== false && data.spriteSourceSize) { - trim = new Rectangle(Math.floor(data.spriteSourceSize.x) / this.resolution, Math.floor(data.spriteSourceSize.y) / this.resolution, Math.floor(rect.w) / this.resolution, Math.floor(rect.h) / this.resolution); - } - this.textures[i] = new Texture(this.baseTexture, frame, orig, trim, data.rotated ? 2 : 0, data.anchor); - // lets also add the frame to pixi's global cache for 'from' and 'fromLoader' functions - Texture.addToCache(this.textures[i], i); - } - frameIndex++; - } - }; - /** - * Parse animations config - * - * @private - */ - Spritesheet.prototype._processAnimations = function () { - var animations = this.data.animations || {}; - for (var animName in animations) { - this.animations[animName] = []; - for (var i = 0; i < animations[animName].length; i++) { - var frameName = animations[animName][i]; - this.animations[animName].push(this.textures[frameName]); - } - } - }; - /** - * The parse has completed. - * - * @private - */ - Spritesheet.prototype._parseComplete = function () { - var callback = this._callback; - this._callback = null; - this._batchIndex = 0; - callback.call(this, this.textures); - }; - /** - * Begin the next batch of textures. - * - * @private - */ - Spritesheet.prototype._nextBatch = function () { - var _this = this; - this._processFrames(this._batchIndex * Spritesheet.BATCH_SIZE); - this._batchIndex++; - setTimeout(function () { - if (_this._batchIndex * Spritesheet.BATCH_SIZE < _this._frameKeys.length) { - _this._nextBatch(); - } - else { - _this._processAnimations(); - _this._parseComplete(); - } - }, 0); - }; - /** - * Destroy Spritesheet and don't use after this. - * - * @param {boolean} [destroyBase=false] - Whether to destroy the base texture as well - */ - Spritesheet.prototype.destroy = function (destroyBase) { - var _a; - if (destroyBase === void 0) { destroyBase = false; } - for (var i in this.textures) { - this.textures[i].destroy(); - } - this._frames = null; - this._frameKeys = null; - this.data = null; - this.textures = null; - if (destroyBase) { - (_a = this._texture) === null || _a === void 0 ? void 0 : _a.destroy(); - this.baseTexture.destroy(); - } - this._texture = null; - this.baseTexture = null; - }; - /** - * The maximum number of Textures to build per process. - * - * @type {number} - * @default 1000 - */ - Spritesheet.BATCH_SIZE = 1000; - return Spritesheet; - }()); - - /** - * {@link PIXI.Loader Loader} middleware for loading texture atlases that have been created with - * TexturePacker or similar JSON-based spritesheet. - * - * This middleware automatically generates Texture resources. - * - * @class - * @memberof PIXI - * @implements PIXI.ILoaderPlugin - */ - var SpritesheetLoader = /** @class */ (function () { - function SpritesheetLoader() { - } - /** - * Called after a resource is loaded. - * @see PIXI.Loader.loaderMiddleware - * @param {PIXI.LoaderResource} resource - * @param {function} next - */ - SpritesheetLoader.use = function (resource, next) { - // because this is middleware, it execute in loader context. `this` = loader - var loader = this; - var imageResourceName = resource.name + "_image"; - // skip if no data, its not json, it isn't spritesheet data, or the image resource already exists - if (!resource.data - || resource.type !== LoaderResource.TYPE.JSON - || !resource.data.frames - || loader.resources[imageResourceName]) { - next(); - return; - } - var loadOptions = { - crossOrigin: resource.crossOrigin, - metadata: resource.metadata.imageMetadata, - parentResource: resource, - }; - var resourcePath = SpritesheetLoader.getResourcePath(resource, loader.baseUrl); - // load the image for this sheet - loader.add(imageResourceName, resourcePath, loadOptions, function onImageLoad(res) { - if (res.error) { - next(res.error); - return; - } - var spritesheet = new Spritesheet(res.texture, resource.data, resource.url); - spritesheet.parse(function () { - resource.spritesheet = spritesheet; - resource.textures = spritesheet.textures; - next(); - }); - }); - }; - /** - * Get the spritesheets root path - * @param {PIXI.LoaderResource} resource - Resource to check path - * @param {string} baseUrl - Base root url - */ - SpritesheetLoader.getResourcePath = function (resource, baseUrl) { - // Prepend url path unless the resource image is a data url - if (resource.isDataUrl) { - return resource.data.meta.image; - } - return url.resolve(resource.url.replace(baseUrl, ''), resource.data.meta.image); - }; - return SpritesheetLoader; - }()); - - /*! - * @pixi/sprite-tiling - v5.3.3 - * Compiled Tue, 04 Aug 2020 16:23:09 UTC - * - * @pixi/sprite-tiling is licensed under the MIT License. - * http://www.opensource.org/licenses/mit-license - */ - - /*! ***************************************************************************** - Copyright (c) Microsoft Corporation. All rights reserved. - Licensed under the Apache License, Version 2.0 (the "License"); you may not use - this file except in compliance with the License. You may obtain a copy of the - License at http://www.apache.org/licenses/LICENSE-2.0 + THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH + REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY + AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, + INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM + LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR + OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR + PERFORMANCE OF THIS SOFTWARE. + ***************************************************************************** */ + /* global Reflect, Promise */ - THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED - WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, - MERCHANTABLITY OR NON-INFRINGEMENT. + var extendStatics$g = function(d, b) { + extendStatics$g = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) { if (b.hasOwnProperty(p)) { d[p] = b[p]; } } }; + return extendStatics$g(d, b); + }; - See the Apache Version 2.0 License for specific language governing permissions - and limitations under the License. - ***************************************************************************** */ - /* global Reflect, Promise */ + function __extends$g(d, b) { + extendStatics$g(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + } - var extendStatics$9 = function(d, b) { - extendStatics$9 = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) { if (b.hasOwnProperty(p)) { d[p] = b[p]; } } }; - return extendStatics$9(d, b); - }; + function __awaiter(thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + } - function __extends$9(d, b) { - extendStatics$9(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - } - - var tempPoint$1 = new Point(); - /** - * A tiling sprite is a fast way of rendering a tiling image - * - * @class - * @extends PIXI.Sprite - * @memberof PIXI - */ - var TilingSprite = /** @class */ (function (_super) { - __extends$9(TilingSprite, _super); - /** - * @param {PIXI.Texture} texture - the texture of the tiling sprite - * @param {number} [width=100] - the width of the tiling sprite - * @param {number} [height=100] - the height of the tiling sprite - */ - function TilingSprite(texture, width, height) { - if (width === void 0) { width = 100; } - if (height === void 0) { height = 100; } - var _this = _super.call(this, texture) || this; - /** - * Tile transform - * - * @member {PIXI.Transform} - */ - _this.tileTransform = new Transform(); - /** - * The with of the tiling sprite - * - * @member {number} - * @private - */ - _this._width = width; - /** - * The height of the tiling sprite - * - * @member {number} - * @private - */ - _this._height = height; - /** - * matrix that is applied to UV to get the coords in Texture normalized space to coords in BaseTexture space - * - * @member {PIXI.TextureMatrix} - */ - _this.uvMatrix = texture.uvMatrix || new TextureMatrix(texture); - /** - * Plugin that is responsible for rendering this element. - * Allows to customize the rendering process without overriding '_render' method. - * - * @member {string} - * @default 'tilingSprite' - */ - _this.pluginName = 'tilingSprite'; - /** - * Whether or not anchor affects uvs - * - * @member {boolean} - * @default false - */ - _this.uvRespectAnchor = false; - return _this; - } - Object.defineProperty(TilingSprite.prototype, "clampMargin", { - /** - * Changes frame clamping in corresponding textureTransform, shortcut - * Change to -0.5 to add a pixel to the edge, recommended for transparent trimmed textures in atlas - * - * @default 0.5 - * @member {number} - */ - get: function () { - return this.uvMatrix.clampMargin; - }, - set: function (value) { - this.uvMatrix.clampMargin = value; - this.uvMatrix.update(true); - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(TilingSprite.prototype, "tileScale", { - /** - * The scaling of the image that is being tiled - * - * @member {PIXI.ObservablePoint} - */ - get: function () { - return this.tileTransform.scale; - }, - set: function (value) { - this.tileTransform.scale.copyFrom(value); - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(TilingSprite.prototype, "tilePosition", { - /** - * The offset of the image that is being tiled - * - * @member {PIXI.ObservablePoint} - */ - get: function () { - return this.tileTransform.position; - }, - set: function (value) { - this.tileTransform.position.copyFrom(value); - }, - enumerable: false, - configurable: true - }); - /** - * @protected - */ - TilingSprite.prototype._onTextureUpdate = function () { - if (this.uvMatrix) { - this.uvMatrix.texture = this._texture; - } - this._cachedTint = 0xFFFFFF; - }; - /** - * Renders the object using the WebGL renderer - * - * @protected - * @param {PIXI.Renderer} renderer - The renderer - */ - TilingSprite.prototype._render = function (renderer) { - // tweak our texture temporarily.. - var texture = this._texture; - if (!texture || !texture.valid) { - return; - } - this.tileTransform.updateLocalTransform(); - this.uvMatrix.update(); - renderer.batch.setObjectRenderer(renderer.plugins[this.pluginName]); - renderer.plugins[this.pluginName].render(this); - }; - /** - * Updates the bounds of the tiling sprite. - * - * @protected - */ - TilingSprite.prototype._calculateBounds = function () { - var minX = this._width * -this._anchor._x; - var minY = this._height * -this._anchor._y; - var maxX = this._width * (1 - this._anchor._x); - var maxY = this._height * (1 - this._anchor._y); - this._bounds.addFrame(this.transform, minX, minY, maxX, maxY); - }; - /** - * Gets the local bounds of the sprite object. - * - * @param {PIXI.Rectangle} rect - The output rectangle. - * @return {PIXI.Rectangle} The bounds. - */ - TilingSprite.prototype.getLocalBounds = function (rect) { - // we can do a fast local bounds if the sprite has no children! - if (this.children.length === 0) { - this._bounds.minX = this._width * -this._anchor._x; - this._bounds.minY = this._height * -this._anchor._y; - this._bounds.maxX = this._width * (1 - this._anchor._x); - this._bounds.maxY = this._height * (1 - this._anchor._y); - if (!rect) { - if (!this._localBoundsRect) { - this._localBoundsRect = new Rectangle(); - } - rect = this._localBoundsRect; - } - return this._bounds.getRectangle(rect); - } - return _super.prototype.getLocalBounds.call(this, rect); - }; - /** - * Checks if a point is inside this tiling sprite. - * - * @param {PIXI.IPointData} point - the point to check - * @return {boolean} Whether or not the sprite contains the point. - */ - TilingSprite.prototype.containsPoint = function (point) { - this.worldTransform.applyInverse(point, tempPoint$1); - var width = this._width; - var height = this._height; - var x1 = -width * this.anchor._x; - if (tempPoint$1.x >= x1 && tempPoint$1.x < x1 + width) { - var y1 = -height * this.anchor._y; - if (tempPoint$1.y >= y1 && tempPoint$1.y < y1 + height) { - return true; - } - } - return false; - }; - /** - * Destroys this sprite and optionally its texture and children - * - * @param {object|boolean} [options] - Options parameter. A boolean will act as if all options - * have been set to that value - * @param {boolean} [options.children=false] - if set to true, all the children will have their destroy - * method called as well. 'options' will be passed on to those calls. - * @param {boolean} [options.texture=false] - Should it destroy the current texture of the sprite as well - * @param {boolean} [options.baseTexture=false] - Should it destroy the base texture of the sprite as well - */ - TilingSprite.prototype.destroy = function (options) { - _super.prototype.destroy.call(this, options); - this.tileTransform = null; - this.uvMatrix = null; - }; - /** - * Helper function that creates a new tiling sprite based on the source you provide. - * The source can be - frame id, image url, video url, canvas element, video element, base texture - * - * @static - * @param {string|PIXI.Texture|HTMLCanvasElement|HTMLVideoElement} source - Source to create texture from - * @param {Object} options - See {@link PIXI.BaseTexture}'s constructor for options. - * @param {number} options.width - required width of the tiling sprite - * @param {number} options.height - required height of the tiling sprite - * @return {PIXI.TilingSprite} The newly created texture - */ - TilingSprite.from = function (source, options) { - // Deprecated - if (typeof options === 'number') { - deprecation('5.3.0', 'TilingSprite.from use options instead of width and height args'); - // eslint-disable-next-line prefer-rest-params - options = { width: options, height: arguments[2] }; - } - return new TilingSprite(Texture.from(source, options), options.width, options.height); - }; - Object.defineProperty(TilingSprite.prototype, "width", { - /** - * The width of the sprite, setting this will actually modify the scale to achieve the value set - * - * @member {number} - */ - get: function () { - return this._width; - }, - set: function (value) { - this._width = value; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(TilingSprite.prototype, "height", { - /** - * The height of the TilingSprite, setting this will actually modify the scale to achieve the value set - * - * @member {number} - */ - get: function () { - return this._height; - }, - set: function (value) { - this._height = value; - }, - enumerable: false, - configurable: true - }); - return TilingSprite; - }(Sprite)); - - var vertex$2 = "attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\nuniform mat3 translationMatrix;\nuniform mat3 uTransform;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n vTextureCoord = (uTransform * vec3(aTextureCoord, 1.0)).xy;\n}\n"; - - var fragment$2 = "varying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\nuniform vec4 uColor;\nuniform mat3 uMapCoord;\nuniform vec4 uClampFrame;\nuniform vec2 uClampOffset;\n\nvoid main(void)\n{\n vec2 coord = vTextureCoord - floor(vTextureCoord - uClampOffset);\n coord = (uMapCoord * vec3(coord, 1.0)).xy;\n coord = clamp(coord, uClampFrame.xy, uClampFrame.zw);\n\n vec4 texSample = texture2D(uSampler, coord);\n gl_FragColor = texSample * uColor;\n}\n"; - - var fragmentSimple = "varying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\nuniform vec4 uColor;\n\nvoid main(void)\n{\n vec4 sample = texture2D(uSampler, vTextureCoord);\n gl_FragColor = sample * uColor;\n}\n"; - - var tempMat$1 = new Matrix(); - /** - * WebGL renderer plugin for tiling sprites - * - * @class - * @memberof PIXI - * @extends PIXI.ObjectRenderer - */ - var TilingSpriteRenderer = /** @class */ (function (_super) { - __extends$9(TilingSpriteRenderer, _super); - /** - * constructor for renderer - * - * @param {PIXI.Renderer} renderer - The renderer this tiling awesomeness works for. - */ - function TilingSpriteRenderer(renderer) { - var _this = _super.call(this, renderer) || this; - var uniforms = { globals: _this.renderer.globalUniforms }; - _this.shader = Shader.from(vertex$2, fragment$2, uniforms); - _this.simpleShader = Shader.from(vertex$2, fragmentSimple, uniforms); - _this.quad = new QuadUv(); - /** - * The WebGL state in which this renderer will work. - * - * @member {PIXI.State} - * @readonly - */ - _this.state = State.for2d(); - return _this; - } - /** - * - * @param {PIXI.TilingSprite} ts - tilingSprite to be rendered - */ - TilingSpriteRenderer.prototype.render = function (ts) { - var renderer = this.renderer; - var quad = this.quad; - var vertices = quad.vertices; - vertices[0] = vertices[6] = (ts._width) * -ts.anchor.x; - vertices[1] = vertices[3] = ts._height * -ts.anchor.y; - vertices[2] = vertices[4] = (ts._width) * (1.0 - ts.anchor.x); - vertices[5] = vertices[7] = ts._height * (1.0 - ts.anchor.y); - if (ts.uvRespectAnchor) { - vertices = quad.uvs; - vertices[0] = vertices[6] = -ts.anchor.x; - vertices[1] = vertices[3] = -ts.anchor.y; - vertices[2] = vertices[4] = 1.0 - ts.anchor.x; - vertices[5] = vertices[7] = 1.0 - ts.anchor.y; - } - quad.invalidate(); - var tex = ts._texture; - var baseTex = tex.baseTexture; - var lt = ts.tileTransform.localTransform; - var uv = ts.uvMatrix; - var isSimple = baseTex.isPowerOfTwo - && tex.frame.width === baseTex.width && tex.frame.height === baseTex.height; - // auto, force repeat wrapMode for big tiling textures - if (isSimple) { - if (!baseTex._glTextures[renderer.CONTEXT_UID]) { - if (baseTex.wrapMode === exports.WRAP_MODES.CLAMP) { - baseTex.wrapMode = exports.WRAP_MODES.REPEAT; - } - } - else { - isSimple = baseTex.wrapMode !== exports.WRAP_MODES.CLAMP; - } - } - var shader = isSimple ? this.simpleShader : this.shader; - var w = tex.width; - var h = tex.height; - var W = ts._width; - var H = ts._height; - tempMat$1.set(lt.a * w / W, lt.b * w / H, lt.c * h / W, lt.d * h / H, lt.tx / W, lt.ty / H); - // that part is the same as above: - // tempMat.identity(); - // tempMat.scale(tex.width, tex.height); - // tempMat.prepend(lt); - // tempMat.scale(1.0 / ts._width, 1.0 / ts._height); - tempMat$1.invert(); - if (isSimple) { - tempMat$1.prepend(uv.mapCoord); - } - else { - shader.uniforms.uMapCoord = uv.mapCoord.toArray(true); - shader.uniforms.uClampFrame = uv.uClampFrame; - shader.uniforms.uClampOffset = uv.uClampOffset; - } - shader.uniforms.uTransform = tempMat$1.toArray(true); - shader.uniforms.uColor = premultiplyTintToRgba(ts.tint, ts.worldAlpha, shader.uniforms.uColor, baseTex.alphaMode); - shader.uniforms.translationMatrix = ts.transform.worldTransform.toArray(true); - shader.uniforms.uSampler = tex; - renderer.shader.bind(shader); - renderer.geometry.bind(quad); - this.state.blendMode = correctBlendMode(ts.blendMode, baseTex.alphaMode); - renderer.state.set(this.state); - renderer.geometry.draw(this.renderer.gl.TRIANGLES, 6, 0); - }; - return TilingSpriteRenderer; - }(ObjectRenderer)); - - /*! - * @pixi/mesh - v5.3.3 - * Compiled Tue, 04 Aug 2020 16:23:09 UTC - * - * @pixi/mesh is licensed under the MIT License. - * http://www.opensource.org/licenses/mit-license - */ - - /*! ***************************************************************************** - Copyright (c) Microsoft Corporation. All rights reserved. - Licensed under the Apache License, Version 2.0 (the "License"); you may not use - this file except in compliance with the License. You may obtain a copy of the - License at http://www.apache.org/licenses/LICENSE-2.0 + function __generator(thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) { throw t[1]; } return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) { throw new TypeError("Generator is already executing."); } + while (_) { try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) { return t; } + if (y = 0, t) { op = [op[0] & 2, t.value]; } + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) { _.ops.pop(); } + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } } + if (op[0] & 5) { throw op[1]; } return { value: op[0] ? op[1] : void 0, done: true }; + } + } + + /** + * Resource that fetches texture data over the network and stores it in a buffer. + * @class + * @extends PIXI.Resource + * @memberof PIXI + */ + var BlobResource = /** @class */ (function (_super) { + __extends$g(BlobResource, _super); + /** + * @param {string} source - the URL of the texture file + * @param {PIXI.IBlobOptions} options + * @param {boolean}[options.autoLoad] - whether to fetch the data immediately; + * you can fetch it later via {@link BlobResource#load} + * @param {boolean}[options.width] - the width in pixels. + * @param {boolean}[options.height] - the height in pixels. + */ + function BlobResource(source, options) { + if (options === void 0) { options = { width: 1, height: 1, autoLoad: true }; } + var _this = this; + var origin; + var data; + if (typeof source === 'string') { + origin = source; + data = new Uint8Array(); + } + else { + origin = null; + data = source; + } + _this = _super.call(this, data, options) || this; + /** + * The URL of the texture file + * @member {string} + */ + _this.origin = origin; + /** + * The viewable buffer on the data + * @member {ViewableBuffer} + */ + // HINT: BlobResource allows "null" sources, assuming the child class provides an alternative + _this.buffer = data ? new ViewableBuffer(data) : null; + // Allow autoLoad = "undefined" still load the resource by default + if (_this.origin && options.autoLoad !== false) { + _this.load(); + } + if (data && data.length) { + _this.loaded = true; + _this.onBlobLoaded(_this.buffer.rawBinaryData); + } + return _this; + } + BlobResource.prototype.onBlobLoaded = function (_data) { + // TODO: Override this method + }; + /** Loads the blob */ + BlobResource.prototype.load = function () { + return __awaiter(this, void 0, Promise, function () { + var response, blob, arrayBuffer; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: return [4 /*yield*/, fetch(this.origin)]; + case 1: + response = _a.sent(); + return [4 /*yield*/, response.blob()]; + case 2: + blob = _a.sent(); + return [4 /*yield*/, blob.arrayBuffer()]; + case 3: + arrayBuffer = _a.sent(); + this.data = new Uint32Array(arrayBuffer); + this.buffer = new ViewableBuffer(arrayBuffer); + this.loaded = true; + this.onBlobLoaded(arrayBuffer); + this.update(); + return [2 /*return*/, this]; + } + }); + }); + }; + return BlobResource; + }(BufferResource)); + + /** + * Resource for compressed texture formats, as follows: S3TC/DXTn (& their sRGB formats), ATC, ASTC, ETC 1/2, PVRTC. + * + * Compressed textures improve performance when rendering is texture-bound. The texture data stays compressed in + * graphics memory, increasing memory locality and speeding up texture fetches. These formats can also be used to store + * more detail in the same amount of memory. + * + * For most developers, container file formats are a better abstraction instead of directly handling raw texture + * data. PixiJS provides native support for the following texture file formats (via {@link PIXI.Loader}): + * + * **.dds** - the DirectDraw Surface file format stores DXTn (DXT-1,3,5) data. See {@link PIXI.DDSLoader} + * **.ktx** - the Khronos Texture Container file format supports storing all the supported WebGL compression formats. + * See {@link PIXI.KTXLoader}. + * **.basis** - the BASIS supercompressed file format stores texture data in an internal format that is transcoded + * to the compression format supported on the device at _runtime_. It also supports transcoding into a uncompressed + * format as a fallback; you must install the `@pixi/basis-loader`, `@pixi/basis-transcoder` packages separately to + * use these files. See {@link PIXI.BasisLoader}. + * + * The loaders for the aforementioned formats use `CompressedTextureResource` internally. It is strongly suggested that + * they be used instead. + * + * ## Working directly with CompressedTextureResource + * + * Since `CompressedTextureResource` inherits `BlobResource`, you can provide it a URL pointing to a file containing + * the raw texture data (with no file headers!): + * + * ```js + * // The resource backing the texture data for your textures. + * // NOTE: You can also provide a ArrayBufferView instead of a URL. This is used when loading data from a container file + * // format such as KTX, DDS, or BASIS. + * const compressedResource = new PIXI.CompressedTextureResource("bunny.dxt5", { + * format: PIXI.INTERNAL_FORMATS.COMPRESSED_RGBA_S3TC_DXT5_EXT, + * width: 256, + * height: 256 + * }); + * + * // You can create a base-texture to the cache, so that future `Texture`s can be created using the `Texture.from` API. + * const baseTexture = new PIXI.BaseTexture(compressedResource, { pmaMode: PIXI.ALPHA_MODES.NPM }); + * + * // Create a Texture to add to the TextureCache + * const texture = new PIXI.Texture(baseTexture); + * + * // Add baseTexture & texture to the global texture cache + * PIXI.BaseTexture.addToCache(baseTexture, "bunny.dxt5"); + * PIXI.Texture.addToCache(texture, "bunny.dxt5"); + * ``` + * @memberof PIXI + */ + var CompressedTextureResource = /** @class */ (function (_super) { + __extends$g(CompressedTextureResource, _super); + /** + * @param source - the buffer/URL holding the compressed texture data + * @param options + * @param {PIXI.INTERNAL_FORMATS} options.format - the compression format + * @param {number} options.width - the image width in pixels. + * @param {number} options.height - the image height in pixels. + * @param {number} [options.level=1] - the mipmap levels stored in the compressed texture, including level 0. + * @param {number} [options.levelBuffers] - the buffers for each mipmap level. `CompressedTextureResource` can allows you + * to pass `null` for `source`, for cases where each level is stored in non-contiguous memory. + */ + function CompressedTextureResource(source, options) { + var _this = _super.call(this, source, options) || this; + _this.format = options.format; + _this.levels = options.levels || 1; + _this._width = options.width; + _this._height = options.height; + _this._extension = CompressedTextureResource._formatToExtension(_this.format); + if (options.levelBuffers || _this.buffer) { + // ViewableBuffer doesn't support byteOffset :-( so allow source to be Uint8Array + _this._levelBuffers = options.levelBuffers + || CompressedTextureResource._createLevelBuffers(source instanceof Uint8Array ? source : _this.buffer.uint8View, _this.format, _this.levels, 4, 4, // PVRTC has 8x4 blocks in 2bpp mode + _this.width, _this.height); + } + return _this; + } + /** + * @override + * @param renderer - A reference to the current renderer + * @param _texture - the texture + * @param _glTexture - texture instance for this webgl context + */ + CompressedTextureResource.prototype.upload = function (renderer, _texture, _glTexture) { + var gl = renderer.gl; + var extension = renderer.context.extensions[this._extension]; + if (!extension) { + throw new Error(this._extension + " textures are not supported on the current machine"); + } + if (!this._levelBuffers) { + // Do not try to upload data before BlobResource loads, unless the levelBuffers were provided directly! + return false; + } + for (var i = 0, j = this.levels; i < j; i++) { + var _a = this._levelBuffers[i], levelID = _a.levelID, levelWidth = _a.levelWidth, levelHeight = _a.levelHeight, levelBuffer = _a.levelBuffer; + gl.compressedTexImage2D(gl.TEXTURE_2D, levelID, this.format, levelWidth, levelHeight, 0, levelBuffer); + } + return true; + }; + /** @protected */ + CompressedTextureResource.prototype.onBlobLoaded = function () { + this._levelBuffers = CompressedTextureResource._createLevelBuffers(this.buffer.uint8View, this.format, this.levels, 4, 4, // PVRTC has 8x4 blocks in 2bpp mode + this.width, this.height); + }; + /** + * Returns the key (to ContextSystem#extensions) for the WebGL extension supporting the compression format + * @private + * @param format - the compression format to get the extension for. + */ + CompressedTextureResource._formatToExtension = function (format) { + if (format >= 0x83F0 && format <= 0x83F3) { + return 's3tc'; + } + else if (format >= 0x9270 && format <= 0x9279) { + return 'etc'; + } + else if (format >= 0x8C00 && format <= 0x8C03) { + return 'pvrtc'; + } + else if (format >= 0x8D64) { + return 'etc1'; + } + else if (format >= 0x8C92 && format <= 0x87EE) { + return 'atc'; + } + throw new Error('Invalid (compressed) texture format given!'); + }; + /** + * Pre-creates buffer views for each mipmap level + * @private + * @param buffer - + * @param format - compression formats + * @param levels - mipmap levels + * @param blockWidth - + * @param blockHeight - + * @param imageWidth - width of the image in pixels + * @param imageHeight - height of the image in pixels + */ + CompressedTextureResource._createLevelBuffers = function (buffer, format, levels, blockWidth, blockHeight, imageWidth, imageHeight) { + // The byte-size of the first level buffer + var buffers = new Array(levels); + var offset = buffer.byteOffset; + var levelWidth = imageWidth; + var levelHeight = imageHeight; + var alignedLevelWidth = (levelWidth + blockWidth - 1) & ~(blockWidth - 1); + var alignedLevelHeight = (levelHeight + blockHeight - 1) & ~(blockHeight - 1); + var levelSize = alignedLevelWidth * alignedLevelHeight * INTERNAL_FORMAT_TO_BYTES_PER_PIXEL[format]; + for (var i = 0; i < levels; i++) { + buffers[i] = { + levelID: i, + levelWidth: levels > 1 ? levelWidth : alignedLevelWidth, + levelHeight: levels > 1 ? levelHeight : alignedLevelHeight, + levelBuffer: new Uint8Array(buffer.buffer, offset, levelSize) + }; + offset += levelSize; + // Calculate levelBuffer dimensions for next iteration + levelWidth = (levelWidth >> 1) || 1; + levelHeight = (levelHeight >> 1) || 1; + alignedLevelWidth = (levelWidth + blockWidth - 1) & ~(blockWidth - 1); + alignedLevelHeight = (levelHeight + blockHeight - 1) & ~(blockHeight - 1); + levelSize = alignedLevelWidth * alignedLevelHeight * INTERNAL_FORMAT_TO_BYTES_PER_PIXEL[format]; + } + return buffers; + }; + return CompressedTextureResource; + }(BlobResource)); + + /* eslint-enable camelcase */ + /** + * Loader plugin for handling compressed textures for all platforms. + * @class + * @memberof PIXI + * @implements {PIXI.ILoaderPlugin} + */ + var CompressedTextureLoader = /** @class */ (function () { + function CompressedTextureLoader() { + } + /** + * Called after a compressed-textures manifest is loaded. + * + * This will then load the correct compression format for the device. Your manifest should adhere + * to the following schema: + * + * ```js + * import { INTERNAL_FORMATS } from '@pixi/constants'; + * + * type CompressedTextureManifest = { + * textures: Array<{ src: string, format?: keyof INTERNAL_FORMATS}>, + * cacheID: string; + * }; + * ``` + * + * This is an example of a .json manifest file + * + * ```json + * { + * "cacheID":"asset", + * "textures":[ + * { "src":"asset.fallback.png" }, + * { "format":"COMPRESSED_RGBA_S3TC_DXT5_EXT", "src":"asset.s3tc.ktx" }, + * { "format":"COMPRESSED_RGBA8_ETC2_EAC", "src":"asset.etc.ktx" }, + * { "format":"RGBA_PVRTC_4BPPV1_IMG", "src":"asset.pvrtc.ktx" } + * ] + * } + * ``` + */ + CompressedTextureLoader.use = function (resource, next) { + var data = resource.data; + var loader = this; + if (resource.type === exports.LoaderResource.TYPE.JSON + && data + && data.cacheID + && data.textures) { + var textures = data.textures; + var textureURL = void 0; + var fallbackURL = void 0; + // Search for an extension that holds one the formats + for (var i = 0, j = textures.length; i < j; i++) { + var texture = textures[i]; + var url_1 = texture.src; + var format = texture.format; + if (!format) { + fallbackURL = url_1; + } + if (CompressedTextureLoader.textureFormats[format]) { + textureURL = url_1; + break; + } + } + textureURL = textureURL || fallbackURL; + // Make sure we have a URL + if (!textureURL) { + next(new Error("Cannot load compressed-textures in " + resource.url + ", make sure you provide a fallback")); + return; + } + if (textureURL === resource.url) { + // Prevent infinite loops + next(new Error('URL of compressed texture cannot be the same as the manifest\'s URL')); + return; + } + var loadOptions = { + crossOrigin: resource.crossOrigin, + metadata: resource.metadata.imageMetadata, + parentResource: resource + }; + var resourcePath = url.resolve(resource.url.replace(loader.baseUrl, ''), textureURL); + var resourceName = data.cacheID; + // The appropriate loader should register the texture + loader.add(resourceName, resourcePath, loadOptions, function (res) { + if (res.error) { + next(res.error); + return; + } + var _a = res.texture, texture = _a === void 0 ? null : _a, _b = res.textures, textures = _b === void 0 ? {} : _b; + // Make sure texture/textures is assigned to parent resource + Object.assign(resource, { texture: texture, textures: textures }); + // Pass along any error + next(); + }); + } + else { + next(); + } + }; + Object.defineProperty(CompressedTextureLoader, "textureExtensions", { + /** Map of available texture extensions. */ + get: function () { + if (!CompressedTextureLoader._textureExtensions) { + // Auto-detect WebGL compressed-texture extensions + var canvas = settings$1.ADAPTER.createCanvas(); + var gl = canvas.getContext('webgl'); + if (!gl) { + console.warn('WebGL not available for compressed textures. Silently failing.'); + return {}; + } + var extensions = { + s3tc: gl.getExtension('WEBGL_compressed_texture_s3tc'), + s3tc_sRGB: gl.getExtension('WEBGL_compressed_texture_s3tc_srgb'), + etc: gl.getExtension('WEBGL_compressed_texture_etc'), + etc1: gl.getExtension('WEBGL_compressed_texture_etc1'), + pvrtc: gl.getExtension('WEBGL_compressed_texture_pvrtc') + || gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc'), + atc: gl.getExtension('WEBGL_compressed_texture_atc'), + astc: gl.getExtension('WEBGL_compressed_texture_astc') + }; + CompressedTextureLoader._textureExtensions = extensions; + } + return CompressedTextureLoader._textureExtensions; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(CompressedTextureLoader, "textureFormats", { + /** Map of available texture formats. */ + get: function () { + if (!CompressedTextureLoader._textureFormats) { + var extensions = CompressedTextureLoader.textureExtensions; + CompressedTextureLoader._textureFormats = {}; + // Assign all available compressed-texture formats + for (var extensionName in extensions) { + var extension = extensions[extensionName]; + if (!extension) { + continue; + } + Object.assign(CompressedTextureLoader._textureFormats, Object.getPrototypeOf(extension)); + } + } + return CompressedTextureLoader._textureFormats; + }, + enumerable: false, + configurable: true + }); + /** @ignore */ + CompressedTextureLoader.extension = exports.ExtensionType.Loader; + return CompressedTextureLoader; + }()); + + /** + * Creates base-textures and textures for each compressed-texture resource and adds them into the global + * texture cache. The first texture has two IDs - `${url}`, `${url}-1`; while the rest have an ID of the + * form `${url}-i`. + * @param url - the original address of the resources + * @param resources - the resources backing texture data + * @ignore + */ + function registerCompressedTextures(url, resources, metadata) { + var result = { + textures: {}, + texture: null, + }; + if (!resources) { + return result; + } + var textures = resources.map(function (resource) { + return (new Texture(new BaseTexture(resource, Object.assign({ + mipmap: exports.MIPMAP_MODES.OFF, + alphaMode: exports.ALPHA_MODES.NO_PREMULTIPLIED_ALPHA + }, metadata)))); + }); + textures.forEach(function (texture, i) { + var baseTexture = texture.baseTexture; + var cacheID = url + "-" + (i + 1); + BaseTexture.addToCache(baseTexture, cacheID); + Texture.addToCache(texture, cacheID); + if (i === 0) { + BaseTexture.addToCache(baseTexture, url); + Texture.addToCache(texture, url); + result.texture = texture; + } + result.textures[cacheID] = texture; + }); + return result; + } + + var _a$1, _b$1; + var DDS_MAGIC_SIZE = 4; + var DDS_HEADER_SIZE = 124; + var DDS_HEADER_PF_SIZE = 32; + var DDS_HEADER_DX10_SIZE = 20; + // DDS file format magic word + var DDS_MAGIC = 0x20534444; + /** + * DWORD offsets of the DDS file header fields (relative to file start). + * @ignore + */ + var DDS_FIELDS = { + SIZE: 1, + FLAGS: 2, + HEIGHT: 3, + WIDTH: 4, + MIPMAP_COUNT: 7, + PIXEL_FORMAT: 19, + }; + /** + * DWORD offsets of the DDS PIXEL_FORMAT fields. + * @ignore + */ + var DDS_PF_FIELDS = { + SIZE: 0, + FLAGS: 1, + FOURCC: 2, + RGB_BITCOUNT: 3, + R_BIT_MASK: 4, + G_BIT_MASK: 5, + B_BIT_MASK: 6, + A_BIT_MASK: 7 + }; + /** + * DWORD offsets of the DDS_HEADER_DX10 fields. + * @ignore + */ + var DDS_DX10_FIELDS = { + DXGI_FORMAT: 0, + RESOURCE_DIMENSION: 1, + MISC_FLAG: 2, + ARRAY_SIZE: 3, + MISC_FLAGS2: 4 + }; + /** + * @see https://docs.microsoft.com/en-us/windows/win32/api/dxgiformat/ne-dxgiformat-dxgi_format + * @ignore + */ + // This is way over-blown for us! Lend us a hand, and remove the ones that aren't used (but set the remaining + // ones to their correct value) + var DXGI_FORMAT; + (function (DXGI_FORMAT) { + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_UNKNOWN"] = 0] = "DXGI_FORMAT_UNKNOWN"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R32G32B32A32_TYPELESS"] = 1] = "DXGI_FORMAT_R32G32B32A32_TYPELESS"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R32G32B32A32_FLOAT"] = 2] = "DXGI_FORMAT_R32G32B32A32_FLOAT"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R32G32B32A32_UINT"] = 3] = "DXGI_FORMAT_R32G32B32A32_UINT"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R32G32B32A32_SINT"] = 4] = "DXGI_FORMAT_R32G32B32A32_SINT"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R32G32B32_TYPELESS"] = 5] = "DXGI_FORMAT_R32G32B32_TYPELESS"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R32G32B32_FLOAT"] = 6] = "DXGI_FORMAT_R32G32B32_FLOAT"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R32G32B32_UINT"] = 7] = "DXGI_FORMAT_R32G32B32_UINT"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R32G32B32_SINT"] = 8] = "DXGI_FORMAT_R32G32B32_SINT"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R16G16B16A16_TYPELESS"] = 9] = "DXGI_FORMAT_R16G16B16A16_TYPELESS"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R16G16B16A16_FLOAT"] = 10] = "DXGI_FORMAT_R16G16B16A16_FLOAT"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R16G16B16A16_UNORM"] = 11] = "DXGI_FORMAT_R16G16B16A16_UNORM"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R16G16B16A16_UINT"] = 12] = "DXGI_FORMAT_R16G16B16A16_UINT"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R16G16B16A16_SNORM"] = 13] = "DXGI_FORMAT_R16G16B16A16_SNORM"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R16G16B16A16_SINT"] = 14] = "DXGI_FORMAT_R16G16B16A16_SINT"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R32G32_TYPELESS"] = 15] = "DXGI_FORMAT_R32G32_TYPELESS"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R32G32_FLOAT"] = 16] = "DXGI_FORMAT_R32G32_FLOAT"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R32G32_UINT"] = 17] = "DXGI_FORMAT_R32G32_UINT"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R32G32_SINT"] = 18] = "DXGI_FORMAT_R32G32_SINT"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R32G8X24_TYPELESS"] = 19] = "DXGI_FORMAT_R32G8X24_TYPELESS"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_D32_FLOAT_S8X24_UINT"] = 20] = "DXGI_FORMAT_D32_FLOAT_S8X24_UINT"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS"] = 21] = "DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_X32_TYPELESS_G8X24_UINT"] = 22] = "DXGI_FORMAT_X32_TYPELESS_G8X24_UINT"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R10G10B10A2_TYPELESS"] = 23] = "DXGI_FORMAT_R10G10B10A2_TYPELESS"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R10G10B10A2_UNORM"] = 24] = "DXGI_FORMAT_R10G10B10A2_UNORM"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R10G10B10A2_UINT"] = 25] = "DXGI_FORMAT_R10G10B10A2_UINT"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R11G11B10_FLOAT"] = 26] = "DXGI_FORMAT_R11G11B10_FLOAT"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R8G8B8A8_TYPELESS"] = 27] = "DXGI_FORMAT_R8G8B8A8_TYPELESS"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R8G8B8A8_UNORM"] = 28] = "DXGI_FORMAT_R8G8B8A8_UNORM"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R8G8B8A8_UNORM_SRGB"] = 29] = "DXGI_FORMAT_R8G8B8A8_UNORM_SRGB"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R8G8B8A8_UINT"] = 30] = "DXGI_FORMAT_R8G8B8A8_UINT"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R8G8B8A8_SNORM"] = 31] = "DXGI_FORMAT_R8G8B8A8_SNORM"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R8G8B8A8_SINT"] = 32] = "DXGI_FORMAT_R8G8B8A8_SINT"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R16G16_TYPELESS"] = 33] = "DXGI_FORMAT_R16G16_TYPELESS"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R16G16_FLOAT"] = 34] = "DXGI_FORMAT_R16G16_FLOAT"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R16G16_UNORM"] = 35] = "DXGI_FORMAT_R16G16_UNORM"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R16G16_UINT"] = 36] = "DXGI_FORMAT_R16G16_UINT"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R16G16_SNORM"] = 37] = "DXGI_FORMAT_R16G16_SNORM"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R16G16_SINT"] = 38] = "DXGI_FORMAT_R16G16_SINT"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R32_TYPELESS"] = 39] = "DXGI_FORMAT_R32_TYPELESS"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_D32_FLOAT"] = 40] = "DXGI_FORMAT_D32_FLOAT"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R32_FLOAT"] = 41] = "DXGI_FORMAT_R32_FLOAT"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R32_UINT"] = 42] = "DXGI_FORMAT_R32_UINT"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R32_SINT"] = 43] = "DXGI_FORMAT_R32_SINT"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R24G8_TYPELESS"] = 44] = "DXGI_FORMAT_R24G8_TYPELESS"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_D24_UNORM_S8_UINT"] = 45] = "DXGI_FORMAT_D24_UNORM_S8_UINT"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R24_UNORM_X8_TYPELESS"] = 46] = "DXGI_FORMAT_R24_UNORM_X8_TYPELESS"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_X24_TYPELESS_G8_UINT"] = 47] = "DXGI_FORMAT_X24_TYPELESS_G8_UINT"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R8G8_TYPELESS"] = 48] = "DXGI_FORMAT_R8G8_TYPELESS"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R8G8_UNORM"] = 49] = "DXGI_FORMAT_R8G8_UNORM"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R8G8_UINT"] = 50] = "DXGI_FORMAT_R8G8_UINT"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R8G8_SNORM"] = 51] = "DXGI_FORMAT_R8G8_SNORM"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R8G8_SINT"] = 52] = "DXGI_FORMAT_R8G8_SINT"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R16_TYPELESS"] = 53] = "DXGI_FORMAT_R16_TYPELESS"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R16_FLOAT"] = 54] = "DXGI_FORMAT_R16_FLOAT"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_D16_UNORM"] = 55] = "DXGI_FORMAT_D16_UNORM"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R16_UNORM"] = 56] = "DXGI_FORMAT_R16_UNORM"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R16_UINT"] = 57] = "DXGI_FORMAT_R16_UINT"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R16_SNORM"] = 58] = "DXGI_FORMAT_R16_SNORM"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R16_SINT"] = 59] = "DXGI_FORMAT_R16_SINT"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R8_TYPELESS"] = 60] = "DXGI_FORMAT_R8_TYPELESS"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R8_UNORM"] = 61] = "DXGI_FORMAT_R8_UNORM"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R8_UINT"] = 62] = "DXGI_FORMAT_R8_UINT"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R8_SNORM"] = 63] = "DXGI_FORMAT_R8_SNORM"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R8_SINT"] = 64] = "DXGI_FORMAT_R8_SINT"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_A8_UNORM"] = 65] = "DXGI_FORMAT_A8_UNORM"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R1_UNORM"] = 66] = "DXGI_FORMAT_R1_UNORM"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R9G9B9E5_SHAREDEXP"] = 67] = "DXGI_FORMAT_R9G9B9E5_SHAREDEXP"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R8G8_B8G8_UNORM"] = 68] = "DXGI_FORMAT_R8G8_B8G8_UNORM"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_G8R8_G8B8_UNORM"] = 69] = "DXGI_FORMAT_G8R8_G8B8_UNORM"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_BC1_TYPELESS"] = 70] = "DXGI_FORMAT_BC1_TYPELESS"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_BC1_UNORM"] = 71] = "DXGI_FORMAT_BC1_UNORM"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_BC1_UNORM_SRGB"] = 72] = "DXGI_FORMAT_BC1_UNORM_SRGB"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_BC2_TYPELESS"] = 73] = "DXGI_FORMAT_BC2_TYPELESS"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_BC2_UNORM"] = 74] = "DXGI_FORMAT_BC2_UNORM"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_BC2_UNORM_SRGB"] = 75] = "DXGI_FORMAT_BC2_UNORM_SRGB"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_BC3_TYPELESS"] = 76] = "DXGI_FORMAT_BC3_TYPELESS"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_BC3_UNORM"] = 77] = "DXGI_FORMAT_BC3_UNORM"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_BC3_UNORM_SRGB"] = 78] = "DXGI_FORMAT_BC3_UNORM_SRGB"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_BC4_TYPELESS"] = 79] = "DXGI_FORMAT_BC4_TYPELESS"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_BC4_UNORM"] = 80] = "DXGI_FORMAT_BC4_UNORM"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_BC4_SNORM"] = 81] = "DXGI_FORMAT_BC4_SNORM"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_BC5_TYPELESS"] = 82] = "DXGI_FORMAT_BC5_TYPELESS"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_BC5_UNORM"] = 83] = "DXGI_FORMAT_BC5_UNORM"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_BC5_SNORM"] = 84] = "DXGI_FORMAT_BC5_SNORM"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_B5G6R5_UNORM"] = 85] = "DXGI_FORMAT_B5G6R5_UNORM"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_B5G5R5A1_UNORM"] = 86] = "DXGI_FORMAT_B5G5R5A1_UNORM"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_B8G8R8A8_UNORM"] = 87] = "DXGI_FORMAT_B8G8R8A8_UNORM"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_B8G8R8X8_UNORM"] = 88] = "DXGI_FORMAT_B8G8R8X8_UNORM"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R10G10B10_XR_BIAS_A2_UNORM"] = 89] = "DXGI_FORMAT_R10G10B10_XR_BIAS_A2_UNORM"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_B8G8R8A8_TYPELESS"] = 90] = "DXGI_FORMAT_B8G8R8A8_TYPELESS"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_B8G8R8A8_UNORM_SRGB"] = 91] = "DXGI_FORMAT_B8G8R8A8_UNORM_SRGB"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_B8G8R8X8_TYPELESS"] = 92] = "DXGI_FORMAT_B8G8R8X8_TYPELESS"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_B8G8R8X8_UNORM_SRGB"] = 93] = "DXGI_FORMAT_B8G8R8X8_UNORM_SRGB"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_BC6H_TYPELESS"] = 94] = "DXGI_FORMAT_BC6H_TYPELESS"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_BC6H_UF16"] = 95] = "DXGI_FORMAT_BC6H_UF16"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_BC6H_SF16"] = 96] = "DXGI_FORMAT_BC6H_SF16"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_BC7_TYPELESS"] = 97] = "DXGI_FORMAT_BC7_TYPELESS"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_BC7_UNORM"] = 98] = "DXGI_FORMAT_BC7_UNORM"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_BC7_UNORM_SRGB"] = 99] = "DXGI_FORMAT_BC7_UNORM_SRGB"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_AYUV"] = 100] = "DXGI_FORMAT_AYUV"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_Y410"] = 101] = "DXGI_FORMAT_Y410"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_Y416"] = 102] = "DXGI_FORMAT_Y416"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_NV12"] = 103] = "DXGI_FORMAT_NV12"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_P010"] = 104] = "DXGI_FORMAT_P010"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_P016"] = 105] = "DXGI_FORMAT_P016"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_420_OPAQUE"] = 106] = "DXGI_FORMAT_420_OPAQUE"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_YUY2"] = 107] = "DXGI_FORMAT_YUY2"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_Y210"] = 108] = "DXGI_FORMAT_Y210"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_Y216"] = 109] = "DXGI_FORMAT_Y216"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_NV11"] = 110] = "DXGI_FORMAT_NV11"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_AI44"] = 111] = "DXGI_FORMAT_AI44"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_IA44"] = 112] = "DXGI_FORMAT_IA44"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_P8"] = 113] = "DXGI_FORMAT_P8"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_A8P8"] = 114] = "DXGI_FORMAT_A8P8"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_B4G4R4A4_UNORM"] = 115] = "DXGI_FORMAT_B4G4R4A4_UNORM"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_P208"] = 116] = "DXGI_FORMAT_P208"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_V208"] = 117] = "DXGI_FORMAT_V208"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_V408"] = 118] = "DXGI_FORMAT_V408"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_SAMPLER_FEEDBACK_MIN_MIP_OPAQUE"] = 119] = "DXGI_FORMAT_SAMPLER_FEEDBACK_MIN_MIP_OPAQUE"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_SAMPLER_FEEDBACK_MIP_REGION_USED_OPAQUE"] = 120] = "DXGI_FORMAT_SAMPLER_FEEDBACK_MIP_REGION_USED_OPAQUE"; + DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_FORCE_UINT"] = 121] = "DXGI_FORMAT_FORCE_UINT"; + })(DXGI_FORMAT || (DXGI_FORMAT = {})); + /** + * Possible values of the field {@link DDS_DX10_FIELDS.RESOURCE_DIMENSION} + * @ignore + */ + var D3D10_RESOURCE_DIMENSION; + (function (D3D10_RESOURCE_DIMENSION) { + D3D10_RESOURCE_DIMENSION[D3D10_RESOURCE_DIMENSION["DDS_DIMENSION_TEXTURE1D"] = 2] = "DDS_DIMENSION_TEXTURE1D"; + D3D10_RESOURCE_DIMENSION[D3D10_RESOURCE_DIMENSION["DDS_DIMENSION_TEXTURE2D"] = 3] = "DDS_DIMENSION_TEXTURE2D"; + D3D10_RESOURCE_DIMENSION[D3D10_RESOURCE_DIMENSION["DDS_DIMENSION_TEXTURE3D"] = 6] = "DDS_DIMENSION_TEXTURE3D"; + })(D3D10_RESOURCE_DIMENSION || (D3D10_RESOURCE_DIMENSION = {})); + var PF_FLAGS = 1; + // PIXEL_FORMAT flags + var DDPF_ALPHA = 0x2; + var DDPF_FOURCC = 0x4; + var DDPF_RGB = 0x40; + var DDPF_YUV = 0x200; + var DDPF_LUMINANCE = 0x20000; + // Four character codes for DXTn formats + var FOURCC_DXT1 = 0x31545844; + var FOURCC_DXT3 = 0x33545844; + var FOURCC_DXT5 = 0x35545844; + var FOURCC_DX10 = 0x30315844; + // Cubemap texture flag (for DDS_DX10_FIELDS.MISC_FLAG) + var DDS_RESOURCE_MISC_TEXTURECUBE = 0x4; + /** + * Maps `FOURCC_*` formats to internal formats (see {@link PIXI.INTERNAL_FORMATS}). + * @ignore + */ + var FOURCC_TO_FORMAT = (_a$1 = {}, + _a$1[FOURCC_DXT1] = exports.INTERNAL_FORMATS.COMPRESSED_RGBA_S3TC_DXT1_EXT, + _a$1[FOURCC_DXT3] = exports.INTERNAL_FORMATS.COMPRESSED_RGBA_S3TC_DXT3_EXT, + _a$1[FOURCC_DXT5] = exports.INTERNAL_FORMATS.COMPRESSED_RGBA_S3TC_DXT5_EXT, + _a$1); + /** + * Maps {@link DXGI_FORMAT} to types/internal-formats (see {@link PIXI.TYPES}, {@link PIXI.INTERNAL_FORMATS}) + * @ignore + */ + var DXGI_TO_FORMAT = (_b$1 = {}, + // WEBGL_compressed_texture_s3tc + _b$1[DXGI_FORMAT.DXGI_FORMAT_BC1_TYPELESS] = exports.INTERNAL_FORMATS.COMPRESSED_RGBA_S3TC_DXT1_EXT, + _b$1[DXGI_FORMAT.DXGI_FORMAT_BC1_UNORM] = exports.INTERNAL_FORMATS.COMPRESSED_RGBA_S3TC_DXT1_EXT, + _b$1[DXGI_FORMAT.DXGI_FORMAT_BC2_TYPELESS] = exports.INTERNAL_FORMATS.COMPRESSED_RGBA_S3TC_DXT3_EXT, + _b$1[DXGI_FORMAT.DXGI_FORMAT_BC2_UNORM] = exports.INTERNAL_FORMATS.COMPRESSED_RGBA_S3TC_DXT3_EXT, + _b$1[DXGI_FORMAT.DXGI_FORMAT_BC3_TYPELESS] = exports.INTERNAL_FORMATS.COMPRESSED_RGBA_S3TC_DXT5_EXT, + _b$1[DXGI_FORMAT.DXGI_FORMAT_BC3_UNORM] = exports.INTERNAL_FORMATS.COMPRESSED_RGBA_S3TC_DXT5_EXT, + // WEBGL_compressed_texture_s3tc_srgb + _b$1[DXGI_FORMAT.DXGI_FORMAT_BC1_UNORM_SRGB] = exports.INTERNAL_FORMATS.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT, + _b$1[DXGI_FORMAT.DXGI_FORMAT_BC2_UNORM_SRGB] = exports.INTERNAL_FORMATS.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT, + _b$1[DXGI_FORMAT.DXGI_FORMAT_BC3_UNORM_SRGB] = exports.INTERNAL_FORMATS.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT, + _b$1); + /** + * @class + * @memberof PIXI + * @implements {PIXI.ILoaderPlugin} + * @see https://docs.microsoft.com/en-us/windows/win32/direct3ddds/dx-graphics-dds-pguide + */ + /** + * Parses the DDS file header, generates base-textures, and puts them into the texture cache. + * @param arrayBuffer + */ + function parseDDS(arrayBuffer) { + var data = new Uint32Array(arrayBuffer); + var magicWord = data[0]; + if (magicWord !== DDS_MAGIC) { + throw new Error('Invalid DDS file magic word'); + } + var header = new Uint32Array(arrayBuffer, 0, DDS_HEADER_SIZE / Uint32Array.BYTES_PER_ELEMENT); + // DDS header fields + var height = header[DDS_FIELDS.HEIGHT]; + var width = header[DDS_FIELDS.WIDTH]; + var mipmapCount = header[DDS_FIELDS.MIPMAP_COUNT]; + // PIXEL_FORMAT fields + var pixelFormat = new Uint32Array(arrayBuffer, DDS_FIELDS.PIXEL_FORMAT * Uint32Array.BYTES_PER_ELEMENT, DDS_HEADER_PF_SIZE / Uint32Array.BYTES_PER_ELEMENT); + var formatFlags = pixelFormat[PF_FLAGS]; + // File contains compressed texture(s) + if (formatFlags & DDPF_FOURCC) { + var fourCC = pixelFormat[DDS_PF_FIELDS.FOURCC]; + // File contains one DXTn compressed texture + if (fourCC !== FOURCC_DX10) { + var internalFormat_1 = FOURCC_TO_FORMAT[fourCC]; + var dataOffset_1 = DDS_MAGIC_SIZE + DDS_HEADER_SIZE; + var texData = new Uint8Array(arrayBuffer, dataOffset_1); + var resource = new CompressedTextureResource(texData, { + format: internalFormat_1, + width: width, + height: height, + levels: mipmapCount // CompressedTextureResource will separate the levelBuffers for us! + }); + return [resource]; + } + // FOURCC_DX10 indicates there is a 20-byte DDS_HEADER_DX10 after DDS_HEADER + var dx10Offset = DDS_MAGIC_SIZE + DDS_HEADER_SIZE; + var dx10Header = new Uint32Array(data.buffer, dx10Offset, DDS_HEADER_DX10_SIZE / Uint32Array.BYTES_PER_ELEMENT); + var dxgiFormat = dx10Header[DDS_DX10_FIELDS.DXGI_FORMAT]; + var resourceDimension = dx10Header[DDS_DX10_FIELDS.RESOURCE_DIMENSION]; + var miscFlag = dx10Header[DDS_DX10_FIELDS.MISC_FLAG]; + var arraySize = dx10Header[DDS_DX10_FIELDS.ARRAY_SIZE]; + // Map dxgiFormat to PIXI.INTERNAL_FORMATS + var internalFormat_2 = DXGI_TO_FORMAT[dxgiFormat]; + if (internalFormat_2 === undefined) { + throw new Error("DDSParser cannot parse texture data with DXGI format " + dxgiFormat); + } + if (miscFlag === DDS_RESOURCE_MISC_TEXTURECUBE) { + // FIXME: Anybody excited about cubemap compressed textures? + throw new Error('DDSParser does not support cubemap textures'); + } + if (resourceDimension === D3D10_RESOURCE_DIMENSION.DDS_DIMENSION_TEXTURE3D) { + // FIXME: Anybody excited about 3D compressed textures? + throw new Error('DDSParser does not supported 3D texture data'); + } + // Uint8Array buffers of image data, including all mipmap levels in each image + var imageBuffers = new Array(); + var dataOffset = DDS_MAGIC_SIZE + + DDS_HEADER_SIZE + + DDS_HEADER_DX10_SIZE; + if (arraySize === 1) { + // No need bothering with the imageSize calculation! + imageBuffers.push(new Uint8Array(arrayBuffer, dataOffset)); + } + else { + // Calculate imageSize for each texture, and then locate each image's texture data + var pixelSize = INTERNAL_FORMAT_TO_BYTES_PER_PIXEL[internalFormat_2]; + var imageSize = 0; + var levelWidth = width; + var levelHeight = height; + for (var i = 0; i < mipmapCount; i++) { + var alignedLevelWidth = Math.max(1, (levelWidth + 3) & ~3); + var alignedLevelHeight = Math.max(1, (levelHeight + 3) & ~3); + var levelSize = alignedLevelWidth * alignedLevelHeight * pixelSize; + imageSize += levelSize; + levelWidth = levelWidth >>> 1; + levelHeight = levelHeight >>> 1; + } + var imageOffset = dataOffset; + // NOTE: Cubemaps have 6-images per texture (but they aren't supported so ^_^) + for (var i = 0; i < arraySize; i++) { + imageBuffers.push(new Uint8Array(arrayBuffer, imageOffset, imageSize)); + imageOffset += imageSize; + } + } + // Uint8Array -> CompressedTextureResource, and we're done! + return imageBuffers.map(function (buffer) { return new CompressedTextureResource(buffer, { + format: internalFormat_2, + width: width, + height: height, + levels: mipmapCount + }); }); + } + if (formatFlags & DDPF_RGB) { + // FIXME: We might want to allow uncompressed *.dds files? + throw new Error('DDSParser does not support uncompressed texture data.'); + } + if (formatFlags & DDPF_YUV) { + // FIXME: Does anybody need this feature? + throw new Error('DDSParser does not supported YUV uncompressed texture data.'); + } + if (formatFlags & DDPF_LUMINANCE) { + // FIXME: Microsoft says older DDS filers use this feature! Probably not worth the effort! + throw new Error('DDSParser does not support single-channel (lumninance) texture data!'); + } + if (formatFlags & DDPF_ALPHA) { + // FIXME: I'm tired! See above =) + throw new Error('DDSParser does not support single-channel (alpha) texture data!'); + } + throw new Error('DDSParser failed to load a texture file due to an unknown reason!'); + } + + var _a$3, _b, _c; + /** + * The 12-byte KTX file identifier + * @see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/#2.1 + * @ignore + */ + var FILE_IDENTIFIER = [0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A]; + /** + * The value stored in the "endianness" field. + * @see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/#2.2 + * @ignore + */ + var ENDIANNESS = 0x04030201; + /** + * Byte offsets of the KTX file header fields + * @ignore + */ + var KTX_FIELDS = { + FILE_IDENTIFIER: 0, + ENDIANNESS: 12, + GL_TYPE: 16, + GL_TYPE_SIZE: 20, + GL_FORMAT: 24, + GL_INTERNAL_FORMAT: 28, + GL_BASE_INTERNAL_FORMAT: 32, + PIXEL_WIDTH: 36, + PIXEL_HEIGHT: 40, + PIXEL_DEPTH: 44, + NUMBER_OF_ARRAY_ELEMENTS: 48, + NUMBER_OF_FACES: 52, + NUMBER_OF_MIPMAP_LEVELS: 56, + BYTES_OF_KEY_VALUE_DATA: 60 + }; + /** + * Byte size of the file header fields in {@code KTX_FIELDS} + * @ignore + */ + var FILE_HEADER_SIZE = 64; + /** + * Maps {@link PIXI.TYPES} to the bytes taken per component, excluding those ones that are bit-fields. + * @ignore + */ + var TYPES_TO_BYTES_PER_COMPONENT = (_a$3 = {}, + _a$3[exports.TYPES.UNSIGNED_BYTE] = 1, + _a$3[exports.TYPES.UNSIGNED_SHORT] = 2, + _a$3[exports.TYPES.INT] = 4, + _a$3[exports.TYPES.UNSIGNED_INT] = 4, + _a$3[exports.TYPES.FLOAT] = 4, + _a$3[exports.TYPES.HALF_FLOAT] = 8, + _a$3); + /** + * Number of components in each {@link PIXI.FORMATS} + * @ignore + */ + var FORMATS_TO_COMPONENTS = (_b = {}, + _b[exports.FORMATS.RGBA] = 4, + _b[exports.FORMATS.RGB] = 3, + _b[exports.FORMATS.RG] = 2, + _b[exports.FORMATS.RED] = 1, + _b[exports.FORMATS.LUMINANCE] = 1, + _b[exports.FORMATS.LUMINANCE_ALPHA] = 2, + _b[exports.FORMATS.ALPHA] = 1, + _b); + /** + * Number of bytes per pixel in bit-field types in {@link PIXI.TYPES} + * @ignore + */ + var TYPES_TO_BYTES_PER_PIXEL = (_c = {}, + _c[exports.TYPES.UNSIGNED_SHORT_4_4_4_4] = 2, + _c[exports.TYPES.UNSIGNED_SHORT_5_5_5_1] = 2, + _c[exports.TYPES.UNSIGNED_SHORT_5_6_5] = 2, + _c); + function parseKTX(url, arrayBuffer, loadKeyValueData) { + if (loadKeyValueData === void 0) { loadKeyValueData = false; } + var dataView = new DataView(arrayBuffer); + if (!validate(url, dataView)) { + return null; + } + var littleEndian = dataView.getUint32(KTX_FIELDS.ENDIANNESS, true) === ENDIANNESS; + var glType = dataView.getUint32(KTX_FIELDS.GL_TYPE, littleEndian); + // const glTypeSize = dataView.getUint32(KTX_FIELDS.GL_TYPE_SIZE, littleEndian); + var glFormat = dataView.getUint32(KTX_FIELDS.GL_FORMAT, littleEndian); + var glInternalFormat = dataView.getUint32(KTX_FIELDS.GL_INTERNAL_FORMAT, littleEndian); + var pixelWidth = dataView.getUint32(KTX_FIELDS.PIXEL_WIDTH, littleEndian); + var pixelHeight = dataView.getUint32(KTX_FIELDS.PIXEL_HEIGHT, littleEndian) || 1; // "pixelHeight = 0" -> "1" + var pixelDepth = dataView.getUint32(KTX_FIELDS.PIXEL_DEPTH, littleEndian) || 1; // ^^ + var numberOfArrayElements = dataView.getUint32(KTX_FIELDS.NUMBER_OF_ARRAY_ELEMENTS, littleEndian) || 1; // ^^ + var numberOfFaces = dataView.getUint32(KTX_FIELDS.NUMBER_OF_FACES, littleEndian); + var numberOfMipmapLevels = dataView.getUint32(KTX_FIELDS.NUMBER_OF_MIPMAP_LEVELS, littleEndian); + var bytesOfKeyValueData = dataView.getUint32(KTX_FIELDS.BYTES_OF_KEY_VALUE_DATA, littleEndian); + // Whether the platform architecture is little endian. If littleEndian !== platformLittleEndian, then the + // file contents must be endian-converted! + // TODO: Endianness conversion + // const platformLittleEndian = new Uint8Array((new Uint32Array([ENDIANNESS])).buffer)[0] === 0x01; + if (pixelHeight === 0 || pixelDepth !== 1) { + throw new Error('Only 2D textures are supported'); + } + if (numberOfFaces !== 1) { + throw new Error('CubeTextures are not supported by KTXLoader yet!'); + } + if (numberOfArrayElements !== 1) { + // TODO: Support splitting array-textures into multiple BaseTextures + throw new Error('WebGL does not support array textures'); + } + // TODO: 8x4 blocks for 2bpp pvrtc + var blockWidth = 4; + var blockHeight = 4; + var alignedWidth = (pixelWidth + 3) & ~3; + var alignedHeight = (pixelHeight + 3) & ~3; + var imageBuffers = new Array(numberOfArrayElements); + var imagePixels = pixelWidth * pixelHeight; + if (glType === 0) { + // Align to 16 pixels (4x4 blocks) + imagePixels = alignedWidth * alignedHeight; + } + var imagePixelByteSize; + if (glType !== 0) { + // Uncompressed texture format + if (TYPES_TO_BYTES_PER_COMPONENT[glType]) { + imagePixelByteSize = TYPES_TO_BYTES_PER_COMPONENT[glType] * FORMATS_TO_COMPONENTS[glFormat]; + } + else { + imagePixelByteSize = TYPES_TO_BYTES_PER_PIXEL[glType]; + } + } + else { + imagePixelByteSize = INTERNAL_FORMAT_TO_BYTES_PER_PIXEL[glInternalFormat]; + } + if (imagePixelByteSize === undefined) { + throw new Error('Unable to resolve the pixel format stored in the *.ktx file!'); + } + var kvData = loadKeyValueData + ? parseKvData(dataView, bytesOfKeyValueData, littleEndian) + : null; + var imageByteSize = imagePixels * imagePixelByteSize; + var mipByteSize = imageByteSize; + var mipWidth = pixelWidth; + var mipHeight = pixelHeight; + var alignedMipWidth = alignedWidth; + var alignedMipHeight = alignedHeight; + var imageOffset = FILE_HEADER_SIZE + bytesOfKeyValueData; + for (var mipmapLevel = 0; mipmapLevel < numberOfMipmapLevels; mipmapLevel++) { + var imageSize = dataView.getUint32(imageOffset, littleEndian); + var elementOffset = imageOffset + 4; + for (var arrayElement = 0; arrayElement < numberOfArrayElements; arrayElement++) { + // TODO: Maybe support 3D textures? :-) + // for (let zSlice = 0; zSlice < pixelDepth; zSlice) + var mips = imageBuffers[arrayElement]; + if (!mips) { + mips = imageBuffers[arrayElement] = new Array(numberOfMipmapLevels); + } + mips[mipmapLevel] = { + levelID: mipmapLevel, + // don't align mipWidth when texture not compressed! (glType not zero) + levelWidth: numberOfMipmapLevels > 1 || glType !== 0 ? mipWidth : alignedMipWidth, + levelHeight: numberOfMipmapLevels > 1 || glType !== 0 ? mipHeight : alignedMipHeight, + levelBuffer: new Uint8Array(arrayBuffer, elementOffset, mipByteSize) + }; + elementOffset += mipByteSize; + } + // HINT: Aligns to 4-byte boundary after jumping imageSize (in lieu of mipPadding) + imageOffset += imageSize + 4; // (+4 to jump the imageSize field itself) + imageOffset = imageOffset % 4 !== 0 ? imageOffset + 4 - (imageOffset % 4) : imageOffset; + // Calculate mipWidth, mipHeight for _next_ iteration + mipWidth = (mipWidth >> 1) || 1; + mipHeight = (mipHeight >> 1) || 1; + alignedMipWidth = (mipWidth + blockWidth - 1) & ~(blockWidth - 1); + alignedMipHeight = (mipHeight + blockHeight - 1) & ~(blockHeight - 1); + // Each mipmap level is 4-times smaller? + mipByteSize = alignedMipWidth * alignedMipHeight * imagePixelByteSize; + } + // We use the levelBuffers feature of CompressedTextureResource b/c texture data is image-major, not level-major. + if (glType !== 0) { + return { + uncompressed: imageBuffers.map(function (levelBuffers) { + var buffer = levelBuffers[0].levelBuffer; + var convertToInt = false; + if (glType === exports.TYPES.FLOAT) { + buffer = new Float32Array(levelBuffers[0].levelBuffer.buffer, levelBuffers[0].levelBuffer.byteOffset, levelBuffers[0].levelBuffer.byteLength / 4); + } + else if (glType === exports.TYPES.UNSIGNED_INT) { + convertToInt = true; + buffer = new Uint32Array(levelBuffers[0].levelBuffer.buffer, levelBuffers[0].levelBuffer.byteOffset, levelBuffers[0].levelBuffer.byteLength / 4); + } + else if (glType === exports.TYPES.INT) { + convertToInt = true; + buffer = new Int32Array(levelBuffers[0].levelBuffer.buffer, levelBuffers[0].levelBuffer.byteOffset, levelBuffers[0].levelBuffer.byteLength / 4); + } + return { + resource: new BufferResource(buffer, { + width: levelBuffers[0].levelWidth, + height: levelBuffers[0].levelHeight, + }), + type: glType, + format: convertToInt ? convertFormatToInteger(glFormat) : glFormat, + }; + }), + kvData: kvData + }; + } + return { + compressed: imageBuffers.map(function (levelBuffers) { return new CompressedTextureResource(null, { + format: glInternalFormat, + width: pixelWidth, + height: pixelHeight, + levels: numberOfMipmapLevels, + levelBuffers: levelBuffers, + }); }), + kvData: kvData + }; + } + /** + * Checks whether the arrayBuffer contains a valid *.ktx file. + * @param url + * @param dataView + */ + function validate(url, dataView) { + // NOTE: Do not optimize this into 3 32-bit integer comparison because the endianness + // of the data is not specified. + for (var i = 0; i < FILE_IDENTIFIER.length; i++) { + if (dataView.getUint8(i) !== FILE_IDENTIFIER[i]) { + console.error(url + " is not a valid *.ktx file!"); + return false; + } + } + return true; + } + function convertFormatToInteger(format) { + switch (format) { + case exports.FORMATS.RGBA: return exports.FORMATS.RGBA_INTEGER; + case exports.FORMATS.RGB: return exports.FORMATS.RGB_INTEGER; + case exports.FORMATS.RG: return exports.FORMATS.RG_INTEGER; + case exports.FORMATS.RED: return exports.FORMATS.RED_INTEGER; + default: return format; + } + } + function parseKvData(dataView, bytesOfKeyValueData, littleEndian) { + var kvData = new Map(); + var bytesIntoKeyValueData = 0; + while (bytesIntoKeyValueData < bytesOfKeyValueData) { + var keyAndValueByteSize = dataView.getUint32(FILE_HEADER_SIZE + bytesIntoKeyValueData, littleEndian); + var keyAndValueByteOffset = FILE_HEADER_SIZE + bytesIntoKeyValueData + 4; + var valuePadding = 3 - ((keyAndValueByteSize + 3) % 4); + // Bounds check + if (keyAndValueByteSize === 0 || keyAndValueByteSize > bytesOfKeyValueData - bytesIntoKeyValueData) { + console.error('KTXLoader: keyAndValueByteSize out of bounds'); + break; + } + // Note: keyNulByte can't be 0 otherwise the key is an empty string. + var keyNulByte = 0; + for (; keyNulByte < keyAndValueByteSize; keyNulByte++) { + if (dataView.getUint8(keyAndValueByteOffset + keyNulByte) === 0x00) { + break; + } + } + if (keyNulByte === -1) { + console.error('KTXLoader: Failed to find null byte terminating kvData key'); + break; + } + var key = new TextDecoder().decode(new Uint8Array(dataView.buffer, keyAndValueByteOffset, keyNulByte)); + var value = new DataView(dataView.buffer, keyAndValueByteOffset + keyNulByte + 1, keyAndValueByteSize - keyNulByte - 1); + kvData.set(key, value); + // 4 = the keyAndValueByteSize field itself + // keyAndValueByteSize = the bytes taken by the key and value + // valuePadding = extra padding to align with 4 bytes + bytesIntoKeyValueData += 4 + keyAndValueByteSize + valuePadding; + } + return kvData; + } + + // Set DDS files to be loaded as an ArrayBuffer + exports.LoaderResource.setExtensionXhrType('dds', exports.LoaderResource.XHR_RESPONSE_TYPE.BUFFER); + /** + * @class + * @memberof PIXI + * @implements {PIXI.ILoaderPlugin} + * @see https://docs.microsoft.com/en-us/windows/win32/direct3ddds/dx-graphics-dds-pguide + */ + var DDSLoader = /** @class */ (function () { + function DDSLoader() { + } + /** + * Registers a DDS compressed texture + * @see PIXI.Loader.loaderMiddleware + * @param resource - loader resource that is checked to see if it is a DDS file + * @param next - callback Function to call when done + */ + DDSLoader.use = function (resource, next) { + if (resource.extension === 'dds' && resource.data) { + try { + Object.assign(resource, registerCompressedTextures(resource.name || resource.url, parseDDS(resource.data), resource.metadata)); + } + catch (err) { + next(err); + return; + } + } + next(); + }; + /** @ignore */ + DDSLoader.extension = exports.ExtensionType.Loader; + return DDSLoader; + }()); + + // Set KTX files to be loaded as an ArrayBuffer + exports.LoaderResource.setExtensionXhrType('ktx', exports.LoaderResource.XHR_RESPONSE_TYPE.BUFFER); + /** + * Loader plugin for handling KTX texture container files. + * + * This KTX loader does not currently support the following features: + * * cube textures + * * 3D textures + * * endianness conversion for big-endian machines + * * embedded *.basis files + * + * It does supports the following features: + * * multiple textures per file + * * mipmapping (only for compressed formats) + * * vendor-specific key/value data parsing (enable {@link PIXI.KTXLoader.loadKeyValueData}) + * @class + * @memberof PIXI + * @implements {PIXI.ILoaderPlugin} + */ + var KTXLoader = /** @class */ (function () { + function KTXLoader() { + } + /** + * Called after a KTX file is loaded. + * + * This will parse the KTX file header and add a {@code BaseTexture} to the texture + * cache. + * @see PIXI.Loader.loaderMiddleware + * @param resource - loader resource that is checked to see if it is a KTX file + * @param next - callback Function to call when done + */ + KTXLoader.use = function (resource, next) { + if (resource.extension === 'ktx' && resource.data) { + try { + var url_1 = resource.name || resource.url; + var _a = parseKTX(url_1, resource.data, this.loadKeyValueData), compressed = _a.compressed, uncompressed = _a.uncompressed, kvData_1 = _a.kvData; + if (compressed) { + var result = registerCompressedTextures(url_1, compressed, resource.metadata); + if (kvData_1 && result.textures) { + for (var textureId in result.textures) { + result.textures[textureId].baseTexture.ktxKeyValueData = kvData_1; + } + } + Object.assign(resource, result); + } + else if (uncompressed) { + var textures_1 = {}; + uncompressed.forEach(function (image, i) { + var texture = new Texture(new BaseTexture(image.resource, { + mipmap: exports.MIPMAP_MODES.OFF, + alphaMode: exports.ALPHA_MODES.NO_PREMULTIPLIED_ALPHA, + type: image.type, + format: image.format, + })); + var cacheID = url_1 + "-" + (i + 1); + if (kvData_1) + { texture.baseTexture.ktxKeyValueData = kvData_1; } + BaseTexture.addToCache(texture.baseTexture, cacheID); + Texture.addToCache(texture, cacheID); + if (i === 0) { + textures_1[url_1] = texture; + BaseTexture.addToCache(texture.baseTexture, url_1); + Texture.addToCache(texture, url_1); + } + textures_1[cacheID] = texture; + }); + Object.assign(resource, { textures: textures_1 }); + } + } + catch (err) { + next(err); + return; + } + } + next(); + }; + /** @ignore */ + KTXLoader.extension = exports.ExtensionType.Loader; + /** + * If set to `true`, {@link PIXI.KTXLoader} will parse key-value data in KTX textures. This feature relies + * on the [Encoding Standard]{@link https://encoding.spec.whatwg.org}. + * + * The key-value data will be available on the base-textures as {@code PIXI.BaseTexture.ktxKeyValueData}. They + * will hold a reference to the texture data buffer, so make sure to delete key-value data once you are done + * using it. + */ + KTXLoader.loadKeyValueData = false; + return KTXLoader; + }()); + + /*! + * @pixi/particle-container - v6.5.3 + * Compiled Fri, 09 Sep 2022 13:55:20 UTC + * + * @pixi/particle-container is licensed under the MIT License. + * http://www.opensource.org/licenses/mit-license + */ + + /*! ***************************************************************************** + Copyright (c) Microsoft Corporation. - THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED - WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, - MERCHANTABLITY OR NON-INFRINGEMENT. + Permission to use, copy, modify, and/or distribute this software for any + purpose with or without fee is hereby granted. - See the Apache Version 2.0 License for specific language governing permissions - and limitations under the License. - ***************************************************************************** */ - /* global Reflect, Promise */ + THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH + REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY + AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, + INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM + LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR + OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR + PERFORMANCE OF THIS SOFTWARE. + ***************************************************************************** */ + /* global Reflect, Promise */ - var extendStatics$a = function(d, b) { - extendStatics$a = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) { if (b.hasOwnProperty(p)) { d[p] = b[p]; } } }; - return extendStatics$a(d, b); - }; + var extendStatics$f = function(d, b) { + extendStatics$f = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) { if (b.hasOwnProperty(p)) { d[p] = b[p]; } } }; + return extendStatics$f(d, b); + }; - function __extends$a(d, b) { - extendStatics$a(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - } - - /** - * Class controls cache for UV mapping from Texture normal space to BaseTexture normal space. - * - * @class - * @memberof PIXI - */ - var MeshBatchUvs = /** @class */ (function () { - /** - * @param {PIXI.Buffer} uvBuffer - Buffer with normalized uv's - * @param {PIXI.TextureMatrix} uvMatrix - Material UV matrix - */ - function MeshBatchUvs(uvBuffer, uvMatrix) { - /** - * Buffer with normalized UV's - * @member {PIXI.Buffer} - */ - this.uvBuffer = uvBuffer; - /** - * Material UV matrix - * @member {PIXI.TextureMatrix} - */ - this.uvMatrix = uvMatrix; - /** - * UV Buffer data - * @member {Float32Array} - * @readonly - */ - this.data = null; - this._bufferUpdateId = -1; - this._textureUpdateId = -1; - this._updateID = 0; - } - /** - * updates - * - * @param {boolean} [forceUpdate] - force the update - */ - MeshBatchUvs.prototype.update = function (forceUpdate) { - if (!forceUpdate - && this._bufferUpdateId === this.uvBuffer._updateID - && this._textureUpdateId === this.uvMatrix._updateID) { - return; - } - this._bufferUpdateId = this.uvBuffer._updateID; - this._textureUpdateId = this.uvMatrix._updateID; - var data = this.uvBuffer.data; - if (!this.data || this.data.length !== data.length) { - this.data = new Float32Array(data.length); - } - this.uvMatrix.multiplyUvs(data, this.data); - this._updateID++; - }; - return MeshBatchUvs; - }()); - - var tempPoint$2 = new Point(); - var tempPolygon = new Polygon(); - /** - * Base mesh class. - * - * This class empowers you to have maximum flexibility to render any kind of WebGL visuals you can think of. - * This class assumes a certain level of WebGL knowledge. - * If you know a bit this should abstract enough away to make you life easier! - * - * Pretty much ALL WebGL can be broken down into the following: - * - Geometry - The structure and data for the mesh. This can include anything from positions, uvs, normals, colors etc.. - * - Shader - This is the shader that PixiJS will render the geometry with (attributes in the shader must match the geometry) - * - State - This is the state of WebGL required to render the mesh. - * - * Through a combination of the above elements you can render anything you want, 2D or 3D! - * - * @class - * @extends PIXI.Container - * @memberof PIXI - */ - var Mesh = /** @class */ (function (_super) { - __extends$a(Mesh, _super); - /** - * @param {PIXI.Geometry} geometry - the geometry the mesh will use - * @param {PIXI.MeshMaterial} shader - the shader the mesh will use - * @param {PIXI.State} [state] - the state that the WebGL context is required to be in to render the mesh - * if no state is provided, uses {@link PIXI.State.for2d} to create a 2D state for PixiJS. - * @param {number} [drawMode=PIXI.DRAW_MODES.TRIANGLES] - the drawMode, can be any of the PIXI.DRAW_MODES consts - */ - function Mesh(geometry, shader, state, drawMode) { - if (drawMode === void 0) { drawMode = exports.DRAW_MODES.TRIANGLES; } - var _this = _super.call(this) || this; - /** - * Includes vertex positions, face indices, normals, colors, UVs, and - * custom attributes within buffers, reducing the cost of passing all - * this data to the GPU. Can be shared between multiple Mesh objects. - * @member {PIXI.Geometry} - * @readonly - */ - _this.geometry = geometry; - geometry.refCount++; - /** - * Represents the vertex and fragment shaders that processes the geometry and runs on the GPU. - * Can be shared between multiple Mesh objects. - * @member {PIXI.Shader|PIXI.MeshMaterial} - */ - _this.shader = shader; - /** - * Represents the WebGL state the Mesh required to render, excludes shader and geometry. E.g., - * blend mode, culling, depth testing, direction of rendering triangles, backface, etc. - * @member {PIXI.State} - */ - _this.state = state || State.for2d(); - /** - * The way the Mesh should be drawn, can be any of the {@link PIXI.DRAW_MODES} constants. - * - * @member {number} - * @see PIXI.DRAW_MODES - */ - _this.drawMode = drawMode; - /** - * Typically the index of the IndexBuffer where to start drawing. - * @member {number} - * @default 0 - */ - _this.start = 0; - /** - * How much of the geometry to draw, by default `0` renders everything. - * @member {number} - * @default 0 - */ - _this.size = 0; - /** - * thease are used as easy access for batching - * @member {Float32Array} - * @private - */ - _this.uvs = null; - /** - * thease are used as easy access for batching - * @member {Uint16Array} - * @private - */ - _this.indices = null; - /** - * this is the caching layer used by the batcher - * @member {Float32Array} - * @private - */ - _this.vertexData = new Float32Array(1); - /** - * If geometry is changed used to decide to re-transform - * the vertexData. - * @member {number} - * @private - */ - _this.vertexDirty = 0; - _this._transformID = -1; - // Inherited from DisplayMode, set defaults - _this.tint = 0xFFFFFF; - _this.blendMode = exports.BLEND_MODES.NORMAL; - /** - * Internal roundPixels field - * - * @member {boolean} - * @private - */ - _this._roundPixels = settings.ROUND_PIXELS; - /** - * Batched UV's are cached for atlas textures - * @member {PIXI.MeshBatchUvs} - * @private - */ - _this.batchUvs = null; - return _this; - } - Object.defineProperty(Mesh.prototype, "uvBuffer", { - /** - * To change mesh uv's, change its uvBuffer data and increment its _updateID. - * @member {PIXI.Buffer} - * @readonly - */ - get: function () { - return this.geometry.buffers[1]; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(Mesh.prototype, "verticesBuffer", { - /** - * To change mesh vertices, change its uvBuffer data and increment its _updateID. - * Incrementing _updateID is optional because most of Mesh objects do it anyway. - * @member {PIXI.Buffer} - * @readonly - */ - get: function () { - return this.geometry.buffers[0]; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(Mesh.prototype, "material", { - get: function () { - return this.shader; - }, - /** - * Alias for {@link PIXI.Mesh#shader}. - * @member {PIXI.MeshMaterial} - */ - set: function (value) { - this.shader = value; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(Mesh.prototype, "blendMode", { - get: function () { - return this.state.blendMode; - }, - /** - * The blend mode to be applied to the Mesh. Apply a value of - * `PIXI.BLEND_MODES.NORMAL` to reset the blend mode. - * - * @member {number} - * @default PIXI.BLEND_MODES.NORMAL; - * @see PIXI.BLEND_MODES - */ - set: function (value) { - this.state.blendMode = value; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(Mesh.prototype, "roundPixels", { - get: function () { - return this._roundPixels; - }, - /** - * If true PixiJS will Math.floor() x/y values when rendering, stopping pixel interpolation. - * Advantages can include sharper image quality (like text) and faster rendering on canvas. - * The main disadvantage is movement of objects may appear less smooth. - * To set the global default, change {@link PIXI.settings.ROUND_PIXELS} - * - * @member {boolean} - * @default false - */ - set: function (value) { - if (this._roundPixels !== value) { - this._transformID = -1; - } - this._roundPixels = value; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(Mesh.prototype, "tint", { - /** - * The multiply tint applied to the Mesh. This is a hex value. A value of - * `0xFFFFFF` will remove any tint effect. - * - * @member {number} - * @default 0xFFFFFF - */ - get: function () { - return this.shader.tint; - }, - set: function (value) { - this.shader.tint = value; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(Mesh.prototype, "texture", { - /** - * The texture that the Mesh uses. - * - * @member {PIXI.Texture} - */ - get: function () { - return this.shader.texture; - }, - set: function (value) { - this.shader.texture = value; - }, - enumerable: false, - configurable: true - }); - /** - * Standard renderer draw. - * @protected - * @param {PIXI.Renderer} renderer - Instance to renderer. - */ - Mesh.prototype._render = function (renderer) { - // set properties for batching.. - // TODO could use a different way to grab verts? - var vertices = this.geometry.buffers[0].data; - // TODO benchmark check for attribute size.. - if (this.shader.batchable - && this.drawMode === exports.DRAW_MODES.TRIANGLES - && vertices.length < Mesh.BATCHABLE_SIZE * 2) { - this._renderToBatch(renderer); - } - else { - this._renderDefault(renderer); - } - }; - /** - * Standard non-batching way of rendering. - * @protected - * @param {PIXI.Renderer} renderer - Instance to renderer. - */ - Mesh.prototype._renderDefault = function (renderer) { - var shader = this.shader; - shader.alpha = this.worldAlpha; - if (shader.update) { - shader.update(); - } - renderer.batch.flush(); - if (shader.program.uniformData.translationMatrix) { - shader.uniforms.translationMatrix = this.transform.worldTransform.toArray(true); - } - // bind and sync uniforms.. - renderer.shader.bind(shader); - // set state.. - renderer.state.set(this.state); - // bind the geometry... - renderer.geometry.bind(this.geometry, shader); - // then render it - renderer.geometry.draw(this.drawMode, this.size, this.start, this.geometry.instanceCount); - }; - /** - * Rendering by using the Batch system. - * @protected - * @param {PIXI.Renderer} renderer - Instance to renderer. - */ - Mesh.prototype._renderToBatch = function (renderer) { - var geometry = this.geometry; - if (this.shader.uvMatrix) { - this.shader.uvMatrix.update(); - this.calculateUvs(); - } - // set properties for batching.. - this.calculateVertices(); - this.indices = geometry.indexBuffer.data; - this._tintRGB = this.shader._tintRGB; - this._texture = this.shader.texture; - var pluginName = this.material.pluginName; - renderer.batch.setObjectRenderer(renderer.plugins[pluginName]); - renderer.plugins[pluginName].render(this); - }; - /** - * Updates vertexData field based on transform and vertices - */ - Mesh.prototype.calculateVertices = function () { - var geometry = this.geometry; - var vertices = geometry.buffers[0].data; - if (geometry.vertexDirtyId === this.vertexDirty && this._transformID === this.transform._worldID) { - return; - } - this._transformID = this.transform._worldID; - if (this.vertexData.length !== vertices.length) { - this.vertexData = new Float32Array(vertices.length); - } - var wt = this.transform.worldTransform; - var a = wt.a; - var b = wt.b; - var c = wt.c; - var d = wt.d; - var tx = wt.tx; - var ty = wt.ty; - var vertexData = this.vertexData; - for (var i = 0; i < vertexData.length / 2; i++) { - var x = vertices[(i * 2)]; - var y = vertices[(i * 2) + 1]; - vertexData[(i * 2)] = (a * x) + (c * y) + tx; - vertexData[(i * 2) + 1] = (b * x) + (d * y) + ty; - } - if (this._roundPixels) { - var resolution = settings.RESOLUTION; - for (var i = 0; i < vertexData.length; ++i) { - vertexData[i] = Math.round((vertexData[i] * resolution | 0) / resolution); - } - } - this.vertexDirty = geometry.vertexDirtyId; - }; - /** - * Updates uv field based on from geometry uv's or batchUvs - */ - Mesh.prototype.calculateUvs = function () { - var geomUvs = this.geometry.buffers[1]; - if (!this.shader.uvMatrix.isSimple) { - if (!this.batchUvs) { - this.batchUvs = new MeshBatchUvs(geomUvs, this.shader.uvMatrix); - } - this.batchUvs.update(); - this.uvs = this.batchUvs.data; - } - else { - this.uvs = geomUvs.data; - } - }; - /** - * Updates the bounds of the mesh as a rectangle. The bounds calculation takes the worldTransform into account. - * there must be a aVertexPosition attribute present in the geometry for bounds to be calculated correctly. - * - * @protected - */ - Mesh.prototype._calculateBounds = function () { - this.calculateVertices(); - this._bounds.addVertexData(this.vertexData, 0, this.vertexData.length); - }; - /** - * Tests if a point is inside this mesh. Works only for PIXI.DRAW_MODES.TRIANGLES. - * - * @param {PIXI.IPointData} point - the point to test - * @return {boolean} the result of the test - */ - Mesh.prototype.containsPoint = function (point) { - if (!this.getBounds().contains(point.x, point.y)) { - return false; - } - this.worldTransform.applyInverse(point, tempPoint$2); - var vertices = this.geometry.getBuffer('aVertexPosition').data; - var points = tempPolygon.points; - var indices = this.geometry.getIndex().data; - var len = indices.length; - var step = this.drawMode === 4 ? 3 : 1; - for (var i = 0; i + 2 < len; i += step) { - var ind0 = indices[i] * 2; - var ind1 = indices[i + 1] * 2; - var ind2 = indices[i + 2] * 2; - points[0] = vertices[ind0]; - points[1] = vertices[ind0 + 1]; - points[2] = vertices[ind1]; - points[3] = vertices[ind1 + 1]; - points[4] = vertices[ind2]; - points[5] = vertices[ind2 + 1]; - if (tempPolygon.contains(tempPoint$2.x, tempPoint$2.y)) { - return true; - } - } - return false; - }; - /** - * Destroys the Mesh object. - * - * @param {object|boolean} [options] - Options parameter. A boolean will act as if all - * options have been set to that value - * @param {boolean} [options.children=false] - if set to true, all the children will have - * their destroy method called as well. 'options' will be passed on to those calls. - */ - Mesh.prototype.destroy = function (options) { - _super.prototype.destroy.call(this, options); - this.geometry.refCount--; - if (this.geometry.refCount === 0) { - this.geometry.dispose(); - } - this.geometry = null; - this.shader = null; - this.state = null; - this.uvs = null; - this.indices = null; - this.vertexData = null; - }; - /** - * The maximum number of vertices to consider batchable. Generally, the complexity - * of the geometry. - * @memberof PIXI.Mesh - * @static - * @member {number} BATCHABLE_SIZE - */ - Mesh.BATCHABLE_SIZE = 100; - return Mesh; - }(Container)); - - var fragment$3 = "varying vec2 vTextureCoord;\nuniform vec4 uColor;\n\nuniform sampler2D uSampler;\n\nvoid main(void)\n{\n gl_FragColor = texture2D(uSampler, vTextureCoord) * uColor;\n}\n"; - - var vertex$3 = "attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\nuniform mat3 translationMatrix;\nuniform mat3 uTextureMatrix;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n vTextureCoord = (uTextureMatrix * vec3(aTextureCoord, 1.0)).xy;\n}\n"; - - /** - * Slightly opinionated default shader for PixiJS 2D objects. - * @class - * @memberof PIXI - * @extends PIXI.Shader - */ - var MeshMaterial = /** @class */ (function (_super) { - __extends$a(MeshMaterial, _super); - /** - * @param {PIXI.Texture} uSampler - Texture that material uses to render. - * @param {object} [options] - Additional options - * @param {number} [options.alpha=1] - Default alpha. - * @param {number} [options.tint=0xFFFFFF] - Default tint. - * @param {string} [options.pluginName='batch'] - Renderer plugin for batching. - * @param {PIXI.Program} [options.program=0xFFFFFF] - Custom program. - * @param {object} [options.uniforms] - Custom uniforms. - */ - function MeshMaterial(uSampler, options) { - var _this = this; - var uniforms = { - uSampler: uSampler, - alpha: 1, - uTextureMatrix: Matrix.IDENTITY, - uColor: new Float32Array([1, 1, 1, 1]), - }; - // Set defaults - options = Object.assign({ - tint: 0xFFFFFF, - alpha: 1, - pluginName: 'batch', - }, options); - if (options.uniforms) { - Object.assign(uniforms, options.uniforms); - } - _this = _super.call(this, options.program || Program.from(vertex$3, fragment$3), uniforms) || this; - /** - * Only do update if tint or alpha changes. - * @member {boolean} - * @private - * @default false - */ - _this._colorDirty = false; - /** - * TextureMatrix instance for this Mesh, used to track Texture changes - * - * @member {PIXI.TextureMatrix} - * @readonly - */ - _this.uvMatrix = new TextureMatrix(uSampler); - /** - * `true` if shader can be batch with the renderer's batch system. - * @member {boolean} - * @default true - */ - _this.batchable = options.program === undefined; - /** - * Renderer plugin for batching - * - * @member {string} - * @default 'batch' - */ - _this.pluginName = options.pluginName; - _this.tint = options.tint; - _this.alpha = options.alpha; - return _this; - } - Object.defineProperty(MeshMaterial.prototype, "texture", { - /** - * Reference to the texture being rendered. - * @member {PIXI.Texture} - */ - get: function () { - return this.uniforms.uSampler; - }, - set: function (value) { - if (this.uniforms.uSampler !== value) { - this.uniforms.uSampler = value; - this.uvMatrix.texture = value; - } - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(MeshMaterial.prototype, "alpha", { - get: function () { - return this._alpha; - }, - /** - * This gets automatically set by the object using this. - * - * @default 1 - * @member {number} - */ - set: function (value) { - if (value === this._alpha) - { return; } - this._alpha = value; - this._colorDirty = true; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(MeshMaterial.prototype, "tint", { - get: function () { - return this._tint; - }, - /** - * Multiply tint for the material. - * @member {number} - * @default 0xFFFFFF - */ - set: function (value) { - if (value === this._tint) - { return; } - this._tint = value; - this._tintRGB = (value >> 16) + (value & 0xff00) + ((value & 0xff) << 16); - this._colorDirty = true; - }, - enumerable: false, - configurable: true - }); - /** - * Gets called automatically by the Mesh. Intended to be overridden for custom - * MeshMaterial objects. - */ - MeshMaterial.prototype.update = function () { - if (this._colorDirty) { - this._colorDirty = false; - var baseTexture = this.texture.baseTexture; - premultiplyTintToRgba(this._tint, this._alpha, this.uniforms.uColor, baseTexture.alphaMode); - } - if (this.uvMatrix.update()) { - this.uniforms.uTextureMatrix = this.uvMatrix.mapCoord; - } - }; - return MeshMaterial; - }(Shader)); - - /** - * Standard 2D geometry used in PixiJS. - * - * Geometry can be defined without passing in a style or data if required. - * - * ```js - * const geometry = new PIXI.Geometry(); - * - * geometry.addAttribute('positions', [0, 0, 100, 0, 100, 100, 0, 100], 2); - * geometry.addAttribute('uvs', [0,0,1,0,1,1,0,1], 2); - * geometry.addIndex([0,1,2,1,3,2]); - * - * ``` - * @class - * @memberof PIXI - * @extends PIXI.Geometry - */ - var MeshGeometry = /** @class */ (function (_super) { - __extends$a(MeshGeometry, _super); - /** - * @param {Float32Array|number[]} [vertices] - Positional data on geometry. - * @param {Float32Array|number[]} [uvs] - Texture UVs. - * @param {Uint16Array|number[]} [index] - IndexBuffer - */ - function MeshGeometry(vertices, uvs, index) { - var _this = _super.call(this) || this; - var verticesBuffer = new Buffer(vertices); - var uvsBuffer = new Buffer(uvs, true); - var indexBuffer = new Buffer(index, true, true); - _this.addAttribute('aVertexPosition', verticesBuffer, 2, false, exports.TYPES.FLOAT) - .addAttribute('aTextureCoord', uvsBuffer, 2, false, exports.TYPES.FLOAT) - .addIndex(indexBuffer); - /** - * Dirty flag to limit update calls on Mesh. For example, - * limiting updates on a single Mesh instance with a shared Geometry - * within the render loop. - * @private - * @member {number} - * @default -1 - */ - _this._updateId = -1; - return _this; - } - Object.defineProperty(MeshGeometry.prototype, "vertexDirtyId", { - /** - * If the vertex position is updated. - * @member {number} - * @readonly - * @private - */ - get: function () { - return this.buffers[0]._updateID; - }, - enumerable: false, - configurable: true - }); - return MeshGeometry; - }(Geometry)); - - /*! - * @pixi/text-bitmap - v5.3.3 - * Compiled Tue, 04 Aug 2020 16:23:09 UTC - * - * @pixi/text-bitmap is licensed under the MIT License. - * http://www.opensource.org/licenses/mit-license - */ - - /*! ***************************************************************************** - Copyright (c) Microsoft Corporation. All rights reserved. - Licensed under the Apache License, Version 2.0 (the "License"); you may not use - this file except in compliance with the License. You may obtain a copy of the - License at http://www.apache.org/licenses/LICENSE-2.0 + function __extends$f(d, b) { + extendStatics$f(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + } + + /** + * The ParticleContainer class is a really fast version of the Container built solely for speed, + * so use when you need a lot of sprites or particles. + * + * The tradeoff of the ParticleContainer is that most advanced functionality will not work. + * ParticleContainer implements the basic object transform (position, scale, rotation) + * and some advanced functionality like tint (as of v4.5.6). + * + * Other more advanced functionality like masking, children, filters, etc will not work on sprites in this batch. + * + * It's extremely easy to use: + * ```js + * let container = new ParticleContainer(); + * + * for (let i = 0; i < 100; ++i) + * { + * let sprite = PIXI.Sprite.from("myImage.png"); + * container.addChild(sprite); + * } + * ``` + * + * And here you have a hundred sprites that will be rendered at the speed of light. + * @memberof PIXI + */ + var ParticleContainer = /** @class */ (function (_super) { + __extends$f(ParticleContainer, _super); + /** + * @param maxSize - The maximum number of particles that can be rendered by the container. + * Affects size of allocated buffers. + * @param properties - The properties of children that should be uploaded to the gpu and applied. + * @param {boolean} [properties.vertices=false] - When true, vertices be uploaded and applied. + * if sprite's ` scale/anchor/trim/frame/orig` is dynamic, please set `true`. + * @param {boolean} [properties.position=true] - When true, position be uploaded and applied. + * @param {boolean} [properties.rotation=false] - When true, rotation be uploaded and applied. + * @param {boolean} [properties.uvs=false] - When true, uvs be uploaded and applied. + * @param {boolean} [properties.tint=false] - When true, alpha and tint be uploaded and applied. + * @param {number} [batchSize=16384] - Number of particles per batch. If less than maxSize, it uses maxSize instead. + * @param {boolean} [autoResize=false] - If true, container allocates more batches in case + * there are more than `maxSize` particles. + */ + function ParticleContainer(maxSize, properties, batchSize, autoResize) { + if (maxSize === void 0) { maxSize = 1500; } + if (batchSize === void 0) { batchSize = 16384; } + if (autoResize === void 0) { autoResize = false; } + var _this = _super.call(this) || this; + // Making sure the batch size is valid + // 65535 is max vertex index in the index buffer (see ParticleRenderer) + // so max number of particles is 65536 / 4 = 16384 + var maxBatchSize = 16384; + if (batchSize > maxBatchSize) { + batchSize = maxBatchSize; + } + _this._properties = [false, true, false, false, false]; + _this._maxSize = maxSize; + _this._batchSize = batchSize; + _this._buffers = null; + _this._bufferUpdateIDs = []; + _this._updateID = 0; + _this.interactiveChildren = false; + _this.blendMode = exports.BLEND_MODES.NORMAL; + _this.autoResize = autoResize; + _this.roundPixels = true; + _this.baseTexture = null; + _this.setProperties(properties); + _this._tint = 0; + _this.tintRgb = new Float32Array(4); + _this.tint = 0xFFFFFF; + return _this; + } + /** + * Sets the private properties array to dynamic / static based on the passed properties object + * @param properties - The properties to be uploaded + */ + ParticleContainer.prototype.setProperties = function (properties) { + if (properties) { + this._properties[0] = 'vertices' in properties || 'scale' in properties + ? !!properties.vertices || !!properties.scale : this._properties[0]; + this._properties[1] = 'position' in properties ? !!properties.position : this._properties[1]; + this._properties[2] = 'rotation' in properties ? !!properties.rotation : this._properties[2]; + this._properties[3] = 'uvs' in properties ? !!properties.uvs : this._properties[3]; + this._properties[4] = 'tint' in properties || 'alpha' in properties + ? !!properties.tint || !!properties.alpha : this._properties[4]; + } + }; + ParticleContainer.prototype.updateTransform = function () { + // TODO don't need to! + this.displayObjectUpdateTransform(); + }; + Object.defineProperty(ParticleContainer.prototype, "tint", { + /** + * The tint applied to the container. This is a hex value. + * A value of 0xFFFFFF will remove any tint effect. + * IMPORTANT: This is a WebGL only feature and will be ignored by the canvas renderer. + * @default 0xFFFFFF + */ + get: function () { + return this._tint; + }, + set: function (value) { + this._tint = value; + hex2rgb(value, this.tintRgb); + }, + enumerable: false, + configurable: true + }); + /** + * Renders the container using the WebGL renderer. + * @param renderer - The WebGL renderer. + */ + ParticleContainer.prototype.render = function (renderer) { + var _this = this; + if (!this.visible || this.worldAlpha <= 0 || !this.children.length || !this.renderable) { + return; + } + if (!this.baseTexture) { + this.baseTexture = this.children[0]._texture.baseTexture; + if (!this.baseTexture.valid) { + this.baseTexture.once('update', function () { return _this.onChildrenChange(0); }); + } + } + renderer.batch.setObjectRenderer(renderer.plugins.particle); + renderer.plugins.particle.render(this); + }; + /** + * Set the flag that static data should be updated to true + * @param smallestChildIndex - The smallest child index. + */ + ParticleContainer.prototype.onChildrenChange = function (smallestChildIndex) { + var bufferIndex = Math.floor(smallestChildIndex / this._batchSize); + while (this._bufferUpdateIDs.length < bufferIndex) { + this._bufferUpdateIDs.push(0); + } + this._bufferUpdateIDs[bufferIndex] = ++this._updateID; + }; + ParticleContainer.prototype.dispose = function () { + if (this._buffers) { + for (var i = 0; i < this._buffers.length; ++i) { + this._buffers[i].destroy(); + } + this._buffers = null; + } + }; + /** + * Destroys the container + * @param options - Options parameter. A boolean will act as if all options + * have been set to that value + * @param {boolean} [options.children=false] - if set to true, all the children will have their + * destroy method called as well. 'options' will be passed on to those calls. + * @param {boolean} [options.texture=false] - Only used for child Sprites if options.children is set to true + * Should it destroy the texture of the child sprite + * @param {boolean} [options.baseTexture=false] - Only used for child Sprites if options.children is set to true + * Should it destroy the base texture of the child sprite + */ + ParticleContainer.prototype.destroy = function (options) { + _super.prototype.destroy.call(this, options); + this.dispose(); + this._properties = null; + this._buffers = null; + this._bufferUpdateIDs = null; + }; + return ParticleContainer; + }(Container)); + + /* + * @author Mat Groves + * + * Big thanks to the very clever Matt DesLauriers https://github.com/mattdesl/ + * for creating the original PixiJS version! + * Also a thanks to https://github.com/bchevalier for tweaking the tint and alpha so that + * they now share 4 bytes on the vertex buffer + * + * Heavily inspired by LibGDX's ParticleBuffer: + * https://github.com/libgdx/libgdx/blob/master/gdx/src/com/badlogic/gdx/graphics/g2d/ParticleBuffer.java + */ + /** + * The particle buffer manages the static and dynamic buffers for a particle container. + * @private + * @memberof PIXI + */ + var ParticleBuffer = /** @class */ (function () { + /** + * @param {object} properties - The properties to upload. + * @param {boolean[]} dynamicPropertyFlags - Flags for which properties are dynamic. + * @param {number} size - The size of the batch. + */ + function ParticleBuffer(properties, dynamicPropertyFlags, size) { + this.geometry = new Geometry(); + this.indexBuffer = null; + this.size = size; + this.dynamicProperties = []; + this.staticProperties = []; + for (var i = 0; i < properties.length; ++i) { + var property = properties[i]; + // Make copy of properties object so that when we edit the offset it doesn't + // change all other instances of the object literal + property = { + attributeName: property.attributeName, + size: property.size, + uploadFunction: property.uploadFunction, + type: property.type || exports.TYPES.FLOAT, + offset: property.offset, + }; + if (dynamicPropertyFlags[i]) { + this.dynamicProperties.push(property); + } + else { + this.staticProperties.push(property); + } + } + this.staticStride = 0; + this.staticBuffer = null; + this.staticData = null; + this.staticDataUint32 = null; + this.dynamicStride = 0; + this.dynamicBuffer = null; + this.dynamicData = null; + this.dynamicDataUint32 = null; + this._updateID = 0; + this.initBuffers(); + } + /** Sets up the renderer context and necessary buffers. */ + ParticleBuffer.prototype.initBuffers = function () { + var geometry = this.geometry; + var dynamicOffset = 0; + this.indexBuffer = new Buffer(createIndicesForQuads(this.size), true, true); + geometry.addIndex(this.indexBuffer); + this.dynamicStride = 0; + for (var i = 0; i < this.dynamicProperties.length; ++i) { + var property = this.dynamicProperties[i]; + property.offset = dynamicOffset; + dynamicOffset += property.size; + this.dynamicStride += property.size; + } + var dynBuffer = new ArrayBuffer(this.size * this.dynamicStride * 4 * 4); + this.dynamicData = new Float32Array(dynBuffer); + this.dynamicDataUint32 = new Uint32Array(dynBuffer); + this.dynamicBuffer = new Buffer(this.dynamicData, false, false); + // static // + var staticOffset = 0; + this.staticStride = 0; + for (var i = 0; i < this.staticProperties.length; ++i) { + var property = this.staticProperties[i]; + property.offset = staticOffset; + staticOffset += property.size; + this.staticStride += property.size; + } + var statBuffer = new ArrayBuffer(this.size * this.staticStride * 4 * 4); + this.staticData = new Float32Array(statBuffer); + this.staticDataUint32 = new Uint32Array(statBuffer); + this.staticBuffer = new Buffer(this.staticData, true, false); + for (var i = 0; i < this.dynamicProperties.length; ++i) { + var property = this.dynamicProperties[i]; + geometry.addAttribute(property.attributeName, this.dynamicBuffer, 0, property.type === exports.TYPES.UNSIGNED_BYTE, property.type, this.dynamicStride * 4, property.offset * 4); + } + for (var i = 0; i < this.staticProperties.length; ++i) { + var property = this.staticProperties[i]; + geometry.addAttribute(property.attributeName, this.staticBuffer, 0, property.type === exports.TYPES.UNSIGNED_BYTE, property.type, this.staticStride * 4, property.offset * 4); + } + }; + /** + * Uploads the dynamic properties. + * @param children - The children to upload. + * @param startIndex - The index to start at. + * @param amount - The number to upload. + */ + ParticleBuffer.prototype.uploadDynamic = function (children, startIndex, amount) { + for (var i = 0; i < this.dynamicProperties.length; i++) { + var property = this.dynamicProperties[i]; + property.uploadFunction(children, startIndex, amount, property.type === exports.TYPES.UNSIGNED_BYTE ? this.dynamicDataUint32 : this.dynamicData, this.dynamicStride, property.offset); + } + this.dynamicBuffer._updateID++; + }; + /** + * Uploads the static properties. + * @param children - The children to upload. + * @param startIndex - The index to start at. + * @param amount - The number to upload. + */ + ParticleBuffer.prototype.uploadStatic = function (children, startIndex, amount) { + for (var i = 0; i < this.staticProperties.length; i++) { + var property = this.staticProperties[i]; + property.uploadFunction(children, startIndex, amount, property.type === exports.TYPES.UNSIGNED_BYTE ? this.staticDataUint32 : this.staticData, this.staticStride, property.offset); + } + this.staticBuffer._updateID++; + }; + /** Destroys the ParticleBuffer. */ + ParticleBuffer.prototype.destroy = function () { + this.indexBuffer = null; + this.dynamicProperties = null; + this.dynamicBuffer = null; + this.dynamicData = null; + this.dynamicDataUint32 = null; + this.staticProperties = null; + this.staticBuffer = null; + this.staticData = null; + this.staticDataUint32 = null; + // all buffers are destroyed inside geometry + this.geometry.destroy(); + }; + return ParticleBuffer; + }()); + + var fragment$6 = "varying vec2 vTextureCoord;\nvarying vec4 vColor;\n\nuniform sampler2D uSampler;\n\nvoid main(void){\n vec4 color = texture2D(uSampler, vTextureCoord) * vColor;\n gl_FragColor = color;\n}"; + + var vertex$3 = "attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\nattribute vec4 aColor;\n\nattribute vec2 aPositionCoord;\nattribute float aRotation;\n\nuniform mat3 translationMatrix;\nuniform vec4 uColor;\n\nvarying vec2 vTextureCoord;\nvarying vec4 vColor;\n\nvoid main(void){\n float x = (aVertexPosition.x) * cos(aRotation) - (aVertexPosition.y) * sin(aRotation);\n float y = (aVertexPosition.x) * sin(aRotation) + (aVertexPosition.y) * cos(aRotation);\n\n vec2 v = vec2(x, y);\n v = v + aPositionCoord;\n\n gl_Position = vec4((translationMatrix * vec3(v, 1.0)).xy, 0.0, 1.0);\n\n vTextureCoord = aTextureCoord;\n vColor = aColor * uColor;\n}\n"; + + /* + * @author Mat Groves + * + * Big thanks to the very clever Matt DesLauriers https://github.com/mattdesl/ + * for creating the original PixiJS version! + * Also a thanks to https://github.com/bchevalier for tweaking the tint and alpha so that they now + * share 4 bytes on the vertex buffer + * + * Heavily inspired by LibGDX's ParticleRenderer: + * https://github.com/libgdx/libgdx/blob/master/gdx/src/com/badlogic/gdx/graphics/g2d/ParticleRenderer.java + */ + /** + * Renderer for Particles that is designer for speed over feature set. + * @memberof PIXI + */ + var ParticleRenderer = /** @class */ (function (_super) { + __extends$f(ParticleRenderer, _super); + /** + * @param renderer - The renderer this sprite batch works for. + */ + function ParticleRenderer(renderer) { + var _this = _super.call(this, renderer) || this; + // 65535 is max vertex index in the index buffer (see ParticleRenderer) + // so max number of particles is 65536 / 4 = 16384 + // and max number of element in the index buffer is 16384 * 6 = 98304 + // Creating a full index buffer, overhead is 98304 * 2 = 196Ko + // let numIndices = 98304; + _this.shader = null; + _this.properties = null; + _this.tempMatrix = new Matrix(); + _this.properties = [ + // verticesData + { + attributeName: 'aVertexPosition', + size: 2, + uploadFunction: _this.uploadVertices, + offset: 0, + }, + // positionData + { + attributeName: 'aPositionCoord', + size: 2, + uploadFunction: _this.uploadPosition, + offset: 0, + }, + // rotationData + { + attributeName: 'aRotation', + size: 1, + uploadFunction: _this.uploadRotation, + offset: 0, + }, + // uvsData + { + attributeName: 'aTextureCoord', + size: 2, + uploadFunction: _this.uploadUvs, + offset: 0, + }, + // tintData + { + attributeName: 'aColor', + size: 1, + type: exports.TYPES.UNSIGNED_BYTE, + uploadFunction: _this.uploadTint, + offset: 0, + } ]; + _this.shader = Shader.from(vertex$3, fragment$6, {}); + _this.state = State.for2d(); + return _this; + } + /** + * Renders the particle container object. + * @param container - The container to render using this ParticleRenderer. + */ + ParticleRenderer.prototype.render = function (container) { + var children = container.children; + var maxSize = container._maxSize; + var batchSize = container._batchSize; + var renderer = this.renderer; + var totalChildren = children.length; + if (totalChildren === 0) { + return; + } + else if (totalChildren > maxSize && !container.autoResize) { + totalChildren = maxSize; + } + var buffers = container._buffers; + if (!buffers) { + buffers = container._buffers = this.generateBuffers(container); + } + var baseTexture = children[0]._texture.baseTexture; + var premultiplied = baseTexture.alphaMode > 0; + // if the uvs have not updated then no point rendering just yet! + this.state.blendMode = correctBlendMode(container.blendMode, premultiplied); + renderer.state.set(this.state); + var gl = renderer.gl; + var m = container.worldTransform.copyTo(this.tempMatrix); + m.prepend(renderer.globalUniforms.uniforms.projectionMatrix); + this.shader.uniforms.translationMatrix = m.toArray(true); + this.shader.uniforms.uColor = premultiplyRgba(container.tintRgb, container.worldAlpha, this.shader.uniforms.uColor, premultiplied); + this.shader.uniforms.uSampler = baseTexture; + this.renderer.shader.bind(this.shader); + var updateStatic = false; + // now lets upload and render the buffers.. + for (var i = 0, j = 0; i < totalChildren; i += batchSize, j += 1) { + var amount = (totalChildren - i); + if (amount > batchSize) { + amount = batchSize; + } + if (j >= buffers.length) { + buffers.push(this._generateOneMoreBuffer(container)); + } + var buffer = buffers[j]; + // we always upload the dynamic + buffer.uploadDynamic(children, i, amount); + var bid = container._bufferUpdateIDs[j] || 0; + updateStatic = updateStatic || (buffer._updateID < bid); + // we only upload the static content when we have to! + if (updateStatic) { + buffer._updateID = container._updateID; + buffer.uploadStatic(children, i, amount); + } + // bind the buffer + renderer.geometry.bind(buffer.geometry); + gl.drawElements(gl.TRIANGLES, amount * 6, gl.UNSIGNED_SHORT, 0); + } + }; + /** + * Creates one particle buffer for each child in the container we want to render and updates internal properties. + * @param container - The container to render using this ParticleRenderer + * @returns - The buffers + */ + ParticleRenderer.prototype.generateBuffers = function (container) { + var buffers = []; + var size = container._maxSize; + var batchSize = container._batchSize; + var dynamicPropertyFlags = container._properties; + for (var i = 0; i < size; i += batchSize) { + buffers.push(new ParticleBuffer(this.properties, dynamicPropertyFlags, batchSize)); + } + return buffers; + }; + /** + * Creates one more particle buffer, because container has autoResize feature. + * @param container - The container to render using this ParticleRenderer + * @returns - The generated buffer + */ + ParticleRenderer.prototype._generateOneMoreBuffer = function (container) { + var batchSize = container._batchSize; + var dynamicPropertyFlags = container._properties; + return new ParticleBuffer(this.properties, dynamicPropertyFlags, batchSize); + }; + /** + * Uploads the vertices. + * @param children - the array of sprites to render + * @param startIndex - the index to start from in the children array + * @param amount - the amount of children that will have their vertices uploaded + * @param array - The vertices to upload. + * @param stride - Stride to use for iteration. + * @param offset - Offset to start at. + */ + ParticleRenderer.prototype.uploadVertices = function (children, startIndex, amount, array, stride, offset) { + var w0 = 0; + var w1 = 0; + var h0 = 0; + var h1 = 0; + for (var i = 0; i < amount; ++i) { + var sprite = children[startIndex + i]; + var texture = sprite._texture; + var sx = sprite.scale.x; + var sy = sprite.scale.y; + var trim = texture.trim; + var orig = texture.orig; + if (trim) { + // if the sprite is trimmed and is not a tilingsprite then we need to add the + // extra space before transforming the sprite coords.. + w1 = trim.x - (sprite.anchor.x * orig.width); + w0 = w1 + trim.width; + h1 = trim.y - (sprite.anchor.y * orig.height); + h0 = h1 + trim.height; + } + else { + w0 = (orig.width) * (1 - sprite.anchor.x); + w1 = (orig.width) * -sprite.anchor.x; + h0 = orig.height * (1 - sprite.anchor.y); + h1 = orig.height * -sprite.anchor.y; + } + array[offset] = w1 * sx; + array[offset + 1] = h1 * sy; + array[offset + stride] = w0 * sx; + array[offset + stride + 1] = h1 * sy; + array[offset + (stride * 2)] = w0 * sx; + array[offset + (stride * 2) + 1] = h0 * sy; + array[offset + (stride * 3)] = w1 * sx; + array[offset + (stride * 3) + 1] = h0 * sy; + offset += stride * 4; + } + }; + /** + * Uploads the position. + * @param children - the array of sprites to render + * @param startIndex - the index to start from in the children array + * @param amount - the amount of children that will have their positions uploaded + * @param array - The vertices to upload. + * @param stride - Stride to use for iteration. + * @param offset - Offset to start at. + */ + ParticleRenderer.prototype.uploadPosition = function (children, startIndex, amount, array, stride, offset) { + for (var i = 0; i < amount; i++) { + var spritePosition = children[startIndex + i].position; + array[offset] = spritePosition.x; + array[offset + 1] = spritePosition.y; + array[offset + stride] = spritePosition.x; + array[offset + stride + 1] = spritePosition.y; + array[offset + (stride * 2)] = spritePosition.x; + array[offset + (stride * 2) + 1] = spritePosition.y; + array[offset + (stride * 3)] = spritePosition.x; + array[offset + (stride * 3) + 1] = spritePosition.y; + offset += stride * 4; + } + }; + /** + * Uploads the rotation. + * @param children - the array of sprites to render + * @param startIndex - the index to start from in the children array + * @param amount - the amount of children that will have their rotation uploaded + * @param array - The vertices to upload. + * @param stride - Stride to use for iteration. + * @param offset - Offset to start at. + */ + ParticleRenderer.prototype.uploadRotation = function (children, startIndex, amount, array, stride, offset) { + for (var i = 0; i < amount; i++) { + var spriteRotation = children[startIndex + i].rotation; + array[offset] = spriteRotation; + array[offset + stride] = spriteRotation; + array[offset + (stride * 2)] = spriteRotation; + array[offset + (stride * 3)] = spriteRotation; + offset += stride * 4; + } + }; + /** + * Uploads the UVs. + * @param children - the array of sprites to render + * @param startIndex - the index to start from in the children array + * @param amount - the amount of children that will have their rotation uploaded + * @param array - The vertices to upload. + * @param stride - Stride to use for iteration. + * @param offset - Offset to start at. + */ + ParticleRenderer.prototype.uploadUvs = function (children, startIndex, amount, array, stride, offset) { + for (var i = 0; i < amount; ++i) { + var textureUvs = children[startIndex + i]._texture._uvs; + if (textureUvs) { + array[offset] = textureUvs.x0; + array[offset + 1] = textureUvs.y0; + array[offset + stride] = textureUvs.x1; + array[offset + stride + 1] = textureUvs.y1; + array[offset + (stride * 2)] = textureUvs.x2; + array[offset + (stride * 2) + 1] = textureUvs.y2; + array[offset + (stride * 3)] = textureUvs.x3; + array[offset + (stride * 3) + 1] = textureUvs.y3; + offset += stride * 4; + } + else { + // TODO you know this can be easier! + array[offset] = 0; + array[offset + 1] = 0; + array[offset + stride] = 0; + array[offset + stride + 1] = 0; + array[offset + (stride * 2)] = 0; + array[offset + (stride * 2) + 1] = 0; + array[offset + (stride * 3)] = 0; + array[offset + (stride * 3) + 1] = 0; + offset += stride * 4; + } + } + }; + /** + * Uploads the tint. + * @param children - the array of sprites to render + * @param startIndex - the index to start from in the children array + * @param amount - the amount of children that will have their rotation uploaded + * @param array - The vertices to upload. + * @param stride - Stride to use for iteration. + * @param offset - Offset to start at. + */ + ParticleRenderer.prototype.uploadTint = function (children, startIndex, amount, array, stride, offset) { + for (var i = 0; i < amount; ++i) { + var sprite = children[startIndex + i]; + var premultiplied = sprite._texture.baseTexture.alphaMode > 0; + var alpha = sprite.alpha; + // we dont call extra function if alpha is 1.0, that's faster + var argb = alpha < 1.0 && premultiplied + ? premultiplyTint(sprite._tintRGB, alpha) : sprite._tintRGB + (alpha * 255 << 24); + array[offset] = argb; + array[offset + stride] = argb; + array[offset + (stride * 2)] = argb; + array[offset + (stride * 3)] = argb; + offset += stride * 4; + } + }; + /** Destroys the ParticleRenderer. */ + ParticleRenderer.prototype.destroy = function () { + _super.prototype.destroy.call(this); + if (this.shader) { + this.shader.destroy(); + this.shader = null; + } + this.tempMatrix = null; + }; + /** @ignore */ + ParticleRenderer.extension = { + name: 'particle', + type: exports.ExtensionType.RendererPlugin, + }; + return ParticleRenderer; + }(ObjectRenderer)); + + /*! + * @pixi/graphics - v6.5.3 + * Compiled Fri, 09 Sep 2022 13:55:20 UTC + * + * @pixi/graphics is licensed under the MIT License. + * http://www.opensource.org/licenses/mit-license + */ + + /** + * Supported line joints in `PIXI.LineStyle` for graphics. + * @see PIXI.Graphics#lineStyle + * @see https://graphicdesign.stackexchange.com/questions/59018/what-is-a-bevel-join-of-two-lines-exactly-illustrator + * @name LINE_JOIN + * @memberof PIXI + * @static + * @enum {string} + * @property {string} MITER - 'miter': make a sharp corner where outer part of lines meet + * @property {string} BEVEL - 'bevel': add a square butt at each end of line segment and fill the triangle at turn + * @property {string} ROUND - 'round': add an arc at the joint + */ + exports.LINE_JOIN = void 0; + (function (LINE_JOIN) { + LINE_JOIN["MITER"] = "miter"; + LINE_JOIN["BEVEL"] = "bevel"; + LINE_JOIN["ROUND"] = "round"; + })(exports.LINE_JOIN || (exports.LINE_JOIN = {})); + /** + * Support line caps in `PIXI.LineStyle` for graphics. + * @see PIXI.Graphics#lineStyle + * @name LINE_CAP + * @memberof PIXI + * @static + * @enum {string} + * @property {string} BUTT - 'butt': don't add any cap at line ends (leaves orthogonal edges) + * @property {string} ROUND - 'round': add semicircle at ends + * @property {string} SQUARE - 'square': add square at end (like `BUTT` except more length at end) + */ + exports.LINE_CAP = void 0; + (function (LINE_CAP) { + LINE_CAP["BUTT"] = "butt"; + LINE_CAP["ROUND"] = "round"; + LINE_CAP["SQUARE"] = "square"; + })(exports.LINE_CAP || (exports.LINE_CAP = {})); + /** + * Graphics curves resolution settings. If `adaptive` flag is set to `true`, + * the resolution is calculated based on the curve's length to ensure better visual quality. + * Adaptive draw works with `bezierCurveTo` and `quadraticCurveTo`. + * @static + * @constant + * @memberof PIXI + * @name GRAPHICS_CURVES + * @type {object} + * @property {boolean} [adaptive=true] - flag indicating if the resolution should be adaptive + * @property {number} [maxLength=10] - maximal length of a single segment of the curve (if adaptive = false, ignored) + * @property {number} [minSegments=8] - minimal number of segments in the curve (if adaptive = false, ignored) + * @property {number} [maxSegments=2048] - maximal number of segments in the curve (if adaptive = false, ignored) + */ + var GRAPHICS_CURVES = { + adaptive: true, + maxLength: 10, + minSegments: 8, + maxSegments: 2048, + epsilon: 0.0001, + _segmentsCount: function (length, defaultSegments) { + if (defaultSegments === void 0) { defaultSegments = 20; } + if (!this.adaptive || !length || isNaN(length)) { + return defaultSegments; + } + var result = Math.ceil(length / this.maxLength); + if (result < this.minSegments) { + result = this.minSegments; + } + else if (result > this.maxSegments) { + result = this.maxSegments; + } + return result; + }, + }; + + /** + * Fill style object for Graphics. + * @memberof PIXI + */ + var FillStyle = /** @class */ (function () { + function FillStyle() { + /** + * The hex color value used when coloring the Graphics object. + * @default 0xFFFFFF + */ + this.color = 0xFFFFFF; + /** The alpha value used when filling the Graphics object. */ + this.alpha = 1.0; + /** + * The texture to be used for the fill. + * @default 0 + */ + this.texture = Texture.WHITE; + /** + * The transform applied to the texture. + * @default null + */ + this.matrix = null; + /** If the current fill is visible. */ + this.visible = false; + this.reset(); + } + /** Clones the object */ + FillStyle.prototype.clone = function () { + var obj = new FillStyle(); + obj.color = this.color; + obj.alpha = this.alpha; + obj.texture = this.texture; + obj.matrix = this.matrix; + obj.visible = this.visible; + return obj; + }; + /** Reset */ + FillStyle.prototype.reset = function () { + this.color = 0xFFFFFF; + this.alpha = 1; + this.texture = Texture.WHITE; + this.matrix = null; + this.visible = false; + }; + /** Destroy and don't use after this. */ + FillStyle.prototype.destroy = function () { + this.texture = null; + this.matrix = null; + }; + return FillStyle; + }()); + + /*! ***************************************************************************** + Copyright (c) Microsoft Corporation. - THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED - WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, - MERCHANTABLITY OR NON-INFRINGEMENT. + Permission to use, copy, modify, and/or distribute this software for any + purpose with or without fee is hereby granted. - See the Apache Version 2.0 License for specific language governing permissions - and limitations under the License. - ***************************************************************************** */ - /* global Reflect, Promise */ + THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH + REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY + AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, + INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM + LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR + OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR + PERFORMANCE OF THIS SOFTWARE. + ***************************************************************************** */ + /* global Reflect, Promise */ - var extendStatics$b = function(d, b) { - extendStatics$b = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) { if (b.hasOwnProperty(p)) { d[p] = b[p]; } } }; - return extendStatics$b(d, b); - }; + var extendStatics$e = function(d, b) { + extendStatics$e = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) { if (b.hasOwnProperty(p)) { d[p] = b[p]; } } }; + return extendStatics$e(d, b); + }; - function __extends$b(d, b) { - extendStatics$b(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - } - - /* eslint-disable max-len */ - /** - * Normalized parsed data from .fnt files. - * - * @class - * @memberof PIXI - */ - var BitmapFontData = /** @class */ (function () { - function BitmapFontData() { - /** - * @member {PIXI.IBitmapFontDataInfo[]} - * @readOnly - */ - this.info = []; - /** - * @member {PIXI.IBitmapFontDataCommon[]} - * @readOnly - */ - this.common = []; - /** - * @member {PIXI.IBitmapFontDataPage[]} - * @readOnly - */ - this.page = []; - /** - * @member {PIXI.IBitmapFontDataChar[]} - * @readOnly - */ - this.char = []; - /** - * @member {PIXI.IBitmapFontDataKerning[]} - * @readOnly - */ - this.kerning = []; - } - return BitmapFontData; - }()); - /** - * @memberof PIXI - * @typedef {object} IBitmapFontDataInfo - * @property {string} face - * @property {number} size - */ - /** - * @memberof PIXI - * @typedef {object} IBitmapFontDataCommon - * @property {number} lineHeight - */ - /** - * @memberof PIXI - * @typedef {object} IBitmapFontDataPage - * @property {number} id - * @property {string} file - */ - /** - * @memberof PIXI - * @typedef {object} IBitmapFontDataChar - * @property {string} id - * @property {number} page - * @property {number} x - * @property {number} y - * @property {number} width - * @property {number} height - * @property {number} xoffset - * @property {number} yoffset - * @property {number} xadvance - */ - /** - * @memberof PIXI - * @typedef {object} IBitmapFontDataKerning - * @property {number} first - * @property {number} second - * @property {number} amount - */ - - /** - * BitmapFont format that's Text-based. - * - * @class - * @private - */ - var TextFormat = /** @class */ (function () { - function TextFormat() { - } - /** - * Check if resource refers to txt font data. - * - * @static - * @private - * @param {any} data - * @return {boolean} True if resource could be treated as font data, false otherwise. - */ - TextFormat.test = function (data) { - return typeof data === 'string' && data.indexOf('info face=') === 0; - }; - /** - * Convert text font data to a javascript object. - * - * @static - * @private - * @param {string} txt - Raw string data to be converted - * @return {PIXI.BitmapFontData} Parsed font data - */ - TextFormat.parse = function (txt) { - // Retrieve data item - var items = txt.match(/^[a-z]+\s+.+$/gm); - var rawData = { - info: [], - common: [], - page: [], - char: [], - chars: [], - kerning: [], - }; - for (var i in items) { - // Extract item name - var name = items[i].match(/^[a-z]+/gm)[0]; - // Extract item attribute list as string ex.: "width=10" - var attributeList = items[i].match(/[a-zA-Z]+=([^\s"']+|"([^"]*)")/gm); - // Convert attribute list into an object - var itemData = {}; - for (var i_1 in attributeList) { - // Split key-value pairs - var split = attributeList[i_1].split('='); - var key = split[0]; - // Remove eventual quotes from value - var strValue = split[1].replace(/"/gm, ''); - // Try to convert value into float - var floatValue = parseFloat(strValue); - // Use string value case float value is NaN - var value = isNaN(floatValue) ? strValue : floatValue; - itemData[key] = value; - } - // Push current item to the resulting data - rawData[name].push(itemData); - } - var font = new BitmapFontData(); - rawData.info.forEach(function (info) { return font.info.push({ - face: info.face, - size: parseInt(info.size, 10), - }); }); - rawData.common.forEach(function (common) { return font.common.push({ - lineHeight: parseInt(common.lineHeight, 10), - }); }); - rawData.page.forEach(function (page) { return font.page.push({ - id: parseInt(page.id, 10), - file: page.file, - }); }); - rawData.char.forEach(function (char) { return font.char.push({ - id: parseInt(char.id, 10), - page: parseInt(char.page, 10), - x: parseInt(char.x, 10), - y: parseInt(char.y, 10), - width: parseInt(char.width, 10), - height: parseInt(char.height, 10), - xoffset: parseInt(char.xoffset, 10), - yoffset: parseInt(char.yoffset, 10), - xadvance: parseInt(char.xadvance, 10), - }); }); - rawData.kerning.forEach(function (kerning) { return font.kerning.push({ - first: parseInt(kerning.first, 10), - second: parseInt(kerning.second, 10), - amount: parseInt(kerning.amount, 10), - }); }); - return font; - }; - return TextFormat; - }()); - - /** - * BitmapFont format that's XML-based. - * - * @class - * @private - */ - var XMLFormat = /** @class */ (function () { - function XMLFormat() { - } - /** - * Check if resource refers to xml font data. - * - * @static - * @private - * @param {any} data - * @return {boolean} True if resource could be treated as font data, false otherwise. - */ - XMLFormat.test = function (data) { - return data instanceof XMLDocument - && data.getElementsByTagName('page').length - && data.getElementsByTagName('info')[0].getAttribute('face') !== null; - }; - /** - * Convert the XML into BitmapFontData that we can use. - * - * @static - * @private - * @param {XMLDocument} xml - * @return {BitmapFontData} Data to use for BitmapFont - */ - XMLFormat.parse = function (xml) { - var data = new BitmapFontData(); - var info = xml.getElementsByTagName('info'); - var common = xml.getElementsByTagName('common'); - var page = xml.getElementsByTagName('page'); - var char = xml.getElementsByTagName('char'); - var kerning = xml.getElementsByTagName('kerning'); - for (var i = 0; i < info.length; i++) { - data.info.push({ - face: info[i].getAttribute('face'), - size: parseInt(info[i].getAttribute('size'), 10), - }); - } - for (var i = 0; i < common.length; i++) { - data.common.push({ - lineHeight: parseInt(common[i].getAttribute('lineHeight'), 10), - }); - } - for (var i = 0; i < page.length; i++) { - data.page.push({ - id: parseInt(page[i].getAttribute('id'), 10) || 0, - file: page[i].getAttribute('file'), - }); - } - for (var i = 0; i < char.length; i++) { - var letter = char[i]; - data.char.push({ - id: parseInt(letter.getAttribute('id'), 10), - page: parseInt(letter.getAttribute('page'), 10) || 0, - x: parseInt(letter.getAttribute('x'), 10), - y: parseInt(letter.getAttribute('y'), 10), - width: parseInt(letter.getAttribute('width'), 10), - height: parseInt(letter.getAttribute('height'), 10), - xoffset: parseInt(letter.getAttribute('xoffset'), 10), - yoffset: parseInt(letter.getAttribute('yoffset'), 10), - xadvance: parseInt(letter.getAttribute('xadvance'), 10), - }); - } - for (var i = 0; i < kerning.length; i++) { - data.kerning.push({ - first: parseInt(kerning[i].getAttribute('first'), 10), - second: parseInt(kerning[i].getAttribute('second'), 10), - amount: parseInt(kerning[i].getAttribute('amount'), 10), - }); - } - return data; - }; - return XMLFormat; - }()); - - // Registered formats, maybe make this extensible in the future? - var formats = [ - TextFormat, - XMLFormat ]; - /** - * Auto-detect BitmapFont parsing format based on data. - * @private - * @param {any} data - Data to detect format - * @return {any} Format or null - */ - function autoDetectFormat(data) { - for (var i = 0; i < formats.length; i++) { - if (formats[i].test(data)) { - return formats[i]; - } - } - return null; - } - - // TODO: Prevent code duplication b/w generateFillStyle & Text#generateFillStyle - /** - * Generates the fill style. Can automatically generate a gradient based on the fill style being an array - * - * @private - * @param {object} style - The style. - * @param {string[]} lines - The lines of text. - * @return {string|number|CanvasGradient} The fill style - */ - function generateFillStyle(canvas, context, style, resolution, lines, metrics) { - // TODO: Can't have different types for getter and setter. The getter shouldn't have the number type as - // the setter converts to string. See this thread for more details: - // https://github.com/microsoft/TypeScript/issues/2521 - var fillStyle = style.fill; - if (!Array.isArray(fillStyle)) { - return fillStyle; - } - else if (fillStyle.length === 1) { - return fillStyle[0]; - } - // the gradient will be evenly spaced out according to how large the array is. - // ['#FF0000', '#00FF00', '#0000FF'] would created stops at 0.25, 0.5 and 0.75 - var gradient; - // a dropshadow will enlarge the canvas and result in the gradient being - // generated with the incorrect dimensions - var dropShadowCorrection = (style.dropShadow) ? style.dropShadowDistance : 0; - // should also take padding into account, padding can offset the gradient - var padding = style.padding || 0; - var width = Math.ceil(canvas.width / resolution) - dropShadowCorrection - (padding * 2); - var height = Math.ceil(canvas.height / resolution) - dropShadowCorrection - (padding * 2); - // make a copy of the style settings, so we can manipulate them later - var fill = fillStyle.slice(); - var fillGradientStops = style.fillGradientStops.slice(); - // wanting to evenly distribute the fills. So an array of 4 colours should give fills of 0.25, 0.5 and 0.75 - if (!fillGradientStops.length) { - var lengthPlus1 = fill.length + 1; - for (var i = 1; i < lengthPlus1; ++i) { - fillGradientStops.push(i / lengthPlus1); - } - } - // stop the bleeding of the last gradient on the line above to the top gradient of the this line - // by hard defining the first gradient colour at point 0, and last gradient colour at point 1 - fill.unshift(fillStyle[0]); - fillGradientStops.unshift(0); - fill.push(fillStyle[fillStyle.length - 1]); - fillGradientStops.push(1); - if (style.fillGradientType === exports.TEXT_GRADIENT.LINEAR_VERTICAL) { - // start the gradient at the top center of the canvas, and end at the bottom middle of the canvas - gradient = context.createLinearGradient(width / 2, padding, width / 2, height + padding); - // we need to repeat the gradient so that each individual line of text has the same vertical gradient effect - // ['#FF0000', '#00FF00', '#0000FF'] over 2 lines would create stops at 0.125, 0.25, 0.375, 0.625, 0.75, 0.875 - // There's potential for floating point precision issues at the seams between gradient repeats. - // The loop below generates the stops in order, so track the last generated one to prevent - // floating point precision from making us go the teeniest bit backwards, resulting in - // the first and last colors getting swapped. - var lastIterationStop = 0; - // Actual height of the text itself, not counting spacing for lineHeight/leading/dropShadow etc - var textHeight = metrics.fontProperties.fontSize + style.strokeThickness; - // textHeight, but as a 0-1 size in global gradient stop space - var gradStopLineHeight = textHeight / height; - for (var i = 0; i < lines.length; i++) { - var thisLineTop = metrics.lineHeight * i; - for (var j = 0; j < fill.length; j++) { - // 0-1 stop point for the current line, multiplied to global space afterwards - var lineStop = 0; - if (typeof fillGradientStops[j] === 'number') { - lineStop = fillGradientStops[j]; - } - else { - lineStop = j / fill.length; - } - var globalStop = (thisLineTop / height) + (lineStop * gradStopLineHeight); - // Prevent color stop generation going backwards from floating point imprecision - var clampedStop = Math.max(lastIterationStop, globalStop); - clampedStop = Math.min(clampedStop, 1); // Cap at 1 as well for safety's sake to avoid a possible throw. - gradient.addColorStop(clampedStop, fill[j]); - lastIterationStop = clampedStop; - } - } - } - else { - // start the gradient at the center left of the canvas, and end at the center right of the canvas - gradient = context.createLinearGradient(padding, height / 2, width + padding, height / 2); - // can just evenly space out the gradients in this case, as multiple lines makes no difference - // to an even left to right gradient - var totalIterations = fill.length + 1; - var currentIteration = 1; - for (var i = 0; i < fill.length; i++) { - var stop = void 0; - if (typeof fillGradientStops[i] === 'number') { - stop = fillGradientStops[i]; - } - else { - stop = currentIteration / totalIterations; - } - gradient.addColorStop(stop, fill[i]); - currentIteration++; - } - } - return gradient; - } - - // TODO: Prevent code duplication b/w drawGlyph & Text#updateText - /** - * Draws the glyph `metrics.text` on the given canvas. - * - * Ignored because not directly exposed. - * - * @ignore - * @param {HTMLCanvasElement} canvas - * @param {CanvasRenderingContext2D} context - * @param {TextMetrics} metrics - * @param {number} x - * @param {number} y - * @param {number} resolution - * @param {TextStyle} style - */ - function drawGlyph(canvas, context, metrics, x, y, resolution, style) { - var char = metrics.text; - var fontProperties = metrics.fontProperties; - context.translate(x, y); - context.scale(resolution, resolution); - var tx = style.strokeThickness / 2; - var ty = -(style.strokeThickness / 2); - context.font = style.toFontString(); - context.lineWidth = style.strokeThickness; - context.textBaseline = style.textBaseline; - context.lineJoin = style.lineJoin; - context.miterLimit = style.miterLimit; - // set canvas text styles - context.fillStyle = generateFillStyle(canvas, context, style, resolution, [char], metrics); - context.strokeStyle = style.stroke; - context.font = style.toFontString(); - context.lineWidth = style.strokeThickness; - context.textBaseline = style.textBaseline; - context.lineJoin = style.lineJoin; - context.miterLimit = style.miterLimit; - // set canvas text styles - context.fillStyle = generateFillStyle(canvas, context, style, resolution, [char], metrics); - context.strokeStyle = style.stroke; - var dropShadowColor = style.dropShadowColor; - var rgb = hex2rgb(typeof dropShadowColor === 'number' ? dropShadowColor : string2hex(dropShadowColor)); - if (style.dropShadow) { - context.shadowColor = "rgba(" + rgb[0] * 255 + "," + rgb[1] * 255 + "," + rgb[2] * 255 + "," + style.dropShadowAlpha + ")"; - context.shadowBlur = style.dropShadowBlur; - context.shadowOffsetX = Math.cos(style.dropShadowAngle) * style.dropShadowDistance; - context.shadowOffsetY = Math.sin(style.dropShadowAngle) * style.dropShadowDistance; - } - else { - context.shadowColor = '0'; - context.shadowBlur = 0; - context.shadowOffsetX = 0; - context.shadowOffsetY = 0; - } - if (style.stroke && style.strokeThickness) { - context.strokeText(char, tx, ty + metrics.lineHeight - fontProperties.descent); - } - if (style.fill) { - context.fillText(char, tx, ty + metrics.lineHeight - fontProperties.descent); - } - context.setTransform(); - context.fillStyle = 'rgba(0, 0, 0, 0)'; - } - - /** - * Processes the passed character set data and returns a flattened array of all the characters. - * - * Ignored because not directly exposed. - * - * @ignore - * @param {string | string[] | string[][] } chars - * @returns {string[]} - */ - function resolveCharacters(chars) { - // Split the chars string into individual characters - if (typeof chars === 'string') { - chars = [chars]; - } - // Handle an array of characters+ranges - var result = []; - for (var i = 0, j = chars.length; i < j; i++) { - var item = chars[i]; - // Handle range delimited by start/end chars - if (Array.isArray(item)) { - if (item.length !== 2) { - throw new Error("[BitmapFont]: Invalid character range length, expecting 2 got " + item.length + "."); - } - var startCode = item[0].charCodeAt(0); - var endCode = item[1].charCodeAt(0); - if (endCode < startCode) { - throw new Error('[BitmapFont]: Invalid character range.'); - } - for (var i_1 = startCode, j_1 = endCode; i_1 <= j_1; i_1++) { - result.push(String.fromCharCode(i_1)); - } - } - // Handle a character set string - else { - result.push.apply(result, item.split('')); - } - } - if (result.length === 0) { - throw new Error('[BitmapFont]: Empty set when resolving characters.'); - } - return result; - } - - /** - * BitmapFont represents a typeface available for use with the BitmapText class. Use the `install` - * method for adding a font to be used. - * - * @class - * @memberof PIXI - */ - var BitmapFont = /** @class */ (function () { - /** - * @param {PIXI.BitmapFontData} data - * @param {PIXI.Texture[]|Object.} textures - */ - function BitmapFont(data, textures) { - var info = data.info[0]; - var common = data.common[0]; - var page = data.page[0]; - var res = getResolutionOfUrl(page.file); - var pageTextures = {}; - /** - * The name of the font face. - * - * @member {string} - * @readonly - */ - this.font = info.face; - /** - * The size of the font face in pixels. - * - * @member {number} - * @readonly - */ - this.size = info.size; - /** - * The line-height of the font face in pixels. - * - * @member {number} - * @readonly - */ - this.lineHeight = common.lineHeight / res; - /** - * The map of characters by character code. - * - * @member {object} - * @readonly - */ - this.chars = {}; - /** - * The map of base page textures (i.e., sheets of glyphs). - * - * @member {object} - * @readonly - * @private - */ - this.pageTextures = pageTextures; - // Convert the input Texture, Textures or object - // into a page Texture lookup by "id" - for (var i = 0; i < data.page.length; i++) { - var _a = data.page[i], id = _a.id, file = _a.file; - pageTextures[id] = textures instanceof Array - ? textures[i] : textures[file]; - } - // parse letters - for (var i = 0; i < data.char.length; i++) { - var _b = data.char[i], id = _b.id, page_1 = _b.page; - var _c = data.char[i], x = _c.x, y = _c.y, width = _c.width, height = _c.height, xoffset = _c.xoffset, yoffset = _c.yoffset, xadvance = _c.xadvance; - x /= res; - y /= res; - width /= res; - height /= res; - xoffset /= res; - yoffset /= res; - xadvance /= res; - var rect = new Rectangle(x + (pageTextures[page_1].frame.x / res), y + (pageTextures[page_1].frame.y / res), width, height); - this.chars[id] = { - xOffset: xoffset, - yOffset: yoffset, - xAdvance: xadvance, - kerning: {}, - texture: new Texture(pageTextures[page_1].baseTexture, rect), - page: page_1, - }; - } - // parse kernings - for (var i = 0; i < data.kerning.length; i++) { - var _d = data.kerning[i], first = _d.first, second = _d.second, amount = _d.amount; - first /= res; - second /= res; - amount /= res; - if (this.chars[second]) { - this.chars[second].kerning[first] = amount; - } - } - } - /** - * Remove references to created glyph textures. - */ - BitmapFont.prototype.destroy = function () { - for (var id in this.chars) { - this.chars[id].texture.destroy(); - this.chars[id].texture = null; - } - for (var id in this.pageTextures) { - this.pageTextures[id].destroy(true); - this.pageTextures[id] = null; - } - // Set readonly null. - this.chars = null; - this.pageTextures = null; - }; - /** - * Register a new bitmap font. - * - * @static - * @param {XMLDocument|string|PIXI.BitmapFontData} data - The - * characters map that could be provided as xml or raw string. - * @param {Object.|PIXI.Texture|PIXI.Texture[]} - * textures - List of textures for each page. - * @return {PIXI.BitmapFont} Result font object with font, size, lineHeight - * and char fields. - */ - BitmapFont.install = function (data, textures) { - var fontData; - if (data instanceof BitmapFontData) { - fontData = data; - } - else { - var format = autoDetectFormat(data); - if (!format) { - throw new Error('Unrecognized data format for font.'); - } - fontData = format.parse(data); - } - // Single texture, convert to list - if (textures instanceof Texture) { - textures = [textures]; - } - var font = new BitmapFont(fontData, textures); - BitmapFont.available[font.font] = font; - return font; - }; - /** - * Remove bitmap font by name. - * - * @static - * @param {string} name - */ - BitmapFont.uninstall = function (name) { - var font = BitmapFont.available[name]; - if (!font) { - throw new Error("No font found named '" + name + "'"); - } - font.destroy(); - delete BitmapFont.available[name]; - }; - /** - * Generates a bitmap-font for the given style and character set. This does not support - * kernings yet. With `style` properties, only the following non-layout properties are used: - * - * - {@link PIXI.TextStyle#dropShadow|dropShadow} - * - {@link PIXI.TextStyle#dropShadowDistance|dropShadowDistance} - * - {@link PIXI.TextStyle#dropShadowColor|dropShadowColor} - * - {@link PIXI.TextStyle#dropShadowBlur|dropShadowBlur} - * - {@link PIXI.TextStyle#dropShadowAngle|dropShadowAngle} - * - {@link PIXI.TextStyle#fill|fill} - * - {@link PIXI.TextStyle#fillGradientStops|fillGradientStops} - * - {@link PIXI.TextStyle#fillGradientType|fillGradientType} - * - {@link PIXI.TextStyle#fontFamily|fontFamily} - * - {@link PIXI.TextStyle#fontSize|fontSize} - * - {@link PIXI.TextStyle#fontVariant|fontVariant} - * - {@link PIXI.TextStyle#fontWeight|fontWeight} - * - {@link PIXI.TextStyle#lineJoin|lineJoin} - * - {@link PIXI.TextStyle#miterLimit|miterLimit} - * - {@link PIXI.TextStyle#stroke|stroke} - * - {@link PIXI.TextStyle#strokeThickness|strokeThickness} - * - {@link PIXI.TextStyle#textBaseline|textBaseline} - * - * @param {string} name - The name of the custom font to use with BitmapText. - * @param {object|PIXI.TextStyle} [style] - Style options to render with BitmapFont. - * @param {PIXI.IBitmapFontOptions} [options] - Setup options for font or name of the font. - * @param {string|string[]|string[][]} [options.chars=PIXI.BitmapFont.ALPHANUMERIC] - characters included - * in the font set. You can also use ranges. For example, `[['a', 'z'], ['A', 'Z'], "!@#$%^&*()~{}[] "]`. - * Don't forget to include spaces ' ' in your character set! - * @param {number} [options.resolution=1] - Render resolution for glyphs. - * @param {number} [options.textureWidth=512] - Optional width of atlas, smaller values to reduce memory. - * @param {number} [options.textureHeight=512] - Optional height of atlas, smaller values to reduce memory. - * @param {number} [options.padding=4] - Padding between glyphs on texture atlas. - * @return {PIXI.BitmapFont} Font generated by style options. - * @static - * @example - * PIXI.BitmapFont.from("TitleFont", { - * fontFamily: "Arial", - * fontSize: 12, - * strokeThickness: 2, - * fill: "purple" - * }); - * - * const title = new PIXI.BitmapText("This is the title", { fontName: "TitleFont" }); - */ - BitmapFont.from = function (name, textStyle, options) { - if (!name) { - throw new Error('[BitmapFont] Property `name` is required.'); - } - var _a = Object.assign({}, BitmapFont.defaultOptions, options), chars = _a.chars, padding = _a.padding, resolution = _a.resolution, textureWidth = _a.textureWidth, textureHeight = _a.textureHeight; - var charsList = resolveCharacters(chars); - var style = textStyle instanceof TextStyle ? textStyle : new TextStyle(textStyle); - var lineWidth = textureWidth; - var fontData = new BitmapFontData(); - fontData.info[0] = { - face: style.fontFamily, - size: style.fontSize, - }; - fontData.common[0] = { - lineHeight: style.fontSize, - }; - var positionX = 0; - var positionY = 0; - var canvas; - var context; - var baseTexture; - var maxCharHeight = 0; - var textures = []; - for (var i = 0; i < charsList.length; i++) { - if (!canvas) { - canvas = document.createElement('canvas'); - canvas.width = textureWidth; - canvas.height = textureHeight; - context = canvas.getContext('2d'); - baseTexture = new BaseTexture(canvas, { resolution: resolution }); - textures.push(new Texture(baseTexture)); - fontData.page.push({ - id: textures.length - 1, - file: '', - }); - } - // Measure glyph dimensions - var metrics = TextMetrics.measureText(charsList[i], style, false, canvas); - var width = metrics.width; - var height = Math.ceil(metrics.height); - // This is ugly - but italics are given more space so they don't overlap - var textureGlyphWidth = Math.ceil((style.fontStyle === 'italic' ? 2 : 1) * width); - // Can't fit char anymore: next canvas please! - if (positionY >= textureHeight - (height * resolution)) { - if (positionY === 0) { - // We don't want user debugging an infinite loop (or do we? :) - throw new Error("[BitmapFont] textureHeight " + textureHeight + "px is " - + ("too small for " + style.fontSize + "px fonts")); - } - --i; - // Create new atlas once current has filled up - canvas = null; - context = null; - baseTexture = null; - positionY = 0; - positionX = 0; - maxCharHeight = 0; - continue; - } - maxCharHeight = Math.max(height + metrics.fontProperties.descent, maxCharHeight); - // Wrap line once full row has been rendered - if ((textureGlyphWidth * resolution) + positionX >= lineWidth) { - --i; - positionY += maxCharHeight * resolution; - positionY = Math.ceil(positionY); - positionX = 0; - maxCharHeight = 0; - continue; - } - drawGlyph(canvas, context, metrics, positionX, positionY, resolution, style); - // Unique (numeric) ID mapping to this glyph - var id = metrics.text.charCodeAt(0); - // Create a texture holding just the glyph - fontData.char.push({ - id: id, - page: textures.length - 1, - x: positionX / resolution, - y: positionY / resolution, - width: textureGlyphWidth, - height: height, - xoffset: 0, - yoffset: 0, - xadvance: Math.ceil(width - - (style.dropShadow ? style.dropShadowDistance : 0) - - (style.stroke ? style.strokeThickness : 0)), - }); - positionX += (textureGlyphWidth + (2 * padding)) * resolution; - positionX = Math.ceil(positionX); - } - var font = new BitmapFont(fontData, textures); - // Make it easier to replace a font - if (BitmapFont.available[name] !== undefined) { - BitmapFont.uninstall(name); - } - BitmapFont.available[name] = font; - return font; - }; - /** - * This character set includes all the letters in the alphabet (both lower- and upper- case). - * @readonly - * @static - * @member {string[][]} - * @example - * BitmapFont.from("ExampleFont", style, { chars: BitmapFont.ALPHA }) - */ - BitmapFont.ALPHA = [['a', 'z'], ['A', 'Z'], ' ']; - /** - * This character set includes all decimal digits (from 0 to 9). - * @readonly - * @static - * @member {string[][]} - * @example - * BitmapFont.from("ExampleFont", style, { chars: BitmapFont.NUMERIC }) - */ - BitmapFont.NUMERIC = [['0', '9']]; - /** - * This character set is the union of `BitmapFont.ALPHA` and `BitmapFont.NUMERIC`. - * @readonly - * @static - * @member {string[][]} - */ - BitmapFont.ALPHANUMERIC = [['a', 'z'], ['A', 'Z'], ['0', '9'], ' ']; - /** - * This character set consists of all the ASCII table. - * @readonly - * @static - * @member {string[][]} - * @see http://www.asciitable.com/ - */ - BitmapFont.ASCII = [[' ', '~']]; - /** - * Collection of default options when using `BitmapFont.from`. - * - * @readonly - * @static - * @member {PIXI.IBitmapFontOptions} - * @property {number} resolution=1 - * @property {number} textureWidth=512 - * @property {number} textureHeight=512 - * @property {number} padding=4 - * @property {string|string[]|string[][]} chars=PIXI.BitmapFont.ALPHANUMERIC - */ - BitmapFont.defaultOptions = { - resolution: 1, - textureWidth: 512, - textureHeight: 512, - padding: 4, - chars: BitmapFont.ALPHANUMERIC, - }; - /** - * Collection of available/installed fonts. - * - * @readonly - * @static - * @member {Object.} - */ - BitmapFont.available = {}; - return BitmapFont; - }()); - /** - * @memberof PIXI - * @interface IBitmapFontOptions - * @property {string | string[] | string[][]} [chars=PIXI.BitmapFont.ALPHANUMERIC] - the character set to generate - * @property {number} [resolution=1] - the resolution for rendering - * @property {number} [padding=4] - the padding between glyphs in the atlas - * @property {number} [textureWidth=512] - the width of the texture atlas - * @property {number} [textureHeight=512] - the height of the texture atlas - */ - - var pageMeshDataPool = []; - var charRenderDataPool = []; - /** - * A BitmapText object will create a line or multiple lines of text using bitmap font. - * - * The primary advantage of this class over Text is that all of your textures are pre-generated and loading, - * meaning that rendering is fast, and changing text has no performance implications. - * - * Supporting character sets other than latin, such as CJK languages, may be impractical due to the number of characters. - * - * To split a line you can use '\n', '\r' or '\r\n' in your string. - * - * PixiJS can auto-generate fonts on-the-fly using BitmapFont or use fnt files provided by: - * http://www.angelcode.com/products/bmfont/ for Windows or - * http://www.bmglyph.com/ for Mac. - * - * A BitmapText can only be created when the font is loaded. - * - * ```js - * // in this case the font is in a file called 'desyrel.fnt' - * let bitmapText = new PIXI.BitmapText("text using a fancy font!", {font: "35px Desyrel", align: "right"}); - * ``` - * - * @class - * @extends PIXI.Container - * @memberof PIXI - */ - var BitmapText = /** @class */ (function (_super) { - __extends$b(BitmapText, _super); - /** - * @param {string} text - A string that you would like the text to display. - * @param {object} style - The style parameters. - * @param {string} style.fontName - The installed BitmapFont name. - * @param {number} [style.fontSize] - The size of the font in pixels, e.g. 24. If undefined, - *. this will default to the BitmapFont size. - * @param {string} [style.align='left'] - Alignment for multiline text ('left', 'center' or 'right'), - * does not affect single line text. - * @param {number} [style.tint=0xFFFFFF] - The tint color. - * @param {number} [style.letterSpacing=0] - The amount of spacing between letters. - * @param {number} [style.maxWidth=0] - The max width of the text before line wrapping. - */ - function BitmapText(text, style) { - if (style === void 0) { style = {}; } - var _this = _super.call(this) || this; - _this._tint = 0xFFFFFF; - if (style.font) { - deprecation('5.3.0', 'PIXI.BitmapText constructor style.font property is deprecated.'); - _this._upgradeStyle(style); - } - // Apply the defaults - var _a = Object.assign({}, BitmapText.styleDefaults, style), align = _a.align, tint = _a.tint, maxWidth = _a.maxWidth, letterSpacing = _a.letterSpacing, fontName = _a.fontName, fontSize = _a.fontSize; - if (!BitmapFont.available[fontName]) { - throw new Error("Missing BitmapFont \"" + fontName + "\""); - } - /** - * Collection of page mesh data. - * - * @member {object} - * @private - */ - _this._activePagesMeshData = []; - /** - * Private tracker for the width of the overall text - * - * @member {number} - * @private - */ - _this._textWidth = 0; - /** - * Private tracker for the height of the overall text - * - * @member {number} - * @private - */ - _this._textHeight = 0; - /** - * Private tracker for the current text align. - * - * @member {string} - * @private - */ - _this._align = align; - /** - * Private tracker for the current tint. - * - * @member {number} - * @private - */ - _this._tint = tint; - /** - * Private tracker for the current font name. - * - * @member {string} - * @private - */ - _this._fontName = fontName; - /** - * Private tracker for the current font size. - * - * @member {number} - * @private - */ - _this._fontSize = fontSize || BitmapFont.available[fontName].size; - /** - * Private tracker for the current text. - * - * @member {string} - * @private - */ - _this._text = text; - /** - * The max width of this bitmap text in pixels. If the text provided is longer than the - * value provided, line breaks will be automatically inserted in the last whitespace. - * Disable by setting value to 0 - * - * @member {number} - * @private - */ - _this._maxWidth = maxWidth; - /** - * The max line height. This is useful when trying to use the total height of the Text, - * ie: when trying to vertically align. (Internally used) - * - * @member {number} - * @private - */ - _this._maxLineHeight = 0; - /** - * Letter spacing. This is useful for setting the space between characters. - * @member {number} - * @private - */ - _this._letterSpacing = letterSpacing; - /** - * Text anchor. read-only - * - * @member {PIXI.ObservablePoint} - * @private - */ - _this._anchor = new ObservablePoint(function () { _this.dirty = true; }, _this, 0, 0); - /** - * If true PixiJS will Math.floor() x/y values when rendering, stopping pixel interpolation. - * Advantages can include sharper image quality (like text) and faster rendering on canvas. - * The main disadvantage is movement of objects may appear less smooth. - * To set the global default, change {@link PIXI.settings.ROUND_PIXELS} - * - * @member {boolean} - * @default PIXI.settings.ROUND_PIXELS - */ - _this.roundPixels = settings.ROUND_PIXELS; - /** - * Set to `true` if the BitmapText needs to be redrawn. - * - * @member {boolean} - */ - _this.dirty = true; - return _this; - } - /** - * Renders text and updates it when needed. This should only be called - * if the BitmapFont is regenerated. - */ - BitmapText.prototype.updateText = function () { - var _a; - var data = BitmapFont.available[this._fontName]; - var scale = this._fontSize / data.size; - var pos = new Point(); - var chars = []; - var lineWidths = []; - var text = this._text.replace(/(?:\r\n|\r)/g, '\n') || ' '; - var textLength = text.length; - var maxWidth = this._maxWidth * data.size / this._fontSize; - var prevCharCode = null; - var lastLineWidth = 0; - var maxLineWidth = 0; - var line = 0; - var lastBreakPos = -1; - var lastBreakWidth = 0; - var spacesRemoved = 0; - var maxLineHeight = 0; - for (var i = 0; i < textLength; i++) { - var charCode = text.charCodeAt(i); - var char = text.charAt(i); - if ((/(?:\s)/).test(char)) { - lastBreakPos = i; - lastBreakWidth = lastLineWidth; - } - if (char === '\r' || char === '\n') { - lineWidths.push(lastLineWidth); - maxLineWidth = Math.max(maxLineWidth, lastLineWidth); - ++line; - ++spacesRemoved; - pos.x = 0; - pos.y += data.lineHeight; - prevCharCode = null; - continue; - } - var charData = data.chars[charCode]; - if (!charData) { - continue; - } - if (prevCharCode && charData.kerning[prevCharCode]) { - pos.x += charData.kerning[prevCharCode]; - } - var charRenderData = charRenderDataPool.pop() || { - texture: Texture.EMPTY, - line: 0, - charCode: 0, - position: new Point(), - }; - charRenderData.texture = charData.texture; - charRenderData.line = line; - charRenderData.charCode = charCode; - charRenderData.position.x = pos.x + charData.xOffset + (this._letterSpacing / 2); - charRenderData.position.y = pos.y + charData.yOffset; - chars.push(charRenderData); - pos.x += charData.xAdvance + this._letterSpacing; - lastLineWidth = pos.x; - maxLineHeight = Math.max(maxLineHeight, (charData.yOffset + charData.texture.height)); - prevCharCode = charCode; - if (lastBreakPos !== -1 && maxWidth > 0 && pos.x > maxWidth) { - ++spacesRemoved; - removeItems(chars, 1 + lastBreakPos - spacesRemoved, 1 + i - lastBreakPos); - i = lastBreakPos; - lastBreakPos = -1; - lineWidths.push(lastBreakWidth); - maxLineWidth = Math.max(maxLineWidth, lastBreakWidth); - line++; - pos.x = 0; - pos.y += data.lineHeight; - prevCharCode = null; - } - } - var lastChar = text.charAt(text.length - 1); - if (lastChar !== '\r' && lastChar !== '\n') { - if ((/(?:\s)/).test(lastChar)) { - lastLineWidth = lastBreakWidth; - } - lineWidths.push(lastLineWidth); - maxLineWidth = Math.max(maxLineWidth, lastLineWidth); - } - var lineAlignOffsets = []; - for (var i = 0; i <= line; i++) { - var alignOffset = 0; - if (this._align === 'right') { - alignOffset = maxLineWidth - lineWidths[i]; - } - else if (this._align === 'center') { - alignOffset = (maxLineWidth - lineWidths[i]) / 2; - } - lineAlignOffsets.push(alignOffset); - } - var lenChars = chars.length; - var pagesMeshData = {}; - var newPagesMeshData = []; - var activePagesMeshData = this._activePagesMeshData; - for (var i = 0; i < activePagesMeshData.length; i++) { - pageMeshDataPool.push(activePagesMeshData[i]); - } - for (var i = 0; i < lenChars; i++) { - var texture = chars[i].texture; - var baseTextureUid = texture.baseTexture.uid; - if (!pagesMeshData[baseTextureUid]) { - var pageMeshData = pageMeshDataPool.pop(); - if (!pageMeshData) { - var geometry = new MeshGeometry(); - var material = new MeshMaterial(Texture.EMPTY); - var mesh = new Mesh(geometry, material); - pageMeshData = { - index: 0, - indexCount: 0, - vertexCount: 0, - uvsCount: 0, - total: 0, - mesh: mesh, - vertices: null, - uvs: null, - indices: null, - }; - } - // reset data.. - pageMeshData.index = 0; - pageMeshData.indexCount = 0; - pageMeshData.vertexCount = 0; - pageMeshData.uvsCount = 0; - pageMeshData.total = 0; - // TODO need to get page texture here somehow.. - pageMeshData.mesh.texture = new Texture(texture.baseTexture); - pageMeshData.mesh.tint = this._tint; - newPagesMeshData.push(pageMeshData); - pagesMeshData[baseTextureUid] = pageMeshData; - } - pagesMeshData[baseTextureUid].total++; - } - // lets find any previously active pageMeshDatas that are no longer required for - // the updated text (if any), removed and return them to the pool. - for (var i = 0; i < activePagesMeshData.length; i++) { - if (newPagesMeshData.indexOf(activePagesMeshData[i]) === -1) { - this.removeChild(activePagesMeshData[i].mesh); - } - } - // next lets add any new meshes, that have not yet been added to this BitmapText - // we only add if its not already a child of this BitmapObject - for (var i = 0; i < newPagesMeshData.length; i++) { - if (newPagesMeshData[i].mesh.parent !== this) { - this.addChild(newPagesMeshData[i].mesh); - } - } - // active page mesh datas are set to be the new pages added. - this._activePagesMeshData = newPagesMeshData; - for (var i in pagesMeshData) { - var pageMeshData = pagesMeshData[i]; - var total = pageMeshData.total; - // lets only allocate new buffers if we can fit the new text in the current ones.. - // unless that is, we will be batching. Currently batching dose not respect the size property of mesh - if (!(((_a = pageMeshData.indices) === null || _a === void 0 ? void 0 : _a.length) > 6 * total) || pageMeshData.vertices.length < Mesh.BATCHABLE_SIZE * 2) { - pageMeshData.vertices = new Float32Array(4 * 2 * total); - pageMeshData.uvs = new Float32Array(4 * 2 * total); - pageMeshData.indices = new Uint16Array(6 * total); - } - // as a buffer maybe bigger than the current word, we set the size of the meshMaterial - // to match the number of letters needed - pageMeshData.mesh.size = 6 * total; - } - for (var i = 0; i < lenChars; i++) { - var char = chars[i]; - var xPos = (char.position.x + lineAlignOffsets[char.line]) * scale; - var yPos = char.position.y * scale; - var texture = char.texture; - var pageMesh = pagesMeshData[texture.baseTexture.uid]; - var textureFrame = texture.frame; - var textureUvs = texture._uvs; - var index = pageMesh.index++; - pageMesh.indices[(index * 6) + 0] = 0 + (index * 4); - pageMesh.indices[(index * 6) + 1] = 1 + (index * 4); - pageMesh.indices[(index * 6) + 2] = 2 + (index * 4); - pageMesh.indices[(index * 6) + 3] = 0 + (index * 4); - pageMesh.indices[(index * 6) + 4] = 2 + (index * 4); - pageMesh.indices[(index * 6) + 5] = 3 + (index * 4); - pageMesh.vertices[(index * 8) + 0] = xPos; - pageMesh.vertices[(index * 8) + 1] = yPos; - pageMesh.vertices[(index * 8) + 2] = xPos + (textureFrame.width * scale); - pageMesh.vertices[(index * 8) + 3] = yPos; - pageMesh.vertices[(index * 8) + 4] = xPos + (textureFrame.width * scale); - pageMesh.vertices[(index * 8) + 5] = yPos + (textureFrame.height * scale); - pageMesh.vertices[(index * 8) + 6] = xPos; - pageMesh.vertices[(index * 8) + 7] = yPos + (textureFrame.height * scale); - pageMesh.uvs[(index * 8) + 0] = textureUvs.x0; - pageMesh.uvs[(index * 8) + 1] = textureUvs.y0; - pageMesh.uvs[(index * 8) + 2] = textureUvs.x1; - pageMesh.uvs[(index * 8) + 3] = textureUvs.y1; - pageMesh.uvs[(index * 8) + 4] = textureUvs.x2; - pageMesh.uvs[(index * 8) + 5] = textureUvs.y2; - pageMesh.uvs[(index * 8) + 6] = textureUvs.x3; - pageMesh.uvs[(index * 8) + 7] = textureUvs.y3; - } - this._textWidth = maxLineWidth * scale; - this._textHeight = (pos.y + data.lineHeight) * scale; - for (var i in pagesMeshData) { - var pageMeshData = pagesMeshData[i]; - // apply anchor - if (this.anchor.x !== 0 || this.anchor.y !== 0) { - var vertexCount = 0; - var anchorOffsetX = this._textWidth * this.anchor.x; - var anchorOffsetY = this._textHeight * this.anchor.y; - for (var i_1 = 0; i_1 < pageMeshData.total; i_1++) { - pageMeshData.vertices[vertexCount++] -= anchorOffsetX; - pageMeshData.vertices[vertexCount++] -= anchorOffsetY; - pageMeshData.vertices[vertexCount++] -= anchorOffsetX; - pageMeshData.vertices[vertexCount++] -= anchorOffsetY; - pageMeshData.vertices[vertexCount++] -= anchorOffsetX; - pageMeshData.vertices[vertexCount++] -= anchorOffsetY; - pageMeshData.vertices[vertexCount++] -= anchorOffsetX; - pageMeshData.vertices[vertexCount++] -= anchorOffsetY; - } - } - this._maxLineHeight = maxLineHeight * scale; - var vertexBuffer = pageMeshData.mesh.geometry.getBuffer('aVertexPosition'); - var textureBuffer = pageMeshData.mesh.geometry.getBuffer('aTextureCoord'); - var indexBuffer = pageMeshData.mesh.geometry.getIndex(); - vertexBuffer.data = pageMeshData.vertices; - textureBuffer.data = pageMeshData.uvs; - indexBuffer.data = pageMeshData.indices; - vertexBuffer.update(); - textureBuffer.update(); - indexBuffer.update(); - } - for (var i = 0; i < chars.length; i++) { - charRenderDataPool.push(chars[i]); - } - }; - /** - * Updates the transform of this object - * - * @private - */ - BitmapText.prototype.updateTransform = function () { - this.validate(); - this.containerUpdateTransform(); - }; - /** - * Validates text before calling parent's getLocalBounds - * - * @return {PIXI.Rectangle} The rectangular bounding area - */ - BitmapText.prototype.getLocalBounds = function () { - this.validate(); - return _super.prototype.getLocalBounds.call(this); - }; - /** - * Updates text when needed - * - * @private - */ - BitmapText.prototype.validate = function () { - if (this.dirty) { - this.updateText(); - this.dirty = false; - } - }; - Object.defineProperty(BitmapText.prototype, "tint", { - /** - * The tint of the BitmapText object. - * - * @member {number} - * @default 0xffffff - */ - get: function () { - return this._tint; - }, - set: function (value) { - if (this._tint === value) - { return; } - this._tint = value; - for (var i = 0; i < this._activePagesMeshData.length; i++) { - this._activePagesMeshData[i].mesh.tint = value; - } - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BitmapText.prototype, "align", { - /** - * The alignment of the BitmapText object. - * - * @member {string} - * @default 'left' - */ - get: function () { - return this._align; - }, - set: function (value) { - if (this._align !== value) { - this._align = value; - this.dirty = true; - } - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BitmapText.prototype, "fontName", { - /** - * The name of the BitmapFont. - * - * @member {string} - */ - get: function () { - return this._fontName; - }, - set: function (value) { - if (!BitmapFont.available[value]) { - throw new Error("Missing BitmapFont \"" + value + "\""); - } - if (this._fontName !== value) { - this._fontName = value; - this.dirty = true; - } - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BitmapText.prototype, "fontSize", { - /** - * The size of the font to display. - * - * @member {number} - */ - get: function () { - return this._fontSize; - }, - set: function (value) { - if (this._fontSize !== value) { - this._fontSize = value; - this.dirty = true; - } - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BitmapText.prototype, "anchor", { - /** - * The anchor sets the origin point of the text. - * - * The default is `(0,0)`, this means the text's origin is the top left. - * - * Setting the anchor to `(0.5,0.5)` means the text's origin is centered. - * - * Setting the anchor to `(1,1)` would mean the text's origin point will be the bottom right corner. - * - * @member {PIXI.Point | number} - */ - get: function () { - return this._anchor; - }, - set: function (value) { - if (typeof value === 'number') { - this._anchor.set(value); - } - else { - this._anchor.copyFrom(value); - } - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BitmapText.prototype, "text", { - /** - * The text of the BitmapText object. - * - * @member {string} - */ - get: function () { - return this._text; - }, - set: function (text) { - text = String(text === null || text === undefined ? '' : text); - if (this._text === text) { - return; - } - this._text = text; - this.dirty = true; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BitmapText.prototype, "maxWidth", { - /** - * The max width of this bitmap text in pixels. If the text provided is longer than the - * value provided, line breaks will be automatically inserted in the last whitespace. - * Disable by setting the value to 0. - * - * @member {number} - */ - get: function () { - return this._maxWidth; - }, - set: function (value) { - if (this._maxWidth === value) { - return; - } - this._maxWidth = value; - this.dirty = true; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BitmapText.prototype, "maxLineHeight", { - /** - * The max line height. This is useful when trying to use the total height of the Text, - * i.e. when trying to vertically align. - * - * @member {number} - * @readonly - */ - get: function () { - this.validate(); - return this._maxLineHeight; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BitmapText.prototype, "textWidth", { - /** - * The width of the overall text, different from fontSize, - * which is defined in the style object. - * - * @member {number} - * @readonly - */ - get: function () { - this.validate(); - return this._textWidth; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BitmapText.prototype, "letterSpacing", { - /** - * Additional space between characters. - * - * @member {number} - */ - get: function () { - return this._letterSpacing; - }, - set: function (value) { - if (this._letterSpacing !== value) { - this._letterSpacing = value; - this.dirty = true; - } - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BitmapText.prototype, "textHeight", { - /** - * The height of the overall text, different from fontSize, - * which is defined in the style object. - * - * @member {number} - * @readonly - */ - get: function () { - this.validate(); - return this._textHeight; - }, - enumerable: false, - configurable: true - }); - /** - * For backward compatibility, convert old style.font constructor param to fontName & fontSize properties. - * - * @private - * @deprecated since 5.3.0 - */ - BitmapText.prototype._upgradeStyle = function (style) { - if (typeof style.font === 'string') { - var valueSplit = style.font.split(' '); - style.fontName = valueSplit.length === 1 - ? valueSplit[0] - : valueSplit.slice(1).join(' '); - if (valueSplit.length >= 2) { - style.fontSize = parseInt(valueSplit[0], 10); - } - } - else { - style.fontName = style.font.name; - style.fontSize = typeof style.font.size === 'number' - ? style.font.size - : parseInt(style.font.size, 10); - } - }; - /** - * Register a bitmap font with data and a texture. - * - * @deprecated since 5.3.0 - * @see PIXI.BitmapFont.install - * @static - */ - BitmapText.registerFont = function (data, textures) { - deprecation('5.3.0', 'PIXI.BitmapText.registerFont is deprecated, use PIXI.BitmapFont.install'); - return BitmapFont.install(data, textures); - }; - Object.defineProperty(BitmapText, "fonts", { - /** - * Get the list of installed fonts. - * - * @see PIXI.BitmapFont.available - * @deprecated since 5.3.0 - * @static - * @readonly - * @member {Object.} - */ - get: function () { - deprecation('5.3.0', 'PIXI.BitmapText.fonts is deprecated, use PIXI.BitmapFont.available'); - return BitmapFont.available; - }, - enumerable: false, - configurable: true - }); - BitmapText.styleDefaults = { - align: 'left', - tint: 0xFFFFFF, - maxWidth: 0, - letterSpacing: 0, - }; - return BitmapText; - }(Container)); - - /** - * {@link PIXI.Loader Loader} middleware for loading - * bitmap-based fonts suitable for using with {@link PIXI.BitmapText}. - * @class - * @memberof PIXI - * @implements PIXI.ILoaderPlugin - */ - var BitmapFontLoader = /** @class */ (function () { - function BitmapFontLoader() { - } - /** - * Called when the plugin is installed. - * - * @see PIXI.Loader.registerPlugin - */ - BitmapFontLoader.add = function () { - LoaderResource.setExtensionXhrType('fnt', LoaderResource.XHR_RESPONSE_TYPE.DOCUMENT); - }; - /** - * Called after a resource is loaded. - * @see PIXI.Loader.loaderMiddleware - * @param {PIXI.LoaderResource} resource - * @param {function} next - */ - BitmapFontLoader.use = function (resource, next) { - var format = autoDetectFormat(resource.data); - // Resource was not recognised as any of the expected font data format - if (!format) { - next(); - return; - } - var baseUrl = BitmapFontLoader.getBaseUrl(this, resource); - var data = format.parse(resource.data); - var textures = {}; - // Handle completed, when the number of textures - // load is the same number as references in the fnt file - var completed = function (page) { - textures[page.metadata.pageFile] = page.texture; - if (Object.keys(textures).length === data.page.length) { - resource.bitmapFont = BitmapFont.install(data, textures); - next(); - } - }; - for (var i = 0; i < data.page.length; ++i) { - var pageFile = data.page[i].file; - var url = baseUrl + pageFile; - var exists = false; - // incase the image is loaded outside - // using the same loader, resource will be available - for (var name in this.resources) { - var bitmapResource = this.resources[name]; - if (bitmapResource.url === url) { - bitmapResource.metadata.pageFile = pageFile; - if (bitmapResource.texture) { - completed(bitmapResource); - } - else { - bitmapResource.onAfterMiddleware.add(completed); - } - exists = true; - break; - } - } - // texture is not loaded, we'll attempt to add - // it to the load and add the texture to the list - if (!exists) { - // Standard loading options for images - var options = { - crossOrigin: resource.crossOrigin, - loadType: LoaderResource.LOAD_TYPE.IMAGE, - metadata: Object.assign({ pageFile: pageFile }, resource.metadata.imageMetadata), - parentResource: resource, - }; - this.add(url, options, completed); - } - } - }; - /** - * Get folder path from a resource - * @private - * @param {PIXI.Loader} loader - * @param {PIXI.LoaderResource} resource - * @return {string} - */ - BitmapFontLoader.getBaseUrl = function (loader, resource) { - var resUrl = !resource.isDataUrl ? BitmapFontLoader.dirname(resource.url) : ''; - if (resource.isDataUrl) { - if (resUrl === '.') { - resUrl = ''; - } - if (loader.baseUrl && resUrl) { - // if baseurl has a trailing slash then add one to resUrl so the replace works below - if (loader.baseUrl.charAt(loader.baseUrl.length - 1) === '/') { - resUrl += '/'; - } - } - } - // remove baseUrl from resUrl - resUrl = resUrl.replace(loader.baseUrl, ''); - // if there is an resUrl now, it needs a trailing slash. Ensure that it does if the string isn't empty. - if (resUrl && resUrl.charAt(resUrl.length - 1) !== '/') { - resUrl += '/'; - } - return resUrl; - }; - /** - * Replacement for NodeJS's path.dirname - * @private - * @param {string} url - Path to get directory for - */ - BitmapFontLoader.dirname = function (url) { - var dir = url - .replace(/\\/g, '/') // convert windows notation to UNIX notation, URL-safe because it's a forbidden character - .replace(/\/$/, '') // replace trailing slash - .replace(/\/[^\/]*$/, ''); // remove everything after the last - // File request is relative, use current directory - if (dir === url) { - return '.'; - } - // Started with a slash - else if (dir === '') { - return '/'; - } - return dir; - }; - return BitmapFontLoader; - }()); - - /*! - * @pixi/filter-alpha - v5.3.3 - * Compiled Tue, 04 Aug 2020 16:23:09 UTC - * - * @pixi/filter-alpha is licensed under the MIT License. - * http://www.opensource.org/licenses/mit-license - */ - - /*! ***************************************************************************** - Copyright (c) Microsoft Corporation. All rights reserved. - Licensed under the Apache License, Version 2.0 (the "License"); you may not use - this file except in compliance with the License. You may obtain a copy of the - License at http://www.apache.org/licenses/LICENSE-2.0 + function __extends$e(d, b) { + extendStatics$e(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + } + + function fixOrientation(points, hole) { + var _a, _b; + if (hole === void 0) { hole = false; } + var m = points.length; + if (m < 6) { + return; + } + var area = 0; + for (var i = 0, x1 = points[m - 2], y1 = points[m - 1]; i < m; i += 2) { + var x2 = points[i]; + var y2 = points[i + 1]; + area += (x2 - x1) * (y2 + y1); + x1 = x2; + y1 = y2; + } + if ((!hole && area > 0) || (hole && area <= 0)) { + var n = m / 2; + for (var i = n + (n % 2); i < m; i += 2) { + var i1 = m - i - 2; + var i2 = m - i - 1; + var i3 = i; + var i4 = i + 1; + _a = [points[i3], points[i1]], points[i1] = _a[0], points[i3] = _a[1]; + _b = [points[i4], points[i2]], points[i2] = _b[0], points[i4] = _b[1]; + } + } + } + /** + * Builds a polygon to draw + * + * Ignored from docs since it is not directly exposed. + * @ignore + * @private + * @param {PIXI.WebGLGraphicsData} graphicsData - The graphics object containing all the necessary properties + * @param {object} webGLData - an object containing all the WebGL-specific information to create this shape + * @param {object} webGLDataNativeLines - an object containing all the WebGL-specific information to create nativeLines + */ + var buildPoly = { + build: function (graphicsData) { + graphicsData.points = graphicsData.shape.points.slice(); + }, + triangulate: function (graphicsData, graphicsGeometry) { + var points = graphicsData.points; + var holes = graphicsData.holes; + var verts = graphicsGeometry.points; + var indices = graphicsGeometry.indices; + if (points.length >= 6) { + fixOrientation(points, false); + var holeArray = []; + // Process holes.. + for (var i = 0; i < holes.length; i++) { + var hole = holes[i]; + fixOrientation(hole.points, true); + holeArray.push(points.length / 2); + points = points.concat(hole.points); + } + // sort color + var triangles = earcut_1(points, holeArray, 2); + if (!triangles) { + return; + } + var vertPos = verts.length / 2; + for (var i = 0; i < triangles.length; i += 3) { + indices.push(triangles[i] + vertPos); + indices.push(triangles[i + 1] + vertPos); + indices.push(triangles[i + 2] + vertPos); + } + for (var i = 0; i < points.length; i++) { + verts.push(points[i]); + } + } + }, + }; + + // for type only + /** + * Builds a circle to draw + * + * Ignored from docs since it is not directly exposed. + * @ignore + * @private + * @param {PIXI.WebGLGraphicsData} graphicsData - The graphics object to draw + * @param {object} webGLData - an object containing all the WebGL-specific information to create this shape + * @param {object} webGLDataNativeLines - an object containing all the WebGL-specific information to create nativeLines + */ + var buildCircle = { + build: function (graphicsData) { + // need to convert points to a nice regular data + var points = graphicsData.points; + var x; + var y; + var dx; + var dy; + var rx; + var ry; + if (graphicsData.type === exports.SHAPES.CIRC) { + var circle = graphicsData.shape; + x = circle.x; + y = circle.y; + rx = ry = circle.radius; + dx = dy = 0; + } + else if (graphicsData.type === exports.SHAPES.ELIP) { + var ellipse = graphicsData.shape; + x = ellipse.x; + y = ellipse.y; + rx = ellipse.width; + ry = ellipse.height; + dx = dy = 0; + } + else { + var roundedRect = graphicsData.shape; + var halfWidth = roundedRect.width / 2; + var halfHeight = roundedRect.height / 2; + x = roundedRect.x + halfWidth; + y = roundedRect.y + halfHeight; + rx = ry = Math.max(0, Math.min(roundedRect.radius, Math.min(halfWidth, halfHeight))); + dx = halfWidth - rx; + dy = halfHeight - ry; + } + if (!(rx >= 0 && ry >= 0 && dx >= 0 && dy >= 0)) { + points.length = 0; + return; + } + // Choose a number of segments such that the maximum absolute deviation from the circle is approximately 0.029 + var n = Math.ceil(2.3 * Math.sqrt(rx + ry)); + var m = (n * 8) + (dx ? 4 : 0) + (dy ? 4 : 0); + points.length = m; + if (m === 0) { + return; + } + if (n === 0) { + points.length = 8; + points[0] = points[6] = x + dx; + points[1] = points[3] = y + dy; + points[2] = points[4] = x - dx; + points[5] = points[7] = y - dy; + return; + } + var j1 = 0; + var j2 = (n * 4) + (dx ? 2 : 0) + 2; + var j3 = j2; + var j4 = m; + { + var x0 = dx + rx; + var y0 = dy; + var x1 = x + x0; + var x2 = x - x0; + var y1 = y + y0; + points[j1++] = x1; + points[j1++] = y1; + points[--j2] = y1; + points[--j2] = x2; + if (dy) { + var y2 = y - y0; + points[j3++] = x2; + points[j3++] = y2; + points[--j4] = y2; + points[--j4] = x1; + } + } + for (var i = 1; i < n; i++) { + var a = Math.PI / 2 * (i / n); + var x0 = dx + (Math.cos(a) * rx); + var y0 = dy + (Math.sin(a) * ry); + var x1 = x + x0; + var x2 = x - x0; + var y1 = y + y0; + var y2 = y - y0; + points[j1++] = x1; + points[j1++] = y1; + points[--j2] = y1; + points[--j2] = x2; + points[j3++] = x2; + points[j3++] = y2; + points[--j4] = y2; + points[--j4] = x1; + } + { + var x0 = dx; + var y0 = dy + ry; + var x1 = x + x0; + var x2 = x - x0; + var y1 = y + y0; + var y2 = y - y0; + points[j1++] = x1; + points[j1++] = y1; + points[--j4] = y2; + points[--j4] = x1; + if (dx) { + points[j1++] = x2; + points[j1++] = y1; + points[--j4] = y2; + points[--j4] = x2; + } + } + }, + triangulate: function (graphicsData, graphicsGeometry) { + var points = graphicsData.points; + var verts = graphicsGeometry.points; + var indices = graphicsGeometry.indices; + if (points.length === 0) { + return; + } + var vertPos = verts.length / 2; + var center = vertPos; + var x; + var y; + if (graphicsData.type !== exports.SHAPES.RREC) { + var circle = graphicsData.shape; + x = circle.x; + y = circle.y; + } + else { + var roundedRect = graphicsData.shape; + x = roundedRect.x + (roundedRect.width / 2); + y = roundedRect.y + (roundedRect.height / 2); + } + var matrix = graphicsData.matrix; + // Push center (special point) + verts.push(graphicsData.matrix ? (matrix.a * x) + (matrix.c * y) + matrix.tx : x, graphicsData.matrix ? (matrix.b * x) + (matrix.d * y) + matrix.ty : y); + vertPos++; + verts.push(points[0], points[1]); + for (var i = 2; i < points.length; i += 2) { + verts.push(points[i], points[i + 1]); + // add some uvs + indices.push(vertPos++, center, vertPos); + } + indices.push(center + 1, center, vertPos); + }, + }; + + /** + * Builds a rectangle to draw + * + * Ignored from docs since it is not directly exposed. + * @ignore + * @private + * @param {PIXI.WebGLGraphicsData} graphicsData - The graphics object containing all the necessary properties + * @param {object} webGLData - an object containing all the WebGL-specific information to create this shape + * @param {object} webGLDataNativeLines - an object containing all the WebGL-specific information to create nativeLines + */ + var buildRectangle = { + build: function (graphicsData) { + // --- // + // need to convert points to a nice regular data + // + var rectData = graphicsData.shape; + var x = rectData.x; + var y = rectData.y; + var width = rectData.width; + var height = rectData.height; + var points = graphicsData.points; + points.length = 0; + points.push(x, y, x + width, y, x + width, y + height, x, y + height); + }, + triangulate: function (graphicsData, graphicsGeometry) { + var points = graphicsData.points; + var verts = graphicsGeometry.points; + var vertPos = verts.length / 2; + verts.push(points[0], points[1], points[2], points[3], points[6], points[7], points[4], points[5]); + graphicsGeometry.indices.push(vertPos, vertPos + 1, vertPos + 2, vertPos + 1, vertPos + 2, vertPos + 3); + }, + }; + + /** + * Calculate a single point for a quadratic bezier curve. + * Utility function used by quadraticBezierCurve. + * Ignored from docs since it is not directly exposed. + * @ignore + * @private + * @param {number} n1 - first number + * @param {number} n2 - second number + * @param {number} perc - percentage + * @returns {number} the result + */ + function getPt(n1, n2, perc) { + var diff = n2 - n1; + return n1 + (diff * perc); + } + /** + * Calculate the points for a quadratic bezier curve. (helper function..) + * Based on: https://stackoverflow.com/questions/785097/how-do-i-implement-a-bezier-curve-in-c + * + * Ignored from docs since it is not directly exposed. + * @ignore + * @private + * @param {number} fromX - Origin point x + * @param {number} fromY - Origin point x + * @param {number} cpX - Control point x + * @param {number} cpY - Control point y + * @param {number} toX - Destination point x + * @param {number} toY - Destination point y + * @param {number[]} [out=[]] - The output array to add points into. If not passed, a new array is created. + * @returns {number[]} an array of points + */ + function quadraticBezierCurve(fromX, fromY, cpX, cpY, toX, toY, out) { + if (out === void 0) { out = []; } + var n = 20; + var points = out; + var xa = 0; + var ya = 0; + var xb = 0; + var yb = 0; + var x = 0; + var y = 0; + for (var i = 0, j = 0; i <= n; ++i) { + j = i / n; + // The Green Line + xa = getPt(fromX, cpX, j); + ya = getPt(fromY, cpY, j); + xb = getPt(cpX, toX, j); + yb = getPt(cpY, toY, j); + // The Black Dot + x = getPt(xa, xb, j); + y = getPt(ya, yb, j); + // Handle case when first curve points overlaps and earcut fails to triangulate + if (i === 0 && points[points.length - 2] === x && points[points.length - 1] === y) { + continue; + } + points.push(x, y); + } + return points; + } + /** + * Builds a rounded rectangle to draw + * + * Ignored from docs since it is not directly exposed. + * @ignore + * @private + * @param {PIXI.WebGLGraphicsData} graphicsData - The graphics object containing all the necessary properties + * @param {object} webGLData - an object containing all the WebGL-specific information to create this shape + * @param {object} webGLDataNativeLines - an object containing all the WebGL-specific information to create nativeLines + */ + var buildRoundedRectangle = { + build: function (graphicsData) { + if (Graphics.nextRoundedRectBehavior) { + buildCircle.build(graphicsData); + return; + } + var rrectData = graphicsData.shape; + var points = graphicsData.points; + var x = rrectData.x; + var y = rrectData.y; + var width = rrectData.width; + var height = rrectData.height; + // Don't allow negative radius or greater than half the smallest width + var radius = Math.max(0, Math.min(rrectData.radius, Math.min(width, height) / 2)); + points.length = 0; + // No radius, do a simple rectangle + if (!radius) { + points.push(x, y, x + width, y, x + width, y + height, x, y + height); + } + else { + quadraticBezierCurve(x, y + radius, x, y, x + radius, y, points); + quadraticBezierCurve(x + width - radius, y, x + width, y, x + width, y + radius, points); + quadraticBezierCurve(x + width, y + height - radius, x + width, y + height, x + width - radius, y + height, points); + quadraticBezierCurve(x + radius, y + height, x, y + height, x, y + height - radius, points); + } + }, + triangulate: function (graphicsData, graphicsGeometry) { + if (Graphics.nextRoundedRectBehavior) { + buildCircle.triangulate(graphicsData, graphicsGeometry); + return; + } + var points = graphicsData.points; + var verts = graphicsGeometry.points; + var indices = graphicsGeometry.indices; + var vecPos = verts.length / 2; + var triangles = earcut_1(points, null, 2); + for (var i = 0, j = triangles.length; i < j; i += 3) { + indices.push(triangles[i] + vecPos); + // indices.push(triangles[i] + vecPos); + indices.push(triangles[i + 1] + vecPos); + // indices.push(triangles[i + 2] + vecPos); + indices.push(triangles[i + 2] + vecPos); + } + for (var i = 0, j = points.length; i < j; i++) { + verts.push(points[i], points[++i]); + } + }, + }; + + /** + * Buffers vertices to draw a square cap. + * + * Ignored from docs since it is not directly exposed. + * @ignore + * @private + * @param {number} x - X-coord of end point + * @param {number} y - Y-coord of end point + * @param {number} nx - X-coord of line normal pointing inside + * @param {number} ny - Y-coord of line normal pointing inside + * @param {number} innerWeight - Weight of inner points + * @param {number} outerWeight - Weight of outer points + * @param {boolean} clockwise - Whether the cap is drawn clockwise + * @param {Array} verts - vertex buffer + * @returns {number} - no. of vertices pushed + */ + function square(x, y, nx, ny, innerWeight, outerWeight, clockwise, /* rotation for square (true at left end, false at right end) */ verts) { + var ix = x - (nx * innerWeight); + var iy = y - (ny * innerWeight); + var ox = x + (nx * outerWeight); + var oy = y + (ny * outerWeight); + /* Rotate nx,ny for extension vector */ + var exx; + var eyy; + if (clockwise) { + exx = ny; + eyy = -nx; + } + else { + exx = -ny; + eyy = nx; + } + /* [i|0]x,y extended at cap */ + var eix = ix + exx; + var eiy = iy + eyy; + var eox = ox + exx; + var eoy = oy + eyy; + /* Square itself must be inserted clockwise*/ + verts.push(eix, eiy); + verts.push(eox, eoy); + return 2; + } + /** + * Buffers vertices to draw an arc at the line joint or cap. + * + * Ignored from docs since it is not directly exposed. + * @ignore + * @private + * @param {number} cx - X-coord of center + * @param {number} cy - Y-coord of center + * @param {number} sx - X-coord of arc start + * @param {number} sy - Y-coord of arc start + * @param {number} ex - X-coord of arc end + * @param {number} ey - Y-coord of arc end + * @param {Array} verts - buffer of vertices + * @param {boolean} clockwise - orientation of vertices + * @returns {number} - no. of vertices pushed + */ + function round(cx, cy, sx, sy, ex, ey, verts, clockwise) { + var cx2p0x = sx - cx; + var cy2p0y = sy - cy; + var angle0 = Math.atan2(cx2p0x, cy2p0y); + var angle1 = Math.atan2(ex - cx, ey - cy); + if (clockwise && angle0 < angle1) { + angle0 += Math.PI * 2; + } + else if (!clockwise && angle0 > angle1) { + angle1 += Math.PI * 2; + } + var startAngle = angle0; + var angleDiff = angle1 - angle0; + var absAngleDiff = Math.abs(angleDiff); + /* if (absAngleDiff >= PI_LBOUND && absAngleDiff <= PI_UBOUND) + { + const r1x = cx - nxtPx; + const r1y = cy - nxtPy; + + if (r1x === 0) + { + if (r1y > 0) + { + angleDiff = -angleDiff; + } + } + else if (r1x >= -GRAPHICS_CURVES.epsilon) + { + angleDiff = -angleDiff; + } + }*/ + var radius = Math.sqrt((cx2p0x * cx2p0x) + (cy2p0y * cy2p0y)); + var segCount = ((15 * absAngleDiff * Math.sqrt(radius) / Math.PI) >> 0) + 1; + var angleInc = angleDiff / segCount; + startAngle += angleInc; + if (clockwise) { + verts.push(cx, cy); + verts.push(sx, sy); + for (var i = 1, angle = startAngle; i < segCount; i++, angle += angleInc) { + verts.push(cx, cy); + verts.push(cx + ((Math.sin(angle) * radius)), cy + ((Math.cos(angle) * radius))); + } + verts.push(cx, cy); + verts.push(ex, ey); + } + else { + verts.push(sx, sy); + verts.push(cx, cy); + for (var i = 1, angle = startAngle; i < segCount; i++, angle += angleInc) { + verts.push(cx + ((Math.sin(angle) * radius)), cy + ((Math.cos(angle) * radius))); + verts.push(cx, cy); + } + verts.push(ex, ey); + verts.push(cx, cy); + } + return segCount * 2; + } + /** + * Builds a line to draw using the polygon method. + * + * Ignored from docs since it is not directly exposed. + * @ignore + * @private + * @param {PIXI.GraphicsData} graphicsData - The graphics object containing all the necessary properties + * @param {PIXI.GraphicsGeometry} graphicsGeometry - Geometry where to append output + */ + function buildNonNativeLine(graphicsData, graphicsGeometry) { + var shape = graphicsData.shape; + var points = graphicsData.points || shape.points.slice(); + var eps = graphicsGeometry.closePointEps; + if (points.length === 0) { + return; + } + // if the line width is an odd number add 0.5 to align to a whole pixel + // commenting this out fixes #711 and #1620 + // if (graphicsData.lineWidth%2) + // { + // for (i = 0; i < points.length; i++) + // { + // points[i] += 0.5; + // } + // } + var style = graphicsData.lineStyle; + // get first and last point.. figure out the middle! + var firstPoint = new Point(points[0], points[1]); + var lastPoint = new Point(points[points.length - 2], points[points.length - 1]); + var closedShape = shape.type !== exports.SHAPES.POLY || shape.closeStroke; + var closedPath = Math.abs(firstPoint.x - lastPoint.x) < eps + && Math.abs(firstPoint.y - lastPoint.y) < eps; + // if the first point is the last point - gonna have issues :) + if (closedShape) { + // need to clone as we are going to slightly modify the shape.. + points = points.slice(); + if (closedPath) { + points.pop(); + points.pop(); + lastPoint.set(points[points.length - 2], points[points.length - 1]); + } + var midPointX = (firstPoint.x + lastPoint.x) * 0.5; + var midPointY = (lastPoint.y + firstPoint.y) * 0.5; + points.unshift(midPointX, midPointY); + points.push(midPointX, midPointY); + } + var verts = graphicsGeometry.points; + var length = points.length / 2; + var indexCount = points.length; + var indexStart = verts.length / 2; + // Max. inner and outer width + var width = style.width / 2; + var widthSquared = width * width; + var miterLimitSquared = style.miterLimit * style.miterLimit; + /* Line segments of interest where (x1,y1) forms the corner. */ + var x0 = points[0]; + var y0 = points[1]; + var x1 = points[2]; + var y1 = points[3]; + var x2 = 0; + var y2 = 0; + /* perp[?](x|y) = the line normal with magnitude lineWidth. */ + var perpx = -(y0 - y1); + var perpy = x0 - x1; + var perp1x = 0; + var perp1y = 0; + var dist = Math.sqrt((perpx * perpx) + (perpy * perpy)); + perpx /= dist; + perpy /= dist; + perpx *= width; + perpy *= width; + var ratio = style.alignment; // 0.5; + var innerWeight = (1 - ratio) * 2; + var outerWeight = ratio * 2; + if (!closedShape) { + if (style.cap === exports.LINE_CAP.ROUND) { + indexCount += round(x0 - (perpx * (innerWeight - outerWeight) * 0.5), y0 - (perpy * (innerWeight - outerWeight) * 0.5), x0 - (perpx * innerWeight), y0 - (perpy * innerWeight), x0 + (perpx * outerWeight), y0 + (perpy * outerWeight), verts, true) + 2; + } + else if (style.cap === exports.LINE_CAP.SQUARE) { + indexCount += square(x0, y0, perpx, perpy, innerWeight, outerWeight, true, verts); + } + } + // Push first point (below & above vertices) + verts.push(x0 - (perpx * innerWeight), y0 - (perpy * innerWeight)); + verts.push(x0 + (perpx * outerWeight), y0 + (perpy * outerWeight)); + for (var i = 1; i < length - 1; ++i) { + x0 = points[(i - 1) * 2]; + y0 = points[((i - 1) * 2) + 1]; + x1 = points[i * 2]; + y1 = points[(i * 2) + 1]; + x2 = points[(i + 1) * 2]; + y2 = points[((i + 1) * 2) + 1]; + perpx = -(y0 - y1); + perpy = x0 - x1; + dist = Math.sqrt((perpx * perpx) + (perpy * perpy)); + perpx /= dist; + perpy /= dist; + perpx *= width; + perpy *= width; + perp1x = -(y1 - y2); + perp1y = x1 - x2; + dist = Math.sqrt((perp1x * perp1x) + (perp1y * perp1y)); + perp1x /= dist; + perp1y /= dist; + perp1x *= width; + perp1y *= width; + /* d[x|y](0|1) = the component displacement between points p(0,1|1,2) */ + var dx0 = x1 - x0; + var dy0 = y0 - y1; + var dx1 = x1 - x2; + var dy1 = y2 - y1; + /* +ve if internal angle counterclockwise, -ve if internal angle clockwise. */ + var cross = (dy0 * dx1) - (dy1 * dx0); + var clockwise = (cross < 0); + /* Going nearly straight? */ + if (Math.abs(cross) < 0.1) { + verts.push(x1 - (perpx * innerWeight), y1 - (perpy * innerWeight)); + verts.push(x1 + (perpx * outerWeight), y1 + (perpy * outerWeight)); + continue; + } + /* p[x|y] is the miter point. pdist is the distance between miter point and p1. */ + var c1 = ((-perpx + x0) * (-perpy + y1)) - ((-perpx + x1) * (-perpy + y0)); + var c2 = ((-perp1x + x2) * (-perp1y + y1)) - ((-perp1x + x1) * (-perp1y + y2)); + var px = ((dx0 * c2) - (dx1 * c1)) / cross; + var py = ((dy1 * c1) - (dy0 * c2)) / cross; + var pdist = ((px - x1) * (px - x1)) + ((py - y1) * (py - y1)); + /* Inner miter point */ + var imx = x1 + ((px - x1) * innerWeight); + var imy = y1 + ((py - y1) * innerWeight); + /* Outer miter point */ + var omx = x1 - ((px - x1) * outerWeight); + var omy = y1 - ((py - y1) * outerWeight); + /* Is the inside miter point too far away, creating a spike? */ + var smallerInsideSegmentSq = Math.min((dx0 * dx0) + (dy0 * dy0), (dx1 * dx1) + (dy1 * dy1)); + var insideWeight = clockwise ? innerWeight : outerWeight; + var smallerInsideDiagonalSq = smallerInsideSegmentSq + (insideWeight * insideWeight * widthSquared); + var insideMiterOk = pdist <= smallerInsideDiagonalSq; + if (insideMiterOk) { + if (style.join === exports.LINE_JOIN.BEVEL || pdist / widthSquared > miterLimitSquared) { + if (clockwise) /* rotating at inner angle */ { + verts.push(imx, imy); // inner miter point + verts.push(x1 + (perpx * outerWeight), y1 + (perpy * outerWeight)); // first segment's outer vertex + verts.push(imx, imy); // inner miter point + verts.push(x1 + (perp1x * outerWeight), y1 + (perp1y * outerWeight)); // second segment's outer vertex + } + else /* rotating at outer angle */ { + verts.push(x1 - (perpx * innerWeight), y1 - (perpy * innerWeight)); // first segment's inner vertex + verts.push(omx, omy); // outer miter point + verts.push(x1 - (perp1x * innerWeight), y1 - (perp1y * innerWeight)); // second segment's outer vertex + verts.push(omx, omy); // outer miter point + } + indexCount += 2; + } + else if (style.join === exports.LINE_JOIN.ROUND) { + if (clockwise) /* arc is outside */ { + verts.push(imx, imy); + verts.push(x1 + (perpx * outerWeight), y1 + (perpy * outerWeight)); + indexCount += round(x1, y1, x1 + (perpx * outerWeight), y1 + (perpy * outerWeight), x1 + (perp1x * outerWeight), y1 + (perp1y * outerWeight), verts, true) + 4; + verts.push(imx, imy); + verts.push(x1 + (perp1x * outerWeight), y1 + (perp1y * outerWeight)); + } + else /* arc is inside */ { + verts.push(x1 - (perpx * innerWeight), y1 - (perpy * innerWeight)); + verts.push(omx, omy); + indexCount += round(x1, y1, x1 - (perpx * innerWeight), y1 - (perpy * innerWeight), x1 - (perp1x * innerWeight), y1 - (perp1y * innerWeight), verts, false) + 4; + verts.push(x1 - (perp1x * innerWeight), y1 - (perp1y * innerWeight)); + verts.push(omx, omy); + } + } + else { + verts.push(imx, imy); + verts.push(omx, omy); + } + } + else // inside miter is NOT ok + { + verts.push(x1 - (perpx * innerWeight), y1 - (perpy * innerWeight)); // first segment's inner vertex + verts.push(x1 + (perpx * outerWeight), y1 + (perpy * outerWeight)); // first segment's outer vertex + if (style.join === exports.LINE_JOIN.ROUND) { + if (clockwise) /* arc is outside */ { + indexCount += round(x1, y1, x1 + (perpx * outerWeight), y1 + (perpy * outerWeight), x1 + (perp1x * outerWeight), y1 + (perp1y * outerWeight), verts, true) + 2; + } + else /* arc is inside */ { + indexCount += round(x1, y1, x1 - (perpx * innerWeight), y1 - (perpy * innerWeight), x1 - (perp1x * innerWeight), y1 - (perp1y * innerWeight), verts, false) + 2; + } + } + else if (style.join === exports.LINE_JOIN.MITER && pdist / widthSquared <= miterLimitSquared) { + if (clockwise) { + verts.push(omx, omy); // inner miter point + verts.push(omx, omy); // inner miter point + } + else { + verts.push(imx, imy); // outer miter point + verts.push(imx, imy); // outer miter point + } + indexCount += 2; + } + verts.push(x1 - (perp1x * innerWeight), y1 - (perp1y * innerWeight)); // second segment's inner vertex + verts.push(x1 + (perp1x * outerWeight), y1 + (perp1y * outerWeight)); // second segment's outer vertex + indexCount += 2; + } + } + x0 = points[(length - 2) * 2]; + y0 = points[((length - 2) * 2) + 1]; + x1 = points[(length - 1) * 2]; + y1 = points[((length - 1) * 2) + 1]; + perpx = -(y0 - y1); + perpy = x0 - x1; + dist = Math.sqrt((perpx * perpx) + (perpy * perpy)); + perpx /= dist; + perpy /= dist; + perpx *= width; + perpy *= width; + verts.push(x1 - (perpx * innerWeight), y1 - (perpy * innerWeight)); + verts.push(x1 + (perpx * outerWeight), y1 + (perpy * outerWeight)); + if (!closedShape) { + if (style.cap === exports.LINE_CAP.ROUND) { + indexCount += round(x1 - (perpx * (innerWeight - outerWeight) * 0.5), y1 - (perpy * (innerWeight - outerWeight) * 0.5), x1 - (perpx * innerWeight), y1 - (perpy * innerWeight), x1 + (perpx * outerWeight), y1 + (perpy * outerWeight), verts, false) + 2; + } + else if (style.cap === exports.LINE_CAP.SQUARE) { + indexCount += square(x1, y1, perpx, perpy, innerWeight, outerWeight, false, verts); + } + } + var indices = graphicsGeometry.indices; + var eps2 = GRAPHICS_CURVES.epsilon * GRAPHICS_CURVES.epsilon; + // indices.push(indexStart); + for (var i = indexStart; i < indexCount + indexStart - 2; ++i) { + x0 = verts[(i * 2)]; + y0 = verts[(i * 2) + 1]; + x1 = verts[(i + 1) * 2]; + y1 = verts[((i + 1) * 2) + 1]; + x2 = verts[(i + 2) * 2]; + y2 = verts[((i + 2) * 2) + 1]; + /* Skip zero area triangles */ + if (Math.abs((x0 * (y1 - y2)) + (x1 * (y2 - y0)) + (x2 * (y0 - y1))) < eps2) { + continue; + } + indices.push(i, i + 1, i + 2); + } + } + /** + * Builds a line to draw using the gl.drawArrays(gl.LINES) method + * + * Ignored from docs since it is not directly exposed. + * @ignore + * @private + * @param {PIXI.GraphicsData} graphicsData - The graphics object containing all the necessary properties + * @param {PIXI.GraphicsGeometry} graphicsGeometry - Geometry where to append output + */ + function buildNativeLine(graphicsData, graphicsGeometry) { + var i = 0; + var shape = graphicsData.shape; + var points = graphicsData.points || shape.points; + var closedShape = shape.type !== exports.SHAPES.POLY || shape.closeStroke; + if (points.length === 0) + { return; } + var verts = graphicsGeometry.points; + var indices = graphicsGeometry.indices; + var length = points.length / 2; + var startIndex = verts.length / 2; + var currentIndex = startIndex; + verts.push(points[0], points[1]); + for (i = 1; i < length; i++) { + verts.push(points[i * 2], points[(i * 2) + 1]); + indices.push(currentIndex, currentIndex + 1); + currentIndex++; + } + if (closedShape) { + indices.push(currentIndex, startIndex); + } + } + /** + * Builds a line to draw + * + * Ignored from docs since it is not directly exposed. + * @ignore + * @private + * @param {PIXI.GraphicsData} graphicsData - The graphics object containing all the necessary properties + * @param {PIXI.GraphicsGeometry} graphicsGeometry - Geometry where to append output + */ + function buildLine(graphicsData, graphicsGeometry) { + if (graphicsData.lineStyle.native) { + buildNativeLine(graphicsData, graphicsGeometry); + } + else { + buildNonNativeLine(graphicsData, graphicsGeometry); + } + } + + /** + * Utilities for arc curves. + * @private + */ + var ArcUtils = /** @class */ (function () { + function ArcUtils() { + } + /** + * The arcTo() method creates an arc/curve between two tangents on the canvas. + * + * "borrowed" from https://code.google.com/p/fxcanvas/ - thanks google! + * @private + * @param x1 - The x-coordinate of the beginning of the arc + * @param y1 - The y-coordinate of the beginning of the arc + * @param x2 - The x-coordinate of the end of the arc + * @param y2 - The y-coordinate of the end of the arc + * @param radius - The radius of the arc + * @param points - + * @returns - If the arc length is valid, return center of circle, radius and other info otherwise `null`. + */ + ArcUtils.curveTo = function (x1, y1, x2, y2, radius, points) { + var fromX = points[points.length - 2]; + var fromY = points[points.length - 1]; + var a1 = fromY - y1; + var b1 = fromX - x1; + var a2 = y2 - y1; + var b2 = x2 - x1; + var mm = Math.abs((a1 * b2) - (b1 * a2)); + if (mm < 1.0e-8 || radius === 0) { + if (points[points.length - 2] !== x1 || points[points.length - 1] !== y1) { + points.push(x1, y1); + } + return null; + } + var dd = (a1 * a1) + (b1 * b1); + var cc = (a2 * a2) + (b2 * b2); + var tt = (a1 * a2) + (b1 * b2); + var k1 = radius * Math.sqrt(dd) / mm; + var k2 = radius * Math.sqrt(cc) / mm; + var j1 = k1 * tt / dd; + var j2 = k2 * tt / cc; + var cx = (k1 * b2) + (k2 * b1); + var cy = (k1 * a2) + (k2 * a1); + var px = b1 * (k2 + j1); + var py = a1 * (k2 + j1); + var qx = b2 * (k1 + j2); + var qy = a2 * (k1 + j2); + var startAngle = Math.atan2(py - cy, px - cx); + var endAngle = Math.atan2(qy - cy, qx - cx); + return { + cx: (cx + x1), + cy: (cy + y1), + radius: radius, + startAngle: startAngle, + endAngle: endAngle, + anticlockwise: (b1 * a2 > b2 * a1), + }; + }; + /* eslint-disable max-len */ + /** + * The arc method creates an arc/curve (used to create circles, or parts of circles). + * @private + * @param _startX - Start x location of arc + * @param _startY - Start y location of arc + * @param cx - The x-coordinate of the center of the circle + * @param cy - The y-coordinate of the center of the circle + * @param radius - The radius of the circle + * @param startAngle - The starting angle, in radians (0 is at the 3 o'clock position + * of the arc's circle) + * @param endAngle - The ending angle, in radians + * @param _anticlockwise - Specifies whether the drawing should be + * counter-clockwise or clockwise. False is default, and indicates clockwise, while true + * indicates counter-clockwise. + * @param points - Collection of points to add to + */ + ArcUtils.arc = function (_startX, _startY, cx, cy, radius, startAngle, endAngle, _anticlockwise, points) { + var sweep = endAngle - startAngle; + var n = GRAPHICS_CURVES._segmentsCount(Math.abs(sweep) * radius, Math.ceil(Math.abs(sweep) / PI_2) * 40); + var theta = (sweep) / (n * 2); + var theta2 = theta * 2; + var cTheta = Math.cos(theta); + var sTheta = Math.sin(theta); + var segMinus = n - 1; + var remainder = (segMinus % 1) / segMinus; + for (var i = 0; i <= segMinus; ++i) { + var real = i + (remainder * i); + var angle = ((theta) + startAngle + (theta2 * real)); + var c = Math.cos(angle); + var s = -Math.sin(angle); + points.push((((cTheta * c) + (sTheta * s)) * radius) + cx, (((cTheta * -s) + (sTheta * c)) * radius) + cy); + } + }; + return ArcUtils; + }()); + + /** + * Utilities for bezier curves + * @private + */ + var BezierUtils = /** @class */ (function () { + function BezierUtils() { + } + /** + * Calculate length of bezier curve. + * Analytical solution is impossible, since it involves an integral that does not integrate in general. + * Therefore numerical solution is used. + * @private + * @param fromX - Starting point x + * @param fromY - Starting point y + * @param cpX - Control point x + * @param cpY - Control point y + * @param cpX2 - Second Control point x + * @param cpY2 - Second Control point y + * @param toX - Destination point x + * @param toY - Destination point y + * @returns - Length of bezier curve + */ + BezierUtils.curveLength = function (fromX, fromY, cpX, cpY, cpX2, cpY2, toX, toY) { + var n = 10; + var result = 0.0; + var t = 0.0; + var t2 = 0.0; + var t3 = 0.0; + var nt = 0.0; + var nt2 = 0.0; + var nt3 = 0.0; + var x = 0.0; + var y = 0.0; + var dx = 0.0; + var dy = 0.0; + var prevX = fromX; + var prevY = fromY; + for (var i = 1; i <= n; ++i) { + t = i / n; + t2 = t * t; + t3 = t2 * t; + nt = (1.0 - t); + nt2 = nt * nt; + nt3 = nt2 * nt; + x = (nt3 * fromX) + (3.0 * nt2 * t * cpX) + (3.0 * nt * t2 * cpX2) + (t3 * toX); + y = (nt3 * fromY) + (3.0 * nt2 * t * cpY) + (3 * nt * t2 * cpY2) + (t3 * toY); + dx = prevX - x; + dy = prevY - y; + prevX = x; + prevY = y; + result += Math.sqrt((dx * dx) + (dy * dy)); + } + return result; + }; + /** + * Calculate the points for a bezier curve and then draws it. + * + * Ignored from docs since it is not directly exposed. + * @ignore + * @param cpX - Control point x + * @param cpY - Control point y + * @param cpX2 - Second Control point x + * @param cpY2 - Second Control point y + * @param toX - Destination point x + * @param toY - Destination point y + * @param points - Path array to push points into + */ + BezierUtils.curveTo = function (cpX, cpY, cpX2, cpY2, toX, toY, points) { + var fromX = points[points.length - 2]; + var fromY = points[points.length - 1]; + points.length -= 2; + var n = GRAPHICS_CURVES._segmentsCount(BezierUtils.curveLength(fromX, fromY, cpX, cpY, cpX2, cpY2, toX, toY)); + var dt = 0; + var dt2 = 0; + var dt3 = 0; + var t2 = 0; + var t3 = 0; + points.push(fromX, fromY); + for (var i = 1, j = 0; i <= n; ++i) { + j = i / n; + dt = (1 - j); + dt2 = dt * dt; + dt3 = dt2 * dt; + t2 = j * j; + t3 = t2 * j; + points.push((dt3 * fromX) + (3 * dt2 * j * cpX) + (3 * dt * t2 * cpX2) + (t3 * toX), (dt3 * fromY) + (3 * dt2 * j * cpY) + (3 * dt * t2 * cpY2) + (t3 * toY)); + } + }; + return BezierUtils; + }()); + + /** + * Utilities for quadratic curves. + * @private + */ + var QuadraticUtils = /** @class */ (function () { + function QuadraticUtils() { + } + /** + * Calculate length of quadratic curve + * @see {@link http://www.malczak.linuxpl.com/blog/quadratic-bezier-curve-length/} + * for the detailed explanation of math behind this. + * @private + * @param fromX - x-coordinate of curve start point + * @param fromY - y-coordinate of curve start point + * @param cpX - x-coordinate of curve control point + * @param cpY - y-coordinate of curve control point + * @param toX - x-coordinate of curve end point + * @param toY - y-coordinate of curve end point + * @returns - Length of quadratic curve + */ + QuadraticUtils.curveLength = function (fromX, fromY, cpX, cpY, toX, toY) { + var ax = fromX - (2.0 * cpX) + toX; + var ay = fromY - (2.0 * cpY) + toY; + var bx = (2.0 * cpX) - (2.0 * fromX); + var by = (2.0 * cpY) - (2.0 * fromY); + var a = 4.0 * ((ax * ax) + (ay * ay)); + var b = 4.0 * ((ax * bx) + (ay * by)); + var c = (bx * bx) + (by * by); + var s = 2.0 * Math.sqrt(a + b + c); + var a2 = Math.sqrt(a); + var a32 = 2.0 * a * a2; + var c2 = 2.0 * Math.sqrt(c); + var ba = b / a2; + return ((a32 * s) + + (a2 * b * (s - c2)) + + (((4.0 * c * a) - (b * b)) + * Math.log(((2.0 * a2) + ba + s) / (ba + c2)))) / (4.0 * a32); + }; + /** + * Calculate the points for a quadratic bezier curve and then draws it. + * Based on: https://stackoverflow.com/questions/785097/how-do-i-implement-a-bezier-curve-in-c + * @private + * @param cpX - Control point x + * @param cpY - Control point y + * @param toX - Destination point x + * @param toY - Destination point y + * @param points - Points to add segments to. + */ + QuadraticUtils.curveTo = function (cpX, cpY, toX, toY, points) { + var fromX = points[points.length - 2]; + var fromY = points[points.length - 1]; + var n = GRAPHICS_CURVES._segmentsCount(QuadraticUtils.curveLength(fromX, fromY, cpX, cpY, toX, toY)); + var xa = 0; + var ya = 0; + for (var i = 1; i <= n; ++i) { + var j = i / n; + xa = fromX + ((cpX - fromX) * j); + ya = fromY + ((cpY - fromY) * j); + points.push(xa + (((cpX + ((toX - cpX) * j)) - xa) * j), ya + (((cpY + ((toY - cpY) * j)) - ya) * j)); + } + }; + return QuadraticUtils; + }()); + + /** + * A structure to hold interim batch objects for Graphics. + * @memberof PIXI.graphicsUtils + */ + var BatchPart = /** @class */ (function () { + function BatchPart() { + this.reset(); + } + /** + * Begin batch part. + * @param style + * @param startIndex + * @param attribStart + */ + BatchPart.prototype.begin = function (style, startIndex, attribStart) { + this.reset(); + this.style = style; + this.start = startIndex; + this.attribStart = attribStart; + }; + /** + * End batch part. + * @param endIndex + * @param endAttrib + */ + BatchPart.prototype.end = function (endIndex, endAttrib) { + this.attribSize = endAttrib - this.attribStart; + this.size = endIndex - this.start; + }; + BatchPart.prototype.reset = function () { + this.style = null; + this.size = 0; + this.start = 0; + this.attribStart = 0; + this.attribSize = 0; + }; + return BatchPart; + }()); + + /** + * Generalized convenience utilities for Graphics. + * @namespace graphicsUtils + * @memberof PIXI + */ + var _a; + /** + * Map of fill commands for each shape type. + * @memberof PIXI.graphicsUtils + * @member {object} FILL_COMMANDS + */ + var FILL_COMMANDS = (_a = {}, + _a[exports.SHAPES.POLY] = buildPoly, + _a[exports.SHAPES.CIRC] = buildCircle, + _a[exports.SHAPES.ELIP] = buildCircle, + _a[exports.SHAPES.RECT] = buildRectangle, + _a[exports.SHAPES.RREC] = buildRoundedRectangle, + _a); + /** + * Batch pool, stores unused batches for preventing allocations. + * @memberof PIXI.graphicsUtils + * @member {Array} BATCH_POOL + */ + var BATCH_POOL = []; + /** + * Draw call pool, stores unused draw calls for preventing allocations. + * @memberof PIXI.graphicsUtils + * @member {Array} DRAW_CALL_POOL + */ + var DRAW_CALL_POOL = []; + + /** + * A class to contain data useful for Graphics objects + * @memberof PIXI + */ + var GraphicsData = /** @class */ (function () { + /** + * @param {PIXI.Circle|PIXI.Ellipse|PIXI.Polygon|PIXI.Rectangle|PIXI.RoundedRectangle} shape - The shape object to draw. + * @param fillStyle - the width of the line to draw + * @param lineStyle - the color of the line to draw + * @param matrix - Transform matrix + */ + function GraphicsData(shape, fillStyle, lineStyle, matrix) { + if (fillStyle === void 0) { fillStyle = null; } + if (lineStyle === void 0) { lineStyle = null; } + if (matrix === void 0) { matrix = null; } + /** The collection of points. */ + this.points = []; + /** The collection of holes. */ + this.holes = []; + this.shape = shape; + this.lineStyle = lineStyle; + this.fillStyle = fillStyle; + this.matrix = matrix; + this.type = shape.type; + } + /** + * Creates a new GraphicsData object with the same values as this one. + * @returns - Cloned GraphicsData object + */ + GraphicsData.prototype.clone = function () { + return new GraphicsData(this.shape, this.fillStyle, this.lineStyle, this.matrix); + }; + /** Destroys the Graphics data. */ + GraphicsData.prototype.destroy = function () { + this.shape = null; + this.holes.length = 0; + this.holes = null; + this.points.length = 0; + this.points = null; + this.lineStyle = null; + this.fillStyle = null; + }; + return GraphicsData; + }()); + + var tmpPoint = new Point(); + /** + * The Graphics class contains methods used to draw primitive shapes such as lines, circles and + * rectangles to the display, and to color and fill them. + * + * GraphicsGeometry is designed to not be continually updating the geometry since it's expensive + * to re-tesselate using **earcut**. Consider using {@link PIXI.Mesh} for this use-case, it's much faster. + * @memberof PIXI + */ + var GraphicsGeometry = /** @class */ (function (_super) { + __extends$e(GraphicsGeometry, _super); + // eslint-disable-next-line @typescript-eslint/no-useless-constructor + function GraphicsGeometry() { + var _this = _super.call(this) || this; + /** Minimal distance between points that are considered different. Affects line tesselation. */ + _this.closePointEps = 1e-4; + /** Padding to add to the bounds. */ + _this.boundsPadding = 0; + _this.uvsFloat32 = null; + _this.indicesUint16 = null; + _this.batchable = false; + /** An array of points to draw, 2 numbers per point */ + _this.points = []; + /** The collection of colors */ + _this.colors = []; + /** The UVs collection */ + _this.uvs = []; + /** The indices of the vertices */ + _this.indices = []; + /** Reference to the texture IDs. */ + _this.textureIds = []; + /** + * The collection of drawn shapes. + * @member {PIXI.GraphicsData[]} + */ + _this.graphicsData = []; + /** + * List of current draw calls drived from the batches. + * @member {PIXI.BatchDrawCall[]} + */ + _this.drawCalls = []; + /** Batches need to regenerated if the geometry is updated. */ + _this.batchDirty = -1; + /** + * Intermediate abstract format sent to batch system. + * Can be converted to drawCalls or to batchable objects. + * @member {PIXI.graphicsUtils.BatchPart[]} + */ + _this.batches = []; + /** Used to detect if the graphics object has changed. */ + _this.dirty = 0; + /** Used to check if the cache is dirty. */ + _this.cacheDirty = -1; + /** Used to detect if we cleared the graphicsData. */ + _this.clearDirty = 0; + /** Index of the last batched shape in the stack of calls. */ + _this.shapeIndex = 0; + /** Cached bounds. */ + _this._bounds = new Bounds(); + /** The bounds dirty flag. */ + _this.boundsDirty = -1; + return _this; + } + Object.defineProperty(GraphicsGeometry.prototype, "bounds", { + /** + * Get the current bounds of the graphic geometry. + * @readonly + */ + get: function () { + this.updateBatches(); + if (this.boundsDirty !== this.dirty) { + this.boundsDirty = this.dirty; + this.calculateBounds(); + } + return this._bounds; + }, + enumerable: false, + configurable: true + }); + /** Call if you changed graphicsData manually. Empties all batch buffers. */ + GraphicsGeometry.prototype.invalidate = function () { + this.boundsDirty = -1; + this.dirty++; + this.batchDirty++; + this.shapeIndex = 0; + this.points.length = 0; + this.colors.length = 0; + this.uvs.length = 0; + this.indices.length = 0; + this.textureIds.length = 0; + for (var i = 0; i < this.drawCalls.length; i++) { + this.drawCalls[i].texArray.clear(); + DRAW_CALL_POOL.push(this.drawCalls[i]); + } + this.drawCalls.length = 0; + for (var i = 0; i < this.batches.length; i++) { + var batchPart = this.batches[i]; + batchPart.reset(); + BATCH_POOL.push(batchPart); + } + this.batches.length = 0; + }; + /** + * Clears the graphics that were drawn to this Graphics object, and resets fill and line style settings. + * @returns - This GraphicsGeometry object. Good for chaining method calls + */ + GraphicsGeometry.prototype.clear = function () { + if (this.graphicsData.length > 0) { + this.invalidate(); + this.clearDirty++; + this.graphicsData.length = 0; + } + return this; + }; + /** + * Draws the given shape to this Graphics object. Can be any of Circle, Rectangle, Ellipse, Line or Polygon. + * @param {PIXI.Circle|PIXI.Ellipse|PIXI.Polygon|PIXI.Rectangle|PIXI.RoundedRectangle} shape - The shape object to draw. + * @param fillStyle - Defines style of the fill. + * @param lineStyle - Defines style of the lines. + * @param matrix - Transform applied to the points of the shape. + * @returns - Returns geometry for chaining. + */ + GraphicsGeometry.prototype.drawShape = function (shape, fillStyle, lineStyle, matrix) { + if (fillStyle === void 0) { fillStyle = null; } + if (lineStyle === void 0) { lineStyle = null; } + if (matrix === void 0) { matrix = null; } + var data = new GraphicsData(shape, fillStyle, lineStyle, matrix); + this.graphicsData.push(data); + this.dirty++; + return this; + }; + /** + * Draws the given shape to this Graphics object. Can be any of Circle, Rectangle, Ellipse, Line or Polygon. + * @param {PIXI.Circle|PIXI.Ellipse|PIXI.Polygon|PIXI.Rectangle|PIXI.RoundedRectangle} shape - The shape object to draw. + * @param matrix - Transform applied to the points of the shape. + * @returns - Returns geometry for chaining. + */ + GraphicsGeometry.prototype.drawHole = function (shape, matrix) { + if (matrix === void 0) { matrix = null; } + if (!this.graphicsData.length) { + return null; + } + var data = new GraphicsData(shape, null, null, matrix); + var lastShape = this.graphicsData[this.graphicsData.length - 1]; + data.lineStyle = lastShape.lineStyle; + lastShape.holes.push(data); + this.dirty++; + return this; + }; + /** Destroys the GraphicsGeometry object. */ + GraphicsGeometry.prototype.destroy = function () { + _super.prototype.destroy.call(this); + // destroy each of the GraphicsData objects + for (var i = 0; i < this.graphicsData.length; ++i) { + this.graphicsData[i].destroy(); + } + this.points.length = 0; + this.points = null; + this.colors.length = 0; + this.colors = null; + this.uvs.length = 0; + this.uvs = null; + this.indices.length = 0; + this.indices = null; + this.indexBuffer.destroy(); + this.indexBuffer = null; + this.graphicsData.length = 0; + this.graphicsData = null; + this.drawCalls.length = 0; + this.drawCalls = null; + this.batches.length = 0; + this.batches = null; + this._bounds = null; + }; + /** + * Check to see if a point is contained within this geometry. + * @param point - Point to check if it's contained. + * @returns {boolean} `true` if the point is contained within geometry. + */ + GraphicsGeometry.prototype.containsPoint = function (point) { + var graphicsData = this.graphicsData; + for (var i = 0; i < graphicsData.length; ++i) { + var data = graphicsData[i]; + if (!data.fillStyle.visible) { + continue; + } + // only deal with fills.. + if (data.shape) { + if (data.matrix) { + data.matrix.applyInverse(point, tmpPoint); + } + else { + tmpPoint.copyFrom(point); + } + if (data.shape.contains(tmpPoint.x, tmpPoint.y)) { + var hitHole = false; + if (data.holes) { + for (var i_1 = 0; i_1 < data.holes.length; i_1++) { + var hole = data.holes[i_1]; + if (hole.shape.contains(tmpPoint.x, tmpPoint.y)) { + hitHole = true; + break; + } + } + } + if (!hitHole) { + return true; + } + } + } + } + return false; + }; + /** + * Generates intermediate batch data. Either gets converted to drawCalls + * or used to convert to batch objects directly by the Graphics object. + */ + GraphicsGeometry.prototype.updateBatches = function () { + if (!this.graphicsData.length) { + this.batchable = true; + return; + } + if (!this.validateBatching()) { + return; + } + this.cacheDirty = this.dirty; + var uvs = this.uvs; + var graphicsData = this.graphicsData; + var batchPart = null; + var currentStyle = null; + if (this.batches.length > 0) { + batchPart = this.batches[this.batches.length - 1]; + currentStyle = batchPart.style; + } + for (var i = this.shapeIndex; i < graphicsData.length; i++) { + this.shapeIndex++; + var data = graphicsData[i]; + var fillStyle = data.fillStyle; + var lineStyle = data.lineStyle; + var command = FILL_COMMANDS[data.type]; + // build out the shapes points.. + command.build(data); + if (data.matrix) { + this.transformPoints(data.points, data.matrix); + } + if (fillStyle.visible || lineStyle.visible) { + this.processHoles(data.holes); + } + for (var j = 0; j < 2; j++) { + var style = (j === 0) ? fillStyle : lineStyle; + if (!style.visible) + { continue; } + var nextTexture = style.texture.baseTexture; + var index_1 = this.indices.length; + var attribIndex = this.points.length / 2; + nextTexture.wrapMode = exports.WRAP_MODES.REPEAT; + if (j === 0) { + this.processFill(data); + } + else { + this.processLine(data); + } + var size = (this.points.length / 2) - attribIndex; + if (size === 0) + { continue; } + // close batch if style is different + if (batchPart && !this._compareStyles(currentStyle, style)) { + batchPart.end(index_1, attribIndex); + batchPart = null; + } + // spawn new batch if its first batch or previous was closed + if (!batchPart) { + batchPart = BATCH_POOL.pop() || new BatchPart(); + batchPart.begin(style, index_1, attribIndex); + this.batches.push(batchPart); + currentStyle = style; + } + this.addUvs(this.points, uvs, style.texture, attribIndex, size, style.matrix); + } + } + var index = this.indices.length; + var attrib = this.points.length / 2; + if (batchPart) { + batchPart.end(index, attrib); + } + if (this.batches.length === 0) { + // there are no visible styles in GraphicsData + // its possible that someone wants Graphics just for the bounds + this.batchable = true; + return; + } + var need32 = attrib > 0xffff; + // prevent allocation when length is same as buffer + if (this.indicesUint16 && this.indices.length === this.indicesUint16.length + && need32 === (this.indicesUint16.BYTES_PER_ELEMENT > 2)) { + this.indicesUint16.set(this.indices); + } + else { + this.indicesUint16 = need32 ? new Uint32Array(this.indices) : new Uint16Array(this.indices); + } + // TODO make this a const.. + this.batchable = this.isBatchable(); + if (this.batchable) { + this.packBatches(); + } + else { + this.buildDrawCalls(); + } + }; + /** + * Affinity check + * @param styleA + * @param styleB + */ + GraphicsGeometry.prototype._compareStyles = function (styleA, styleB) { + if (!styleA || !styleB) { + return false; + } + if (styleA.texture.baseTexture !== styleB.texture.baseTexture) { + return false; + } + if (styleA.color + styleA.alpha !== styleB.color + styleB.alpha) { + return false; + } + if (!!styleA.native !== !!styleB.native) { + return false; + } + return true; + }; + /** Test geometry for batching process. */ + GraphicsGeometry.prototype.validateBatching = function () { + if (this.dirty === this.cacheDirty || !this.graphicsData.length) { + return false; + } + for (var i = 0, l = this.graphicsData.length; i < l; i++) { + var data = this.graphicsData[i]; + var fill = data.fillStyle; + var line = data.lineStyle; + if (fill && !fill.texture.baseTexture.valid) + { return false; } + if (line && !line.texture.baseTexture.valid) + { return false; } + } + return true; + }; + /** Offset the indices so that it works with the batcher. */ + GraphicsGeometry.prototype.packBatches = function () { + this.batchDirty++; + this.uvsFloat32 = new Float32Array(this.uvs); + var batches = this.batches; + for (var i = 0, l = batches.length; i < l; i++) { + var batch = batches[i]; + for (var j = 0; j < batch.size; j++) { + var index = batch.start + j; + this.indicesUint16[index] = this.indicesUint16[index] - batch.attribStart; + } + } + }; + /** + * Checks to see if this graphics geometry can be batched. + * Currently it needs to be small enough and not contain any native lines. + */ + GraphicsGeometry.prototype.isBatchable = function () { + // prevent heavy mesh batching + if (this.points.length > 0xffff * 2) { + return false; + } + var batches = this.batches; + for (var i = 0; i < batches.length; i++) { + if (batches[i].style.native) { + return false; + } + } + return (this.points.length < GraphicsGeometry.BATCHABLE_SIZE * 2); + }; + /** Converts intermediate batches data to drawCalls. */ + GraphicsGeometry.prototype.buildDrawCalls = function () { + var TICK = ++BaseTexture._globalBatch; + for (var i = 0; i < this.drawCalls.length; i++) { + this.drawCalls[i].texArray.clear(); + DRAW_CALL_POOL.push(this.drawCalls[i]); + } + this.drawCalls.length = 0; + var colors = this.colors; + var textureIds = this.textureIds; + var currentGroup = DRAW_CALL_POOL.pop(); + if (!currentGroup) { + currentGroup = new BatchDrawCall(); + currentGroup.texArray = new BatchTextureArray(); + } + currentGroup.texArray.count = 0; + currentGroup.start = 0; + currentGroup.size = 0; + currentGroup.type = exports.DRAW_MODES.TRIANGLES; + var textureCount = 0; + var currentTexture = null; + var textureId = 0; + var native = false; + var drawMode = exports.DRAW_MODES.TRIANGLES; + var index = 0; + this.drawCalls.push(currentGroup); + // TODO - this can be simplified + for (var i = 0; i < this.batches.length; i++) { + var data = this.batches[i]; + // TODO add some full on MAX_TEXTURE CODE.. + var MAX_TEXTURES = 8; + // Forced cast for checking `native` without errors + var style = data.style; + var nextTexture = style.texture.baseTexture; + if (native !== !!style.native) { + native = !!style.native; + drawMode = native ? exports.DRAW_MODES.LINES : exports.DRAW_MODES.TRIANGLES; + // force the batch to break! + currentTexture = null; + textureCount = MAX_TEXTURES; + TICK++; + } + if (currentTexture !== nextTexture) { + currentTexture = nextTexture; + if (nextTexture._batchEnabled !== TICK) { + if (textureCount === MAX_TEXTURES) { + TICK++; + textureCount = 0; + if (currentGroup.size > 0) { + currentGroup = DRAW_CALL_POOL.pop(); + if (!currentGroup) { + currentGroup = new BatchDrawCall(); + currentGroup.texArray = new BatchTextureArray(); + } + this.drawCalls.push(currentGroup); + } + currentGroup.start = index; + currentGroup.size = 0; + currentGroup.texArray.count = 0; + currentGroup.type = drawMode; + } + // TODO add this to the render part.. + // Hack! Because texture has protected `touched` + nextTexture.touched = 1; // touch; + nextTexture._batchEnabled = TICK; + nextTexture._batchLocation = textureCount; + nextTexture.wrapMode = exports.WRAP_MODES.REPEAT; + currentGroup.texArray.elements[currentGroup.texArray.count++] = nextTexture; + textureCount++; + } + } + currentGroup.size += data.size; + index += data.size; + textureId = nextTexture._batchLocation; + this.addColors(colors, style.color, style.alpha, data.attribSize, data.attribStart); + this.addTextureIds(textureIds, textureId, data.attribSize, data.attribStart); + } + BaseTexture._globalBatch = TICK; + // upload.. + // merge for now! + this.packAttributes(); + }; + /** Packs attributes to single buffer. */ + GraphicsGeometry.prototype.packAttributes = function () { + var verts = this.points; + var uvs = this.uvs; + var colors = this.colors; + var textureIds = this.textureIds; + // verts are 2 positions.. so we * by 3 as there are 6 properties.. then 4 cos its bytes + var glPoints = new ArrayBuffer(verts.length * 3 * 4); + var f32 = new Float32Array(glPoints); + var u32 = new Uint32Array(glPoints); + var p = 0; + for (var i = 0; i < verts.length / 2; i++) { + f32[p++] = verts[i * 2]; + f32[p++] = verts[(i * 2) + 1]; + f32[p++] = uvs[i * 2]; + f32[p++] = uvs[(i * 2) + 1]; + u32[p++] = colors[i]; + f32[p++] = textureIds[i]; + } + this._buffer.update(glPoints); + this._indexBuffer.update(this.indicesUint16); + }; + /** + * Process fill part of Graphics. + * @param data + */ + GraphicsGeometry.prototype.processFill = function (data) { + if (data.holes.length) { + buildPoly.triangulate(data, this); + } + else { + var command = FILL_COMMANDS[data.type]; + command.triangulate(data, this); + } + }; + /** + * Process line part of Graphics. + * @param data + */ + GraphicsGeometry.prototype.processLine = function (data) { + buildLine(data, this); + for (var i = 0; i < data.holes.length; i++) { + buildLine(data.holes[i], this); + } + }; + /** + * Process the holes data. + * @param holes + */ + GraphicsGeometry.prototype.processHoles = function (holes) { + for (var i = 0; i < holes.length; i++) { + var hole = holes[i]; + var command = FILL_COMMANDS[hole.type]; + command.build(hole); + if (hole.matrix) { + this.transformPoints(hole.points, hole.matrix); + } + } + }; + /** Update the local bounds of the object. Expensive to use performance-wise. */ + GraphicsGeometry.prototype.calculateBounds = function () { + var bounds = this._bounds; + bounds.clear(); + bounds.addVertexData(this.points, 0, this.points.length); + bounds.pad(this.boundsPadding, this.boundsPadding); + }; + /** + * Transform points using matrix. + * @param points - Points to transform + * @param matrix - Transform matrix + */ + GraphicsGeometry.prototype.transformPoints = function (points, matrix) { + for (var i = 0; i < points.length / 2; i++) { + var x = points[(i * 2)]; + var y = points[(i * 2) + 1]; + points[(i * 2)] = (matrix.a * x) + (matrix.c * y) + matrix.tx; + points[(i * 2) + 1] = (matrix.b * x) + (matrix.d * y) + matrix.ty; + } + }; + /** + * Add colors. + * @param colors - List of colors to add to + * @param color - Color to add + * @param alpha - Alpha to use + * @param size - Number of colors to add + * @param offset + */ + GraphicsGeometry.prototype.addColors = function (colors, color, alpha, size, offset) { + if (offset === void 0) { offset = 0; } + // TODO use the premultiply bits Ivan added + var rgb = (color >> 16) + (color & 0xff00) + ((color & 0xff) << 16); + var rgba = premultiplyTint(rgb, alpha); + colors.length = Math.max(colors.length, offset + size); + for (var i = 0; i < size; i++) { + colors[offset + i] = rgba; + } + }; + /** + * Add texture id that the shader/fragment wants to use. + * @param textureIds + * @param id + * @param size + * @param offset + */ + GraphicsGeometry.prototype.addTextureIds = function (textureIds, id, size, offset) { + if (offset === void 0) { offset = 0; } + textureIds.length = Math.max(textureIds.length, offset + size); + for (var i = 0; i < size; i++) { + textureIds[offset + i] = id; + } + }; + /** + * Generates the UVs for a shape. + * @param verts - Vertices + * @param uvs - UVs + * @param texture - Reference to Texture + * @param start - Index buffer start index. + * @param size - The size/length for index buffer. + * @param matrix - Optional transform for all points. + */ + GraphicsGeometry.prototype.addUvs = function (verts, uvs, texture, start, size, matrix) { + if (matrix === void 0) { matrix = null; } + var index = 0; + var uvsStart = uvs.length; + var frame = texture.frame; + while (index < size) { + var x = verts[(start + index) * 2]; + var y = verts[((start + index) * 2) + 1]; + if (matrix) { + var nx = (matrix.a * x) + (matrix.c * y) + matrix.tx; + y = (matrix.b * x) + (matrix.d * y) + matrix.ty; + x = nx; + } + index++; + uvs.push(x / frame.width, y / frame.height); + } + var baseTexture = texture.baseTexture; + if (frame.width < baseTexture.width + || frame.height < baseTexture.height) { + this.adjustUvs(uvs, texture, uvsStart, size); + } + }; + /** + * Modify uvs array according to position of texture region + * Does not work with rotated or trimmed textures + * @param uvs - array + * @param texture - region + * @param start - starting index for uvs + * @param size - how many points to adjust + */ + GraphicsGeometry.prototype.adjustUvs = function (uvs, texture, start, size) { + var baseTexture = texture.baseTexture; + var eps = 1e-6; + var finish = start + (size * 2); + var frame = texture.frame; + var scaleX = frame.width / baseTexture.width; + var scaleY = frame.height / baseTexture.height; + var offsetX = frame.x / frame.width; + var offsetY = frame.y / frame.height; + var minX = Math.floor(uvs[start] + eps); + var minY = Math.floor(uvs[start + 1] + eps); + for (var i = start + 2; i < finish; i += 2) { + minX = Math.min(minX, Math.floor(uvs[i] + eps)); + minY = Math.min(minY, Math.floor(uvs[i + 1] + eps)); + } + offsetX -= minX; + offsetY -= minY; + for (var i = start; i < finish; i += 2) { + uvs[i] = (uvs[i] + offsetX) * scaleX; + uvs[i + 1] = (uvs[i + 1] + offsetY) * scaleY; + } + }; + /** + * The maximum number of points to consider an object "batchable", + * able to be batched by the renderer's batch system. + \ + */ + GraphicsGeometry.BATCHABLE_SIZE = 100; + return GraphicsGeometry; + }(BatchGeometry)); + + /** + * Represents the line style for Graphics. + * @memberof PIXI + */ + var LineStyle = /** @class */ (function (_super) { + __extends$e(LineStyle, _super); + function LineStyle() { + var _this = _super !== null && _super.apply(this, arguments) || this; + /** The width (thickness) of any lines drawn. */ + _this.width = 0; + /** The alignment of any lines drawn (0.5 = middle, 1 = outer, 0 = inner). WebGL only. */ + _this.alignment = 0.5; + /** If true the lines will be draw using LINES instead of TRIANGLE_STRIP. */ + _this.native = false; + /** + * Line cap style. + * @member {PIXI.LINE_CAP} + * @default PIXI.LINE_CAP.BUTT + */ + _this.cap = exports.LINE_CAP.BUTT; + /** + * Line join style. + * @member {PIXI.LINE_JOIN} + * @default PIXI.LINE_JOIN.MITER + */ + _this.join = exports.LINE_JOIN.MITER; + /** Miter limit. */ + _this.miterLimit = 10; + return _this; + } + /** Clones the object. */ + LineStyle.prototype.clone = function () { + var obj = new LineStyle(); + obj.color = this.color; + obj.alpha = this.alpha; + obj.texture = this.texture; + obj.matrix = this.matrix; + obj.visible = this.visible; + obj.width = this.width; + obj.alignment = this.alignment; + obj.native = this.native; + obj.cap = this.cap; + obj.join = this.join; + obj.miterLimit = this.miterLimit; + return obj; + }; + /** Reset the line style to default. */ + LineStyle.prototype.reset = function () { + _super.prototype.reset.call(this); + // Override default line style color + this.color = 0x0; + this.alignment = 0.5; + this.width = 0; + this.native = false; + }; + return LineStyle; + }(FillStyle)); + + var temp = new Float32Array(3); + // a default shaders map used by graphics.. + var DEFAULT_SHADERS = {}; + /** + * The Graphics class is primarily used to render primitive shapes such as lines, circles and + * rectangles to the display, and to color and fill them. However, you can also use a Graphics + * object to build a list of primitives to use as a mask, or as a complex hitArea. + * + * Please note that due to legacy naming conventions, the behavior of some functions in this class + * can be confusing. Each call to `drawRect()`, `drawPolygon()`, etc. actually stores that primitive + * in the Geometry class's GraphicsGeometry object for later use in rendering or hit testing - the + * functions do not directly draw anything to the screen. Similarly, the `clear()` function doesn't + * change the screen, it simply resets the list of primitives, which can be useful if you want to + * rebuild the contents of an existing Graphics object. + * + * Once a GraphicsGeometry list is built, you can re-use it in other Geometry objects as + * an optimization, by passing it into a new Geometry object's constructor. Because of this + * ability, it's important to call `destroy()` on Geometry objects once you are done with them, to + * properly dereference each GraphicsGeometry and prevent memory leaks. + * @memberof PIXI + */ + var Graphics = /** @class */ (function (_super) { + __extends$e(Graphics, _super); + /** + * @param geometry - Geometry to use, if omitted will create a new GraphicsGeometry instance. + */ + function Graphics(geometry) { + if (geometry === void 0) { geometry = null; } + var _this = _super.call(this) || this; + /** + * Represents the vertex and fragment shaders that processes the geometry and runs on the GPU. + * Can be shared between multiple Graphics objects. + */ + _this.shader = null; + /** Renderer plugin for batching */ + _this.pluginName = 'batch'; + /** + * Current path + * @readonly + */ + _this.currentPath = null; + /** A collections of batches! These can be drawn by the renderer batch system. */ + _this.batches = []; + /** Update dirty for limiting calculating tints for batches. */ + _this.batchTint = -1; + /** Update dirty for limiting calculating batches.*/ + _this.batchDirty = -1; + /** Copy of the object vertex data. */ + _this.vertexData = null; + /** Current fill style. */ + _this._fillStyle = new FillStyle(); + /** Current line style. */ + _this._lineStyle = new LineStyle(); + /** Current shape transform matrix. */ + _this._matrix = null; + /** Current hole mode is enabled. */ + _this._holeMode = false; + /** + * Represents the WebGL state the Graphics required to render, excludes shader and geometry. E.g., + * blend mode, culling, depth testing, direction of rendering triangles, backface, etc. + */ + _this.state = State.for2d(); + _this._geometry = geometry || new GraphicsGeometry(); + _this._geometry.refCount++; + /** + * When cacheAsBitmap is set to true the graphics object will be rendered as if it was a sprite. + * This is useful if your graphics element does not change often, as it will speed up the rendering + * of the object in exchange for taking up texture memory. It is also useful if you need the graphics + * object to be anti-aliased, because it will be rendered using canvas. This is not recommended if + * you are constantly redrawing the graphics element. + * @name cacheAsBitmap + * @member {boolean} + * @memberof PIXI.Graphics# + * @default false + */ + _this._transformID = -1; + // Set default + _this.tint = 0xFFFFFF; + _this.blendMode = exports.BLEND_MODES.NORMAL; + return _this; + } + Object.defineProperty(Graphics.prototype, "geometry", { + /** + * Includes vertex positions, face indices, normals, colors, UVs, and + * custom attributes within buffers, reducing the cost of passing all + * this data to the GPU. Can be shared between multiple Mesh or Graphics objects. + * @readonly + */ + get: function () { + return this._geometry; + }, + enumerable: false, + configurable: true + }); + /** + * Creates a new Graphics object with the same values as this one. + * Note that only the geometry of the object is cloned, not its transform (position,scale,etc) + * @returns - A clone of the graphics object + */ + Graphics.prototype.clone = function () { + this.finishPoly(); + return new Graphics(this._geometry); + }; + Object.defineProperty(Graphics.prototype, "blendMode", { + get: function () { + return this.state.blendMode; + }, + /** + * The blend mode to be applied to the graphic shape. Apply a value of + * `PIXI.BLEND_MODES.NORMAL` to reset the blend mode. Note that, since each + * primitive in the GraphicsGeometry list is rendered sequentially, modes + * such as `PIXI.BLEND_MODES.ADD` and `PIXI.BLEND_MODES.MULTIPLY` will + * be applied per-primitive. + * @default PIXI.BLEND_MODES.NORMAL + */ + set: function (value) { + this.state.blendMode = value; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(Graphics.prototype, "tint", { + /** + * The tint applied to each graphic shape. This is a hex value. A value of + * 0xFFFFFF will remove any tint effect. + * @default 0xFFFFFF + */ + get: function () { + return this._tint; + }, + set: function (value) { + this._tint = value; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(Graphics.prototype, "fill", { + /** + * The current fill style. + * @readonly + */ + get: function () { + return this._fillStyle; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(Graphics.prototype, "line", { + /** + * The current line style. + * @readonly + */ + get: function () { + return this._lineStyle; + }, + enumerable: false, + configurable: true + }); + Graphics.prototype.lineStyle = function (options, color, alpha, alignment, native) { + if (options === void 0) { options = null; } + if (color === void 0) { color = 0x0; } + if (alpha === void 0) { alpha = 1; } + if (alignment === void 0) { alignment = 0.5; } + if (native === void 0) { native = false; } + // Support non-object params: (width, color, alpha, alignment, native) + if (typeof options === 'number') { + options = { width: options, color: color, alpha: alpha, alignment: alignment, native: native }; + } + return this.lineTextureStyle(options); + }; + /** + * Like line style but support texture for line fill. + * @param [options] - Collection of options for setting line style. + * @param {number} [options.width=0] - width of the line to draw, will update the objects stored style + * @param {PIXI.Texture} [options.texture=PIXI.Texture.WHITE] - Texture to use + * @param {number} [options.color=0x0] - color of the line to draw, will update the objects stored style. + * Default 0xFFFFFF if texture present. + * @param {number} [options.alpha=1] - alpha of the line to draw, will update the objects stored style + * @param {PIXI.Matrix} [options.matrix=null] - Texture matrix to transform texture + * @param {number} [options.alignment=0.5] - alignment of the line to draw, (0 = inner, 0.5 = middle, 1 = outer). + * WebGL only. + * @param {boolean} [options.native=false] - If true the lines will be draw using LINES instead of TRIANGLE_STRIP + * @param {PIXI.LINE_CAP}[options.cap=PIXI.LINE_CAP.BUTT] - line cap style + * @param {PIXI.LINE_JOIN}[options.join=PIXI.LINE_JOIN.MITER] - line join style + * @param {number}[options.miterLimit=10] - miter limit ratio + * @returns {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + Graphics.prototype.lineTextureStyle = function (options) { + // Apply defaults + options = Object.assign({ + width: 0, + texture: Texture.WHITE, + color: (options && options.texture) ? 0xFFFFFF : 0x0, + alpha: 1, + matrix: null, + alignment: 0.5, + native: false, + cap: exports.LINE_CAP.BUTT, + join: exports.LINE_JOIN.MITER, + miterLimit: 10, + }, options); + if (this.currentPath) { + this.startPoly(); + } + var visible = options.width > 0 && options.alpha > 0; + if (!visible) { + this._lineStyle.reset(); + } + else { + if (options.matrix) { + options.matrix = options.matrix.clone(); + options.matrix.invert(); + } + Object.assign(this._lineStyle, { visible: visible }, options); + } + return this; + }; + /** + * Start a polygon object internally. + * @protected + */ + Graphics.prototype.startPoly = function () { + if (this.currentPath) { + var points = this.currentPath.points; + var len = this.currentPath.points.length; + if (len > 2) { + this.drawShape(this.currentPath); + this.currentPath = new Polygon(); + this.currentPath.closeStroke = false; + this.currentPath.points.push(points[len - 2], points[len - 1]); + } + } + else { + this.currentPath = new Polygon(); + this.currentPath.closeStroke = false; + } + }; + /** + * Finish the polygon object. + * @protected + */ + Graphics.prototype.finishPoly = function () { + if (this.currentPath) { + if (this.currentPath.points.length > 2) { + this.drawShape(this.currentPath); + this.currentPath = null; + } + else { + this.currentPath.points.length = 0; + } + } + }; + /** + * Moves the current drawing position to x, y. + * @param x - the X coordinate to move to + * @param y - the Y coordinate to move to + * @returns - This Graphics object. Good for chaining method calls + */ + Graphics.prototype.moveTo = function (x, y) { + this.startPoly(); + this.currentPath.points[0] = x; + this.currentPath.points[1] = y; + return this; + }; + /** + * Draws a line using the current line style from the current drawing position to (x, y); + * The current drawing position is then set to (x, y). + * @param x - the X coordinate to draw to + * @param y - the Y coordinate to draw to + * @returns - This Graphics object. Good for chaining method calls + */ + Graphics.prototype.lineTo = function (x, y) { + if (!this.currentPath) { + this.moveTo(0, 0); + } + // remove duplicates.. + var points = this.currentPath.points; + var fromX = points[points.length - 2]; + var fromY = points[points.length - 1]; + if (fromX !== x || fromY !== y) { + points.push(x, y); + } + return this; + }; + /** + * Initialize the curve + * @param x + * @param y + */ + Graphics.prototype._initCurve = function (x, y) { + if (x === void 0) { x = 0; } + if (y === void 0) { y = 0; } + if (this.currentPath) { + if (this.currentPath.points.length === 0) { + this.currentPath.points = [x, y]; + } + } + else { + this.moveTo(x, y); + } + }; + /** + * Calculate the points for a quadratic bezier curve and then draws it. + * Based on: https://stackoverflow.com/questions/785097/how-do-i-implement-a-bezier-curve-in-c + * @param cpX - Control point x + * @param cpY - Control point y + * @param toX - Destination point x + * @param toY - Destination point y + * @returns - This Graphics object. Good for chaining method calls + */ + Graphics.prototype.quadraticCurveTo = function (cpX, cpY, toX, toY) { + this._initCurve(); + var points = this.currentPath.points; + if (points.length === 0) { + this.moveTo(0, 0); + } + QuadraticUtils.curveTo(cpX, cpY, toX, toY, points); + return this; + }; + /** + * Calculate the points for a bezier curve and then draws it. + * @param cpX - Control point x + * @param cpY - Control point y + * @param cpX2 - Second Control point x + * @param cpY2 - Second Control point y + * @param toX - Destination point x + * @param toY - Destination point y + * @returns This Graphics object. Good for chaining method calls + */ + Graphics.prototype.bezierCurveTo = function (cpX, cpY, cpX2, cpY2, toX, toY) { + this._initCurve(); + BezierUtils.curveTo(cpX, cpY, cpX2, cpY2, toX, toY, this.currentPath.points); + return this; + }; + /** + * The arcTo() method creates an arc/curve between two tangents on the canvas. + * + * "borrowed" from https://code.google.com/p/fxcanvas/ - thanks google! + * @param x1 - The x-coordinate of the first tangent point of the arc + * @param y1 - The y-coordinate of the first tangent point of the arc + * @param x2 - The x-coordinate of the end of the arc + * @param y2 - The y-coordinate of the end of the arc + * @param radius - The radius of the arc + * @returns - This Graphics object. Good for chaining method calls + */ + Graphics.prototype.arcTo = function (x1, y1, x2, y2, radius) { + this._initCurve(x1, y1); + var points = this.currentPath.points; + var result = ArcUtils.curveTo(x1, y1, x2, y2, radius, points); + if (result) { + var cx = result.cx, cy = result.cy, radius_1 = result.radius, startAngle = result.startAngle, endAngle = result.endAngle, anticlockwise = result.anticlockwise; + this.arc(cx, cy, radius_1, startAngle, endAngle, anticlockwise); + } + return this; + }; + /** + * The arc method creates an arc/curve (used to create circles, or parts of circles). + * @param cx - The x-coordinate of the center of the circle + * @param cy - The y-coordinate of the center of the circle + * @param radius - The radius of the circle + * @param startAngle - The starting angle, in radians (0 is at the 3 o'clock position + * of the arc's circle) + * @param endAngle - The ending angle, in radians + * @param anticlockwise - Specifies whether the drawing should be + * counter-clockwise or clockwise. False is default, and indicates clockwise, while true + * indicates counter-clockwise. + * @returns - This Graphics object. Good for chaining method calls + */ + Graphics.prototype.arc = function (cx, cy, radius, startAngle, endAngle, anticlockwise) { + if (anticlockwise === void 0) { anticlockwise = false; } + if (startAngle === endAngle) { + return this; + } + if (!anticlockwise && endAngle <= startAngle) { + endAngle += PI_2; + } + else if (anticlockwise && startAngle <= endAngle) { + startAngle += PI_2; + } + var sweep = endAngle - startAngle; + if (sweep === 0) { + return this; + } + var startX = cx + (Math.cos(startAngle) * radius); + var startY = cy + (Math.sin(startAngle) * radius); + var eps = this._geometry.closePointEps; + // If the currentPath exists, take its points. Otherwise call `moveTo` to start a path. + var points = this.currentPath ? this.currentPath.points : null; + if (points) { + // TODO: make a better fix. + // We check how far our start is from the last existing point + var xDiff = Math.abs(points[points.length - 2] - startX); + var yDiff = Math.abs(points[points.length - 1] - startY); + if (xDiff < eps && yDiff < eps) { ; } + else { + points.push(startX, startY); + } + } + else { + this.moveTo(startX, startY); + points = this.currentPath.points; + } + ArcUtils.arc(startX, startY, cx, cy, radius, startAngle, endAngle, anticlockwise, points); + return this; + }; + /** + * Specifies a simple one-color fill that subsequent calls to other Graphics methods + * (such as lineTo() or drawCircle()) use when drawing. + * @param color - the color of the fill + * @param alpha - the alpha of the fill + * @returns - This Graphics object. Good for chaining method calls + */ + Graphics.prototype.beginFill = function (color, alpha) { + if (color === void 0) { color = 0; } + if (alpha === void 0) { alpha = 1; } + return this.beginTextureFill({ texture: Texture.WHITE, color: color, alpha: alpha }); + }; + /** + * Begin the texture fill + * @param options - Object object. + * @param {PIXI.Texture} [options.texture=PIXI.Texture.WHITE] - Texture to fill + * @param {number} [options.color=0xffffff] - Background to fill behind texture + * @param {number} [options.alpha=1] - Alpha of fill + * @param {PIXI.Matrix} [options.matrix=null] - Transform matrix + * @returns {PIXI.Graphics} This Graphics object. Good for chaining method calls + */ + Graphics.prototype.beginTextureFill = function (options) { + // Apply defaults + options = Object.assign({ + texture: Texture.WHITE, + color: 0xFFFFFF, + alpha: 1, + matrix: null, + }, options); + if (this.currentPath) { + this.startPoly(); + } + var visible = options.alpha > 0; + if (!visible) { + this._fillStyle.reset(); + } + else { + if (options.matrix) { + options.matrix = options.matrix.clone(); + options.matrix.invert(); + } + Object.assign(this._fillStyle, { visible: visible }, options); + } + return this; + }; + /** + * Applies a fill to the lines and shapes that were added since the last call to the beginFill() method. + * @returns - This Graphics object. Good for chaining method calls + */ + Graphics.prototype.endFill = function () { + this.finishPoly(); + this._fillStyle.reset(); + return this; + }; + /** + * Draws a rectangle shape. + * @param x - The X coord of the top-left of the rectangle + * @param y - The Y coord of the top-left of the rectangle + * @param width - The width of the rectangle + * @param height - The height of the rectangle + * @returns - This Graphics object. Good for chaining method calls + */ + Graphics.prototype.drawRect = function (x, y, width, height) { + return this.drawShape(new Rectangle(x, y, width, height)); + }; + /** + * Draw a rectangle shape with rounded/beveled corners. + * @param x - The X coord of the top-left of the rectangle + * @param y - The Y coord of the top-left of the rectangle + * @param width - The width of the rectangle + * @param height - The height of the rectangle + * @param radius - Radius of the rectangle corners + * @returns - This Graphics object. Good for chaining method calls + */ + Graphics.prototype.drawRoundedRect = function (x, y, width, height, radius) { + return this.drawShape(new RoundedRectangle(x, y, width, height, radius)); + }; + /** + * Draws a circle. + * @param x - The X coordinate of the center of the circle + * @param y - The Y coordinate of the center of the circle + * @param radius - The radius of the circle + * @returns - This Graphics object. Good for chaining method calls + */ + Graphics.prototype.drawCircle = function (x, y, radius) { + return this.drawShape(new Circle(x, y, radius)); + }; + /** + * Draws an ellipse. + * @param x - The X coordinate of the center of the ellipse + * @param y - The Y coordinate of the center of the ellipse + * @param width - The half width of the ellipse + * @param height - The half height of the ellipse + * @returns - This Graphics object. Good for chaining method calls + */ + Graphics.prototype.drawEllipse = function (x, y, width, height) { + return this.drawShape(new Ellipse(x, y, width, height)); + }; + /** + * Draws a polygon using the given path. + * @param {number[]|PIXI.IPointData[]|PIXI.Polygon} path - The path data used to construct the polygon. + * @returns - This Graphics object. Good for chaining method calls + */ + Graphics.prototype.drawPolygon = function () { + var arguments$1 = arguments; + + var path = []; + for (var _i = 0; _i < arguments.length; _i++) { + path[_i] = arguments$1[_i]; + } + var points; + var closeStroke = true; // !!this._fillStyle; + var poly = path[0]; + // check if data has points.. + if (poly.points) { + closeStroke = poly.closeStroke; + points = poly.points; + } + else if (Array.isArray(path[0])) { + points = path[0]; + } + else { + points = path; + } + var shape = new Polygon(points); + shape.closeStroke = closeStroke; + this.drawShape(shape); + return this; + }; + /** + * Draw any shape. + * @param {PIXI.Circle|PIXI.Ellipse|PIXI.Polygon|PIXI.Rectangle|PIXI.RoundedRectangle} shape - Shape to draw + * @returns - This Graphics object. Good for chaining method calls + */ + Graphics.prototype.drawShape = function (shape) { + if (!this._holeMode) { + this._geometry.drawShape(shape, this._fillStyle.clone(), this._lineStyle.clone(), this._matrix); + } + else { + this._geometry.drawHole(shape, this._matrix); + } + return this; + }; + /** + * Clears the graphics that were drawn to this Graphics object, and resets fill and line style settings. + * @returns - This Graphics object. Good for chaining method calls + */ + Graphics.prototype.clear = function () { + this._geometry.clear(); + this._lineStyle.reset(); + this._fillStyle.reset(); + this._boundsID++; + this._matrix = null; + this._holeMode = false; + this.currentPath = null; + return this; + }; + /** + * True if graphics consists of one rectangle, and thus, can be drawn like a Sprite and + * masked with gl.scissor. + * @returns - True if only 1 rect. + */ + Graphics.prototype.isFastRect = function () { + var data = this._geometry.graphicsData; + return data.length === 1 + && data[0].shape.type === exports.SHAPES.RECT + && !data[0].matrix + && !data[0].holes.length + && !(data[0].lineStyle.visible && data[0].lineStyle.width); + }; + /** + * Renders the object using the WebGL renderer + * @param renderer - The renderer + */ + Graphics.prototype._render = function (renderer) { + this.finishPoly(); + var geometry = this._geometry; + // batch part.. + // batch it! + geometry.updateBatches(); + if (geometry.batchable) { + if (this.batchDirty !== geometry.batchDirty) { + this._populateBatches(); + } + this._renderBatched(renderer); + } + else { + // no batching... + renderer.batch.flush(); + this._renderDirect(renderer); + } + }; + /** Populating batches for rendering. */ + Graphics.prototype._populateBatches = function () { + var geometry = this._geometry; + var blendMode = this.blendMode; + var len = geometry.batches.length; + this.batchTint = -1; + this._transformID = -1; + this.batchDirty = geometry.batchDirty; + this.batches.length = len; + this.vertexData = new Float32Array(geometry.points); + for (var i = 0; i < len; i++) { + var gI = geometry.batches[i]; + var color = gI.style.color; + var vertexData = new Float32Array(this.vertexData.buffer, gI.attribStart * 4 * 2, gI.attribSize * 2); + var uvs = new Float32Array(geometry.uvsFloat32.buffer, gI.attribStart * 4 * 2, gI.attribSize * 2); + var indices = new Uint16Array(geometry.indicesUint16.buffer, gI.start * 2, gI.size); + var batch = { + vertexData: vertexData, + blendMode: blendMode, + indices: indices, + uvs: uvs, + _batchRGB: hex2rgb(color), + _tintRGB: color, + _texture: gI.style.texture, + alpha: gI.style.alpha, + worldAlpha: 1 + }; + this.batches[i] = batch; + } + }; + /** + * Renders the batches using the BathedRenderer plugin + * @param renderer - The renderer + */ + Graphics.prototype._renderBatched = function (renderer) { + if (!this.batches.length) { + return; + } + renderer.batch.setObjectRenderer(renderer.plugins[this.pluginName]); + this.calculateVertices(); + this.calculateTints(); + for (var i = 0, l = this.batches.length; i < l; i++) { + var batch = this.batches[i]; + batch.worldAlpha = this.worldAlpha * batch.alpha; + renderer.plugins[this.pluginName].render(batch); + } + }; + /** + * Renders the graphics direct + * @param renderer - The renderer + */ + Graphics.prototype._renderDirect = function (renderer) { + var shader = this._resolveDirectShader(renderer); + var geometry = this._geometry; + var tint = this.tint; + var worldAlpha = this.worldAlpha; + var uniforms = shader.uniforms; + var drawCalls = geometry.drawCalls; + // lets set the transfomr + uniforms.translationMatrix = this.transform.worldTransform; + // and then lets set the tint.. + uniforms.tint[0] = (((tint >> 16) & 0xFF) / 255) * worldAlpha; + uniforms.tint[1] = (((tint >> 8) & 0xFF) / 255) * worldAlpha; + uniforms.tint[2] = ((tint & 0xFF) / 255) * worldAlpha; + uniforms.tint[3] = worldAlpha; + // the first draw call, we can set the uniforms of the shader directly here. + // this means that we can tack advantage of the sync function of pixi! + // bind and sync uniforms.. + // there is a way to optimise this.. + renderer.shader.bind(shader); + renderer.geometry.bind(geometry, shader); + // set state.. + renderer.state.set(this.state); + // then render the rest of them... + for (var i = 0, l = drawCalls.length; i < l; i++) { + this._renderDrawCallDirect(renderer, geometry.drawCalls[i]); + } + }; + /** + * Renders specific DrawCall + * @param renderer + * @param drawCall + */ + Graphics.prototype._renderDrawCallDirect = function (renderer, drawCall) { + var texArray = drawCall.texArray, type = drawCall.type, size = drawCall.size, start = drawCall.start; + var groupTextureCount = texArray.count; + for (var j = 0; j < groupTextureCount; j++) { + renderer.texture.bind(texArray.elements[j], j); + } + renderer.geometry.draw(type, size, start); + }; + /** + * Resolves shader for direct rendering + * @param renderer - The renderer + */ + Graphics.prototype._resolveDirectShader = function (renderer) { + var shader = this.shader; + var pluginName = this.pluginName; + if (!shader) { + // if there is no shader here, we can use the default shader. + // and that only gets created if we actually need it.. + // but may be more than one plugins for graphics + if (!DEFAULT_SHADERS[pluginName]) { + var MAX_TEXTURES = renderer.plugins[pluginName].MAX_TEXTURES; + var sampleValues = new Int32Array(MAX_TEXTURES); + for (var i = 0; i < MAX_TEXTURES; i++) { + sampleValues[i] = i; + } + var uniforms = { + tint: new Float32Array([1, 1, 1, 1]), + translationMatrix: new Matrix(), + default: UniformGroup.from({ uSamplers: sampleValues }, true), + }; + var program = renderer.plugins[pluginName]._shader.program; + DEFAULT_SHADERS[pluginName] = new Shader(program, uniforms); + } + shader = DEFAULT_SHADERS[pluginName]; + } + return shader; + }; + /** Retrieves the bounds of the graphic shape as a rectangle object. */ + Graphics.prototype._calculateBounds = function () { + this.finishPoly(); + var geometry = this._geometry; + // skipping when graphics is empty, like a container + if (!geometry.graphicsData.length) { + return; + } + var _a = geometry.bounds, minX = _a.minX, minY = _a.minY, maxX = _a.maxX, maxY = _a.maxY; + this._bounds.addFrame(this.transform, minX, minY, maxX, maxY); + }; + /** + * Tests if a point is inside this graphics object + * @param point - the point to test + * @returns - the result of the test + */ + Graphics.prototype.containsPoint = function (point) { + this.worldTransform.applyInverse(point, Graphics._TEMP_POINT); + return this._geometry.containsPoint(Graphics._TEMP_POINT); + }; + /** Recalculate the tint by applying tint to batches using Graphics tint. */ + Graphics.prototype.calculateTints = function () { + if (this.batchTint !== this.tint) { + this.batchTint = this.tint; + var tintRGB = hex2rgb(this.tint, temp); + for (var i = 0; i < this.batches.length; i++) { + var batch = this.batches[i]; + var batchTint = batch._batchRGB; + var r = (tintRGB[0] * batchTint[0]) * 255; + var g = (tintRGB[1] * batchTint[1]) * 255; + var b = (tintRGB[2] * batchTint[2]) * 255; + // TODO Ivan, can this be done in one go? + var color = (r << 16) + (g << 8) + (b | 0); + batch._tintRGB = (color >> 16) + + (color & 0xff00) + + ((color & 0xff) << 16); + } + } + }; + /** If there's a transform update or a change to the shape of the geometry, recalculate the vertices. */ + Graphics.prototype.calculateVertices = function () { + var wtID = this.transform._worldID; + if (this._transformID === wtID) { + return; + } + this._transformID = wtID; + var wt = this.transform.worldTransform; + var a = wt.a; + var b = wt.b; + var c = wt.c; + var d = wt.d; + var tx = wt.tx; + var ty = wt.ty; + var data = this._geometry.points; // batch.vertexDataOriginal; + var vertexData = this.vertexData; + var count = 0; + for (var i = 0; i < data.length; i += 2) { + var x = data[i]; + var y = data[i + 1]; + vertexData[count++] = (a * x) + (c * y) + tx; + vertexData[count++] = (d * y) + (b * x) + ty; + } + }; + /** + * Closes the current path. + * @returns - Returns itself. + */ + Graphics.prototype.closePath = function () { + var currentPath = this.currentPath; + if (currentPath) { + // we don't need to add extra point in the end because buildLine will take care of that + currentPath.closeStroke = true; + // ensure that the polygon is completed, and is available for hit detection + // (even if the graphics is not rendered yet) + this.finishPoly(); + } + return this; + }; + /** + * Apply a matrix to the positional data. + * @param matrix - Matrix to use for transform current shape. + * @returns - Returns itself. + */ + Graphics.prototype.setMatrix = function (matrix) { + this._matrix = matrix; + return this; + }; + /** + * Begin adding holes to the last draw shape + * IMPORTANT: holes must be fully inside a shape to work + * Also weirdness ensues if holes overlap! + * Ellipses, Circles, Rectangles and Rounded Rectangles cannot be holes or host for holes in CanvasRenderer, + * please use `moveTo` `lineTo`, `quadraticCurveTo` if you rely on pixi-legacy bundle. + * @returns - Returns itself. + */ + Graphics.prototype.beginHole = function () { + this.finishPoly(); + this._holeMode = true; + return this; + }; + /** + * End adding holes to the last draw shape. + * @returns - Returns itself. + */ + Graphics.prototype.endHole = function () { + this.finishPoly(); + this._holeMode = false; + return this; + }; + /** + * Destroys the Graphics object. + * @param options - Options parameter. A boolean will act as if all + * options have been set to that value + * @param {boolean} [options.children=false] - if set to true, all the children will have + * their destroy method called as well. 'options' will be passed on to those calls. + * @param {boolean} [options.texture=false] - Only used for child Sprites if options.children is set to true + * Should it destroy the texture of the child sprite + * @param {boolean} [options.baseTexture=false] - Only used for child Sprites if options.children is set to true + * Should it destroy the base texture of the child sprite + */ + Graphics.prototype.destroy = function (options) { + this._geometry.refCount--; + if (this._geometry.refCount === 0) { + this._geometry.dispose(); + } + this._matrix = null; + this.currentPath = null; + this._lineStyle.destroy(); + this._lineStyle = null; + this._fillStyle.destroy(); + this._fillStyle = null; + this._geometry = null; + this.shader = null; + this.vertexData = null; + this.batches.length = 0; + this.batches = null; + _super.prototype.destroy.call(this, options); + }; + /** + * New rendering behavior for rounded rectangles: circular arcs instead of quadratic bezier curves. + * In the next major release, we'll enable this by default. + */ + Graphics.nextRoundedRectBehavior = false; + /** + * Temporary point to use for containsPoint. + * @private + */ + Graphics._TEMP_POINT = new Point(); + return Graphics; + }(Container)); + + var graphicsUtils = { + buildPoly: buildPoly, + buildCircle: buildCircle, + buildRectangle: buildRectangle, + buildRoundedRectangle: buildRoundedRectangle, + buildLine: buildLine, + ArcUtils: ArcUtils, + BezierUtils: BezierUtils, + QuadraticUtils: QuadraticUtils, + BatchPart: BatchPart, + FILL_COMMANDS: FILL_COMMANDS, + BATCH_POOL: BATCH_POOL, + DRAW_CALL_POOL: DRAW_CALL_POOL + }; + + /*! + * @pixi/sprite - v6.5.3 + * Compiled Fri, 09 Sep 2022 13:55:20 UTC + * + * @pixi/sprite is licensed under the MIT License. + * http://www.opensource.org/licenses/mit-license + */ + + /*! ***************************************************************************** + Copyright (c) Microsoft Corporation. - THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED - WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, - MERCHANTABLITY OR NON-INFRINGEMENT. + Permission to use, copy, modify, and/or distribute this software for any + purpose with or without fee is hereby granted. - See the Apache Version 2.0 License for specific language governing permissions - and limitations under the License. - ***************************************************************************** */ - /* global Reflect, Promise */ + THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH + REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY + AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, + INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM + LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR + OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR + PERFORMANCE OF THIS SOFTWARE. + ***************************************************************************** */ + /* global Reflect, Promise */ - var extendStatics$c = function(d, b) { - extendStatics$c = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) { if (b.hasOwnProperty(p)) { d[p] = b[p]; } } }; - return extendStatics$c(d, b); - }; + var extendStatics$d = function(d, b) { + extendStatics$d = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) { if (b.hasOwnProperty(p)) { d[p] = b[p]; } } }; + return extendStatics$d(d, b); + }; - function __extends$c(d, b) { - extendStatics$c(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - } - - var fragment$4 = "varying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\nuniform float uAlpha;\n\nvoid main(void)\n{\n gl_FragColor = texture2D(uSampler, vTextureCoord) * uAlpha;\n}\n"; - - /** - * Simplest filter - applies alpha. - * - * Use this instead of Container's alpha property to avoid visual layering of individual elements. - * AlphaFilter applies alpha evenly across the entire display object and any opaque elements it contains. - * If elements are not opaque, they will blend with each other anyway. - * - * Very handy if you want to use common features of all filters: - * - * 1. Assign a blendMode to this filter, blend all elements inside display object with background. - * - * 2. To use clipping in display coordinates, assign a filterArea to the same container that has this filter. - * - * @class - * @extends PIXI.Filter - * @memberof PIXI.filters - */ - var AlphaFilter = /** @class */ (function (_super) { - __extends$c(AlphaFilter, _super); - /** - * @param {number} [alpha=1] - Amount of alpha from 0 to 1, where 0 is transparent - */ - function AlphaFilter(alpha) { - if (alpha === void 0) { alpha = 1.0; } - var _this = _super.call(this, _default, fragment$4, { uAlpha: 1 }) || this; - _this.alpha = alpha; - return _this; - } - Object.defineProperty(AlphaFilter.prototype, "alpha", { - /** - * Coefficient for alpha multiplication - * - * @member {number} - * @default 1 - */ - get: function () { - return this.uniforms.uAlpha; - }, - set: function (value) { - this.uniforms.uAlpha = value; - }, - enumerable: false, - configurable: true - }); - return AlphaFilter; - }(Filter)); - - /*! - * @pixi/filter-blur - v5.3.3 - * Compiled Tue, 04 Aug 2020 16:23:09 UTC - * - * @pixi/filter-blur is licensed under the MIT License. - * http://www.opensource.org/licenses/mit-license - */ - - /*! ***************************************************************************** - Copyright (c) Microsoft Corporation. All rights reserved. - Licensed under the Apache License, Version 2.0 (the "License"); you may not use - this file except in compliance with the License. You may obtain a copy of the - License at http://www.apache.org/licenses/LICENSE-2.0 + function __extends$d(d, b) { + extendStatics$d(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + } + + var tempPoint$2 = new Point(); + var indices = new Uint16Array([0, 1, 2, 0, 2, 3]); + /** + * The Sprite object is the base for all textured objects that are rendered to the screen + * + * A sprite can be created directly from an image like this: + * + * ```js + * let sprite = PIXI.Sprite.from('assets/image.png'); + * ``` + * + * The more efficient way to create sprites is using a {@link PIXI.Spritesheet}, + * as swapping base textures when rendering to the screen is inefficient. + * + * ```js + * PIXI.Loader.shared.add("assets/spritesheet.json").load(setup); + * + * function setup() { + * let sheet = PIXI.Loader.shared.resources["assets/spritesheet.json"].spritesheet; + * let sprite = new PIXI.Sprite(sheet.textures["image.png"]); + * ... + * } + * ``` + * @memberof PIXI + */ + var Sprite = /** @class */ (function (_super) { + __extends$d(Sprite, _super); + /** @param texture - The texture for this sprite. */ + function Sprite(texture) { + var _this = _super.call(this) || this; + _this._anchor = new ObservablePoint(_this._onAnchorUpdate, _this, (texture ? texture.defaultAnchor.x : 0), (texture ? texture.defaultAnchor.y : 0)); + _this._texture = null; + _this._width = 0; + _this._height = 0; + _this._tint = null; + _this._tintRGB = null; + _this.tint = 0xFFFFFF; + _this.blendMode = exports.BLEND_MODES.NORMAL; + _this._cachedTint = 0xFFFFFF; + _this.uvs = null; + // call texture setter + _this.texture = texture || Texture.EMPTY; + _this.vertexData = new Float32Array(8); + _this.vertexTrimmedData = null; + _this._transformID = -1; + _this._textureID = -1; + _this._transformTrimmedID = -1; + _this._textureTrimmedID = -1; + // Batchable stuff.. + // TODO could make this a mixin? + _this.indices = indices; + _this.pluginName = 'batch'; + /** + * Used to fast check if a sprite is.. a sprite! + * @member {boolean} + */ + _this.isSprite = true; + _this._roundPixels = settings$1.ROUND_PIXELS; + return _this; + } + /** When the texture is updated, this event will fire to update the scale and frame. */ + Sprite.prototype._onTextureUpdate = function () { + this._textureID = -1; + this._textureTrimmedID = -1; + this._cachedTint = 0xFFFFFF; + // so if _width is 0 then width was not set.. + if (this._width) { + this.scale.x = sign(this.scale.x) * this._width / this._texture.orig.width; + } + if (this._height) { + this.scale.y = sign(this.scale.y) * this._height / this._texture.orig.height; + } + }; + /** Called when the anchor position updates. */ + Sprite.prototype._onAnchorUpdate = function () { + this._transformID = -1; + this._transformTrimmedID = -1; + }; + /** Calculates worldTransform * vertices, store it in vertexData. */ + Sprite.prototype.calculateVertices = function () { + var texture = this._texture; + if (this._transformID === this.transform._worldID && this._textureID === texture._updateID) { + return; + } + // update texture UV here, because base texture can be changed without calling `_onTextureUpdate` + if (this._textureID !== texture._updateID) { + this.uvs = this._texture._uvs.uvsFloat32; + } + this._transformID = this.transform._worldID; + this._textureID = texture._updateID; + // set the vertex data + var wt = this.transform.worldTransform; + var a = wt.a; + var b = wt.b; + var c = wt.c; + var d = wt.d; + var tx = wt.tx; + var ty = wt.ty; + var vertexData = this.vertexData; + var trim = texture.trim; + var orig = texture.orig; + var anchor = this._anchor; + var w0 = 0; + var w1 = 0; + var h0 = 0; + var h1 = 0; + if (trim) { + // if the sprite is trimmed and is not a tilingsprite then we need to add the extra + // space before transforming the sprite coords. + w1 = trim.x - (anchor._x * orig.width); + w0 = w1 + trim.width; + h1 = trim.y - (anchor._y * orig.height); + h0 = h1 + trim.height; + } + else { + w1 = -anchor._x * orig.width; + w0 = w1 + orig.width; + h1 = -anchor._y * orig.height; + h0 = h1 + orig.height; + } + // xy + vertexData[0] = (a * w1) + (c * h1) + tx; + vertexData[1] = (d * h1) + (b * w1) + ty; + // xy + vertexData[2] = (a * w0) + (c * h1) + tx; + vertexData[3] = (d * h1) + (b * w0) + ty; + // xy + vertexData[4] = (a * w0) + (c * h0) + tx; + vertexData[5] = (d * h0) + (b * w0) + ty; + // xy + vertexData[6] = (a * w1) + (c * h0) + tx; + vertexData[7] = (d * h0) + (b * w1) + ty; + if (this._roundPixels) { + var resolution = settings$1.RESOLUTION; + for (var i = 0; i < vertexData.length; ++i) { + vertexData[i] = Math.round((vertexData[i] * resolution | 0) / resolution); + } + } + }; + /** + * Calculates worldTransform * vertices for a non texture with a trim. store it in vertexTrimmedData. + * + * This is used to ensure that the true width and height of a trimmed texture is respected. + */ + Sprite.prototype.calculateTrimmedVertices = function () { + if (!this.vertexTrimmedData) { + this.vertexTrimmedData = new Float32Array(8); + } + else if (this._transformTrimmedID === this.transform._worldID && this._textureTrimmedID === this._texture._updateID) { + return; + } + this._transformTrimmedID = this.transform._worldID; + this._textureTrimmedID = this._texture._updateID; + // lets do some special trim code! + var texture = this._texture; + var vertexData = this.vertexTrimmedData; + var orig = texture.orig; + var anchor = this._anchor; + // lets calculate the new untrimmed bounds.. + var wt = this.transform.worldTransform; + var a = wt.a; + var b = wt.b; + var c = wt.c; + var d = wt.d; + var tx = wt.tx; + var ty = wt.ty; + var w1 = -anchor._x * orig.width; + var w0 = w1 + orig.width; + var h1 = -anchor._y * orig.height; + var h0 = h1 + orig.height; + // xy + vertexData[0] = (a * w1) + (c * h1) + tx; + vertexData[1] = (d * h1) + (b * w1) + ty; + // xy + vertexData[2] = (a * w0) + (c * h1) + tx; + vertexData[3] = (d * h1) + (b * w0) + ty; + // xy + vertexData[4] = (a * w0) + (c * h0) + tx; + vertexData[5] = (d * h0) + (b * w0) + ty; + // xy + vertexData[6] = (a * w1) + (c * h0) + tx; + vertexData[7] = (d * h0) + (b * w1) + ty; + }; + /** + * + * Renders the object using the WebGL renderer + * @param renderer - The webgl renderer to use. + */ + Sprite.prototype._render = function (renderer) { + this.calculateVertices(); + renderer.batch.setObjectRenderer(renderer.plugins[this.pluginName]); + renderer.plugins[this.pluginName].render(this); + }; + /** Updates the bounds of the sprite. */ + Sprite.prototype._calculateBounds = function () { + var trim = this._texture.trim; + var orig = this._texture.orig; + // First lets check to see if the current texture has a trim.. + if (!trim || (trim.width === orig.width && trim.height === orig.height)) { + // no trim! lets use the usual calculations.. + this.calculateVertices(); + this._bounds.addQuad(this.vertexData); + } + else { + // lets calculate a special trimmed bounds... + this.calculateTrimmedVertices(); + this._bounds.addQuad(this.vertexTrimmedData); + } + }; + /** + * Gets the local bounds of the sprite object. + * @param rect - Optional output rectangle. + * @returns The bounds. + */ + Sprite.prototype.getLocalBounds = function (rect) { + // we can do a fast local bounds if the sprite has no children! + if (this.children.length === 0) { + if (!this._localBounds) { + this._localBounds = new Bounds(); + } + this._localBounds.minX = this._texture.orig.width * -this._anchor._x; + this._localBounds.minY = this._texture.orig.height * -this._anchor._y; + this._localBounds.maxX = this._texture.orig.width * (1 - this._anchor._x); + this._localBounds.maxY = this._texture.orig.height * (1 - this._anchor._y); + if (!rect) { + if (!this._localBoundsRect) { + this._localBoundsRect = new Rectangle(); + } + rect = this._localBoundsRect; + } + return this._localBounds.getRectangle(rect); + } + return _super.prototype.getLocalBounds.call(this, rect); + }; + /** + * Tests if a point is inside this sprite + * @param point - the point to test + * @returns The result of the test + */ + Sprite.prototype.containsPoint = function (point) { + this.worldTransform.applyInverse(point, tempPoint$2); + var width = this._texture.orig.width; + var height = this._texture.orig.height; + var x1 = -width * this.anchor.x; + var y1 = 0; + if (tempPoint$2.x >= x1 && tempPoint$2.x < x1 + width) { + y1 = -height * this.anchor.y; + if (tempPoint$2.y >= y1 && tempPoint$2.y < y1 + height) { + return true; + } + } + return false; + }; + /** + * Destroys this sprite and optionally its texture and children. + * @param options - Options parameter. A boolean will act as if all options + * have been set to that value + * @param [options.children=false] - if set to true, all the children will have their destroy + * method called as well. 'options' will be passed on to those calls. + * @param [options.texture=false] - Should it destroy the current texture of the sprite as well + * @param [options.baseTexture=false] - Should it destroy the base texture of the sprite as well + */ + Sprite.prototype.destroy = function (options) { + _super.prototype.destroy.call(this, options); + this._texture.off('update', this._onTextureUpdate, this); + this._anchor = null; + var destroyTexture = typeof options === 'boolean' ? options : options && options.texture; + if (destroyTexture) { + var destroyBaseTexture = typeof options === 'boolean' ? options : options && options.baseTexture; + this._texture.destroy(!!destroyBaseTexture); + } + this._texture = null; + }; + // some helper functions.. + /** + * Helper function that creates a new sprite based on the source you provide. + * The source can be - frame id, image url, video url, canvas element, video element, base texture + * @param {string|PIXI.Texture|HTMLCanvasElement|HTMLVideoElement} source - Source to create texture from + * @param {object} [options] - See {@link PIXI.BaseTexture}'s constructor for options. + * @returns The newly created sprite + */ + Sprite.from = function (source, options) { + var texture = (source instanceof Texture) + ? source + : Texture.from(source, options); + return new Sprite(texture); + }; + Object.defineProperty(Sprite.prototype, "roundPixels", { + get: function () { + return this._roundPixels; + }, + /** + * If true PixiJS will Math.floor() x/y values when rendering, stopping pixel interpolation. + * + * Advantages can include sharper image quality (like text) and faster rendering on canvas. + * The main disadvantage is movement of objects may appear less smooth. + * + * To set the global default, change {@link PIXI.settings.ROUND_PIXELS}. + * @default false + */ + set: function (value) { + if (this._roundPixels !== value) { + this._transformID = -1; + } + this._roundPixels = value; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(Sprite.prototype, "width", { + /** The width of the sprite, setting this will actually modify the scale to achieve the value set. */ + get: function () { + return Math.abs(this.scale.x) * this._texture.orig.width; + }, + set: function (value) { + var s = sign(this.scale.x) || 1; + this.scale.x = s * value / this._texture.orig.width; + this._width = value; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(Sprite.prototype, "height", { + /** The height of the sprite, setting this will actually modify the scale to achieve the value set. */ + get: function () { + return Math.abs(this.scale.y) * this._texture.orig.height; + }, + set: function (value) { + var s = sign(this.scale.y) || 1; + this.scale.y = s * value / this._texture.orig.height; + this._height = value; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(Sprite.prototype, "anchor", { + /** + * The anchor sets the origin point of the sprite. The default value is taken from the {@link PIXI.Texture|Texture} + * and passed to the constructor. + * + * The default is `(0,0)`, this means the sprite's origin is the top left. + * + * Setting the anchor to `(0.5,0.5)` means the sprite's origin is centered. + * + * Setting the anchor to `(1,1)` would mean the sprite's origin point will be the bottom right corner. + * + * If you pass only single parameter, it will set both x and y to the same value as shown in the example below. + * @example + * const sprite = new PIXI.Sprite(texture); + * sprite.anchor.set(0.5); // This will set the origin to center. (0.5) is same as (0.5, 0.5). + */ + get: function () { + return this._anchor; + }, + set: function (value) { + this._anchor.copyFrom(value); + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(Sprite.prototype, "tint", { + /** + * The tint applied to the sprite. This is a hex value. + * + * A value of 0xFFFFFF will remove any tint effect. + * @default 0xFFFFFF + */ + get: function () { + return this._tint; + }, + set: function (value) { + this._tint = value; + this._tintRGB = (value >> 16) + (value & 0xff00) + ((value & 0xff) << 16); + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(Sprite.prototype, "texture", { + /** The texture that the sprite is using. */ + get: function () { + return this._texture; + }, + set: function (value) { + if (this._texture === value) { + return; + } + if (this._texture) { + this._texture.off('update', this._onTextureUpdate, this); + } + this._texture = value || Texture.EMPTY; + this._cachedTint = 0xFFFFFF; + this._textureID = -1; + this._textureTrimmedID = -1; + if (value) { + // wait for the texture to load + if (value.baseTexture.valid) { + this._onTextureUpdate(); + } + else { + value.once('update', this._onTextureUpdate, this); + } + } + }, + enumerable: false, + configurable: true + }); + return Sprite; + }(Container)); + + /*! + * @pixi/text - v6.5.3 + * Compiled Fri, 09 Sep 2022 13:55:20 UTC + * + * @pixi/text is licensed under the MIT License. + * http://www.opensource.org/licenses/mit-license + */ + + /*! ***************************************************************************** + Copyright (c) Microsoft Corporation. - THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED - WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, - MERCHANTABLITY OR NON-INFRINGEMENT. + Permission to use, copy, modify, and/or distribute this software for any + purpose with or without fee is hereby granted. - See the Apache Version 2.0 License for specific language governing permissions - and limitations under the License. - ***************************************************************************** */ - /* global Reflect, Promise */ + THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH + REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY + AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, + INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM + LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR + OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR + PERFORMANCE OF THIS SOFTWARE. + ***************************************************************************** */ + /* global Reflect, Promise */ - var extendStatics$d = function(d, b) { - extendStatics$d = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) { if (b.hasOwnProperty(p)) { d[p] = b[p]; } } }; - return extendStatics$d(d, b); - }; + var extendStatics$c = function(d, b) { + extendStatics$c = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) { if (b.hasOwnProperty(p)) { d[p] = b[p]; } } }; + return extendStatics$c(d, b); + }; - function __extends$d(d, b) { - extendStatics$d(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - } - - var vertTemplate = "\n attribute vec2 aVertexPosition;\n\n uniform mat3 projectionMatrix;\n\n uniform float strength;\n\n varying vec2 vBlurTexCoords[%size%];\n\n uniform vec4 inputSize;\n uniform vec4 outputFrame;\n\n vec4 filterVertexPosition( void )\n {\n vec2 position = aVertexPosition * max(outputFrame.zw, vec2(0.)) + outputFrame.xy;\n\n return vec4((projectionMatrix * vec3(position, 1.0)).xy, 0.0, 1.0);\n }\n\n vec2 filterTextureCoord( void )\n {\n return aVertexPosition * (outputFrame.zw * inputSize.zw);\n }\n\n void main(void)\n {\n gl_Position = filterVertexPosition();\n\n vec2 textureCoord = filterTextureCoord();\n %blur%\n }"; - function generateBlurVertSource(kernelSize, x) { - var halfLength = Math.ceil(kernelSize / 2); - var vertSource = vertTemplate; - var blurLoop = ''; - var template; - if (x) { - template = 'vBlurTexCoords[%index%] = textureCoord + vec2(%sampleIndex% * strength, 0.0);'; - } - else { - template = 'vBlurTexCoords[%index%] = textureCoord + vec2(0.0, %sampleIndex% * strength);'; - } - for (var i = 0; i < kernelSize; i++) { - var blur = template.replace('%index%', i.toString()); - blur = blur.replace('%sampleIndex%', i - (halfLength - 1) + ".0"); - blurLoop += blur; - blurLoop += '\n'; - } - vertSource = vertSource.replace('%blur%', blurLoop); - vertSource = vertSource.replace('%size%', kernelSize.toString()); - return vertSource; - } - - var GAUSSIAN_VALUES = { - 5: [0.153388, 0.221461, 0.250301], - 7: [0.071303, 0.131514, 0.189879, 0.214607], - 9: [0.028532, 0.067234, 0.124009, 0.179044, 0.20236], - 11: [0.0093, 0.028002, 0.065984, 0.121703, 0.175713, 0.198596], - 13: [0.002406, 0.009255, 0.027867, 0.065666, 0.121117, 0.174868, 0.197641], - 15: [0.000489, 0.002403, 0.009246, 0.02784, 0.065602, 0.120999, 0.174697, 0.197448], - }; - var fragTemplate$1 = [ - 'varying vec2 vBlurTexCoords[%size%];', - 'uniform sampler2D uSampler;', - 'void main(void)', - '{', - ' gl_FragColor = vec4(0.0);', - ' %blur%', - '}' ].join('\n'); - function generateBlurFragSource(kernelSize) { - var kernel = GAUSSIAN_VALUES[kernelSize]; - var halfLength = kernel.length; - var fragSource = fragTemplate$1; - var blurLoop = ''; - var template = 'gl_FragColor += texture2D(uSampler, vBlurTexCoords[%index%]) * %value%;'; - var value; - for (var i = 0; i < kernelSize; i++) { - var blur = template.replace('%index%', i.toString()); - value = i; - if (i >= halfLength) { - value = kernelSize - i - 1; - } - blur = blur.replace('%value%', kernel[value].toString()); - blurLoop += blur; - blurLoop += '\n'; - } - fragSource = fragSource.replace('%blur%', blurLoop); - fragSource = fragSource.replace('%size%', kernelSize.toString()); - return fragSource; - } - - /** - * Different types of environments for WebGL. - * - * @static - * @memberof PIXI - * @name ENV - * @enum {number} - * @property {number} WEBGL_LEGACY - Used for older v1 WebGL devices. PixiJS will aim to ensure compatibility - * with older / less advanced devices. If you experience unexplained flickering prefer this environment. - * @property {number} WEBGL - Version 1 of WebGL - * @property {number} WEBGL2 - Version 2 of WebGL - */ - var ENV; - (function (ENV) { - ENV[ENV["WEBGL_LEGACY"] = 0] = "WEBGL_LEGACY"; - ENV[ENV["WEBGL"] = 1] = "WEBGL"; - ENV[ENV["WEBGL2"] = 2] = "WEBGL2"; - })(ENV || (ENV = {})); - /** - * Constant to identify the Renderer Type. - * - * @static - * @memberof PIXI - * @name RENDERER_TYPE - * @enum {number} - * @property {number} UNKNOWN - Unknown render type. - * @property {number} WEBGL - WebGL render type. - * @property {number} CANVAS - Canvas render type. - */ - var RENDERER_TYPE; - (function (RENDERER_TYPE) { - RENDERER_TYPE[RENDERER_TYPE["UNKNOWN"] = 0] = "UNKNOWN"; - RENDERER_TYPE[RENDERER_TYPE["WEBGL"] = 1] = "WEBGL"; - RENDERER_TYPE[RENDERER_TYPE["CANVAS"] = 2] = "CANVAS"; - })(RENDERER_TYPE || (RENDERER_TYPE = {})); - /** - * Bitwise OR of masks that indicate the buffers to be cleared. - * - * @static - * @memberof PIXI - * @name BUFFER_BITS - * @enum {number} - * @property {number} COLOR - Indicates the buffers currently enabled for color writing. - * @property {number} DEPTH - Indicates the depth buffer. - * @property {number} STENCIL - Indicates the stencil buffer. - */ - var BUFFER_BITS; - (function (BUFFER_BITS) { - BUFFER_BITS[BUFFER_BITS["COLOR"] = 16384] = "COLOR"; - BUFFER_BITS[BUFFER_BITS["DEPTH"] = 256] = "DEPTH"; - BUFFER_BITS[BUFFER_BITS["STENCIL"] = 1024] = "STENCIL"; - })(BUFFER_BITS || (BUFFER_BITS = {})); - /** - * Various blend modes supported by PIXI. - * - * IMPORTANT - The WebGL renderer only supports the NORMAL, ADD, MULTIPLY and SCREEN blend modes. - * Anything else will silently act like NORMAL. - * - * @memberof PIXI - * @name BLEND_MODES - * @enum {number} - * @property {number} NORMAL - * @property {number} ADD - * @property {number} MULTIPLY - * @property {number} SCREEN - * @property {number} OVERLAY - * @property {number} DARKEN - * @property {number} LIGHTEN - * @property {number} COLOR_DODGE - * @property {number} COLOR_BURN - * @property {number} HARD_LIGHT - * @property {number} SOFT_LIGHT - * @property {number} DIFFERENCE - * @property {number} EXCLUSION - * @property {number} HUE - * @property {number} SATURATION - * @property {number} COLOR - * @property {number} LUMINOSITY - * @property {number} NORMAL_NPM - * @property {number} ADD_NPM - * @property {number} SCREEN_NPM - * @property {number} NONE - * @property {number} SRC_IN - * @property {number} SRC_OUT - * @property {number} SRC_ATOP - * @property {number} DST_OVER - * @property {number} DST_IN - * @property {number} DST_OUT - * @property {number} DST_ATOP - * @property {number} SUBTRACT - * @property {number} SRC_OVER - * @property {number} ERASE - * @property {number} XOR - */ - var BLEND_MODES; - (function (BLEND_MODES) { - BLEND_MODES[BLEND_MODES["NORMAL"] = 0] = "NORMAL"; - BLEND_MODES[BLEND_MODES["ADD"] = 1] = "ADD"; - BLEND_MODES[BLEND_MODES["MULTIPLY"] = 2] = "MULTIPLY"; - BLEND_MODES[BLEND_MODES["SCREEN"] = 3] = "SCREEN"; - BLEND_MODES[BLEND_MODES["OVERLAY"] = 4] = "OVERLAY"; - BLEND_MODES[BLEND_MODES["DARKEN"] = 5] = "DARKEN"; - BLEND_MODES[BLEND_MODES["LIGHTEN"] = 6] = "LIGHTEN"; - BLEND_MODES[BLEND_MODES["COLOR_DODGE"] = 7] = "COLOR_DODGE"; - BLEND_MODES[BLEND_MODES["COLOR_BURN"] = 8] = "COLOR_BURN"; - BLEND_MODES[BLEND_MODES["HARD_LIGHT"] = 9] = "HARD_LIGHT"; - BLEND_MODES[BLEND_MODES["SOFT_LIGHT"] = 10] = "SOFT_LIGHT"; - BLEND_MODES[BLEND_MODES["DIFFERENCE"] = 11] = "DIFFERENCE"; - BLEND_MODES[BLEND_MODES["EXCLUSION"] = 12] = "EXCLUSION"; - BLEND_MODES[BLEND_MODES["HUE"] = 13] = "HUE"; - BLEND_MODES[BLEND_MODES["SATURATION"] = 14] = "SATURATION"; - BLEND_MODES[BLEND_MODES["COLOR"] = 15] = "COLOR"; - BLEND_MODES[BLEND_MODES["LUMINOSITY"] = 16] = "LUMINOSITY"; - BLEND_MODES[BLEND_MODES["NORMAL_NPM"] = 17] = "NORMAL_NPM"; - BLEND_MODES[BLEND_MODES["ADD_NPM"] = 18] = "ADD_NPM"; - BLEND_MODES[BLEND_MODES["SCREEN_NPM"] = 19] = "SCREEN_NPM"; - BLEND_MODES[BLEND_MODES["NONE"] = 20] = "NONE"; - BLEND_MODES[BLEND_MODES["SRC_OVER"] = 0] = "SRC_OVER"; - BLEND_MODES[BLEND_MODES["SRC_IN"] = 21] = "SRC_IN"; - BLEND_MODES[BLEND_MODES["SRC_OUT"] = 22] = "SRC_OUT"; - BLEND_MODES[BLEND_MODES["SRC_ATOP"] = 23] = "SRC_ATOP"; - BLEND_MODES[BLEND_MODES["DST_OVER"] = 24] = "DST_OVER"; - BLEND_MODES[BLEND_MODES["DST_IN"] = 25] = "DST_IN"; - BLEND_MODES[BLEND_MODES["DST_OUT"] = 26] = "DST_OUT"; - BLEND_MODES[BLEND_MODES["DST_ATOP"] = 27] = "DST_ATOP"; - BLEND_MODES[BLEND_MODES["ERASE"] = 26] = "ERASE"; - BLEND_MODES[BLEND_MODES["SUBTRACT"] = 28] = "SUBTRACT"; - BLEND_MODES[BLEND_MODES["XOR"] = 29] = "XOR"; - })(BLEND_MODES || (BLEND_MODES = {})); - /** - * Various webgl draw modes. These can be used to specify which GL drawMode to use - * under certain situations and renderers. - * - * @memberof PIXI - * @static - * @name DRAW_MODES - * @enum {number} - * @property {number} POINTS - * @property {number} LINES - * @property {number} LINE_LOOP - * @property {number} LINE_STRIP - * @property {number} TRIANGLES - * @property {number} TRIANGLE_STRIP - * @property {number} TRIANGLE_FAN - */ - var DRAW_MODES; - (function (DRAW_MODES) { - DRAW_MODES[DRAW_MODES["POINTS"] = 0] = "POINTS"; - DRAW_MODES[DRAW_MODES["LINES"] = 1] = "LINES"; - DRAW_MODES[DRAW_MODES["LINE_LOOP"] = 2] = "LINE_LOOP"; - DRAW_MODES[DRAW_MODES["LINE_STRIP"] = 3] = "LINE_STRIP"; - DRAW_MODES[DRAW_MODES["TRIANGLES"] = 4] = "TRIANGLES"; - DRAW_MODES[DRAW_MODES["TRIANGLE_STRIP"] = 5] = "TRIANGLE_STRIP"; - DRAW_MODES[DRAW_MODES["TRIANGLE_FAN"] = 6] = "TRIANGLE_FAN"; - })(DRAW_MODES || (DRAW_MODES = {})); - /** - * Various GL texture/resources formats. - * - * @memberof PIXI - * @static - * @name FORMATS - * @enum {number} - * @property {number} RGBA=6408 - * @property {number} RGB=6407 - * @property {number} ALPHA=6406 - * @property {number} LUMINANCE=6409 - * @property {number} LUMINANCE_ALPHA=6410 - * @property {number} DEPTH_COMPONENT=6402 - * @property {number} DEPTH_STENCIL=34041 - */ - var FORMATS; - (function (FORMATS) { - FORMATS[FORMATS["RGBA"] = 6408] = "RGBA"; - FORMATS[FORMATS["RGB"] = 6407] = "RGB"; - FORMATS[FORMATS["ALPHA"] = 6406] = "ALPHA"; - FORMATS[FORMATS["LUMINANCE"] = 6409] = "LUMINANCE"; - FORMATS[FORMATS["LUMINANCE_ALPHA"] = 6410] = "LUMINANCE_ALPHA"; - FORMATS[FORMATS["DEPTH_COMPONENT"] = 6402] = "DEPTH_COMPONENT"; - FORMATS[FORMATS["DEPTH_STENCIL"] = 34041] = "DEPTH_STENCIL"; - })(FORMATS || (FORMATS = {})); - /** - * Various GL target types. - * - * @memberof PIXI - * @static - * @name TARGETS - * @enum {number} - * @property {number} TEXTURE_2D=3553 - * @property {number} TEXTURE_CUBE_MAP=34067 - * @property {number} TEXTURE_2D_ARRAY=35866 - * @property {number} TEXTURE_CUBE_MAP_POSITIVE_X=34069 - * @property {number} TEXTURE_CUBE_MAP_NEGATIVE_X=34070 - * @property {number} TEXTURE_CUBE_MAP_POSITIVE_Y=34071 - * @property {number} TEXTURE_CUBE_MAP_NEGATIVE_Y=34072 - * @property {number} TEXTURE_CUBE_MAP_POSITIVE_Z=34073 - * @property {number} TEXTURE_CUBE_MAP_NEGATIVE_Z=34074 - */ - var TARGETS; - (function (TARGETS) { - TARGETS[TARGETS["TEXTURE_2D"] = 3553] = "TEXTURE_2D"; - TARGETS[TARGETS["TEXTURE_CUBE_MAP"] = 34067] = "TEXTURE_CUBE_MAP"; - TARGETS[TARGETS["TEXTURE_2D_ARRAY"] = 35866] = "TEXTURE_2D_ARRAY"; - TARGETS[TARGETS["TEXTURE_CUBE_MAP_POSITIVE_X"] = 34069] = "TEXTURE_CUBE_MAP_POSITIVE_X"; - TARGETS[TARGETS["TEXTURE_CUBE_MAP_NEGATIVE_X"] = 34070] = "TEXTURE_CUBE_MAP_NEGATIVE_X"; - TARGETS[TARGETS["TEXTURE_CUBE_MAP_POSITIVE_Y"] = 34071] = "TEXTURE_CUBE_MAP_POSITIVE_Y"; - TARGETS[TARGETS["TEXTURE_CUBE_MAP_NEGATIVE_Y"] = 34072] = "TEXTURE_CUBE_MAP_NEGATIVE_Y"; - TARGETS[TARGETS["TEXTURE_CUBE_MAP_POSITIVE_Z"] = 34073] = "TEXTURE_CUBE_MAP_POSITIVE_Z"; - TARGETS[TARGETS["TEXTURE_CUBE_MAP_NEGATIVE_Z"] = 34074] = "TEXTURE_CUBE_MAP_NEGATIVE_Z"; - })(TARGETS || (TARGETS = {})); - /** - * Various GL data format types. - * - * @memberof PIXI - * @static - * @name TYPES - * @enum {number} - * @property {number} UNSIGNED_BYTE=5121 - * @property {number} UNSIGNED_SHORT=5123 - * @property {number} UNSIGNED_SHORT_5_6_5=33635 - * @property {number} UNSIGNED_SHORT_4_4_4_4=32819 - * @property {number} UNSIGNED_SHORT_5_5_5_1=32820 - * @property {number} FLOAT=5126 - * @property {number} HALF_FLOAT=36193 - */ - var TYPES; - (function (TYPES) { - TYPES[TYPES["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE"; - TYPES[TYPES["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT"; - TYPES[TYPES["UNSIGNED_SHORT_5_6_5"] = 33635] = "UNSIGNED_SHORT_5_6_5"; - TYPES[TYPES["UNSIGNED_SHORT_4_4_4_4"] = 32819] = "UNSIGNED_SHORT_4_4_4_4"; - TYPES[TYPES["UNSIGNED_SHORT_5_5_5_1"] = 32820] = "UNSIGNED_SHORT_5_5_5_1"; - TYPES[TYPES["FLOAT"] = 5126] = "FLOAT"; - TYPES[TYPES["HALF_FLOAT"] = 36193] = "HALF_FLOAT"; - })(TYPES || (TYPES = {})); - /** - * The scale modes that are supported by pixi. - * - * The {@link PIXI.settings.SCALE_MODE} scale mode affects the default scaling mode of future operations. - * It can be re-assigned to either LINEAR or NEAREST, depending upon suitability. - * - * @memberof PIXI - * @static - * @name SCALE_MODES - * @enum {number} - * @property {number} LINEAR Smooth scaling - * @property {number} NEAREST Pixelating scaling - */ - var SCALE_MODES; - (function (SCALE_MODES) { - SCALE_MODES[SCALE_MODES["NEAREST"] = 0] = "NEAREST"; - SCALE_MODES[SCALE_MODES["LINEAR"] = 1] = "LINEAR"; - })(SCALE_MODES || (SCALE_MODES = {})); - /** - * The wrap modes that are supported by pixi. - * - * The {@link PIXI.settings.WRAP_MODE} wrap mode affects the default wrapping mode of future operations. - * It can be re-assigned to either CLAMP or REPEAT, depending upon suitability. - * If the texture is non power of two then clamp will be used regardless as WebGL can - * only use REPEAT if the texture is po2. - * - * This property only affects WebGL. - * - * @name WRAP_MODES - * @memberof PIXI - * @static - * @enum {number} - * @property {number} CLAMP - The textures uvs are clamped - * @property {number} REPEAT - The texture uvs tile and repeat - * @property {number} MIRRORED_REPEAT - The texture uvs tile and repeat with mirroring - */ - var WRAP_MODES; - (function (WRAP_MODES) { - WRAP_MODES[WRAP_MODES["CLAMP"] = 33071] = "CLAMP"; - WRAP_MODES[WRAP_MODES["REPEAT"] = 10497] = "REPEAT"; - WRAP_MODES[WRAP_MODES["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT"; - })(WRAP_MODES || (WRAP_MODES = {})); - /** - * Mipmap filtering modes that are supported by pixi. - * - * The {@link PIXI.settings.MIPMAP_TEXTURES} affects default texture filtering. - * Mipmaps are generated for a baseTexture if its `mipmap` field is `ON`, - * or its `POW2` and texture dimensions are powers of 2. - * Due to platform restriction, `ON` option will work like `POW2` for webgl-1. - * - * This property only affects WebGL. - * - * @name MIPMAP_MODES - * @memberof PIXI - * @static - * @enum {number} - * @property {number} OFF - No mipmaps - * @property {number} POW2 - Generate mipmaps if texture dimensions are pow2 - * @property {number} ON - Always generate mipmaps - */ - var MIPMAP_MODES; - (function (MIPMAP_MODES) { - MIPMAP_MODES[MIPMAP_MODES["OFF"] = 0] = "OFF"; - MIPMAP_MODES[MIPMAP_MODES["POW2"] = 1] = "POW2"; - MIPMAP_MODES[MIPMAP_MODES["ON"] = 2] = "ON"; - })(MIPMAP_MODES || (MIPMAP_MODES = {})); - /** - * How to treat textures with premultiplied alpha - * - * @name ALPHA_MODES - * @memberof PIXI - * @static - * @enum {number} - * @property {number} NO_PREMULTIPLIED_ALPHA - Source is not premultiplied, leave it like that. - * Option for compressed and data textures that are created from typed arrays. - * @property {number} PREMULTIPLY_ON_UPLOAD - Source is not premultiplied, premultiply on upload. - * Default option, used for all loaded images. - * @property {number} PREMULTIPLIED_ALPHA - Source is already premultiplied - * Example: spine atlases with `_pma` suffix. - * @property {number} NPM - Alias for NO_PREMULTIPLIED_ALPHA. - * @property {number} UNPACK - Default option, alias for PREMULTIPLY_ON_UPLOAD. - * @property {number} PMA - Alias for PREMULTIPLIED_ALPHA. - */ - var ALPHA_MODES; - (function (ALPHA_MODES) { - ALPHA_MODES[ALPHA_MODES["NPM"] = 0] = "NPM"; - ALPHA_MODES[ALPHA_MODES["UNPACK"] = 1] = "UNPACK"; - ALPHA_MODES[ALPHA_MODES["PMA"] = 2] = "PMA"; - ALPHA_MODES[ALPHA_MODES["NO_PREMULTIPLIED_ALPHA"] = 0] = "NO_PREMULTIPLIED_ALPHA"; - ALPHA_MODES[ALPHA_MODES["PREMULTIPLY_ON_UPLOAD"] = 1] = "PREMULTIPLY_ON_UPLOAD"; - ALPHA_MODES[ALPHA_MODES["PREMULTIPLY_ALPHA"] = 2] = "PREMULTIPLY_ALPHA"; - })(ALPHA_MODES || (ALPHA_MODES = {})); - /** - * How to clear renderTextures in filter - * - * @name CLEAR_MODES - * @memberof PIXI - * @static - * @enum {number} - * @property {number} BLEND - Preserve the information in the texture, blend above - * @property {number} CLEAR - Must use `gl.clear` operation - * @property {number} BLIT - Clear or blit it, depends on device and level of paranoia - * @property {number} NO - Alias for BLEND, same as `false` in earlier versions - * @property {number} YES - Alias for CLEAR, same as `true` in earlier versions - * @property {number} AUTO - Alias for BLIT - */ - var CLEAR_MODES; - (function (CLEAR_MODES) { - CLEAR_MODES[CLEAR_MODES["NO"] = 0] = "NO"; - CLEAR_MODES[CLEAR_MODES["YES"] = 1] = "YES"; - CLEAR_MODES[CLEAR_MODES["AUTO"] = 2] = "AUTO"; - CLEAR_MODES[CLEAR_MODES["BLEND"] = 0] = "BLEND"; - CLEAR_MODES[CLEAR_MODES["CLEAR"] = 1] = "CLEAR"; - CLEAR_MODES[CLEAR_MODES["BLIT"] = 2] = "BLIT"; - })(CLEAR_MODES || (CLEAR_MODES = {})); - /** - * The gc modes that are supported by pixi. - * - * The {@link PIXI.settings.GC_MODE} Garbage Collection mode for PixiJS textures is AUTO - * If set to GC_MODE, the renderer will occasionally check textures usage. If they are not - * used for a specified period of time they will be removed from the GPU. They will of course - * be uploaded again when they are required. This is a silent behind the scenes process that - * should ensure that the GPU does not get filled up. - * - * Handy for mobile devices! - * This property only affects WebGL. - * - * @name GC_MODES - * @enum {number} - * @static - * @memberof PIXI - * @property {number} AUTO - Garbage collection will happen periodically automatically - * @property {number} MANUAL - Garbage collection will need to be called manually - */ - var GC_MODES; - (function (GC_MODES) { - GC_MODES[GC_MODES["AUTO"] = 0] = "AUTO"; - GC_MODES[GC_MODES["MANUAL"] = 1] = "MANUAL"; - })(GC_MODES || (GC_MODES = {})); - /** - * Constants that specify float precision in shaders. - * - * @name PRECISION - * @memberof PIXI - * @constant - * @static - * @enum {string} - * @property {string} LOW='lowp' - * @property {string} MEDIUM='mediump' - * @property {string} HIGH='highp' - */ - var PRECISION; - (function (PRECISION) { - PRECISION["LOW"] = "lowp"; - PRECISION["MEDIUM"] = "mediump"; - PRECISION["HIGH"] = "highp"; - })(PRECISION || (PRECISION = {})); - /** - * Constants for mask implementations. - * We use `type` suffix because it leads to very different behaviours - * - * @name MASK_TYPES - * @memberof PIXI - * @static - * @enum {number} - * @property {number} NONE - Mask is ignored - * @property {number} SCISSOR - Scissor mask, rectangle on screen, cheap - * @property {number} STENCIL - Stencil mask, 1-bit, medium, works only if renderer supports stencil - * @property {number} SPRITE - Mask that uses SpriteMaskFilter, uses temporary RenderTexture - */ - var MASK_TYPES; - (function (MASK_TYPES) { - MASK_TYPES[MASK_TYPES["NONE"] = 0] = "NONE"; - MASK_TYPES[MASK_TYPES["SCISSOR"] = 1] = "SCISSOR"; - MASK_TYPES[MASK_TYPES["STENCIL"] = 2] = "STENCIL"; - MASK_TYPES[MASK_TYPES["SPRITE"] = 3] = "SPRITE"; - })(MASK_TYPES || (MASK_TYPES = {})); - /** - * Constants for multi-sampling antialiasing. - * - * @see PIXI.Framebuffer#multisample - * - * @name MSAA_QUALITY - * @memberof PIXI - * @static - * @enum {number} - * @property {number} NONE - No multisampling for this renderTexture - * @property {number} LOW - Try 2 samples - * @property {number} MEDIUM - Try 4 samples - * @property {number} HIGH - Try 8 samples - */ - var MSAA_QUALITY; - (function (MSAA_QUALITY) { - MSAA_QUALITY[MSAA_QUALITY["NONE"] = 0] = "NONE"; - MSAA_QUALITY[MSAA_QUALITY["LOW"] = 2] = "LOW"; - MSAA_QUALITY[MSAA_QUALITY["MEDIUM"] = 4] = "MEDIUM"; - MSAA_QUALITY[MSAA_QUALITY["HIGH"] = 8] = "HIGH"; - })(MSAA_QUALITY || (MSAA_QUALITY = {})); - - /** - * The BlurFilterPass applies a horizontal or vertical Gaussian blur to an object. - * - * @class - * @extends PIXI.Filter - * @memberof PIXI.filters - */ - var BlurFilterPass = /** @class */ (function (_super) { - __extends$d(BlurFilterPass, _super); - /** - * @param {boolean} horizontal - Do pass along the x-axis (`true`) or y-axis (`false`). - * @param {number} [strength=8] - The strength of the blur filter. - * @param {number} [quality=4] - The quality of the blur filter. - * @param {number} [resolution=1] - The resolution of the blur filter. - * @param {number} [kernelSize=5] - The kernelSize of the blur filter.Options: 5, 7, 9, 11, 13, 15. - */ - function BlurFilterPass(horizontal, strength, quality, resolution, kernelSize) { - if (strength === void 0) { strength = 8; } - if (quality === void 0) { quality = 4; } - if (resolution === void 0) { resolution = settings.RESOLUTION; } - if (kernelSize === void 0) { kernelSize = 5; } - var _this = this; - var vertSrc = generateBlurVertSource(kernelSize, horizontal); - var fragSrc = generateBlurFragSource(kernelSize); - _this = _super.call(this, - // vertex shader - vertSrc, - // fragment shader - fragSrc) || this; - _this.horizontal = horizontal; - _this.resolution = resolution; - _this._quality = 0; - _this.quality = quality; - _this.blur = strength; - return _this; - } - /** - * Applies the filter. - * - * @param {PIXI.systems.FilterSystem} filterManager - The manager. - * @param {PIXI.RenderTexture} input - The input target. - * @param {PIXI.RenderTexture} output - The output target. - * @param {PIXI.CLEAR_MODES} clearMode - How to clear - */ - BlurFilterPass.prototype.apply = function (filterManager, input, output, clearMode) { - if (output) { - if (this.horizontal) { - this.uniforms.strength = (1 / output.width) * (output.width / input.width); - } - else { - this.uniforms.strength = (1 / output.height) * (output.height / input.height); - } - } - else { - if (this.horizontal) // eslint-disable-line - { - this.uniforms.strength = (1 / filterManager.renderer.width) * (filterManager.renderer.width / input.width); - } - else { - this.uniforms.strength = (1 / filterManager.renderer.height) * (filterManager.renderer.height / input.height); // eslint-disable-line - } - } - // screen space! - this.uniforms.strength *= this.strength; - this.uniforms.strength /= this.passes; - if (this.passes === 1) { - filterManager.applyFilter(this, input, output, clearMode); - } - else { - var renderTarget = filterManager.getFilterTexture(); - var renderer = filterManager.renderer; - var flip = input; - var flop = renderTarget; - this.state.blend = false; - filterManager.applyFilter(this, flip, flop, CLEAR_MODES.CLEAR); - for (var i = 1; i < this.passes - 1; i++) { - filterManager.bindAndClear(flip, CLEAR_MODES.BLIT); - this.uniforms.uSampler = flop; - var temp = flop; - flop = flip; - flip = temp; - renderer.shader.bind(this); - renderer.geometry.draw(5); - } - this.state.blend = true; - filterManager.applyFilter(this, flop, output, clearMode); - filterManager.returnFilterTexture(renderTarget); - } - }; - Object.defineProperty(BlurFilterPass.prototype, "blur", { - /** - * Sets the strength of both the blur. - * - * @member {number} - * @default 16 - */ - get: function () { - return this.strength; - }, - set: function (value) { - this.padding = 1 + (Math.abs(value) * 2); - this.strength = value; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BlurFilterPass.prototype, "quality", { - /** - * Sets the quality of the blur by modifying the number of passes. More passes means higher - * quaility bluring but the lower the performance. - * - * @member {number} - * @default 4 - */ - get: function () { - return this._quality; - }, - set: function (value) { - this._quality = value; - this.passes = value; - }, - enumerable: false, - configurable: true - }); - return BlurFilterPass; - }(Filter)); - - /** - * The BlurFilter applies a Gaussian blur to an object. - * - * The strength of the blur can be set for the x-axis and y-axis separately. - * - * @class - * @extends PIXI.Filter - * @memberof PIXI.filters - */ - var BlurFilter = /** @class */ (function (_super) { - __extends$d(BlurFilter, _super); - /** - * @param {number} [strength=8] - The strength of the blur filter. - * @param {number} [quality=4] - The quality of the blur filter. - * @param {number} [resolution=1] - The resolution of the blur filter. - * @param {number} [kernelSize=5] - The kernelSize of the blur filter.Options: 5, 7, 9, 11, 13, 15. - */ - function BlurFilter(strength, quality, resolution, kernelSize) { - if (strength === void 0) { strength = 8; } - if (quality === void 0) { quality = 4; } - if (resolution === void 0) { resolution = settings.RESOLUTION; } - if (kernelSize === void 0) { kernelSize = 5; } - var _this = _super.call(this) || this; - _this.blurXFilter = new BlurFilterPass(true, strength, quality, resolution, kernelSize); - _this.blurYFilter = new BlurFilterPass(false, strength, quality, resolution, kernelSize); - _this.resolution = resolution; - _this.quality = quality; - _this.blur = strength; - _this.repeatEdgePixels = false; - return _this; - } - /** - * Applies the filter. - * - * @param {PIXI.systems.FilterSystem} filterManager - The manager. - * @param {PIXI.RenderTexture} input - The input target. - * @param {PIXI.RenderTexture} output - The output target. - * @param {PIXI.CLEAR_MODES} clearMode - How to clear - */ - BlurFilter.prototype.apply = function (filterManager, input, output, clearMode) { - var xStrength = Math.abs(this.blurXFilter.strength); - var yStrength = Math.abs(this.blurYFilter.strength); - if (xStrength && yStrength) { - var renderTarget = filterManager.getFilterTexture(); - this.blurXFilter.apply(filterManager, input, renderTarget, CLEAR_MODES.CLEAR); - this.blurYFilter.apply(filterManager, renderTarget, output, clearMode); - filterManager.returnFilterTexture(renderTarget); - } - else if (yStrength) { - this.blurYFilter.apply(filterManager, input, output, clearMode); - } - else { - this.blurXFilter.apply(filterManager, input, output, clearMode); - } - }; - BlurFilter.prototype.updatePadding = function () { - if (this._repeatEdgePixels) { - this.padding = 0; - } - else { - this.padding = Math.max(Math.abs(this.blurXFilter.strength), Math.abs(this.blurYFilter.strength)) * 2; - } - }; - Object.defineProperty(BlurFilter.prototype, "blur", { - /** - * Sets the strength of both the blurX and blurY properties simultaneously - * - * @member {number} - * @default 2 - */ - get: function () { - return this.blurXFilter.blur; - }, - set: function (value) { - this.blurXFilter.blur = this.blurYFilter.blur = value; - this.updatePadding(); - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BlurFilter.prototype, "quality", { - /** - * Sets the number of passes for blur. More passes means higher quaility bluring. - * - * @member {number} - * @default 1 - */ - get: function () { - return this.blurXFilter.quality; - }, - set: function (value) { - this.blurXFilter.quality = this.blurYFilter.quality = value; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BlurFilter.prototype, "blurX", { - /** - * Sets the strength of the blurX property - * - * @member {number} - * @default 2 - */ - get: function () { - return this.blurXFilter.blur; - }, - set: function (value) { - this.blurXFilter.blur = value; - this.updatePadding(); - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BlurFilter.prototype, "blurY", { - /** - * Sets the strength of the blurY property - * - * @member {number} - * @default 2 - */ - get: function () { - return this.blurYFilter.blur; - }, - set: function (value) { - this.blurYFilter.blur = value; - this.updatePadding(); - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BlurFilter.prototype, "blendMode", { - /** - * Sets the blendmode of the filter - * - * @member {number} - * @default PIXI.BLEND_MODES.NORMAL - */ - get: function () { - return this.blurYFilter.blendMode; - }, - set: function (value) { - this.blurYFilter.blendMode = value; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(BlurFilter.prototype, "repeatEdgePixels", { - /** - * If set to true the edge of the target will be clamped - * - * @member {boolean} - * @default false - */ - get: function () { - return this._repeatEdgePixels; - }, - set: function (value) { - this._repeatEdgePixels = value; - this.updatePadding(); - }, - enumerable: false, - configurable: true - }); - return BlurFilter; - }(Filter)); - - /*! - * @pixi/filter-color-matrix - v5.3.3 - * Compiled Tue, 04 Aug 2020 16:23:09 UTC - * - * @pixi/filter-color-matrix is licensed under the MIT License. - * http://www.opensource.org/licenses/mit-license - */ - - /*! ***************************************************************************** - Copyright (c) Microsoft Corporation. All rights reserved. - Licensed under the Apache License, Version 2.0 (the "License"); you may not use - this file except in compliance with the License. You may obtain a copy of the - License at http://www.apache.org/licenses/LICENSE-2.0 + function __extends$c(d, b) { + extendStatics$c(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + } + + /** + * Constants that define the type of gradient on text. + * @static + * @constant + * @name TEXT_GRADIENT + * @memberof PIXI + * @type {object} + * @property {number} LINEAR_VERTICAL Vertical gradient + * @property {number} LINEAR_HORIZONTAL Linear gradient + */ + exports.TEXT_GRADIENT = void 0; + (function (TEXT_GRADIENT) { + TEXT_GRADIENT[TEXT_GRADIENT["LINEAR_VERTICAL"] = 0] = "LINEAR_VERTICAL"; + TEXT_GRADIENT[TEXT_GRADIENT["LINEAR_HORIZONTAL"] = 1] = "LINEAR_HORIZONTAL"; + })(exports.TEXT_GRADIENT || (exports.TEXT_GRADIENT = {})); + + // disabling eslint for now, going to rewrite this in v5 + var defaultStyle = { + align: 'left', + breakWords: false, + dropShadow: false, + dropShadowAlpha: 1, + dropShadowAngle: Math.PI / 6, + dropShadowBlur: 0, + dropShadowColor: 'black', + dropShadowDistance: 5, + fill: 'black', + fillGradientType: exports.TEXT_GRADIENT.LINEAR_VERTICAL, + fillGradientStops: [], + fontFamily: 'Arial', + fontSize: 26, + fontStyle: 'normal', + fontVariant: 'normal', + fontWeight: 'normal', + letterSpacing: 0, + lineHeight: 0, + lineJoin: 'miter', + miterLimit: 10, + padding: 0, + stroke: 'black', + strokeThickness: 0, + textBaseline: 'alphabetic', + trim: false, + whiteSpace: 'pre', + wordWrap: false, + wordWrapWidth: 100, + leading: 0, + }; + var genericFontFamilies = [ + 'serif', + 'sans-serif', + 'monospace', + 'cursive', + 'fantasy', + 'system-ui' ]; + /** + * A TextStyle Object contains information to decorate a Text objects. + * + * An instance can be shared between multiple Text objects; then changing the style will update all text objects using it. + * + * A tool can be used to generate a text style [here](https://pixijs.io/pixi-text-style). + * + * @memberof PIXI + */ + var TextStyle = /** @class */ (function () { + /** + * @param {object} [style] - The style parameters + * @param {string} [style.align='left'] - Alignment for multiline text ('left', 'center' or 'right'), + * does not affect single line text + * @param {boolean} [style.breakWords=false] - Indicates if lines can be wrapped within words, it + * needs wordWrap to be set to true + * @param {boolean} [style.dropShadow=false] - Set a drop shadow for the text + * @param {number} [style.dropShadowAlpha=1] - Set alpha for the drop shadow + * @param {number} [style.dropShadowAngle=Math.PI/6] - Set a angle of the drop shadow + * @param {number} [style.dropShadowBlur=0] - Set a shadow blur radius + * @param {string|number} [style.dropShadowColor='black'] - A fill style to be used on the dropshadow e.g 'red', '#00FF00' + * @param {number} [style.dropShadowDistance=5] - Set a distance of the drop shadow + * @param {string|string[]|number|number[]|CanvasGradient|CanvasPattern} [style.fill='black'] - A canvas + * fillstyle that will be used on the text e.g 'red', '#00FF00'. Can be an array to create a gradient + * eg ['#000000','#FFFFFF'] + * {@link https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/fillStyle|MDN} + * @param {number} [style.fillGradientType=PIXI.TEXT_GRADIENT.LINEAR_VERTICAL] - If fill is an array of colours + * to create a gradient, this can change the type/direction of the gradient. See {@link PIXI.TEXT_GRADIENT} + * @param {number[]} [style.fillGradientStops] - If fill is an array of colours to create a gradient, this array can set + * the stop points (numbers between 0 and 1) for the color, overriding the default behaviour of evenly spacing them. + * @param {string|string[]} [style.fontFamily='Arial'] - The font family + * @param {number|string} [style.fontSize=26] - The font size (as a number it converts to px, but as a string, + * equivalents are '26px','20pt','160%' or '1.6em') + * @param {string} [style.fontStyle='normal'] - The font style ('normal', 'italic' or 'oblique') + * @param {string} [style.fontVariant='normal'] - The font variant ('normal' or 'small-caps') + * @param {string} [style.fontWeight='normal'] - The font weight ('normal', 'bold', 'bolder', 'lighter' and '100', + * '200', '300', '400', '500', '600', '700', '800' or '900') + * @param {number} [style.leading=0] - The space between lines + * @param {number} [style.letterSpacing=0] - The amount of spacing between letters, default is 0 + * @param {number} [style.lineHeight] - The line height, a number that represents the vertical space that a letter uses + * @param {string} [style.lineJoin='miter'] - The lineJoin property sets the type of corner created, it can resolve + * spiked text issues. Possible values "miter" (creates a sharp corner), "round" (creates a round corner) or "bevel" + * (creates a squared corner). + * @param {number} [style.miterLimit=10] - The miter limit to use when using the 'miter' lineJoin mode. This can reduce + * or increase the spikiness of rendered text. + * @param {number} [style.padding=0] - Occasionally some fonts are cropped. Adding some padding will prevent this from + * happening by adding padding to all sides of the text. + * @param {string|number} [style.stroke='black'] - A canvas fillstyle that will be used on the text stroke + * e.g 'blue', '#FCFF00' + * @param {number} [style.strokeThickness=0] - A number that represents the thickness of the stroke. + * Default is 0 (no stroke) + * @param {boolean} [style.trim=false] - Trim transparent borders + * @param {string} [style.textBaseline='alphabetic'] - The baseline of the text that is rendered. + * @param {string} [style.whiteSpace='pre'] - Determines whether newlines & spaces are collapsed or preserved "normal" + * (collapse, collapse), "pre" (preserve, preserve) | "pre-line" (preserve, collapse). It needs wordWrap to be set to true + * @param {boolean} [style.wordWrap=false] - Indicates if word wrap should be used + * @param {number} [style.wordWrapWidth=100] - The width at which text will wrap, it needs wordWrap to be set to true + */ + function TextStyle(style) { + this.styleID = 0; + this.reset(); + deepCopyProperties(this, style, style); + } + /** + * Creates a new TextStyle object with the same values as this one. + * Note that the only the properties of the object are cloned. + * + * @return New cloned TextStyle object + */ + TextStyle.prototype.clone = function () { + var clonedProperties = {}; + deepCopyProperties(clonedProperties, this, defaultStyle); + return new TextStyle(clonedProperties); + }; + /** Resets all properties to the defaults specified in TextStyle.prototype._default */ + TextStyle.prototype.reset = function () { + deepCopyProperties(this, defaultStyle, defaultStyle); + }; + Object.defineProperty(TextStyle.prototype, "align", { + /** + * Alignment for multiline text ('left', 'center' or 'right'), does not affect single line text + * + * @member {string} + */ + get: function () { + return this._align; + }, + set: function (align) { + if (this._align !== align) { + this._align = align; + this.styleID++; + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(TextStyle.prototype, "breakWords", { + /** Indicates if lines can be wrapped within words, it needs wordWrap to be set to true. */ + get: function () { + return this._breakWords; + }, + set: function (breakWords) { + if (this._breakWords !== breakWords) { + this._breakWords = breakWords; + this.styleID++; + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(TextStyle.prototype, "dropShadow", { + /** Set a drop shadow for the text. */ + get: function () { + return this._dropShadow; + }, + set: function (dropShadow) { + if (this._dropShadow !== dropShadow) { + this._dropShadow = dropShadow; + this.styleID++; + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(TextStyle.prototype, "dropShadowAlpha", { + /** Set alpha for the drop shadow. */ + get: function () { + return this._dropShadowAlpha; + }, + set: function (dropShadowAlpha) { + if (this._dropShadowAlpha !== dropShadowAlpha) { + this._dropShadowAlpha = dropShadowAlpha; + this.styleID++; + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(TextStyle.prototype, "dropShadowAngle", { + /** Set a angle of the drop shadow. */ + get: function () { + return this._dropShadowAngle; + }, + set: function (dropShadowAngle) { + if (this._dropShadowAngle !== dropShadowAngle) { + this._dropShadowAngle = dropShadowAngle; + this.styleID++; + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(TextStyle.prototype, "dropShadowBlur", { + /** Set a shadow blur radius. */ + get: function () { + return this._dropShadowBlur; + }, + set: function (dropShadowBlur) { + if (this._dropShadowBlur !== dropShadowBlur) { + this._dropShadowBlur = dropShadowBlur; + this.styleID++; + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(TextStyle.prototype, "dropShadowColor", { + /** A fill style to be used on the dropshadow e.g 'red', '#00FF00'. */ + get: function () { + return this._dropShadowColor; + }, + set: function (dropShadowColor) { + var outputColor = getColor(dropShadowColor); + if (this._dropShadowColor !== outputColor) { + this._dropShadowColor = outputColor; + this.styleID++; + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(TextStyle.prototype, "dropShadowDistance", { + /** Set a distance of the drop shadow. */ + get: function () { + return this._dropShadowDistance; + }, + set: function (dropShadowDistance) { + if (this._dropShadowDistance !== dropShadowDistance) { + this._dropShadowDistance = dropShadowDistance; + this.styleID++; + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(TextStyle.prototype, "fill", { + /** + * A canvas fillstyle that will be used on the text e.g 'red', '#00FF00'. + * + * Can be an array to create a gradient eg ['#000000','#FFFFFF'] + * {@link https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/fillStyle|MDN} + * + * @member {string|string[]|number|number[]|CanvasGradient|CanvasPattern} + */ + get: function () { + return this._fill; + }, + set: function (fill) { + // TODO: Can't have different types for getter and setter. The getter shouldn't have the number type as + // the setter converts to string. See this thread for more details: + // https://github.com/microsoft/TypeScript/issues/2521 + // TODO: Not sure if getColor works properly with CanvasGradient and/or CanvasPattern, can't pass in + // without casting here. + var outputColor = getColor(fill); + if (this._fill !== outputColor) { + this._fill = outputColor; + this.styleID++; + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(TextStyle.prototype, "fillGradientType", { + /** + * If fill is an array of colours to create a gradient, this can change the type/direction of the gradient. + * + * @see PIXI.TEXT_GRADIENT + */ + get: function () { + return this._fillGradientType; + }, + set: function (fillGradientType) { + if (this._fillGradientType !== fillGradientType) { + this._fillGradientType = fillGradientType; + this.styleID++; + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(TextStyle.prototype, "fillGradientStops", { + /** + * If fill is an array of colours to create a gradient, this array can set the stop points + * (numbers between 0 and 1) for the color, overriding the default behaviour of evenly spacing them. + */ + get: function () { + return this._fillGradientStops; + }, + set: function (fillGradientStops) { + if (!areArraysEqual(this._fillGradientStops, fillGradientStops)) { + this._fillGradientStops = fillGradientStops; + this.styleID++; + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(TextStyle.prototype, "fontFamily", { + /** The font family. */ + get: function () { + return this._fontFamily; + }, + set: function (fontFamily) { + if (this.fontFamily !== fontFamily) { + this._fontFamily = fontFamily; + this.styleID++; + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(TextStyle.prototype, "fontSize", { + /** + * The font size + * (as a number it converts to px, but as a string, equivalents are '26px','20pt','160%' or '1.6em') + */ + get: function () { + return this._fontSize; + }, + set: function (fontSize) { + if (this._fontSize !== fontSize) { + this._fontSize = fontSize; + this.styleID++; + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(TextStyle.prototype, "fontStyle", { + /** + * The font style + * ('normal', 'italic' or 'oblique') + * + * @member {string} + */ + get: function () { + return this._fontStyle; + }, + set: function (fontStyle) { + if (this._fontStyle !== fontStyle) { + this._fontStyle = fontStyle; + this.styleID++; + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(TextStyle.prototype, "fontVariant", { + /** + * The font variant + * ('normal' or 'small-caps') + * + * @member {string} + */ + get: function () { + return this._fontVariant; + }, + set: function (fontVariant) { + if (this._fontVariant !== fontVariant) { + this._fontVariant = fontVariant; + this.styleID++; + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(TextStyle.prototype, "fontWeight", { + /** + * The font weight + * ('normal', 'bold', 'bolder', 'lighter' and '100', '200', '300', '400', '500', '600', '700', 800' or '900') + * + * @member {string} + */ + get: function () { + return this._fontWeight; + }, + set: function (fontWeight) { + if (this._fontWeight !== fontWeight) { + this._fontWeight = fontWeight; + this.styleID++; + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(TextStyle.prototype, "letterSpacing", { + /** The amount of spacing between letters, default is 0. */ + get: function () { + return this._letterSpacing; + }, + set: function (letterSpacing) { + if (this._letterSpacing !== letterSpacing) { + this._letterSpacing = letterSpacing; + this.styleID++; + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(TextStyle.prototype, "lineHeight", { + /** The line height, a number that represents the vertical space that a letter uses. */ + get: function () { + return this._lineHeight; + }, + set: function (lineHeight) { + if (this._lineHeight !== lineHeight) { + this._lineHeight = lineHeight; + this.styleID++; + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(TextStyle.prototype, "leading", { + /** The space between lines. */ + get: function () { + return this._leading; + }, + set: function (leading) { + if (this._leading !== leading) { + this._leading = leading; + this.styleID++; + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(TextStyle.prototype, "lineJoin", { + /** + * The lineJoin property sets the type of corner created, it can resolve spiked text issues. + * Default is 'miter' (creates a sharp corner). + * + * @member {string} + */ + get: function () { + return this._lineJoin; + }, + set: function (lineJoin) { + if (this._lineJoin !== lineJoin) { + this._lineJoin = lineJoin; + this.styleID++; + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(TextStyle.prototype, "miterLimit", { + /** + * The miter limit to use when using the 'miter' lineJoin mode. + * + * This can reduce or increase the spikiness of rendered text. + */ + get: function () { + return this._miterLimit; + }, + set: function (miterLimit) { + if (this._miterLimit !== miterLimit) { + this._miterLimit = miterLimit; + this.styleID++; + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(TextStyle.prototype, "padding", { + /** + * Occasionally some fonts are cropped. Adding some padding will prevent this from happening + * by adding padding to all sides of the text. + */ + get: function () { + return this._padding; + }, + set: function (padding) { + if (this._padding !== padding) { + this._padding = padding; + this.styleID++; + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(TextStyle.prototype, "stroke", { + /** + * A canvas fillstyle that will be used on the text stroke + * e.g 'blue', '#FCFF00' + */ + get: function () { + return this._stroke; + }, + set: function (stroke) { + // TODO: Can't have different types for getter and setter. The getter shouldn't have the number type as + // the setter converts to string. See this thread for more details: + // https://github.com/microsoft/TypeScript/issues/2521 + var outputColor = getColor(stroke); + if (this._stroke !== outputColor) { + this._stroke = outputColor; + this.styleID++; + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(TextStyle.prototype, "strokeThickness", { + /** + * A number that represents the thickness of the stroke. + * + * @default 0 + */ + get: function () { + return this._strokeThickness; + }, + set: function (strokeThickness) { + if (this._strokeThickness !== strokeThickness) { + this._strokeThickness = strokeThickness; + this.styleID++; + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(TextStyle.prototype, "textBaseline", { + /** + * The baseline of the text that is rendered. + * + * @member {string} + */ + get: function () { + return this._textBaseline; + }, + set: function (textBaseline) { + if (this._textBaseline !== textBaseline) { + this._textBaseline = textBaseline; + this.styleID++; + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(TextStyle.prototype, "trim", { + /** Trim transparent borders. */ + get: function () { + return this._trim; + }, + set: function (trim) { + if (this._trim !== trim) { + this._trim = trim; + this.styleID++; + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(TextStyle.prototype, "whiteSpace", { + /** + * How newlines and spaces should be handled. + * Default is 'pre' (preserve, preserve). + * + * value | New lines | Spaces + * --- | --- | --- + * 'normal' | Collapse | Collapse + * 'pre' | Preserve | Preserve + * 'pre-line' | Preserve | Collapse + * + * @member {string} + */ + get: function () { + return this._whiteSpace; + }, + set: function (whiteSpace) { + if (this._whiteSpace !== whiteSpace) { + this._whiteSpace = whiteSpace; + this.styleID++; + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(TextStyle.prototype, "wordWrap", { + /** Indicates if word wrap should be used. */ + get: function () { + return this._wordWrap; + }, + set: function (wordWrap) { + if (this._wordWrap !== wordWrap) { + this._wordWrap = wordWrap; + this.styleID++; + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(TextStyle.prototype, "wordWrapWidth", { + /** The width at which text will wrap, it needs wordWrap to be set to true. */ + get: function () { + return this._wordWrapWidth; + }, + set: function (wordWrapWidth) { + if (this._wordWrapWidth !== wordWrapWidth) { + this._wordWrapWidth = wordWrapWidth; + this.styleID++; + } + }, + enumerable: false, + configurable: true + }); + /** + * Generates a font style string to use for `TextMetrics.measureFont()`. + * + * @return Font style string, for passing to `TextMetrics.measureFont()` + */ + TextStyle.prototype.toFontString = function () { + // build canvas api font setting from individual components. Convert a numeric this.fontSize to px + var fontSizeString = (typeof this.fontSize === 'number') ? this.fontSize + "px" : this.fontSize; + // Clean-up fontFamily property by quoting each font name + // this will support font names with spaces + var fontFamilies = this.fontFamily; + if (!Array.isArray(this.fontFamily)) { + fontFamilies = this.fontFamily.split(','); + } + for (var i = fontFamilies.length - 1; i >= 0; i--) { + // Trim any extra white-space + var fontFamily = fontFamilies[i].trim(); + // Check if font already contains strings + if (!(/([\"\'])[^\'\"]+\1/).test(fontFamily) && genericFontFamilies.indexOf(fontFamily) < 0) { + fontFamily = "\"" + fontFamily + "\""; + } + fontFamilies[i] = fontFamily; + } + return this.fontStyle + " " + this.fontVariant + " " + this.fontWeight + " " + fontSizeString + " " + fontFamilies.join(','); + }; + return TextStyle; + }()); + /** + * Utility function to convert hexadecimal colors to strings, and simply return the color if it's a string. + * @private + * @param color + * @return The color as a string. + */ + function getSingleColor(color) { + if (typeof color === 'number') { + return hex2string(color); + } + else if (typeof color === 'string') { + if (color.indexOf('0x') === 0) { + color = color.replace('0x', '#'); + } + } + return color; + } + function getColor(color) { + if (!Array.isArray(color)) { + return getSingleColor(color); + } + else { + for (var i = 0; i < color.length; ++i) { + color[i] = getSingleColor(color[i]); + } + return color; + } + } + /** + * Utility function to convert hexadecimal colors to strings, and simply return the color if it's a string. + * This version can also convert array of colors + * @private + * @param array1 - First array to compare + * @param array2 - Second array to compare + * @return Do the arrays contain the same values in the same order + */ + function areArraysEqual(array1, array2) { + if (!Array.isArray(array1) || !Array.isArray(array2)) { + return false; + } + if (array1.length !== array2.length) { + return false; + } + for (var i = 0; i < array1.length; ++i) { + if (array1[i] !== array2[i]) { + return false; + } + } + return true; + } + /** + * Utility function to ensure that object properties are copied by value, and not by reference + * @private + * @param target - Target object to copy properties into + * @param source - Source object for the properties to copy + * @param propertyObj - Object containing properties names we want to loop over + */ + function deepCopyProperties(target, source, propertyObj) { + for (var prop in propertyObj) { + if (Array.isArray(source[prop])) { + target[prop] = source[prop].slice(); + } + else { + target[prop] = source[prop]; + } + } + } + + /** + * The TextMetrics object represents the measurement of a block of text with a specified style. + * + * ```js + * let style = new PIXI.TextStyle({fontFamily : 'Arial', fontSize: 24, fill : 0xff1010, align : 'center'}) + * let textMetrics = PIXI.TextMetrics.measureText('Your text', style) + * ``` + * @memberof PIXI + */ + var TextMetrics = /** @class */ (function () { + /** + * @param text - the text that was measured + * @param style - the style that was measured + * @param width - the measured width of the text + * @param height - the measured height of the text + * @param lines - an array of the lines of text broken by new lines and wrapping if specified in style + * @param lineWidths - an array of the line widths for each line matched to `lines` + * @param lineHeight - the measured line height for this style + * @param maxLineWidth - the maximum line width for all measured lines + * @param {PIXI.IFontMetrics} fontProperties - the font properties object from TextMetrics.measureFont + */ + function TextMetrics(text, style, width, height, lines, lineWidths, lineHeight, maxLineWidth, fontProperties) { + this.text = text; + this.style = style; + this.width = width; + this.height = height; + this.lines = lines; + this.lineWidths = lineWidths; + this.lineHeight = lineHeight; + this.maxLineWidth = maxLineWidth; + this.fontProperties = fontProperties; + } + /** + * Measures the supplied string of text and returns a Rectangle. + * @param text - The text to measure. + * @param style - The text style to use for measuring + * @param wordWrap - Override for if word-wrap should be applied to the text. + * @param canvas - optional specification of the canvas to use for measuring. + * @returns Measured width and height of the text. + */ + TextMetrics.measureText = function (text, style, wordWrap, canvas) { + if (canvas === void 0) { canvas = TextMetrics._canvas; } + wordWrap = (wordWrap === undefined || wordWrap === null) ? style.wordWrap : wordWrap; + var font = style.toFontString(); + var fontProperties = TextMetrics.measureFont(font); + // fallback in case UA disallow canvas data extraction + // (toDataURI, getImageData functions) + if (fontProperties.fontSize === 0) { + fontProperties.fontSize = style.fontSize; + fontProperties.ascent = style.fontSize; + } + var context = canvas.getContext('2d'); + context.font = font; + var outputText = wordWrap ? TextMetrics.wordWrap(text, style, canvas) : text; + var lines = outputText.split(/(?:\r\n|\r|\n)/); + var lineWidths = new Array(lines.length); + var maxLineWidth = 0; + for (var i = 0; i < lines.length; i++) { + var lineWidth = context.measureText(lines[i]).width + ((lines[i].length - 1) * style.letterSpacing); + lineWidths[i] = lineWidth; + maxLineWidth = Math.max(maxLineWidth, lineWidth); + } + var width = maxLineWidth + style.strokeThickness; + if (style.dropShadow) { + width += style.dropShadowDistance; + } + var lineHeight = style.lineHeight || fontProperties.fontSize + style.strokeThickness; + var height = Math.max(lineHeight, fontProperties.fontSize + style.strokeThickness) + + ((lines.length - 1) * (lineHeight + style.leading)); + if (style.dropShadow) { + height += style.dropShadowDistance; + } + return new TextMetrics(text, style, width, height, lines, lineWidths, lineHeight + style.leading, maxLineWidth, fontProperties); + }; + /** + * Applies newlines to a string to have it optimally fit into the horizontal + * bounds set by the Text object's wordWrapWidth property. + * @param text - String to apply word wrapping to + * @param style - the style to use when wrapping + * @param canvas - optional specification of the canvas to use for measuring. + * @returns New string with new lines applied where required + */ + TextMetrics.wordWrap = function (text, style, canvas) { + if (canvas === void 0) { canvas = TextMetrics._canvas; } + var context = canvas.getContext('2d'); + var width = 0; + var line = ''; + var lines = ''; + var cache = Object.create(null); + var letterSpacing = style.letterSpacing, whiteSpace = style.whiteSpace; + // How to handle whitespaces + var collapseSpaces = TextMetrics.collapseSpaces(whiteSpace); + var collapseNewlines = TextMetrics.collapseNewlines(whiteSpace); + // whether or not spaces may be added to the beginning of lines + var canPrependSpaces = !collapseSpaces; + // There is letterSpacing after every char except the last one + // t_h_i_s_' '_i_s_' '_a_n_' '_e_x_a_m_p_l_e_' '_! + // so for convenience the above needs to be compared to width + 1 extra letterSpace + // t_h_i_s_' '_i_s_' '_a_n_' '_e_x_a_m_p_l_e_' '_!_ + // ________________________________________________ + // And then the final space is simply no appended to each line + var wordWrapWidth = style.wordWrapWidth + letterSpacing; + // break text into words, spaces and newline chars + var tokens = TextMetrics.tokenize(text); + for (var i = 0; i < tokens.length; i++) { + // get the word, space or newlineChar + var token = tokens[i]; + // if word is a new line + if (TextMetrics.isNewline(token)) { + // keep the new line + if (!collapseNewlines) { + lines += TextMetrics.addLine(line); + canPrependSpaces = !collapseSpaces; + line = ''; + width = 0; + continue; + } + // if we should collapse new lines + // we simply convert it into a space + token = ' '; + } + // if we should collapse repeated whitespaces + if (collapseSpaces) { + // check both this and the last tokens for spaces + var currIsBreakingSpace = TextMetrics.isBreakingSpace(token); + var lastIsBreakingSpace = TextMetrics.isBreakingSpace(line[line.length - 1]); + if (currIsBreakingSpace && lastIsBreakingSpace) { + continue; + } + } + // get word width from cache if possible + var tokenWidth = TextMetrics.getFromCache(token, letterSpacing, cache, context); + // word is longer than desired bounds + if (tokenWidth > wordWrapWidth) { + // if we are not already at the beginning of a line + if (line !== '') { + // start newlines for overflow words + lines += TextMetrics.addLine(line); + line = ''; + width = 0; + } + // break large word over multiple lines + if (TextMetrics.canBreakWords(token, style.breakWords)) { + // break word into characters + var characters = TextMetrics.wordWrapSplit(token); + // loop the characters + for (var j = 0; j < characters.length; j++) { + var char = characters[j]; + var k = 1; + // we are not at the end of the token + while (characters[j + k]) { + var nextChar = characters[j + k]; + var lastChar = char[char.length - 1]; + // should not split chars + if (!TextMetrics.canBreakChars(lastChar, nextChar, token, j, style.breakWords)) { + // combine chars & move forward one + char += nextChar; + } + else { + break; + } + k++; + } + j += char.length - 1; + var characterWidth = TextMetrics.getFromCache(char, letterSpacing, cache, context); + if (characterWidth + width > wordWrapWidth) { + lines += TextMetrics.addLine(line); + canPrependSpaces = false; + line = ''; + width = 0; + } + line += char; + width += characterWidth; + } + } + // run word out of the bounds + else { + // if there are words in this line already + // finish that line and start a new one + if (line.length > 0) { + lines += TextMetrics.addLine(line); + line = ''; + width = 0; + } + var isLastToken = i === tokens.length - 1; + // give it its own line if it's not the end + lines += TextMetrics.addLine(token, !isLastToken); + canPrependSpaces = false; + line = ''; + width = 0; + } + } + // word could fit + else { + // word won't fit because of existing words + // start a new line + if (tokenWidth + width > wordWrapWidth) { + // if its a space we don't want it + canPrependSpaces = false; + // add a new line + lines += TextMetrics.addLine(line); + // start a new line + line = ''; + width = 0; + } + // don't add spaces to the beginning of lines + if (line.length > 0 || !TextMetrics.isBreakingSpace(token) || canPrependSpaces) { + // add the word to the current line + line += token; + // update width counter + width += tokenWidth; + } + } + } + lines += TextMetrics.addLine(line, false); + return lines; + }; + /** + * Convienience function for logging each line added during the wordWrap method. + * @param line - The line of text to add + * @param newLine - Add new line character to end + * @returns A formatted line + */ + TextMetrics.addLine = function (line, newLine) { + if (newLine === void 0) { newLine = true; } + line = TextMetrics.trimRight(line); + line = (newLine) ? line + "\n" : line; + return line; + }; + /** + * Gets & sets the widths of calculated characters in a cache object + * @param key - The key + * @param letterSpacing - The letter spacing + * @param cache - The cache + * @param context - The canvas context + * @returns The from cache. + */ + TextMetrics.getFromCache = function (key, letterSpacing, cache, context) { + var width = cache[key]; + if (typeof width !== 'number') { + var spacing = ((key.length) * letterSpacing); + width = context.measureText(key).width + spacing; + cache[key] = width; + } + return width; + }; + /** + * Determines whether we should collapse breaking spaces. + * @param whiteSpace - The TextStyle property whiteSpace + * @returns Should collapse + */ + TextMetrics.collapseSpaces = function (whiteSpace) { + return (whiteSpace === 'normal' || whiteSpace === 'pre-line'); + }; + /** + * Determines whether we should collapse newLine chars. + * @param whiteSpace - The white space + * @returns should collapse + */ + TextMetrics.collapseNewlines = function (whiteSpace) { + return (whiteSpace === 'normal'); + }; + /** + * Trims breaking whitespaces from string. + * @param text - The text + * @returns Trimmed string + */ + TextMetrics.trimRight = function (text) { + if (typeof text !== 'string') { + return ''; + } + for (var i = text.length - 1; i >= 0; i--) { + var char = text[i]; + if (!TextMetrics.isBreakingSpace(char)) { + break; + } + text = text.slice(0, -1); + } + return text; + }; + /** + * Determines if char is a newline. + * @param char - The character + * @returns True if newline, False otherwise. + */ + TextMetrics.isNewline = function (char) { + if (typeof char !== 'string') { + return false; + } + return (TextMetrics._newlines.indexOf(char.charCodeAt(0)) >= 0); + }; + /** + * Determines if char is a breaking whitespace. + * + * It allows one to determine whether char should be a breaking whitespace + * For example certain characters in CJK langs or numbers. + * It must return a boolean. + * @param char - The character + * @param [_nextChar] - The next character + * @returns True if whitespace, False otherwise. + */ + TextMetrics.isBreakingSpace = function (char, _nextChar) { + if (typeof char !== 'string') { + return false; + } + return (TextMetrics._breakingSpaces.indexOf(char.charCodeAt(0)) >= 0); + }; + /** + * Splits a string into words, breaking-spaces and newLine characters + * @param text - The text + * @returns A tokenized array + */ + TextMetrics.tokenize = function (text) { + var tokens = []; + var token = ''; + if (typeof text !== 'string') { + return tokens; + } + for (var i = 0; i < text.length; i++) { + var char = text[i]; + var nextChar = text[i + 1]; + if (TextMetrics.isBreakingSpace(char, nextChar) || TextMetrics.isNewline(char)) { + if (token !== '') { + tokens.push(token); + token = ''; + } + tokens.push(char); + continue; + } + token += char; + } + if (token !== '') { + tokens.push(token); + } + return tokens; + }; + /** + * Overridable helper method used internally by TextMetrics, exposed to allow customizing the class's behavior. + * + * It allows one to customise which words should break + * Examples are if the token is CJK or numbers. + * It must return a boolean. + * @param _token - The token + * @param breakWords - The style attr break words + * @returns Whether to break word or not + */ + TextMetrics.canBreakWords = function (_token, breakWords) { + return breakWords; + }; + /** + * Overridable helper method used internally by TextMetrics, exposed to allow customizing the class's behavior. + * + * It allows one to determine whether a pair of characters + * should be broken by newlines + * For example certain characters in CJK langs or numbers. + * It must return a boolean. + * @param _char - The character + * @param _nextChar - The next character + * @param _token - The token/word the characters are from + * @param _index - The index in the token of the char + * @param _breakWords - The style attr break words + * @returns whether to break word or not + */ + TextMetrics.canBreakChars = function (_char, _nextChar, _token, _index, _breakWords) { + return true; + }; + /** + * Overridable helper method used internally by TextMetrics, exposed to allow customizing the class's behavior. + * + * It is called when a token (usually a word) has to be split into separate pieces + * in order to determine the point to break a word. + * It must return an array of characters. + * @example + * // Correctly splits emojis, eg "🤪🤪" will result in two element array, each with one emoji. + * TextMetrics.wordWrapSplit = (token) => [...token]; + * @param token - The token to split + * @returns The characters of the token + */ + TextMetrics.wordWrapSplit = function (token) { + return token.split(''); + }; + /** + * Calculates the ascent, descent and fontSize of a given font-style + * @param font - String representing the style of the font + * @returns Font properties object + */ + TextMetrics.measureFont = function (font) { + // as this method is used for preparing assets, don't recalculate things if we don't need to + if (TextMetrics._fonts[font]) { + return TextMetrics._fonts[font]; + } + var properties = { + ascent: 0, + descent: 0, + fontSize: 0, + }; + var canvas = TextMetrics._canvas; + var context = TextMetrics._context; + context.font = font; + var metricsString = TextMetrics.METRICS_STRING + TextMetrics.BASELINE_SYMBOL; + var width = Math.ceil(context.measureText(metricsString).width); + var baseline = Math.ceil(context.measureText(TextMetrics.BASELINE_SYMBOL).width); + var height = Math.ceil(TextMetrics.HEIGHT_MULTIPLIER * baseline); + baseline = baseline * TextMetrics.BASELINE_MULTIPLIER | 0; + canvas.width = width; + canvas.height = height; + context.fillStyle = '#f00'; + context.fillRect(0, 0, width, height); + context.font = font; + context.textBaseline = 'alphabetic'; + context.fillStyle = '#000'; + context.fillText(metricsString, 0, baseline); + var imagedata = context.getImageData(0, 0, width, height).data; + var pixels = imagedata.length; + var line = width * 4; + var i = 0; + var idx = 0; + var stop = false; + // ascent. scan from top to bottom until we find a non red pixel + for (i = 0; i < baseline; ++i) { + for (var j = 0; j < line; j += 4) { + if (imagedata[idx + j] !== 255) { + stop = true; + break; + } + } + if (!stop) { + idx += line; + } + else { + break; + } + } + properties.ascent = baseline - i; + idx = pixels - line; + stop = false; + // descent. scan from bottom to top until we find a non red pixel + for (i = height; i > baseline; --i) { + for (var j = 0; j < line; j += 4) { + if (imagedata[idx + j] !== 255) { + stop = true; + break; + } + } + if (!stop) { + idx -= line; + } + else { + break; + } + } + properties.descent = i - baseline; + properties.fontSize = properties.ascent + properties.descent; + TextMetrics._fonts[font] = properties; + return properties; + }; + /** + * Clear font metrics in metrics cache. + * @param {string} [font] - font name. If font name not set then clear cache for all fonts. + */ + TextMetrics.clearMetrics = function (font) { + if (font === void 0) { font = ''; } + if (font) { + delete TextMetrics._fonts[font]; + } + else { + TextMetrics._fonts = {}; + } + }; + Object.defineProperty(TextMetrics, "_canvas", { + /** + * Cached canvas element for measuring text + * TODO: this should be private, but isn't because of backward compat, will fix later. + * @ignore + */ + get: function () { + if (!TextMetrics.__canvas) { + var canvas = void 0; + try { + // OffscreenCanvas2D measureText can be up to 40% faster. + var c = new OffscreenCanvas(0, 0); + var context = c.getContext('2d'); + if (context && context.measureText) { + TextMetrics.__canvas = c; + return c; + } + canvas = settings$1.ADAPTER.createCanvas(); + } + catch (ex) { + canvas = settings$1.ADAPTER.createCanvas(); + } + canvas.width = canvas.height = 10; + TextMetrics.__canvas = canvas; + } + return TextMetrics.__canvas; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(TextMetrics, "_context", { + /** + * TODO: this should be private, but isn't because of backward compat, will fix later. + * @ignore + */ + get: function () { + if (!TextMetrics.__context) { + TextMetrics.__context = TextMetrics._canvas.getContext('2d'); + } + return TextMetrics.__context; + }, + enumerable: false, + configurable: true + }); + return TextMetrics; + }()); + /** + * Internal return object for {@link PIXI.TextMetrics.measureFont `TextMetrics.measureFont`}. + * @typedef {object} FontMetrics + * @property {number} ascent - The ascent distance + * @property {number} descent - The descent distance + * @property {number} fontSize - Font size from ascent to descent + * @memberof PIXI.TextMetrics + * @private + */ + /** + * Cache of {@see PIXI.TextMetrics.FontMetrics} objects. + * @memberof PIXI.TextMetrics + * @type {object} + * @private + */ + TextMetrics._fonts = {}; + /** + * String used for calculate font metrics. + * These characters are all tall to help calculate the height required for text. + * @static + * @memberof PIXI.TextMetrics + * @name METRICS_STRING + * @type {string} + * @default |ÉqÅ + */ + TextMetrics.METRICS_STRING = '|ÉqÅ'; + /** + * Baseline symbol for calculate font metrics. + * @static + * @memberof PIXI.TextMetrics + * @name BASELINE_SYMBOL + * @type {string} + * @default M + */ + TextMetrics.BASELINE_SYMBOL = 'M'; + /** + * Baseline multiplier for calculate font metrics. + * @static + * @memberof PIXI.TextMetrics + * @name BASELINE_MULTIPLIER + * @type {number} + * @default 1.4 + */ + TextMetrics.BASELINE_MULTIPLIER = 1.4; + /** + * Height multiplier for setting height of canvas to calculate font metrics. + * @static + * @memberof PIXI.TextMetrics + * @name HEIGHT_MULTIPLIER + * @type {number} + * @default 2.00 + */ + TextMetrics.HEIGHT_MULTIPLIER = 2.0; + /** + * Cache of new line chars. + * @memberof PIXI.TextMetrics + * @type {number[]} + * @private + */ + TextMetrics._newlines = [ + 0x000A, + 0x000D ]; + /** + * Cache of breaking spaces. + * @memberof PIXI.TextMetrics + * @type {number[]} + * @private + */ + TextMetrics._breakingSpaces = [ + 0x0009, + 0x0020, + 0x2000, + 0x2001, + 0x2002, + 0x2003, + 0x2004, + 0x2005, + 0x2006, + 0x2008, + 0x2009, + 0x200A, + 0x205F, + 0x3000 ]; + /** + * A number, or a string containing a number. + * @memberof PIXI + * @typedef {object} IFontMetrics + * @property {number} ascent - Font ascent + * @property {number} descent - Font descent + * @property {number} fontSize - Font size + */ + + var defaultDestroyOptions = { + texture: true, + children: false, + baseTexture: true, + }; + /** + * A Text Object will create a line or multiple lines of text. + * + * The text is created using the [Canvas API](https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API). + * + * The primary advantage of this class over BitmapText is that you have great control over the style of the text, + * which you can change at runtime. + * + * The primary disadvantages is that each piece of text has it's own texture, which can use more memory. + * When text changes, this texture has to be re-generated and re-uploaded to the GPU, taking up time. + * + * To split a line you can use '\n' in your text string, or, on the `style` object, + * change its `wordWrap` property to true and and give the `wordWrapWidth` property a value. + * + * A Text can be created directly from a string and a style object, + * which can be generated [here](https://pixijs.io/pixi-text-style). + * + * ```js + * let text = new PIXI.Text('This is a PixiJS text',{fontFamily : 'Arial', fontSize: 24, fill : 0xff1010, align : 'center'}); + * ``` + * @memberof PIXI + */ + var Text = /** @class */ (function (_super) { + __extends$c(Text, _super); + /** + * @param text - The string that you would like the text to display + * @param {object|PIXI.TextStyle} [style] - The style parameters + * @param canvas - The canvas element for drawing text + */ + function Text(text, style, canvas) { + var _this = this; + var ownCanvas = false; + if (!canvas) { + canvas = settings$1.ADAPTER.createCanvas(); + ownCanvas = true; + } + canvas.width = 3; + canvas.height = 3; + var texture = Texture.from(canvas); + texture.orig = new Rectangle(); + texture.trim = new Rectangle(); + _this = _super.call(this, texture) || this; + _this._ownCanvas = ownCanvas; + _this.canvas = canvas; + _this.context = canvas.getContext('2d'); + _this._resolution = settings$1.RESOLUTION; + _this._autoResolution = true; + _this._text = null; + _this._style = null; + _this._styleListener = null; + _this._font = ''; + _this.text = text; + _this.style = style; + _this.localStyleID = -1; + return _this; + } + /** + * Renders text to its canvas, and updates its texture. + * + * By default this is used internally to ensure the texture is correct before rendering, + * but it can be used called externally, for example from this class to 'pre-generate' the texture from a piece of text, + * and then shared across multiple Sprites. + * @param respectDirty - Whether to abort updating the text if the Text isn't dirty and the function is called. + */ + Text.prototype.updateText = function (respectDirty) { + var style = this._style; + // check if style has changed.. + if (this.localStyleID !== style.styleID) { + this.dirty = true; + this.localStyleID = style.styleID; + } + if (!this.dirty && respectDirty) { + return; + } + this._font = this._style.toFontString(); + var context = this.context; + var measured = TextMetrics.measureText(this._text || ' ', this._style, this._style.wordWrap, this.canvas); + var width = measured.width; + var height = measured.height; + var lines = measured.lines; + var lineHeight = measured.lineHeight; + var lineWidths = measured.lineWidths; + var maxLineWidth = measured.maxLineWidth; + var fontProperties = measured.fontProperties; + this.canvas.width = Math.ceil(Math.ceil((Math.max(1, width) + (style.padding * 2))) * this._resolution); + this.canvas.height = Math.ceil(Math.ceil((Math.max(1, height) + (style.padding * 2))) * this._resolution); + context.scale(this._resolution, this._resolution); + context.clearRect(0, 0, this.canvas.width, this.canvas.height); + context.font = this._font; + context.lineWidth = style.strokeThickness; + context.textBaseline = style.textBaseline; + context.lineJoin = style.lineJoin; + context.miterLimit = style.miterLimit; + var linePositionX; + var linePositionY; + // require 2 passes if a shadow; the first to draw the drop shadow, the second to draw the text + var passesCount = style.dropShadow ? 2 : 1; + // For v4, we drew text at the colours of the drop shadow underneath the normal text. This gave the correct zIndex, + // but features such as alpha and shadowblur did not look right at all, since we were using actual text as a shadow. + // + // For v5.0.0, we moved over to just use the canvas API for drop shadows, which made them look much nicer and more + // visually please, but now because the stroke is drawn and then the fill, drop shadows would appear on both the fill + // and the stroke; and fill drop shadows would appear over the top of the stroke. + // + // For v5.1.1, the new route is to revert to v4 style of drawing text first to get the drop shadows underneath normal + // text, but instead drawing text in the correct location, we'll draw it off screen (-paddingY), and then adjust the + // drop shadow so only that appears on screen (+paddingY). Now we'll have the correct draw order of the shadow + // beneath the text, whilst also having the proper text shadow styling. + for (var i = 0; i < passesCount; ++i) { + var isShadowPass = style.dropShadow && i === 0; + // we only want the drop shadow, so put text way off-screen + var dsOffsetText = isShadowPass ? Math.ceil(Math.max(1, height) + (style.padding * 2)) : 0; + var dsOffsetShadow = dsOffsetText * this._resolution; + if (isShadowPass) { + // On Safari, text with gradient and drop shadows together do not position correctly + // if the scale of the canvas is not 1: https://bugs.webkit.org/show_bug.cgi?id=197689 + // Therefore we'll set the styles to be a plain black whilst generating this drop shadow + context.fillStyle = 'black'; + context.strokeStyle = 'black'; + var dropShadowColor = style.dropShadowColor; + var rgb = hex2rgb(typeof dropShadowColor === 'number' ? dropShadowColor : string2hex(dropShadowColor)); + var dropShadowBlur = style.dropShadowBlur * this._resolution; + var dropShadowDistance = style.dropShadowDistance * this._resolution; + context.shadowColor = "rgba(" + rgb[0] * 255 + "," + rgb[1] * 255 + "," + rgb[2] * 255 + "," + style.dropShadowAlpha + ")"; + context.shadowBlur = dropShadowBlur; + context.shadowOffsetX = Math.cos(style.dropShadowAngle) * dropShadowDistance; + context.shadowOffsetY = (Math.sin(style.dropShadowAngle) * dropShadowDistance) + dsOffsetShadow; + } + else { + // set canvas text styles + context.fillStyle = this._generateFillStyle(style, lines, measured); + // TODO: Can't have different types for getter and setter. The getter shouldn't have the number type as + // the setter converts to string. See this thread for more details: + // https://github.com/microsoft/TypeScript/issues/2521 + context.strokeStyle = style.stroke; + context.shadowColor = 'black'; + context.shadowBlur = 0; + context.shadowOffsetX = 0; + context.shadowOffsetY = 0; + } + var linePositionYShift = (lineHeight - fontProperties.fontSize) / 2; + if (!Text.nextLineHeightBehavior || lineHeight - fontProperties.fontSize < 0) { + linePositionYShift = 0; + } + // draw lines line by line + for (var i_1 = 0; i_1 < lines.length; i_1++) { + linePositionX = style.strokeThickness / 2; + linePositionY = ((style.strokeThickness / 2) + (i_1 * lineHeight)) + fontProperties.ascent + + linePositionYShift; + if (style.align === 'right') { + linePositionX += maxLineWidth - lineWidths[i_1]; + } + else if (style.align === 'center') { + linePositionX += (maxLineWidth - lineWidths[i_1]) / 2; + } + if (style.stroke && style.strokeThickness) { + this.drawLetterSpacing(lines[i_1], linePositionX + style.padding, linePositionY + style.padding - dsOffsetText, true); + } + if (style.fill) { + this.drawLetterSpacing(lines[i_1], linePositionX + style.padding, linePositionY + style.padding - dsOffsetText); + } + } + } + this.updateTexture(); + }; + /** + * Render the text with letter-spacing. + * @param text - The text to draw + * @param x - Horizontal position to draw the text + * @param y - Vertical position to draw the text + * @param isStroke - Is this drawing for the outside stroke of the + * text? If not, it's for the inside fill + */ + Text.prototype.drawLetterSpacing = function (text, x, y, isStroke) { + if (isStroke === void 0) { isStroke = false; } + var style = this._style; + // letterSpacing of 0 means normal + var letterSpacing = style.letterSpacing; + // Checking that we can use moddern canvas2D api + // https://developer.chrome.com/origintrials/#/view_trial/3585991203293757441 + // note: this is unstable API, Chrome less 94 use a `textLetterSpacing`, newest use a letterSpacing + // eslint-disable-next-line max-len + var supportLetterSpacing = Text.experimentalLetterSpacing + && ('letterSpacing' in CanvasRenderingContext2D.prototype + || 'textLetterSpacing' in CanvasRenderingContext2D.prototype); + if (letterSpacing === 0 || supportLetterSpacing) { + if (supportLetterSpacing) { + this.context.letterSpacing = letterSpacing; + this.context.textLetterSpacing = letterSpacing; + } + if (isStroke) { + this.context.strokeText(text, x, y); + } + else { + this.context.fillText(text, x, y); + } + return; + } + var currentPosition = x; + // Using Array.from correctly splits characters whilst keeping emoji together. + // This is not supported on IE as it requires ES6, so regular text splitting occurs. + // This also doesn't account for emoji that are multiple emoji put together to make something else. + // Handling all of this would require a big library itself. + // https://medium.com/@giltayar/iterating-over-emoji-characters-the-es6-way-f06e4589516 + // https://github.com/orling/grapheme-splitter + var stringArray = Array.from ? Array.from(text) : text.split(''); + var previousWidth = this.context.measureText(text).width; + var currentWidth = 0; + for (var i = 0; i < stringArray.length; ++i) { + var currentChar = stringArray[i]; + if (isStroke) { + this.context.strokeText(currentChar, currentPosition, y); + } + else { + this.context.fillText(currentChar, currentPosition, y); + } + var textStr = ''; + for (var j = i + 1; j < stringArray.length; ++j) { + textStr += stringArray[j]; + } + currentWidth = this.context.measureText(textStr).width; + currentPosition += previousWidth - currentWidth + letterSpacing; + previousWidth = currentWidth; + } + }; + /** Updates texture size based on canvas size. */ + Text.prototype.updateTexture = function () { + var canvas = this.canvas; + if (this._style.trim) { + var trimmed = trimCanvas(canvas); + if (trimmed.data) { + canvas.width = trimmed.width; + canvas.height = trimmed.height; + this.context.putImageData(trimmed.data, 0, 0); + } + } + var texture = this._texture; + var style = this._style; + var padding = style.trim ? 0 : style.padding; + var baseTexture = texture.baseTexture; + texture.trim.width = texture._frame.width = canvas.width / this._resolution; + texture.trim.height = texture._frame.height = canvas.height / this._resolution; + texture.trim.x = -padding; + texture.trim.y = -padding; + texture.orig.width = texture._frame.width - (padding * 2); + texture.orig.height = texture._frame.height - (padding * 2); + // call sprite onTextureUpdate to update scale if _width or _height were set + this._onTextureUpdate(); + baseTexture.setRealSize(canvas.width, canvas.height, this._resolution); + texture.updateUvs(); + this.dirty = false; + }; + /** + * Renders the object using the WebGL renderer + * @param renderer - The renderer + */ + Text.prototype._render = function (renderer) { + if (this._autoResolution && this._resolution !== renderer.resolution) { + this._resolution = renderer.resolution; + this.dirty = true; + } + this.updateText(true); + _super.prototype._render.call(this, renderer); + }; + /** Updates the transform on all children of this container for rendering. */ + Text.prototype.updateTransform = function () { + this.updateText(true); + _super.prototype.updateTransform.call(this); + }; + Text.prototype.getBounds = function (skipUpdate, rect) { + this.updateText(true); + if (this._textureID === -1) { + // texture was updated: recalculate transforms + skipUpdate = false; + } + return _super.prototype.getBounds.call(this, skipUpdate, rect); + }; + /** + * Gets the local bounds of the text object. + * @param rect - The output rectangle. + * @returns The bounds. + */ + Text.prototype.getLocalBounds = function (rect) { + this.updateText(true); + return _super.prototype.getLocalBounds.call(this, rect); + }; + /** Calculates the bounds of the Text as a rectangle. The bounds calculation takes the worldTransform into account. */ + Text.prototype._calculateBounds = function () { + this.calculateVertices(); + // if we have already done this on THIS frame. + this._bounds.addQuad(this.vertexData); + }; + /** + * Generates the fill style. Can automatically generate a gradient based on the fill style being an array + * @param style - The style. + * @param lines - The lines of text. + * @param metrics + * @returns The fill style + */ + Text.prototype._generateFillStyle = function (style, lines, metrics) { + // TODO: Can't have different types for getter and setter. The getter shouldn't have the number type as + // the setter converts to string. See this thread for more details: + // https://github.com/microsoft/TypeScript/issues/2521 + var fillStyle = style.fill; + if (!Array.isArray(fillStyle)) { + return fillStyle; + } + else if (fillStyle.length === 1) { + return fillStyle[0]; + } + // the gradient will be evenly spaced out according to how large the array is. + // ['#FF0000', '#00FF00', '#0000FF'] would created stops at 0.25, 0.5 and 0.75 + var gradient; + // a dropshadow will enlarge the canvas and result in the gradient being + // generated with the incorrect dimensions + var dropShadowCorrection = (style.dropShadow) ? style.dropShadowDistance : 0; + // should also take padding into account, padding can offset the gradient + var padding = style.padding || 0; + var width = (this.canvas.width / this._resolution) - dropShadowCorrection - (padding * 2); + var height = (this.canvas.height / this._resolution) - dropShadowCorrection - (padding * 2); + // make a copy of the style settings, so we can manipulate them later + var fill = fillStyle.slice(); + var fillGradientStops = style.fillGradientStops.slice(); + // wanting to evenly distribute the fills. So an array of 4 colours should give fills of 0.25, 0.5 and 0.75 + if (!fillGradientStops.length) { + var lengthPlus1 = fill.length + 1; + for (var i = 1; i < lengthPlus1; ++i) { + fillGradientStops.push(i / lengthPlus1); + } + } + // stop the bleeding of the last gradient on the line above to the top gradient of the this line + // by hard defining the first gradient colour at point 0, and last gradient colour at point 1 + fill.unshift(fillStyle[0]); + fillGradientStops.unshift(0); + fill.push(fillStyle[fillStyle.length - 1]); + fillGradientStops.push(1); + if (style.fillGradientType === exports.TEXT_GRADIENT.LINEAR_VERTICAL) { + // start the gradient at the top center of the canvas, and end at the bottom middle of the canvas + gradient = this.context.createLinearGradient(width / 2, padding, width / 2, height + padding); + // we need to repeat the gradient so that each individual line of text has the same vertical gradient effect + // ['#FF0000', '#00FF00', '#0000FF'] over 2 lines would create stops at 0.125, 0.25, 0.375, 0.625, 0.75, 0.875 + // Actual height of the text itself, not counting spacing for lineHeight/leading/dropShadow etc + var textHeight = metrics.fontProperties.fontSize + style.strokeThickness; + for (var i = 0; i < lines.length; i++) { + var lastLineBottom = (metrics.lineHeight * (i - 1)) + textHeight; + var thisLineTop = metrics.lineHeight * i; + var thisLineGradientStart = thisLineTop; + // Handle case where last & this line overlap + if (i > 0 && lastLineBottom > thisLineTop) { + thisLineGradientStart = (thisLineTop + lastLineBottom) / 2; + } + var thisLineBottom = thisLineTop + textHeight; + var nextLineTop = metrics.lineHeight * (i + 1); + var thisLineGradientEnd = thisLineBottom; + // Handle case where this & next line overlap + if (i + 1 < lines.length && nextLineTop < thisLineBottom) { + thisLineGradientEnd = (thisLineBottom + nextLineTop) / 2; + } + // textHeight, but as a 0-1 size in global gradient stop space + var gradStopLineHeight = (thisLineGradientEnd - thisLineGradientStart) / height; + for (var j = 0; j < fill.length; j++) { + // 0-1 stop point for the current line, multiplied to global space afterwards + var lineStop = 0; + if (typeof fillGradientStops[j] === 'number') { + lineStop = fillGradientStops[j]; + } + else { + lineStop = j / fill.length; + } + var globalStop = Math.min(1, Math.max(0, (thisLineGradientStart / height) + (lineStop * gradStopLineHeight))); + // There's potential for floating point precision issues at the seams between gradient repeats. + globalStop = Number(globalStop.toFixed(5)); + gradient.addColorStop(globalStop, fill[j]); + } + } + } + else { + // start the gradient at the center left of the canvas, and end at the center right of the canvas + gradient = this.context.createLinearGradient(padding, height / 2, width + padding, height / 2); + // can just evenly space out the gradients in this case, as multiple lines makes no difference + // to an even left to right gradient + var totalIterations = fill.length + 1; + var currentIteration = 1; + for (var i = 0; i < fill.length; i++) { + var stop = void 0; + if (typeof fillGradientStops[i] === 'number') { + stop = fillGradientStops[i]; + } + else { + stop = currentIteration / totalIterations; + } + gradient.addColorStop(stop, fill[i]); + currentIteration++; + } + } + return gradient; + }; + /** + * Destroys this text object. + * + * Note* Unlike a Sprite, a Text object will automatically destroy its baseTexture and texture as + * the majority of the time the texture will not be shared with any other Sprites. + * @param options - Options parameter. A boolean will act as if all options + * have been set to that value + * @param {boolean} [options.children=false] - if set to true, all the children will have their + * destroy method called as well. 'options' will be passed on to those calls. + * @param {boolean} [options.texture=true] - Should it destroy the current texture of the sprite as well + * @param {boolean} [options.baseTexture=true] - Should it destroy the base texture of the sprite as well + */ + Text.prototype.destroy = function (options) { + if (typeof options === 'boolean') { + options = { children: options }; + } + options = Object.assign({}, defaultDestroyOptions, options); + _super.prototype.destroy.call(this, options); + // set canvas width and height to 0 to workaround memory leak in Safari < 13 + // https://stackoverflow.com/questions/52532614/total-canvas-memory-use-exceeds-the-maximum-limit-safari-12 + if (this._ownCanvas) { + this.canvas.height = this.canvas.width = 0; + } + // make sure to reset the context and canvas.. dont want this hanging around in memory! + this.context = null; + this.canvas = null; + this._style = null; + }; + Object.defineProperty(Text.prototype, "width", { + /** The width of the Text, setting this will actually modify the scale to achieve the value set. */ + get: function () { + this.updateText(true); + return Math.abs(this.scale.x) * this._texture.orig.width; + }, + set: function (value) { + this.updateText(true); + var s = sign(this.scale.x) || 1; + this.scale.x = s * value / this._texture.orig.width; + this._width = value; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(Text.prototype, "height", { + /** The height of the Text, setting this will actually modify the scale to achieve the value set. */ + get: function () { + this.updateText(true); + return Math.abs(this.scale.y) * this._texture.orig.height; + }, + set: function (value) { + this.updateText(true); + var s = sign(this.scale.y) || 1; + this.scale.y = s * value / this._texture.orig.height; + this._height = value; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(Text.prototype, "style", { + /** + * Set the style of the text. + * + * Set up an event listener to listen for changes on the style object and mark the text as dirty. + */ + get: function () { + // TODO: Can't have different types for getter and setter. The getter shouldn't have the ITextStyle + // since the setter creates the TextStyle. See this thread for more details: + // https://github.com/microsoft/TypeScript/issues/2521 + return this._style; + }, + set: function (style) { + style = style || {}; + if (style instanceof TextStyle) { + this._style = style; + } + else { + this._style = new TextStyle(style); + } + this.localStyleID = -1; + this.dirty = true; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(Text.prototype, "text", { + /** Set the copy for the text object. To split a line you can use '\n'. */ + get: function () { + return this._text; + }, + set: function (text) { + text = String(text === null || text === undefined ? '' : text); + if (this._text === text) { + return; + } + this._text = text; + this.dirty = true; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(Text.prototype, "resolution", { + /** + * The resolution / device pixel ratio of the canvas. + * + * This is set to automatically match the renderer resolution by default, but can be overridden by setting manually. + * @default 1 + */ + get: function () { + return this._resolution; + }, + set: function (value) { + this._autoResolution = false; + if (this._resolution === value) { + return; + } + this._resolution = value; + this.dirty = true; + }, + enumerable: false, + configurable: true + }); + /** + * New behavior for `lineHeight` that's meant to mimic HTML text. A value of `true` will + * make sure the first baseline is offset by the `lineHeight` value if it is greater than `fontSize`. + * A value of `false` will use the legacy behavior and not change the baseline of the first line. + * In the next major release, we'll enable this by default. + */ + Text.nextLineHeightBehavior = false; + /** + * New rendering behavior for letter-spacing which uses Chrome's new native API. This will + * lead to more accurate letter-spacing results because it does not try to manually draw + * each character. However, this Chrome API is experimental and may not serve all cases yet. + */ + Text.experimentalLetterSpacing = false; + return Text; + }(Sprite)); + + /*! + * @pixi/prepare - v6.5.3 + * Compiled Fri, 09 Sep 2022 13:55:20 UTC + * + * @pixi/prepare is licensed under the MIT License. + * http://www.opensource.org/licenses/mit-license + */ + + /** + * Default number of uploads per frame using prepare plugin. + * @static + * @memberof PIXI.settings + * @name UPLOADS_PER_FRAME + * @type {number} + * @default 4 + */ + settings$1.UPLOADS_PER_FRAME = 4; + + /*! ***************************************************************************** + Copyright (c) Microsoft Corporation. - THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED - WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, - MERCHANTABLITY OR NON-INFRINGEMENT. + Permission to use, copy, modify, and/or distribute this software for any + purpose with or without fee is hereby granted. - See the Apache Version 2.0 License for specific language governing permissions - and limitations under the License. - ***************************************************************************** */ - /* global Reflect, Promise */ + THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH + REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY + AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, + INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM + LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR + OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR + PERFORMANCE OF THIS SOFTWARE. + ***************************************************************************** */ + /* global Reflect, Promise */ - var extendStatics$e = function(d, b) { - extendStatics$e = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) { if (b.hasOwnProperty(p)) { d[p] = b[p]; } } }; - return extendStatics$e(d, b); - }; + var extendStatics$b = function(d, b) { + extendStatics$b = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) { if (b.hasOwnProperty(p)) { d[p] = b[p]; } } }; + return extendStatics$b(d, b); + }; - function __extends$e(d, b) { - extendStatics$e(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - } - - var fragment$5 = "varying vec2 vTextureCoord;\nuniform sampler2D uSampler;\nuniform float m[20];\nuniform float uAlpha;\n\nvoid main(void)\n{\n vec4 c = texture2D(uSampler, vTextureCoord);\n\n if (uAlpha == 0.0) {\n gl_FragColor = c;\n return;\n }\n\n // Un-premultiply alpha before applying the color matrix. See issue #3539.\n if (c.a > 0.0) {\n c.rgb /= c.a;\n }\n\n vec4 result;\n\n result.r = (m[0] * c.r);\n result.r += (m[1] * c.g);\n result.r += (m[2] * c.b);\n result.r += (m[3] * c.a);\n result.r += m[4];\n\n result.g = (m[5] * c.r);\n result.g += (m[6] * c.g);\n result.g += (m[7] * c.b);\n result.g += (m[8] * c.a);\n result.g += m[9];\n\n result.b = (m[10] * c.r);\n result.b += (m[11] * c.g);\n result.b += (m[12] * c.b);\n result.b += (m[13] * c.a);\n result.b += m[14];\n\n result.a = (m[15] * c.r);\n result.a += (m[16] * c.g);\n result.a += (m[17] * c.b);\n result.a += (m[18] * c.a);\n result.a += m[19];\n\n vec3 rgb = mix(c.rgb, result.rgb, uAlpha);\n\n // Premultiply alpha again.\n rgb *= result.a;\n\n gl_FragColor = vec4(rgb, result.a);\n}\n"; - - /** - * The ColorMatrixFilter class lets you apply a 5x4 matrix transformation on the RGBA - * color and alpha values of every pixel on your displayObject to produce a result - * with a new set of RGBA color and alpha values. It's pretty powerful! - * - * ```js - * let colorMatrix = new PIXI.filters.ColorMatrixFilter(); - * container.filters = [colorMatrix]; - * colorMatrix.contrast(2); - * ``` - * @author Clément Chenebault - * @class - * @extends PIXI.Filter - * @memberof PIXI.filters - */ - var ColorMatrixFilter = /** @class */ (function (_super) { - __extends$e(ColorMatrixFilter, _super); - function ColorMatrixFilter() { - var _this = this; - var uniforms = { - m: new Float32Array([1, 0, 0, 0, 0, - 0, 1, 0, 0, 0, - 0, 0, 1, 0, 0, - 0, 0, 0, 1, 0]), - uAlpha: 1, - }; - _this = _super.call(this, defaultFilter, fragment$5, uniforms) || this; - _this.alpha = 1; - return _this; - } - /** - * Transforms current matrix and set the new one - * - * @param {number[]} matrix - 5x4 matrix - * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, - * just set the current matrix with @param matrix - */ - ColorMatrixFilter.prototype._loadMatrix = function (matrix, multiply) { - if (multiply === void 0) { multiply = false; } - var newMatrix = matrix; - if (multiply) { - this._multiply(newMatrix, this.uniforms.m, matrix); - newMatrix = this._colorMatrix(newMatrix); - } - // set the new matrix - this.uniforms.m = newMatrix; - }; - /** - * Multiplies two mat5's - * - * @private - * @param {number[]} out - 5x4 matrix the receiving matrix - * @param {number[]} a - 5x4 matrix the first operand - * @param {number[]} b - 5x4 matrix the second operand - * @returns {number[]} 5x4 matrix - */ - ColorMatrixFilter.prototype._multiply = function (out, a, b) { - // Red Channel - out[0] = (a[0] * b[0]) + (a[1] * b[5]) + (a[2] * b[10]) + (a[3] * b[15]); - out[1] = (a[0] * b[1]) + (a[1] * b[6]) + (a[2] * b[11]) + (a[3] * b[16]); - out[2] = (a[0] * b[2]) + (a[1] * b[7]) + (a[2] * b[12]) + (a[3] * b[17]); - out[3] = (a[0] * b[3]) + (a[1] * b[8]) + (a[2] * b[13]) + (a[3] * b[18]); - out[4] = (a[0] * b[4]) + (a[1] * b[9]) + (a[2] * b[14]) + (a[3] * b[19]) + a[4]; - // Green Channel - out[5] = (a[5] * b[0]) + (a[6] * b[5]) + (a[7] * b[10]) + (a[8] * b[15]); - out[6] = (a[5] * b[1]) + (a[6] * b[6]) + (a[7] * b[11]) + (a[8] * b[16]); - out[7] = (a[5] * b[2]) + (a[6] * b[7]) + (a[7] * b[12]) + (a[8] * b[17]); - out[8] = (a[5] * b[3]) + (a[6] * b[8]) + (a[7] * b[13]) + (a[8] * b[18]); - out[9] = (a[5] * b[4]) + (a[6] * b[9]) + (a[7] * b[14]) + (a[8] * b[19]) + a[9]; - // Blue Channel - out[10] = (a[10] * b[0]) + (a[11] * b[5]) + (a[12] * b[10]) + (a[13] * b[15]); - out[11] = (a[10] * b[1]) + (a[11] * b[6]) + (a[12] * b[11]) + (a[13] * b[16]); - out[12] = (a[10] * b[2]) + (a[11] * b[7]) + (a[12] * b[12]) + (a[13] * b[17]); - out[13] = (a[10] * b[3]) + (a[11] * b[8]) + (a[12] * b[13]) + (a[13] * b[18]); - out[14] = (a[10] * b[4]) + (a[11] * b[9]) + (a[12] * b[14]) + (a[13] * b[19]) + a[14]; - // Alpha Channel - out[15] = (a[15] * b[0]) + (a[16] * b[5]) + (a[17] * b[10]) + (a[18] * b[15]); - out[16] = (a[15] * b[1]) + (a[16] * b[6]) + (a[17] * b[11]) + (a[18] * b[16]); - out[17] = (a[15] * b[2]) + (a[16] * b[7]) + (a[17] * b[12]) + (a[18] * b[17]); - out[18] = (a[15] * b[3]) + (a[16] * b[8]) + (a[17] * b[13]) + (a[18] * b[18]); - out[19] = (a[15] * b[4]) + (a[16] * b[9]) + (a[17] * b[14]) + (a[18] * b[19]) + a[19]; - return out; - }; - /** - * Create a Float32 Array and normalize the offset component to 0-1 - * - * @private - * @param {number[]} matrix - 5x4 matrix - * @return {number[]} 5x4 matrix with all values between 0-1 - */ - ColorMatrixFilter.prototype._colorMatrix = function (matrix) { - // Create a Float32 Array and normalize the offset component to 0-1 - var m = new Float32Array(matrix); - m[4] /= 255; - m[9] /= 255; - m[14] /= 255; - m[19] /= 255; - return m; - }; - /** - * Adjusts brightness - * - * @param {number} b - value of the brigthness (0-1, where 0 is black) - * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, - * just set the current matrix with @param matrix - */ - ColorMatrixFilter.prototype.brightness = function (b, multiply) { - var matrix = [ - b, 0, 0, 0, 0, - 0, b, 0, 0, 0, - 0, 0, b, 0, 0, - 0, 0, 0, 1, 0 ]; - this._loadMatrix(matrix, multiply); - }; - /** - * Set the matrices in grey scales - * - * @param {number} scale - value of the grey (0-1, where 0 is black) - * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, - * just set the current matrix with @param matrix - */ - ColorMatrixFilter.prototype.greyscale = function (scale, multiply) { - var matrix = [ - scale, scale, scale, 0, 0, - scale, scale, scale, 0, 0, - scale, scale, scale, 0, 0, - 0, 0, 0, 1, 0 ]; - this._loadMatrix(matrix, multiply); - }; - /** - * Set the black and white matrice. - * - * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, - * just set the current matrix with @param matrix - */ - ColorMatrixFilter.prototype.blackAndWhite = function (multiply) { - var matrix = [ - 0.3, 0.6, 0.1, 0, 0, - 0.3, 0.6, 0.1, 0, 0, - 0.3, 0.6, 0.1, 0, 0, - 0, 0, 0, 1, 0 ]; - this._loadMatrix(matrix, multiply); - }; - /** - * Set the hue property of the color - * - * @param {number} rotation - in degrees - * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, - * just set the current matrix with @param matrix - */ - ColorMatrixFilter.prototype.hue = function (rotation, multiply) { - rotation = (rotation || 0) / 180 * Math.PI; - var cosR = Math.cos(rotation); - var sinR = Math.sin(rotation); - var sqrt = Math.sqrt; - /* a good approximation for hue rotation - This matrix is far better than the versions with magic luminance constants - formerly used here, but also used in the starling framework (flash) and known from this - old part of the internet: quasimondo.com/archives/000565.php - - This new matrix is based on rgb cube rotation in space. Look here for a more descriptive - implementation as a shader not a general matrix: - https://github.com/evanw/glfx.js/blob/58841c23919bd59787effc0333a4897b43835412/src/filters/adjust/huesaturation.js - - This is the source for the code: - see http://stackoverflow.com/questions/8507885/shift-hue-of-an-rgb-color/8510751#8510751 - */ - var w = 1 / 3; - var sqrW = sqrt(w); // weight is - var a00 = cosR + ((1.0 - cosR) * w); - var a01 = (w * (1.0 - cosR)) - (sqrW * sinR); - var a02 = (w * (1.0 - cosR)) + (sqrW * sinR); - var a10 = (w * (1.0 - cosR)) + (sqrW * sinR); - var a11 = cosR + (w * (1.0 - cosR)); - var a12 = (w * (1.0 - cosR)) - (sqrW * sinR); - var a20 = (w * (1.0 - cosR)) - (sqrW * sinR); - var a21 = (w * (1.0 - cosR)) + (sqrW * sinR); - var a22 = cosR + (w * (1.0 - cosR)); - var matrix = [ - a00, a01, a02, 0, 0, - a10, a11, a12, 0, 0, - a20, a21, a22, 0, 0, - 0, 0, 0, 1, 0 ]; - this._loadMatrix(matrix, multiply); - }; - /** - * Set the contrast matrix, increase the separation between dark and bright - * Increase contrast : shadows darker and highlights brighter - * Decrease contrast : bring the shadows up and the highlights down - * - * @param {number} amount - value of the contrast (0-1) - * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, - * just set the current matrix with @param matrix - */ - ColorMatrixFilter.prototype.contrast = function (amount, multiply) { - var v = (amount || 0) + 1; - var o = -0.5 * (v - 1); - var matrix = [ - v, 0, 0, 0, o, - 0, v, 0, 0, o, - 0, 0, v, 0, o, - 0, 0, 0, 1, 0 ]; - this._loadMatrix(matrix, multiply); - }; - /** - * Set the saturation matrix, increase the separation between colors - * Increase saturation : increase contrast, brightness, and sharpness - * - * @param {number} amount - The saturation amount (0-1) - * @param {boolean} [multiply] - if true, current matrix and matrix are multiplied. If false, - * just set the current matrix with @param matrix - */ - ColorMatrixFilter.prototype.saturate = function (amount, multiply) { - if (amount === void 0) { amount = 0; } - var x = (amount * 2 / 3) + 1; - var y = ((x - 1) * -0.5); - var matrix = [ - x, y, y, 0, 0, - y, x, y, 0, 0, - y, y, x, 0, 0, - 0, 0, 0, 1, 0 ]; - this._loadMatrix(matrix, multiply); - }; - /** - * Desaturate image (remove color) - * - * Call the saturate function - * - */ - ColorMatrixFilter.prototype.desaturate = function () { - this.saturate(-1); - }; - /** - * Negative image (inverse of classic rgb matrix) - * - * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, - * just set the current matrix with @param matrix - */ - ColorMatrixFilter.prototype.negative = function (multiply) { - var matrix = [ - -1, 0, 0, 1, 0, - 0, -1, 0, 1, 0, - 0, 0, -1, 1, 0, - 0, 0, 0, 1, 0 ]; - this._loadMatrix(matrix, multiply); - }; - /** - * Sepia image - * - * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, - * just set the current matrix with @param matrix - */ - ColorMatrixFilter.prototype.sepia = function (multiply) { - var matrix = [ - 0.393, 0.7689999, 0.18899999, 0, 0, - 0.349, 0.6859999, 0.16799999, 0, 0, - 0.272, 0.5339999, 0.13099999, 0, 0, - 0, 0, 0, 1, 0 ]; - this._loadMatrix(matrix, multiply); - }; - /** - * Color motion picture process invented in 1916 (thanks Dominic Szablewski) - * - * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, - * just set the current matrix with @param matrix - */ - ColorMatrixFilter.prototype.technicolor = function (multiply) { - var matrix = [ - 1.9125277891456083, -0.8545344976951645, -0.09155508482755585, 0, 11.793603434377337, - -0.3087833385928097, 1.7658908555458428, -0.10601743074722245, 0, -70.35205161461398, - -0.231103377548616, -0.7501899197440212, 1.847597816108189, 0, 30.950940869491138, - 0, 0, 0, 1, 0 ]; - this._loadMatrix(matrix, multiply); - }; - /** - * Polaroid filter - * - * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, - * just set the current matrix with @param matrix - */ - ColorMatrixFilter.prototype.polaroid = function (multiply) { - var matrix = [ - 1.438, -0.062, -0.062, 0, 0, - -0.122, 1.378, -0.122, 0, 0, - -0.016, -0.016, 1.483, 0, 0, - 0, 0, 0, 1, 0 ]; - this._loadMatrix(matrix, multiply); - }; - /** - * Filter who transforms : Red -> Blue and Blue -> Red - * - * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, - * just set the current matrix with @param matrix - */ - ColorMatrixFilter.prototype.toBGR = function (multiply) { - var matrix = [ - 0, 0, 1, 0, 0, - 0, 1, 0, 0, 0, - 1, 0, 0, 0, 0, - 0, 0, 0, 1, 0 ]; - this._loadMatrix(matrix, multiply); - }; - /** - * Color reversal film introduced by Eastman Kodak in 1935. (thanks Dominic Szablewski) - * - * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, - * just set the current matrix with @param matrix - */ - ColorMatrixFilter.prototype.kodachrome = function (multiply) { - var matrix = [ - 1.1285582396593525, -0.3967382283601348, -0.03992559172921793, 0, 63.72958762196502, - -0.16404339962244616, 1.0835251566291304, -0.05498805115633132, 0, 24.732407896706203, - -0.16786010706155763, -0.5603416277695248, 1.6014850761964943, 0, 35.62982807460946, - 0, 0, 0, 1, 0 ]; - this._loadMatrix(matrix, multiply); - }; - /** - * Brown delicious browni filter (thanks Dominic Szablewski) - * - * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, - * just set the current matrix with @param matrix - */ - ColorMatrixFilter.prototype.browni = function (multiply) { - var matrix = [ - 0.5997023498159715, 0.34553243048391263, -0.2708298674538042, 0, 47.43192855600873, - -0.037703249837783157, 0.8609577587992641, 0.15059552388459913, 0, -36.96841498319127, - 0.24113635128153335, -0.07441037908422492, 0.44972182064877153, 0, -7.562075277591283, - 0, 0, 0, 1, 0 ]; - this._loadMatrix(matrix, multiply); - }; - /** - * Vintage filter (thanks Dominic Szablewski) - * - * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, - * just set the current matrix with @param matrix - */ - ColorMatrixFilter.prototype.vintage = function (multiply) { - var matrix = [ - 0.6279345635605994, 0.3202183420819367, -0.03965408211312453, 0, 9.651285835294123, - 0.02578397704808868, 0.6441188644374771, 0.03259127616149294, 0, 7.462829176470591, - 0.0466055556782719, -0.0851232987247891, 0.5241648018700465, 0, 5.159190588235296, - 0, 0, 0, 1, 0 ]; - this._loadMatrix(matrix, multiply); - }; - /** - * We don't know exactly what it does, kind of gradient map, but funny to play with! - * - * @param {number} desaturation - Tone values. - * @param {number} toned - Tone values. - * @param {number} lightColor - Tone values, example: `0xFFE580` - * @param {number} darkColor - Tone values, example: `0xFFE580` - * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, - * just set the current matrix with @param matrix - */ - ColorMatrixFilter.prototype.colorTone = function (desaturation, toned, lightColor, darkColor, multiply) { - desaturation = desaturation || 0.2; - toned = toned || 0.15; - lightColor = lightColor || 0xFFE580; - darkColor = darkColor || 0x338000; - var lR = ((lightColor >> 16) & 0xFF) / 255; - var lG = ((lightColor >> 8) & 0xFF) / 255; - var lB = (lightColor & 0xFF) / 255; - var dR = ((darkColor >> 16) & 0xFF) / 255; - var dG = ((darkColor >> 8) & 0xFF) / 255; - var dB = (darkColor & 0xFF) / 255; - var matrix = [ - 0.3, 0.59, 0.11, 0, 0, - lR, lG, lB, desaturation, 0, - dR, dG, dB, toned, 0, - lR - dR, lG - dG, lB - dB, 0, 0 ]; - this._loadMatrix(matrix, multiply); - }; - /** - * Night effect - * - * @param {number} intensity - The intensity of the night effect. - * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, - * just set the current matrix with @param matrix - */ - ColorMatrixFilter.prototype.night = function (intensity, multiply) { - intensity = intensity || 0.1; - var matrix = [ - intensity * (-2.0), -intensity, 0, 0, 0, - -intensity, 0, intensity, 0, 0, - 0, intensity, intensity * 2.0, 0, 0, - 0, 0, 0, 1, 0 ]; - this._loadMatrix(matrix, multiply); - }; - /** - * Predator effect - * - * Erase the current matrix by setting a new indepent one - * - * @param {number} amount - how much the predator feels his future victim - * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, - * just set the current matrix with @param matrix - */ - ColorMatrixFilter.prototype.predator = function (amount, multiply) { - var matrix = [ - // row 1 - 11.224130630493164 * amount, - -4.794486999511719 * amount, - -2.8746118545532227 * amount, - 0 * amount, - 0.40342438220977783 * amount, - // row 2 - -3.6330697536468506 * amount, - 9.193157196044922 * amount, - -2.951810836791992 * amount, - 0 * amount, - -1.316135048866272 * amount, - // row 3 - -3.2184197902679443 * amount, - -4.2375030517578125 * amount, - 7.476448059082031 * amount, - 0 * amount, - 0.8044459223747253 * amount, - // row 4 - 0, 0, 0, 1, 0 ]; - this._loadMatrix(matrix, multiply); - }; - /** - * LSD effect - * - * Multiply the current matrix - * - * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false, - * just set the current matrix with @param matrix - */ - ColorMatrixFilter.prototype.lsd = function (multiply) { - var matrix = [ - 2, -0.4, 0.5, 0, 0, - -0.5, 2, -0.4, 0, 0, - -0.4, -0.5, 3, 0, 0, - 0, 0, 0, 1, 0 ]; - this._loadMatrix(matrix, multiply); - }; - /** - * Erase the current matrix by setting the default one - * - */ - ColorMatrixFilter.prototype.reset = function () { - var matrix = [ - 1, 0, 0, 0, 0, - 0, 1, 0, 0, 0, - 0, 0, 1, 0, 0, - 0, 0, 0, 1, 0 ]; - this._loadMatrix(matrix, false); - }; - Object.defineProperty(ColorMatrixFilter.prototype, "matrix", { - /** - * The matrix of the color matrix filter - * - * @member {number[]} - * @default [1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0] - */ - get: function () { - return this.uniforms.m; - }, - set: function (value) { - this.uniforms.m = value; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(ColorMatrixFilter.prototype, "alpha", { - /** - * The opacity value to use when mixing the original and resultant colors. - * - * When the value is 0, the original color is used without modification. - * When the value is 1, the result color is used. - * When in the range (0, 1) the color is interpolated between the original and result by this amount. - * - * @member {number} - * @default 1 - */ - get: function () { - return this.uniforms.uAlpha; - }, - set: function (value) { - this.uniforms.uAlpha = value; - }, - enumerable: false, - configurable: true - }); - return ColorMatrixFilter; - }(Filter)); - // Americanized alias - ColorMatrixFilter.prototype.grayscale = ColorMatrixFilter.prototype.greyscale; - - /*! - * @pixi/filter-displacement - v5.3.3 - * Compiled Tue, 04 Aug 2020 16:23:09 UTC - * - * @pixi/filter-displacement is licensed under the MIT License. - * http://www.opensource.org/licenses/mit-license - */ - - /*! ***************************************************************************** - Copyright (c) Microsoft Corporation. All rights reserved. - Licensed under the Apache License, Version 2.0 (the "License"); you may not use - this file except in compliance with the License. You may obtain a copy of the - License at http://www.apache.org/licenses/LICENSE-2.0 + function __extends$b(d, b) { + extendStatics$b(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + } + + /** + * CountLimiter limits the number of items handled by a {@link PIXI.BasePrepare} to a specified + * number of items per frame. + * @memberof PIXI + */ + var CountLimiter = /** @class */ (function () { + /** + * @param maxItemsPerFrame - The maximum number of items that can be prepared each frame. + */ + function CountLimiter(maxItemsPerFrame) { + this.maxItemsPerFrame = maxItemsPerFrame; + this.itemsLeft = 0; + } + /** Resets any counting properties to start fresh on a new frame. */ + CountLimiter.prototype.beginFrame = function () { + this.itemsLeft = this.maxItemsPerFrame; + }; + /** + * Checks to see if another item can be uploaded. This should only be called once per item. + * @returns If the item is allowed to be uploaded. + */ + CountLimiter.prototype.allowedToUpload = function () { + return this.itemsLeft-- > 0; + }; + return CountLimiter; + }()); + + /** + * Built-in hook to find multiple textures from objects like AnimatedSprites. + * @private + * @param item - Display object to check + * @param queue - Collection of items to upload + * @returns If a PIXI.Texture object was found. + */ + function findMultipleBaseTextures(item, queue) { + var result = false; + // Objects with multiple textures + if (item && item._textures && item._textures.length) { + for (var i = 0; i < item._textures.length; i++) { + if (item._textures[i] instanceof Texture) { + var baseTexture = item._textures[i].baseTexture; + if (queue.indexOf(baseTexture) === -1) { + queue.push(baseTexture); + result = true; + } + } + } + } + return result; + } + /** + * Built-in hook to find BaseTextures from Texture. + * @private + * @param item - Display object to check + * @param queue - Collection of items to upload + * @returns If a PIXI.Texture object was found. + */ + function findBaseTexture(item, queue) { + if (item.baseTexture instanceof BaseTexture) { + var texture = item.baseTexture; + if (queue.indexOf(texture) === -1) { + queue.push(texture); + } + return true; + } + return false; + } + /** + * Built-in hook to find textures from objects. + * @private + * @param item - Display object to check + * @param queue - Collection of items to upload + * @returns If a PIXI.Texture object was found. + */ + function findTexture(item, queue) { + if (item._texture && item._texture instanceof Texture) { + var texture = item._texture.baseTexture; + if (queue.indexOf(texture) === -1) { + queue.push(texture); + } + return true; + } + return false; + } + /** + * Built-in hook to draw PIXI.Text to its texture. + * @private + * @param _helper - Not used by this upload handler + * @param item - Item to check + * @returns If item was uploaded. + */ + function drawText(_helper, item) { + if (item instanceof Text) { + // updating text will return early if it is not dirty + item.updateText(true); + return true; + } + return false; + } + /** + * Built-in hook to calculate a text style for a PIXI.Text object. + * @private + * @param _helper - Not used by this upload handler + * @param item - Item to check + * @returns If item was uploaded. + */ + function calculateTextStyle(_helper, item) { + if (item instanceof TextStyle) { + var font = item.toFontString(); + TextMetrics.measureFont(font); + return true; + } + return false; + } + /** + * Built-in hook to find Text objects. + * @private + * @param item - Display object to check + * @param queue - Collection of items to upload + * @returns if a PIXI.Text object was found. + */ + function findText(item, queue) { + if (item instanceof Text) { + // push the text style to prepare it - this can be really expensive + if (queue.indexOf(item.style) === -1) { + queue.push(item.style); + } + // also push the text object so that we can render it (to canvas/texture) if needed + if (queue.indexOf(item) === -1) { + queue.push(item); + } + // also push the Text's texture for upload to GPU + var texture = item._texture.baseTexture; + if (queue.indexOf(texture) === -1) { + queue.push(texture); + } + return true; + } + return false; + } + /** + * Built-in hook to find TextStyle objects. + * @private + * @param item - Display object to check + * @param queue - Collection of items to upload + * @returns If a PIXI.TextStyle object was found. + */ + function findTextStyle(item, queue) { + if (item instanceof TextStyle) { + if (queue.indexOf(item) === -1) { + queue.push(item); + } + return true; + } + return false; + } + /** + * The prepare manager provides functionality to upload content to the GPU. + * + * BasePrepare handles basic queuing functionality and is extended by + * {@link PIXI.Prepare} and {@link PIXI.CanvasPrepare} + * to provide preparation capabilities specific to their respective renderers. + * @example + * // Create a sprite + * const sprite = PIXI.Sprite.from('something.png'); + * + * // Load object into GPU + * app.renderer.plugins.prepare.upload(sprite, () => { + * + * //Texture(s) has been uploaded to GPU + * app.stage.addChild(sprite); + * + * }) + * @abstract + * @memberof PIXI + */ + var BasePrepare = /** @class */ (function () { + /** + * @param {PIXI.AbstractRenderer} renderer - A reference to the current renderer + */ + function BasePrepare(renderer) { + var _this = this; + this.limiter = new CountLimiter(settings$1.UPLOADS_PER_FRAME); + this.renderer = renderer; + this.uploadHookHelper = null; + this.queue = []; + this.addHooks = []; + this.uploadHooks = []; + this.completes = []; + this.ticking = false; + this.delayedTick = function () { + // unlikely, but in case we were destroyed between tick() and delayedTick() + if (!_this.queue) { + return; + } + _this.prepareItems(); + }; + // hooks to find the correct texture + this.registerFindHook(findText); + this.registerFindHook(findTextStyle); + this.registerFindHook(findMultipleBaseTextures); + this.registerFindHook(findBaseTexture); + this.registerFindHook(findTexture); + // upload hooks + this.registerUploadHook(drawText); + this.registerUploadHook(calculateTextStyle); + } + /** @ignore */ + BasePrepare.prototype.upload = function (item, done) { + var _this = this; + if (typeof item === 'function') { + done = item; + item = null; + } + if (done) { + deprecation$1('6.5.0', 'BasePrepare.upload callback is deprecated, use the return Promise instead.'); + } + return new Promise(function (resolve) { + // If a display object, search for items + // that we could upload + if (item) { + _this.add(item); + } + // TODO: remove done callback and just use resolve + var complete = function () { + done === null || done === void 0 ? void 0 : done(); + resolve(); + }; + // Get the items for upload from the display + if (_this.queue.length) { + _this.completes.push(complete); + if (!_this.ticking) { + _this.ticking = true; + Ticker.system.addOnce(_this.tick, _this, exports.UPDATE_PRIORITY.UTILITY); + } + } + else { + complete(); + } + }); + }; + /** + * Handle tick update + * @private + */ + BasePrepare.prototype.tick = function () { + setTimeout(this.delayedTick, 0); + }; + /** + * Actually prepare items. This is handled outside of the tick because it will take a while + * and we do NOT want to block the current animation frame from rendering. + * @private + */ + BasePrepare.prototype.prepareItems = function () { + this.limiter.beginFrame(); + // Upload the graphics + while (this.queue.length && this.limiter.allowedToUpload()) { + var item = this.queue[0]; + var uploaded = false; + if (item && !item._destroyed) { + for (var i = 0, len = this.uploadHooks.length; i < len; i++) { + if (this.uploadHooks[i](this.uploadHookHelper, item)) { + this.queue.shift(); + uploaded = true; + break; + } + } + } + if (!uploaded) { + this.queue.shift(); + } + } + // We're finished + if (!this.queue.length) { + this.ticking = false; + var completes = this.completes.slice(0); + this.completes.length = 0; + for (var i = 0, len = completes.length; i < len; i++) { + completes[i](); + } + } + else { + // if we are not finished, on the next rAF do this again + Ticker.system.addOnce(this.tick, this, exports.UPDATE_PRIORITY.UTILITY); + } + }; + /** + * Adds hooks for finding items. + * @param {Function} addHook - Function call that takes two parameters: `item:*, queue:Array` + * function must return `true` if it was able to add item to the queue. + * @returns Instance of plugin for chaining. + */ + BasePrepare.prototype.registerFindHook = function (addHook) { + if (addHook) { + this.addHooks.push(addHook); + } + return this; + }; + /** + * Adds hooks for uploading items. + * @param {Function} uploadHook - Function call that takes two parameters: `prepare:CanvasPrepare, item:*` and + * function must return `true` if it was able to handle upload of item. + * @returns Instance of plugin for chaining. + */ + BasePrepare.prototype.registerUploadHook = function (uploadHook) { + if (uploadHook) { + this.uploadHooks.push(uploadHook); + } + return this; + }; + /** + * Manually add an item to the uploading queue. + * @param {PIXI.DisplayObject|PIXI.Container|PIXI.BaseTexture|PIXI.Texture|PIXI.Graphics|PIXI.Text|*} item - Object to + * add to the queue + * @returns Instance of plugin for chaining. + */ + BasePrepare.prototype.add = function (item) { + // Add additional hooks for finding elements on special + // types of objects that + for (var i = 0, len = this.addHooks.length; i < len; i++) { + if (this.addHooks[i](item, this.queue)) { + break; + } + } + // Get children recursively + if (item instanceof Container) { + for (var i = item.children.length - 1; i >= 0; i--) { + this.add(item.children[i]); + } + } + return this; + }; + /** Destroys the plugin, don't use after this. */ + BasePrepare.prototype.destroy = function () { + if (this.ticking) { + Ticker.system.remove(this.tick, this); + } + this.ticking = false; + this.addHooks = null; + this.uploadHooks = null; + this.renderer = null; + this.completes = null; + this.queue = null; + this.limiter = null; + this.uploadHookHelper = null; + }; + return BasePrepare; + }()); + + /** + * Built-in hook to upload PIXI.Texture objects to the GPU. + * @private + * @param renderer - instance of the webgl renderer + * @param item - Item to check + * @returns If item was uploaded. + */ + function uploadBaseTextures(renderer, item) { + if (item instanceof BaseTexture) { + // if the texture already has a GL texture, then the texture has been prepared or rendered + // before now. If the texture changed, then the changer should be calling texture.update() which + // reuploads the texture without need for preparing it again + if (!item._glTextures[renderer.CONTEXT_UID]) { + renderer.texture.bind(item); + } + return true; + } + return false; + } + /** + * Built-in hook to upload PIXI.Graphics to the GPU. + * @private + * @param renderer - instance of the webgl renderer + * @param item - Item to check + * @returns If item was uploaded. + */ + function uploadGraphics(renderer, item) { + if (!(item instanceof Graphics)) { + return false; + } + var geometry = item.geometry; + // update dirty graphics to get batches + item.finishPoly(); + geometry.updateBatches(); + var batches = geometry.batches; + // upload all textures found in styles + for (var i = 0; i < batches.length; i++) { + var texture = batches[i].style.texture; + if (texture) { + uploadBaseTextures(renderer, texture.baseTexture); + } + } + // if its not batchable - update vao for particular shader + if (!geometry.batchable) { + renderer.geometry.bind(geometry, item._resolveDirectShader(renderer)); + } + return true; + } + /** + * Built-in hook to find graphics. + * @private + * @param item - Display object to check + * @param queue - Collection of items to upload + * @returns if a PIXI.Graphics object was found. + */ + function findGraphics(item, queue) { + if (item instanceof Graphics) { + queue.push(item); + return true; + } + return false; + } + /** + * The prepare plugin provides renderer-specific plugins for pre-rendering DisplayObjects. These plugins are useful for + * asynchronously preparing and uploading to the GPU assets, textures, graphics waiting to be displayed. + * + * Do not instantiate this plugin directly. It is available from the `renderer.plugins` property. + * See {@link PIXI.CanvasRenderer#plugins} or {@link PIXI.Renderer#plugins}. + * @example + * // Create a new application + * const app = new PIXI.Application(); + * document.body.appendChild(app.view); + * + * // Don't start rendering right away + * app.stop(); + * + * // create a display object + * const rect = new PIXI.Graphics() + * .beginFill(0x00ff00) + * .drawRect(40, 40, 200, 200); + * + * // Add to the stage + * app.stage.addChild(rect); + * + * // Don't start rendering until the graphic is uploaded to the GPU + * app.renderer.plugins.prepare.upload(app.stage, () => { + * app.start(); + * }); + * @memberof PIXI + */ + var Prepare = /** @class */ (function (_super) { + __extends$b(Prepare, _super); + /** + * @param {PIXI.Renderer} renderer - A reference to the current renderer + */ + function Prepare(renderer) { + var _this = _super.call(this, renderer) || this; + _this.uploadHookHelper = _this.renderer; + // Add textures and graphics to upload + _this.registerFindHook(findGraphics); + _this.registerUploadHook(uploadBaseTextures); + _this.registerUploadHook(uploadGraphics); + return _this; + } + /** @ignore */ + Prepare.extension = { + name: 'prepare', + type: exports.ExtensionType.RendererPlugin, + }; + return Prepare; + }(BasePrepare)); + + /** + * TimeLimiter limits the number of items handled by a {@link PIXI.BasePrepare} to a specified + * number of milliseconds per frame. + * @memberof PIXI + */ + var TimeLimiter = /** @class */ (function () { + /** @param maxMilliseconds - The maximum milliseconds that can be spent preparing items each frame. */ + function TimeLimiter(maxMilliseconds) { + this.maxMilliseconds = maxMilliseconds; + this.frameStart = 0; + } + /** Resets any counting properties to start fresh on a new frame. */ + TimeLimiter.prototype.beginFrame = function () { + this.frameStart = Date.now(); + }; + /** + * Checks to see if another item can be uploaded. This should only be called once per item. + * @returns - If the item is allowed to be uploaded. + */ + TimeLimiter.prototype.allowedToUpload = function () { + return Date.now() - this.frameStart < this.maxMilliseconds; + }; + return TimeLimiter; + }()); + + /*! + * @pixi/spritesheet - v6.5.3 + * Compiled Fri, 09 Sep 2022 13:55:20 UTC + * + * @pixi/spritesheet is licensed under the MIT License. + * http://www.opensource.org/licenses/mit-license + */ + + /** + * Utility class for maintaining reference to a collection + * of Textures on a single Spritesheet. + * + * To access a sprite sheet from your code you may pass its JSON data file to Pixi's loader: + * + * ```js + * PIXI.Loader.shared.add("images/spritesheet.json").load(setup); + * + * function setup() { + * let sheet = PIXI.Loader.shared.resources["images/spritesheet.json"].spritesheet; + * ... + * } + * ``` + * + * Alternately, you may circumvent the loader by instantiating the Spritesheet directly: + * ```js + * const sheet = new PIXI.Spritesheet(texture, spritesheetData); + * await sheet.parse(); + * console.log('Spritesheet ready to use!'); + * ``` + * + * With the `sheet.textures` you can create Sprite objects,`sheet.animations` can be used to create an AnimatedSprite. + * + * Sprite sheets can be packed using tools like {@link https://codeandweb.com/texturepacker|TexturePacker}, + * {@link https://renderhjs.net/shoebox/|Shoebox} or {@link https://github.com/krzysztof-o/spritesheet.js|Spritesheet.js}. + * Default anchor points (see {@link PIXI.Texture#defaultAnchor}) and grouping of animation sprites are currently only + * supported by TexturePacker. + * @memberof PIXI + */ + var Spritesheet = /** @class */ (function () { + /** + * @param texture - Reference to the source BaseTexture object. + * @param {object} data - Spritesheet image data. + * @param resolutionFilename - The filename to consider when determining + * the resolution of the spritesheet. If not provided, the imageUrl will + * be used on the BaseTexture. + */ + function Spritesheet(texture, data, resolutionFilename) { + if (resolutionFilename === void 0) { resolutionFilename = null; } + /** For multi-packed spritesheets, this contains a reference to all the other spritesheets it depends on. */ + this.linkedSheets = []; + this._texture = texture instanceof Texture ? texture : null; + this.baseTexture = texture instanceof BaseTexture ? texture : this._texture.baseTexture; + this.textures = {}; + this.animations = {}; + this.data = data; + var resource = this.baseTexture.resource; + this.resolution = this._updateResolution(resolutionFilename || (resource ? resource.url : null)); + this._frames = this.data.frames; + this._frameKeys = Object.keys(this._frames); + this._batchIndex = 0; + this._callback = null; + } + /** + * Generate the resolution from the filename or fallback + * to the meta.scale field of the JSON data. + * @param resolutionFilename - The filename to use for resolving + * the default resolution. + * @returns Resolution to use for spritesheet. + */ + Spritesheet.prototype._updateResolution = function (resolutionFilename) { + if (resolutionFilename === void 0) { resolutionFilename = null; } + var scale = this.data.meta.scale; + // Use a defaultValue of `null` to check if a url-based resolution is set + var resolution = getResolutionOfUrl(resolutionFilename, null); + // No resolution found via URL + if (resolution === null) { + // Use the scale value or default to 1 + resolution = scale !== undefined ? parseFloat(scale) : 1; + } + // For non-1 resolutions, update baseTexture + if (resolution !== 1) { + this.baseTexture.setResolution(resolution); + } + return resolution; + }; + /** @ignore */ + Spritesheet.prototype.parse = function (callback) { + var _this = this; + if (callback) { + deprecation$1('6.5.0', 'Spritesheet.parse callback is deprecated, use the return Promise instead.'); + } + return new Promise(function (resolve) { + _this._callback = function (textures) { + callback === null || callback === void 0 ? void 0 : callback(textures); + resolve(textures); + }; + _this._batchIndex = 0; + if (_this._frameKeys.length <= Spritesheet.BATCH_SIZE) { + _this._processFrames(0); + _this._processAnimations(); + _this._parseComplete(); + } + else { + _this._nextBatch(); + } + }); + }; + /** + * Process a batch of frames + * @param initialFrameIndex - The index of frame to start. + */ + Spritesheet.prototype._processFrames = function (initialFrameIndex) { + var frameIndex = initialFrameIndex; + var maxFrames = Spritesheet.BATCH_SIZE; + while (frameIndex - initialFrameIndex < maxFrames && frameIndex < this._frameKeys.length) { + var i = this._frameKeys[frameIndex]; + var data = this._frames[i]; + var rect = data.frame; + if (rect) { + var frame = null; + var trim = null; + var sourceSize = data.trimmed !== false && data.sourceSize + ? data.sourceSize : data.frame; + var orig = new Rectangle(0, 0, Math.floor(sourceSize.w) / this.resolution, Math.floor(sourceSize.h) / this.resolution); + if (data.rotated) { + frame = new Rectangle(Math.floor(rect.x) / this.resolution, Math.floor(rect.y) / this.resolution, Math.floor(rect.h) / this.resolution, Math.floor(rect.w) / this.resolution); + } + else { + frame = new Rectangle(Math.floor(rect.x) / this.resolution, Math.floor(rect.y) / this.resolution, Math.floor(rect.w) / this.resolution, Math.floor(rect.h) / this.resolution); + } + // Check to see if the sprite is trimmed + if (data.trimmed !== false && data.spriteSourceSize) { + trim = new Rectangle(Math.floor(data.spriteSourceSize.x) / this.resolution, Math.floor(data.spriteSourceSize.y) / this.resolution, Math.floor(rect.w) / this.resolution, Math.floor(rect.h) / this.resolution); + } + this.textures[i] = new Texture(this.baseTexture, frame, orig, trim, data.rotated ? 2 : 0, data.anchor); + // lets also add the frame to pixi's global cache for 'from' and 'fromLoader' functions + Texture.addToCache(this.textures[i], i); + } + frameIndex++; + } + }; + /** Parse animations config. */ + Spritesheet.prototype._processAnimations = function () { + var animations = this.data.animations || {}; + for (var animName in animations) { + this.animations[animName] = []; + for (var i = 0; i < animations[animName].length; i++) { + var frameName = animations[animName][i]; + this.animations[animName].push(this.textures[frameName]); + } + } + }; + /** The parse has completed. */ + Spritesheet.prototype._parseComplete = function () { + var callback = this._callback; + this._callback = null; + this._batchIndex = 0; + callback.call(this, this.textures); + }; + /** Begin the next batch of textures. */ + Spritesheet.prototype._nextBatch = function () { + var _this = this; + this._processFrames(this._batchIndex * Spritesheet.BATCH_SIZE); + this._batchIndex++; + setTimeout(function () { + if (_this._batchIndex * Spritesheet.BATCH_SIZE < _this._frameKeys.length) { + _this._nextBatch(); + } + else { + _this._processAnimations(); + _this._parseComplete(); + } + }, 0); + }; + /** + * Destroy Spritesheet and don't use after this. + * @param {boolean} [destroyBase=false] - Whether to destroy the base texture as well + */ + Spritesheet.prototype.destroy = function (destroyBase) { + var _a; + if (destroyBase === void 0) { destroyBase = false; } + for (var i in this.textures) { + this.textures[i].destroy(); + } + this._frames = null; + this._frameKeys = null; + this.data = null; + this.textures = null; + if (destroyBase) { + (_a = this._texture) === null || _a === void 0 ? void 0 : _a.destroy(); + this.baseTexture.destroy(); + } + this._texture = null; + this.baseTexture = null; + this.linkedSheets = []; + }; + /** The maximum number of Textures to build per process. */ + Spritesheet.BATCH_SIZE = 1000; + return Spritesheet; + }()); + /** + * Reference to Spritesheet object created. + * @member {PIXI.Spritesheet} spritesheet + * @memberof PIXI.LoaderResource + * @instance + */ + /** + * Dictionary of textures from Spritesheet. + * @member {Object} textures + * @memberof PIXI.LoaderResource + * @instance + */ + + /** + * {@link PIXI.Loader} middleware for loading texture atlases that have been created with + * TexturePacker or similar JSON-based spritesheet. + * + * This middleware automatically generates Texture resources. + * + * If you're using Webpack or other bundlers and plan on bundling the atlas' JSON, + * use the {@link PIXI.Spritesheet} class to directly parse the JSON. + * + * The Loader's image Resource name is automatically appended with `"_image"`. + * If a Resource with this name is already loaded, the Loader will skip parsing the + * Spritesheet. The code below will generate an internal Loader Resource called `"myatlas_image"`. + * @example + * loader.add('myatlas', 'path/to/myatlas.json'); + * loader.load(() => { + * loader.resources.myatlas; // atlas JSON resource + * loader.resources.myatlas_image; // atlas Image resource + * }); + * @memberof PIXI + */ + var SpritesheetLoader = /** @class */ (function () { + function SpritesheetLoader() { + } + /** + * Called after a resource is loaded. + * @see PIXI.Loader.loaderMiddleware + * @param resource + * @param next + */ + SpritesheetLoader.use = function (resource, next) { + var _a, _b; + // because this is middleware, it execute in loader context. `this` = loader + var loader = this; + var imageResourceName = resource.name + "_image"; + // skip if no data, its not json, it isn't spritesheet data, or the image resource already exists + if (!resource.data + || resource.type !== exports.LoaderResource.TYPE.JSON + || !resource.data.frames + || loader.resources[imageResourceName]) { + next(); + return; + } + // Check and add the multi atlas + // Heavily influenced and based on https://github.com/rocket-ua/pixi-tps-loader/blob/master/src/ResourceLoader.js + // eslint-disable-next-line camelcase + var multiPacks = (_b = (_a = resource.data) === null || _a === void 0 ? void 0 : _a.meta) === null || _b === void 0 ? void 0 : _b.related_multi_packs; + if (Array.isArray(multiPacks)) { + var _loop_1 = function (item) { + if (typeof item !== 'string') { + return "continue"; + } + var itemName = item.replace('.json', ''); + var itemUrl = url.resolve(resource.url.replace(loader.baseUrl, ''), item); + // Check if the file wasn't already added as multipacks are redundant + if (loader.resources[itemName] + || Object.values(loader.resources).some(function (r) { return url.format(url.parse(r.url)) === itemUrl; })) { + return "continue"; + } + var options = { + crossOrigin: resource.crossOrigin, + loadType: exports.LoaderResource.LOAD_TYPE.XHR, + xhrType: exports.LoaderResource.XHR_RESPONSE_TYPE.JSON, + parentResource: resource, + metadata: resource.metadata + }; + loader.add(itemName, itemUrl, options); + }; + for (var _i = 0, multiPacks_1 = multiPacks; _i < multiPacks_1.length; _i++) { + var item = multiPacks_1[_i]; + _loop_1(item); + } + } + var loadOptions = { + crossOrigin: resource.crossOrigin, + metadata: resource.metadata.imageMetadata, + parentResource: resource, + }; + var resourcePath = SpritesheetLoader.getResourcePath(resource, loader.baseUrl); + // load the image for this sheet + loader.add(imageResourceName, resourcePath, loadOptions, function onImageLoad(res) { + if (res.error) { + next(res.error); + return; + } + var spritesheet = new Spritesheet(res.texture, resource.data, resource.url); + spritesheet.parse().then(function () { + resource.spritesheet = spritesheet; + resource.textures = spritesheet.textures; + next(); + }); + }); + }; + /** + * Get the spritesheets root path + * @param resource - Resource to check path + * @param baseUrl - Base root url + */ + SpritesheetLoader.getResourcePath = function (resource, baseUrl) { + // Prepend url path unless the resource image is a data url + if (resource.isDataUrl) { + return resource.data.meta.image; + } + return url.resolve(resource.url.replace(baseUrl, ''), resource.data.meta.image); + }; + /** @ignore */ + SpritesheetLoader.extension = exports.ExtensionType.Loader; + return SpritesheetLoader; + }()); + + /*! + * @pixi/sprite-tiling - v6.5.3 + * Compiled Fri, 09 Sep 2022 13:55:20 UTC + * + * @pixi/sprite-tiling is licensed under the MIT License. + * http://www.opensource.org/licenses/mit-license + */ + + /*! ***************************************************************************** + Copyright (c) Microsoft Corporation. - THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED - WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, - MERCHANTABLITY OR NON-INFRINGEMENT. + Permission to use, copy, modify, and/or distribute this software for any + purpose with or without fee is hereby granted. - See the Apache Version 2.0 License for specific language governing permissions - and limitations under the License. - ***************************************************************************** */ - /* global Reflect, Promise */ + THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH + REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY + AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, + INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM + LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR + OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR + PERFORMANCE OF THIS SOFTWARE. + ***************************************************************************** */ + /* global Reflect, Promise */ - var extendStatics$f = function(d, b) { - extendStatics$f = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) { if (b.hasOwnProperty(p)) { d[p] = b[p]; } } }; - return extendStatics$f(d, b); - }; + var extendStatics$a = function(d, b) { + extendStatics$a = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) { if (b.hasOwnProperty(p)) { d[p] = b[p]; } } }; + return extendStatics$a(d, b); + }; - function __extends$f(d, b) { - extendStatics$f(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - } - - var fragment$6 = "varying vec2 vFilterCoord;\nvarying vec2 vTextureCoord;\n\nuniform vec2 scale;\nuniform mat2 rotation;\nuniform sampler2D uSampler;\nuniform sampler2D mapSampler;\n\nuniform highp vec4 inputSize;\nuniform vec4 inputClamp;\n\nvoid main(void)\n{\n vec4 map = texture2D(mapSampler, vFilterCoord);\n\n map -= 0.5;\n map.xy = scale * inputSize.zw * (rotation * map.xy);\n\n gl_FragColor = texture2D(uSampler, clamp(vec2(vTextureCoord.x + map.x, vTextureCoord.y + map.y), inputClamp.xy, inputClamp.zw));\n}\n"; - - var vertex$4 = "attribute vec2 aVertexPosition;\n\nuniform mat3 projectionMatrix;\nuniform mat3 filterMatrix;\n\nvarying vec2 vTextureCoord;\nvarying vec2 vFilterCoord;\n\nuniform vec4 inputSize;\nuniform vec4 outputFrame;\n\nvec4 filterVertexPosition( void )\n{\n vec2 position = aVertexPosition * max(outputFrame.zw, vec2(0.)) + outputFrame.xy;\n\n return vec4((projectionMatrix * vec3(position, 1.0)).xy, 0.0, 1.0);\n}\n\nvec2 filterTextureCoord( void )\n{\n return aVertexPosition * (outputFrame.zw * inputSize.zw);\n}\n\nvoid main(void)\n{\n\tgl_Position = filterVertexPosition();\n\tvTextureCoord = filterTextureCoord();\n\tvFilterCoord = ( filterMatrix * vec3( vTextureCoord, 1.0) ).xy;\n}\n"; - - /** - * The DisplacementFilter class uses the pixel values from the specified texture - * (called the displacement map) to perform a displacement of an object. - * - * You can use this filter to apply all manor of crazy warping effects. - * Currently the `r` property of the texture is used to offset the `x` - * and the `g` property of the texture is used to offset the `y`. - * - * The way it works is it uses the values of the displacement map to look up the - * correct pixels to output. This means it's not technically moving the original. - * Instead, it's starting at the output and asking "which pixel from the original goes here". - * For example, if a displacement map pixel has `red = 1` and the filter scale is `20`, - * this filter will output the pixel approximately 20 pixels to the right of the original. - * - * @class - * @extends PIXI.Filter - * @memberof PIXI.filters - */ - var DisplacementFilter = /** @class */ (function (_super) { - __extends$f(DisplacementFilter, _super); - /** - * @param {PIXI.Sprite} sprite - The sprite used for the displacement map. (make sure its added to the scene!) - * @param {number} [scale] - The scale of the displacement - */ - function DisplacementFilter(sprite, scale) { - var _this = this; - var maskMatrix = new Matrix(); - sprite.renderable = false; - _this = _super.call(this, vertex$4, fragment$6, { - mapSampler: sprite._texture, - filterMatrix: maskMatrix, - scale: { x: 1, y: 1 }, - rotation: new Float32Array([1, 0, 0, 1]), - }) || this; - _this.maskSprite = sprite; - _this.maskMatrix = maskMatrix; - if (scale === null || scale === undefined) { - scale = 20; - } - /** - * scaleX, scaleY for displacements - * @member {PIXI.Point} - */ - _this.scale = new Point(scale, scale); - return _this; - } - /** - * Applies the filter. - * - * @param {PIXI.systems.FilterSystem} filterManager - The manager. - * @param {PIXI.RenderTexture} input - The input target. - * @param {PIXI.RenderTexture} output - The output target. - * @param {PIXI.CLEAR_MODES} clearMode - clearMode. - */ - DisplacementFilter.prototype.apply = function (filterManager, input, output, clearMode) { - // fill maskMatrix with _normalized sprite texture coords_ - this.uniforms.filterMatrix = filterManager.calculateSpriteMatrix(this.maskMatrix, this.maskSprite); - this.uniforms.scale.x = this.scale.x; - this.uniforms.scale.y = this.scale.y; - // Extract rotation from world transform - var wt = this.maskSprite.worldTransform; - var lenX = Math.sqrt((wt.a * wt.a) + (wt.b * wt.b)); - var lenY = Math.sqrt((wt.c * wt.c) + (wt.d * wt.d)); - if (lenX !== 0 && lenY !== 0) { - this.uniforms.rotation[0] = wt.a / lenX; - this.uniforms.rotation[1] = wt.b / lenX; - this.uniforms.rotation[2] = wt.c / lenY; - this.uniforms.rotation[3] = wt.d / lenY; - } - // draw the filter... - filterManager.applyFilter(this, input, output, clearMode); - }; - Object.defineProperty(DisplacementFilter.prototype, "map", { - /** - * The texture used for the displacement map. Must be power of 2 sized texture. - * - * @member {PIXI.Texture} - */ - get: function () { - return this.uniforms.mapSampler; - }, - set: function (value) { - this.uniforms.mapSampler = value; - }, - enumerable: false, - configurable: true - }); - return DisplacementFilter; - }(Filter)); - - /*! - * @pixi/filter-fxaa - v5.3.3 - * Compiled Tue, 04 Aug 2020 16:23:09 UTC - * - * @pixi/filter-fxaa is licensed under the MIT License. - * http://www.opensource.org/licenses/mit-license - */ - - /*! ***************************************************************************** - Copyright (c) Microsoft Corporation. All rights reserved. - Licensed under the Apache License, Version 2.0 (the "License"); you may not use - this file except in compliance with the License. You may obtain a copy of the - License at http://www.apache.org/licenses/LICENSE-2.0 + function __extends$a(d, b) { + extendStatics$a(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + } + + var tempPoint$1 = new Point(); + /** + * A tiling sprite is a fast way of rendering a tiling image. + * @memberof PIXI + */ + var TilingSprite = /** @class */ (function (_super) { + __extends$a(TilingSprite, _super); + /** + * @param texture - The texture of the tiling sprite. + * @param width - The width of the tiling sprite. + * @param height - The height of the tiling sprite. + */ + function TilingSprite(texture, width, height) { + if (width === void 0) { width = 100; } + if (height === void 0) { height = 100; } + var _this = _super.call(this, texture) || this; + _this.tileTransform = new Transform(); + // The width of the tiling sprite + _this._width = width; + // The height of the tiling sprite + _this._height = height; + _this.uvMatrix = _this.texture.uvMatrix || new TextureMatrix(texture); + /** + * Plugin that is responsible for rendering this element. + * Allows to customize the rendering process without overriding '_render' method. + * @default 'tilingSprite' + */ + _this.pluginName = 'tilingSprite'; + _this.uvRespectAnchor = false; + return _this; + } + Object.defineProperty(TilingSprite.prototype, "clampMargin", { + /** + * Changes frame clamping in corresponding textureTransform, shortcut + * Change to -0.5 to add a pixel to the edge, recommended for transparent trimmed textures in atlas + * @default 0.5 + * @member {number} + */ + get: function () { + return this.uvMatrix.clampMargin; + }, + set: function (value) { + this.uvMatrix.clampMargin = value; + this.uvMatrix.update(true); + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(TilingSprite.prototype, "tileScale", { + /** The scaling of the image that is being tiled. */ + get: function () { + return this.tileTransform.scale; + }, + set: function (value) { + this.tileTransform.scale.copyFrom(value); + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(TilingSprite.prototype, "tilePosition", { + /** The offset of the image that is being tiled. */ + get: function () { + return this.tileTransform.position; + }, + set: function (value) { + this.tileTransform.position.copyFrom(value); + }, + enumerable: false, + configurable: true + }); + /** + * @protected + */ + TilingSprite.prototype._onTextureUpdate = function () { + if (this.uvMatrix) { + this.uvMatrix.texture = this._texture; + } + this._cachedTint = 0xFFFFFF; + }; + /** + * Renders the object using the WebGL renderer + * @param renderer - The renderer + */ + TilingSprite.prototype._render = function (renderer) { + // tweak our texture temporarily.. + var texture = this._texture; + if (!texture || !texture.valid) { + return; + } + this.tileTransform.updateLocalTransform(); + this.uvMatrix.update(); + renderer.batch.setObjectRenderer(renderer.plugins[this.pluginName]); + renderer.plugins[this.pluginName].render(this); + }; + /** Updates the bounds of the tiling sprite. */ + TilingSprite.prototype._calculateBounds = function () { + var minX = this._width * -this._anchor._x; + var minY = this._height * -this._anchor._y; + var maxX = this._width * (1 - this._anchor._x); + var maxY = this._height * (1 - this._anchor._y); + this._bounds.addFrame(this.transform, minX, minY, maxX, maxY); + }; + /** + * Gets the local bounds of the sprite object. + * @param rect - Optional output rectangle. + * @returns The bounds. + */ + TilingSprite.prototype.getLocalBounds = function (rect) { + // we can do a fast local bounds if the sprite has no children! + if (this.children.length === 0) { + this._bounds.minX = this._width * -this._anchor._x; + this._bounds.minY = this._height * -this._anchor._y; + this._bounds.maxX = this._width * (1 - this._anchor._x); + this._bounds.maxY = this._height * (1 - this._anchor._y); + if (!rect) { + if (!this._localBoundsRect) { + this._localBoundsRect = new Rectangle(); + } + rect = this._localBoundsRect; + } + return this._bounds.getRectangle(rect); + } + return _super.prototype.getLocalBounds.call(this, rect); + }; + /** + * Checks if a point is inside this tiling sprite. + * @param point - The point to check. + * @returns Whether or not the sprite contains the point. + */ + TilingSprite.prototype.containsPoint = function (point) { + this.worldTransform.applyInverse(point, tempPoint$1); + var width = this._width; + var height = this._height; + var x1 = -width * this.anchor._x; + if (tempPoint$1.x >= x1 && tempPoint$1.x < x1 + width) { + var y1 = -height * this.anchor._y; + if (tempPoint$1.y >= y1 && tempPoint$1.y < y1 + height) { + return true; + } + } + return false; + }; + /** + * Destroys this sprite and optionally its texture and children + * @param {object|boolean} [options] - Options parameter. A boolean will act as if all options + * have been set to that value + * @param {boolean} [options.children=false] - if set to true, all the children will have their destroy + * method called as well. 'options' will be passed on to those calls. + * @param {boolean} [options.texture=false] - Should it destroy the current texture of the sprite as well + * @param {boolean} [options.baseTexture=false] - Should it destroy the base texture of the sprite as well + */ + TilingSprite.prototype.destroy = function (options) { + _super.prototype.destroy.call(this, options); + this.tileTransform = null; + this.uvMatrix = null; + }; + /** + * Helper function that creates a new tiling sprite based on the source you provide. + * The source can be - frame id, image url, video url, canvas element, video element, base texture + * @static + * @param {string|PIXI.Texture|HTMLCanvasElement|HTMLVideoElement} source - Source to create texture from + * @param {object} options - See {@link PIXI.BaseTexture}'s constructor for options. + * @param {number} options.width - required width of the tiling sprite + * @param {number} options.height - required height of the tiling sprite + * @returns {PIXI.TilingSprite} The newly created texture + */ + TilingSprite.from = function (source, options) { + var texture = (source instanceof Texture) + ? source + : Texture.from(source, options); + return new TilingSprite(texture, options.width, options.height); + }; + Object.defineProperty(TilingSprite.prototype, "width", { + /** The width of the sprite, setting this will actually modify the scale to achieve the value set. */ + get: function () { + return this._width; + }, + set: function (value) { + this._width = value; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(TilingSprite.prototype, "height", { + /** The height of the TilingSprite, setting this will actually modify the scale to achieve the value set. */ + get: function () { + return this._height; + }, + set: function (value) { + this._height = value; + }, + enumerable: false, + configurable: true + }); + return TilingSprite; + }(Sprite)); + + var fragmentSimpleSrc = "#version 100\n#define SHADER_NAME Tiling-Sprite-Simple-100\n\nprecision lowp float;\n\nvarying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\nuniform vec4 uColor;\n\nvoid main(void)\n{\n vec4 texSample = texture2D(uSampler, vTextureCoord);\n gl_FragColor = texSample * uColor;\n}\n"; + + var gl1VertexSrc = "#version 100\n#define SHADER_NAME Tiling-Sprite-100\n\nprecision lowp float;\n\nattribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\nuniform mat3 translationMatrix;\nuniform mat3 uTransform;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n vTextureCoord = (uTransform * vec3(aTextureCoord, 1.0)).xy;\n}\n"; + + var gl1FragmentSrc = "#version 100\n#ifdef GL_EXT_shader_texture_lod\n #extension GL_EXT_shader_texture_lod : enable\n#endif\n#define SHADER_NAME Tiling-Sprite-100\n\nprecision lowp float;\n\nvarying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\nuniform vec4 uColor;\nuniform mat3 uMapCoord;\nuniform vec4 uClampFrame;\nuniform vec2 uClampOffset;\n\nvoid main(void)\n{\n vec2 coord = vTextureCoord + ceil(uClampOffset - vTextureCoord);\n coord = (uMapCoord * vec3(coord, 1.0)).xy;\n vec2 unclamped = coord;\n coord = clamp(coord, uClampFrame.xy, uClampFrame.zw);\n\n #ifdef GL_EXT_shader_texture_lod\n vec4 texSample = unclamped == coord\n ? texture2D(uSampler, coord) \n : texture2DLodEXT(uSampler, coord, 0);\n #else\n vec4 texSample = texture2D(uSampler, coord);\n #endif\n\n gl_FragColor = texSample * uColor;\n}\n"; + + var gl2VertexSrc = "#version 300 es\n#define SHADER_NAME Tiling-Sprite-300\n\nprecision lowp float;\n\nin vec2 aVertexPosition;\nin vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\nuniform mat3 translationMatrix;\nuniform mat3 uTransform;\n\nout vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n vTextureCoord = (uTransform * vec3(aTextureCoord, 1.0)).xy;\n}\n"; + + var gl2FragmentSrc = "#version 300 es\n#define SHADER_NAME Tiling-Sprite-100\n\nprecision lowp float;\n\nin vec2 vTextureCoord;\n\nout vec4 fragmentColor;\n\nuniform sampler2D uSampler;\nuniform vec4 uColor;\nuniform mat3 uMapCoord;\nuniform vec4 uClampFrame;\nuniform vec2 uClampOffset;\n\nvoid main(void)\n{\n vec2 coord = vTextureCoord + ceil(uClampOffset - vTextureCoord);\n coord = (uMapCoord * vec3(coord, 1.0)).xy;\n vec2 unclamped = coord;\n coord = clamp(coord, uClampFrame.xy, uClampFrame.zw);\n\n vec4 texSample = texture(uSampler, coord, unclamped == coord ? 0.0f : -32.0f);// lod-bias very negative to force lod 0\n\n fragmentColor = texSample * uColor;\n}\n"; + + var tempMat = new Matrix(); + /** + * WebGL renderer plugin for tiling sprites + * @class + * @memberof PIXI + * @extends PIXI.ObjectRenderer + */ + var TilingSpriteRenderer = /** @class */ (function (_super) { + __extends$a(TilingSpriteRenderer, _super); + /** + * constructor for renderer + * @param {PIXI.Renderer} renderer - The renderer this tiling awesomeness works for. + */ + function TilingSpriteRenderer(renderer) { + var _this = _super.call(this, renderer) || this; + // WebGL version is not available during initialization! + renderer.runners.contextChange.add(_this); + _this.quad = new QuadUv(); + /** + * The WebGL state in which this renderer will work. + * @member {PIXI.State} + * @readonly + */ + _this.state = State.for2d(); + return _this; + } + /** Creates shaders when context is initialized. */ + TilingSpriteRenderer.prototype.contextChange = function () { + var renderer = this.renderer; + var uniforms = { globals: renderer.globalUniforms }; + this.simpleShader = Shader.from(gl1VertexSrc, fragmentSimpleSrc, uniforms); + this.shader = renderer.context.webGLVersion > 1 + ? Shader.from(gl2VertexSrc, gl2FragmentSrc, uniforms) + : Shader.from(gl1VertexSrc, gl1FragmentSrc, uniforms); + }; + /** + * @param {PIXI.TilingSprite} ts - tilingSprite to be rendered + */ + TilingSpriteRenderer.prototype.render = function (ts) { + var renderer = this.renderer; + var quad = this.quad; + var vertices = quad.vertices; + vertices[0] = vertices[6] = (ts._width) * -ts.anchor.x; + vertices[1] = vertices[3] = ts._height * -ts.anchor.y; + vertices[2] = vertices[4] = (ts._width) * (1.0 - ts.anchor.x); + vertices[5] = vertices[7] = ts._height * (1.0 - ts.anchor.y); + var anchorX = ts.uvRespectAnchor ? ts.anchor.x : 0; + var anchorY = ts.uvRespectAnchor ? ts.anchor.y : 0; + vertices = quad.uvs; + vertices[0] = vertices[6] = -anchorX; + vertices[1] = vertices[3] = -anchorY; + vertices[2] = vertices[4] = 1.0 - anchorX; + vertices[5] = vertices[7] = 1.0 - anchorY; + quad.invalidate(); + var tex = ts._texture; + var baseTex = tex.baseTexture; + var premultiplied = baseTex.alphaMode > 0; + var lt = ts.tileTransform.localTransform; + var uv = ts.uvMatrix; + var isSimple = baseTex.isPowerOfTwo + && tex.frame.width === baseTex.width && tex.frame.height === baseTex.height; + // auto, force repeat wrapMode for big tiling textures + if (isSimple) { + if (!baseTex._glTextures[renderer.CONTEXT_UID]) { + if (baseTex.wrapMode === exports.WRAP_MODES.CLAMP) { + baseTex.wrapMode = exports.WRAP_MODES.REPEAT; + } + } + else { + isSimple = baseTex.wrapMode !== exports.WRAP_MODES.CLAMP; + } + } + var shader = isSimple ? this.simpleShader : this.shader; + var w = tex.width; + var h = tex.height; + var W = ts._width; + var H = ts._height; + tempMat.set(lt.a * w / W, lt.b * w / H, lt.c * h / W, lt.d * h / H, lt.tx / W, lt.ty / H); + // that part is the same as above: + // tempMat.identity(); + // tempMat.scale(tex.width, tex.height); + // tempMat.prepend(lt); + // tempMat.scale(1.0 / ts._width, 1.0 / ts._height); + tempMat.invert(); + if (isSimple) { + tempMat.prepend(uv.mapCoord); + } + else { + shader.uniforms.uMapCoord = uv.mapCoord.toArray(true); + shader.uniforms.uClampFrame = uv.uClampFrame; + shader.uniforms.uClampOffset = uv.uClampOffset; + } + shader.uniforms.uTransform = tempMat.toArray(true); + shader.uniforms.uColor = premultiplyTintToRgba(ts.tint, ts.worldAlpha, shader.uniforms.uColor, premultiplied); + shader.uniforms.translationMatrix = ts.transform.worldTransform.toArray(true); + shader.uniforms.uSampler = tex; + renderer.shader.bind(shader); + renderer.geometry.bind(quad); + this.state.blendMode = correctBlendMode(ts.blendMode, premultiplied); + renderer.state.set(this.state); + renderer.geometry.draw(this.renderer.gl.TRIANGLES, 6, 0); + }; + /** @ignore */ + TilingSpriteRenderer.extension = { + name: 'tilingSprite', + type: exports.ExtensionType.RendererPlugin, + }; + return TilingSpriteRenderer; + }(ObjectRenderer)); + + /*! + * @pixi/mesh - v6.5.3 + * Compiled Fri, 09 Sep 2022 13:55:20 UTC + * + * @pixi/mesh is licensed under the MIT License. + * http://www.opensource.org/licenses/mit-license + */ + + /*! ***************************************************************************** + Copyright (c) Microsoft Corporation. - THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED - WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, - MERCHANTABLITY OR NON-INFRINGEMENT. + Permission to use, copy, modify, and/or distribute this software for any + purpose with or without fee is hereby granted. - See the Apache Version 2.0 License for specific language governing permissions - and limitations under the License. - ***************************************************************************** */ - /* global Reflect, Promise */ + THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH + REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY + AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, + INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM + LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR + OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR + PERFORMANCE OF THIS SOFTWARE. + ***************************************************************************** */ + /* global Reflect, Promise */ - var extendStatics$g = function(d, b) { - extendStatics$g = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) { if (b.hasOwnProperty(p)) { d[p] = b[p]; } } }; - return extendStatics$g(d, b); - }; + var extendStatics$9 = function(d, b) { + extendStatics$9 = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) { if (b.hasOwnProperty(p)) { d[p] = b[p]; } } }; + return extendStatics$9(d, b); + }; - function __extends$g(d, b) { - extendStatics$g(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - } - - var vertex$5 = "\nattribute vec2 aVertexPosition;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 v_rgbNW;\nvarying vec2 v_rgbNE;\nvarying vec2 v_rgbSW;\nvarying vec2 v_rgbSE;\nvarying vec2 v_rgbM;\n\nvarying vec2 vFragCoord;\n\nuniform vec4 inputPixel;\nuniform vec4 outputFrame;\n\nvec4 filterVertexPosition( void )\n{\n vec2 position = aVertexPosition * max(outputFrame.zw, vec2(0.)) + outputFrame.xy;\n\n return vec4((projectionMatrix * vec3(position, 1.0)).xy, 0.0, 1.0);\n}\n\nvoid texcoords(vec2 fragCoord, vec2 inverseVP,\n out vec2 v_rgbNW, out vec2 v_rgbNE,\n out vec2 v_rgbSW, out vec2 v_rgbSE,\n out vec2 v_rgbM) {\n v_rgbNW = (fragCoord + vec2(-1.0, -1.0)) * inverseVP;\n v_rgbNE = (fragCoord + vec2(1.0, -1.0)) * inverseVP;\n v_rgbSW = (fragCoord + vec2(-1.0, 1.0)) * inverseVP;\n v_rgbSE = (fragCoord + vec2(1.0, 1.0)) * inverseVP;\n v_rgbM = vec2(fragCoord * inverseVP);\n}\n\nvoid main(void) {\n\n gl_Position = filterVertexPosition();\n\n vFragCoord = aVertexPosition * outputFrame.zw;\n\n texcoords(vFragCoord, inputPixel.zw, v_rgbNW, v_rgbNE, v_rgbSW, v_rgbSE, v_rgbM);\n}\n"; - - var fragment$7 = "varying vec2 v_rgbNW;\nvarying vec2 v_rgbNE;\nvarying vec2 v_rgbSW;\nvarying vec2 v_rgbSE;\nvarying vec2 v_rgbM;\n\nvarying vec2 vFragCoord;\nuniform sampler2D uSampler;\nuniform highp vec4 inputPixel;\n\n\n/**\n Basic FXAA implementation based on the code on geeks3d.com with the\n modification that the texture2DLod stuff was removed since it's\n unsupported by WebGL.\n\n --\n\n From:\n https://github.com/mitsuhiko/webgl-meincraft\n\n Copyright (c) 2011 by Armin Ronacher.\n\n Some rights reserved.\n\n Redistribution and use in source and binary forms, with or without\n modification, are permitted provided that the following conditions are\n met:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n\n * Redistributions in binary form must reproduce the above\n copyright notice, this list of conditions and the following\n disclaimer in the documentation and/or other materials provided\n with the distribution.\n\n * The names of the contributors may not be used to endorse or\n promote products derived from this software without specific\n prior written permission.\n\n THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n#ifndef FXAA_REDUCE_MIN\n#define FXAA_REDUCE_MIN (1.0/ 128.0)\n#endif\n#ifndef FXAA_REDUCE_MUL\n#define FXAA_REDUCE_MUL (1.0 / 8.0)\n#endif\n#ifndef FXAA_SPAN_MAX\n#define FXAA_SPAN_MAX 8.0\n#endif\n\n//optimized version for mobile, where dependent\n//texture reads can be a bottleneck\nvec4 fxaa(sampler2D tex, vec2 fragCoord, vec2 inverseVP,\n vec2 v_rgbNW, vec2 v_rgbNE,\n vec2 v_rgbSW, vec2 v_rgbSE,\n vec2 v_rgbM) {\n vec4 color;\n vec3 rgbNW = texture2D(tex, v_rgbNW).xyz;\n vec3 rgbNE = texture2D(tex, v_rgbNE).xyz;\n vec3 rgbSW = texture2D(tex, v_rgbSW).xyz;\n vec3 rgbSE = texture2D(tex, v_rgbSE).xyz;\n vec4 texColor = texture2D(tex, v_rgbM);\n vec3 rgbM = texColor.xyz;\n vec3 luma = vec3(0.299, 0.587, 0.114);\n float lumaNW = dot(rgbNW, luma);\n float lumaNE = dot(rgbNE, luma);\n float lumaSW = dot(rgbSW, luma);\n float lumaSE = dot(rgbSE, luma);\n float lumaM = dot(rgbM, luma);\n float lumaMin = min(lumaM, min(min(lumaNW, lumaNE), min(lumaSW, lumaSE)));\n float lumaMax = max(lumaM, max(max(lumaNW, lumaNE), max(lumaSW, lumaSE)));\n\n mediump vec2 dir;\n dir.x = -((lumaNW + lumaNE) - (lumaSW + lumaSE));\n dir.y = ((lumaNW + lumaSW) - (lumaNE + lumaSE));\n\n float dirReduce = max((lumaNW + lumaNE + lumaSW + lumaSE) *\n (0.25 * FXAA_REDUCE_MUL), FXAA_REDUCE_MIN);\n\n float rcpDirMin = 1.0 / (min(abs(dir.x), abs(dir.y)) + dirReduce);\n dir = min(vec2(FXAA_SPAN_MAX, FXAA_SPAN_MAX),\n max(vec2(-FXAA_SPAN_MAX, -FXAA_SPAN_MAX),\n dir * rcpDirMin)) * inverseVP;\n\n vec3 rgbA = 0.5 * (\n texture2D(tex, fragCoord * inverseVP + dir * (1.0 / 3.0 - 0.5)).xyz +\n texture2D(tex, fragCoord * inverseVP + dir * (2.0 / 3.0 - 0.5)).xyz);\n vec3 rgbB = rgbA * 0.5 + 0.25 * (\n texture2D(tex, fragCoord * inverseVP + dir * -0.5).xyz +\n texture2D(tex, fragCoord * inverseVP + dir * 0.5).xyz);\n\n float lumaB = dot(rgbB, luma);\n if ((lumaB < lumaMin) || (lumaB > lumaMax))\n color = vec4(rgbA, texColor.a);\n else\n color = vec4(rgbB, texColor.a);\n return color;\n}\n\nvoid main() {\n\n vec4 color;\n\n color = fxaa(uSampler, vFragCoord, inputPixel.zw, v_rgbNW, v_rgbNE, v_rgbSW, v_rgbSE, v_rgbM);\n\n gl_FragColor = color;\n}\n"; - - /** - * Basic FXAA (Fast Approximate Anti-Aliasing) implementation based on the code on geeks3d.com - * with the modification that the texture2DLod stuff was removed since it is unsupported by WebGL. - * - * @see https://github.com/mitsuhiko/webgl-meincraft - * - * @class - * @extends PIXI.Filter - * @memberof PIXI.filters - * - */ - var FXAAFilter = /** @class */ (function (_super) { - __extends$g(FXAAFilter, _super); - function FXAAFilter() { - // TODO - needs work - return _super.call(this, vertex$5, fragment$7) || this; - } - return FXAAFilter; - }(Filter)); - - /*! - * @pixi/filter-noise - v5.3.3 - * Compiled Tue, 04 Aug 2020 16:23:09 UTC - * - * @pixi/filter-noise is licensed under the MIT License. - * http://www.opensource.org/licenses/mit-license - */ - - /*! ***************************************************************************** - Copyright (c) Microsoft Corporation. All rights reserved. - Licensed under the Apache License, Version 2.0 (the "License"); you may not use - this file except in compliance with the License. You may obtain a copy of the - License at http://www.apache.org/licenses/LICENSE-2.0 + function __extends$9(d, b) { + extendStatics$9(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + } + + /** + * Class controls cache for UV mapping from Texture normal space to BaseTexture normal space. + * @memberof PIXI + */ + var MeshBatchUvs = /** @class */ (function () { + /** + * @param uvBuffer - Buffer with normalized uv's + * @param uvMatrix - Material UV matrix + */ + function MeshBatchUvs(uvBuffer, uvMatrix) { + this.uvBuffer = uvBuffer; + this.uvMatrix = uvMatrix; + this.data = null; + this._bufferUpdateId = -1; + this._textureUpdateId = -1; + this._updateID = 0; + } + /** + * Updates + * @param forceUpdate - force the update + */ + MeshBatchUvs.prototype.update = function (forceUpdate) { + if (!forceUpdate + && this._bufferUpdateId === this.uvBuffer._updateID + && this._textureUpdateId === this.uvMatrix._updateID) { + return; + } + this._bufferUpdateId = this.uvBuffer._updateID; + this._textureUpdateId = this.uvMatrix._updateID; + var data = this.uvBuffer.data; + if (!this.data || this.data.length !== data.length) { + this.data = new Float32Array(data.length); + } + this.uvMatrix.multiplyUvs(data, this.data); + this._updateID++; + }; + return MeshBatchUvs; + }()); + + var tempPoint = new Point(); + var tempPolygon = new Polygon(); + /** + * Base mesh class. + * + * This class empowers you to have maximum flexibility to render any kind of WebGL visuals you can think of. + * This class assumes a certain level of WebGL knowledge. + * If you know a bit this should abstract enough away to make your life easier! + * + * Pretty much ALL WebGL can be broken down into the following: + * - Geometry - The structure and data for the mesh. This can include anything from positions, uvs, normals, colors etc.. + * - Shader - This is the shader that PixiJS will render the geometry with (attributes in the shader must match the geometry) + * - State - This is the state of WebGL required to render the mesh. + * + * Through a combination of the above elements you can render anything you want, 2D or 3D! + * @memberof PIXI + */ + var Mesh = /** @class */ (function (_super) { + __extends$9(Mesh, _super); + /** + * @param geometry - The geometry the mesh will use. + * @param {PIXI.MeshMaterial} shader - The shader the mesh will use. + * @param state - The state that the WebGL context is required to be in to render the mesh + * if no state is provided, uses {@link PIXI.State.for2d} to create a 2D state for PixiJS. + * @param drawMode - The drawMode, can be any of the {@link PIXI.DRAW_MODES} constants. + */ + function Mesh(geometry, shader, state, drawMode) { + if (drawMode === void 0) { drawMode = exports.DRAW_MODES.TRIANGLES; } + var _this = _super.call(this) || this; + _this.geometry = geometry; + _this.shader = shader; + _this.state = state || State.for2d(); + _this.drawMode = drawMode; + _this.start = 0; + _this.size = 0; + _this.uvs = null; + _this.indices = null; + _this.vertexData = new Float32Array(1); + _this.vertexDirty = -1; + _this._transformID = -1; + _this._roundPixels = settings$1.ROUND_PIXELS; + _this.batchUvs = null; + return _this; + } + Object.defineProperty(Mesh.prototype, "geometry", { + /** + * Includes vertex positions, face indices, normals, colors, UVs, and + * custom attributes within buffers, reducing the cost of passing all + * this data to the GPU. Can be shared between multiple Mesh objects. + */ + get: function () { + return this._geometry; + }, + set: function (value) { + if (this._geometry === value) { + return; + } + if (this._geometry) { + this._geometry.refCount--; + if (this._geometry.refCount === 0) { + this._geometry.dispose(); + } + } + this._geometry = value; + if (this._geometry) { + this._geometry.refCount++; + } + this.vertexDirty = -1; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(Mesh.prototype, "uvBuffer", { + /** + * To change mesh uv's, change its uvBuffer data and increment its _updateID. + * @readonly + */ + get: function () { + return this.geometry.buffers[1]; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(Mesh.prototype, "verticesBuffer", { + /** + * To change mesh vertices, change its uvBuffer data and increment its _updateID. + * Incrementing _updateID is optional because most of Mesh objects do it anyway. + * @readonly + */ + get: function () { + return this.geometry.buffers[0]; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(Mesh.prototype, "material", { + get: function () { + return this.shader; + }, + /** Alias for {@link PIXI.Mesh#shader}. */ + set: function (value) { + this.shader = value; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(Mesh.prototype, "blendMode", { + get: function () { + return this.state.blendMode; + }, + /** + * The blend mode to be applied to the Mesh. Apply a value of + * `PIXI.BLEND_MODES.NORMAL` to reset the blend mode. + * @default PIXI.BLEND_MODES.NORMAL; + */ + set: function (value) { + this.state.blendMode = value; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(Mesh.prototype, "roundPixels", { + get: function () { + return this._roundPixels; + }, + /** + * If true PixiJS will Math.floor() x/y values when rendering, stopping pixel interpolation. + * Advantages can include sharper image quality (like text) and faster rendering on canvas. + * The main disadvantage is movement of objects may appear less smooth. + * To set the global default, change {@link PIXI.settings.ROUND_PIXELS} + * @default false + */ + set: function (value) { + if (this._roundPixels !== value) { + this._transformID = -1; + } + this._roundPixels = value; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(Mesh.prototype, "tint", { + /** + * The multiply tint applied to the Mesh. This is a hex value. A value of + * `0xFFFFFF` will remove any tint effect. + * + * Null for non-MeshMaterial shaders + * @default 0xFFFFFF + */ + get: function () { + return 'tint' in this.shader ? this.shader.tint : null; + }, + set: function (value) { + this.shader.tint = value; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(Mesh.prototype, "texture", { + /** The texture that the Mesh uses. Null for non-MeshMaterial shaders */ + get: function () { + return 'texture' in this.shader ? this.shader.texture : null; + }, + set: function (value) { + this.shader.texture = value; + }, + enumerable: false, + configurable: true + }); + /** + * Standard renderer draw. + * @param renderer - Instance to renderer. + */ + Mesh.prototype._render = function (renderer) { + // set properties for batching.. + // TODO could use a different way to grab verts? + var vertices = this.geometry.buffers[0].data; + var shader = this.shader; + // TODO benchmark check for attribute size.. + if (shader.batchable + && this.drawMode === exports.DRAW_MODES.TRIANGLES + && vertices.length < Mesh.BATCHABLE_SIZE * 2) { + this._renderToBatch(renderer); + } + else { + this._renderDefault(renderer); + } + }; + /** + * Standard non-batching way of rendering. + * @param renderer - Instance to renderer. + */ + Mesh.prototype._renderDefault = function (renderer) { + var shader = this.shader; + shader.alpha = this.worldAlpha; + if (shader.update) { + shader.update(); + } + renderer.batch.flush(); + // bind and sync uniforms.. + shader.uniforms.translationMatrix = this.transform.worldTransform.toArray(true); + renderer.shader.bind(shader); + // set state.. + renderer.state.set(this.state); + // bind the geometry... + renderer.geometry.bind(this.geometry, shader); + // then render it + renderer.geometry.draw(this.drawMode, this.size, this.start, this.geometry.instanceCount); + }; + /** + * Rendering by using the Batch system. + * @param renderer - Instance to renderer. + */ + Mesh.prototype._renderToBatch = function (renderer) { + var geometry = this.geometry; + var shader = this.shader; + if (shader.uvMatrix) { + shader.uvMatrix.update(); + this.calculateUvs(); + } + // set properties for batching.. + this.calculateVertices(); + this.indices = geometry.indexBuffer.data; + this._tintRGB = shader._tintRGB; + this._texture = shader.texture; + var pluginName = this.material.pluginName; + renderer.batch.setObjectRenderer(renderer.plugins[pluginName]); + renderer.plugins[pluginName].render(this); + }; + /** Updates vertexData field based on transform and vertices. */ + Mesh.prototype.calculateVertices = function () { + var geometry = this.geometry; + var verticesBuffer = geometry.buffers[0]; + var vertices = verticesBuffer.data; + var vertexDirtyId = verticesBuffer._updateID; + if (vertexDirtyId === this.vertexDirty && this._transformID === this.transform._worldID) { + return; + } + this._transformID = this.transform._worldID; + if (this.vertexData.length !== vertices.length) { + this.vertexData = new Float32Array(vertices.length); + } + var wt = this.transform.worldTransform; + var a = wt.a; + var b = wt.b; + var c = wt.c; + var d = wt.d; + var tx = wt.tx; + var ty = wt.ty; + var vertexData = this.vertexData; + for (var i = 0; i < vertexData.length / 2; i++) { + var x = vertices[(i * 2)]; + var y = vertices[(i * 2) + 1]; + vertexData[(i * 2)] = (a * x) + (c * y) + tx; + vertexData[(i * 2) + 1] = (b * x) + (d * y) + ty; + } + if (this._roundPixels) { + var resolution = settings$1.RESOLUTION; + for (var i = 0; i < vertexData.length; ++i) { + vertexData[i] = Math.round((vertexData[i] * resolution | 0) / resolution); + } + } + this.vertexDirty = vertexDirtyId; + }; + /** Updates uv field based on from geometry uv's or batchUvs. */ + Mesh.prototype.calculateUvs = function () { + var geomUvs = this.geometry.buffers[1]; + var shader = this.shader; + if (!shader.uvMatrix.isSimple) { + if (!this.batchUvs) { + this.batchUvs = new MeshBatchUvs(geomUvs, shader.uvMatrix); + } + this.batchUvs.update(); + this.uvs = this.batchUvs.data; + } + else { + this.uvs = geomUvs.data; + } + }; + /** + * Updates the bounds of the mesh as a rectangle. The bounds calculation takes the worldTransform into account. + * there must be a aVertexPosition attribute present in the geometry for bounds to be calculated correctly. + */ + Mesh.prototype._calculateBounds = function () { + this.calculateVertices(); + this._bounds.addVertexData(this.vertexData, 0, this.vertexData.length); + }; + /** + * Tests if a point is inside this mesh. Works only for PIXI.DRAW_MODES.TRIANGLES. + * @param point - The point to test. + * @returns - The result of the test. + */ + Mesh.prototype.containsPoint = function (point) { + if (!this.getBounds().contains(point.x, point.y)) { + return false; + } + this.worldTransform.applyInverse(point, tempPoint); + var vertices = this.geometry.getBuffer('aVertexPosition').data; + var points = tempPolygon.points; + var indices = this.geometry.getIndex().data; + var len = indices.length; + var step = this.drawMode === 4 ? 3 : 1; + for (var i = 0; i + 2 < len; i += step) { + var ind0 = indices[i] * 2; + var ind1 = indices[i + 1] * 2; + var ind2 = indices[i + 2] * 2; + points[0] = vertices[ind0]; + points[1] = vertices[ind0 + 1]; + points[2] = vertices[ind1]; + points[3] = vertices[ind1 + 1]; + points[4] = vertices[ind2]; + points[5] = vertices[ind2 + 1]; + if (tempPolygon.contains(tempPoint.x, tempPoint.y)) { + return true; + } + } + return false; + }; + Mesh.prototype.destroy = function (options) { + _super.prototype.destroy.call(this, options); + if (this._cachedTexture) { + this._cachedTexture.destroy(); + this._cachedTexture = null; + } + this.geometry = null; + this.shader = null; + this.state = null; + this.uvs = null; + this.indices = null; + this.vertexData = null; + }; + /** The maximum number of vertices to consider batchable. Generally, the complexity of the geometry. */ + Mesh.BATCHABLE_SIZE = 100; + return Mesh; + }(Container)); + + var fragment$5 = "varying vec2 vTextureCoord;\nuniform vec4 uColor;\n\nuniform sampler2D uSampler;\n\nvoid main(void)\n{\n gl_FragColor = texture2D(uSampler, vTextureCoord) * uColor;\n}\n"; + + var vertex$2 = "attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\nuniform mat3 translationMatrix;\nuniform mat3 uTextureMatrix;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n vTextureCoord = (uTextureMatrix * vec3(aTextureCoord, 1.0)).xy;\n}\n"; + + /** + * Slightly opinionated default shader for PixiJS 2D objects. + * @memberof PIXI + */ + var MeshMaterial = /** @class */ (function (_super) { + __extends$9(MeshMaterial, _super); + /** + * @param uSampler - Texture that material uses to render. + * @param options - Additional options + * @param {number} [options.alpha=1] - Default alpha. + * @param {number} [options.tint=0xFFFFFF] - Default tint. + * @param {string} [options.pluginName='batch'] - Renderer plugin for batching. + * @param {PIXI.Program} [options.program=0xFFFFFF] - Custom program. + * @param {object} [options.uniforms] - Custom uniforms. + */ + function MeshMaterial(uSampler, options) { + var _this = this; + var uniforms = { + uSampler: uSampler, + alpha: 1, + uTextureMatrix: Matrix.IDENTITY, + uColor: new Float32Array([1, 1, 1, 1]), + }; + // Set defaults + options = Object.assign({ + tint: 0xFFFFFF, + alpha: 1, + pluginName: 'batch', + }, options); + if (options.uniforms) { + Object.assign(uniforms, options.uniforms); + } + _this = _super.call(this, options.program || Program.from(vertex$2, fragment$5), uniforms) || this; + _this._colorDirty = false; + _this.uvMatrix = new TextureMatrix(uSampler); + _this.batchable = options.program === undefined; + _this.pluginName = options.pluginName; + _this.tint = options.tint; + _this.alpha = options.alpha; + return _this; + } + Object.defineProperty(MeshMaterial.prototype, "texture", { + /** Reference to the texture being rendered. */ + get: function () { + return this.uniforms.uSampler; + }, + set: function (value) { + if (this.uniforms.uSampler !== value) { + if (!this.uniforms.uSampler.baseTexture.alphaMode !== !value.baseTexture.alphaMode) { + this._colorDirty = true; + } + this.uniforms.uSampler = value; + this.uvMatrix.texture = value; + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(MeshMaterial.prototype, "alpha", { + get: function () { + return this._alpha; + }, + /** + * This gets automatically set by the object using this. + * @default 1 + */ + set: function (value) { + if (value === this._alpha) + { return; } + this._alpha = value; + this._colorDirty = true; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(MeshMaterial.prototype, "tint", { + get: function () { + return this._tint; + }, + /** + * Multiply tint for the material. + * @default 0xFFFFFF + */ + set: function (value) { + if (value === this._tint) + { return; } + this._tint = value; + this._tintRGB = (value >> 16) + (value & 0xff00) + ((value & 0xff) << 16); + this._colorDirty = true; + }, + enumerable: false, + configurable: true + }); + /** Gets called automatically by the Mesh. Intended to be overridden for custom {@link MeshMaterial} objects. */ + MeshMaterial.prototype.update = function () { + if (this._colorDirty) { + this._colorDirty = false; + var baseTexture = this.texture.baseTexture; + premultiplyTintToRgba(this._tint, this._alpha, this.uniforms.uColor, baseTexture.alphaMode); + } + if (this.uvMatrix.update()) { + this.uniforms.uTextureMatrix = this.uvMatrix.mapCoord; + } + }; + return MeshMaterial; + }(Shader)); + + /** + * Standard 2D geometry used in PixiJS. + * + * Geometry can be defined without passing in a style or data if required. + * + * ```js + * const geometry = new PIXI.Geometry(); + * + * geometry.addAttribute('positions', [0, 0, 100, 0, 100, 100, 0, 100], 2); + * geometry.addAttribute('uvs', [0,0,1,0,1,1,0,1], 2); + * geometry.addIndex([0,1,2,1,3,2]); + * + * ``` + * @memberof PIXI + */ + var MeshGeometry = /** @class */ (function (_super) { + __extends$9(MeshGeometry, _super); + /** + * @param {Float32Array|number[]} [vertices] - Positional data on geometry. + * @param {Float32Array|number[]} [uvs] - Texture UVs. + * @param {Uint16Array|number[]} [index] - IndexBuffer + */ + function MeshGeometry(vertices, uvs, index) { + var _this = _super.call(this) || this; + var verticesBuffer = new Buffer(vertices); + var uvsBuffer = new Buffer(uvs, true); + var indexBuffer = new Buffer(index, true, true); + _this.addAttribute('aVertexPosition', verticesBuffer, 2, false, exports.TYPES.FLOAT) + .addAttribute('aTextureCoord', uvsBuffer, 2, false, exports.TYPES.FLOAT) + .addIndex(indexBuffer); + _this._updateId = -1; + return _this; + } + Object.defineProperty(MeshGeometry.prototype, "vertexDirtyId", { + /** + * If the vertex position is updated. + * @readonly + * @private + */ + get: function () { + return this.buffers[0]._updateID; + }, + enumerable: false, + configurable: true + }); + return MeshGeometry; + }(Geometry)); + + /*! + * @pixi/text-bitmap - v6.5.3 + * Compiled Fri, 09 Sep 2022 13:55:20 UTC + * + * @pixi/text-bitmap is licensed under the MIT License. + * http://www.opensource.org/licenses/mit-license + */ + + /*! ***************************************************************************** + Copyright (c) Microsoft Corporation. - THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED - WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, - MERCHANTABLITY OR NON-INFRINGEMENT. + Permission to use, copy, modify, and/or distribute this software for any + purpose with or without fee is hereby granted. - See the Apache Version 2.0 License for specific language governing permissions - and limitations under the License. - ***************************************************************************** */ - /* global Reflect, Promise */ + THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH + REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY + AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, + INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM + LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR + OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR + PERFORMANCE OF THIS SOFTWARE. + ***************************************************************************** */ + /* global Reflect, Promise */ - var extendStatics$h = function(d, b) { - extendStatics$h = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) { if (b.hasOwnProperty(p)) { d[p] = b[p]; } } }; - return extendStatics$h(d, b); - }; + var extendStatics$8 = function(d, b) { + extendStatics$8 = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) { if (b.hasOwnProperty(p)) { d[p] = b[p]; } } }; + return extendStatics$8(d, b); + }; - function __extends$h(d, b) { - extendStatics$h(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - } - - var fragment$8 = "precision highp float;\n\nvarying vec2 vTextureCoord;\nvarying vec4 vColor;\n\nuniform float uNoise;\nuniform float uSeed;\nuniform sampler2D uSampler;\n\nfloat rand(vec2 co)\n{\n return fract(sin(dot(co.xy, vec2(12.9898, 78.233))) * 43758.5453);\n}\n\nvoid main()\n{\n vec4 color = texture2D(uSampler, vTextureCoord);\n float randomValue = rand(gl_FragCoord.xy * uSeed);\n float diff = (randomValue - 0.5) * uNoise;\n\n // Un-premultiply alpha before applying the color matrix. See issue #3539.\n if (color.a > 0.0) {\n color.rgb /= color.a;\n }\n\n color.r += diff;\n color.g += diff;\n color.b += diff;\n\n // Premultiply alpha again.\n color.rgb *= color.a;\n\n gl_FragColor = color;\n}\n"; - - /** - * @author Vico @vicocotea - * original filter: https://github.com/evanw/glfx.js/blob/master/src/filters/adjust/noise.js - */ - /** - * A Noise effect filter. - * - * @class - * @extends PIXI.Filter - * @memberof PIXI.filters - */ - var NoiseFilter = /** @class */ (function (_super) { - __extends$h(NoiseFilter, _super); - /** - * @param {number} [noise=0.5] - The noise intensity, should be a normalized value in the range [0, 1]. - * @param {number} [seed] - A random seed for the noise generation. Default is `Math.random()`. - */ - function NoiseFilter(noise, seed) { - if (noise === void 0) { noise = 0.5; } - if (seed === void 0) { seed = Math.random(); } - var _this = _super.call(this, defaultFilter, fragment$8, { - uNoise: 0, - uSeed: 0, - }) || this; - _this.noise = noise; - _this.seed = seed; - return _this; - } - Object.defineProperty(NoiseFilter.prototype, "noise", { - /** - * The amount of noise to apply, this value should be in the range (0, 1]. - * - * @member {number} - * @default 0.5 - */ - get: function () { - return this.uniforms.uNoise; - }, - set: function (value) { - this.uniforms.uNoise = value; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(NoiseFilter.prototype, "seed", { - /** - * A seed value to apply to the random noise generation. `Math.random()` is a good value to use. - * - * @member {number} - */ - get: function () { - return this.uniforms.uSeed; - }, - set: function (value) { - this.uniforms.uSeed = value; - }, - enumerable: false, - configurable: true - }); - return NoiseFilter; - }(Filter)); - - /*! - * @pixi/mixin-cache-as-bitmap - v5.3.3 - * Compiled Tue, 04 Aug 2020 16:23:09 UTC - * - * @pixi/mixin-cache-as-bitmap is licensed under the MIT License. - * http://www.opensource.org/licenses/mit-license - */ - - var _tempMatrix = new Matrix(); - DisplayObject.prototype._cacheAsBitmap = false; - DisplayObject.prototype._cacheData = null; - // figured there's no point adding ALL the extra variables to prototype. - // this model can hold the information needed. This can also be generated on demand as - // most objects are not cached as bitmaps. - /** - * @class - * @ignore - */ - var CacheData = /** @class */ (function () { - function CacheData() { - this.textureCacheId = null; - this.originalRender = null; - this.originalRenderCanvas = null; - this.originalCalculateBounds = null; - this.originalGetLocalBounds = null; - this.originalUpdateTransform = null; - this.originalDestroy = null; - this.originalMask = null; - this.originalFilterArea = null; - this.originalContainsPoint = null; - this.sprite = null; - } - return CacheData; - }()); - Object.defineProperties(DisplayObject.prototype, { - /** - * Set this to true if you want this display object to be cached as a bitmap. - * This basically takes a snap shot of the display object as it is at that moment. It can - * provide a performance benefit for complex static displayObjects. - * To remove simply set this property to `false` - * - * IMPORTANT GOTCHA - Make sure that all your textures are preloaded BEFORE setting this property to true - * as it will take a snapshot of what is currently there. If the textures have not loaded then they will not appear. - * - * @member {boolean} - * @memberof PIXI.DisplayObject# - */ - cacheAsBitmap: { - get: function () { - return this._cacheAsBitmap; - }, - set: function (value) { - if (this._cacheAsBitmap === value) { - return; - } - this._cacheAsBitmap = value; - var data; - if (value) { - if (!this._cacheData) { - this._cacheData = new CacheData(); - } - data = this._cacheData; - data.originalRender = this.render; - data.originalRenderCanvas = this.renderCanvas; - data.originalUpdateTransform = this.updateTransform; - data.originalCalculateBounds = this.calculateBounds; - data.originalGetLocalBounds = this.getLocalBounds; - data.originalDestroy = this.destroy; - data.originalContainsPoint = this.containsPoint; - data.originalMask = this._mask; - data.originalFilterArea = this.filterArea; - this.render = this._renderCached; - this.renderCanvas = this._renderCachedCanvas; - this.destroy = this._cacheAsBitmapDestroy; - } - else { - data = this._cacheData; - if (data.sprite) { - this._destroyCachedDisplayObject(); - } - this.render = data.originalRender; - this.renderCanvas = data.originalRenderCanvas; - this.calculateBounds = data.originalCalculateBounds; - this.getLocalBounds = data.originalGetLocalBounds; - this.destroy = data.originalDestroy; - this.updateTransform = data.originalUpdateTransform; - this.containsPoint = data.originalContainsPoint; - this._mask = data.originalMask; - this.filterArea = data.originalFilterArea; - } - }, - }, - }); - /** - * Renders a cached version of the sprite with WebGL - * - * @private - * @function _renderCached - * @memberof PIXI.DisplayObject# - * @param {PIXI.Renderer} renderer - the WebGL renderer - */ - DisplayObject.prototype._renderCached = function _renderCached(renderer) { - if (!this.visible || this.worldAlpha <= 0 || !this.renderable) { - return; - } - this._initCachedDisplayObject(renderer); - this._cacheData.sprite.transform._worldID = this.transform._worldID; - this._cacheData.sprite.worldAlpha = this.worldAlpha; - this._cacheData.sprite._render(renderer); - }; - /** - * Prepares the WebGL renderer to cache the sprite - * - * @private - * @function _initCachedDisplayObject - * @memberof PIXI.DisplayObject# - * @param {PIXI.Renderer} renderer - the WebGL renderer - */ - DisplayObject.prototype._initCachedDisplayObject = function _initCachedDisplayObject(renderer) { - if (this._cacheData && this._cacheData.sprite) { - return; - } - // make sure alpha is set to 1 otherwise it will get rendered as invisible! - var cacheAlpha = this.alpha; - this.alpha = 1; - // first we flush anything left in the renderer (otherwise it would get rendered to the cached texture) - renderer.batch.flush(); - // this.filters= []; - // next we find the dimensions of the untransformed object - // this function also calls updatetransform on all its children as part of the measuring. - // This means we don't need to update the transform again in this function - // TODO pass an object to clone too? saves having to create a new one each time! - var bounds = this.getLocalBounds(null, true).clone(); - // add some padding! - if (this.filters) { - var padding = this.filters[0].padding; - bounds.pad(padding); - } - bounds.ceil(settings.RESOLUTION); - // for now we cache the current renderTarget that the WebGL renderer is currently using. - // this could be more elegant.. - var cachedRenderTexture = renderer.renderTexture.current; - var cachedSourceFrame = renderer.renderTexture.sourceFrame.clone(); - var cachedProjectionTransform = renderer.projection.transform; - // We also store the filter stack - I will definitely look to change how this works a little later down the line. - // const stack = renderer.filterManager.filterStack; - // this renderTexture will be used to store the cached DisplayObject - var renderTexture = RenderTexture.create({ width: bounds.width, height: bounds.height }); - var textureCacheId = "cacheAsBitmap_" + uid(); - this._cacheData.textureCacheId = textureCacheId; - BaseTexture.addToCache(renderTexture.baseTexture, textureCacheId); - Texture.addToCache(renderTexture, textureCacheId); - // need to set // - var m = this.transform.localTransform.copyTo(_tempMatrix).invert().translate(-bounds.x, -bounds.y); - // set all properties to there original so we can render to a texture - this.render = this._cacheData.originalRender; - renderer.render(this, renderTexture, true, m, false); - // now restore the state be setting the new properties - renderer.projection.transform = cachedProjectionTransform; - renderer.renderTexture.bind(cachedRenderTexture, cachedSourceFrame); - // renderer.filterManager.filterStack = stack; - this.render = this._renderCached; - // the rest is the same as for Canvas - this.updateTransform = this.displayObjectUpdateTransform; - this.calculateBounds = this._calculateCachedBounds; - this.getLocalBounds = this._getCachedLocalBounds; - this._mask = null; - this.filterArea = null; - // create our cached sprite - var cachedSprite = new Sprite(renderTexture); - cachedSprite.transform.worldTransform = this.transform.worldTransform; - cachedSprite.anchor.x = -(bounds.x / bounds.width); - cachedSprite.anchor.y = -(bounds.y / bounds.height); - cachedSprite.alpha = cacheAlpha; - cachedSprite._bounds = this._bounds; - this._cacheData.sprite = cachedSprite; - this.transform._parentID = -1; - // restore the transform of the cached sprite to avoid the nasty flicker.. - if (!this.parent) { - this.enableTempParent(); - this.updateTransform(); - this.disableTempParent(null); - } - else { - this.updateTransform(); - } - // map the hit test.. - this.containsPoint = cachedSprite.containsPoint.bind(cachedSprite); - }; - /** - * Renders a cached version of the sprite with canvas - * - * @private - * @function _renderCachedCanvas - * @memberof PIXI.DisplayObject# - * @param {PIXI.CanvasRenderer} renderer - The canvas renderer - */ - DisplayObject.prototype._renderCachedCanvas = function _renderCachedCanvas(renderer) { - if (!this.visible || this.worldAlpha <= 0 || !this.renderable) { - return; - } - this._initCachedDisplayObjectCanvas(renderer); - this._cacheData.sprite.worldAlpha = this.worldAlpha; - this._cacheData.sprite._renderCanvas(renderer); - }; - // TODO this can be the same as the WebGL version.. will need to do a little tweaking first though.. - /** - * Prepares the Canvas renderer to cache the sprite - * - * @private - * @function _initCachedDisplayObjectCanvas - * @memberof PIXI.DisplayObject# - * @param {PIXI.CanvasRenderer} renderer - The canvas renderer - */ - DisplayObject.prototype._initCachedDisplayObjectCanvas = function _initCachedDisplayObjectCanvas(renderer) { - if (this._cacheData && this._cacheData.sprite) { - return; - } - // get bounds actually transforms the object for us already! - var bounds = this.getLocalBounds(null, true); - var cacheAlpha = this.alpha; - this.alpha = 1; - var cachedRenderTarget = renderer.context; - var cachedProjectionTransform = renderer._projTransform; - bounds.ceil(settings.RESOLUTION); - var renderTexture = RenderTexture.create({ width: bounds.width, height: bounds.height }); - var textureCacheId = "cacheAsBitmap_" + uid(); - this._cacheData.textureCacheId = textureCacheId; - BaseTexture.addToCache(renderTexture.baseTexture, textureCacheId); - Texture.addToCache(renderTexture, textureCacheId); - // need to set // - var m = _tempMatrix; - this.transform.localTransform.copyTo(m); - m.invert(); - m.tx -= bounds.x; - m.ty -= bounds.y; - // m.append(this.transform.worldTransform.) - // set all properties to there original so we can render to a texture - this.renderCanvas = this._cacheData.originalRenderCanvas; - renderer.render(this, renderTexture, true, m, false); - // now restore the state be setting the new properties - renderer.context = cachedRenderTarget; - renderer._projTransform = cachedProjectionTransform; - this.renderCanvas = this._renderCachedCanvas; - // the rest is the same as for WebGL - this.updateTransform = this.displayObjectUpdateTransform; - this.calculateBounds = this._calculateCachedBounds; - this.getLocalBounds = this._getCachedLocalBounds; - this._mask = null; - this.filterArea = null; - // create our cached sprite - var cachedSprite = new Sprite(renderTexture); - cachedSprite.transform.worldTransform = this.transform.worldTransform; - cachedSprite.anchor.x = -(bounds.x / bounds.width); - cachedSprite.anchor.y = -(bounds.y / bounds.height); - cachedSprite.alpha = cacheAlpha; - cachedSprite._bounds = this._bounds; - this._cacheData.sprite = cachedSprite; - this.transform._parentID = -1; - // restore the transform of the cached sprite to avoid the nasty flicker.. - if (!this.parent) { - this.parent = renderer._tempDisplayObjectParent; - this.updateTransform(); - this.parent = null; - } - else { - this.updateTransform(); - } - // map the hit test.. - this.containsPoint = cachedSprite.containsPoint.bind(cachedSprite); - }; - /** - * Calculates the bounds of the cached sprite - * - * @private - */ - DisplayObject.prototype._calculateCachedBounds = function _calculateCachedBounds() { - this._bounds.clear(); - this._cacheData.sprite.transform._worldID = this.transform._worldID; - this._cacheData.sprite._calculateBounds(); - this._bounds.updateID = this._boundsID; - }; - /** - * Gets the bounds of the cached sprite. - * - * @private - * @return {Rectangle} The local bounds. - */ - DisplayObject.prototype._getCachedLocalBounds = function _getCachedLocalBounds() { - return this._cacheData.sprite.getLocalBounds(null); - }; - /** - * Destroys the cached sprite. - * - * @private - */ - DisplayObject.prototype._destroyCachedDisplayObject = function _destroyCachedDisplayObject() { - this._cacheData.sprite._texture.destroy(true); - this._cacheData.sprite = null; - BaseTexture.removeFromCache(this._cacheData.textureCacheId); - Texture.removeFromCache(this._cacheData.textureCacheId); - this._cacheData.textureCacheId = null; - }; - /** - * Destroys the cached object. - * - * @private - * @param {object|boolean} [options] - Options parameter. A boolean will act as if all options - * have been set to that value. - * Used when destroying containers, see the Container.destroy method. - */ - DisplayObject.prototype._cacheAsBitmapDestroy = function _cacheAsBitmapDestroy(options) { - this.cacheAsBitmap = false; - this.destroy(options); - }; - - /*! - * @pixi/mixin-get-child-by-name - v5.3.3 - * Compiled Tue, 04 Aug 2020 16:23:09 UTC - * - * @pixi/mixin-get-child-by-name is licensed under the MIT License. - * http://www.opensource.org/licenses/mit-license - */ - - /** - * The instance name of the object. - * - * @memberof PIXI.DisplayObject# - * @member {string} name - */ - DisplayObject.prototype.name = null; - /** - * Returns the display object in the container. - * - * Recursive searches are done in a preorder traversal. - * - * @method getChildByName - * @memberof PIXI.Container# - * @param {string} name - Instance name. - * @param {boolean}[deep=false] - Whether to search recursively - * @return {PIXI.DisplayObject} The child with the specified name. - */ - Container.prototype.getChildByName = function getChildByName(name, deep) { - for (var i = 0, j = this.children.length; i < j; i++) { - if (this.children[i].name === name) { - return this.children[i]; - } - } - if (deep) { - for (var i = 0, j = this.children.length; i < j; i++) { - var child = this.children[i]; - if (!child.getChildByName) { - continue; - } - var target = this.children[i].getChildByName(name, true); - if (target) { - return target; - } - } - } - return null; - }; - - /*! - * @pixi/mixin-get-global-position - v5.3.3 - * Compiled Tue, 04 Aug 2020 16:23:09 UTC - * - * @pixi/mixin-get-global-position is licensed under the MIT License. - * http://www.opensource.org/licenses/mit-license - */ - - /** - * Returns the global position of the displayObject. Does not depend on object scale, rotation and pivot. - * - * @method getGlobalPosition - * @memberof PIXI.DisplayObject# - * @param {PIXI.Point} [point=new PIXI.Point()] - The point to write the global value to. - * @param {boolean} [skipUpdate=false] - Setting to true will stop the transforms of the scene graph from - * being updated. This means the calculation returned MAY be out of date BUT will give you a - * nice performance boost. - * @return {PIXI.Point} The updated point. - */ - DisplayObject.prototype.getGlobalPosition = function getGlobalPosition(point, skipUpdate) { - if (point === void 0) { point = new Point(); } - if (skipUpdate === void 0) { skipUpdate = false; } - if (this.parent) { - this.parent.toGlobal(this.position, point, skipUpdate); - } - else { - point.x = this.position.x; - point.y = this.position.y; - } - return point; - }; - - /*! ***************************************************************************** - Copyright (c) Microsoft Corporation. All rights reserved. - Licensed under the Apache License, Version 2.0 (the "License"); you may not use - this file except in compliance with the License. You may obtain a copy of the - License at http://www.apache.org/licenses/LICENSE-2.0 + function __extends$8(d, b) { + extendStatics$8(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + } + + /* eslint-disable max-len */ + /** + * Normalized parsed data from .fnt files. + * @memberof PIXI + */ + var BitmapFontData = /** @class */ (function () { + function BitmapFontData() { + this.info = []; + this.common = []; + this.page = []; + this.char = []; + this.kerning = []; + this.distanceField = []; + } + return BitmapFontData; + }()); + + /** + * BitmapFont format that's Text-based. + * @private + */ + var TextFormat = /** @class */ (function () { + function TextFormat() { + } + /** + * Check if resource refers to txt font data. + * @param data + * @returns - True if resource could be treated as font data, false otherwise. + */ + TextFormat.test = function (data) { + return typeof data === 'string' && data.indexOf('info face=') === 0; + }; + /** + * Convert text font data to a javascript object. + * @param txt - Raw string data to be converted + * @returns - Parsed font data + */ + TextFormat.parse = function (txt) { + // Retrieve data item + var items = txt.match(/^[a-z]+\s+.+$/gm); + var rawData = { + info: [], + common: [], + page: [], + char: [], + chars: [], + kerning: [], + kernings: [], + distanceField: [], + }; + for (var i in items) { + // Extract item name + var name = items[i].match(/^[a-z]+/gm)[0]; + // Extract item attribute list as string ex.: "width=10" + var attributeList = items[i].match(/[a-zA-Z]+=([^\s"']+|"([^"]*)")/gm); + // Convert attribute list into an object + var itemData = {}; + for (var i_1 in attributeList) { + // Split key-value pairs + var split = attributeList[i_1].split('='); + var key = split[0]; + // Remove eventual quotes from value + var strValue = split[1].replace(/"/gm, ''); + // Try to convert value into float + var floatValue = parseFloat(strValue); + // Use string value case float value is NaN + var value = isNaN(floatValue) ? strValue : floatValue; + itemData[key] = value; + } + // Push current item to the resulting data + rawData[name].push(itemData); + } + var font = new BitmapFontData(); + rawData.info.forEach(function (info) { return font.info.push({ + face: info.face, + size: parseInt(info.size, 10), + }); }); + rawData.common.forEach(function (common) { return font.common.push({ + lineHeight: parseInt(common.lineHeight, 10), + }); }); + rawData.page.forEach(function (page) { return font.page.push({ + id: parseInt(page.id, 10), + file: page.file, + }); }); + rawData.char.forEach(function (char) { return font.char.push({ + id: parseInt(char.id, 10), + page: parseInt(char.page, 10), + x: parseInt(char.x, 10), + y: parseInt(char.y, 10), + width: parseInt(char.width, 10), + height: parseInt(char.height, 10), + xoffset: parseInt(char.xoffset, 10), + yoffset: parseInt(char.yoffset, 10), + xadvance: parseInt(char.xadvance, 10), + }); }); + rawData.kerning.forEach(function (kerning) { return font.kerning.push({ + first: parseInt(kerning.first, 10), + second: parseInt(kerning.second, 10), + amount: parseInt(kerning.amount, 10), + }); }); + rawData.distanceField.forEach(function (df) { return font.distanceField.push({ + distanceRange: parseInt(df.distanceRange, 10), + fieldType: df.fieldType, + }); }); + return font; + }; + return TextFormat; + }()); + + /** + * BitmapFont format that's XML-based. + * @private + */ + var XMLFormat = /** @class */ (function () { + function XMLFormat() { + } + /** + * Check if resource refers to xml font data. + * @param data + * @returns - True if resource could be treated as font data, false otherwise. + */ + XMLFormat.test = function (data) { + return data instanceof XMLDocument + && data.getElementsByTagName('page').length + && data.getElementsByTagName('info')[0].getAttribute('face') !== null; + }; + /** + * Convert the XML into BitmapFontData that we can use. + * @param xml + * @returns - Data to use for BitmapFont + */ + XMLFormat.parse = function (xml) { + var data = new BitmapFontData(); + var info = xml.getElementsByTagName('info'); + var common = xml.getElementsByTagName('common'); + var page = xml.getElementsByTagName('page'); + var char = xml.getElementsByTagName('char'); + var kerning = xml.getElementsByTagName('kerning'); + var distanceField = xml.getElementsByTagName('distanceField'); + for (var i = 0; i < info.length; i++) { + data.info.push({ + face: info[i].getAttribute('face'), + size: parseInt(info[i].getAttribute('size'), 10), + }); + } + for (var i = 0; i < common.length; i++) { + data.common.push({ + lineHeight: parseInt(common[i].getAttribute('lineHeight'), 10), + }); + } + for (var i = 0; i < page.length; i++) { + data.page.push({ + id: parseInt(page[i].getAttribute('id'), 10) || 0, + file: page[i].getAttribute('file'), + }); + } + for (var i = 0; i < char.length; i++) { + var letter = char[i]; + data.char.push({ + id: parseInt(letter.getAttribute('id'), 10), + page: parseInt(letter.getAttribute('page'), 10) || 0, + x: parseInt(letter.getAttribute('x'), 10), + y: parseInt(letter.getAttribute('y'), 10), + width: parseInt(letter.getAttribute('width'), 10), + height: parseInt(letter.getAttribute('height'), 10), + xoffset: parseInt(letter.getAttribute('xoffset'), 10), + yoffset: parseInt(letter.getAttribute('yoffset'), 10), + xadvance: parseInt(letter.getAttribute('xadvance'), 10), + }); + } + for (var i = 0; i < kerning.length; i++) { + data.kerning.push({ + first: parseInt(kerning[i].getAttribute('first'), 10), + second: parseInt(kerning[i].getAttribute('second'), 10), + amount: parseInt(kerning[i].getAttribute('amount'), 10), + }); + } + for (var i = 0; i < distanceField.length; i++) { + data.distanceField.push({ + fieldType: distanceField[i].getAttribute('fieldType'), + distanceRange: parseInt(distanceField[i].getAttribute('distanceRange'), 10), + }); + } + return data; + }; + return XMLFormat; + }()); + + /** + * BitmapFont format that's XML-based. + * @private + */ + var XMLStringFormat = /** @class */ (function () { + function XMLStringFormat() { + } + /** + * Check if resource refers to text xml font data. + * @param data + * @returns - True if resource could be treated as font data, false otherwise. + */ + XMLStringFormat.test = function (data) { + if (typeof data === 'string' && data.indexOf('') > -1) { + var xml = new globalThis.DOMParser().parseFromString(data, 'text/xml'); + return XMLFormat.test(xml); + } + return false; + }; + /** + * Convert the text XML into BitmapFontData that we can use. + * @param xmlTxt + * @returns - Data to use for BitmapFont + */ + XMLStringFormat.parse = function (xmlTxt) { + var xml = new globalThis.DOMParser().parseFromString(xmlTxt, 'text/xml'); + return XMLFormat.parse(xml); + }; + return XMLStringFormat; + }()); + + // Registered formats, maybe make this extensible in the future? + var formats = [ + TextFormat, + XMLFormat, + XMLStringFormat ]; + /** + * Auto-detect BitmapFont parsing format based on data. + * @private + * @param {any} data - Data to detect format + * @returns {any} Format or null + */ + function autoDetectFormat(data) { + for (var i = 0; i < formats.length; i++) { + if (formats[i].test(data)) { + return formats[i]; + } + } + return null; + } + + // TODO: Prevent code duplication b/w generateFillStyle & Text#generateFillStyle + /** + * Generates the fill style. Can automatically generate a gradient based on the fill style being an array + * @private + * @param canvas + * @param context + * @param {object} style - The style. + * @param resolution + * @param {string[]} lines - The lines of text. + * @param metrics + * @returns {string|number|CanvasGradient} The fill style + */ + function generateFillStyle(canvas, context, style, resolution, lines, metrics) { + // TODO: Can't have different types for getter and setter. The getter shouldn't have the number type as + // the setter converts to string. See this thread for more details: + // https://github.com/microsoft/TypeScript/issues/2521 + var fillStyle = style.fill; + if (!Array.isArray(fillStyle)) { + return fillStyle; + } + else if (fillStyle.length === 1) { + return fillStyle[0]; + } + // the gradient will be evenly spaced out according to how large the array is. + // ['#FF0000', '#00FF00', '#0000FF'] would created stops at 0.25, 0.5 and 0.75 + var gradient; + // a dropshadow will enlarge the canvas and result in the gradient being + // generated with the incorrect dimensions + var dropShadowCorrection = (style.dropShadow) ? style.dropShadowDistance : 0; + // should also take padding into account, padding can offset the gradient + var padding = style.padding || 0; + var width = (canvas.width / resolution) - dropShadowCorrection - (padding * 2); + var height = (canvas.height / resolution) - dropShadowCorrection - (padding * 2); + // make a copy of the style settings, so we can manipulate them later + var fill = fillStyle.slice(); + var fillGradientStops = style.fillGradientStops.slice(); + // wanting to evenly distribute the fills. So an array of 4 colours should give fills of 0.25, 0.5 and 0.75 + if (!fillGradientStops.length) { + var lengthPlus1 = fill.length + 1; + for (var i = 1; i < lengthPlus1; ++i) { + fillGradientStops.push(i / lengthPlus1); + } + } + // stop the bleeding of the last gradient on the line above to the top gradient of the this line + // by hard defining the first gradient colour at point 0, and last gradient colour at point 1 + fill.unshift(fillStyle[0]); + fillGradientStops.unshift(0); + fill.push(fillStyle[fillStyle.length - 1]); + fillGradientStops.push(1); + if (style.fillGradientType === exports.TEXT_GRADIENT.LINEAR_VERTICAL) { + // start the gradient at the top center of the canvas, and end at the bottom middle of the canvas + gradient = context.createLinearGradient(width / 2, padding, width / 2, height + padding); + // we need to repeat the gradient so that each individual line of text has the same vertical gradient effect + // ['#FF0000', '#00FF00', '#0000FF'] over 2 lines would create stops at 0.125, 0.25, 0.375, 0.625, 0.75, 0.875 + // There's potential for floating point precision issues at the seams between gradient repeats. + // The loop below generates the stops in order, so track the last generated one to prevent + // floating point precision from making us go the teeniest bit backwards, resulting in + // the first and last colors getting swapped. + var lastIterationStop = 0; + // Actual height of the text itself, not counting spacing for lineHeight/leading/dropShadow etc + var textHeight = metrics.fontProperties.fontSize + style.strokeThickness; + // textHeight, but as a 0-1 size in global gradient stop space + var gradStopLineHeight = textHeight / height; + for (var i = 0; i < lines.length; i++) { + var thisLineTop = metrics.lineHeight * i; + for (var j = 0; j < fill.length; j++) { + // 0-1 stop point for the current line, multiplied to global space afterwards + var lineStop = 0; + if (typeof fillGradientStops[j] === 'number') { + lineStop = fillGradientStops[j]; + } + else { + lineStop = j / fill.length; + } + var globalStop = (thisLineTop / height) + (lineStop * gradStopLineHeight); + // Prevent color stop generation going backwards from floating point imprecision + var clampedStop = Math.max(lastIterationStop, globalStop); + clampedStop = Math.min(clampedStop, 1); // Cap at 1 as well for safety's sake to avoid a possible throw. + gradient.addColorStop(clampedStop, fill[j]); + lastIterationStop = clampedStop; + } + } + } + else { + // start the gradient at the center left of the canvas, and end at the center right of the canvas + gradient = context.createLinearGradient(padding, height / 2, width + padding, height / 2); + // can just evenly space out the gradients in this case, as multiple lines makes no difference + // to an even left to right gradient + var totalIterations = fill.length + 1; + var currentIteration = 1; + for (var i = 0; i < fill.length; i++) { + var stop = void 0; + if (typeof fillGradientStops[i] === 'number') { + stop = fillGradientStops[i]; + } + else { + stop = currentIteration / totalIterations; + } + gradient.addColorStop(stop, fill[i]); + currentIteration++; + } + } + return gradient; + } + + // TODO: Prevent code duplication b/w drawGlyph & Text#updateText + /** + * Draws the glyph `metrics.text` on the given canvas. + * + * Ignored because not directly exposed. + * @ignore + * @param {HTMLCanvasElement} canvas + * @param {CanvasRenderingContext2D} context + * @param {TextMetrics} metrics + * @param {number} x + * @param {number} y + * @param {number} resolution + * @param {TextStyle} style + */ + function drawGlyph(canvas, context, metrics, x, y, resolution, style) { + var char = metrics.text; + var fontProperties = metrics.fontProperties; + context.translate(x, y); + context.scale(resolution, resolution); + var tx = style.strokeThickness / 2; + var ty = -(style.strokeThickness / 2); + context.font = style.toFontString(); + context.lineWidth = style.strokeThickness; + context.textBaseline = style.textBaseline; + context.lineJoin = style.lineJoin; + context.miterLimit = style.miterLimit; + // set canvas text styles + context.fillStyle = generateFillStyle(canvas, context, style, resolution, [char], metrics); + context.strokeStyle = style.stroke; + if (style.dropShadow) { + var dropShadowColor = style.dropShadowColor; + var rgb = hex2rgb(typeof dropShadowColor === 'number' ? dropShadowColor : string2hex(dropShadowColor)); + var dropShadowBlur = style.dropShadowBlur * resolution; + var dropShadowDistance = style.dropShadowDistance * resolution; + context.shadowColor = "rgba(" + rgb[0] * 255 + "," + rgb[1] * 255 + "," + rgb[2] * 255 + "," + style.dropShadowAlpha + ")"; + context.shadowBlur = dropShadowBlur; + context.shadowOffsetX = Math.cos(style.dropShadowAngle) * dropShadowDistance; + context.shadowOffsetY = Math.sin(style.dropShadowAngle) * dropShadowDistance; + } + else { + context.shadowColor = 'black'; + context.shadowBlur = 0; + context.shadowOffsetX = 0; + context.shadowOffsetY = 0; + } + if (style.stroke && style.strokeThickness) { + context.strokeText(char, tx, ty + metrics.lineHeight - fontProperties.descent); + } + if (style.fill) { + context.fillText(char, tx, ty + metrics.lineHeight - fontProperties.descent); + } + context.setTransform(1, 0, 0, 1, 0, 0); // defaults needed for older browsers (e.g. Opera 29) + context.fillStyle = 'rgba(0, 0, 0, 0)'; + } + + /** + * Ponyfill for IE because it doesn't support `Array.from` + * @param text + * @private + */ + function splitTextToCharacters(text) { + return Array.from ? Array.from(text) : text.split(''); + } + + /** + * Processes the passed character set data and returns a flattened array of all the characters. + * + * Ignored because not directly exposed. + * @ignore + * @param {string | string[] | string[][] } chars + * @returns {string[]} the flattened array of characters + */ + function resolveCharacters(chars) { + // Split the chars string into individual characters + if (typeof chars === 'string') { + chars = [chars]; + } + // Handle an array of characters+ranges + var result = []; + for (var i = 0, j = chars.length; i < j; i++) { + var item = chars[i]; + // Handle range delimited by start/end chars + if (Array.isArray(item)) { + if (item.length !== 2) { + throw new Error("[BitmapFont]: Invalid character range length, expecting 2 got " + item.length + "."); + } + var startCode = item[0].charCodeAt(0); + var endCode = item[1].charCodeAt(0); + if (endCode < startCode) { + throw new Error('[BitmapFont]: Invalid character range.'); + } + for (var i_1 = startCode, j_1 = endCode; i_1 <= j_1; i_1++) { + result.push(String.fromCharCode(i_1)); + } + } + // Handle a character set string + else { + result.push.apply(result, splitTextToCharacters(item)); + } + } + if (result.length === 0) { + throw new Error('[BitmapFont]: Empty set when resolving characters.'); + } + return result; + } + + /** + * Ponyfill for IE because it doesn't support `codePointAt` + * @param str + * @private + */ + function extractCharCode(str) { + return str.codePointAt ? str.codePointAt(0) : str.charCodeAt(0); + } + + /** + * BitmapFont represents a typeface available for use with the BitmapText class. Use the `install` + * method for adding a font to be used. + * @memberof PIXI + */ + var BitmapFont = /** @class */ (function () { + /** + * @param data + * @param textures + * @param ownsTextures - Setting to `true` will destroy page textures + * when the font is uninstalled. + */ + function BitmapFont(data, textures, ownsTextures) { + var _a, _b; + var info = data.info[0]; + var common = data.common[0]; + var page = data.page[0]; + var distanceField = data.distanceField[0]; + var res = getResolutionOfUrl(page.file); + var pageTextures = {}; + this._ownsTextures = ownsTextures; + this.font = info.face; + this.size = info.size; + this.lineHeight = common.lineHeight / res; + this.chars = {}; + this.pageTextures = pageTextures; + // Convert the input Texture, Textures or object + // into a page Texture lookup by "id" + for (var i = 0; i < data.page.length; i++) { + var _c = data.page[i], id = _c.id, file = _c.file; + pageTextures[id] = textures instanceof Array + ? textures[i] : textures[file]; + // only MSDF and SDF fonts need no-premultiplied-alpha + if ((distanceField === null || distanceField === void 0 ? void 0 : distanceField.fieldType) && distanceField.fieldType !== 'none') { + pageTextures[id].baseTexture.alphaMode = exports.ALPHA_MODES.NO_PREMULTIPLIED_ALPHA; + } + } + // parse letters + for (var i = 0; i < data.char.length; i++) { + var _d = data.char[i], id = _d.id, page_1 = _d.page; + var _e = data.char[i], x = _e.x, y = _e.y, width = _e.width, height = _e.height, xoffset = _e.xoffset, yoffset = _e.yoffset, xadvance = _e.xadvance; + x /= res; + y /= res; + width /= res; + height /= res; + xoffset /= res; + yoffset /= res; + xadvance /= res; + var rect = new Rectangle(x + (pageTextures[page_1].frame.x / res), y + (pageTextures[page_1].frame.y / res), width, height); + this.chars[id] = { + xOffset: xoffset, + yOffset: yoffset, + xAdvance: xadvance, + kerning: {}, + texture: new Texture(pageTextures[page_1].baseTexture, rect), + page: page_1, + }; + } + // parse kernings + for (var i = 0; i < data.kerning.length; i++) { + var _f = data.kerning[i], first = _f.first, second = _f.second, amount = _f.amount; + first /= res; + second /= res; + amount /= res; + if (this.chars[second]) { + this.chars[second].kerning[first] = amount; + } + } + // Store distance field information + this.distanceFieldRange = distanceField === null || distanceField === void 0 ? void 0 : distanceField.distanceRange; + this.distanceFieldType = (_b = (_a = distanceField === null || distanceField === void 0 ? void 0 : distanceField.fieldType) === null || _a === void 0 ? void 0 : _a.toLowerCase()) !== null && _b !== void 0 ? _b : 'none'; + } + /** Remove references to created glyph textures. */ + BitmapFont.prototype.destroy = function () { + for (var id in this.chars) { + this.chars[id].texture.destroy(); + this.chars[id].texture = null; + } + for (var id in this.pageTextures) { + if (this._ownsTextures) { + this.pageTextures[id].destroy(true); + } + this.pageTextures[id] = null; + } + // Set readonly null. + this.chars = null; + this.pageTextures = null; + }; + /** + * Register a new bitmap font. + * @param data - The + * characters map that could be provided as xml or raw string. + * @param textures - List of textures for each page. + * @param ownsTextures - Set to `true` to destroy page textures + * when the font is uninstalled. By default fonts created with + * `BitmapFont.from` or from the `BitmapFontLoader` are `true`. + * @returns {PIXI.BitmapFont} Result font object with font, size, lineHeight + * and char fields. + */ + BitmapFont.install = function (data, textures, ownsTextures) { + var fontData; + if (data instanceof BitmapFontData) { + fontData = data; + } + else { + var format = autoDetectFormat(data); + if (!format) { + throw new Error('Unrecognized data format for font.'); + } + fontData = format.parse(data); + } + // Single texture, convert to list + if (textures instanceof Texture) { + textures = [textures]; + } + var font = new BitmapFont(fontData, textures, ownsTextures); + BitmapFont.available[font.font] = font; + return font; + }; + /** + * Remove bitmap font by name. + * @param name - Name of the font to uninstall. + */ + BitmapFont.uninstall = function (name) { + var font = BitmapFont.available[name]; + if (!font) { + throw new Error("No font found named '" + name + "'"); + } + font.destroy(); + delete BitmapFont.available[name]; + }; + /** + * Generates a bitmap-font for the given style and character set. This does not support + * kernings yet. With `style` properties, only the following non-layout properties are used: + * + * - {@link PIXI.TextStyle#dropShadow|dropShadow} + * - {@link PIXI.TextStyle#dropShadowDistance|dropShadowDistance} + * - {@link PIXI.TextStyle#dropShadowColor|dropShadowColor} + * - {@link PIXI.TextStyle#dropShadowBlur|dropShadowBlur} + * - {@link PIXI.TextStyle#dropShadowAngle|dropShadowAngle} + * - {@link PIXI.TextStyle#fill|fill} + * - {@link PIXI.TextStyle#fillGradientStops|fillGradientStops} + * - {@link PIXI.TextStyle#fillGradientType|fillGradientType} + * - {@link PIXI.TextStyle#fontFamily|fontFamily} + * - {@link PIXI.TextStyle#fontSize|fontSize} + * - {@link PIXI.TextStyle#fontVariant|fontVariant} + * - {@link PIXI.TextStyle#fontWeight|fontWeight} + * - {@link PIXI.TextStyle#lineJoin|lineJoin} + * - {@link PIXI.TextStyle#miterLimit|miterLimit} + * - {@link PIXI.TextStyle#stroke|stroke} + * - {@link PIXI.TextStyle#strokeThickness|strokeThickness} + * - {@link PIXI.TextStyle#textBaseline|textBaseline} + * @param name - The name of the custom font to use with BitmapText. + * @param textStyle - Style options to render with BitmapFont. + * @param options - Setup options for font or name of the font. + * @param {string|string[]|string[][]} [options.chars=PIXI.BitmapFont.ALPHANUMERIC] - characters included + * in the font set. You can also use ranges. For example, `[['a', 'z'], ['A', 'Z'], "!@#$%^&*()~{}[] "]`. + * Don't forget to include spaces ' ' in your character set! + * @param {number} [options.resolution=1] - Render resolution for glyphs. + * @param {number} [options.textureWidth=512] - Optional width of atlas, smaller values to reduce memory. + * @param {number} [options.textureHeight=512] - Optional height of atlas, smaller values to reduce memory. + * @param {number} [options.padding=4] - Padding between glyphs on texture atlas. + * @returns Font generated by style options. + * @example + * PIXI.BitmapFont.from("TitleFont", { + * fontFamily: "Arial", + * fontSize: 12, + * strokeThickness: 2, + * fill: "purple" + * }); + * + * const title = new PIXI.BitmapText("This is the title", { fontName: "TitleFont" }); + */ + BitmapFont.from = function (name, textStyle, options) { + if (!name) { + throw new Error('[BitmapFont] Property `name` is required.'); + } + var _a = Object.assign({}, BitmapFont.defaultOptions, options), chars = _a.chars, padding = _a.padding, resolution = _a.resolution, textureWidth = _a.textureWidth, textureHeight = _a.textureHeight; + var charsList = resolveCharacters(chars); + var style = textStyle instanceof TextStyle ? textStyle : new TextStyle(textStyle); + var lineWidth = textureWidth; + var fontData = new BitmapFontData(); + fontData.info[0] = { + face: style.fontFamily, + size: style.fontSize, + }; + fontData.common[0] = { + lineHeight: style.fontSize, + }; + var positionX = 0; + var positionY = 0; + var canvas; + var context; + var baseTexture; + var maxCharHeight = 0; + var textures = []; + for (var i = 0; i < charsList.length; i++) { + if (!canvas) { + canvas = settings$1.ADAPTER.createCanvas(); + canvas.width = textureWidth; + canvas.height = textureHeight; + context = canvas.getContext('2d'); + baseTexture = new BaseTexture(canvas, { resolution: resolution }); + textures.push(new Texture(baseTexture)); + fontData.page.push({ + id: textures.length - 1, + file: '', + }); + } + // Measure glyph dimensions + var metrics = TextMetrics.measureText(charsList[i], style, false, canvas); + var width = metrics.width; + var height = Math.ceil(metrics.height); + // This is ugly - but italics are given more space so they don't overlap + var textureGlyphWidth = Math.ceil((style.fontStyle === 'italic' ? 2 : 1) * width); + // Can't fit char anymore: next canvas please! + if (positionY >= textureHeight - (height * resolution)) { + if (positionY === 0) { + // We don't want user debugging an infinite loop (or do we? :) + throw new Error("[BitmapFont] textureHeight " + textureHeight + "px is " + + ("too small for " + style.fontSize + "px fonts")); + } + --i; + // Create new atlas once current has filled up + canvas = null; + context = null; + baseTexture = null; + positionY = 0; + positionX = 0; + maxCharHeight = 0; + continue; + } + maxCharHeight = Math.max(height + metrics.fontProperties.descent, maxCharHeight); + // Wrap line once full row has been rendered + if ((textureGlyphWidth * resolution) + positionX >= lineWidth) { + --i; + positionY += maxCharHeight * resolution; + positionY = Math.ceil(positionY); + positionX = 0; + maxCharHeight = 0; + continue; + } + drawGlyph(canvas, context, metrics, positionX, positionY, resolution, style); + // Unique (numeric) ID mapping to this glyph + var id = extractCharCode(metrics.text); + // Create a texture holding just the glyph + fontData.char.push({ + id: id, + page: textures.length - 1, + x: positionX / resolution, + y: positionY / resolution, + width: textureGlyphWidth, + height: height, + xoffset: 0, + yoffset: 0, + xadvance: Math.ceil(width + - (style.dropShadow ? style.dropShadowDistance : 0) + - (style.stroke ? style.strokeThickness : 0)), + }); + positionX += (textureGlyphWidth + (2 * padding)) * resolution; + positionX = Math.ceil(positionX); + } + // Brute-force kerning info, this can be expensive b/c it's an O(n²), + // but we're using measureText which is native and fast. + for (var i = 0, len = charsList.length; i < len; i++) { + var first = charsList[i]; + for (var j = 0; j < len; j++) { + var second = charsList[j]; + var c1 = context.measureText(first).width; + var c2 = context.measureText(second).width; + var total = context.measureText(first + second).width; + var amount = total - (c1 + c2); + if (amount) { + fontData.kerning.push({ + first: extractCharCode(first), + second: extractCharCode(second), + amount: amount, + }); + } + } + } + var font = new BitmapFont(fontData, textures, true); + // Make it easier to replace a font + if (BitmapFont.available[name] !== undefined) { + BitmapFont.uninstall(name); + } + BitmapFont.available[name] = font; + return font; + }; + /** + * This character set includes all the letters in the alphabet (both lower- and upper- case). + * @type {string[][]} + * @example + * BitmapFont.from("ExampleFont", style, { chars: BitmapFont.ALPHA }) + */ + BitmapFont.ALPHA = [['a', 'z'], ['A', 'Z'], ' ']; + /** + * This character set includes all decimal digits (from 0 to 9). + * @type {string[][]} + * @example + * BitmapFont.from("ExampleFont", style, { chars: BitmapFont.NUMERIC }) + */ + BitmapFont.NUMERIC = [['0', '9']]; + /** + * This character set is the union of `BitmapFont.ALPHA` and `BitmapFont.NUMERIC`. + * @type {string[][]} + */ + BitmapFont.ALPHANUMERIC = [['a', 'z'], ['A', 'Z'], ['0', '9'], ' ']; + /** + * This character set consists of all the ASCII table. + * @member {string[][]} + * @see http://www.asciitable.com/ + */ + BitmapFont.ASCII = [[' ', '~']]; + /** + * Collection of default options when using `BitmapFont.from`. + * @property {number} [resolution=1] - + * @property {number} [textureWidth=512] - + * @property {number} [textureHeight=512] - + * @property {number} [padding=4] - + * @property {string|string[]|string[][]} chars = PIXI.BitmapFont.ALPHANUMERIC + */ + BitmapFont.defaultOptions = { + resolution: 1, + textureWidth: 512, + textureHeight: 512, + padding: 4, + chars: BitmapFont.ALPHANUMERIC, + }; + /** Collection of available/installed fonts. */ + BitmapFont.available = {}; + return BitmapFont; + }()); + + var msdfFrag = "// Pixi texture info\r\nvarying vec2 vTextureCoord;\r\nuniform sampler2D uSampler;\r\n\r\n// Tint\r\nuniform vec4 uColor;\r\n\r\n// on 2D applications fwidth is screenScale / glyphAtlasScale * distanceFieldRange\r\nuniform float uFWidth;\r\n\r\nvoid main(void) {\r\n\r\n // To stack MSDF and SDF we need a non-pre-multiplied-alpha texture.\r\n vec4 texColor = texture2D(uSampler, vTextureCoord);\r\n\r\n // MSDF\r\n float median = texColor.r + texColor.g + texColor.b -\r\n min(texColor.r, min(texColor.g, texColor.b)) -\r\n max(texColor.r, max(texColor.g, texColor.b));\r\n // SDF\r\n median = min(median, texColor.a);\r\n\r\n float screenPxDistance = uFWidth * (median - 0.5);\r\n float alpha = clamp(screenPxDistance + 0.5, 0.0, 1.0);\r\n\r\n // NPM Textures, NPM outputs\r\n gl_FragColor = vec4(uColor.rgb, uColor.a * alpha);\r\n\r\n}\r\n"; + + var msdfVert = "// Mesh material default fragment\r\nattribute vec2 aVertexPosition;\r\nattribute vec2 aTextureCoord;\r\n\r\nuniform mat3 projectionMatrix;\r\nuniform mat3 translationMatrix;\r\nuniform mat3 uTextureMatrix;\r\n\r\nvarying vec2 vTextureCoord;\r\n\r\nvoid main(void)\r\n{\r\n gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\r\n\r\n vTextureCoord = (uTextureMatrix * vec3(aTextureCoord, 1.0)).xy;\r\n}\r\n"; + + // If we ever need more than two pools, please make a Dict or something better. + var pageMeshDataDefaultPageMeshData = []; + var pageMeshDataMSDFPageMeshData = []; + var charRenderDataPool = []; + /** + * A BitmapText object will create a line or multiple lines of text using bitmap font. + * + * The primary advantage of this class over Text is that all of your textures are pre-generated and loading, + * meaning that rendering is fast, and changing text has no performance implications. + * + * Supporting character sets other than latin, such as CJK languages, may be impractical due to the number of characters. + * + * To split a line you can use '\n', '\r' or '\r\n' in your string. + * + * PixiJS can auto-generate fonts on-the-fly using BitmapFont or use fnt files provided by: + * http://www.angelcode.com/products/bmfont/ for Windows or + * http://www.bmglyph.com/ for Mac. + * + * You can also use SDF, MSDF and MTSDF BitmapFonts for vector-like scaling appearance provided by: + * https://github.com/soimy/msdf-bmfont-xml for SDF and MSDF fnt files or + * https://github.com/Chlumsky/msdf-atlas-gen for SDF, MSDF and MTSDF json files + * + * A BitmapText can only be created when the font is loaded. + * + * ```js + * // in this case the font is in a file called 'desyrel.fnt' + * let bitmapText = new PIXI.BitmapText("text using a fancy font!", { + * fontName: "Desyrel", + * fontSize: 35, + * align: "right" + * }); + * ``` + * @memberof PIXI + */ + var BitmapText = /** @class */ (function (_super) { + __extends$8(BitmapText, _super); + /** + * @param text - A string that you would like the text to display. + * @param style - The style parameters. + * @param {string} style.fontName - The installed BitmapFont name. + * @param {number} [style.fontSize] - The size of the font in pixels, e.g. 24. If undefined, + *. this will default to the BitmapFont size. + * @param {string} [style.align='left'] - Alignment for multiline text ('left', 'center', 'right' or 'justify'), + * does not affect single line text. + * @param {number} [style.tint=0xFFFFFF] - The tint color. + * @param {number} [style.letterSpacing=0] - The amount of spacing between letters. + * @param {number} [style.maxWidth=0] - The max width of the text before line wrapping. + */ + function BitmapText(text, style) { + if (style === void 0) { style = {}; } + var _this = _super.call(this) || this; + /** + * Private tracker for the current tint. + * @private + */ + _this._tint = 0xFFFFFF; + // Apply the defaults + var _a = Object.assign({}, BitmapText.styleDefaults, style), align = _a.align, tint = _a.tint, maxWidth = _a.maxWidth, letterSpacing = _a.letterSpacing, fontName = _a.fontName, fontSize = _a.fontSize; + if (!BitmapFont.available[fontName]) { + throw new Error("Missing BitmapFont \"" + fontName + "\""); + } + _this._activePagesMeshData = []; + _this._textWidth = 0; + _this._textHeight = 0; + _this._align = align; + _this._tint = tint; + _this._fontName = fontName; + _this._fontSize = fontSize || BitmapFont.available[fontName].size; + _this.text = text; + _this._maxWidth = maxWidth; + _this._maxLineHeight = 0; + _this._letterSpacing = letterSpacing; + _this._anchor = new ObservablePoint(function () { _this.dirty = true; }, _this, 0, 0); + _this._roundPixels = settings$1.ROUND_PIXELS; + _this.dirty = true; + _this._resolution = settings$1.RESOLUTION; + _this._autoResolution = true; + _this._textureCache = {}; + return _this; + } + /** Renders text and updates it when needed. This should only be called if the BitmapFont is regenerated. */ + BitmapText.prototype.updateText = function () { + var _a; + var data = BitmapFont.available[this._fontName]; + var scale = this._fontSize / data.size; + var pos = new Point(); + var chars = []; + var lineWidths = []; + var lineSpaces = []; + var text = this._text.replace(/(?:\r\n|\r)/g, '\n') || ' '; + var charsInput = splitTextToCharacters(text); + var maxWidth = this._maxWidth * data.size / this._fontSize; + var pageMeshDataPool = data.distanceFieldType === 'none' + ? pageMeshDataDefaultPageMeshData : pageMeshDataMSDFPageMeshData; + var prevCharCode = null; + var lastLineWidth = 0; + var maxLineWidth = 0; + var line = 0; + var lastBreakPos = -1; + var lastBreakWidth = 0; + var spacesRemoved = 0; + var maxLineHeight = 0; + var spaceCount = 0; + for (var i = 0; i < charsInput.length; i++) { + var char = charsInput[i]; + var charCode = extractCharCode(char); + if ((/(?:\s)/).test(char)) { + lastBreakPos = i; + lastBreakWidth = lastLineWidth; + spaceCount++; + } + if (char === '\r' || char === '\n') { + lineWidths.push(lastLineWidth); + lineSpaces.push(-1); + maxLineWidth = Math.max(maxLineWidth, lastLineWidth); + ++line; + ++spacesRemoved; + pos.x = 0; + pos.y += data.lineHeight; + prevCharCode = null; + spaceCount = 0; + continue; + } + var charData = data.chars[charCode]; + if (!charData) { + continue; + } + if (prevCharCode && charData.kerning[prevCharCode]) { + pos.x += charData.kerning[prevCharCode]; + } + var charRenderData = charRenderDataPool.pop() || { + texture: Texture.EMPTY, + line: 0, + charCode: 0, + prevSpaces: 0, + position: new Point(), + }; + charRenderData.texture = charData.texture; + charRenderData.line = line; + charRenderData.charCode = charCode; + charRenderData.position.x = pos.x + charData.xOffset + (this._letterSpacing / 2); + charRenderData.position.y = pos.y + charData.yOffset; + charRenderData.prevSpaces = spaceCount; + chars.push(charRenderData); + lastLineWidth = charRenderData.position.x + + Math.max(charData.xAdvance - charData.xOffset, charData.texture.orig.width); + pos.x += charData.xAdvance + this._letterSpacing; + maxLineHeight = Math.max(maxLineHeight, (charData.yOffset + charData.texture.height)); + prevCharCode = charCode; + if (lastBreakPos !== -1 && maxWidth > 0 && pos.x > maxWidth) { + ++spacesRemoved; + removeItems(chars, 1 + lastBreakPos - spacesRemoved, 1 + i - lastBreakPos); + i = lastBreakPos; + lastBreakPos = -1; + lineWidths.push(lastBreakWidth); + lineSpaces.push(chars.length > 0 ? chars[chars.length - 1].prevSpaces : 0); + maxLineWidth = Math.max(maxLineWidth, lastBreakWidth); + line++; + pos.x = 0; + pos.y += data.lineHeight; + prevCharCode = null; + spaceCount = 0; + } + } + var lastChar = charsInput[charsInput.length - 1]; + if (lastChar !== '\r' && lastChar !== '\n') { + if ((/(?:\s)/).test(lastChar)) { + lastLineWidth = lastBreakWidth; + } + lineWidths.push(lastLineWidth); + maxLineWidth = Math.max(maxLineWidth, lastLineWidth); + lineSpaces.push(-1); + } + var lineAlignOffsets = []; + for (var i = 0; i <= line; i++) { + var alignOffset = 0; + if (this._align === 'right') { + alignOffset = maxLineWidth - lineWidths[i]; + } + else if (this._align === 'center') { + alignOffset = (maxLineWidth - lineWidths[i]) / 2; + } + else if (this._align === 'justify') { + alignOffset = lineSpaces[i] < 0 ? 0 : (maxLineWidth - lineWidths[i]) / lineSpaces[i]; + } + lineAlignOffsets.push(alignOffset); + } + var lenChars = chars.length; + var pagesMeshData = {}; + var newPagesMeshData = []; + var activePagesMeshData = this._activePagesMeshData; + for (var i = 0; i < activePagesMeshData.length; i++) { + pageMeshDataPool.push(activePagesMeshData[i]); + } + for (var i = 0; i < lenChars; i++) { + var texture = chars[i].texture; + var baseTextureUid = texture.baseTexture.uid; + if (!pagesMeshData[baseTextureUid]) { + var pageMeshData = pageMeshDataPool.pop(); + if (!pageMeshData) { + var geometry = new MeshGeometry(); + var material = void 0; + var meshBlendMode = void 0; + if (data.distanceFieldType === 'none') { + material = new MeshMaterial(Texture.EMPTY); + meshBlendMode = exports.BLEND_MODES.NORMAL; + } + else { + material = new MeshMaterial(Texture.EMPTY, { program: Program.from(msdfVert, msdfFrag), uniforms: { uFWidth: 0 } }); + meshBlendMode = exports.BLEND_MODES.NORMAL_NPM; + } + var mesh = new Mesh(geometry, material); + mesh.blendMode = meshBlendMode; + pageMeshData = { + index: 0, + indexCount: 0, + vertexCount: 0, + uvsCount: 0, + total: 0, + mesh: mesh, + vertices: null, + uvs: null, + indices: null, + }; + } + // reset data.. + pageMeshData.index = 0; + pageMeshData.indexCount = 0; + pageMeshData.vertexCount = 0; + pageMeshData.uvsCount = 0; + pageMeshData.total = 0; + // TODO need to get page texture here somehow.. + var _textureCache = this._textureCache; + _textureCache[baseTextureUid] = _textureCache[baseTextureUid] || new Texture(texture.baseTexture); + pageMeshData.mesh.texture = _textureCache[baseTextureUid]; + pageMeshData.mesh.tint = this._tint; + newPagesMeshData.push(pageMeshData); + pagesMeshData[baseTextureUid] = pageMeshData; + } + pagesMeshData[baseTextureUid].total++; + } + // lets find any previously active pageMeshDatas that are no longer required for + // the updated text (if any), removed and return them to the pool. + for (var i = 0; i < activePagesMeshData.length; i++) { + if (newPagesMeshData.indexOf(activePagesMeshData[i]) === -1) { + this.removeChild(activePagesMeshData[i].mesh); + } + } + // next lets add any new meshes, that have not yet been added to this BitmapText + // we only add if its not already a child of this BitmapObject + for (var i = 0; i < newPagesMeshData.length; i++) { + if (newPagesMeshData[i].mesh.parent !== this) { + this.addChild(newPagesMeshData[i].mesh); + } + } + // active page mesh datas are set to be the new pages added. + this._activePagesMeshData = newPagesMeshData; + for (var i in pagesMeshData) { + var pageMeshData = pagesMeshData[i]; + var total = pageMeshData.total; + // lets only allocate new buffers if we can fit the new text in the current ones.. + // unless that is, we will be batching. Currently batching dose not respect the size property of mesh + if (!(((_a = pageMeshData.indices) === null || _a === void 0 ? void 0 : _a.length) > 6 * total) || pageMeshData.vertices.length < Mesh.BATCHABLE_SIZE * 2) { + pageMeshData.vertices = new Float32Array(4 * 2 * total); + pageMeshData.uvs = new Float32Array(4 * 2 * total); + pageMeshData.indices = new Uint16Array(6 * total); + } + else { + var total_1 = pageMeshData.total; + var vertices = pageMeshData.vertices; + // Clear the garbage at the end of the vertices buffer. This will prevent the bounds miscalculation. + for (var i_1 = total_1 * 4 * 2; i_1 < vertices.length; i_1++) { + vertices[i_1] = 0; + } + } + // as a buffer maybe bigger than the current word, we set the size of the meshMaterial + // to match the number of letters needed + pageMeshData.mesh.size = 6 * total; + } + for (var i = 0; i < lenChars; i++) { + var char = chars[i]; + var offset = char.position.x + (lineAlignOffsets[char.line] * (this._align === 'justify' ? char.prevSpaces : 1)); + if (this._roundPixels) { + offset = Math.round(offset); + } + var xPos = offset * scale; + var yPos = char.position.y * scale; + var texture = char.texture; + var pageMesh = pagesMeshData[texture.baseTexture.uid]; + var textureFrame = texture.frame; + var textureUvs = texture._uvs; + var index = pageMesh.index++; + pageMesh.indices[(index * 6) + 0] = 0 + (index * 4); + pageMesh.indices[(index * 6) + 1] = 1 + (index * 4); + pageMesh.indices[(index * 6) + 2] = 2 + (index * 4); + pageMesh.indices[(index * 6) + 3] = 0 + (index * 4); + pageMesh.indices[(index * 6) + 4] = 2 + (index * 4); + pageMesh.indices[(index * 6) + 5] = 3 + (index * 4); + pageMesh.vertices[(index * 8) + 0] = xPos; + pageMesh.vertices[(index * 8) + 1] = yPos; + pageMesh.vertices[(index * 8) + 2] = xPos + (textureFrame.width * scale); + pageMesh.vertices[(index * 8) + 3] = yPos; + pageMesh.vertices[(index * 8) + 4] = xPos + (textureFrame.width * scale); + pageMesh.vertices[(index * 8) + 5] = yPos + (textureFrame.height * scale); + pageMesh.vertices[(index * 8) + 6] = xPos; + pageMesh.vertices[(index * 8) + 7] = yPos + (textureFrame.height * scale); + pageMesh.uvs[(index * 8) + 0] = textureUvs.x0; + pageMesh.uvs[(index * 8) + 1] = textureUvs.y0; + pageMesh.uvs[(index * 8) + 2] = textureUvs.x1; + pageMesh.uvs[(index * 8) + 3] = textureUvs.y1; + pageMesh.uvs[(index * 8) + 4] = textureUvs.x2; + pageMesh.uvs[(index * 8) + 5] = textureUvs.y2; + pageMesh.uvs[(index * 8) + 6] = textureUvs.x3; + pageMesh.uvs[(index * 8) + 7] = textureUvs.y3; + } + this._textWidth = maxLineWidth * scale; + this._textHeight = (pos.y + data.lineHeight) * scale; + for (var i in pagesMeshData) { + var pageMeshData = pagesMeshData[i]; + // apply anchor + if (this.anchor.x !== 0 || this.anchor.y !== 0) { + var vertexCount = 0; + var anchorOffsetX = this._textWidth * this.anchor.x; + var anchorOffsetY = this._textHeight * this.anchor.y; + for (var i_2 = 0; i_2 < pageMeshData.total; i_2++) { + pageMeshData.vertices[vertexCount++] -= anchorOffsetX; + pageMeshData.vertices[vertexCount++] -= anchorOffsetY; + pageMeshData.vertices[vertexCount++] -= anchorOffsetX; + pageMeshData.vertices[vertexCount++] -= anchorOffsetY; + pageMeshData.vertices[vertexCount++] -= anchorOffsetX; + pageMeshData.vertices[vertexCount++] -= anchorOffsetY; + pageMeshData.vertices[vertexCount++] -= anchorOffsetX; + pageMeshData.vertices[vertexCount++] -= anchorOffsetY; + } + } + this._maxLineHeight = maxLineHeight * scale; + var vertexBuffer = pageMeshData.mesh.geometry.getBuffer('aVertexPosition'); + var textureBuffer = pageMeshData.mesh.geometry.getBuffer('aTextureCoord'); + var indexBuffer = pageMeshData.mesh.geometry.getIndex(); + vertexBuffer.data = pageMeshData.vertices; + textureBuffer.data = pageMeshData.uvs; + indexBuffer.data = pageMeshData.indices; + vertexBuffer.update(); + textureBuffer.update(); + indexBuffer.update(); + } + for (var i = 0; i < chars.length; i++) { + charRenderDataPool.push(chars[i]); + } + }; + BitmapText.prototype.updateTransform = function () { + this.validate(); + this.containerUpdateTransform(); + }; + BitmapText.prototype._render = function (renderer) { + if (this._autoResolution && this._resolution !== renderer.resolution) { + this._resolution = renderer.resolution; + this.dirty = true; + } + // Update the uniform + var _a = BitmapFont.available[this._fontName], distanceFieldRange = _a.distanceFieldRange, distanceFieldType = _a.distanceFieldType, size = _a.size; + if (distanceFieldType !== 'none') { + // Inject the shader code with the correct value + var _b = this.worldTransform, a = _b.a, b = _b.b, c = _b.c, d = _b.d; + var dx = Math.sqrt((a * a) + (b * b)); + var dy = Math.sqrt((c * c) + (d * d)); + var worldScale = (Math.abs(dx) + Math.abs(dy)) / 2; + var fontScale = this._fontSize / size; + for (var _i = 0, _c = this._activePagesMeshData; _i < _c.length; _i++) { + var mesh = _c[_i]; + mesh.mesh.shader.uniforms.uFWidth = worldScale * distanceFieldRange * fontScale * this._resolution; + } + } + _super.prototype._render.call(this, renderer); + }; + /** + * Validates text before calling parent's getLocalBounds + * @returns - The rectangular bounding area + */ + BitmapText.prototype.getLocalBounds = function () { + this.validate(); + return _super.prototype.getLocalBounds.call(this); + }; + /** + * Updates text when needed + * @private + */ + BitmapText.prototype.validate = function () { + if (this.dirty) { + this.updateText(); + this.dirty = false; + } + }; + Object.defineProperty(BitmapText.prototype, "tint", { + /** + * The tint of the BitmapText object. + * @default 0xffffff + */ + get: function () { + return this._tint; + }, + set: function (value) { + if (this._tint === value) + { return; } + this._tint = value; + for (var i = 0; i < this._activePagesMeshData.length; i++) { + this._activePagesMeshData[i].mesh.tint = value; + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(BitmapText.prototype, "align", { + /** + * The alignment of the BitmapText object. + * @member {string} + * @default 'left' + */ + get: function () { + return this._align; + }, + set: function (value) { + if (this._align !== value) { + this._align = value; + this.dirty = true; + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(BitmapText.prototype, "fontName", { + /** The name of the BitmapFont. */ + get: function () { + return this._fontName; + }, + set: function (value) { + if (!BitmapFont.available[value]) { + throw new Error("Missing BitmapFont \"" + value + "\""); + } + if (this._fontName !== value) { + this._fontName = value; + this.dirty = true; + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(BitmapText.prototype, "fontSize", { + /** The size of the font to display. */ + get: function () { + return this._fontSize; + }, + set: function (value) { + if (this._fontSize !== value) { + this._fontSize = value; + this.dirty = true; + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(BitmapText.prototype, "anchor", { + /** + * The anchor sets the origin point of the text. + * + * The default is `(0,0)`, this means the text's origin is the top left. + * + * Setting the anchor to `(0.5,0.5)` means the text's origin is centered. + * + * Setting the anchor to `(1,1)` would mean the text's origin point will be the bottom right corner. + */ + get: function () { + return this._anchor; + }, + set: function (value) { + if (typeof value === 'number') { + this._anchor.set(value); + } + else { + this._anchor.copyFrom(value); + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(BitmapText.prototype, "text", { + /** The text of the BitmapText object. */ + get: function () { + return this._text; + }, + set: function (text) { + text = String(text === null || text === undefined ? '' : text); + if (this._text === text) { + return; + } + this._text = text; + this.dirty = true; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(BitmapText.prototype, "maxWidth", { + /** + * The max width of this bitmap text in pixels. If the text provided is longer than the + * value provided, line breaks will be automatically inserted in the last whitespace. + * Disable by setting the value to 0. + */ + get: function () { + return this._maxWidth; + }, + set: function (value) { + if (this._maxWidth === value) { + return; + } + this._maxWidth = value; + this.dirty = true; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(BitmapText.prototype, "maxLineHeight", { + /** + * The max line height. This is useful when trying to use the total height of the Text, + * i.e. when trying to vertically align. + * @readonly + */ + get: function () { + this.validate(); + return this._maxLineHeight; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(BitmapText.prototype, "textWidth", { + /** + * The width of the overall text, different from fontSize, + * which is defined in the style object. + * @readonly + */ + get: function () { + this.validate(); + return this._textWidth; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(BitmapText.prototype, "letterSpacing", { + /** Additional space between characters. */ + get: function () { + return this._letterSpacing; + }, + set: function (value) { + if (this._letterSpacing !== value) { + this._letterSpacing = value; + this.dirty = true; + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(BitmapText.prototype, "roundPixels", { + /** + * If true PixiJS will Math.floor() x/y values when rendering, stopping pixel interpolation. + * Advantages can include sharper image quality (like text) and faster rendering on canvas. + * The main disadvantage is movement of objects may appear less smooth. + * To set the global default, change {@link PIXI.settings.ROUND_PIXELS} + * @default PIXI.settings.ROUND_PIXELS + */ + get: function () { + return this._roundPixels; + }, + set: function (value) { + if (value !== this._roundPixels) { + this._roundPixels = value; + this.dirty = true; + } + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(BitmapText.prototype, "textHeight", { + /** + * The height of the overall text, different from fontSize, + * which is defined in the style object. + * @readonly + */ + get: function () { + this.validate(); + return this._textHeight; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(BitmapText.prototype, "resolution", { + /** + * The resolution / device pixel ratio of the canvas. + * + * This is set to automatically match the renderer resolution by default, but can be overridden by setting manually. + * @default 1 + */ + get: function () { + return this._resolution; + }, + set: function (value) { + this._autoResolution = false; + if (this._resolution === value) { + return; + } + this._resolution = value; + this.dirty = true; + }, + enumerable: false, + configurable: true + }); + BitmapText.prototype.destroy = function (options) { + var _textureCache = this._textureCache; + for (var id in _textureCache) { + var texture = _textureCache[id]; + texture.destroy(); + delete _textureCache[id]; + } + this._textureCache = null; + _super.prototype.destroy.call(this, options); + }; + BitmapText.styleDefaults = { + align: 'left', + tint: 0xFFFFFF, + maxWidth: 0, + letterSpacing: 0, + }; + return BitmapText; + }(Container)); + + /** + * {@link PIXI.Loader Loader} middleware for loading + * bitmap-based fonts suitable for using with {@link PIXI.BitmapText}. + * @memberof PIXI + */ + var BitmapFontLoader = /** @class */ (function () { + function BitmapFontLoader() { + } + /** + * Called when the plugin is installed. + * @see PIXI.extensions.add + */ + BitmapFontLoader.add = function () { + exports.LoaderResource.setExtensionXhrType('fnt', exports.LoaderResource.XHR_RESPONSE_TYPE.TEXT); + }; + /** + * Called after a resource is loaded. + * @see PIXI.Loader.loaderMiddleware + * @param this + * @param {PIXI.LoaderResource} resource + * @param {Function} next + */ + BitmapFontLoader.use = function (resource, next) { + var format = autoDetectFormat(resource.data); + // Resource was not recognised as any of the expected font data format + if (!format) { + next(); + return; + } + var baseUrl = BitmapFontLoader.getBaseUrl(this, resource); + var data = format.parse(resource.data); + var textures = {}; + // Handle completed, when the number of textures + // load is the same number as references in the fnt file + var completed = function (page) { + textures[page.metadata.pageFile] = page.texture; + if (Object.keys(textures).length === data.page.length) { + resource.bitmapFont = BitmapFont.install(data, textures, true); + next(); + } + }; + for (var i = 0; i < data.page.length; ++i) { + var pageFile = data.page[i].file; + var url = baseUrl + pageFile; + var exists = false; + // incase the image is loaded outside + // using the same loader, resource will be available + for (var name in this.resources) { + var bitmapResource = this.resources[name]; + if (bitmapResource.url === url) { + bitmapResource.metadata.pageFile = pageFile; + if (bitmapResource.texture) { + completed(bitmapResource); + } + else { + bitmapResource.onAfterMiddleware.add(completed); + } + exists = true; + break; + } + } + // texture is not loaded, we'll attempt to add + // it to the load and add the texture to the list + if (!exists) { + // Standard loading options for images + var options = { + crossOrigin: resource.crossOrigin, + loadType: exports.LoaderResource.LOAD_TYPE.IMAGE, + metadata: Object.assign({ pageFile: pageFile }, resource.metadata.imageMetadata), + parentResource: resource, + }; + this.add(url, options, completed); + } + } + }; + /** + * Get folder path from a resource. + * @param loader + * @param resource + */ + BitmapFontLoader.getBaseUrl = function (loader, resource) { + var resUrl = !resource.isDataUrl ? BitmapFontLoader.dirname(resource.url) : ''; + if (resource.isDataUrl) { + if (resUrl === '.') { + resUrl = ''; + } + if (loader.baseUrl && resUrl) { + // if baseurl has a trailing slash then add one to resUrl so the replace works below + if (loader.baseUrl.charAt(loader.baseUrl.length - 1) === '/') { + resUrl += '/'; + } + } + } + // remove baseUrl from resUrl + resUrl = resUrl.replace(loader.baseUrl, ''); + // if there is an resUrl now, it needs a trailing slash. Ensure that it does if the string isn't empty. + if (resUrl && resUrl.charAt(resUrl.length - 1) !== '/') { + resUrl += '/'; + } + return resUrl; + }; + /** + * Replacement for NodeJS's path.dirname + * @param {string} url - Path to get directory for + */ + BitmapFontLoader.dirname = function (url) { + var dir = url + .replace(/\\/g, '/') // convert windows notation to UNIX notation, URL-safe because it's a forbidden character + .replace(/\/$/, '') // replace trailing slash + .replace(/\/[^\/]*$/, ''); // remove everything after the last + // File request is relative, use current directory + if (dir === url) { + return '.'; + } + // Started with a slash + else if (dir === '') { + return '/'; + } + return dir; + }; + /** @ignore */ + BitmapFontLoader.extension = exports.ExtensionType.Loader; + return BitmapFontLoader; + }()); + + /*! + * @pixi/filter-alpha - v6.5.3 + * Compiled Fri, 09 Sep 2022 13:55:20 UTC + * + * @pixi/filter-alpha is licensed under the MIT License. + * http://www.opensource.org/licenses/mit-license + */ + + /*! ***************************************************************************** + Copyright (c) Microsoft Corporation. - THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED - WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, - MERCHANTABLITY OR NON-INFRINGEMENT. + Permission to use, copy, modify, and/or distribute this software for any + purpose with or without fee is hereby granted. - See the Apache Version 2.0 License for specific language governing permissions - and limitations under the License. - ***************************************************************************** */ - /* global Reflect, Promise */ + THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH + REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY + AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, + INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM + LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR + OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR + PERFORMANCE OF THIS SOFTWARE. + ***************************************************************************** */ + /* global Reflect, Promise */ - var extendStatics$i = function(d, b) { - extendStatics$i = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) { if (b.hasOwnProperty(p)) { d[p] = b[p]; } } }; - return extendStatics$i(d, b); - }; + var extendStatics$7 = function(d, b) { + extendStatics$7 = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) { if (b.hasOwnProperty(p)) { d[p] = b[p]; } } }; + return extendStatics$7(d, b); + }; - function __extends$i(d, b) { - extendStatics$i(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - } + function __extends$7(d, b) { + extendStatics$7(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + } + + var fragment$4 = "varying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\nuniform float uAlpha;\n\nvoid main(void)\n{\n gl_FragColor = texture2D(uSampler, vTextureCoord) * uAlpha;\n}\n"; + + /** + * Simplest filter - applies alpha. + * + * Use this instead of Container's alpha property to avoid visual layering of individual elements. + * AlphaFilter applies alpha evenly across the entire display object and any opaque elements it contains. + * If elements are not opaque, they will blend with each other anyway. + * + * Very handy if you want to use common features of all filters: + * + * 1. Assign a blendMode to this filter, blend all elements inside display object with background. + * + * 2. To use clipping in display coordinates, assign a filterArea to the same container that has this filter. + * @memberof PIXI.filters + */ + var AlphaFilter = /** @class */ (function (_super) { + __extends$7(AlphaFilter, _super); + /** + * @param alpha - Amount of alpha from 0 to 1, where 0 is transparent + */ + function AlphaFilter(alpha) { + if (alpha === void 0) { alpha = 1.0; } + var _this = _super.call(this, defaultVertex$1, fragment$4, { uAlpha: 1 }) || this; + _this.alpha = alpha; + return _this; + } + Object.defineProperty(AlphaFilter.prototype, "alpha", { + /** + * Coefficient for alpha multiplication + * @default 1 + */ + get: function () { + return this.uniforms.uAlpha; + }, + set: function (value) { + this.uniforms.uAlpha = value; + }, + enumerable: false, + configurable: true + }); + return AlphaFilter; + }(Filter)); + + /*! + * @pixi/filter-blur - v6.5.3 + * Compiled Fri, 09 Sep 2022 13:55:20 UTC + * + * @pixi/filter-blur is licensed under the MIT License. + * http://www.opensource.org/licenses/mit-license + */ + + /*! ***************************************************************************** + Copyright (c) Microsoft Corporation. - var __assign = function() { - __assign = Object.assign || function __assign(t) { - var arguments$1 = arguments; + Permission to use, copy, modify, and/or distribute this software for any + purpose with or without fee is hereby granted. - for (var s, i = 1, n = arguments.length; i < n; i++) { - s = arguments$1[i]; - for (var p in s) { if (Object.prototype.hasOwnProperty.call(s, p)) { t[p] = s[p]; } } - } - return t; - }; - return __assign.apply(this, arguments); - }; + THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH + REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY + AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, + INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM + LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR + OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR + PERFORMANCE OF THIS SOFTWARE. + ***************************************************************************** */ + /* global Reflect, Promise */ - function __rest(s, e) { - var t = {}; - for (var p in s) { if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) - { t[p] = s[p]; } } - if (s != null && typeof Object.getOwnPropertySymbols === "function") - { for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { if (e.indexOf(p[i]) < 0) - { t[p[i]] = s[p[i]]; } } } - return t; - } + var extendStatics$6 = function(d, b) { + extendStatics$6 = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) { if (b.hasOwnProperty(p)) { d[p] = b[p]; } } }; + return extendStatics$6(d, b); + }; - function __decorate(decorators, target, key, desc) { - var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; - if (typeof Reflect === "object" && typeof Reflect.decorate === "function") { r = Reflect.decorate(decorators, target, key, desc); } - else { for (var i = decorators.length - 1; i >= 0; i--) { if (d = decorators[i]) { r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; } } } - return c > 3 && r && Object.defineProperty(target, key, r), r; - } + function __extends$6(d, b) { + extendStatics$6(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + } + + var vertTemplate = "\n attribute vec2 aVertexPosition;\n\n uniform mat3 projectionMatrix;\n\n uniform float strength;\n\n varying vec2 vBlurTexCoords[%size%];\n\n uniform vec4 inputSize;\n uniform vec4 outputFrame;\n\n vec4 filterVertexPosition( void )\n {\n vec2 position = aVertexPosition * max(outputFrame.zw, vec2(0.)) + outputFrame.xy;\n\n return vec4((projectionMatrix * vec3(position, 1.0)).xy, 0.0, 1.0);\n }\n\n vec2 filterTextureCoord( void )\n {\n return aVertexPosition * (outputFrame.zw * inputSize.zw);\n }\n\n void main(void)\n {\n gl_Position = filterVertexPosition();\n\n vec2 textureCoord = filterTextureCoord();\n %blur%\n }"; + function generateBlurVertSource(kernelSize, x) { + var halfLength = Math.ceil(kernelSize / 2); + var vertSource = vertTemplate; + var blurLoop = ''; + var template; + if (x) { + template = 'vBlurTexCoords[%index%] = textureCoord + vec2(%sampleIndex% * strength, 0.0);'; + } + else { + template = 'vBlurTexCoords[%index%] = textureCoord + vec2(0.0, %sampleIndex% * strength);'; + } + for (var i = 0; i < kernelSize; i++) { + var blur = template.replace('%index%', i.toString()); + blur = blur.replace('%sampleIndex%', i - (halfLength - 1) + ".0"); + blurLoop += blur; + blurLoop += '\n'; + } + vertSource = vertSource.replace('%blur%', blurLoop); + vertSource = vertSource.replace('%size%', kernelSize.toString()); + return vertSource; + } + + var GAUSSIAN_VALUES = { + 5: [0.153388, 0.221461, 0.250301], + 7: [0.071303, 0.131514, 0.189879, 0.214607], + 9: [0.028532, 0.067234, 0.124009, 0.179044, 0.20236], + 11: [0.0093, 0.028002, 0.065984, 0.121703, 0.175713, 0.198596], + 13: [0.002406, 0.009255, 0.027867, 0.065666, 0.121117, 0.174868, 0.197641], + 15: [0.000489, 0.002403, 0.009246, 0.02784, 0.065602, 0.120999, 0.174697, 0.197448], + }; + var fragTemplate = [ + 'varying vec2 vBlurTexCoords[%size%];', + 'uniform sampler2D uSampler;', + 'void main(void)', + '{', + ' gl_FragColor = vec4(0.0);', + ' %blur%', + '}' ].join('\n'); + function generateBlurFragSource(kernelSize) { + var kernel = GAUSSIAN_VALUES[kernelSize]; + var halfLength = kernel.length; + var fragSource = fragTemplate; + var blurLoop = ''; + var template = 'gl_FragColor += texture2D(uSampler, vBlurTexCoords[%index%]) * %value%;'; + var value; + for (var i = 0; i < kernelSize; i++) { + var blur = template.replace('%index%', i.toString()); + value = i; + if (i >= halfLength) { + value = kernelSize - i - 1; + } + blur = blur.replace('%value%', kernel[value].toString()); + blurLoop += blur; + blurLoop += '\n'; + } + fragSource = fragSource.replace('%blur%', blurLoop); + fragSource = fragSource.replace('%size%', kernelSize.toString()); + return fragSource; + } + + /*! + * @pixi/constants - v6.5.3 + * Compiled Fri, 09 Sep 2022 13:55:20 UTC + * + * @pixi/constants is licensed under the MIT License. + * http://www.opensource.org/licenses/mit-license + */ + /** + * Different types of environments for WebGL. + * @static + * @memberof PIXI + * @name ENV + * @enum {number} + * @property {number} WEBGL_LEGACY - Used for older v1 WebGL devices. PixiJS will aim to ensure compatibility + * with older / less advanced devices. If you experience unexplained flickering prefer this environment. + * @property {number} WEBGL - Version 1 of WebGL + * @property {number} WEBGL2 - Version 2 of WebGL + */ + var ENV$3; + (function (ENV) { + ENV[ENV["WEBGL_LEGACY"] = 0] = "WEBGL_LEGACY"; + ENV[ENV["WEBGL"] = 1] = "WEBGL"; + ENV[ENV["WEBGL2"] = 2] = "WEBGL2"; + })(ENV$3 || (ENV$3 = {})); + /** + * Constant to identify the Renderer Type. + * @static + * @memberof PIXI + * @name RENDERER_TYPE + * @enum {number} + * @property {number} UNKNOWN - Unknown render type. + * @property {number} WEBGL - WebGL render type. + * @property {number} CANVAS - Canvas render type. + */ + var RENDERER_TYPE$3; + (function (RENDERER_TYPE) { + RENDERER_TYPE[RENDERER_TYPE["UNKNOWN"] = 0] = "UNKNOWN"; + RENDERER_TYPE[RENDERER_TYPE["WEBGL"] = 1] = "WEBGL"; + RENDERER_TYPE[RENDERER_TYPE["CANVAS"] = 2] = "CANVAS"; + })(RENDERER_TYPE$3 || (RENDERER_TYPE$3 = {})); + /** + * Bitwise OR of masks that indicate the buffers to be cleared. + * @static + * @memberof PIXI + * @name BUFFER_BITS + * @enum {number} + * @property {number} COLOR - Indicates the buffers currently enabled for color writing. + * @property {number} DEPTH - Indicates the depth buffer. + * @property {number} STENCIL - Indicates the stencil buffer. + */ + var BUFFER_BITS$3; + (function (BUFFER_BITS) { + BUFFER_BITS[BUFFER_BITS["COLOR"] = 16384] = "COLOR"; + BUFFER_BITS[BUFFER_BITS["DEPTH"] = 256] = "DEPTH"; + BUFFER_BITS[BUFFER_BITS["STENCIL"] = 1024] = "STENCIL"; + })(BUFFER_BITS$3 || (BUFFER_BITS$3 = {})); + /** + * Various blend modes supported by PIXI. + * + * IMPORTANT - The WebGL renderer only supports the NORMAL, ADD, MULTIPLY and SCREEN blend modes. + * Anything else will silently act like NORMAL. + * @memberof PIXI + * @name BLEND_MODES + * @enum {number} + * @property {number} NORMAL - + * @property {number} ADD - + * @property {number} MULTIPLY - + * @property {number} SCREEN - + * @property {number} OVERLAY - + * @property {number} DARKEN - + * @property {number} LIGHTEN - + * @property {number} COLOR_DODGE - + * @property {number} COLOR_BURN - + * @property {number} HARD_LIGHT - + * @property {number} SOFT_LIGHT - + * @property {number} DIFFERENCE - + * @property {number} EXCLUSION - + * @property {number} HUE - + * @property {number} SATURATION - + * @property {number} COLOR - + * @property {number} LUMINOSITY - + * @property {number} NORMAL_NPM - + * @property {number} ADD_NPM - + * @property {number} SCREEN_NPM - + * @property {number} NONE - + * @property {number} SRC_IN - + * @property {number} SRC_OUT - + * @property {number} SRC_ATOP - + * @property {number} DST_OVER - + * @property {number} DST_IN - + * @property {number} DST_OUT - + * @property {number} DST_ATOP - + * @property {number} SUBTRACT - + * @property {number} SRC_OVER - + * @property {number} ERASE - + * @property {number} XOR - + */ + var BLEND_MODES$3; + (function (BLEND_MODES) { + BLEND_MODES[BLEND_MODES["NORMAL"] = 0] = "NORMAL"; + BLEND_MODES[BLEND_MODES["ADD"] = 1] = "ADD"; + BLEND_MODES[BLEND_MODES["MULTIPLY"] = 2] = "MULTIPLY"; + BLEND_MODES[BLEND_MODES["SCREEN"] = 3] = "SCREEN"; + BLEND_MODES[BLEND_MODES["OVERLAY"] = 4] = "OVERLAY"; + BLEND_MODES[BLEND_MODES["DARKEN"] = 5] = "DARKEN"; + BLEND_MODES[BLEND_MODES["LIGHTEN"] = 6] = "LIGHTEN"; + BLEND_MODES[BLEND_MODES["COLOR_DODGE"] = 7] = "COLOR_DODGE"; + BLEND_MODES[BLEND_MODES["COLOR_BURN"] = 8] = "COLOR_BURN"; + BLEND_MODES[BLEND_MODES["HARD_LIGHT"] = 9] = "HARD_LIGHT"; + BLEND_MODES[BLEND_MODES["SOFT_LIGHT"] = 10] = "SOFT_LIGHT"; + BLEND_MODES[BLEND_MODES["DIFFERENCE"] = 11] = "DIFFERENCE"; + BLEND_MODES[BLEND_MODES["EXCLUSION"] = 12] = "EXCLUSION"; + BLEND_MODES[BLEND_MODES["HUE"] = 13] = "HUE"; + BLEND_MODES[BLEND_MODES["SATURATION"] = 14] = "SATURATION"; + BLEND_MODES[BLEND_MODES["COLOR"] = 15] = "COLOR"; + BLEND_MODES[BLEND_MODES["LUMINOSITY"] = 16] = "LUMINOSITY"; + BLEND_MODES[BLEND_MODES["NORMAL_NPM"] = 17] = "NORMAL_NPM"; + BLEND_MODES[BLEND_MODES["ADD_NPM"] = 18] = "ADD_NPM"; + BLEND_MODES[BLEND_MODES["SCREEN_NPM"] = 19] = "SCREEN_NPM"; + BLEND_MODES[BLEND_MODES["NONE"] = 20] = "NONE"; + BLEND_MODES[BLEND_MODES["SRC_OVER"] = 0] = "SRC_OVER"; + BLEND_MODES[BLEND_MODES["SRC_IN"] = 21] = "SRC_IN"; + BLEND_MODES[BLEND_MODES["SRC_OUT"] = 22] = "SRC_OUT"; + BLEND_MODES[BLEND_MODES["SRC_ATOP"] = 23] = "SRC_ATOP"; + BLEND_MODES[BLEND_MODES["DST_OVER"] = 24] = "DST_OVER"; + BLEND_MODES[BLEND_MODES["DST_IN"] = 25] = "DST_IN"; + BLEND_MODES[BLEND_MODES["DST_OUT"] = 26] = "DST_OUT"; + BLEND_MODES[BLEND_MODES["DST_ATOP"] = 27] = "DST_ATOP"; + BLEND_MODES[BLEND_MODES["ERASE"] = 26] = "ERASE"; + BLEND_MODES[BLEND_MODES["SUBTRACT"] = 28] = "SUBTRACT"; + BLEND_MODES[BLEND_MODES["XOR"] = 29] = "XOR"; + })(BLEND_MODES$3 || (BLEND_MODES$3 = {})); + /** + * Various webgl draw modes. These can be used to specify which GL drawMode to use + * under certain situations and renderers. + * @memberof PIXI + * @static + * @name DRAW_MODES + * @enum {number} + * @property {number} POINTS - + * @property {number} LINES - + * @property {number} LINE_LOOP - + * @property {number} LINE_STRIP - + * @property {number} TRIANGLES - + * @property {number} TRIANGLE_STRIP - + * @property {number} TRIANGLE_FAN - + */ + var DRAW_MODES$3; + (function (DRAW_MODES) { + DRAW_MODES[DRAW_MODES["POINTS"] = 0] = "POINTS"; + DRAW_MODES[DRAW_MODES["LINES"] = 1] = "LINES"; + DRAW_MODES[DRAW_MODES["LINE_LOOP"] = 2] = "LINE_LOOP"; + DRAW_MODES[DRAW_MODES["LINE_STRIP"] = 3] = "LINE_STRIP"; + DRAW_MODES[DRAW_MODES["TRIANGLES"] = 4] = "TRIANGLES"; + DRAW_MODES[DRAW_MODES["TRIANGLE_STRIP"] = 5] = "TRIANGLE_STRIP"; + DRAW_MODES[DRAW_MODES["TRIANGLE_FAN"] = 6] = "TRIANGLE_FAN"; + })(DRAW_MODES$3 || (DRAW_MODES$3 = {})); + /** + * Various GL texture/resources formats. + * @memberof PIXI + * @static + * @name FORMATS + * @enum {number} + * @property {number} [RGBA=6408] - + * @property {number} [RGB=6407] - + * @property {number} [RG=33319] - + * @property {number} [RED=6403] - + * @property {number} [RGBA_INTEGER=36249] - + * @property {number} [RGB_INTEGER=36248] - + * @property {number} [RG_INTEGER=33320] - + * @property {number} [RED_INTEGER=36244] - + * @property {number} [ALPHA=6406] - + * @property {number} [LUMINANCE=6409] - + * @property {number} [LUMINANCE_ALPHA=6410] - + * @property {number} [DEPTH_COMPONENT=6402] - + * @property {number} [DEPTH_STENCIL=34041] - + */ + var FORMATS$3; + (function (FORMATS) { + FORMATS[FORMATS["RGBA"] = 6408] = "RGBA"; + FORMATS[FORMATS["RGB"] = 6407] = "RGB"; + FORMATS[FORMATS["RG"] = 33319] = "RG"; + FORMATS[FORMATS["RED"] = 6403] = "RED"; + FORMATS[FORMATS["RGBA_INTEGER"] = 36249] = "RGBA_INTEGER"; + FORMATS[FORMATS["RGB_INTEGER"] = 36248] = "RGB_INTEGER"; + FORMATS[FORMATS["RG_INTEGER"] = 33320] = "RG_INTEGER"; + FORMATS[FORMATS["RED_INTEGER"] = 36244] = "RED_INTEGER"; + FORMATS[FORMATS["ALPHA"] = 6406] = "ALPHA"; + FORMATS[FORMATS["LUMINANCE"] = 6409] = "LUMINANCE"; + FORMATS[FORMATS["LUMINANCE_ALPHA"] = 6410] = "LUMINANCE_ALPHA"; + FORMATS[FORMATS["DEPTH_COMPONENT"] = 6402] = "DEPTH_COMPONENT"; + FORMATS[FORMATS["DEPTH_STENCIL"] = 34041] = "DEPTH_STENCIL"; + })(FORMATS$3 || (FORMATS$3 = {})); + /** + * Various GL target types. + * @memberof PIXI + * @static + * @name TARGETS + * @enum {number} + * @property {number} [TEXTURE_2D=3553] - + * @property {number} [TEXTURE_CUBE_MAP=34067] - + * @property {number} [TEXTURE_2D_ARRAY=35866] - + * @property {number} [TEXTURE_CUBE_MAP_POSITIVE_X=34069] - + * @property {number} [TEXTURE_CUBE_MAP_NEGATIVE_X=34070] - + * @property {number} [TEXTURE_CUBE_MAP_POSITIVE_Y=34071] - + * @property {number} [TEXTURE_CUBE_MAP_NEGATIVE_Y=34072] - + * @property {number} [TEXTURE_CUBE_MAP_POSITIVE_Z=34073] - + * @property {number} [TEXTURE_CUBE_MAP_NEGATIVE_Z=34074] - + */ + var TARGETS$3; + (function (TARGETS) { + TARGETS[TARGETS["TEXTURE_2D"] = 3553] = "TEXTURE_2D"; + TARGETS[TARGETS["TEXTURE_CUBE_MAP"] = 34067] = "TEXTURE_CUBE_MAP"; + TARGETS[TARGETS["TEXTURE_2D_ARRAY"] = 35866] = "TEXTURE_2D_ARRAY"; + TARGETS[TARGETS["TEXTURE_CUBE_MAP_POSITIVE_X"] = 34069] = "TEXTURE_CUBE_MAP_POSITIVE_X"; + TARGETS[TARGETS["TEXTURE_CUBE_MAP_NEGATIVE_X"] = 34070] = "TEXTURE_CUBE_MAP_NEGATIVE_X"; + TARGETS[TARGETS["TEXTURE_CUBE_MAP_POSITIVE_Y"] = 34071] = "TEXTURE_CUBE_MAP_POSITIVE_Y"; + TARGETS[TARGETS["TEXTURE_CUBE_MAP_NEGATIVE_Y"] = 34072] = "TEXTURE_CUBE_MAP_NEGATIVE_Y"; + TARGETS[TARGETS["TEXTURE_CUBE_MAP_POSITIVE_Z"] = 34073] = "TEXTURE_CUBE_MAP_POSITIVE_Z"; + TARGETS[TARGETS["TEXTURE_CUBE_MAP_NEGATIVE_Z"] = 34074] = "TEXTURE_CUBE_MAP_NEGATIVE_Z"; + })(TARGETS$3 || (TARGETS$3 = {})); + /** + * Various GL data format types. + * @memberof PIXI + * @static + * @name TYPES + * @enum {number} + * @property {number} [UNSIGNED_BYTE=5121] - + * @property {number} [UNSIGNED_SHORT=5123] - + * @property {number} [UNSIGNED_SHORT_5_6_5=33635] - + * @property {number} [UNSIGNED_SHORT_4_4_4_4=32819] - + * @property {number} [UNSIGNED_SHORT_5_5_5_1=32820] - + * @property {number} [UNSIGNED_INT=5125] - + * @property {number} [UNSIGNED_INT_10F_11F_11F_REV=35899] - + * @property {number} [UNSIGNED_INT_2_10_10_10_REV=33640] - + * @property {number} [UNSIGNED_INT_24_8=34042] - + * @property {number} [UNSIGNED_INT_5_9_9_9_REV=35902] - + * @property {number} [BYTE=5120] - + * @property {number} [SHORT=5122] - + * @property {number} [INT=5124] - + * @property {number} [FLOAT=5126] - + * @property {number} [FLOAT_32_UNSIGNED_INT_24_8_REV=36269] - + * @property {number} [HALF_FLOAT=36193] - + */ + var TYPES$3; + (function (TYPES) { + TYPES[TYPES["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE"; + TYPES[TYPES["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT"; + TYPES[TYPES["UNSIGNED_SHORT_5_6_5"] = 33635] = "UNSIGNED_SHORT_5_6_5"; + TYPES[TYPES["UNSIGNED_SHORT_4_4_4_4"] = 32819] = "UNSIGNED_SHORT_4_4_4_4"; + TYPES[TYPES["UNSIGNED_SHORT_5_5_5_1"] = 32820] = "UNSIGNED_SHORT_5_5_5_1"; + TYPES[TYPES["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT"; + TYPES[TYPES["UNSIGNED_INT_10F_11F_11F_REV"] = 35899] = "UNSIGNED_INT_10F_11F_11F_REV"; + TYPES[TYPES["UNSIGNED_INT_2_10_10_10_REV"] = 33640] = "UNSIGNED_INT_2_10_10_10_REV"; + TYPES[TYPES["UNSIGNED_INT_24_8"] = 34042] = "UNSIGNED_INT_24_8"; + TYPES[TYPES["UNSIGNED_INT_5_9_9_9_REV"] = 35902] = "UNSIGNED_INT_5_9_9_9_REV"; + TYPES[TYPES["BYTE"] = 5120] = "BYTE"; + TYPES[TYPES["SHORT"] = 5122] = "SHORT"; + TYPES[TYPES["INT"] = 5124] = "INT"; + TYPES[TYPES["FLOAT"] = 5126] = "FLOAT"; + TYPES[TYPES["FLOAT_32_UNSIGNED_INT_24_8_REV"] = 36269] = "FLOAT_32_UNSIGNED_INT_24_8_REV"; + TYPES[TYPES["HALF_FLOAT"] = 36193] = "HALF_FLOAT"; + })(TYPES$3 || (TYPES$3 = {})); + /** + * Various sampler types. Correspond to `sampler`, `isampler`, `usampler` GLSL types respectively. + * WebGL1 works only with FLOAT. + * @memberof PIXI + * @static + * @name SAMPLER_TYPES + * @enum {number} + * @property {number} [FLOAT=0] - + * @property {number} [INT=1] - + * @property {number} [UINT=2] - + */ + var SAMPLER_TYPES$3; + (function (SAMPLER_TYPES) { + SAMPLER_TYPES[SAMPLER_TYPES["FLOAT"] = 0] = "FLOAT"; + SAMPLER_TYPES[SAMPLER_TYPES["INT"] = 1] = "INT"; + SAMPLER_TYPES[SAMPLER_TYPES["UINT"] = 2] = "UINT"; + })(SAMPLER_TYPES$3 || (SAMPLER_TYPES$3 = {})); + /** + * The scale modes that are supported by pixi. + * + * The {@link PIXI.settings.SCALE_MODE} scale mode affects the default scaling mode of future operations. + * It can be re-assigned to either LINEAR or NEAREST, depending upon suitability. + * @memberof PIXI + * @static + * @name SCALE_MODES + * @enum {number} + * @property {number} LINEAR Smooth scaling + * @property {number} NEAREST Pixelating scaling + */ + var SCALE_MODES$3; + (function (SCALE_MODES) { + SCALE_MODES[SCALE_MODES["NEAREST"] = 0] = "NEAREST"; + SCALE_MODES[SCALE_MODES["LINEAR"] = 1] = "LINEAR"; + })(SCALE_MODES$3 || (SCALE_MODES$3 = {})); + /** + * The wrap modes that are supported by pixi. + * + * The {@link PIXI.settings.WRAP_MODE} wrap mode affects the default wrapping mode of future operations. + * It can be re-assigned to either CLAMP or REPEAT, depending upon suitability. + * If the texture is non power of two then clamp will be used regardless as WebGL can + * only use REPEAT if the texture is po2. + * + * This property only affects WebGL. + * @name WRAP_MODES + * @memberof PIXI + * @static + * @enum {number} + * @property {number} CLAMP - The textures uvs are clamped + * @property {number} REPEAT - The texture uvs tile and repeat + * @property {number} MIRRORED_REPEAT - The texture uvs tile and repeat with mirroring + */ + var WRAP_MODES$3; + (function (WRAP_MODES) { + WRAP_MODES[WRAP_MODES["CLAMP"] = 33071] = "CLAMP"; + WRAP_MODES[WRAP_MODES["REPEAT"] = 10497] = "REPEAT"; + WRAP_MODES[WRAP_MODES["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT"; + })(WRAP_MODES$3 || (WRAP_MODES$3 = {})); + /** + * Mipmap filtering modes that are supported by pixi. + * + * The {@link PIXI.settings.MIPMAP_TEXTURES} affects default texture filtering. + * Mipmaps are generated for a baseTexture if its `mipmap` field is `ON`, + * or its `POW2` and texture dimensions are powers of 2. + * Due to platform restriction, `ON` option will work like `POW2` for webgl-1. + * + * This property only affects WebGL. + * @name MIPMAP_MODES + * @memberof PIXI + * @static + * @enum {number} + * @property {number} OFF - No mipmaps + * @property {number} POW2 - Generate mipmaps if texture dimensions are pow2 + * @property {number} ON - Always generate mipmaps + * @property {number} ON_MANUAL - Use mipmaps, but do not auto-generate them; this is used with a resource + * that supports buffering each level-of-detail. + */ + var MIPMAP_MODES$3; + (function (MIPMAP_MODES) { + MIPMAP_MODES[MIPMAP_MODES["OFF"] = 0] = "OFF"; + MIPMAP_MODES[MIPMAP_MODES["POW2"] = 1] = "POW2"; + MIPMAP_MODES[MIPMAP_MODES["ON"] = 2] = "ON"; + MIPMAP_MODES[MIPMAP_MODES["ON_MANUAL"] = 3] = "ON_MANUAL"; + })(MIPMAP_MODES$3 || (MIPMAP_MODES$3 = {})); + /** + * How to treat textures with premultiplied alpha + * @name ALPHA_MODES + * @memberof PIXI + * @static + * @enum {number} + * @property {number} NO_PREMULTIPLIED_ALPHA - Source is not premultiplied, leave it like that. + * Option for compressed and data textures that are created from typed arrays. + * @property {number} PREMULTIPLY_ON_UPLOAD - Source is not premultiplied, premultiply on upload. + * Default option, used for all loaded images. + * @property {number} PREMULTIPLIED_ALPHA - Source is already premultiplied + * Example: spine atlases with `_pma` suffix. + * @property {number} NPM - Alias for NO_PREMULTIPLIED_ALPHA. + * @property {number} UNPACK - Default option, alias for PREMULTIPLY_ON_UPLOAD. + * @property {number} PMA - Alias for PREMULTIPLIED_ALPHA. + */ + var ALPHA_MODES$3; + (function (ALPHA_MODES) { + ALPHA_MODES[ALPHA_MODES["NPM"] = 0] = "NPM"; + ALPHA_MODES[ALPHA_MODES["UNPACK"] = 1] = "UNPACK"; + ALPHA_MODES[ALPHA_MODES["PMA"] = 2] = "PMA"; + ALPHA_MODES[ALPHA_MODES["NO_PREMULTIPLIED_ALPHA"] = 0] = "NO_PREMULTIPLIED_ALPHA"; + ALPHA_MODES[ALPHA_MODES["PREMULTIPLY_ON_UPLOAD"] = 1] = "PREMULTIPLY_ON_UPLOAD"; + ALPHA_MODES[ALPHA_MODES["PREMULTIPLY_ALPHA"] = 2] = "PREMULTIPLY_ALPHA"; + ALPHA_MODES[ALPHA_MODES["PREMULTIPLIED_ALPHA"] = 2] = "PREMULTIPLIED_ALPHA"; + })(ALPHA_MODES$3 || (ALPHA_MODES$3 = {})); + /** + * Configure whether filter textures are cleared after binding. + * + * Filter textures need not be cleared if the filter does not use pixel blending. {@link CLEAR_MODES.BLIT} will detect + * this and skip clearing as an optimization. + * @name CLEAR_MODES + * @memberof PIXI + * @static + * @enum {number} + * @property {number} BLEND - Do not clear the filter texture. The filter's output will blend on top of the output texture. + * @property {number} CLEAR - Always clear the filter texture. + * @property {number} BLIT - Clear only if {@link FilterSystem.forceClear} is set or if the filter uses pixel blending. + * @property {number} NO - Alias for BLEND, same as `false` in earlier versions + * @property {number} YES - Alias for CLEAR, same as `true` in earlier versions + * @property {number} AUTO - Alias for BLIT + */ + var CLEAR_MODES$3; + (function (CLEAR_MODES) { + CLEAR_MODES[CLEAR_MODES["NO"] = 0] = "NO"; + CLEAR_MODES[CLEAR_MODES["YES"] = 1] = "YES"; + CLEAR_MODES[CLEAR_MODES["AUTO"] = 2] = "AUTO"; + CLEAR_MODES[CLEAR_MODES["BLEND"] = 0] = "BLEND"; + CLEAR_MODES[CLEAR_MODES["CLEAR"] = 1] = "CLEAR"; + CLEAR_MODES[CLEAR_MODES["BLIT"] = 2] = "BLIT"; + })(CLEAR_MODES$3 || (CLEAR_MODES$3 = {})); + /** + * The gc modes that are supported by pixi. + * + * The {@link PIXI.settings.GC_MODE} Garbage Collection mode for PixiJS textures is AUTO + * If set to GC_MODE, the renderer will occasionally check textures usage. If they are not + * used for a specified period of time they will be removed from the GPU. They will of course + * be uploaded again when they are required. This is a silent behind the scenes process that + * should ensure that the GPU does not get filled up. + * + * Handy for mobile devices! + * This property only affects WebGL. + * @name GC_MODES + * @enum {number} + * @static + * @memberof PIXI + * @property {number} AUTO - Garbage collection will happen periodically automatically + * @property {number} MANUAL - Garbage collection will need to be called manually + */ + var GC_MODES$3; + (function (GC_MODES) { + GC_MODES[GC_MODES["AUTO"] = 0] = "AUTO"; + GC_MODES[GC_MODES["MANUAL"] = 1] = "MANUAL"; + })(GC_MODES$3 || (GC_MODES$3 = {})); + /** + * Constants that specify float precision in shaders. + * @name PRECISION + * @memberof PIXI + * @constant + * @static + * @enum {string} + * @property {string} [LOW='lowp'] - + * @property {string} [MEDIUM='mediump'] - + * @property {string} [HIGH='highp'] - + */ + var PRECISION$3; + (function (PRECISION) { + PRECISION["LOW"] = "lowp"; + PRECISION["MEDIUM"] = "mediump"; + PRECISION["HIGH"] = "highp"; + })(PRECISION$3 || (PRECISION$3 = {})); + /** + * Constants for mask implementations. + * We use `type` suffix because it leads to very different behaviours + * @name MASK_TYPES + * @memberof PIXI + * @static + * @enum {number} + * @property {number} NONE - Mask is ignored + * @property {number} SCISSOR - Scissor mask, rectangle on screen, cheap + * @property {number} STENCIL - Stencil mask, 1-bit, medium, works only if renderer supports stencil + * @property {number} SPRITE - Mask that uses SpriteMaskFilter, uses temporary RenderTexture + * @property {number} COLOR - Color mask (RGBA) + */ + var MASK_TYPES$3; + (function (MASK_TYPES) { + MASK_TYPES[MASK_TYPES["NONE"] = 0] = "NONE"; + MASK_TYPES[MASK_TYPES["SCISSOR"] = 1] = "SCISSOR"; + MASK_TYPES[MASK_TYPES["STENCIL"] = 2] = "STENCIL"; + MASK_TYPES[MASK_TYPES["SPRITE"] = 3] = "SPRITE"; + MASK_TYPES[MASK_TYPES["COLOR"] = 4] = "COLOR"; + })(MASK_TYPES$3 || (MASK_TYPES$3 = {})); + /** + * Bitwise OR of masks that indicate the color channels that are rendered to. + * @static + * @memberof PIXI + * @name COLOR_MASK_BITS + * @enum {number} + * @property {number} RED - Red channel. + * @property {number} GREEN - Green channel + * @property {number} BLUE - Blue channel. + * @property {number} ALPHA - Alpha channel. + */ + var COLOR_MASK_BITS$3; + (function (COLOR_MASK_BITS) { + COLOR_MASK_BITS[COLOR_MASK_BITS["RED"] = 1] = "RED"; + COLOR_MASK_BITS[COLOR_MASK_BITS["GREEN"] = 2] = "GREEN"; + COLOR_MASK_BITS[COLOR_MASK_BITS["BLUE"] = 4] = "BLUE"; + COLOR_MASK_BITS[COLOR_MASK_BITS["ALPHA"] = 8] = "ALPHA"; + })(COLOR_MASK_BITS$3 || (COLOR_MASK_BITS$3 = {})); + /** + * Constants for multi-sampling antialiasing. + * @see PIXI.Framebuffer#multisample + * @name MSAA_QUALITY + * @memberof PIXI + * @static + * @enum {number} + * @property {number} NONE - No multisampling for this renderTexture + * @property {number} LOW - Try 2 samples + * @property {number} MEDIUM - Try 4 samples + * @property {number} HIGH - Try 8 samples + */ + var MSAA_QUALITY$3; + (function (MSAA_QUALITY) { + MSAA_QUALITY[MSAA_QUALITY["NONE"] = 0] = "NONE"; + MSAA_QUALITY[MSAA_QUALITY["LOW"] = 2] = "LOW"; + MSAA_QUALITY[MSAA_QUALITY["MEDIUM"] = 4] = "MEDIUM"; + MSAA_QUALITY[MSAA_QUALITY["HIGH"] = 8] = "HIGH"; + })(MSAA_QUALITY$3 || (MSAA_QUALITY$3 = {})); + /** + * Constants for various buffer types in Pixi + * @see PIXI.BUFFER_TYPE + * @name BUFFER_TYPE + * @memberof PIXI + * @static + * @enum {number} + * @property {number} ELEMENT_ARRAY_BUFFER - buffer type for using as an index buffer + * @property {number} ARRAY_BUFFER - buffer type for using attribute data + * @property {number} UNIFORM_BUFFER - the buffer type is for uniform buffer objects + */ + var BUFFER_TYPE$3; + (function (BUFFER_TYPE) { + BUFFER_TYPE[BUFFER_TYPE["ELEMENT_ARRAY_BUFFER"] = 34963] = "ELEMENT_ARRAY_BUFFER"; + BUFFER_TYPE[BUFFER_TYPE["ARRAY_BUFFER"] = 34962] = "ARRAY_BUFFER"; + // NOT YET SUPPORTED + BUFFER_TYPE[BUFFER_TYPE["UNIFORM_BUFFER"] = 35345] = "UNIFORM_BUFFER"; + })(BUFFER_TYPE$3 || (BUFFER_TYPE$3 = {})); + + /** + * The BlurFilterPass applies a horizontal or vertical Gaussian blur to an object. + * @memberof PIXI.filters + */ + var BlurFilterPass = /** @class */ (function (_super) { + __extends$6(BlurFilterPass, _super); + /** + * @param horizontal - Do pass along the x-axis (`true`) or y-axis (`false`). + * @param strength - The strength of the blur filter. + * @param quality - The quality of the blur filter. + * @param resolution - The resolution of the blur filter. + * @param kernelSize - The kernelSize of the blur filter.Options: 5, 7, 9, 11, 13, 15. + */ + function BlurFilterPass(horizontal, strength, quality, resolution, kernelSize) { + if (strength === void 0) { strength = 8; } + if (quality === void 0) { quality = 4; } + if (resolution === void 0) { resolution = settings$1.FILTER_RESOLUTION; } + if (kernelSize === void 0) { kernelSize = 5; } + var _this = this; + var vertSrc = generateBlurVertSource(kernelSize, horizontal); + var fragSrc = generateBlurFragSource(kernelSize); + _this = _super.call(this, + // vertex shader + vertSrc, + // fragment shader + fragSrc) || this; + _this.horizontal = horizontal; + _this.resolution = resolution; + _this._quality = 0; + _this.quality = quality; + _this.blur = strength; + return _this; + } + /** + * Applies the filter. + * @param filterManager - The manager. + * @param input - The input target. + * @param output - The output target. + * @param clearMode - How to clear + */ + BlurFilterPass.prototype.apply = function (filterManager, input, output, clearMode) { + if (output) { + if (this.horizontal) { + this.uniforms.strength = (1 / output.width) * (output.width / input.width); + } + else { + this.uniforms.strength = (1 / output.height) * (output.height / input.height); + } + } + else { + if (this.horizontal) // eslint-disable-line + { + this.uniforms.strength = (1 / filterManager.renderer.width) * (filterManager.renderer.width / input.width); + } + else { + this.uniforms.strength = (1 / filterManager.renderer.height) * (filterManager.renderer.height / input.height); // eslint-disable-line + } + } + // screen space! + this.uniforms.strength *= this.strength; + this.uniforms.strength /= this.passes; + if (this.passes === 1) { + filterManager.applyFilter(this, input, output, clearMode); + } + else { + var renderTarget = filterManager.getFilterTexture(); + var renderer = filterManager.renderer; + var flip = input; + var flop = renderTarget; + this.state.blend = false; + filterManager.applyFilter(this, flip, flop, CLEAR_MODES$3.CLEAR); + for (var i = 1; i < this.passes - 1; i++) { + filterManager.bindAndClear(flip, CLEAR_MODES$3.BLIT); + this.uniforms.uSampler = flop; + var temp = flop; + flop = flip; + flip = temp; + renderer.shader.bind(this); + renderer.geometry.draw(5); + } + this.state.blend = true; + filterManager.applyFilter(this, flop, output, clearMode); + filterManager.returnFilterTexture(renderTarget); + } + }; + Object.defineProperty(BlurFilterPass.prototype, "blur", { + /** + * Sets the strength of both the blur. + * @default 16 + */ + get: function () { + return this.strength; + }, + set: function (value) { + this.padding = 1 + (Math.abs(value) * 2); + this.strength = value; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(BlurFilterPass.prototype, "quality", { + /** + * Sets the quality of the blur by modifying the number of passes. More passes means higher + * quality bluring but the lower the performance. + * @default 4 + */ + get: function () { + return this._quality; + }, + set: function (value) { + this._quality = value; + this.passes = value; + }, + enumerable: false, + configurable: true + }); + return BlurFilterPass; + }(Filter)); + + /** + * The BlurFilter applies a Gaussian blur to an object. + * + * The strength of the blur can be set for the x-axis and y-axis separately. + * @memberof PIXI.filters + */ + var BlurFilter = /** @class */ (function (_super) { + __extends$6(BlurFilter, _super); + /** + * @param strength - The strength of the blur filter. + * @param quality - The quality of the blur filter. + * @param [resolution=PIXI.settings.FILTER_RESOLUTION] - The resolution of the blur filter. + * @param kernelSize - The kernelSize of the blur filter.Options: 5, 7, 9, 11, 13, 15. + */ + function BlurFilter(strength, quality, resolution, kernelSize) { + if (strength === void 0) { strength = 8; } + if (quality === void 0) { quality = 4; } + if (resolution === void 0) { resolution = settings$1.FILTER_RESOLUTION; } + if (kernelSize === void 0) { kernelSize = 5; } + var _this = _super.call(this) || this; + _this.blurXFilter = new BlurFilterPass(true, strength, quality, resolution, kernelSize); + _this.blurYFilter = new BlurFilterPass(false, strength, quality, resolution, kernelSize); + _this.resolution = resolution; + _this.quality = quality; + _this.blur = strength; + _this.repeatEdgePixels = false; + return _this; + } + /** + * Applies the filter. + * @param filterManager - The manager. + * @param input - The input target. + * @param output - The output target. + * @param clearMode - How to clear + */ + BlurFilter.prototype.apply = function (filterManager, input, output, clearMode) { + var xStrength = Math.abs(this.blurXFilter.strength); + var yStrength = Math.abs(this.blurYFilter.strength); + if (xStrength && yStrength) { + var renderTarget = filterManager.getFilterTexture(); + this.blurXFilter.apply(filterManager, input, renderTarget, CLEAR_MODES$3.CLEAR); + this.blurYFilter.apply(filterManager, renderTarget, output, clearMode); + filterManager.returnFilterTexture(renderTarget); + } + else if (yStrength) { + this.blurYFilter.apply(filterManager, input, output, clearMode); + } + else { + this.blurXFilter.apply(filterManager, input, output, clearMode); + } + }; + BlurFilter.prototype.updatePadding = function () { + if (this._repeatEdgePixels) { + this.padding = 0; + } + else { + this.padding = Math.max(Math.abs(this.blurXFilter.strength), Math.abs(this.blurYFilter.strength)) * 2; + } + }; + Object.defineProperty(BlurFilter.prototype, "blur", { + /** + * Sets the strength of both the blurX and blurY properties simultaneously + * @default 2 + */ + get: function () { + return this.blurXFilter.blur; + }, + set: function (value) { + this.blurXFilter.blur = this.blurYFilter.blur = value; + this.updatePadding(); + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(BlurFilter.prototype, "quality", { + /** + * Sets the number of passes for blur. More passes means higher quality bluring. + * @default 1 + */ + get: function () { + return this.blurXFilter.quality; + }, + set: function (value) { + this.blurXFilter.quality = this.blurYFilter.quality = value; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(BlurFilter.prototype, "blurX", { + /** + * Sets the strength of the blurX property + * @default 2 + */ + get: function () { + return this.blurXFilter.blur; + }, + set: function (value) { + this.blurXFilter.blur = value; + this.updatePadding(); + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(BlurFilter.prototype, "blurY", { + /** + * Sets the strength of the blurY property + * @default 2 + */ + get: function () { + return this.blurYFilter.blur; + }, + set: function (value) { + this.blurYFilter.blur = value; + this.updatePadding(); + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(BlurFilter.prototype, "blendMode", { + /** + * Sets the blendmode of the filter + * @default PIXI.BLEND_MODES.NORMAL + */ + get: function () { + return this.blurYFilter.blendMode; + }, + set: function (value) { + this.blurYFilter.blendMode = value; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(BlurFilter.prototype, "repeatEdgePixels", { + /** + * If set to true the edge of the target will be clamped + * @default false + */ + get: function () { + return this._repeatEdgePixels; + }, + set: function (value) { + this._repeatEdgePixels = value; + this.updatePadding(); + }, + enumerable: false, + configurable: true + }); + return BlurFilter; + }(Filter)); + + /*! + * @pixi/filter-color-matrix - v6.5.3 + * Compiled Fri, 09 Sep 2022 13:55:20 UTC + * + * @pixi/filter-color-matrix is licensed under the MIT License. + * http://www.opensource.org/licenses/mit-license + */ + + /*! ***************************************************************************** + Copyright (c) Microsoft Corporation. - function __param(paramIndex, decorator) { - return function (target, key) { decorator(target, key, paramIndex); } - } + Permission to use, copy, modify, and/or distribute this software for any + purpose with or without fee is hereby granted. - function __metadata(metadataKey, metadataValue) { - if (typeof Reflect === "object" && typeof Reflect.metadata === "function") { return Reflect.metadata(metadataKey, metadataValue); } - } + THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH + REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY + AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, + INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM + LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR + OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR + PERFORMANCE OF THIS SOFTWARE. + ***************************************************************************** */ + /* global Reflect, Promise */ - function __awaiter(thisArg, _arguments, P, generator) { - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - } + var extendStatics$5 = function(d, b) { + extendStatics$5 = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) { if (b.hasOwnProperty(p)) { d[p] = b[p]; } } }; + return extendStatics$5(d, b); + }; - function __generator(thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) { throw t[1]; } return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) { throw new TypeError("Generator is already executing."); } - while (_) { try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) { return t; } - if (y = 0, t) { op = [op[0] & 2, t.value]; } - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) { _.ops.pop(); } - _.trys.pop(); continue; - } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } } - if (op[0] & 5) { throw op[1]; } return { value: op[0] ? op[1] : void 0, done: true }; - } - } + function __extends$5(d, b) { + extendStatics$5(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + } + + var fragment$3 = "varying vec2 vTextureCoord;\nuniform sampler2D uSampler;\nuniform float m[20];\nuniform float uAlpha;\n\nvoid main(void)\n{\n vec4 c = texture2D(uSampler, vTextureCoord);\n\n if (uAlpha == 0.0) {\n gl_FragColor = c;\n return;\n }\n\n // Un-premultiply alpha before applying the color matrix. See issue #3539.\n if (c.a > 0.0) {\n c.rgb /= c.a;\n }\n\n vec4 result;\n\n result.r = (m[0] * c.r);\n result.r += (m[1] * c.g);\n result.r += (m[2] * c.b);\n result.r += (m[3] * c.a);\n result.r += m[4];\n\n result.g = (m[5] * c.r);\n result.g += (m[6] * c.g);\n result.g += (m[7] * c.b);\n result.g += (m[8] * c.a);\n result.g += m[9];\n\n result.b = (m[10] * c.r);\n result.b += (m[11] * c.g);\n result.b += (m[12] * c.b);\n result.b += (m[13] * c.a);\n result.b += m[14];\n\n result.a = (m[15] * c.r);\n result.a += (m[16] * c.g);\n result.a += (m[17] * c.b);\n result.a += (m[18] * c.a);\n result.a += m[19];\n\n vec3 rgb = mix(c.rgb, result.rgb, uAlpha);\n\n // Premultiply alpha again.\n rgb *= result.a;\n\n gl_FragColor = vec4(rgb, result.a);\n}\n"; + + /** + * The ColorMatrixFilter class lets you apply a 5x4 matrix transformation on the RGBA + * color and alpha values of every pixel on your displayObject to produce a result + * with a new set of RGBA color and alpha values. It's pretty powerful! + * + * ```js + * let colorMatrix = new PIXI.filters.ColorMatrixFilter(); + * container.filters = [colorMatrix]; + * colorMatrix.contrast(2); + * ``` + * @author Clément Chenebault + * @memberof PIXI.filters + */ + var ColorMatrixFilter = /** @class */ (function (_super) { + __extends$5(ColorMatrixFilter, _super); + function ColorMatrixFilter() { + var _this = this; + var uniforms = { + m: new Float32Array([1, 0, 0, 0, 0, + 0, 1, 0, 0, 0, + 0, 0, 1, 0, 0, + 0, 0, 0, 1, 0]), + uAlpha: 1, + }; + _this = _super.call(this, defaultFilterVertex, fragment$3, uniforms) || this; + _this.alpha = 1; + return _this; + } + /** + * Transforms current matrix and set the new one + * @param {number[]} matrix - 5x4 matrix + * @param multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + ColorMatrixFilter.prototype._loadMatrix = function (matrix, multiply) { + if (multiply === void 0) { multiply = false; } + var newMatrix = matrix; + if (multiply) { + this._multiply(newMatrix, this.uniforms.m, matrix); + newMatrix = this._colorMatrix(newMatrix); + } + // set the new matrix + this.uniforms.m = newMatrix; + }; + /** + * Multiplies two mat5's + * @private + * @param out - 5x4 matrix the receiving matrix + * @param a - 5x4 matrix the first operand + * @param b - 5x4 matrix the second operand + * @returns {number[]} 5x4 matrix + */ + ColorMatrixFilter.prototype._multiply = function (out, a, b) { + // Red Channel + out[0] = (a[0] * b[0]) + (a[1] * b[5]) + (a[2] * b[10]) + (a[3] * b[15]); + out[1] = (a[0] * b[1]) + (a[1] * b[6]) + (a[2] * b[11]) + (a[3] * b[16]); + out[2] = (a[0] * b[2]) + (a[1] * b[7]) + (a[2] * b[12]) + (a[3] * b[17]); + out[3] = (a[0] * b[3]) + (a[1] * b[8]) + (a[2] * b[13]) + (a[3] * b[18]); + out[4] = (a[0] * b[4]) + (a[1] * b[9]) + (a[2] * b[14]) + (a[3] * b[19]) + a[4]; + // Green Channel + out[5] = (a[5] * b[0]) + (a[6] * b[5]) + (a[7] * b[10]) + (a[8] * b[15]); + out[6] = (a[5] * b[1]) + (a[6] * b[6]) + (a[7] * b[11]) + (a[8] * b[16]); + out[7] = (a[5] * b[2]) + (a[6] * b[7]) + (a[7] * b[12]) + (a[8] * b[17]); + out[8] = (a[5] * b[3]) + (a[6] * b[8]) + (a[7] * b[13]) + (a[8] * b[18]); + out[9] = (a[5] * b[4]) + (a[6] * b[9]) + (a[7] * b[14]) + (a[8] * b[19]) + a[9]; + // Blue Channel + out[10] = (a[10] * b[0]) + (a[11] * b[5]) + (a[12] * b[10]) + (a[13] * b[15]); + out[11] = (a[10] * b[1]) + (a[11] * b[6]) + (a[12] * b[11]) + (a[13] * b[16]); + out[12] = (a[10] * b[2]) + (a[11] * b[7]) + (a[12] * b[12]) + (a[13] * b[17]); + out[13] = (a[10] * b[3]) + (a[11] * b[8]) + (a[12] * b[13]) + (a[13] * b[18]); + out[14] = (a[10] * b[4]) + (a[11] * b[9]) + (a[12] * b[14]) + (a[13] * b[19]) + a[14]; + // Alpha Channel + out[15] = (a[15] * b[0]) + (a[16] * b[5]) + (a[17] * b[10]) + (a[18] * b[15]); + out[16] = (a[15] * b[1]) + (a[16] * b[6]) + (a[17] * b[11]) + (a[18] * b[16]); + out[17] = (a[15] * b[2]) + (a[16] * b[7]) + (a[17] * b[12]) + (a[18] * b[17]); + out[18] = (a[15] * b[3]) + (a[16] * b[8]) + (a[17] * b[13]) + (a[18] * b[18]); + out[19] = (a[15] * b[4]) + (a[16] * b[9]) + (a[17] * b[14]) + (a[18] * b[19]) + a[19]; + return out; + }; + /** + * Create a Float32 Array and normalize the offset component to 0-1 + * @param {number[]} matrix - 5x4 matrix + * @returns {number[]} 5x4 matrix with all values between 0-1 + */ + ColorMatrixFilter.prototype._colorMatrix = function (matrix) { + // Create a Float32 Array and normalize the offset component to 0-1 + var m = new Float32Array(matrix); + m[4] /= 255; + m[9] /= 255; + m[14] /= 255; + m[19] /= 255; + return m; + }; + /** + * Adjusts brightness + * @param b - value of the brigthness (0-1, where 0 is black) + * @param multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + ColorMatrixFilter.prototype.brightness = function (b, multiply) { + var matrix = [ + b, 0, 0, 0, 0, + 0, b, 0, 0, 0, + 0, 0, b, 0, 0, + 0, 0, 0, 1, 0 ]; + this._loadMatrix(matrix, multiply); + }; + /** + * Sets each channel on the diagonal of the color matrix. + * This can be used to achieve a tinting effect on Containers similar to the tint field of some + * display objects like Sprite, Text, Graphics, and Mesh. + * @param color - Color of the tint. This is a hex value. + * @param multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + ColorMatrixFilter.prototype.tint = function (color, multiply) { + var r = (color >> 16) & 0xff; + var g = (color >> 8) & 0xff; + var b = color & 0xff; + var matrix = [ + r / 255, 0, 0, 0, 0, + 0, g / 255, 0, 0, 0, + 0, 0, b / 255, 0, 0, + 0, 0, 0, 1, 0 ]; + this._loadMatrix(matrix, multiply); + }; + /** + * Set the matrices in grey scales + * @param scale - value of the grey (0-1, where 0 is black) + * @param multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + ColorMatrixFilter.prototype.greyscale = function (scale, multiply) { + var matrix = [ + scale, scale, scale, 0, 0, + scale, scale, scale, 0, 0, + scale, scale, scale, 0, 0, + 0, 0, 0, 1, 0 ]; + this._loadMatrix(matrix, multiply); + }; + /** + * Set the black and white matrice. + * @param multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + ColorMatrixFilter.prototype.blackAndWhite = function (multiply) { + var matrix = [ + 0.3, 0.6, 0.1, 0, 0, + 0.3, 0.6, 0.1, 0, 0, + 0.3, 0.6, 0.1, 0, 0, + 0, 0, 0, 1, 0 ]; + this._loadMatrix(matrix, multiply); + }; + /** + * Set the hue property of the color + * @param rotation - in degrees + * @param multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + ColorMatrixFilter.prototype.hue = function (rotation, multiply) { + rotation = (rotation || 0) / 180 * Math.PI; + var cosR = Math.cos(rotation); + var sinR = Math.sin(rotation); + var sqrt = Math.sqrt; + /* a good approximation for hue rotation + This matrix is far better than the versions with magic luminance constants + formerly used here, but also used in the starling framework (flash) and known from this + old part of the internet: quasimondo.com/archives/000565.php + + This new matrix is based on rgb cube rotation in space. Look here for a more descriptive + implementation as a shader not a general matrix: + https://github.com/evanw/glfx.js/blob/58841c23919bd59787effc0333a4897b43835412/src/filters/adjust/huesaturation.js + + This is the source for the code: + see http://stackoverflow.com/questions/8507885/shift-hue-of-an-rgb-color/8510751#8510751 + */ + var w = 1 / 3; + var sqrW = sqrt(w); // weight is + var a00 = cosR + ((1.0 - cosR) * w); + var a01 = (w * (1.0 - cosR)) - (sqrW * sinR); + var a02 = (w * (1.0 - cosR)) + (sqrW * sinR); + var a10 = (w * (1.0 - cosR)) + (sqrW * sinR); + var a11 = cosR + (w * (1.0 - cosR)); + var a12 = (w * (1.0 - cosR)) - (sqrW * sinR); + var a20 = (w * (1.0 - cosR)) - (sqrW * sinR); + var a21 = (w * (1.0 - cosR)) + (sqrW * sinR); + var a22 = cosR + (w * (1.0 - cosR)); + var matrix = [ + a00, a01, a02, 0, 0, + a10, a11, a12, 0, 0, + a20, a21, a22, 0, 0, + 0, 0, 0, 1, 0 ]; + this._loadMatrix(matrix, multiply); + }; + /** + * Set the contrast matrix, increase the separation between dark and bright + * Increase contrast : shadows darker and highlights brighter + * Decrease contrast : bring the shadows up and the highlights down + * @param amount - value of the contrast (0-1) + * @param multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + ColorMatrixFilter.prototype.contrast = function (amount, multiply) { + var v = (amount || 0) + 1; + var o = -0.5 * (v - 1); + var matrix = [ + v, 0, 0, 0, o, + 0, v, 0, 0, o, + 0, 0, v, 0, o, + 0, 0, 0, 1, 0 ]; + this._loadMatrix(matrix, multiply); + }; + /** + * Set the saturation matrix, increase the separation between colors + * Increase saturation : increase contrast, brightness, and sharpness + * @param amount - The saturation amount (0-1) + * @param multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + ColorMatrixFilter.prototype.saturate = function (amount, multiply) { + if (amount === void 0) { amount = 0; } + var x = (amount * 2 / 3) + 1; + var y = ((x - 1) * -0.5); + var matrix = [ + x, y, y, 0, 0, + y, x, y, 0, 0, + y, y, x, 0, 0, + 0, 0, 0, 1, 0 ]; + this._loadMatrix(matrix, multiply); + }; + /** Desaturate image (remove color) Call the saturate function */ + ColorMatrixFilter.prototype.desaturate = function () { + this.saturate(-1); + }; + /** + * Negative image (inverse of classic rgb matrix) + * @param multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + ColorMatrixFilter.prototype.negative = function (multiply) { + var matrix = [ + -1, 0, 0, 1, 0, + 0, -1, 0, 1, 0, + 0, 0, -1, 1, 0, + 0, 0, 0, 1, 0 ]; + this._loadMatrix(matrix, multiply); + }; + /** + * Sepia image + * @param multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + ColorMatrixFilter.prototype.sepia = function (multiply) { + var matrix = [ + 0.393, 0.7689999, 0.18899999, 0, 0, + 0.349, 0.6859999, 0.16799999, 0, 0, + 0.272, 0.5339999, 0.13099999, 0, 0, + 0, 0, 0, 1, 0 ]; + this._loadMatrix(matrix, multiply); + }; + /** + * Color motion picture process invented in 1916 (thanks Dominic Szablewski) + * @param multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + ColorMatrixFilter.prototype.technicolor = function (multiply) { + var matrix = [ + 1.9125277891456083, -0.8545344976951645, -0.09155508482755585, 0, 11.793603434377337, + -0.3087833385928097, 1.7658908555458428, -0.10601743074722245, 0, -70.35205161461398, + -0.231103377548616, -0.7501899197440212, 1.847597816108189, 0, 30.950940869491138, + 0, 0, 0, 1, 0 ]; + this._loadMatrix(matrix, multiply); + }; + /** + * Polaroid filter + * @param multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + ColorMatrixFilter.prototype.polaroid = function (multiply) { + var matrix = [ + 1.438, -0.062, -0.062, 0, 0, + -0.122, 1.378, -0.122, 0, 0, + -0.016, -0.016, 1.483, 0, 0, + 0, 0, 0, 1, 0 ]; + this._loadMatrix(matrix, multiply); + }; + /** + * Filter who transforms : Red -> Blue and Blue -> Red + * @param multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + ColorMatrixFilter.prototype.toBGR = function (multiply) { + var matrix = [ + 0, 0, 1, 0, 0, + 0, 1, 0, 0, 0, + 1, 0, 0, 0, 0, + 0, 0, 0, 1, 0 ]; + this._loadMatrix(matrix, multiply); + }; + /** + * Color reversal film introduced by Eastman Kodak in 1935. (thanks Dominic Szablewski) + * @param multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + ColorMatrixFilter.prototype.kodachrome = function (multiply) { + var matrix = [ + 1.1285582396593525, -0.3967382283601348, -0.03992559172921793, 0, 63.72958762196502, + -0.16404339962244616, 1.0835251566291304, -0.05498805115633132, 0, 24.732407896706203, + -0.16786010706155763, -0.5603416277695248, 1.6014850761964943, 0, 35.62982807460946, + 0, 0, 0, 1, 0 ]; + this._loadMatrix(matrix, multiply); + }; + /** + * Brown delicious browni filter (thanks Dominic Szablewski) + * @param multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + ColorMatrixFilter.prototype.browni = function (multiply) { + var matrix = [ + 0.5997023498159715, 0.34553243048391263, -0.2708298674538042, 0, 47.43192855600873, + -0.037703249837783157, 0.8609577587992641, 0.15059552388459913, 0, -36.96841498319127, + 0.24113635128153335, -0.07441037908422492, 0.44972182064877153, 0, -7.562075277591283, + 0, 0, 0, 1, 0 ]; + this._loadMatrix(matrix, multiply); + }; + /** + * Vintage filter (thanks Dominic Szablewski) + * @param multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + ColorMatrixFilter.prototype.vintage = function (multiply) { + var matrix = [ + 0.6279345635605994, 0.3202183420819367, -0.03965408211312453, 0, 9.651285835294123, + 0.02578397704808868, 0.6441188644374771, 0.03259127616149294, 0, 7.462829176470591, + 0.0466055556782719, -0.0851232987247891, 0.5241648018700465, 0, 5.159190588235296, + 0, 0, 0, 1, 0 ]; + this._loadMatrix(matrix, multiply); + }; + /** + * We don't know exactly what it does, kind of gradient map, but funny to play with! + * @param desaturation - Tone values. + * @param toned - Tone values. + * @param lightColor - Tone values, example: `0xFFE580` + * @param darkColor - Tone values, example: `0xFFE580` + * @param multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + ColorMatrixFilter.prototype.colorTone = function (desaturation, toned, lightColor, darkColor, multiply) { + desaturation = desaturation || 0.2; + toned = toned || 0.15; + lightColor = lightColor || 0xFFE580; + darkColor = darkColor || 0x338000; + var lR = ((lightColor >> 16) & 0xFF) / 255; + var lG = ((lightColor >> 8) & 0xFF) / 255; + var lB = (lightColor & 0xFF) / 255; + var dR = ((darkColor >> 16) & 0xFF) / 255; + var dG = ((darkColor >> 8) & 0xFF) / 255; + var dB = (darkColor & 0xFF) / 255; + var matrix = [ + 0.3, 0.59, 0.11, 0, 0, + lR, lG, lB, desaturation, 0, + dR, dG, dB, toned, 0, + lR - dR, lG - dG, lB - dB, 0, 0 ]; + this._loadMatrix(matrix, multiply); + }; + /** + * Night effect + * @param intensity - The intensity of the night effect. + * @param multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + ColorMatrixFilter.prototype.night = function (intensity, multiply) { + intensity = intensity || 0.1; + var matrix = [ + intensity * (-2.0), -intensity, 0, 0, 0, + -intensity, 0, intensity, 0, 0, + 0, intensity, intensity * 2.0, 0, 0, + 0, 0, 0, 1, 0 ]; + this._loadMatrix(matrix, multiply); + }; + /** + * Predator effect + * + * Erase the current matrix by setting a new indepent one + * @param amount - how much the predator feels his future victim + * @param multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + ColorMatrixFilter.prototype.predator = function (amount, multiply) { + var matrix = [ + // row 1 + 11.224130630493164 * amount, + -4.794486999511719 * amount, + -2.8746118545532227 * amount, + 0 * amount, + 0.40342438220977783 * amount, + // row 2 + -3.6330697536468506 * amount, + 9.193157196044922 * amount, + -2.951810836791992 * amount, + 0 * amount, + -1.316135048866272 * amount, + // row 3 + -3.2184197902679443 * amount, + -4.2375030517578125 * amount, + 7.476448059082031 * amount, + 0 * amount, + 0.8044459223747253 * amount, + // row 4 + 0, 0, 0, 1, 0 ]; + this._loadMatrix(matrix, multiply); + }; + /** + * LSD effect + * + * Multiply the current matrix + * @param multiply - if true, current matrix and matrix are multiplied. If false, + * just set the current matrix with @param matrix + */ + ColorMatrixFilter.prototype.lsd = function (multiply) { + var matrix = [ + 2, -0.4, 0.5, 0, 0, + -0.5, 2, -0.4, 0, 0, + -0.4, -0.5, 3, 0, 0, + 0, 0, 0, 1, 0 ]; + this._loadMatrix(matrix, multiply); + }; + /** Erase the current matrix by setting the default one. */ + ColorMatrixFilter.prototype.reset = function () { + var matrix = [ + 1, 0, 0, 0, 0, + 0, 1, 0, 0, 0, + 0, 0, 1, 0, 0, + 0, 0, 0, 1, 0 ]; + this._loadMatrix(matrix, false); + }; + Object.defineProperty(ColorMatrixFilter.prototype, "matrix", { + /** + * The matrix of the color matrix filter + * @member {number[]} + * @default [1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0] + */ + get: function () { + return this.uniforms.m; + }, + set: function (value) { + this.uniforms.m = value; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(ColorMatrixFilter.prototype, "alpha", { + /** + * The opacity value to use when mixing the original and resultant colors. + * + * When the value is 0, the original color is used without modification. + * When the value is 1, the result color is used. + * When in the range (0, 1) the color is interpolated between the original and result by this amount. + * @default 1 + */ + get: function () { + return this.uniforms.uAlpha; + }, + set: function (value) { + this.uniforms.uAlpha = value; + }, + enumerable: false, + configurable: true + }); + return ColorMatrixFilter; + }(Filter)); + // Americanized alias + ColorMatrixFilter.prototype.grayscale = ColorMatrixFilter.prototype.greyscale; + + /*! + * @pixi/filter-displacement - v6.5.3 + * Compiled Fri, 09 Sep 2022 13:55:20 UTC + * + * @pixi/filter-displacement is licensed under the MIT License. + * http://www.opensource.org/licenses/mit-license + */ + + /*! ***************************************************************************** + Copyright (c) Microsoft Corporation. - function __exportStar(m, exports) { - for (var p in m) { if (!exports.hasOwnProperty(p)) { exports[p] = m[p]; } } - } + Permission to use, copy, modify, and/or distribute this software for any + purpose with or without fee is hereby granted. - function __values(o) { - var m = typeof Symbol === "function" && o[Symbol.iterator], i = 0; - if (m) { return m.call(o); } - return { - next: function () { - if (o && i >= o.length) { o = void 0; } - return { value: o && o[i++], done: !o }; - } - }; - } + THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH + REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY + AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, + INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM + LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR + OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR + PERFORMANCE OF THIS SOFTWARE. + ***************************************************************************** */ + /* global Reflect, Promise */ - function __read(o, n) { - var m = typeof Symbol === "function" && o[Symbol.iterator]; - if (!m) { return o; } - var i = m.call(o), r, ar = [], e; - try { - while ((n === void 0 || n-- > 0) && !(r = i.next()).done) { ar.push(r.value); } - } - catch (error) { e = { error: error }; } - finally { - try { - if (r && !r.done && (m = i["return"])) { m.call(i); } - } - finally { if (e) { throw e.error; } } - } - return ar; - } + var extendStatics$4 = function(d, b) { + extendStatics$4 = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) { if (b.hasOwnProperty(p)) { d[p] = b[p]; } } }; + return extendStatics$4(d, b); + }; - function __spread() { - var arguments$1 = arguments; + function __extends$4(d, b) { + extendStatics$4(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + } + + var fragment$2 = "varying vec2 vFilterCoord;\nvarying vec2 vTextureCoord;\n\nuniform vec2 scale;\nuniform mat2 rotation;\nuniform sampler2D uSampler;\nuniform sampler2D mapSampler;\n\nuniform highp vec4 inputSize;\nuniform vec4 inputClamp;\n\nvoid main(void)\n{\n vec4 map = texture2D(mapSampler, vFilterCoord);\n\n map -= 0.5;\n map.xy = scale * inputSize.zw * (rotation * map.xy);\n\n gl_FragColor = texture2D(uSampler, clamp(vec2(vTextureCoord.x + map.x, vTextureCoord.y + map.y), inputClamp.xy, inputClamp.zw));\n}\n"; + + var vertex$1 = "attribute vec2 aVertexPosition;\n\nuniform mat3 projectionMatrix;\nuniform mat3 filterMatrix;\n\nvarying vec2 vTextureCoord;\nvarying vec2 vFilterCoord;\n\nuniform vec4 inputSize;\nuniform vec4 outputFrame;\n\nvec4 filterVertexPosition( void )\n{\n vec2 position = aVertexPosition * max(outputFrame.zw, vec2(0.)) + outputFrame.xy;\n\n return vec4((projectionMatrix * vec3(position, 1.0)).xy, 0.0, 1.0);\n}\n\nvec2 filterTextureCoord( void )\n{\n return aVertexPosition * (outputFrame.zw * inputSize.zw);\n}\n\nvoid main(void)\n{\n\tgl_Position = filterVertexPosition();\n\tvTextureCoord = filterTextureCoord();\n\tvFilterCoord = ( filterMatrix * vec3( vTextureCoord, 1.0) ).xy;\n}\n"; + + /** + * The DisplacementFilter class uses the pixel values from the specified texture + * (called the displacement map) to perform a displacement of an object. + * + * You can use this filter to apply all manor of crazy warping effects. + * Currently the `r` property of the texture is used to offset the `x` + * and the `g` property of the texture is used to offset the `y`. + * + * The way it works is it uses the values of the displacement map to look up the + * correct pixels to output. This means it's not technically moving the original. + * Instead, it's starting at the output and asking "which pixel from the original goes here". + * For example, if a displacement map pixel has `red = 1` and the filter scale is `20`, + * this filter will output the pixel approximately 20 pixels to the right of the original. + * @memberof PIXI.filters + */ + var DisplacementFilter = /** @class */ (function (_super) { + __extends$4(DisplacementFilter, _super); + /** + * @param {PIXI.Sprite} sprite - The sprite used for the displacement map. (make sure its added to the scene!) + * @param scale - The scale of the displacement + */ + function DisplacementFilter(sprite, scale) { + var _this = this; + var maskMatrix = new Matrix(); + sprite.renderable = false; + _this = _super.call(this, vertex$1, fragment$2, { + mapSampler: sprite._texture, + filterMatrix: maskMatrix, + scale: { x: 1, y: 1 }, + rotation: new Float32Array([1, 0, 0, 1]), + }) || this; + _this.maskSprite = sprite; + _this.maskMatrix = maskMatrix; + if (scale === null || scale === undefined) { + scale = 20; + } + /** + * scaleX, scaleY for displacements + * @member {PIXI.Point} + */ + _this.scale = new Point(scale, scale); + return _this; + } + /** + * Applies the filter. + * @param filterManager - The manager. + * @param input - The input target. + * @param output - The output target. + * @param clearMode - clearMode. + */ + DisplacementFilter.prototype.apply = function (filterManager, input, output, clearMode) { + // fill maskMatrix with _normalized sprite texture coords_ + this.uniforms.filterMatrix = filterManager.calculateSpriteMatrix(this.maskMatrix, this.maskSprite); + this.uniforms.scale.x = this.scale.x; + this.uniforms.scale.y = this.scale.y; + // Extract rotation from world transform + var wt = this.maskSprite.worldTransform; + var lenX = Math.sqrt((wt.a * wt.a) + (wt.b * wt.b)); + var lenY = Math.sqrt((wt.c * wt.c) + (wt.d * wt.d)); + if (lenX !== 0 && lenY !== 0) { + this.uniforms.rotation[0] = wt.a / lenX; + this.uniforms.rotation[1] = wt.b / lenX; + this.uniforms.rotation[2] = wt.c / lenY; + this.uniforms.rotation[3] = wt.d / lenY; + } + // draw the filter... + filterManager.applyFilter(this, input, output, clearMode); + }; + Object.defineProperty(DisplacementFilter.prototype, "map", { + /** The texture used for the displacement map. Must be power of 2 sized texture. */ + get: function () { + return this.uniforms.mapSampler; + }, + set: function (value) { + this.uniforms.mapSampler = value; + }, + enumerable: false, + configurable: true + }); + return DisplacementFilter; + }(Filter)); + + /*! + * @pixi/filter-fxaa - v6.5.3 + * Compiled Fri, 09 Sep 2022 13:55:20 UTC + * + * @pixi/filter-fxaa is licensed under the MIT License. + * http://www.opensource.org/licenses/mit-license + */ + + /*! ***************************************************************************** + Copyright (c) Microsoft Corporation. - for (var ar = [], i = 0; i < arguments.length; i++) - { ar = ar.concat(__read(arguments$1[i])); } - return ar; - } + Permission to use, copy, modify, and/or distribute this software for any + purpose with or without fee is hereby granted. - function __await(v) { - return this instanceof __await ? (this.v = v, this) : new __await(v); - } + THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH + REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY + AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, + INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM + LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR + OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR + PERFORMANCE OF THIS SOFTWARE. + ***************************************************************************** */ + /* global Reflect, Promise */ - function __asyncGenerator(thisArg, _arguments, generator) { - if (!Symbol.asyncIterator) { throw new TypeError("Symbol.asyncIterator is not defined."); } - var g = generator.apply(thisArg, _arguments || []), i, q = []; - return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; - function verb(n) { if (g[n]) { i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } } - function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } - function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } - function fulfill(value) { resume("next", value); } - function reject(value) { resume("throw", value); } - function settle(f, v) { if (f(v), q.shift(), q.length) { resume(q[0][0], q[0][1]); } } - } + var extendStatics$3 = function(d, b) { + extendStatics$3 = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) { if (b.hasOwnProperty(p)) { d[p] = b[p]; } } }; + return extendStatics$3(d, b); + }; - function __asyncDelegator(o) { - var i, p; - return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i; - function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; } : f; } - } + function __extends$3(d, b) { + extendStatics$3(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + } + + var vertex = "\nattribute vec2 aVertexPosition;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 v_rgbNW;\nvarying vec2 v_rgbNE;\nvarying vec2 v_rgbSW;\nvarying vec2 v_rgbSE;\nvarying vec2 v_rgbM;\n\nvarying vec2 vFragCoord;\n\nuniform vec4 inputSize;\nuniform vec4 outputFrame;\n\nvec4 filterVertexPosition( void )\n{\n vec2 position = aVertexPosition * max(outputFrame.zw, vec2(0.)) + outputFrame.xy;\n\n return vec4((projectionMatrix * vec3(position, 1.0)).xy, 0.0, 1.0);\n}\n\nvoid texcoords(vec2 fragCoord, vec2 inverseVP,\n out vec2 v_rgbNW, out vec2 v_rgbNE,\n out vec2 v_rgbSW, out vec2 v_rgbSE,\n out vec2 v_rgbM) {\n v_rgbNW = (fragCoord + vec2(-1.0, -1.0)) * inverseVP;\n v_rgbNE = (fragCoord + vec2(1.0, -1.0)) * inverseVP;\n v_rgbSW = (fragCoord + vec2(-1.0, 1.0)) * inverseVP;\n v_rgbSE = (fragCoord + vec2(1.0, 1.0)) * inverseVP;\n v_rgbM = vec2(fragCoord * inverseVP);\n}\n\nvoid main(void) {\n\n gl_Position = filterVertexPosition();\n\n vFragCoord = aVertexPosition * outputFrame.zw;\n\n texcoords(vFragCoord, inputSize.zw, v_rgbNW, v_rgbNE, v_rgbSW, v_rgbSE, v_rgbM);\n}\n"; + + var fragment$1 = "varying vec2 v_rgbNW;\nvarying vec2 v_rgbNE;\nvarying vec2 v_rgbSW;\nvarying vec2 v_rgbSE;\nvarying vec2 v_rgbM;\n\nvarying vec2 vFragCoord;\nuniform sampler2D uSampler;\nuniform highp vec4 inputSize;\n\n\n/**\n Basic FXAA implementation based on the code on geeks3d.com with the\n modification that the texture2DLod stuff was removed since it's\n unsupported by WebGL.\n\n --\n\n From:\n https://github.com/mitsuhiko/webgl-meincraft\n\n Copyright (c) 2011 by Armin Ronacher.\n\n Some rights reserved.\n\n Redistribution and use in source and binary forms, with or without\n modification, are permitted provided that the following conditions are\n met:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n\n * Redistributions in binary form must reproduce the above\n copyright notice, this list of conditions and the following\n disclaimer in the documentation and/or other materials provided\n with the distribution.\n\n * The names of the contributors may not be used to endorse or\n promote products derived from this software without specific\n prior written permission.\n\n THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n#ifndef FXAA_REDUCE_MIN\n#define FXAA_REDUCE_MIN (1.0/ 128.0)\n#endif\n#ifndef FXAA_REDUCE_MUL\n#define FXAA_REDUCE_MUL (1.0 / 8.0)\n#endif\n#ifndef FXAA_SPAN_MAX\n#define FXAA_SPAN_MAX 8.0\n#endif\n\n//optimized version for mobile, where dependent\n//texture reads can be a bottleneck\nvec4 fxaa(sampler2D tex, vec2 fragCoord, vec2 inverseVP,\n vec2 v_rgbNW, vec2 v_rgbNE,\n vec2 v_rgbSW, vec2 v_rgbSE,\n vec2 v_rgbM) {\n vec4 color;\n vec3 rgbNW = texture2D(tex, v_rgbNW).xyz;\n vec3 rgbNE = texture2D(tex, v_rgbNE).xyz;\n vec3 rgbSW = texture2D(tex, v_rgbSW).xyz;\n vec3 rgbSE = texture2D(tex, v_rgbSE).xyz;\n vec4 texColor = texture2D(tex, v_rgbM);\n vec3 rgbM = texColor.xyz;\n vec3 luma = vec3(0.299, 0.587, 0.114);\n float lumaNW = dot(rgbNW, luma);\n float lumaNE = dot(rgbNE, luma);\n float lumaSW = dot(rgbSW, luma);\n float lumaSE = dot(rgbSE, luma);\n float lumaM = dot(rgbM, luma);\n float lumaMin = min(lumaM, min(min(lumaNW, lumaNE), min(lumaSW, lumaSE)));\n float lumaMax = max(lumaM, max(max(lumaNW, lumaNE), max(lumaSW, lumaSE)));\n\n mediump vec2 dir;\n dir.x = -((lumaNW + lumaNE) - (lumaSW + lumaSE));\n dir.y = ((lumaNW + lumaSW) - (lumaNE + lumaSE));\n\n float dirReduce = max((lumaNW + lumaNE + lumaSW + lumaSE) *\n (0.25 * FXAA_REDUCE_MUL), FXAA_REDUCE_MIN);\n\n float rcpDirMin = 1.0 / (min(abs(dir.x), abs(dir.y)) + dirReduce);\n dir = min(vec2(FXAA_SPAN_MAX, FXAA_SPAN_MAX),\n max(vec2(-FXAA_SPAN_MAX, -FXAA_SPAN_MAX),\n dir * rcpDirMin)) * inverseVP;\n\n vec3 rgbA = 0.5 * (\n texture2D(tex, fragCoord * inverseVP + dir * (1.0 / 3.0 - 0.5)).xyz +\n texture2D(tex, fragCoord * inverseVP + dir * (2.0 / 3.0 - 0.5)).xyz);\n vec3 rgbB = rgbA * 0.5 + 0.25 * (\n texture2D(tex, fragCoord * inverseVP + dir * -0.5).xyz +\n texture2D(tex, fragCoord * inverseVP + dir * 0.5).xyz);\n\n float lumaB = dot(rgbB, luma);\n if ((lumaB < lumaMin) || (lumaB > lumaMax))\n color = vec4(rgbA, texColor.a);\n else\n color = vec4(rgbB, texColor.a);\n return color;\n}\n\nvoid main() {\n\n vec4 color;\n\n color = fxaa(uSampler, vFragCoord, inputSize.zw, v_rgbNW, v_rgbNE, v_rgbSW, v_rgbSE, v_rgbM);\n\n gl_FragColor = color;\n}\n"; + + /** + * Basic FXAA (Fast Approximate Anti-Aliasing) implementation based on the code on geeks3d.com + * with the modification that the texture2DLod stuff was removed since it is unsupported by WebGL. + * @see https://github.com/mitsuhiko/webgl-meincraft + * @memberof PIXI.filters + */ + var FXAAFilter = /** @class */ (function (_super) { + __extends$3(FXAAFilter, _super); + function FXAAFilter() { + // TODO - needs work + return _super.call(this, vertex, fragment$1) || this; + } + return FXAAFilter; + }(Filter)); + + /*! + * @pixi/filter-noise - v6.5.3 + * Compiled Fri, 09 Sep 2022 13:55:20 UTC + * + * @pixi/filter-noise is licensed under the MIT License. + * http://www.opensource.org/licenses/mit-license + */ + + /*! ***************************************************************************** + Copyright (c) Microsoft Corporation. - function __asyncValues(o) { - if (!Symbol.asyncIterator) { throw new TypeError("Symbol.asyncIterator is not defined."); } - var m = o[Symbol.asyncIterator], i; - return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i); - function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; } - function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); } - } + Permission to use, copy, modify, and/or distribute this software for any + purpose with or without fee is hereby granted. - function __makeTemplateObject(cooked, raw) { - if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; } - return cooked; - }; + THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH + REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY + AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, + INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM + LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR + OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR + PERFORMANCE OF THIS SOFTWARE. + ***************************************************************************** */ + /* global Reflect, Promise */ - function __importStar(mod) { - if (mod && mod.__esModule) { return mod; } - var result = {}; - if (mod != null) { for (var k in mod) { if (Object.hasOwnProperty.call(mod, k)) { result[k] = mod[k]; } } } - result.default = mod; - return result; - } + var extendStatics$2 = function(d, b) { + extendStatics$2 = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) { if (b.hasOwnProperty(p)) { d[p] = b[p]; } } }; + return extendStatics$2(d, b); + }; - function __importDefault(mod) { - return (mod && mod.__esModule) ? mod : { default: mod }; - } - - var v5 = '5.0.0'; - /** - * Deprecations (backward compatibilities) are automatically applied for browser bundles - * in the UMD module format. If using Webpack or Rollup, you'll need to apply these - * deprecations manually by doing something like this: - * @example - * import * as PIXI from 'pixi.js'; - * PIXI.useDeprecated(); // MUST be bound to namespace - * @memberof PIXI - * @function useDeprecated - */ - // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types - function useDeprecated() { - // eslint-disable-next-line @typescript-eslint/no-this-alias - var PIXI = this; - Object.defineProperties(PIXI, { - /** - * @constant {RegExp|string} SVG_SIZE - * @memberof PIXI - * @see PIXI.resources.SVGResource.SVG_SIZE - * @deprecated since 5.0.0 - */ - SVG_SIZE: { - get: function () { - deprecation(v5, 'PIXI.utils.SVG_SIZE property has moved to PIXI.resources.SVGResource.SVG_SIZE'); - return PIXI.SVGResource.SVG_SIZE; - }, - }, - /** - * @class PIXI.TransformStatic - * @deprecated since 5.0.0 - * @see PIXI.Transform - */ - TransformStatic: { - get: function () { - deprecation(v5, 'PIXI.TransformStatic class has been removed, use PIXI.Transform'); - return PIXI.Transform; - }, - }, - /** - * @class PIXI.TransformBase - * @deprecated since 5.0.0 - * @see PIXI.Transform - */ - TransformBase: { - get: function () { - deprecation(v5, 'PIXI.TransformBase class has been removed, use PIXI.Transform'); - return PIXI.Transform; - }, - }, - /** - * Constants that specify the transform type. - * - * @static - * @constant - * @name TRANSFORM_MODE - * @memberof PIXI - * @enum {number} - * @deprecated since 5.0.0 - * @property {number} STATIC - * @property {number} DYNAMIC - */ - TRANSFORM_MODE: { - get: function () { - deprecation(v5, 'PIXI.TRANSFORM_MODE property has been removed'); - return { STATIC: 0, DYNAMIC: 1 }; - }, - }, - /** - * @class PIXI.WebGLRenderer - * @see PIXI.Renderer - * @deprecated since 5.0.0 - */ - WebGLRenderer: { - get: function () { - deprecation(v5, 'PIXI.WebGLRenderer class has moved to PIXI.Renderer'); - return PIXI.Renderer; - }, - }, - /** - * @class PIXI.CanvasRenderTarget - * @see PIXI.utils.CanvasRenderTarget - * @deprecated since 5.0.0 - */ - CanvasRenderTarget: { - get: function () { - deprecation(v5, 'PIXI.CanvasRenderTarget class has moved to PIXI.utils.CanvasRenderTarget'); - return PIXI.utils.CanvasRenderTarget; - }, - }, - /** - * @memberof PIXI - * @name loader - * @type {PIXI.Loader} - * @see PIXI.Loader.shared - * @deprecated since 5.0.0 - */ - loader: { - get: function () { - deprecation(v5, 'PIXI.loader instance has moved to PIXI.Loader.shared'); - return PIXI.Loader.shared; - }, - }, - /** - * @class PIXI.FilterManager - * @see PIXI.systems.FilterSystem - * @deprecated since 5.0.0 - */ - FilterManager: { - get: function () { - deprecation(v5, 'PIXI.FilterManager class has moved to PIXI.systems.FilterSystem'); - return PIXI.systems.FilterSystem; - }, - }, - /** - * @namespace PIXI.CanvasTinter - * @see PIXI.canvasUtils - * @deprecated since 5.2.0 - */ - CanvasTinter: { - get: function () { - deprecation('5.2.0', 'PIXI.CanvasTinter namespace has moved to PIXI.canvasUtils'); - return PIXI.canvasUtils; - }, - }, - /** - * @namespace PIXI.GroupD8 - * @see PIXI.groupD8 - * @deprecated since 5.2.0 - */ - GroupD8: { - get: function () { - deprecation('5.2.0', 'PIXI.GroupD8 namespace has moved to PIXI.groupD8'); - return PIXI.groupD8; - }, - }, - }); - /** - * @namespace PIXI.accessibility - * @see PIXI - * @deprecated since 5.3.0 - */ - PIXI.accessibility = {}; - Object.defineProperties(PIXI.accessibility, { - /** - * @class PIXI.accessibility.AccessibilityManager - * @deprecated since 5.3.0 - * @see PIXI.AccessibilityManager - */ - AccessibilityManager: { - get: function () { - deprecation('5.3.0', 'PIXI.accessibility.AccessibilityManager moved to PIXI.AccessibilityManager'); - return PIXI.AccessibilityManager; - }, - }, - }); - /** - * @namespace PIXI.interaction - * @see PIXI - * @deprecated since 5.3.0 - */ - PIXI.interaction = {}; - Object.defineProperties(PIXI.interaction, { - /** - * @class PIXI.interaction.InteractionManager - * @deprecated since 5.3.0 - * @see PIXI.InteractionManager - */ - InteractionManager: { - get: function () { - deprecation('5.3.0', 'PIXI.interaction.InteractionManager moved to PIXI.InteractionManager'); - return PIXI.InteractionManager; - }, - }, - /** - * @class PIXI.interaction.InteractionData - * @deprecated since 5.3.0 - * @see PIXI.InteractionData - */ - InteractionData: { - get: function () { - deprecation('5.3.0', 'PIXI.interaction.InteractionData moved to PIXI.InteractionData'); - return PIXI.InteractionData; - }, - }, - /** - * @class PIXI.interaction.InteractionEvent - * @deprecated since 5.3.0 - * @see PIXI.InteractionEvent - */ - InteractionEvent: { - get: function () { - deprecation('5.3.0', 'PIXI.interaction.InteractionEvent moved to PIXI.InteractionEvent'); - return PIXI.InteractionEvent; - }, - }, - }); - /** - * @namespace PIXI.prepare - * @see PIXI - * @deprecated since 5.2.1 - */ - PIXI.prepare = {}; - Object.defineProperties(PIXI.prepare, { - /** - * @class PIXI.prepare.BasePrepare - * @deprecated since 5.2.1 - * @see PIXI.BasePrepare - */ - BasePrepare: { - get: function () { - deprecation('5.2.1', 'PIXI.prepare.BasePrepare moved to PIXI.BasePrepare'); - return PIXI.BasePrepare; - }, - }, - /** - * @class PIXI.prepare.Prepare - * @deprecated since 5.2.1 - * @see PIXI.Prepare - */ - Prepare: { - get: function () { - deprecation('5.2.1', 'PIXI.prepare.Prepare moved to PIXI.Prepare'); - return PIXI.Prepare; - }, - }, - /** - * @class PIXI.prepare.CanvasPrepare - * @deprecated since 5.2.1 - * @see PIXI.CanvasPrepare - */ - CanvasPrepare: { - get: function () { - deprecation('5.2.1', 'PIXI.prepare.CanvasPrepare moved to PIXI.CanvasPrepare'); - return PIXI.CanvasPrepare; - }, - }, - }); - /** - * @namespace PIXI.extract - * @see PIXI - * @deprecated since 5.2.1 - */ - PIXI.extract = {}; - Object.defineProperties(PIXI.extract, { - /** - * @class PIXI.extract.Extract - * @deprecated since 5.2.1 - * @see PIXI.Extract - */ - Extract: { - get: function () { - deprecation('5.2.1', 'PIXI.extract.Extract moved to PIXI.Extract'); - return PIXI.Extract; - }, - }, - /** - * @class PIXI.extract.CanvasExtract - * @deprecated since 5.2.1 - * @see PIXI.CanvasExtract - */ - CanvasExtract: { - get: function () { - deprecation('5.2.1', 'PIXI.extract.CanvasExtract moved to PIXI.CanvasExtract'); - return PIXI.CanvasExtract; - }, - }, - }); - /** - * This namespace has been removed. All classes previous nested - * under this namespace have been moved to the top-level `PIXI` object. - * @namespace PIXI.extras - * @deprecated since 5.0.0 - */ - PIXI.extras = {}; - Object.defineProperties(PIXI.extras, { - /** - * @class PIXI.extras.TilingSprite - * @see PIXI.TilingSprite - * @deprecated since 5.0.0 - */ - TilingSprite: { - get: function () { - deprecation(v5, 'PIXI.extras.TilingSprite class has moved to PIXI.TilingSprite'); - return PIXI.TilingSprite; - }, - }, - /** - * @class PIXI.extras.TilingSpriteRenderer - * @see PIXI.TilingSpriteRenderer - * @deprecated since 5.0.0 - */ - TilingSpriteRenderer: { - get: function () { - deprecation(v5, 'PIXI.extras.TilingSpriteRenderer class has moved to PIXI.TilingSpriteRenderer'); - return PIXI.TilingSpriteRenderer; - }, - }, - /** - * @class PIXI.extras.AnimatedSprite - * @see PIXI.AnimatedSprite - * @deprecated since 5.0.0 - */ - AnimatedSprite: { - get: function () { - deprecation(v5, 'PIXI.extras.AnimatedSprite class has moved to PIXI.AnimatedSprite'); - return PIXI.AnimatedSprite; - }, - }, - /** - * @class PIXI.extras.BitmapText - * @see PIXI.BitmapText - * @deprecated since 5.0.0 - */ - BitmapText: { - get: function () { - deprecation(v5, 'PIXI.extras.BitmapText class has moved to PIXI.BitmapText'); - return PIXI.BitmapText; - }, - }, - }); - /** - * @static - * @method PIXI.TilingSprite.fromFrame - * @deprecated since 5.3.0 - * @see PIXI.TilingSprite.from - */ - PIXI.TilingSprite.fromFrame = function fromFrame(frameId, width, height) { - deprecation('5.3.0', 'TilingSprite.fromFrame is deprecated, use TilingSprite.from'); - return PIXI.TilingSprite.from(frameId, { width: width, height: height }); - }; - /** - * @static - * @method PIXI.TilingSprite.fromImage - * @deprecated since 5.3.0 - * @see PIXI.TilingSprite.from - */ - PIXI.TilingSprite.fromImage = function fromImage(imageId, width, height, options) { - if (options === void 0) { options = {}; } - deprecation('5.3.0', 'TilingSprite.fromImage is deprecated, use TilingSprite.from'); - // Fallback support for crossorigin, scaleMode parameters - if (options && typeof options !== 'object') { - options = { - // eslint-disable-next-line prefer-rest-params - scaleMode: arguments[4], - resourceOptions: { - // eslint-disable-next-line prefer-rest-params - crossorigin: arguments[3], - }, - }; - } - options.width = width; - options.height = height; - return PIXI.TilingSprite.from(imageId, options); - }; - Object.defineProperties(PIXI.utils, { - /** - * @function PIXI.utils.getSvgSize - * @see PIXI.resources.SVGResource.getSize - * @deprecated since 5.0.0 - */ - getSvgSize: { - get: function () { - deprecation(v5, 'PIXI.utils.getSvgSize function has moved to PIXI.resources.SVGResource.getSize'); - return PIXI.resources.SVGResource.getSize; - }, - }, - }); - /** - * All classes on this namespace have moved to the high-level `PIXI` object. - * @namespace PIXI.mesh - * @deprecated since 5.0.0 - */ - PIXI.mesh = {}; - Object.defineProperties(PIXI.mesh, { - /** - * @class PIXI.mesh.Mesh - * @see PIXI.SimpleMesh - * @deprecated since 5.0.0 - */ - Mesh: { - get: function () { - deprecation(v5, 'PIXI.mesh.Mesh class has moved to PIXI.SimpleMesh'); - return PIXI.SimpleMesh; - }, - }, - /** - * @class PIXI.mesh.NineSlicePlane - * @see PIXI.NineSlicePlane - * @deprecated since 5.0.0 - */ - NineSlicePlane: { - get: function () { - deprecation(v5, 'PIXI.mesh.NineSlicePlane class has moved to PIXI.NineSlicePlane'); - return PIXI.NineSlicePlane; - }, - }, - /** - * @class PIXI.mesh.Plane - * @see PIXI.SimplePlane - * @deprecated since 5.0.0 - */ - Plane: { - get: function () { - deprecation(v5, 'PIXI.mesh.Plane class has moved to PIXI.SimplePlane'); - return PIXI.SimplePlane; - }, - }, - /** - * @class PIXI.mesh.Rope - * @see PIXI.SimpleRope - * @deprecated since 5.0.0 - */ - Rope: { - get: function () { - deprecation(v5, 'PIXI.mesh.Rope class has moved to PIXI.SimpleRope'); - return PIXI.SimpleRope; - }, - }, - /** - * @class PIXI.mesh.RawMesh - * @see PIXI.Mesh - * @deprecated since 5.0.0 - */ - RawMesh: { - get: function () { - deprecation(v5, 'PIXI.mesh.RawMesh class has moved to PIXI.Mesh'); - return PIXI.Mesh; - }, - }, - /** - * @class PIXI.mesh.CanvasMeshRenderer - * @see PIXI.CanvasMeshRenderer - * @deprecated since 5.0.0 - */ - CanvasMeshRenderer: { - get: function () { - deprecation(v5, 'PIXI.mesh.CanvasMeshRenderer class has moved to PIXI.CanvasMeshRenderer'); - return PIXI.CanvasMeshRenderer; - }, - }, - /** - * @class PIXI.mesh.MeshRenderer - * @see PIXI.MeshRenderer - * @deprecated since 5.0.0 - */ - MeshRenderer: { - get: function () { - deprecation(v5, 'PIXI.mesh.MeshRenderer class has moved to PIXI.MeshRenderer'); - return PIXI.MeshRenderer; - }, - }, - }); - /** - * This namespace has been removed and items have been moved to - * the top-level `PIXI` object. - * @namespace PIXI.particles - * @deprecated since 5.0.0 - */ - PIXI.particles = {}; - Object.defineProperties(PIXI.particles, { - /** - * @class PIXI.particles.ParticleContainer - * @deprecated since 5.0.0 - * @see PIXI.ParticleContainer - */ - ParticleContainer: { - get: function () { - deprecation(v5, 'PIXI.particles.ParticleContainer class has moved to PIXI.ParticleContainer'); - return PIXI.ParticleContainer; - }, - }, - /** - * @class PIXI.particles.ParticleRenderer - * @deprecated since 5.0.0 - * @see PIXI.ParticleRenderer - */ - ParticleRenderer: { - get: function () { - deprecation(v5, 'PIXI.particles.ParticleRenderer class has moved to PIXI.ParticleRenderer'); - return PIXI.ParticleRenderer; - }, - }, - }); - /** - * This namespace has been removed and items have been moved to - * the top-level `PIXI` object. - * @namespace PIXI.ticker - * @deprecated since 5.0.0 - */ - PIXI.ticker = {}; - Object.defineProperties(PIXI.ticker, { - /** - * @class PIXI.ticker.Ticker - * @deprecated since 5.0.0 - * @see PIXI.Ticker - */ - Ticker: { - get: function () { - deprecation(v5, 'PIXI.ticker.Ticker class has moved to PIXI.Ticker'); - return PIXI.Ticker; - }, - }, - /** - * @name PIXI.ticker.shared - * @type {PIXI.Ticker} - * @deprecated since 5.0.0 - * @see PIXI.Ticker.shared - */ - shared: { - get: function () { - deprecation(v5, 'PIXI.ticker.shared instance has moved to PIXI.Ticker.shared'); - return PIXI.Ticker.shared; - }, - }, - }); - /** - * All classes on this namespace have moved to the high-level `PIXI` object. - * @namespace PIXI.loaders - * @deprecated since 5.0.0 - */ - PIXI.loaders = {}; - Object.defineProperties(PIXI.loaders, { - /** - * @class PIXI.loaders.Loader - * @see PIXI.Loader - * @deprecated since 5.0.0 - */ - Loader: { - get: function () { - deprecation(v5, 'PIXI.loaders.Loader class has moved to PIXI.Loader'); - return PIXI.Loader; - }, - }, - /** - * @class PIXI.loaders.Resource - * @see PIXI.LoaderResource - * @deprecated since 5.0.0 - */ - Resource: { - get: function () { - deprecation(v5, 'PIXI.loaders.Resource class has moved to PIXI.LoaderResource'); - return PIXI.LoaderResource; - }, - }, - /** - * @function PIXI.loaders.bitmapFontParser - * @see PIXI.BitmapFontLoader.use - * @deprecated since 5.0.0 - */ - bitmapFontParser: { - get: function () { - deprecation(v5, 'PIXI.loaders.bitmapFontParser function has moved to PIXI.BitmapFontLoader.use'); - return PIXI.BitmapFontLoader.use; - }, - }, - /** - * @function PIXI.loaders.parseBitmapFontData - * @deprecated since 5.0.0 - */ - parseBitmapFontData: { - get: function () { - deprecation(v5, 'PIXI.loaders.parseBitmapFontData function has removed'); - }, - }, - /** - * @function PIXI.loaders.spritesheetParser - * @see PIXI.SpritesheetLoader.use - * @deprecated since 5.0.0 - */ - spritesheetParser: { - get: function () { - deprecation(v5, 'PIXI.loaders.spritesheetParser function has moved to PIXI.SpritesheetLoader.use'); - return PIXI.SpritesheetLoader.use; - }, - }, - /** - * @function PIXI.loaders.getResourcePath - * @see PIXI.SpritesheetLoader.getResourcePath - * @deprecated since 5.0.0 - */ - getResourcePath: { - get: function () { - deprecation(v5, 'PIXI.loaders.getResourcePath property has moved to PIXI.SpritesheetLoader.getResourcePath'); - return PIXI.SpritesheetLoader.getResourcePath; - }, - }, - }); - /** - * @function PIXI.loaders.Loader.addPixiMiddleware - * @see PIXI.Loader.registerPlugin - * @deprecated since 5.0.0 - * @param {function} middleware - */ - PIXI.Loader.addPixiMiddleware = function addPixiMiddleware(middleware) { - deprecation(v5, 'PIXI.loaders.Loader.addPixiMiddleware function is deprecated, use PIXI.loaders.Loader.registerPlugin'); - return PIXI.loaders.Loader.registerPlugin({ use: middleware() }); - }; - // convenience for converting event name to signal name - var eventToSignal = function (event) { - return "on" + event.charAt(0).toUpperCase() + event.slice(1); - }; - Object.assign(PIXI.Loader.prototype, { - /** - * Use the corresponding signal, e.g., event `start`` is signal `onStart`. - * @method PIXI.Loader#on - * @deprecated since 5.0.0 - */ - on: function (event) { - var signal = eventToSignal(event); - deprecation(v5, "PIXI.Loader#on is completely deprecated, use PIXI.Loader#" + signal + ".add"); - }, - /** - * Use the corresponding signal, e.g., event `start`` is signal `onStart`. - * @method PIXI.Loader#once - * @deprecated since 5.0.0 - */ - once: function (event) { - var signal = eventToSignal(event); - deprecation(v5, "PIXI.Loader#once is completely deprecated, use PIXI.Loader#" + signal + ".once"); - }, - /** - * Use the corresponding signal, e.g., event `start`` is signal `onStart`. - * @method PIXI.Loader#off - * @deprecated since 5.0.0 - */ - off: function (event) { - var signal = eventToSignal(event); - deprecation(v5, "PIXI.Loader#off is completely deprecated, use PIXI.Loader#" + signal + ".detach"); - }, - }); - /** - * @class PIXI.extract.WebGLExtract - * @deprecated since 5.0.0 - * @see PIXI.Extract - */ - Object.defineProperty(PIXI.extract, 'WebGLExtract', { - get: function () { - deprecation(v5, 'PIXI.extract.WebGLExtract method has moved to PIXI.Extract'); - return PIXI.Extract; - }, - }); - /** - * @class PIXI.prepare.WebGLPrepare - * @deprecated since 5.0.0 - * @see PIXI.Prepare - */ - Object.defineProperty(PIXI.prepare, 'WebGLPrepare', { - get: function () { - deprecation(v5, 'PIXI.prepare.WebGLPrepare class has moved to PIXI.Prepare'); - return PIXI.Prepare; - }, - }); - /** - * @method PIXI.Container#_renderWebGL - * @private - * @deprecated since 5.0.0 - * @see PIXI.Container#render - * @param {PIXI.Renderer} renderer Instance of renderer - */ - PIXI.Container.prototype._renderWebGL = function _renderWebGL(renderer) { - deprecation(v5, 'PIXI.Container._renderWebGL method has moved to PIXI.Container._render'); - this._render(renderer); - }; - /** - * @method PIXI.Container#renderWebGL - * @deprecated since 5.0.0 - * @see PIXI.Container#render - * @param {PIXI.Renderer} renderer Instance of renderer - */ - PIXI.Container.prototype.renderWebGL = function renderWebGL(renderer) { - deprecation(v5, 'PIXI.Container.renderWebGL method has moved to PIXI.Container.render'); - this.render(renderer); - }; - /** - * @method PIXI.DisplayObject#renderWebGL - * @deprecated since 5.0.0 - * @see PIXI.DisplayObject#render - * @param {PIXI.Renderer} renderer Instance of renderer - */ - PIXI.DisplayObject.prototype.renderWebGL = function renderWebGL(renderer) { - deprecation(v5, 'PIXI.DisplayObject.renderWebGL method has moved to PIXI.DisplayObject.render'); - this.render(renderer); - }; - /** - * @method PIXI.Container#renderAdvancedWebGL - * @deprecated since 5.0.0 - * @see PIXI.Container#renderAdvanced - * @param {PIXI.Renderer} renderer Instance of renderer - */ - PIXI.Container.prototype.renderAdvancedWebGL = function renderAdvancedWebGL(renderer) { - deprecation(v5, 'PIXI.Container.renderAdvancedWebGL method has moved to PIXI.Container.renderAdvanced'); - this.renderAdvanced(renderer); - }; - Object.defineProperties(PIXI.settings, { - /** - * Default transform type. - * - * @static - * @deprecated since 5.0.0 - * @memberof PIXI.settings - * @type {PIXI.TRANSFORM_MODE} - * @default PIXI.TRANSFORM_MODE.STATIC - */ - TRANSFORM_MODE: { - get: function () { - deprecation(v5, 'PIXI.settings.TRANSFORM_MODE property has been removed'); - return 0; - }, - set: function () { - deprecation(v5, 'PIXI.settings.TRANSFORM_MODE property has been removed'); - }, - }, - }); - var BaseTextureAny = PIXI.BaseTexture; - /** - * @method loadSource - * @memberof PIXI.BaseTexture# - * @deprecated since 5.0.0 - */ - BaseTextureAny.prototype.loadSource = function loadSource(image) { - deprecation(v5, 'PIXI.BaseTexture.loadSource method has been deprecated'); - var resource = PIXI.resources.autoDetectResource(image); - resource.internal = true; - this.setResource(resource); - this.update(); - }; - var baseTextureIdDeprecation = false; - Object.defineProperties(BaseTextureAny.prototype, { - /** - * @name PIXI.BaseTexture#hasLoaded - * @type {boolean} - * @deprecated since 5.0.0 - * @readonly - * @see PIXI.BaseTexture#valid - */ - hasLoaded: { - get: function () { - deprecation(v5, 'PIXI.BaseTexture.hasLoaded property has been removed, use PIXI.BaseTexture.valid'); - return this.valid; - }, - }, - /** - * @name PIXI.BaseTexture#imageUrl - * @type {string} - * @deprecated since 5.0.0 - * @see PIXI.resources.ImageResource#url - */ - imageUrl: { - get: function () { - var _a; - deprecation(v5, 'PIXI.BaseTexture.imageUrl property has been removed, use PIXI.BaseTexture.resource.url'); - return (_a = this.resource) === null || _a === void 0 ? void 0 : _a.url; - }, - set: function (imageUrl) { - deprecation(v5, 'PIXI.BaseTexture.imageUrl property has been removed, use PIXI.BaseTexture.resource.url'); - if (this.resource) { - this.resource.url = imageUrl; - } - }, - }, - /** - * @name PIXI.BaseTexture#source - * @type {HTMLImageElement|HTMLCanvasElement|HTMLVideoElement|SVGElement} - * @deprecated since 5.0.0 - * @readonly - * @see PIXI.resources.BaseImageResource#source - */ - source: { - get: function () { - deprecation(v5, 'PIXI.BaseTexture.source property has been moved, use `PIXI.BaseTexture.resource.source`'); - return this.resource.source; - }, - set: function (source) { - deprecation(v5, 'PIXI.BaseTexture.source property has been moved, use `PIXI.BaseTexture.resource.source` ' - + 'if you want to set HTMLCanvasElement. Otherwise, create new BaseTexture.'); - if (this.resource) { - this.resource.source = source; - } - }, - }, - /** - * @name PIXI.BaseTexture#premultiplyAlpha - * @type {boolean} - * @deprecated since 5.2.0 - * @readonly - * @see PIXI.BaseTexture#alphaMode - */ - premultiplyAlpha: { - get: function () { - deprecation('5.2.0', 'PIXI.BaseTexture.premultiplyAlpha property has been changed to `alphaMode`' - + ', see `PIXI.ALPHA_MODES`'); - return this.alphaMode !== 0; - }, - set: function (value) { - deprecation('5.2.0', 'PIXI.BaseTexture.premultiplyAlpha property has been changed to `alphaMode`' - + ', see `PIXI.ALPHA_MODES`'); - this.alphaMode = Number(value); - }, - }, - /** - * Batch local field, stores current texture location - * - * @name PIXI.BaseTexture#_id - * @deprecated since 5.2.0 - * @type {number} - * @see PIXI.BaseTexture#_batchLocation - */ - _id: { - get: function () { - if (!baseTextureIdDeprecation) { - // #popelyshev: That property was a hot place, I don't want to call deprecation method on it if possible - deprecation('5.2.0', 'PIXI.BaseTexture._id batch local field has been changed to `_batchLocation`'); - baseTextureIdDeprecation = true; - } - return this._batchLocation; - }, - set: function (value) { - this._batchLocation = value; - }, - }, - }); - /** - * @method fromImage - * @static - * @memberof PIXI.BaseTexture - * @deprecated since 5.0.0 - * @see PIXI.BaseTexture.from - */ - BaseTextureAny.fromImage = function fromImage(canvas, crossorigin, scaleMode, scale) { - deprecation(v5, 'PIXI.BaseTexture.fromImage method has been replaced with PIXI.BaseTexture.from'); - var resourceOptions = { scale: scale, crossorigin: crossorigin }; - return BaseTextureAny.from(canvas, { scaleMode: scaleMode, resourceOptions: resourceOptions }); - }; - /** - * @method fromCanvas - * @static - * @memberof PIXI.BaseTexture - * @deprecated since 5.0.0 - * @see PIXI.BaseTexture.from - */ - BaseTextureAny.fromCanvas = function fromCanvas(canvas, scaleMode) { - deprecation(v5, 'PIXI.BaseTexture.fromCanvas method has been replaced with PIXI.BaseTexture.from'); - return BaseTextureAny.from(canvas, { scaleMode: scaleMode }); - }; - /** - * @method fromSVG - * @static - * @memberof PIXI.BaseTexture - * @deprecated since 5.0.0 - * @see PIXI.BaseTexture.from - */ - BaseTextureAny.fromSVG = function fromSVG(canvas, crossorigin, scaleMode, scale) { - deprecation(v5, 'PIXI.BaseTexture.fromSVG method has been replaced with PIXI.BaseTexture.from'); - var resourceOptions = { scale: scale, crossorigin: crossorigin }; - return BaseTextureAny.from(canvas, { scaleMode: scaleMode, resourceOptions: resourceOptions }); - }; - Object.defineProperties(PIXI.resources.ImageResource.prototype, { - /** - * @name PIXI.resources.ImageResource#premultiplyAlpha - * @type {boolean} - * @deprecated since 5.2.0 - * @readonly - * @see PIXI.resources.ImageResource#alphaMode - */ - premultiplyAlpha: { - get: function () { - deprecation('5.2.0', 'PIXI.resources.ImageResource.premultiplyAlpha property ' - + 'has been changed to `alphaMode`, see `PIXI.ALPHA_MODES`'); - return this.alphaMode !== 0; - }, - set: function (value) { - deprecation('5.2.0', 'PIXI.resources.ImageResource.premultiplyAlpha property ' - + 'has been changed to `alphaMode`, see `PIXI.ALPHA_MODES`'); - this.alphaMode = Number(value); - }, - }, - }); - /** - * @method PIXI.Point#copy - * @deprecated since 5.0.0 - * @see PIXI.Point#copyFrom - */ - PIXI.Point.prototype.copy = function copy(p) { - deprecation(v5, 'PIXI.Point.copy method has been replaced with PIXI.Point.copyFrom'); - return this.copyFrom(p); - }; - /** - * @method PIXI.ObservablePoint#copy - * @deprecated since 5.0.0 - * @see PIXI.ObservablePoint#copyFrom - */ - PIXI.ObservablePoint.prototype.copy = function copy(p) { - deprecation(v5, 'PIXI.ObservablePoint.copy method has been replaced with PIXI.ObservablePoint.copyFrom'); - return this.copyFrom(p); - }; - /** - * @method PIXI.Rectangle#copy - * @deprecated since 5.0.0 - * @see PIXI.Rectangle#copyFrom - */ - PIXI.Rectangle.prototype.copy = function copy(p) { - deprecation(v5, 'PIXI.Rectangle.copy method has been replaced with PIXI.Rectangle.copyFrom'); - return this.copyFrom(p); - }; - /** - * @method PIXI.Matrix#copy - * @deprecated since 5.0.0 - * @see PIXI.Matrix#copyTo - */ - PIXI.Matrix.prototype.copy = function copy(p) { - deprecation(v5, 'PIXI.Matrix.copy method has been replaced with PIXI.Matrix.copyTo'); - return this.copyTo(p); - }; - /** - * @method PIXI.systems.StateSystem#setState - * @deprecated since 5.1.0 - * @see PIXI.systems.StateSystem#set - */ - PIXI.systems.StateSystem.prototype.setState = function setState(s) { - deprecation('v5.1.0', 'StateSystem.setState has been renamed to StateSystem.set'); - return this.set(s); - }; - Object.assign(PIXI.systems.FilterSystem.prototype, { - /** - * @method PIXI.FilterManager#getRenderTarget - * @deprecated since 5.0.0 - * @see PIXI.systems.FilterSystem#getFilterTexture - */ - getRenderTarget: function (_clear, resolution) { - deprecation(v5, 'PIXI.FilterManager.getRenderTarget method has been replaced with PIXI.systems.FilterSystem#getFilterTexture'); - return this.getFilterTexture(null, resolution); - }, - /** - * @method PIXI.FilterManager#returnRenderTarget - * @deprecated since 5.0.0 - * @see PIXI.systems.FilterSystem#returnFilterTexture - */ - returnRenderTarget: function (renderTexture) { - deprecation(v5, 'PIXI.FilterManager.returnRenderTarget method has been replaced with ' - + 'PIXI.systems.FilterSystem.returnFilterTexture'); - this.returnFilterTexture(renderTexture); - }, - /** - * @method PIXI.systems.FilterSystem#calculateScreenSpaceMatrix - * @deprecated since 5.0.0 - * @param {PIXI.Matrix} outputMatrix - the matrix to output to. - * @return {PIXI.Matrix} The mapped matrix. - */ - calculateScreenSpaceMatrix: function (outputMatrix) { - deprecation(v5, 'PIXI.systems.FilterSystem.calculateScreenSpaceMatrix method is removed, ' - + 'use `(vTextureCoord * inputSize.xy) + outputFrame.xy` instead'); - var mappedMatrix = outputMatrix.identity(); - var _a = this.activeState, sourceFrame = _a.sourceFrame, destinationFrame = _a.destinationFrame; - mappedMatrix.translate(sourceFrame.x / destinationFrame.width, sourceFrame.y / destinationFrame.height); - mappedMatrix.scale(destinationFrame.width, destinationFrame.height); - return mappedMatrix; - }, - /** - * @method PIXI.systems.FilterSystem#calculateNormalizedScreenSpaceMatrix - * @deprecated since 5.0.0 - * @param {PIXI.Matrix} outputMatrix - The matrix to output to. - * @return {PIXI.Matrix} The mapped matrix. - */ - calculateNormalizedScreenSpaceMatrix: function (outputMatrix) { - deprecation(v5, 'PIXI.systems.FilterManager.calculateNormalizedScreenSpaceMatrix method is removed, ' - + 'use `((vTextureCoord * inputSize.xy) + outputFrame.xy) / outputFrame.zw` instead.'); - var _a = this.activeState, sourceFrame = _a.sourceFrame, destinationFrame = _a.destinationFrame; - var mappedMatrix = outputMatrix.identity(); - mappedMatrix.translate(sourceFrame.x / destinationFrame.width, sourceFrame.y / destinationFrame.height); - var translateScaleX = (destinationFrame.width / sourceFrame.width); - var translateScaleY = (destinationFrame.height / sourceFrame.height); - mappedMatrix.scale(translateScaleX, translateScaleY); - return mappedMatrix; - }, - }); - Object.defineProperties(PIXI.RenderTexture.prototype, { - /** - * @name PIXI.RenderTexture#sourceFrame - * @type {PIXI.Rectangle} - * @deprecated since 5.0.0 - * @readonly - */ - sourceFrame: { - get: function () { - deprecation(v5, 'PIXI.RenderTexture.sourceFrame property has been removed'); - return this.filterFrame; - }, - }, - /** - * @name PIXI.RenderTexture#size - * @type {PIXI.Rectangle} - * @deprecated since 5.0.0 - * @readonly - */ - size: { - get: function () { - deprecation(v5, 'PIXI.RenderTexture.size property has been removed'); - return this._frame; - }, - }, - }); - /** - * @class BlurXFilter - * @memberof PIXI.filters - * @deprecated since 5.0.0 - * @see PIXI.filters.BlurFilterPass - */ - var BlurXFilter = /** @class */ (function (_super) { - __extends$i(BlurXFilter, _super); - function BlurXFilter(strength, quality, resolution, kernelSize) { - var _this = this; - deprecation(v5, 'PIXI.filters.BlurXFilter class is deprecated, use PIXI.filters.BlurFilterPass'); - _this = _super.call(this, true, strength, quality, resolution, kernelSize) || this; - return _this; - } - return BlurXFilter; - }(PIXI.filters.BlurFilterPass)); - /** - * @class BlurYFilter - * @memberof PIXI.filters - * @deprecated since 5.0.0 - * @see PIXI.filters.BlurFilterPass - */ - var BlurYFilter = /** @class */ (function (_super) { - __extends$i(BlurYFilter, _super); - function BlurYFilter(strength, quality, resolution, kernelSize) { - var _this = this; - deprecation(v5, 'PIXI.filters.BlurYFilter class is deprecated, use PIXI.filters.BlurFilterPass'); - _this = _super.call(this, false, strength, quality, resolution, kernelSize) || this; - return _this; - } - return BlurYFilter; - }(PIXI.filters.BlurFilterPass)); - Object.assign(PIXI.filters, { - BlurXFilter: BlurXFilter, - BlurYFilter: BlurYFilter, - }); - var SpriteAny = PIXI.Sprite, TextureAny = PIXI.Texture, GraphicsAny = PIXI.Graphics; - // Support for pixi.js-legacy bifurcation - // give users a friendly assist to use legacy - if (!GraphicsAny.prototype.generateCanvasTexture) { - GraphicsAny.prototype.generateCanvasTexture = function generateCanvasTexture() { - deprecation(v5, 'PIXI.Graphics.generateCanvasTexture method is only available in "pixi.js-legacy"'); - }; - } - /** - * @deprecated since 5.0.0 - * @member {PIXI.Graphics} PIXI.Graphics#graphicsData - * @see PIXI.Graphics#geometry - * @readonly - */ - Object.defineProperty(GraphicsAny.prototype, 'graphicsData', { - get: function () { - deprecation(v5, 'PIXI.Graphics.graphicsData property is deprecated, use PIXI.Graphics.geometry.graphicsData'); - return this.geometry.graphicsData; - }, - }); - // Use these to deprecate all the Sprite from* methods - function spriteFrom(name, source, crossorigin, scaleMode) { - deprecation(v5, "PIXI.Sprite." + name + " method is deprecated, use PIXI.Sprite.from"); - return SpriteAny.from(source, { - resourceOptions: { - scale: scaleMode, - crossorigin: crossorigin, - }, - }); - } - /** - * @deprecated since 5.0.0 - * @see PIXI.Sprite.from - * @method PIXI.Sprite.fromImage - * @return {PIXI.Sprite} - */ - SpriteAny.fromImage = spriteFrom.bind(null, 'fromImage'); - /** - * @deprecated since 5.0.0 - * @method PIXI.Sprite.fromSVG - * @see PIXI.Sprite.from - * @return {PIXI.Sprite} - */ - SpriteAny.fromSVG = spriteFrom.bind(null, 'fromSVG'); - /** - * @deprecated since 5.0.0 - * @method PIXI.Sprite.fromCanvas - * @see PIXI.Sprite.from - * @return {PIXI.Sprite} - */ - SpriteAny.fromCanvas = spriteFrom.bind(null, 'fromCanvas'); - /** - * @deprecated since 5.0.0 - * @method PIXI.Sprite.fromVideo - * @see PIXI.Sprite.from - * @return {PIXI.Sprite} - */ - SpriteAny.fromVideo = spriteFrom.bind(null, 'fromVideo'); - /** - * @deprecated since 5.0.0 - * @method PIXI.Sprite.fromFrame - * @see PIXI.Sprite.from - * @return {PIXI.Sprite} - */ - SpriteAny.fromFrame = spriteFrom.bind(null, 'fromFrame'); - // Use these to deprecate all the Texture from* methods - function textureFrom(name, source, crossorigin, scaleMode) { - deprecation(v5, "PIXI.Texture." + name + " method is deprecated, use PIXI.Texture.from"); - return TextureAny.from(source, { - resourceOptions: { - scale: scaleMode, - crossorigin: crossorigin, - }, - }); - } - /** - * @deprecated since 5.0.0 - * @method PIXI.Texture.fromImage - * @see PIXI.Texture.from - * @return {PIXI.Texture} - */ - TextureAny.fromImage = textureFrom.bind(null, 'fromImage'); - /** - * @deprecated since 5.0.0 - * @method PIXI.Texture.fromSVG - * @see PIXI.Texture.from - * @return {PIXI.Texture} - */ - TextureAny.fromSVG = textureFrom.bind(null, 'fromSVG'); - /** - * @deprecated since 5.0.0 - * @method PIXI.Texture.fromCanvas - * @see PIXI.Texture.from - * @return {PIXI.Texture} - */ - TextureAny.fromCanvas = textureFrom.bind(null, 'fromCanvas'); - /** - * @deprecated since 5.0.0 - * @method PIXI.Texture.fromVideo - * @see PIXI.Texture.from - * @return {PIXI.Texture} - */ - TextureAny.fromVideo = textureFrom.bind(null, 'fromVideo'); - /** - * @deprecated since 5.0.0 - * @method PIXI.Texture.fromFrame - * @see PIXI.Texture.from - * @return {PIXI.Texture} - */ - TextureAny.fromFrame = textureFrom.bind(null, 'fromFrame'); - /** - * @deprecated since 5.0.0 - * @member {boolean} PIXI.AbstractRenderer#autoResize - * @see PIXI.AbstractRenderer#autoDensity - */ - Object.defineProperty(PIXI.AbstractRenderer.prototype, 'autoResize', { - get: function () { - deprecation(v5, 'PIXI.AbstractRenderer.autoResize property is deprecated, ' - + 'use PIXI.AbstractRenderer.autoDensity'); - return this.autoDensity; - }, - set: function (value) { - deprecation(v5, 'PIXI.AbstractRenderer.autoResize property is deprecated, ' - + 'use PIXI.AbstractRenderer.autoDensity'); - this.autoDensity = value; - }, - }); - /** - * @deprecated since 5.0.0 - * @member {PIXI.systems.TextureSystem} PIXI.Renderer#textureManager - * @see PIXI.Renderer#texture - */ - Object.defineProperty(PIXI.Renderer.prototype, 'textureManager', { - get: function () { - deprecation(v5, 'PIXI.Renderer.textureManager property is deprecated, use PIXI.Renderer.texture'); - return this.texture; - }, - }); - /** - * @namespace PIXI.utils.mixins - * @deprecated since 5.0.0 - */ - PIXI.utils.mixins = { - /** - * @memberof PIXI.utils.mixins - * @function mixin - * @deprecated since 5.0.0 - */ - mixin: function () { - deprecation(v5, 'PIXI.utils.mixins.mixin function is no longer available'); - }, - /** - * @memberof PIXI.utils.mixins - * @function delayMixin - * @deprecated since 5.0.0 - */ - delayMixin: function () { - deprecation(v5, 'PIXI.utils.mixins.delayMixin function is no longer available'); - }, - /** - * @memberof PIXI.utils.mixins - * @function performMixins - * @deprecated since 5.0.0 - */ - performMixins: function () { - deprecation(v5, 'PIXI.utils.mixins.performMixins function is no longer available'); - }, - }; - /** - * @memberof PIXI.BitmapText - * @member {object} font - * @deprecated since 5.3.0 - */ - Object.defineProperty(PIXI.BitmapText.prototype, 'font', { - get: function () { - deprecation('5.3.0', 'PIXI.BitmapText.font property is deprecated, ' - + 'use fontName, fontSize, tint or align properties'); - return { - name: this._fontName, - size: this._fontSize, - tint: this._tint, - align: this._align, - }; - }, - set: function (value) { - deprecation('5.3.0', 'PIXI.BitmapText.font property is deprecated, ' - + 'use fontName, fontSize, tint or align properties'); - if (!value) { - return; - } - var style = { font: value }; - this._upgradeStyle(style); - style.fontSize = style.fontSize || PIXI.BitmapFont.available[style.fontName].size; - this._fontName = style.fontName; - this._fontSize = style.fontSize; - this.dirty = true; - }, - }); - } - - /*! - * @pixi/mesh-extras - v5.3.3 - * Compiled Tue, 04 Aug 2020 16:23:09 UTC - * - * @pixi/mesh-extras is licensed under the MIT License. - * http://www.opensource.org/licenses/mit-license - */ - - /*! ***************************************************************************** - Copyright (c) Microsoft Corporation. All rights reserved. - Licensed under the Apache License, Version 2.0 (the "License"); you may not use - this file except in compliance with the License. You may obtain a copy of the - License at http://www.apache.org/licenses/LICENSE-2.0 + function __extends$2(d, b) { + extendStatics$2(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + } + + var fragment = "precision highp float;\n\nvarying vec2 vTextureCoord;\nvarying vec4 vColor;\n\nuniform float uNoise;\nuniform float uSeed;\nuniform sampler2D uSampler;\n\nfloat rand(vec2 co)\n{\n return fract(sin(dot(co.xy, vec2(12.9898, 78.233))) * 43758.5453);\n}\n\nvoid main()\n{\n vec4 color = texture2D(uSampler, vTextureCoord);\n float randomValue = rand(gl_FragCoord.xy * uSeed);\n float diff = (randomValue - 0.5) * uNoise;\n\n // Un-premultiply alpha before applying the color matrix. See issue #3539.\n if (color.a > 0.0) {\n color.rgb /= color.a;\n }\n\n color.r += diff;\n color.g += diff;\n color.b += diff;\n\n // Premultiply alpha again.\n color.rgb *= color.a;\n\n gl_FragColor = color;\n}\n"; + + /** + * A Noise effect filter. + * + * original filter: https://github.com/evanw/glfx.js/blob/master/src/filters/adjust/noise.js + * @memberof PIXI.filters + * @author Vico @vicocotea + */ + var NoiseFilter = /** @class */ (function (_super) { + __extends$2(NoiseFilter, _super); + /** + * @param {number} [noise=0.5] - The noise intensity, should be a normalized value in the range [0, 1]. + * @param {number} [seed] - A random seed for the noise generation. Default is `Math.random()`. + */ + function NoiseFilter(noise, seed) { + if (noise === void 0) { noise = 0.5; } + if (seed === void 0) { seed = Math.random(); } + var _this = _super.call(this, defaultFilterVertex, fragment, { + uNoise: 0, + uSeed: 0, + }) || this; + _this.noise = noise; + _this.seed = seed; + return _this; + } + Object.defineProperty(NoiseFilter.prototype, "noise", { + /** + * The amount of noise to apply, this value should be in the range (0, 1]. + * @default 0.5 + */ + get: function () { + return this.uniforms.uNoise; + }, + set: function (value) { + this.uniforms.uNoise = value; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(NoiseFilter.prototype, "seed", { + /** A seed value to apply to the random noise generation. `Math.random()` is a good value to use. */ + get: function () { + return this.uniforms.uSeed; + }, + set: function (value) { + this.uniforms.uSeed = value; + }, + enumerable: false, + configurable: true + }); + return NoiseFilter; + }(Filter)); + + /*! + * @pixi/mixin-cache-as-bitmap - v6.5.3 + * Compiled Fri, 09 Sep 2022 13:55:20 UTC + * + * @pixi/mixin-cache-as-bitmap is licensed under the MIT License. + * http://www.opensource.org/licenses/mit-license + */ + + /*! + * @pixi/constants - v6.5.3 + * Compiled Fri, 09 Sep 2022 13:55:20 UTC + * + * @pixi/constants is licensed under the MIT License. + * http://www.opensource.org/licenses/mit-license + */ + /** + * Different types of environments for WebGL. + * @static + * @memberof PIXI + * @name ENV + * @enum {number} + * @property {number} WEBGL_LEGACY - Used for older v1 WebGL devices. PixiJS will aim to ensure compatibility + * with older / less advanced devices. If you experience unexplained flickering prefer this environment. + * @property {number} WEBGL - Version 1 of WebGL + * @property {number} WEBGL2 - Version 2 of WebGL + */ + var ENV$2; + (function (ENV) { + ENV[ENV["WEBGL_LEGACY"] = 0] = "WEBGL_LEGACY"; + ENV[ENV["WEBGL"] = 1] = "WEBGL"; + ENV[ENV["WEBGL2"] = 2] = "WEBGL2"; + })(ENV$2 || (ENV$2 = {})); + /** + * Constant to identify the Renderer Type. + * @static + * @memberof PIXI + * @name RENDERER_TYPE + * @enum {number} + * @property {number} UNKNOWN - Unknown render type. + * @property {number} WEBGL - WebGL render type. + * @property {number} CANVAS - Canvas render type. + */ + var RENDERER_TYPE$2; + (function (RENDERER_TYPE) { + RENDERER_TYPE[RENDERER_TYPE["UNKNOWN"] = 0] = "UNKNOWN"; + RENDERER_TYPE[RENDERER_TYPE["WEBGL"] = 1] = "WEBGL"; + RENDERER_TYPE[RENDERER_TYPE["CANVAS"] = 2] = "CANVAS"; + })(RENDERER_TYPE$2 || (RENDERER_TYPE$2 = {})); + /** + * Bitwise OR of masks that indicate the buffers to be cleared. + * @static + * @memberof PIXI + * @name BUFFER_BITS + * @enum {number} + * @property {number} COLOR - Indicates the buffers currently enabled for color writing. + * @property {number} DEPTH - Indicates the depth buffer. + * @property {number} STENCIL - Indicates the stencil buffer. + */ + var BUFFER_BITS$2; + (function (BUFFER_BITS) { + BUFFER_BITS[BUFFER_BITS["COLOR"] = 16384] = "COLOR"; + BUFFER_BITS[BUFFER_BITS["DEPTH"] = 256] = "DEPTH"; + BUFFER_BITS[BUFFER_BITS["STENCIL"] = 1024] = "STENCIL"; + })(BUFFER_BITS$2 || (BUFFER_BITS$2 = {})); + /** + * Various blend modes supported by PIXI. + * + * IMPORTANT - The WebGL renderer only supports the NORMAL, ADD, MULTIPLY and SCREEN blend modes. + * Anything else will silently act like NORMAL. + * @memberof PIXI + * @name BLEND_MODES + * @enum {number} + * @property {number} NORMAL - + * @property {number} ADD - + * @property {number} MULTIPLY - + * @property {number} SCREEN - + * @property {number} OVERLAY - + * @property {number} DARKEN - + * @property {number} LIGHTEN - + * @property {number} COLOR_DODGE - + * @property {number} COLOR_BURN - + * @property {number} HARD_LIGHT - + * @property {number} SOFT_LIGHT - + * @property {number} DIFFERENCE - + * @property {number} EXCLUSION - + * @property {number} HUE - + * @property {number} SATURATION - + * @property {number} COLOR - + * @property {number} LUMINOSITY - + * @property {number} NORMAL_NPM - + * @property {number} ADD_NPM - + * @property {number} SCREEN_NPM - + * @property {number} NONE - + * @property {number} SRC_IN - + * @property {number} SRC_OUT - + * @property {number} SRC_ATOP - + * @property {number} DST_OVER - + * @property {number} DST_IN - + * @property {number} DST_OUT - + * @property {number} DST_ATOP - + * @property {number} SUBTRACT - + * @property {number} SRC_OVER - + * @property {number} ERASE - + * @property {number} XOR - + */ + var BLEND_MODES$2; + (function (BLEND_MODES) { + BLEND_MODES[BLEND_MODES["NORMAL"] = 0] = "NORMAL"; + BLEND_MODES[BLEND_MODES["ADD"] = 1] = "ADD"; + BLEND_MODES[BLEND_MODES["MULTIPLY"] = 2] = "MULTIPLY"; + BLEND_MODES[BLEND_MODES["SCREEN"] = 3] = "SCREEN"; + BLEND_MODES[BLEND_MODES["OVERLAY"] = 4] = "OVERLAY"; + BLEND_MODES[BLEND_MODES["DARKEN"] = 5] = "DARKEN"; + BLEND_MODES[BLEND_MODES["LIGHTEN"] = 6] = "LIGHTEN"; + BLEND_MODES[BLEND_MODES["COLOR_DODGE"] = 7] = "COLOR_DODGE"; + BLEND_MODES[BLEND_MODES["COLOR_BURN"] = 8] = "COLOR_BURN"; + BLEND_MODES[BLEND_MODES["HARD_LIGHT"] = 9] = "HARD_LIGHT"; + BLEND_MODES[BLEND_MODES["SOFT_LIGHT"] = 10] = "SOFT_LIGHT"; + BLEND_MODES[BLEND_MODES["DIFFERENCE"] = 11] = "DIFFERENCE"; + BLEND_MODES[BLEND_MODES["EXCLUSION"] = 12] = "EXCLUSION"; + BLEND_MODES[BLEND_MODES["HUE"] = 13] = "HUE"; + BLEND_MODES[BLEND_MODES["SATURATION"] = 14] = "SATURATION"; + BLEND_MODES[BLEND_MODES["COLOR"] = 15] = "COLOR"; + BLEND_MODES[BLEND_MODES["LUMINOSITY"] = 16] = "LUMINOSITY"; + BLEND_MODES[BLEND_MODES["NORMAL_NPM"] = 17] = "NORMAL_NPM"; + BLEND_MODES[BLEND_MODES["ADD_NPM"] = 18] = "ADD_NPM"; + BLEND_MODES[BLEND_MODES["SCREEN_NPM"] = 19] = "SCREEN_NPM"; + BLEND_MODES[BLEND_MODES["NONE"] = 20] = "NONE"; + BLEND_MODES[BLEND_MODES["SRC_OVER"] = 0] = "SRC_OVER"; + BLEND_MODES[BLEND_MODES["SRC_IN"] = 21] = "SRC_IN"; + BLEND_MODES[BLEND_MODES["SRC_OUT"] = 22] = "SRC_OUT"; + BLEND_MODES[BLEND_MODES["SRC_ATOP"] = 23] = "SRC_ATOP"; + BLEND_MODES[BLEND_MODES["DST_OVER"] = 24] = "DST_OVER"; + BLEND_MODES[BLEND_MODES["DST_IN"] = 25] = "DST_IN"; + BLEND_MODES[BLEND_MODES["DST_OUT"] = 26] = "DST_OUT"; + BLEND_MODES[BLEND_MODES["DST_ATOP"] = 27] = "DST_ATOP"; + BLEND_MODES[BLEND_MODES["ERASE"] = 26] = "ERASE"; + BLEND_MODES[BLEND_MODES["SUBTRACT"] = 28] = "SUBTRACT"; + BLEND_MODES[BLEND_MODES["XOR"] = 29] = "XOR"; + })(BLEND_MODES$2 || (BLEND_MODES$2 = {})); + /** + * Various webgl draw modes. These can be used to specify which GL drawMode to use + * under certain situations and renderers. + * @memberof PIXI + * @static + * @name DRAW_MODES + * @enum {number} + * @property {number} POINTS - + * @property {number} LINES - + * @property {number} LINE_LOOP - + * @property {number} LINE_STRIP - + * @property {number} TRIANGLES - + * @property {number} TRIANGLE_STRIP - + * @property {number} TRIANGLE_FAN - + */ + var DRAW_MODES$2; + (function (DRAW_MODES) { + DRAW_MODES[DRAW_MODES["POINTS"] = 0] = "POINTS"; + DRAW_MODES[DRAW_MODES["LINES"] = 1] = "LINES"; + DRAW_MODES[DRAW_MODES["LINE_LOOP"] = 2] = "LINE_LOOP"; + DRAW_MODES[DRAW_MODES["LINE_STRIP"] = 3] = "LINE_STRIP"; + DRAW_MODES[DRAW_MODES["TRIANGLES"] = 4] = "TRIANGLES"; + DRAW_MODES[DRAW_MODES["TRIANGLE_STRIP"] = 5] = "TRIANGLE_STRIP"; + DRAW_MODES[DRAW_MODES["TRIANGLE_FAN"] = 6] = "TRIANGLE_FAN"; + })(DRAW_MODES$2 || (DRAW_MODES$2 = {})); + /** + * Various GL texture/resources formats. + * @memberof PIXI + * @static + * @name FORMATS + * @enum {number} + * @property {number} [RGBA=6408] - + * @property {number} [RGB=6407] - + * @property {number} [RG=33319] - + * @property {number} [RED=6403] - + * @property {number} [RGBA_INTEGER=36249] - + * @property {number} [RGB_INTEGER=36248] - + * @property {number} [RG_INTEGER=33320] - + * @property {number} [RED_INTEGER=36244] - + * @property {number} [ALPHA=6406] - + * @property {number} [LUMINANCE=6409] - + * @property {number} [LUMINANCE_ALPHA=6410] - + * @property {number} [DEPTH_COMPONENT=6402] - + * @property {number} [DEPTH_STENCIL=34041] - + */ + var FORMATS$2; + (function (FORMATS) { + FORMATS[FORMATS["RGBA"] = 6408] = "RGBA"; + FORMATS[FORMATS["RGB"] = 6407] = "RGB"; + FORMATS[FORMATS["RG"] = 33319] = "RG"; + FORMATS[FORMATS["RED"] = 6403] = "RED"; + FORMATS[FORMATS["RGBA_INTEGER"] = 36249] = "RGBA_INTEGER"; + FORMATS[FORMATS["RGB_INTEGER"] = 36248] = "RGB_INTEGER"; + FORMATS[FORMATS["RG_INTEGER"] = 33320] = "RG_INTEGER"; + FORMATS[FORMATS["RED_INTEGER"] = 36244] = "RED_INTEGER"; + FORMATS[FORMATS["ALPHA"] = 6406] = "ALPHA"; + FORMATS[FORMATS["LUMINANCE"] = 6409] = "LUMINANCE"; + FORMATS[FORMATS["LUMINANCE_ALPHA"] = 6410] = "LUMINANCE_ALPHA"; + FORMATS[FORMATS["DEPTH_COMPONENT"] = 6402] = "DEPTH_COMPONENT"; + FORMATS[FORMATS["DEPTH_STENCIL"] = 34041] = "DEPTH_STENCIL"; + })(FORMATS$2 || (FORMATS$2 = {})); + /** + * Various GL target types. + * @memberof PIXI + * @static + * @name TARGETS + * @enum {number} + * @property {number} [TEXTURE_2D=3553] - + * @property {number} [TEXTURE_CUBE_MAP=34067] - + * @property {number} [TEXTURE_2D_ARRAY=35866] - + * @property {number} [TEXTURE_CUBE_MAP_POSITIVE_X=34069] - + * @property {number} [TEXTURE_CUBE_MAP_NEGATIVE_X=34070] - + * @property {number} [TEXTURE_CUBE_MAP_POSITIVE_Y=34071] - + * @property {number} [TEXTURE_CUBE_MAP_NEGATIVE_Y=34072] - + * @property {number} [TEXTURE_CUBE_MAP_POSITIVE_Z=34073] - + * @property {number} [TEXTURE_CUBE_MAP_NEGATIVE_Z=34074] - + */ + var TARGETS$2; + (function (TARGETS) { + TARGETS[TARGETS["TEXTURE_2D"] = 3553] = "TEXTURE_2D"; + TARGETS[TARGETS["TEXTURE_CUBE_MAP"] = 34067] = "TEXTURE_CUBE_MAP"; + TARGETS[TARGETS["TEXTURE_2D_ARRAY"] = 35866] = "TEXTURE_2D_ARRAY"; + TARGETS[TARGETS["TEXTURE_CUBE_MAP_POSITIVE_X"] = 34069] = "TEXTURE_CUBE_MAP_POSITIVE_X"; + TARGETS[TARGETS["TEXTURE_CUBE_MAP_NEGATIVE_X"] = 34070] = "TEXTURE_CUBE_MAP_NEGATIVE_X"; + TARGETS[TARGETS["TEXTURE_CUBE_MAP_POSITIVE_Y"] = 34071] = "TEXTURE_CUBE_MAP_POSITIVE_Y"; + TARGETS[TARGETS["TEXTURE_CUBE_MAP_NEGATIVE_Y"] = 34072] = "TEXTURE_CUBE_MAP_NEGATIVE_Y"; + TARGETS[TARGETS["TEXTURE_CUBE_MAP_POSITIVE_Z"] = 34073] = "TEXTURE_CUBE_MAP_POSITIVE_Z"; + TARGETS[TARGETS["TEXTURE_CUBE_MAP_NEGATIVE_Z"] = 34074] = "TEXTURE_CUBE_MAP_NEGATIVE_Z"; + })(TARGETS$2 || (TARGETS$2 = {})); + /** + * Various GL data format types. + * @memberof PIXI + * @static + * @name TYPES + * @enum {number} + * @property {number} [UNSIGNED_BYTE=5121] - + * @property {number} [UNSIGNED_SHORT=5123] - + * @property {number} [UNSIGNED_SHORT_5_6_5=33635] - + * @property {number} [UNSIGNED_SHORT_4_4_4_4=32819] - + * @property {number} [UNSIGNED_SHORT_5_5_5_1=32820] - + * @property {number} [UNSIGNED_INT=5125] - + * @property {number} [UNSIGNED_INT_10F_11F_11F_REV=35899] - + * @property {number} [UNSIGNED_INT_2_10_10_10_REV=33640] - + * @property {number} [UNSIGNED_INT_24_8=34042] - + * @property {number} [UNSIGNED_INT_5_9_9_9_REV=35902] - + * @property {number} [BYTE=5120] - + * @property {number} [SHORT=5122] - + * @property {number} [INT=5124] - + * @property {number} [FLOAT=5126] - + * @property {number} [FLOAT_32_UNSIGNED_INT_24_8_REV=36269] - + * @property {number} [HALF_FLOAT=36193] - + */ + var TYPES$2; + (function (TYPES) { + TYPES[TYPES["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE"; + TYPES[TYPES["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT"; + TYPES[TYPES["UNSIGNED_SHORT_5_6_5"] = 33635] = "UNSIGNED_SHORT_5_6_5"; + TYPES[TYPES["UNSIGNED_SHORT_4_4_4_4"] = 32819] = "UNSIGNED_SHORT_4_4_4_4"; + TYPES[TYPES["UNSIGNED_SHORT_5_5_5_1"] = 32820] = "UNSIGNED_SHORT_5_5_5_1"; + TYPES[TYPES["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT"; + TYPES[TYPES["UNSIGNED_INT_10F_11F_11F_REV"] = 35899] = "UNSIGNED_INT_10F_11F_11F_REV"; + TYPES[TYPES["UNSIGNED_INT_2_10_10_10_REV"] = 33640] = "UNSIGNED_INT_2_10_10_10_REV"; + TYPES[TYPES["UNSIGNED_INT_24_8"] = 34042] = "UNSIGNED_INT_24_8"; + TYPES[TYPES["UNSIGNED_INT_5_9_9_9_REV"] = 35902] = "UNSIGNED_INT_5_9_9_9_REV"; + TYPES[TYPES["BYTE"] = 5120] = "BYTE"; + TYPES[TYPES["SHORT"] = 5122] = "SHORT"; + TYPES[TYPES["INT"] = 5124] = "INT"; + TYPES[TYPES["FLOAT"] = 5126] = "FLOAT"; + TYPES[TYPES["FLOAT_32_UNSIGNED_INT_24_8_REV"] = 36269] = "FLOAT_32_UNSIGNED_INT_24_8_REV"; + TYPES[TYPES["HALF_FLOAT"] = 36193] = "HALF_FLOAT"; + })(TYPES$2 || (TYPES$2 = {})); + /** + * Various sampler types. Correspond to `sampler`, `isampler`, `usampler` GLSL types respectively. + * WebGL1 works only with FLOAT. + * @memberof PIXI + * @static + * @name SAMPLER_TYPES + * @enum {number} + * @property {number} [FLOAT=0] - + * @property {number} [INT=1] - + * @property {number} [UINT=2] - + */ + var SAMPLER_TYPES$2; + (function (SAMPLER_TYPES) { + SAMPLER_TYPES[SAMPLER_TYPES["FLOAT"] = 0] = "FLOAT"; + SAMPLER_TYPES[SAMPLER_TYPES["INT"] = 1] = "INT"; + SAMPLER_TYPES[SAMPLER_TYPES["UINT"] = 2] = "UINT"; + })(SAMPLER_TYPES$2 || (SAMPLER_TYPES$2 = {})); + /** + * The scale modes that are supported by pixi. + * + * The {@link PIXI.settings.SCALE_MODE} scale mode affects the default scaling mode of future operations. + * It can be re-assigned to either LINEAR or NEAREST, depending upon suitability. + * @memberof PIXI + * @static + * @name SCALE_MODES + * @enum {number} + * @property {number} LINEAR Smooth scaling + * @property {number} NEAREST Pixelating scaling + */ + var SCALE_MODES$2; + (function (SCALE_MODES) { + SCALE_MODES[SCALE_MODES["NEAREST"] = 0] = "NEAREST"; + SCALE_MODES[SCALE_MODES["LINEAR"] = 1] = "LINEAR"; + })(SCALE_MODES$2 || (SCALE_MODES$2 = {})); + /** + * The wrap modes that are supported by pixi. + * + * The {@link PIXI.settings.WRAP_MODE} wrap mode affects the default wrapping mode of future operations. + * It can be re-assigned to either CLAMP or REPEAT, depending upon suitability. + * If the texture is non power of two then clamp will be used regardless as WebGL can + * only use REPEAT if the texture is po2. + * + * This property only affects WebGL. + * @name WRAP_MODES + * @memberof PIXI + * @static + * @enum {number} + * @property {number} CLAMP - The textures uvs are clamped + * @property {number} REPEAT - The texture uvs tile and repeat + * @property {number} MIRRORED_REPEAT - The texture uvs tile and repeat with mirroring + */ + var WRAP_MODES$2; + (function (WRAP_MODES) { + WRAP_MODES[WRAP_MODES["CLAMP"] = 33071] = "CLAMP"; + WRAP_MODES[WRAP_MODES["REPEAT"] = 10497] = "REPEAT"; + WRAP_MODES[WRAP_MODES["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT"; + })(WRAP_MODES$2 || (WRAP_MODES$2 = {})); + /** + * Mipmap filtering modes that are supported by pixi. + * + * The {@link PIXI.settings.MIPMAP_TEXTURES} affects default texture filtering. + * Mipmaps are generated for a baseTexture if its `mipmap` field is `ON`, + * or its `POW2` and texture dimensions are powers of 2. + * Due to platform restriction, `ON` option will work like `POW2` for webgl-1. + * + * This property only affects WebGL. + * @name MIPMAP_MODES + * @memberof PIXI + * @static + * @enum {number} + * @property {number} OFF - No mipmaps + * @property {number} POW2 - Generate mipmaps if texture dimensions are pow2 + * @property {number} ON - Always generate mipmaps + * @property {number} ON_MANUAL - Use mipmaps, but do not auto-generate them; this is used with a resource + * that supports buffering each level-of-detail. + */ + var MIPMAP_MODES$2; + (function (MIPMAP_MODES) { + MIPMAP_MODES[MIPMAP_MODES["OFF"] = 0] = "OFF"; + MIPMAP_MODES[MIPMAP_MODES["POW2"] = 1] = "POW2"; + MIPMAP_MODES[MIPMAP_MODES["ON"] = 2] = "ON"; + MIPMAP_MODES[MIPMAP_MODES["ON_MANUAL"] = 3] = "ON_MANUAL"; + })(MIPMAP_MODES$2 || (MIPMAP_MODES$2 = {})); + /** + * How to treat textures with premultiplied alpha + * @name ALPHA_MODES + * @memberof PIXI + * @static + * @enum {number} + * @property {number} NO_PREMULTIPLIED_ALPHA - Source is not premultiplied, leave it like that. + * Option for compressed and data textures that are created from typed arrays. + * @property {number} PREMULTIPLY_ON_UPLOAD - Source is not premultiplied, premultiply on upload. + * Default option, used for all loaded images. + * @property {number} PREMULTIPLIED_ALPHA - Source is already premultiplied + * Example: spine atlases with `_pma` suffix. + * @property {number} NPM - Alias for NO_PREMULTIPLIED_ALPHA. + * @property {number} UNPACK - Default option, alias for PREMULTIPLY_ON_UPLOAD. + * @property {number} PMA - Alias for PREMULTIPLIED_ALPHA. + */ + var ALPHA_MODES$2; + (function (ALPHA_MODES) { + ALPHA_MODES[ALPHA_MODES["NPM"] = 0] = "NPM"; + ALPHA_MODES[ALPHA_MODES["UNPACK"] = 1] = "UNPACK"; + ALPHA_MODES[ALPHA_MODES["PMA"] = 2] = "PMA"; + ALPHA_MODES[ALPHA_MODES["NO_PREMULTIPLIED_ALPHA"] = 0] = "NO_PREMULTIPLIED_ALPHA"; + ALPHA_MODES[ALPHA_MODES["PREMULTIPLY_ON_UPLOAD"] = 1] = "PREMULTIPLY_ON_UPLOAD"; + ALPHA_MODES[ALPHA_MODES["PREMULTIPLY_ALPHA"] = 2] = "PREMULTIPLY_ALPHA"; + ALPHA_MODES[ALPHA_MODES["PREMULTIPLIED_ALPHA"] = 2] = "PREMULTIPLIED_ALPHA"; + })(ALPHA_MODES$2 || (ALPHA_MODES$2 = {})); + /** + * Configure whether filter textures are cleared after binding. + * + * Filter textures need not be cleared if the filter does not use pixel blending. {@link CLEAR_MODES.BLIT} will detect + * this and skip clearing as an optimization. + * @name CLEAR_MODES + * @memberof PIXI + * @static + * @enum {number} + * @property {number} BLEND - Do not clear the filter texture. The filter's output will blend on top of the output texture. + * @property {number} CLEAR - Always clear the filter texture. + * @property {number} BLIT - Clear only if {@link FilterSystem.forceClear} is set or if the filter uses pixel blending. + * @property {number} NO - Alias for BLEND, same as `false` in earlier versions + * @property {number} YES - Alias for CLEAR, same as `true` in earlier versions + * @property {number} AUTO - Alias for BLIT + */ + var CLEAR_MODES$2; + (function (CLEAR_MODES) { + CLEAR_MODES[CLEAR_MODES["NO"] = 0] = "NO"; + CLEAR_MODES[CLEAR_MODES["YES"] = 1] = "YES"; + CLEAR_MODES[CLEAR_MODES["AUTO"] = 2] = "AUTO"; + CLEAR_MODES[CLEAR_MODES["BLEND"] = 0] = "BLEND"; + CLEAR_MODES[CLEAR_MODES["CLEAR"] = 1] = "CLEAR"; + CLEAR_MODES[CLEAR_MODES["BLIT"] = 2] = "BLIT"; + })(CLEAR_MODES$2 || (CLEAR_MODES$2 = {})); + /** + * The gc modes that are supported by pixi. + * + * The {@link PIXI.settings.GC_MODE} Garbage Collection mode for PixiJS textures is AUTO + * If set to GC_MODE, the renderer will occasionally check textures usage. If they are not + * used for a specified period of time they will be removed from the GPU. They will of course + * be uploaded again when they are required. This is a silent behind the scenes process that + * should ensure that the GPU does not get filled up. + * + * Handy for mobile devices! + * This property only affects WebGL. + * @name GC_MODES + * @enum {number} + * @static + * @memberof PIXI + * @property {number} AUTO - Garbage collection will happen periodically automatically + * @property {number} MANUAL - Garbage collection will need to be called manually + */ + var GC_MODES$2; + (function (GC_MODES) { + GC_MODES[GC_MODES["AUTO"] = 0] = "AUTO"; + GC_MODES[GC_MODES["MANUAL"] = 1] = "MANUAL"; + })(GC_MODES$2 || (GC_MODES$2 = {})); + /** + * Constants that specify float precision in shaders. + * @name PRECISION + * @memberof PIXI + * @constant + * @static + * @enum {string} + * @property {string} [LOW='lowp'] - + * @property {string} [MEDIUM='mediump'] - + * @property {string} [HIGH='highp'] - + */ + var PRECISION$2; + (function (PRECISION) { + PRECISION["LOW"] = "lowp"; + PRECISION["MEDIUM"] = "mediump"; + PRECISION["HIGH"] = "highp"; + })(PRECISION$2 || (PRECISION$2 = {})); + /** + * Constants for mask implementations. + * We use `type` suffix because it leads to very different behaviours + * @name MASK_TYPES + * @memberof PIXI + * @static + * @enum {number} + * @property {number} NONE - Mask is ignored + * @property {number} SCISSOR - Scissor mask, rectangle on screen, cheap + * @property {number} STENCIL - Stencil mask, 1-bit, medium, works only if renderer supports stencil + * @property {number} SPRITE - Mask that uses SpriteMaskFilter, uses temporary RenderTexture + * @property {number} COLOR - Color mask (RGBA) + */ + var MASK_TYPES$2; + (function (MASK_TYPES) { + MASK_TYPES[MASK_TYPES["NONE"] = 0] = "NONE"; + MASK_TYPES[MASK_TYPES["SCISSOR"] = 1] = "SCISSOR"; + MASK_TYPES[MASK_TYPES["STENCIL"] = 2] = "STENCIL"; + MASK_TYPES[MASK_TYPES["SPRITE"] = 3] = "SPRITE"; + MASK_TYPES[MASK_TYPES["COLOR"] = 4] = "COLOR"; + })(MASK_TYPES$2 || (MASK_TYPES$2 = {})); + /** + * Bitwise OR of masks that indicate the color channels that are rendered to. + * @static + * @memberof PIXI + * @name COLOR_MASK_BITS + * @enum {number} + * @property {number} RED - Red channel. + * @property {number} GREEN - Green channel + * @property {number} BLUE - Blue channel. + * @property {number} ALPHA - Alpha channel. + */ + var COLOR_MASK_BITS$2; + (function (COLOR_MASK_BITS) { + COLOR_MASK_BITS[COLOR_MASK_BITS["RED"] = 1] = "RED"; + COLOR_MASK_BITS[COLOR_MASK_BITS["GREEN"] = 2] = "GREEN"; + COLOR_MASK_BITS[COLOR_MASK_BITS["BLUE"] = 4] = "BLUE"; + COLOR_MASK_BITS[COLOR_MASK_BITS["ALPHA"] = 8] = "ALPHA"; + })(COLOR_MASK_BITS$2 || (COLOR_MASK_BITS$2 = {})); + /** + * Constants for multi-sampling antialiasing. + * @see PIXI.Framebuffer#multisample + * @name MSAA_QUALITY + * @memberof PIXI + * @static + * @enum {number} + * @property {number} NONE - No multisampling for this renderTexture + * @property {number} LOW - Try 2 samples + * @property {number} MEDIUM - Try 4 samples + * @property {number} HIGH - Try 8 samples + */ + var MSAA_QUALITY$2; + (function (MSAA_QUALITY) { + MSAA_QUALITY[MSAA_QUALITY["NONE"] = 0] = "NONE"; + MSAA_QUALITY[MSAA_QUALITY["LOW"] = 2] = "LOW"; + MSAA_QUALITY[MSAA_QUALITY["MEDIUM"] = 4] = "MEDIUM"; + MSAA_QUALITY[MSAA_QUALITY["HIGH"] = 8] = "HIGH"; + })(MSAA_QUALITY$2 || (MSAA_QUALITY$2 = {})); + /** + * Constants for various buffer types in Pixi + * @see PIXI.BUFFER_TYPE + * @name BUFFER_TYPE + * @memberof PIXI + * @static + * @enum {number} + * @property {number} ELEMENT_ARRAY_BUFFER - buffer type for using as an index buffer + * @property {number} ARRAY_BUFFER - buffer type for using attribute data + * @property {number} UNIFORM_BUFFER - the buffer type is for uniform buffer objects + */ + var BUFFER_TYPE$2; + (function (BUFFER_TYPE) { + BUFFER_TYPE[BUFFER_TYPE["ELEMENT_ARRAY_BUFFER"] = 34963] = "ELEMENT_ARRAY_BUFFER"; + BUFFER_TYPE[BUFFER_TYPE["ARRAY_BUFFER"] = 34962] = "ARRAY_BUFFER"; + // NOT YET SUPPORTED + BUFFER_TYPE[BUFFER_TYPE["UNIFORM_BUFFER"] = 35345] = "UNIFORM_BUFFER"; + })(BUFFER_TYPE$2 || (BUFFER_TYPE$2 = {})); + + var _tempMatrix = new Matrix(); + DisplayObject.prototype._cacheAsBitmap = false; + DisplayObject.prototype._cacheData = null; + DisplayObject.prototype._cacheAsBitmapResolution = null; + DisplayObject.prototype._cacheAsBitmapMultisample = MSAA_QUALITY$2.NONE; + // figured there's no point adding ALL the extra variables to prototype. + // this model can hold the information needed. This can also be generated on demand as + // most objects are not cached as bitmaps. + /** + * @class + * @ignore + * @private + */ + var CacheData = /** @class */ (function () { + function CacheData() { + this.textureCacheId = null; + this.originalRender = null; + this.originalRenderCanvas = null; + this.originalCalculateBounds = null; + this.originalGetLocalBounds = null; + this.originalUpdateTransform = null; + this.originalDestroy = null; + this.originalMask = null; + this.originalFilterArea = null; + this.originalContainsPoint = null; + this.sprite = null; + } + return CacheData; + }()); + Object.defineProperties(DisplayObject.prototype, { + /** + * The resolution to use for cacheAsBitmap. By default this will use the renderer's resolution + * but can be overriden for performance. Lower values will reduce memory usage at the expense + * of render quality. A falsey value of `null` or `0` will default to the renderer's resolution. + * If `cacheAsBitmap` is set to `true`, this will re-render with the new resolution. + * @member {number} cacheAsBitmapResolution + * @memberof PIXI.DisplayObject# + * @default null + */ + cacheAsBitmapResolution: { + get: function () { + return this._cacheAsBitmapResolution; + }, + set: function (resolution) { + if (resolution === this._cacheAsBitmapResolution) { + return; + } + this._cacheAsBitmapResolution = resolution; + if (this.cacheAsBitmap) { + // Toggle to re-render at the new resolution + this.cacheAsBitmap = false; + this.cacheAsBitmap = true; + } + }, + }, + /** + * The number of samples to use for cacheAsBitmap. If set to `null`, the renderer's + * sample count is used. + * If `cacheAsBitmap` is set to `true`, this will re-render with the new number of samples. + * @member {number} cacheAsBitmapMultisample + * @memberof PIXI.DisplayObject# + * @default PIXI.MSAA_QUALITY.NONE + */ + cacheAsBitmapMultisample: { + get: function () { + return this._cacheAsBitmapMultisample; + }, + set: function (multisample) { + if (multisample === this._cacheAsBitmapMultisample) { + return; + } + this._cacheAsBitmapMultisample = multisample; + if (this.cacheAsBitmap) { + // Toggle to re-render with new multisample + this.cacheAsBitmap = false; + this.cacheAsBitmap = true; + } + }, + }, + /** + * Set this to true if you want this display object to be cached as a bitmap. + * This basically takes a snap shot of the display object as it is at that moment. It can + * provide a performance benefit for complex static displayObjects. + * To remove simply set this property to `false` + * + * IMPORTANT GOTCHA - Make sure that all your textures are preloaded BEFORE setting this property to true + * as it will take a snapshot of what is currently there. If the textures have not loaded then they will not appear. + * @member {boolean} + * @memberof PIXI.DisplayObject# + */ + cacheAsBitmap: { + get: function () { + return this._cacheAsBitmap; + }, + set: function (value) { + if (this._cacheAsBitmap === value) { + return; + } + this._cacheAsBitmap = value; + var data; + if (value) { + if (!this._cacheData) { + this._cacheData = new CacheData(); + } + data = this._cacheData; + data.originalRender = this.render; + data.originalRenderCanvas = this.renderCanvas; + data.originalUpdateTransform = this.updateTransform; + data.originalCalculateBounds = this.calculateBounds; + data.originalGetLocalBounds = this.getLocalBounds; + data.originalDestroy = this.destroy; + data.originalContainsPoint = this.containsPoint; + data.originalMask = this._mask; + data.originalFilterArea = this.filterArea; + this.render = this._renderCached; + this.renderCanvas = this._renderCachedCanvas; + this.destroy = this._cacheAsBitmapDestroy; + } + else { + data = this._cacheData; + if (data.sprite) { + this._destroyCachedDisplayObject(); + } + this.render = data.originalRender; + this.renderCanvas = data.originalRenderCanvas; + this.calculateBounds = data.originalCalculateBounds; + this.getLocalBounds = data.originalGetLocalBounds; + this.destroy = data.originalDestroy; + this.updateTransform = data.originalUpdateTransform; + this.containsPoint = data.originalContainsPoint; + this._mask = data.originalMask; + this.filterArea = data.originalFilterArea; + } + }, + }, + }); + /** + * Renders a cached version of the sprite with WebGL + * @private + * @method _renderCached + * @memberof PIXI.DisplayObject# + * @param {PIXI.Renderer} renderer - the WebGL renderer + */ + DisplayObject.prototype._renderCached = function _renderCached(renderer) { + if (!this.visible || this.worldAlpha <= 0 || !this.renderable) { + return; + } + this._initCachedDisplayObject(renderer); + this._cacheData.sprite.transform._worldID = this.transform._worldID; + this._cacheData.sprite.worldAlpha = this.worldAlpha; + this._cacheData.sprite._render(renderer); + }; + /** + * Prepares the WebGL renderer to cache the sprite + * @private + * @method _initCachedDisplayObject + * @memberof PIXI.DisplayObject# + * @param {PIXI.Renderer} renderer - the WebGL renderer + */ + DisplayObject.prototype._initCachedDisplayObject = function _initCachedDisplayObject(renderer) { + var _a; + if (this._cacheData && this._cacheData.sprite) { + return; + } + // make sure alpha is set to 1 otherwise it will get rendered as invisible! + var cacheAlpha = this.alpha; + this.alpha = 1; + // first we flush anything left in the renderer (otherwise it would get rendered to the cached texture) + renderer.batch.flush(); + // this.filters= []; + // next we find the dimensions of the untransformed object + // this function also calls updatetransform on all its children as part of the measuring. + // This means we don't need to update the transform again in this function + // TODO pass an object to clone too? saves having to create a new one each time! + var bounds = this.getLocalBounds(null, true).clone(); + // add some padding! + if (this.filters && this.filters.length) { + var padding = this.filters[0].padding; + bounds.pad(padding); + } + bounds.ceil(settings$1.RESOLUTION); + // for now we cache the current renderTarget that the WebGL renderer is currently using. + // this could be more elegant.. + var cachedRenderTexture = renderer.renderTexture.current; + var cachedSourceFrame = renderer.renderTexture.sourceFrame.clone(); + var cachedDestinationFrame = renderer.renderTexture.destinationFrame.clone(); + var cachedProjectionTransform = renderer.projection.transform; + // We also store the filter stack - I will definitely look to change how this works a little later down the line. + // const stack = renderer.filterManager.filterStack; + // this renderTexture will be used to store the cached DisplayObject + var renderTexture = RenderTexture.create({ + width: bounds.width, + height: bounds.height, + resolution: this.cacheAsBitmapResolution || renderer.resolution, + multisample: (_a = this.cacheAsBitmapMultisample) !== null && _a !== void 0 ? _a : renderer.multisample, + }); + var textureCacheId = "cacheAsBitmap_" + uid(); + this._cacheData.textureCacheId = textureCacheId; + BaseTexture.addToCache(renderTexture.baseTexture, textureCacheId); + Texture.addToCache(renderTexture, textureCacheId); + // need to set // + var m = this.transform.localTransform.copyTo(_tempMatrix).invert().translate(-bounds.x, -bounds.y); + // set all properties to there original so we can render to a texture + this.render = this._cacheData.originalRender; + renderer.render(this, { renderTexture: renderTexture, clear: true, transform: m, skipUpdateTransform: false }); + renderer.framebuffer.blit(); + // now restore the state be setting the new properties + renderer.projection.transform = cachedProjectionTransform; + renderer.renderTexture.bind(cachedRenderTexture, cachedSourceFrame, cachedDestinationFrame); + // renderer.filterManager.filterStack = stack; + this.render = this._renderCached; + // the rest is the same as for Canvas + this.updateTransform = this.displayObjectUpdateTransform; + this.calculateBounds = this._calculateCachedBounds; + this.getLocalBounds = this._getCachedLocalBounds; + this._mask = null; + this.filterArea = null; + this.alpha = cacheAlpha; + // create our cached sprite + var cachedSprite = new Sprite(renderTexture); + cachedSprite.transform.worldTransform = this.transform.worldTransform; + cachedSprite.anchor.x = -(bounds.x / bounds.width); + cachedSprite.anchor.y = -(bounds.y / bounds.height); + cachedSprite.alpha = cacheAlpha; + cachedSprite._bounds = this._bounds; + this._cacheData.sprite = cachedSprite; + this.transform._parentID = -1; + // restore the transform of the cached sprite to avoid the nasty flicker.. + if (!this.parent) { + this.enableTempParent(); + this.updateTransform(); + this.disableTempParent(null); + } + else { + this.updateTransform(); + } + // map the hit test.. + this.containsPoint = cachedSprite.containsPoint.bind(cachedSprite); + }; + /** + * Renders a cached version of the sprite with canvas + * @private + * @method _renderCachedCanvas + * @memberof PIXI.DisplayObject# + * @param {PIXI.CanvasRenderer} renderer - The canvas renderer + */ + DisplayObject.prototype._renderCachedCanvas = function _renderCachedCanvas(renderer) { + if (!this.visible || this.worldAlpha <= 0 || !this.renderable) { + return; + } + this._initCachedDisplayObjectCanvas(renderer); + this._cacheData.sprite.worldAlpha = this.worldAlpha; + this._cacheData.sprite._renderCanvas(renderer); + }; + // TODO this can be the same as the WebGL version.. will need to do a little tweaking first though.. + /** + * Prepares the Canvas renderer to cache the sprite + * @private + * @method _initCachedDisplayObjectCanvas + * @memberof PIXI.DisplayObject# + * @param {PIXI.CanvasRenderer} renderer - The canvas renderer + */ + DisplayObject.prototype._initCachedDisplayObjectCanvas = function _initCachedDisplayObjectCanvas(renderer) { + if (this._cacheData && this._cacheData.sprite) { + return; + } + // get bounds actually transforms the object for us already! + var bounds = this.getLocalBounds(null, true); + var cacheAlpha = this.alpha; + this.alpha = 1; + var cachedRenderTarget = renderer.context; + var cachedProjectionTransform = renderer._projTransform; + bounds.ceil(settings$1.RESOLUTION); + var renderTexture = RenderTexture.create({ width: bounds.width, height: bounds.height }); + var textureCacheId = "cacheAsBitmap_" + uid(); + this._cacheData.textureCacheId = textureCacheId; + BaseTexture.addToCache(renderTexture.baseTexture, textureCacheId); + Texture.addToCache(renderTexture, textureCacheId); + // need to set // + var m = _tempMatrix; + this.transform.localTransform.copyTo(m); + m.invert(); + m.tx -= bounds.x; + m.ty -= bounds.y; + // m.append(this.transform.worldTransform.) + // set all properties to there original so we can render to a texture + this.renderCanvas = this._cacheData.originalRenderCanvas; + renderer.render(this, { renderTexture: renderTexture, clear: true, transform: m, skipUpdateTransform: false }); + // now restore the state be setting the new properties + renderer.context = cachedRenderTarget; + renderer._projTransform = cachedProjectionTransform; + this.renderCanvas = this._renderCachedCanvas; + // the rest is the same as for WebGL + this.updateTransform = this.displayObjectUpdateTransform; + this.calculateBounds = this._calculateCachedBounds; + this.getLocalBounds = this._getCachedLocalBounds; + this._mask = null; + this.filterArea = null; + this.alpha = cacheAlpha; + // create our cached sprite + var cachedSprite = new Sprite(renderTexture); + cachedSprite.transform.worldTransform = this.transform.worldTransform; + cachedSprite.anchor.x = -(bounds.x / bounds.width); + cachedSprite.anchor.y = -(bounds.y / bounds.height); + cachedSprite.alpha = cacheAlpha; + cachedSprite._bounds = this._bounds; + this._cacheData.sprite = cachedSprite; + this.transform._parentID = -1; + // restore the transform of the cached sprite to avoid the nasty flicker.. + if (!this.parent) { + this.parent = renderer._tempDisplayObjectParent; + this.updateTransform(); + this.parent = null; + } + else { + this.updateTransform(); + } + // map the hit test.. + this.containsPoint = cachedSprite.containsPoint.bind(cachedSprite); + }; + /** + * Calculates the bounds of the cached sprite + * @private + * @method + */ + DisplayObject.prototype._calculateCachedBounds = function _calculateCachedBounds() { + this._bounds.clear(); + this._cacheData.sprite.transform._worldID = this.transform._worldID; + this._cacheData.sprite._calculateBounds(); + this._bounds.updateID = this._boundsID; + }; + /** + * Gets the bounds of the cached sprite. + * @private + * @method + * @returns {Rectangle} The local bounds. + */ + DisplayObject.prototype._getCachedLocalBounds = function _getCachedLocalBounds() { + return this._cacheData.sprite.getLocalBounds(null); + }; + /** + * Destroys the cached sprite. + * @private + * @method + */ + DisplayObject.prototype._destroyCachedDisplayObject = function _destroyCachedDisplayObject() { + this._cacheData.sprite._texture.destroy(true); + this._cacheData.sprite = null; + BaseTexture.removeFromCache(this._cacheData.textureCacheId); + Texture.removeFromCache(this._cacheData.textureCacheId); + this._cacheData.textureCacheId = null; + }; + /** + * Destroys the cached object. + * @private + * @method + * @param {object|boolean} [options] - Options parameter. A boolean will act as if all options + * have been set to that value. + * Used when destroying containers, see the Container.destroy method. + */ + DisplayObject.prototype._cacheAsBitmapDestroy = function _cacheAsBitmapDestroy(options) { + this.cacheAsBitmap = false; + this.destroy(options); + }; + + /*! + * @pixi/mixin-get-child-by-name - v6.5.3 + * Compiled Fri, 09 Sep 2022 13:55:20 UTC + * + * @pixi/mixin-get-child-by-name is licensed under the MIT License. + * http://www.opensource.org/licenses/mit-license + */ + + /** + * The instance name of the object. + * @memberof PIXI.DisplayObject# + * @member {string} name + */ + DisplayObject.prototype.name = null; + /** + * Returns the display object in the container. + * + * Recursive searches are done in a preorder traversal. + * @method getChildByName + * @memberof PIXI.Container# + * @param {string} name - Instance name. + * @param {boolean}[deep=false] - Whether to search recursively + * @returns {PIXI.DisplayObject} The child with the specified name. + */ + Container.prototype.getChildByName = function getChildByName(name, deep) { + for (var i = 0, j = this.children.length; i < j; i++) { + if (this.children[i].name === name) { + return this.children[i]; + } + } + if (deep) { + for (var i = 0, j = this.children.length; i < j; i++) { + var child = this.children[i]; + if (!child.getChildByName) { + continue; + } + var target = child.getChildByName(name, true); + if (target) { + return target; + } + } + } + return null; + }; + + /*! + * @pixi/mixin-get-global-position - v6.5.3 + * Compiled Fri, 09 Sep 2022 13:55:20 UTC + * + * @pixi/mixin-get-global-position is licensed under the MIT License. + * http://www.opensource.org/licenses/mit-license + */ + + /** + * Returns the global position of the displayObject. Does not depend on object scale, rotation and pivot. + * @method getGlobalPosition + * @memberof PIXI.DisplayObject# + * @param {PIXI.Point} [point=new PIXI.Point()] - The point to write the global value to. + * @param {boolean} [skipUpdate=false] - Setting to true will stop the transforms of the scene graph from + * being updated. This means the calculation returned MAY be out of date BUT will give you a + * nice performance boost. + * @returns {PIXI.Point} The updated point. + */ + DisplayObject.prototype.getGlobalPosition = function getGlobalPosition(point, skipUpdate) { + if (point === void 0) { point = new Point(); } + if (skipUpdate === void 0) { skipUpdate = false; } + if (this.parent) { + this.parent.toGlobal(this.position, point, skipUpdate); + } + else { + point.x = this.position.x; + point.y = this.position.y; + } + return point; + }; + + /*! + * @pixi/app - v6.5.3 + * Compiled Fri, 09 Sep 2022 13:55:20 UTC + * + * @pixi/app is licensed under the MIT License. + * http://www.opensource.org/licenses/mit-license + */ + + /** + * Middleware for for Application's resize functionality + * @private + * @class + */ + var ResizePlugin = /** @class */ (function () { + function ResizePlugin() { + } + /** + * Initialize the plugin with scope of application instance + * @static + * @private + * @param {object} [options] - See application options + */ + ResizePlugin.init = function (options) { + var _this = this; + Object.defineProperty(this, 'resizeTo', + /** + * The HTML element or window to automatically resize the + * renderer's view element to match width and height. + * @member {Window|HTMLElement} + * @name resizeTo + * @memberof PIXI.Application# + */ + { + set: function (dom) { + globalThis.removeEventListener('resize', this.queueResize); + this._resizeTo = dom; + if (dom) { + globalThis.addEventListener('resize', this.queueResize); + this.resize(); + } + }, + get: function () { + return this._resizeTo; + }, + }); + /** + * Resize is throttled, so it's safe to call this multiple times per frame and it'll + * only be called once. + * @memberof PIXI.Application# + * @method queueResize + * @private + */ + this.queueResize = function () { + if (!_this._resizeTo) { + return; + } + _this.cancelResize(); + // // Throttle resize events per raf + _this._resizeId = requestAnimationFrame(function () { return _this.resize(); }); + }; + /** + * Cancel the resize queue. + * @memberof PIXI.Application# + * @method cancelResize + * @private + */ + this.cancelResize = function () { + if (_this._resizeId) { + cancelAnimationFrame(_this._resizeId); + _this._resizeId = null; + } + }; + /** + * Execute an immediate resize on the renderer, this is not + * throttled and can be expensive to call many times in a row. + * Will resize only if `resizeTo` property is set. + * @memberof PIXI.Application# + * @method resize + */ + this.resize = function () { + if (!_this._resizeTo) { + return; + } + // clear queue resize + _this.cancelResize(); + var width; + var height; + // Resize to the window + if (_this._resizeTo === globalThis.window) { + width = globalThis.innerWidth; + height = globalThis.innerHeight; + } + // Resize to other HTML entities + else { + var _a = _this._resizeTo, clientWidth = _a.clientWidth, clientHeight = _a.clientHeight; + width = clientWidth; + height = clientHeight; + } + _this.renderer.resize(width, height); + }; + // On resize + this._resizeId = null; + this._resizeTo = null; + this.resizeTo = options.resizeTo || null; + }; + /** + * Clean up the ticker, scoped to application + * @static + * @private + */ + ResizePlugin.destroy = function () { + globalThis.removeEventListener('resize', this.queueResize); + this.cancelResize(); + this.cancelResize = null; + this.queueResize = null; + this.resizeTo = null; + this.resize = null; + }; + /** @ignore */ + ResizePlugin.extension = exports.ExtensionType.Application; + return ResizePlugin; + }()); + + /*! + * @pixi/settings - v6.5.3 + * Compiled Fri, 09 Sep 2022 13:55:20 UTC + * + * @pixi/settings is licensed under the MIT License. + * http://www.opensource.org/licenses/mit-license + */ + /*! + * @pixi/constants - v6.5.3 + * Compiled Fri, 09 Sep 2022 13:55:20 UTC + * + * @pixi/constants is licensed under the MIT License. + * http://www.opensource.org/licenses/mit-license + */ + /** + * Different types of environments for WebGL. + * @static + * @memberof PIXI + * @name ENV + * @enum {number} + * @property {number} WEBGL_LEGACY - Used for older v1 WebGL devices. PixiJS will aim to ensure compatibility + * with older / less advanced devices. If you experience unexplained flickering prefer this environment. + * @property {number} WEBGL - Version 1 of WebGL + * @property {number} WEBGL2 - Version 2 of WebGL + */ + var ENV$1; + (function (ENV) { + ENV[ENV["WEBGL_LEGACY"] = 0] = "WEBGL_LEGACY"; + ENV[ENV["WEBGL"] = 1] = "WEBGL"; + ENV[ENV["WEBGL2"] = 2] = "WEBGL2"; + })(ENV$1 || (ENV$1 = {})); + /** + * Constant to identify the Renderer Type. + * @static + * @memberof PIXI + * @name RENDERER_TYPE + * @enum {number} + * @property {number} UNKNOWN - Unknown render type. + * @property {number} WEBGL - WebGL render type. + * @property {number} CANVAS - Canvas render type. + */ + var RENDERER_TYPE$1; + (function (RENDERER_TYPE) { + RENDERER_TYPE[RENDERER_TYPE["UNKNOWN"] = 0] = "UNKNOWN"; + RENDERER_TYPE[RENDERER_TYPE["WEBGL"] = 1] = "WEBGL"; + RENDERER_TYPE[RENDERER_TYPE["CANVAS"] = 2] = "CANVAS"; + })(RENDERER_TYPE$1 || (RENDERER_TYPE$1 = {})); + /** + * Bitwise OR of masks that indicate the buffers to be cleared. + * @static + * @memberof PIXI + * @name BUFFER_BITS + * @enum {number} + * @property {number} COLOR - Indicates the buffers currently enabled for color writing. + * @property {number} DEPTH - Indicates the depth buffer. + * @property {number} STENCIL - Indicates the stencil buffer. + */ + var BUFFER_BITS$1; + (function (BUFFER_BITS) { + BUFFER_BITS[BUFFER_BITS["COLOR"] = 16384] = "COLOR"; + BUFFER_BITS[BUFFER_BITS["DEPTH"] = 256] = "DEPTH"; + BUFFER_BITS[BUFFER_BITS["STENCIL"] = 1024] = "STENCIL"; + })(BUFFER_BITS$1 || (BUFFER_BITS$1 = {})); + /** + * Various blend modes supported by PIXI. + * + * IMPORTANT - The WebGL renderer only supports the NORMAL, ADD, MULTIPLY and SCREEN blend modes. + * Anything else will silently act like NORMAL. + * @memberof PIXI + * @name BLEND_MODES + * @enum {number} + * @property {number} NORMAL - + * @property {number} ADD - + * @property {number} MULTIPLY - + * @property {number} SCREEN - + * @property {number} OVERLAY - + * @property {number} DARKEN - + * @property {number} LIGHTEN - + * @property {number} COLOR_DODGE - + * @property {number} COLOR_BURN - + * @property {number} HARD_LIGHT - + * @property {number} SOFT_LIGHT - + * @property {number} DIFFERENCE - + * @property {number} EXCLUSION - + * @property {number} HUE - + * @property {number} SATURATION - + * @property {number} COLOR - + * @property {number} LUMINOSITY - + * @property {number} NORMAL_NPM - + * @property {number} ADD_NPM - + * @property {number} SCREEN_NPM - + * @property {number} NONE - + * @property {number} SRC_IN - + * @property {number} SRC_OUT - + * @property {number} SRC_ATOP - + * @property {number} DST_OVER - + * @property {number} DST_IN - + * @property {number} DST_OUT - + * @property {number} DST_ATOP - + * @property {number} SUBTRACT - + * @property {number} SRC_OVER - + * @property {number} ERASE - + * @property {number} XOR - + */ + var BLEND_MODES$1; + (function (BLEND_MODES) { + BLEND_MODES[BLEND_MODES["NORMAL"] = 0] = "NORMAL"; + BLEND_MODES[BLEND_MODES["ADD"] = 1] = "ADD"; + BLEND_MODES[BLEND_MODES["MULTIPLY"] = 2] = "MULTIPLY"; + BLEND_MODES[BLEND_MODES["SCREEN"] = 3] = "SCREEN"; + BLEND_MODES[BLEND_MODES["OVERLAY"] = 4] = "OVERLAY"; + BLEND_MODES[BLEND_MODES["DARKEN"] = 5] = "DARKEN"; + BLEND_MODES[BLEND_MODES["LIGHTEN"] = 6] = "LIGHTEN"; + BLEND_MODES[BLEND_MODES["COLOR_DODGE"] = 7] = "COLOR_DODGE"; + BLEND_MODES[BLEND_MODES["COLOR_BURN"] = 8] = "COLOR_BURN"; + BLEND_MODES[BLEND_MODES["HARD_LIGHT"] = 9] = "HARD_LIGHT"; + BLEND_MODES[BLEND_MODES["SOFT_LIGHT"] = 10] = "SOFT_LIGHT"; + BLEND_MODES[BLEND_MODES["DIFFERENCE"] = 11] = "DIFFERENCE"; + BLEND_MODES[BLEND_MODES["EXCLUSION"] = 12] = "EXCLUSION"; + BLEND_MODES[BLEND_MODES["HUE"] = 13] = "HUE"; + BLEND_MODES[BLEND_MODES["SATURATION"] = 14] = "SATURATION"; + BLEND_MODES[BLEND_MODES["COLOR"] = 15] = "COLOR"; + BLEND_MODES[BLEND_MODES["LUMINOSITY"] = 16] = "LUMINOSITY"; + BLEND_MODES[BLEND_MODES["NORMAL_NPM"] = 17] = "NORMAL_NPM"; + BLEND_MODES[BLEND_MODES["ADD_NPM"] = 18] = "ADD_NPM"; + BLEND_MODES[BLEND_MODES["SCREEN_NPM"] = 19] = "SCREEN_NPM"; + BLEND_MODES[BLEND_MODES["NONE"] = 20] = "NONE"; + BLEND_MODES[BLEND_MODES["SRC_OVER"] = 0] = "SRC_OVER"; + BLEND_MODES[BLEND_MODES["SRC_IN"] = 21] = "SRC_IN"; + BLEND_MODES[BLEND_MODES["SRC_OUT"] = 22] = "SRC_OUT"; + BLEND_MODES[BLEND_MODES["SRC_ATOP"] = 23] = "SRC_ATOP"; + BLEND_MODES[BLEND_MODES["DST_OVER"] = 24] = "DST_OVER"; + BLEND_MODES[BLEND_MODES["DST_IN"] = 25] = "DST_IN"; + BLEND_MODES[BLEND_MODES["DST_OUT"] = 26] = "DST_OUT"; + BLEND_MODES[BLEND_MODES["DST_ATOP"] = 27] = "DST_ATOP"; + BLEND_MODES[BLEND_MODES["ERASE"] = 26] = "ERASE"; + BLEND_MODES[BLEND_MODES["SUBTRACT"] = 28] = "SUBTRACT"; + BLEND_MODES[BLEND_MODES["XOR"] = 29] = "XOR"; + })(BLEND_MODES$1 || (BLEND_MODES$1 = {})); + /** + * Various webgl draw modes. These can be used to specify which GL drawMode to use + * under certain situations and renderers. + * @memberof PIXI + * @static + * @name DRAW_MODES + * @enum {number} + * @property {number} POINTS - + * @property {number} LINES - + * @property {number} LINE_LOOP - + * @property {number} LINE_STRIP - + * @property {number} TRIANGLES - + * @property {number} TRIANGLE_STRIP - + * @property {number} TRIANGLE_FAN - + */ + var DRAW_MODES$1; + (function (DRAW_MODES) { + DRAW_MODES[DRAW_MODES["POINTS"] = 0] = "POINTS"; + DRAW_MODES[DRAW_MODES["LINES"] = 1] = "LINES"; + DRAW_MODES[DRAW_MODES["LINE_LOOP"] = 2] = "LINE_LOOP"; + DRAW_MODES[DRAW_MODES["LINE_STRIP"] = 3] = "LINE_STRIP"; + DRAW_MODES[DRAW_MODES["TRIANGLES"] = 4] = "TRIANGLES"; + DRAW_MODES[DRAW_MODES["TRIANGLE_STRIP"] = 5] = "TRIANGLE_STRIP"; + DRAW_MODES[DRAW_MODES["TRIANGLE_FAN"] = 6] = "TRIANGLE_FAN"; + })(DRAW_MODES$1 || (DRAW_MODES$1 = {})); + /** + * Various GL texture/resources formats. + * @memberof PIXI + * @static + * @name FORMATS + * @enum {number} + * @property {number} [RGBA=6408] - + * @property {number} [RGB=6407] - + * @property {number} [RG=33319] - + * @property {number} [RED=6403] - + * @property {number} [RGBA_INTEGER=36249] - + * @property {number} [RGB_INTEGER=36248] - + * @property {number} [RG_INTEGER=33320] - + * @property {number} [RED_INTEGER=36244] - + * @property {number} [ALPHA=6406] - + * @property {number} [LUMINANCE=6409] - + * @property {number} [LUMINANCE_ALPHA=6410] - + * @property {number} [DEPTH_COMPONENT=6402] - + * @property {number} [DEPTH_STENCIL=34041] - + */ + var FORMATS$1; + (function (FORMATS) { + FORMATS[FORMATS["RGBA"] = 6408] = "RGBA"; + FORMATS[FORMATS["RGB"] = 6407] = "RGB"; + FORMATS[FORMATS["RG"] = 33319] = "RG"; + FORMATS[FORMATS["RED"] = 6403] = "RED"; + FORMATS[FORMATS["RGBA_INTEGER"] = 36249] = "RGBA_INTEGER"; + FORMATS[FORMATS["RGB_INTEGER"] = 36248] = "RGB_INTEGER"; + FORMATS[FORMATS["RG_INTEGER"] = 33320] = "RG_INTEGER"; + FORMATS[FORMATS["RED_INTEGER"] = 36244] = "RED_INTEGER"; + FORMATS[FORMATS["ALPHA"] = 6406] = "ALPHA"; + FORMATS[FORMATS["LUMINANCE"] = 6409] = "LUMINANCE"; + FORMATS[FORMATS["LUMINANCE_ALPHA"] = 6410] = "LUMINANCE_ALPHA"; + FORMATS[FORMATS["DEPTH_COMPONENT"] = 6402] = "DEPTH_COMPONENT"; + FORMATS[FORMATS["DEPTH_STENCIL"] = 34041] = "DEPTH_STENCIL"; + })(FORMATS$1 || (FORMATS$1 = {})); + /** + * Various GL target types. + * @memberof PIXI + * @static + * @name TARGETS + * @enum {number} + * @property {number} [TEXTURE_2D=3553] - + * @property {number} [TEXTURE_CUBE_MAP=34067] - + * @property {number} [TEXTURE_2D_ARRAY=35866] - + * @property {number} [TEXTURE_CUBE_MAP_POSITIVE_X=34069] - + * @property {number} [TEXTURE_CUBE_MAP_NEGATIVE_X=34070] - + * @property {number} [TEXTURE_CUBE_MAP_POSITIVE_Y=34071] - + * @property {number} [TEXTURE_CUBE_MAP_NEGATIVE_Y=34072] - + * @property {number} [TEXTURE_CUBE_MAP_POSITIVE_Z=34073] - + * @property {number} [TEXTURE_CUBE_MAP_NEGATIVE_Z=34074] - + */ + var TARGETS$1; + (function (TARGETS) { + TARGETS[TARGETS["TEXTURE_2D"] = 3553] = "TEXTURE_2D"; + TARGETS[TARGETS["TEXTURE_CUBE_MAP"] = 34067] = "TEXTURE_CUBE_MAP"; + TARGETS[TARGETS["TEXTURE_2D_ARRAY"] = 35866] = "TEXTURE_2D_ARRAY"; + TARGETS[TARGETS["TEXTURE_CUBE_MAP_POSITIVE_X"] = 34069] = "TEXTURE_CUBE_MAP_POSITIVE_X"; + TARGETS[TARGETS["TEXTURE_CUBE_MAP_NEGATIVE_X"] = 34070] = "TEXTURE_CUBE_MAP_NEGATIVE_X"; + TARGETS[TARGETS["TEXTURE_CUBE_MAP_POSITIVE_Y"] = 34071] = "TEXTURE_CUBE_MAP_POSITIVE_Y"; + TARGETS[TARGETS["TEXTURE_CUBE_MAP_NEGATIVE_Y"] = 34072] = "TEXTURE_CUBE_MAP_NEGATIVE_Y"; + TARGETS[TARGETS["TEXTURE_CUBE_MAP_POSITIVE_Z"] = 34073] = "TEXTURE_CUBE_MAP_POSITIVE_Z"; + TARGETS[TARGETS["TEXTURE_CUBE_MAP_NEGATIVE_Z"] = 34074] = "TEXTURE_CUBE_MAP_NEGATIVE_Z"; + })(TARGETS$1 || (TARGETS$1 = {})); + /** + * Various GL data format types. + * @memberof PIXI + * @static + * @name TYPES + * @enum {number} + * @property {number} [UNSIGNED_BYTE=5121] - + * @property {number} [UNSIGNED_SHORT=5123] - + * @property {number} [UNSIGNED_SHORT_5_6_5=33635] - + * @property {number} [UNSIGNED_SHORT_4_4_4_4=32819] - + * @property {number} [UNSIGNED_SHORT_5_5_5_1=32820] - + * @property {number} [UNSIGNED_INT=5125] - + * @property {number} [UNSIGNED_INT_10F_11F_11F_REV=35899] - + * @property {number} [UNSIGNED_INT_2_10_10_10_REV=33640] - + * @property {number} [UNSIGNED_INT_24_8=34042] - + * @property {number} [UNSIGNED_INT_5_9_9_9_REV=35902] - + * @property {number} [BYTE=5120] - + * @property {number} [SHORT=5122] - + * @property {number} [INT=5124] - + * @property {number} [FLOAT=5126] - + * @property {number} [FLOAT_32_UNSIGNED_INT_24_8_REV=36269] - + * @property {number} [HALF_FLOAT=36193] - + */ + var TYPES$1; + (function (TYPES) { + TYPES[TYPES["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE"; + TYPES[TYPES["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT"; + TYPES[TYPES["UNSIGNED_SHORT_5_6_5"] = 33635] = "UNSIGNED_SHORT_5_6_5"; + TYPES[TYPES["UNSIGNED_SHORT_4_4_4_4"] = 32819] = "UNSIGNED_SHORT_4_4_4_4"; + TYPES[TYPES["UNSIGNED_SHORT_5_5_5_1"] = 32820] = "UNSIGNED_SHORT_5_5_5_1"; + TYPES[TYPES["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT"; + TYPES[TYPES["UNSIGNED_INT_10F_11F_11F_REV"] = 35899] = "UNSIGNED_INT_10F_11F_11F_REV"; + TYPES[TYPES["UNSIGNED_INT_2_10_10_10_REV"] = 33640] = "UNSIGNED_INT_2_10_10_10_REV"; + TYPES[TYPES["UNSIGNED_INT_24_8"] = 34042] = "UNSIGNED_INT_24_8"; + TYPES[TYPES["UNSIGNED_INT_5_9_9_9_REV"] = 35902] = "UNSIGNED_INT_5_9_9_9_REV"; + TYPES[TYPES["BYTE"] = 5120] = "BYTE"; + TYPES[TYPES["SHORT"] = 5122] = "SHORT"; + TYPES[TYPES["INT"] = 5124] = "INT"; + TYPES[TYPES["FLOAT"] = 5126] = "FLOAT"; + TYPES[TYPES["FLOAT_32_UNSIGNED_INT_24_8_REV"] = 36269] = "FLOAT_32_UNSIGNED_INT_24_8_REV"; + TYPES[TYPES["HALF_FLOAT"] = 36193] = "HALF_FLOAT"; + })(TYPES$1 || (TYPES$1 = {})); + /** + * Various sampler types. Correspond to `sampler`, `isampler`, `usampler` GLSL types respectively. + * WebGL1 works only with FLOAT. + * @memberof PIXI + * @static + * @name SAMPLER_TYPES + * @enum {number} + * @property {number} [FLOAT=0] - + * @property {number} [INT=1] - + * @property {number} [UINT=2] - + */ + var SAMPLER_TYPES$1; + (function (SAMPLER_TYPES) { + SAMPLER_TYPES[SAMPLER_TYPES["FLOAT"] = 0] = "FLOAT"; + SAMPLER_TYPES[SAMPLER_TYPES["INT"] = 1] = "INT"; + SAMPLER_TYPES[SAMPLER_TYPES["UINT"] = 2] = "UINT"; + })(SAMPLER_TYPES$1 || (SAMPLER_TYPES$1 = {})); + /** + * The scale modes that are supported by pixi. + * + * The {@link PIXI.settings.SCALE_MODE} scale mode affects the default scaling mode of future operations. + * It can be re-assigned to either LINEAR or NEAREST, depending upon suitability. + * @memberof PIXI + * @static + * @name SCALE_MODES + * @enum {number} + * @property {number} LINEAR Smooth scaling + * @property {number} NEAREST Pixelating scaling + */ + var SCALE_MODES$1; + (function (SCALE_MODES) { + SCALE_MODES[SCALE_MODES["NEAREST"] = 0] = "NEAREST"; + SCALE_MODES[SCALE_MODES["LINEAR"] = 1] = "LINEAR"; + })(SCALE_MODES$1 || (SCALE_MODES$1 = {})); + /** + * The wrap modes that are supported by pixi. + * + * The {@link PIXI.settings.WRAP_MODE} wrap mode affects the default wrapping mode of future operations. + * It can be re-assigned to either CLAMP or REPEAT, depending upon suitability. + * If the texture is non power of two then clamp will be used regardless as WebGL can + * only use REPEAT if the texture is po2. + * + * This property only affects WebGL. + * @name WRAP_MODES + * @memberof PIXI + * @static + * @enum {number} + * @property {number} CLAMP - The textures uvs are clamped + * @property {number} REPEAT - The texture uvs tile and repeat + * @property {number} MIRRORED_REPEAT - The texture uvs tile and repeat with mirroring + */ + var WRAP_MODES$1; + (function (WRAP_MODES) { + WRAP_MODES[WRAP_MODES["CLAMP"] = 33071] = "CLAMP"; + WRAP_MODES[WRAP_MODES["REPEAT"] = 10497] = "REPEAT"; + WRAP_MODES[WRAP_MODES["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT"; + })(WRAP_MODES$1 || (WRAP_MODES$1 = {})); + /** + * Mipmap filtering modes that are supported by pixi. + * + * The {@link PIXI.settings.MIPMAP_TEXTURES} affects default texture filtering. + * Mipmaps are generated for a baseTexture if its `mipmap` field is `ON`, + * or its `POW2` and texture dimensions are powers of 2. + * Due to platform restriction, `ON` option will work like `POW2` for webgl-1. + * + * This property only affects WebGL. + * @name MIPMAP_MODES + * @memberof PIXI + * @static + * @enum {number} + * @property {number} OFF - No mipmaps + * @property {number} POW2 - Generate mipmaps if texture dimensions are pow2 + * @property {number} ON - Always generate mipmaps + * @property {number} ON_MANUAL - Use mipmaps, but do not auto-generate them; this is used with a resource + * that supports buffering each level-of-detail. + */ + var MIPMAP_MODES$1; + (function (MIPMAP_MODES) { + MIPMAP_MODES[MIPMAP_MODES["OFF"] = 0] = "OFF"; + MIPMAP_MODES[MIPMAP_MODES["POW2"] = 1] = "POW2"; + MIPMAP_MODES[MIPMAP_MODES["ON"] = 2] = "ON"; + MIPMAP_MODES[MIPMAP_MODES["ON_MANUAL"] = 3] = "ON_MANUAL"; + })(MIPMAP_MODES$1 || (MIPMAP_MODES$1 = {})); + /** + * How to treat textures with premultiplied alpha + * @name ALPHA_MODES + * @memberof PIXI + * @static + * @enum {number} + * @property {number} NO_PREMULTIPLIED_ALPHA - Source is not premultiplied, leave it like that. + * Option for compressed and data textures that are created from typed arrays. + * @property {number} PREMULTIPLY_ON_UPLOAD - Source is not premultiplied, premultiply on upload. + * Default option, used for all loaded images. + * @property {number} PREMULTIPLIED_ALPHA - Source is already premultiplied + * Example: spine atlases with `_pma` suffix. + * @property {number} NPM - Alias for NO_PREMULTIPLIED_ALPHA. + * @property {number} UNPACK - Default option, alias for PREMULTIPLY_ON_UPLOAD. + * @property {number} PMA - Alias for PREMULTIPLIED_ALPHA. + */ + var ALPHA_MODES$1; + (function (ALPHA_MODES) { + ALPHA_MODES[ALPHA_MODES["NPM"] = 0] = "NPM"; + ALPHA_MODES[ALPHA_MODES["UNPACK"] = 1] = "UNPACK"; + ALPHA_MODES[ALPHA_MODES["PMA"] = 2] = "PMA"; + ALPHA_MODES[ALPHA_MODES["NO_PREMULTIPLIED_ALPHA"] = 0] = "NO_PREMULTIPLIED_ALPHA"; + ALPHA_MODES[ALPHA_MODES["PREMULTIPLY_ON_UPLOAD"] = 1] = "PREMULTIPLY_ON_UPLOAD"; + ALPHA_MODES[ALPHA_MODES["PREMULTIPLY_ALPHA"] = 2] = "PREMULTIPLY_ALPHA"; + ALPHA_MODES[ALPHA_MODES["PREMULTIPLIED_ALPHA"] = 2] = "PREMULTIPLIED_ALPHA"; + })(ALPHA_MODES$1 || (ALPHA_MODES$1 = {})); + /** + * Configure whether filter textures are cleared after binding. + * + * Filter textures need not be cleared if the filter does not use pixel blending. {@link CLEAR_MODES.BLIT} will detect + * this and skip clearing as an optimization. + * @name CLEAR_MODES + * @memberof PIXI + * @static + * @enum {number} + * @property {number} BLEND - Do not clear the filter texture. The filter's output will blend on top of the output texture. + * @property {number} CLEAR - Always clear the filter texture. + * @property {number} BLIT - Clear only if {@link FilterSystem.forceClear} is set or if the filter uses pixel blending. + * @property {number} NO - Alias for BLEND, same as `false` in earlier versions + * @property {number} YES - Alias for CLEAR, same as `true` in earlier versions + * @property {number} AUTO - Alias for BLIT + */ + var CLEAR_MODES$1; + (function (CLEAR_MODES) { + CLEAR_MODES[CLEAR_MODES["NO"] = 0] = "NO"; + CLEAR_MODES[CLEAR_MODES["YES"] = 1] = "YES"; + CLEAR_MODES[CLEAR_MODES["AUTO"] = 2] = "AUTO"; + CLEAR_MODES[CLEAR_MODES["BLEND"] = 0] = "BLEND"; + CLEAR_MODES[CLEAR_MODES["CLEAR"] = 1] = "CLEAR"; + CLEAR_MODES[CLEAR_MODES["BLIT"] = 2] = "BLIT"; + })(CLEAR_MODES$1 || (CLEAR_MODES$1 = {})); + /** + * The gc modes that are supported by pixi. + * + * The {@link PIXI.settings.GC_MODE} Garbage Collection mode for PixiJS textures is AUTO + * If set to GC_MODE, the renderer will occasionally check textures usage. If they are not + * used for a specified period of time they will be removed from the GPU. They will of course + * be uploaded again when they are required. This is a silent behind the scenes process that + * should ensure that the GPU does not get filled up. + * + * Handy for mobile devices! + * This property only affects WebGL. + * @name GC_MODES + * @enum {number} + * @static + * @memberof PIXI + * @property {number} AUTO - Garbage collection will happen periodically automatically + * @property {number} MANUAL - Garbage collection will need to be called manually + */ + var GC_MODES$1; + (function (GC_MODES) { + GC_MODES[GC_MODES["AUTO"] = 0] = "AUTO"; + GC_MODES[GC_MODES["MANUAL"] = 1] = "MANUAL"; + })(GC_MODES$1 || (GC_MODES$1 = {})); + /** + * Constants that specify float precision in shaders. + * @name PRECISION + * @memberof PIXI + * @constant + * @static + * @enum {string} + * @property {string} [LOW='lowp'] - + * @property {string} [MEDIUM='mediump'] - + * @property {string} [HIGH='highp'] - + */ + var PRECISION$1; + (function (PRECISION) { + PRECISION["LOW"] = "lowp"; + PRECISION["MEDIUM"] = "mediump"; + PRECISION["HIGH"] = "highp"; + })(PRECISION$1 || (PRECISION$1 = {})); + /** + * Constants for mask implementations. + * We use `type` suffix because it leads to very different behaviours + * @name MASK_TYPES + * @memberof PIXI + * @static + * @enum {number} + * @property {number} NONE - Mask is ignored + * @property {number} SCISSOR - Scissor mask, rectangle on screen, cheap + * @property {number} STENCIL - Stencil mask, 1-bit, medium, works only if renderer supports stencil + * @property {number} SPRITE - Mask that uses SpriteMaskFilter, uses temporary RenderTexture + * @property {number} COLOR - Color mask (RGBA) + */ + var MASK_TYPES$1; + (function (MASK_TYPES) { + MASK_TYPES[MASK_TYPES["NONE"] = 0] = "NONE"; + MASK_TYPES[MASK_TYPES["SCISSOR"] = 1] = "SCISSOR"; + MASK_TYPES[MASK_TYPES["STENCIL"] = 2] = "STENCIL"; + MASK_TYPES[MASK_TYPES["SPRITE"] = 3] = "SPRITE"; + MASK_TYPES[MASK_TYPES["COLOR"] = 4] = "COLOR"; + })(MASK_TYPES$1 || (MASK_TYPES$1 = {})); + /** + * Bitwise OR of masks that indicate the color channels that are rendered to. + * @static + * @memberof PIXI + * @name COLOR_MASK_BITS + * @enum {number} + * @property {number} RED - Red channel. + * @property {number} GREEN - Green channel + * @property {number} BLUE - Blue channel. + * @property {number} ALPHA - Alpha channel. + */ + var COLOR_MASK_BITS$1; + (function (COLOR_MASK_BITS) { + COLOR_MASK_BITS[COLOR_MASK_BITS["RED"] = 1] = "RED"; + COLOR_MASK_BITS[COLOR_MASK_BITS["GREEN"] = 2] = "GREEN"; + COLOR_MASK_BITS[COLOR_MASK_BITS["BLUE"] = 4] = "BLUE"; + COLOR_MASK_BITS[COLOR_MASK_BITS["ALPHA"] = 8] = "ALPHA"; + })(COLOR_MASK_BITS$1 || (COLOR_MASK_BITS$1 = {})); + /** + * Constants for multi-sampling antialiasing. + * @see PIXI.Framebuffer#multisample + * @name MSAA_QUALITY + * @memberof PIXI + * @static + * @enum {number} + * @property {number} NONE - No multisampling for this renderTexture + * @property {number} LOW - Try 2 samples + * @property {number} MEDIUM - Try 4 samples + * @property {number} HIGH - Try 8 samples + */ + var MSAA_QUALITY$1; + (function (MSAA_QUALITY) { + MSAA_QUALITY[MSAA_QUALITY["NONE"] = 0] = "NONE"; + MSAA_QUALITY[MSAA_QUALITY["LOW"] = 2] = "LOW"; + MSAA_QUALITY[MSAA_QUALITY["MEDIUM"] = 4] = "MEDIUM"; + MSAA_QUALITY[MSAA_QUALITY["HIGH"] = 8] = "HIGH"; + })(MSAA_QUALITY$1 || (MSAA_QUALITY$1 = {})); + /** + * Constants for various buffer types in Pixi + * @see PIXI.BUFFER_TYPE + * @name BUFFER_TYPE + * @memberof PIXI + * @static + * @enum {number} + * @property {number} ELEMENT_ARRAY_BUFFER - buffer type for using as an index buffer + * @property {number} ARRAY_BUFFER - buffer type for using attribute data + * @property {number} UNIFORM_BUFFER - the buffer type is for uniform buffer objects + */ + var BUFFER_TYPE$1; + (function (BUFFER_TYPE) { + BUFFER_TYPE[BUFFER_TYPE["ELEMENT_ARRAY_BUFFER"] = 34963] = "ELEMENT_ARRAY_BUFFER"; + BUFFER_TYPE[BUFFER_TYPE["ARRAY_BUFFER"] = 34962] = "ARRAY_BUFFER"; + // NOT YET SUPPORTED + BUFFER_TYPE[BUFFER_TYPE["UNIFORM_BUFFER"] = 35345] = "UNIFORM_BUFFER"; + })(BUFFER_TYPE$1 || (BUFFER_TYPE$1 = {})); + + var BrowserAdapter = { + /** + * Creates a canvas element of the given size. + * This canvas is created using the browser's native canvas element. + * @param width - width of the canvas + * @param height - height of the canvas + */ + createCanvas: function (width, height) { + var canvas = document.createElement('canvas'); + canvas.width = width; + canvas.height = height; + return canvas; + }, + getWebGLRenderingContext: function () { return WebGLRenderingContext; }, + getNavigator: function () { return navigator; }, + getBaseUrl: function () { var _a; return ((_a = document.baseURI) !== null && _a !== void 0 ? _a : window.location.href); }, + fetch: function (url, options) { return fetch(url, options); }, + }; + + var appleIphone = /iPhone/i; + var appleIpod = /iPod/i; + var appleTablet = /iPad/i; + var appleUniversal = /\biOS-universal(?:.+)Mac\b/i; + var androidPhone = /\bAndroid(?:.+)Mobile\b/i; + var androidTablet = /Android/i; + var amazonPhone = /(?:SD4930UR|\bSilk(?:.+)Mobile\b)/i; + var amazonTablet = /Silk/i; + var windowsPhone = /Windows Phone/i; + var windowsTablet = /\bWindows(?:.+)ARM\b/i; + var otherBlackBerry = /BlackBerry/i; + var otherBlackBerry10 = /BB10/i; + var otherOpera = /Opera Mini/i; + var otherChrome = /\b(CriOS|Chrome)(?:.+)Mobile/i; + var otherFirefox = /Mobile(?:.+)Firefox\b/i; + var isAppleTabletOnIos13 = function (navigator) { + return (typeof navigator !== 'undefined' && + navigator.platform === 'MacIntel' && + typeof navigator.maxTouchPoints === 'number' && + navigator.maxTouchPoints > 1 && + typeof MSStream === 'undefined'); + }; + function createMatch(userAgent) { + return function (regex) { return regex.test(userAgent); }; + } + function isMobile$1(param) { + var nav = { + userAgent: '', + platform: '', + maxTouchPoints: 0 + }; + if (!param && typeof navigator !== 'undefined') { + nav = { + userAgent: navigator.userAgent, + platform: navigator.platform, + maxTouchPoints: navigator.maxTouchPoints || 0 + }; + } + else if (typeof param === 'string') { + nav.userAgent = param; + } + else if (param && param.userAgent) { + nav = { + userAgent: param.userAgent, + platform: param.platform, + maxTouchPoints: param.maxTouchPoints || 0 + }; + } + var userAgent = nav.userAgent; + var tmp = userAgent.split('[FBAN'); + if (typeof tmp[1] !== 'undefined') { + userAgent = tmp[0]; + } + tmp = userAgent.split('Twitter'); + if (typeof tmp[1] !== 'undefined') { + userAgent = tmp[0]; + } + var match = createMatch(userAgent); + var result = { + apple: { + phone: match(appleIphone) && !match(windowsPhone), + ipod: match(appleIpod), + tablet: !match(appleIphone) && + (match(appleTablet) || isAppleTabletOnIos13(nav)) && + !match(windowsPhone), + universal: match(appleUniversal), + device: (match(appleIphone) || + match(appleIpod) || + match(appleTablet) || + match(appleUniversal) || + isAppleTabletOnIos13(nav)) && + !match(windowsPhone) + }, + amazon: { + phone: match(amazonPhone), + tablet: !match(amazonPhone) && match(amazonTablet), + device: match(amazonPhone) || match(amazonTablet) + }, + android: { + phone: (!match(windowsPhone) && match(amazonPhone)) || + (!match(windowsPhone) && match(androidPhone)), + tablet: !match(windowsPhone) && + !match(amazonPhone) && + !match(androidPhone) && + (match(amazonTablet) || match(androidTablet)), + device: (!match(windowsPhone) && + (match(amazonPhone) || + match(amazonTablet) || + match(androidPhone) || + match(androidTablet))) || + match(/\bokhttp\b/i) + }, + windows: { + phone: match(windowsPhone), + tablet: match(windowsTablet), + device: match(windowsPhone) || match(windowsTablet) + }, + other: { + blackberry: match(otherBlackBerry), + blackberry10: match(otherBlackBerry10), + opera: match(otherOpera), + firefox: match(otherFirefox), + chrome: match(otherChrome), + device: match(otherBlackBerry) || + match(otherBlackBerry10) || + match(otherOpera) || + match(otherFirefox) || + match(otherChrome) + }, + any: false, + phone: false, + tablet: false + }; + result.any = + result.apple.device || + result.android.device || + result.windows.device || + result.other.device; + result.phone = + result.apple.phone || result.android.phone || result.windows.phone; + result.tablet = + result.apple.tablet || result.android.tablet || result.windows.tablet; + return result; + } + + var isMobile = isMobile$1(globalThis.navigator); + + /** + * Uploading the same buffer multiple times in a single frame can cause performance issues. + * Apparent on iOS so only check for that at the moment + * This check may become more complex if this issue pops up elsewhere. + * @private + * @returns {boolean} `true` if the same buffer may be uploaded more than once. + */ + function canUploadSameBuffer() { + return !isMobile.apple.device; + } + + /** + * The maximum recommended texture units to use. + * In theory the bigger the better, and for desktop we'll use as many as we can. + * But some mobile devices slow down if there is to many branches in the shader. + * So in practice there seems to be a sweet spot size that varies depending on the device. + * + * In v4, all mobile devices were limited to 4 texture units because for this. + * In v5, we allow all texture units to be used on modern Apple or Android devices. + * @private + * @param {number} max + * @returns {number} The maximum recommended texture units to use. + */ + function maxRecommendedTextures(max) { + var allowMax = true; + if (isMobile.tablet || isMobile.phone) { + if (isMobile.apple.device) { + var match = (navigator.userAgent).match(/OS (\d+)_(\d+)?/); + if (match) { + var majorVersion = parseInt(match[1], 10); + // Limit texture units on devices below iOS 11, which will be older hardware + if (majorVersion < 11) { + allowMax = false; + } + } + } + if (isMobile.android.device) { + var match = (navigator.userAgent).match(/Android\s([0-9.]*)/); + if (match) { + var majorVersion = parseInt(match[1], 10); + // Limit texture units on devices below Android 7 (Nougat), which will be older hardware + if (majorVersion < 7) { + allowMax = false; + } + } + } + } + return allowMax ? max : 4; + } + + /** + * User's customizable globals for overriding the default PIXI settings, such + * as a renderer's default resolution, framerate, float precision, etc. + * @example + * // Use the native window resolution as the default resolution + * // will support high-density displays when rendering + * PIXI.settings.RESOLUTION = window.devicePixelRatio; + * + * // Disable interpolation when scaling, will make texture be pixelated + * PIXI.settings.SCALE_MODE = PIXI.SCALE_MODES.NEAREST; + * @namespace PIXI.settings + */ + var settings = { + /** + * This adapter is used to call methods that are platform dependent. + * For example `document.createElement` only runs on the web but fails in node environments. + * This allows us to support more platforms by abstracting away specific implementations per platform. + * + * By default the adapter is set to work in the browser. However you can create your own + * by implementing the `IAdapter` interface. See `IAdapter` for more information. + * @name ADAPTER + * @memberof PIXI.settings + * @type {PIXI.IAdapter} + * @default PIXI.BrowserAdapter + */ + ADAPTER: BrowserAdapter, + /** + * If set to true WebGL will attempt make textures mimpaped by default. + * Mipmapping will only succeed if the base texture uploaded has power of two dimensions. + * @static + * @name MIPMAP_TEXTURES + * @memberof PIXI.settings + * @type {PIXI.MIPMAP_MODES} + * @default PIXI.MIPMAP_MODES.POW2 + */ + MIPMAP_TEXTURES: MIPMAP_MODES$1.POW2, + /** + * Default anisotropic filtering level of textures. + * Usually from 0 to 16 + * @static + * @name ANISOTROPIC_LEVEL + * @memberof PIXI.settings + * @type {number} + * @default 0 + */ + ANISOTROPIC_LEVEL: 0, + /** + * Default resolution / device pixel ratio of the renderer. + * @static + * @name RESOLUTION + * @memberof PIXI.settings + * @type {number} + * @default 1 + */ + RESOLUTION: 1, + /** + * Default filter resolution. + * @static + * @name FILTER_RESOLUTION + * @memberof PIXI.settings + * @type {number} + * @default 1 + */ + FILTER_RESOLUTION: 1, + /** + * Default filter samples. + * @static + * @name FILTER_MULTISAMPLE + * @memberof PIXI.settings + * @type {PIXI.MSAA_QUALITY} + * @default PIXI.MSAA_QUALITY.NONE + */ + FILTER_MULTISAMPLE: MSAA_QUALITY$1.NONE, + /** + * The maximum textures that this device supports. + * @static + * @name SPRITE_MAX_TEXTURES + * @memberof PIXI.settings + * @type {number} + * @default 32 + */ + SPRITE_MAX_TEXTURES: maxRecommendedTextures(32), + // TODO: maybe change to SPRITE.BATCH_SIZE: 2000 + // TODO: maybe add PARTICLE.BATCH_SIZE: 15000 + /** + * The default sprite batch size. + * + * The default aims to balance desktop and mobile devices. + * @static + * @name SPRITE_BATCH_SIZE + * @memberof PIXI.settings + * @type {number} + * @default 4096 + */ + SPRITE_BATCH_SIZE: 4096, + /** + * The default render options if none are supplied to {@link PIXI.Renderer} + * or {@link PIXI.CanvasRenderer}. + * @static + * @name RENDER_OPTIONS + * @memberof PIXI.settings + * @type {object} + * @property {HTMLCanvasElement} [view=null] - + * @property {boolean} [antialias=false] - + * @property {boolean} [autoDensity=false] - + * @property {boolean} [useContextAlpha=true] - + * @property {number} [backgroundColor=0x000000] - + * @property {number} [backgroundAlpha=1] - + * @property {boolean} [clearBeforeRender=true] - + * @property {boolean} [preserveDrawingBuffer=false] - + * @property {number} [width=800] - + * @property {number} [height=600] - + * @property {boolean} [legacy=false] - + */ + RENDER_OPTIONS: { + view: null, + antialias: false, + autoDensity: false, + backgroundColor: 0x000000, + backgroundAlpha: 1, + useContextAlpha: true, + clearBeforeRender: true, + preserveDrawingBuffer: false, + width: 800, + height: 600, + legacy: false, + }, + /** + * Default Garbage Collection mode. + * @static + * @name GC_MODE + * @memberof PIXI.settings + * @type {PIXI.GC_MODES} + * @default PIXI.GC_MODES.AUTO + */ + GC_MODE: GC_MODES$1.AUTO, + /** + * Default Garbage Collection max idle. + * @static + * @name GC_MAX_IDLE + * @memberof PIXI.settings + * @type {number} + * @default 3600 + */ + GC_MAX_IDLE: 60 * 60, + /** + * Default Garbage Collection maximum check count. + * @static + * @name GC_MAX_CHECK_COUNT + * @memberof PIXI.settings + * @type {number} + * @default 600 + */ + GC_MAX_CHECK_COUNT: 60 * 10, + /** + * Default wrap modes that are supported by pixi. + * @static + * @name WRAP_MODE + * @memberof PIXI.settings + * @type {PIXI.WRAP_MODES} + * @default PIXI.WRAP_MODES.CLAMP + */ + WRAP_MODE: WRAP_MODES$1.CLAMP, + /** + * Default scale mode for textures. + * @static + * @name SCALE_MODE + * @memberof PIXI.settings + * @type {PIXI.SCALE_MODES} + * @default PIXI.SCALE_MODES.LINEAR + */ + SCALE_MODE: SCALE_MODES$1.LINEAR, + /** + * Default specify float precision in vertex shader. + * @static + * @name PRECISION_VERTEX + * @memberof PIXI.settings + * @type {PIXI.PRECISION} + * @default PIXI.PRECISION.HIGH + */ + PRECISION_VERTEX: PRECISION$1.HIGH, + /** + * Default specify float precision in fragment shader. + * iOS is best set at highp due to https://github.com/pixijs/pixi.js/issues/3742 + * @static + * @name PRECISION_FRAGMENT + * @memberof PIXI.settings + * @type {PIXI.PRECISION} + * @default PIXI.PRECISION.MEDIUM + */ + PRECISION_FRAGMENT: isMobile.apple.device ? PRECISION$1.HIGH : PRECISION$1.MEDIUM, + /** + * Can we upload the same buffer in a single frame? + * @static + * @name CAN_UPLOAD_SAME_BUFFER + * @memberof PIXI.settings + * @type {boolean} + */ + CAN_UPLOAD_SAME_BUFFER: canUploadSameBuffer(), + /** + * Enables bitmap creation before image load. This feature is experimental. + * @static + * @name CREATE_IMAGE_BITMAP + * @memberof PIXI.settings + * @type {boolean} + * @default false + */ + CREATE_IMAGE_BITMAP: false, + /** + * If true PixiJS will Math.floor() x/y values when rendering, stopping pixel interpolation. + * Advantages can include sharper image quality (like text) and faster rendering on canvas. + * The main disadvantage is movement of objects may appear less smooth. + * @static + * @constant + * @memberof PIXI.settings + * @type {boolean} + * @default false + */ + ROUND_PIXELS: false, + }; + + var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; + + function createCommonjsModule(fn, basedir, module) { + return module = { + path: basedir, + exports: {}, + require: function (path, base) { + return commonjsRequire(path, (base === undefined || base === null) ? module.path : base); + } + }, fn(module, module.exports), module.exports; + } + + function commonjsRequire () { + throw new Error('Dynamic requires are not currently supported by @rollup/plugin-commonjs'); + } + + createCommonjsModule(function (module) { + + var has = Object.prototype.hasOwnProperty + , prefix = '~'; + + /** + * Constructor to create a storage for our `EE` objects. + * An `Events` instance is a plain object whose properties are event names. + * + * @constructor + * @private + */ + function Events() {} + + // + // We try to not inherit from `Object.prototype`. In some engines creating an + // instance in this way is faster than calling `Object.create(null)` directly. + // If `Object.create(null)` is not supported we prefix the event names with a + // character to make sure that the built-in object properties are not + // overridden or used as an attack vector. + // + if (Object.create) { + Events.prototype = Object.create(null); + + // + // This hack is needed because the `__proto__` property is still inherited in + // some old browsers like Android 4, iPhone 5.1, Opera 11 and Safari 5. + // + if (!new Events().__proto__) { prefix = false; } + } + + /** + * Representation of a single event listener. + * + * @param {Function} fn The listener function. + * @param {*} context The context to invoke the listener with. + * @param {Boolean} [once=false] Specify if the listener is a one-time listener. + * @constructor + * @private + */ + function EE(fn, context, once) { + this.fn = fn; + this.context = context; + this.once = once || false; + } + + /** + * Add a listener for a given event. + * + * @param {EventEmitter} emitter Reference to the `EventEmitter` instance. + * @param {(String|Symbol)} event The event name. + * @param {Function} fn The listener function. + * @param {*} context The context to invoke the listener with. + * @param {Boolean} once Specify if the listener is a one-time listener. + * @returns {EventEmitter} + * @private + */ + function addListener(emitter, event, fn, context, once) { + if (typeof fn !== 'function') { + throw new TypeError('The listener must be a function'); + } + + var listener = new EE(fn, context || emitter, once) + , evt = prefix ? prefix + event : event; + + if (!emitter._events[evt]) { emitter._events[evt] = listener, emitter._eventsCount++; } + else if (!emitter._events[evt].fn) { emitter._events[evt].push(listener); } + else { emitter._events[evt] = [emitter._events[evt], listener]; } + + return emitter; + } + + /** + * Clear event by name. + * + * @param {EventEmitter} emitter Reference to the `EventEmitter` instance. + * @param {(String|Symbol)} evt The Event name. + * @private + */ + function clearEvent(emitter, evt) { + if (--emitter._eventsCount === 0) { emitter._events = new Events(); } + else { delete emitter._events[evt]; } + } + + /** + * Minimal `EventEmitter` interface that is molded against the Node.js + * `EventEmitter` interface. + * + * @constructor + * @public + */ + function EventEmitter() { + this._events = new Events(); + this._eventsCount = 0; + } + + /** + * Return an array listing the events for which the emitter has registered + * listeners. + * + * @returns {Array} + * @public + */ + EventEmitter.prototype.eventNames = function eventNames() { + var names = [] + , events + , name; + + if (this._eventsCount === 0) { return names; } + + for (name in (events = this._events)) { + if (has.call(events, name)) { names.push(prefix ? name.slice(1) : name); } + } + + if (Object.getOwnPropertySymbols) { + return names.concat(Object.getOwnPropertySymbols(events)); + } + + return names; + }; + + /** + * Return the listeners registered for a given event. + * + * @param {(String|Symbol)} event The event name. + * @returns {Array} The registered listeners. + * @public + */ + EventEmitter.prototype.listeners = function listeners(event) { + var evt = prefix ? prefix + event : event + , handlers = this._events[evt]; + + if (!handlers) { return []; } + if (handlers.fn) { return [handlers.fn]; } + + for (var i = 0, l = handlers.length, ee = new Array(l); i < l; i++) { + ee[i] = handlers[i].fn; + } + + return ee; + }; + + /** + * Return the number of listeners listening to a given event. + * + * @param {(String|Symbol)} event The event name. + * @returns {Number} The number of listeners. + * @public + */ + EventEmitter.prototype.listenerCount = function listenerCount(event) { + var evt = prefix ? prefix + event : event + , listeners = this._events[evt]; + + if (!listeners) { return 0; } + if (listeners.fn) { return 1; } + return listeners.length; + }; + + /** + * Calls each of the listeners registered for a given event. + * + * @param {(String|Symbol)} event The event name. + * @returns {Boolean} `true` if the event had listeners, else `false`. + * @public + */ + EventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) { + var arguments$1 = arguments; + + var evt = prefix ? prefix + event : event; + + if (!this._events[evt]) { return false; } + + var listeners = this._events[evt] + , len = arguments.length + , args + , i; + + if (listeners.fn) { + if (listeners.once) { this.removeListener(event, listeners.fn, undefined, true); } + + switch (len) { + case 1: return listeners.fn.call(listeners.context), true; + case 2: return listeners.fn.call(listeners.context, a1), true; + case 3: return listeners.fn.call(listeners.context, a1, a2), true; + case 4: return listeners.fn.call(listeners.context, a1, a2, a3), true; + case 5: return listeners.fn.call(listeners.context, a1, a2, a3, a4), true; + case 6: return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true; + } + + for (i = 1, args = new Array(len -1); i < len; i++) { + args[i - 1] = arguments$1[i]; + } + + listeners.fn.apply(listeners.context, args); + } else { + var length = listeners.length + , j; + + for (i = 0; i < length; i++) { + if (listeners[i].once) { this.removeListener(event, listeners[i].fn, undefined, true); } + + switch (len) { + case 1: listeners[i].fn.call(listeners[i].context); break; + case 2: listeners[i].fn.call(listeners[i].context, a1); break; + case 3: listeners[i].fn.call(listeners[i].context, a1, a2); break; + case 4: listeners[i].fn.call(listeners[i].context, a1, a2, a3); break; + default: + if (!args) { for (j = 1, args = new Array(len -1); j < len; j++) { + args[j - 1] = arguments$1[j]; + } } + + listeners[i].fn.apply(listeners[i].context, args); + } + } + } + + return true; + }; + + /** + * Add a listener for a given event. + * + * @param {(String|Symbol)} event The event name. + * @param {Function} fn The listener function. + * @param {*} [context=this] The context to invoke the listener with. + * @returns {EventEmitter} `this`. + * @public + */ + EventEmitter.prototype.on = function on(event, fn, context) { + return addListener(this, event, fn, context, false); + }; + + /** + * Add a one-time listener for a given event. + * + * @param {(String|Symbol)} event The event name. + * @param {Function} fn The listener function. + * @param {*} [context=this] The context to invoke the listener with. + * @returns {EventEmitter} `this`. + * @public + */ + EventEmitter.prototype.once = function once(event, fn, context) { + return addListener(this, event, fn, context, true); + }; + + /** + * Remove the listeners of a given event. + * + * @param {(String|Symbol)} event The event name. + * @param {Function} fn Only remove the listeners that match this function. + * @param {*} context Only remove the listeners that have this context. + * @param {Boolean} once Only remove one-time listeners. + * @returns {EventEmitter} `this`. + * @public + */ + EventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) { + var evt = prefix ? prefix + event : event; + + if (!this._events[evt]) { return this; } + if (!fn) { + clearEvent(this, evt); + return this; + } + + var listeners = this._events[evt]; + + if (listeners.fn) { + if ( + listeners.fn === fn && + (!once || listeners.once) && + (!context || listeners.context === context) + ) { + clearEvent(this, evt); + } + } else { + for (var i = 0, events = [], length = listeners.length; i < length; i++) { + if ( + listeners[i].fn !== fn || + (once && !listeners[i].once) || + (context && listeners[i].context !== context) + ) { + events.push(listeners[i]); + } + } + + // + // Reset the array, or remove it completely if we have no more listeners. + // + if (events.length) { this._events[evt] = events.length === 1 ? events[0] : events; } + else { clearEvent(this, evt); } + } + + return this; + }; + + /** + * Remove all listeners, or those of the specified event. + * + * @param {(String|Symbol)} [event] The event name. + * @returns {EventEmitter} `this`. + * @public + */ + EventEmitter.prototype.removeAllListeners = function removeAllListeners(event) { + var evt; + + if (event) { + evt = prefix ? prefix + event : event; + if (this._events[evt]) { clearEvent(this, evt); } + } else { + this._events = new Events(); + this._eventsCount = 0; + } + + return this; + }; + + // + // Alias methods names because people roll like that. + // + EventEmitter.prototype.off = EventEmitter.prototype.removeListener; + EventEmitter.prototype.addListener = EventEmitter.prototype.on; + + // + // Expose the prefix. + // + EventEmitter.prefixed = prefix; + + // + // Allow `EventEmitter` to be imported as module namespace. + // + EventEmitter.EventEmitter = EventEmitter; + + // + // Expose the module. + // + { + module.exports = EventEmitter; + } + }); + + createCommonjsModule(function (module, exports) { + (function(root) { + + /** Detect free variables */ + var freeExports = exports && + !exports.nodeType && exports; + var freeModule = module && + !module.nodeType && module; + var freeGlobal = typeof commonjsGlobal == 'object' && commonjsGlobal; + if ( + freeGlobal.global === freeGlobal || + freeGlobal.window === freeGlobal || + freeGlobal.self === freeGlobal + ) { + root = freeGlobal; + } + + /** + * The `punycode` object. + * @name punycode + * @type Object + */ + var punycode, + + /** Highest positive signed 32-bit float value */ + maxInt = 2147483647, // aka. 0x7FFFFFFF or 2^31-1 + + /** Bootstring parameters */ + base = 36, + tMin = 1, + tMax = 26, + skew = 38, + damp = 700, + initialBias = 72, + initialN = 128, // 0x80 + delimiter = '-', // '\x2D' + + /** Regular expressions */ + regexPunycode = /^xn--/, + regexNonASCII = /[^\x20-\x7E]/, // unprintable ASCII chars + non-ASCII chars + regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g, // RFC 3490 separators + + /** Error messages */ + errors = { + 'overflow': 'Overflow: input needs wider integers to process', + 'not-basic': 'Illegal input >= 0x80 (not a basic code point)', + 'invalid-input': 'Invalid input' + }, + + /** Convenience shortcuts */ + baseMinusTMin = base - tMin, + floor = Math.floor, + stringFromCharCode = String.fromCharCode, + + /** Temporary variable */ + key; + + /*--------------------------------------------------------------------------*/ + + /** + * A generic error utility function. + * @private + * @param {String} type The error type. + * @returns {Error} Throws a `RangeError` with the applicable error message. + */ + function error(type) { + throw RangeError(errors[type]); + } + + /** + * A generic `Array#map` utility function. + * @private + * @param {Array} array The array to iterate over. + * @param {Function} callback The function that gets called for every array + * item. + * @returns {Array} A new array of values returned by the callback function. + */ + function map(array, fn) { + var length = array.length; + var result = []; + while (length--) { + result[length] = fn(array[length]); + } + return result; + } + + /** + * A simple `Array#map`-like wrapper to work with domain name strings or email + * addresses. + * @private + * @param {String} domain The domain name or email address. + * @param {Function} callback The function that gets called for every + * character. + * @returns {Array} A new string of characters returned by the callback + * function. + */ + function mapDomain(string, fn) { + var parts = string.split('@'); + var result = ''; + if (parts.length > 1) { + // In email addresses, only the domain name should be punycoded. Leave + // the local part (i.e. everything up to `@`) intact. + result = parts[0] + '@'; + string = parts[1]; + } + // Avoid `split(regex)` for IE8 compatibility. See #17. + string = string.replace(regexSeparators, '\x2E'); + var labels = string.split('.'); + var encoded = map(labels, fn).join('.'); + return result + encoded; + } + + /** + * Creates an array containing the numeric code points of each Unicode + * character in the string. While JavaScript uses UCS-2 internally, + * this function will convert a pair of surrogate halves (each of which + * UCS-2 exposes as separate characters) into a single code point, + * matching UTF-16. + * @see `punycode.ucs2.encode` + * @see + * @memberOf punycode.ucs2 + * @name decode + * @param {String} string The Unicode input string (UCS-2). + * @returns {Array} The new array of code points. + */ + function ucs2decode(string) { + var output = [], + counter = 0, + length = string.length, + value, + extra; + while (counter < length) { + value = string.charCodeAt(counter++); + if (value >= 0xD800 && value <= 0xDBFF && counter < length) { + // high surrogate, and there is a next character + extra = string.charCodeAt(counter++); + if ((extra & 0xFC00) == 0xDC00) { // low surrogate + output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000); + } else { + // unmatched surrogate; only append this code unit, in case the next + // code unit is the high surrogate of a surrogate pair + output.push(value); + counter--; + } + } else { + output.push(value); + } + } + return output; + } + + /** + * Creates a string based on an array of numeric code points. + * @see `punycode.ucs2.decode` + * @memberOf punycode.ucs2 + * @name encode + * @param {Array} codePoints The array of numeric code points. + * @returns {String} The new Unicode string (UCS-2). + */ + function ucs2encode(array) { + return map(array, function(value) { + var output = ''; + if (value > 0xFFFF) { + value -= 0x10000; + output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800); + value = 0xDC00 | value & 0x3FF; + } + output += stringFromCharCode(value); + return output; + }).join(''); + } + + /** + * Converts a basic code point into a digit/integer. + * @see `digitToBasic()` + * @private + * @param {Number} codePoint The basic numeric code point value. + * @returns {Number} The numeric value of a basic code point (for use in + * representing integers) in the range `0` to `base - 1`, or `base` if + * the code point does not represent a value. + */ + function basicToDigit(codePoint) { + if (codePoint - 48 < 10) { + return codePoint - 22; + } + if (codePoint - 65 < 26) { + return codePoint - 65; + } + if (codePoint - 97 < 26) { + return codePoint - 97; + } + return base; + } + + /** + * Converts a digit/integer into a basic code point. + * @see `basicToDigit()` + * @private + * @param {Number} digit The numeric value of a basic code point. + * @returns {Number} The basic code point whose value (when used for + * representing integers) is `digit`, which needs to be in the range + * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is + * used; else, the lowercase form is used. The behavior is undefined + * if `flag` is non-zero and `digit` has no uppercase form. + */ + function digitToBasic(digit, flag) { + // 0..25 map to ASCII a..z or A..Z + // 26..35 map to ASCII 0..9 + return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5); + } + + /** + * Bias adaptation function as per section 3.4 of RFC 3492. + * http://tools.ietf.org/html/rfc3492#section-3.4 + * @private + */ + function adapt(delta, numPoints, firstTime) { + var k = 0; + delta = firstTime ? floor(delta / damp) : delta >> 1; + delta += floor(delta / numPoints); + for (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) { + delta = floor(delta / baseMinusTMin); + } + return floor(k + (baseMinusTMin + 1) * delta / (delta + skew)); + } + + /** + * Converts a Punycode string of ASCII-only symbols to a string of Unicode + * symbols. + * @memberOf punycode + * @param {String} input The Punycode string of ASCII-only symbols. + * @returns {String} The resulting string of Unicode symbols. + */ + function decode(input) { + // Don't use UCS-2 + var output = [], + inputLength = input.length, + out, + i = 0, + n = initialN, + bias = initialBias, + basic, + j, + index, + oldi, + w, + k, + digit, + t, + /** Cached calculation results */ + baseMinusT; + + // Handle the basic code points: let `basic` be the number of input code + // points before the last delimiter, or `0` if there is none, then copy + // the first basic code points to the output. + + basic = input.lastIndexOf(delimiter); + if (basic < 0) { + basic = 0; + } + + for (j = 0; j < basic; ++j) { + // if it's not a basic code point + if (input.charCodeAt(j) >= 0x80) { + error('not-basic'); + } + output.push(input.charCodeAt(j)); + } + + // Main decoding loop: start just after the last delimiter if any basic code + // points were copied; start at the beginning otherwise. + + for (index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) { + + // `index` is the index of the next character to be consumed. + // Decode a generalized variable-length integer into `delta`, + // which gets added to `i`. The overflow checking is easier + // if we increase `i` as we go, then subtract off its starting + // value at the end to obtain `delta`. + for (oldi = i, w = 1, k = base; /* no condition */; k += base) { + + if (index >= inputLength) { + error('invalid-input'); + } + + digit = basicToDigit(input.charCodeAt(index++)); + + if (digit >= base || digit > floor((maxInt - i) / w)) { + error('overflow'); + } + + i += digit * w; + t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); + + if (digit < t) { + break; + } + + baseMinusT = base - t; + if (w > floor(maxInt / baseMinusT)) { + error('overflow'); + } + + w *= baseMinusT; + + } + + out = output.length + 1; + bias = adapt(i - oldi, out, oldi == 0); + + // `i` was supposed to wrap around from `out` to `0`, + // incrementing `n` each time, so we'll fix that now: + if (floor(i / out) > maxInt - n) { + error('overflow'); + } + + n += floor(i / out); + i %= out; + + // Insert `n` at position `i` of the output + output.splice(i++, 0, n); + + } + + return ucs2encode(output); + } + + /** + * Converts a string of Unicode symbols (e.g. a domain name label) to a + * Punycode string of ASCII-only symbols. + * @memberOf punycode + * @param {String} input The string of Unicode symbols. + * @returns {String} The resulting Punycode string of ASCII-only symbols. + */ + function encode(input) { + var n, + delta, + handledCPCount, + basicLength, + bias, + j, + m, + q, + k, + t, + currentValue, + output = [], + /** `inputLength` will hold the number of code points in `input`. */ + inputLength, + /** Cached calculation results */ + handledCPCountPlusOne, + baseMinusT, + qMinusT; + + // Convert the input in UCS-2 to Unicode + input = ucs2decode(input); + + // Cache the length + inputLength = input.length; + + // Initialize the state + n = initialN; + delta = 0; + bias = initialBias; + + // Handle the basic code points + for (j = 0; j < inputLength; ++j) { + currentValue = input[j]; + if (currentValue < 0x80) { + output.push(stringFromCharCode(currentValue)); + } + } + + handledCPCount = basicLength = output.length; + + // `handledCPCount` is the number of code points that have been handled; + // `basicLength` is the number of basic code points. + + // Finish the basic string - if it is not empty - with a delimiter + if (basicLength) { + output.push(delimiter); + } + + // Main encoding loop: + while (handledCPCount < inputLength) { + + // All non-basic code points < n have been handled already. Find the next + // larger one: + for (m = maxInt, j = 0; j < inputLength; ++j) { + currentValue = input[j]; + if (currentValue >= n && currentValue < m) { + m = currentValue; + } + } + + // Increase `delta` enough to advance the decoder's state to , + // but guard against overflow + handledCPCountPlusOne = handledCPCount + 1; + if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) { + error('overflow'); + } + + delta += (m - n) * handledCPCountPlusOne; + n = m; + + for (j = 0; j < inputLength; ++j) { + currentValue = input[j]; + + if (currentValue < n && ++delta > maxInt) { + error('overflow'); + } + + if (currentValue == n) { + // Represent delta as a generalized variable-length integer + for (q = delta, k = base; /* no condition */; k += base) { + t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); + if (q < t) { + break; + } + qMinusT = q - t; + baseMinusT = base - t; + output.push( + stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0)) + ); + q = floor(qMinusT / baseMinusT); + } + + output.push(stringFromCharCode(digitToBasic(q, 0))); + bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength); + delta = 0; + ++handledCPCount; + } + } + + ++delta; + ++n; + + } + return output.join(''); + } + + /** + * Converts a Punycode string representing a domain name or an email address + * to Unicode. Only the Punycoded parts of the input will be converted, i.e. + * it doesn't matter if you call it on a string that has already been + * converted to Unicode. + * @memberOf punycode + * @param {String} input The Punycoded domain name or email address to + * convert to Unicode. + * @returns {String} The Unicode representation of the given Punycode + * string. + */ + function toUnicode(input) { + return mapDomain(input, function(string) { + return regexPunycode.test(string) + ? decode(string.slice(4).toLowerCase()) + : string; + }); + } + + /** + * Converts a Unicode string representing a domain name or an email address to + * Punycode. Only the non-ASCII parts of the domain name will be converted, + * i.e. it doesn't matter if you call it with a domain that's already in + * ASCII. + * @memberOf punycode + * @param {String} input The domain name or email address to convert, as a + * Unicode string. + * @returns {String} The Punycode representation of the given domain name or + * email address. + */ + function toASCII(input) { + return mapDomain(input, function(string) { + return regexNonASCII.test(string) + ? 'xn--' + encode(string) + : string; + }); + } + + /*--------------------------------------------------------------------------*/ + + /** Define the public API */ + punycode = { + /** + * A string representing the current Punycode.js version number. + * @memberOf punycode + * @type String + */ + 'version': '1.3.2', + /** + * An object of methods to convert from JavaScript's internal character + * representation (UCS-2) to Unicode code points, and back. + * @see + * @memberOf punycode + * @type Object + */ + 'ucs2': { + 'decode': ucs2decode, + 'encode': ucs2encode + }, + 'decode': decode, + 'encode': encode, + 'toASCII': toASCII, + 'toUnicode': toUnicode + }; + + /** Expose `punycode` */ + // Some AMD build optimizers, like r.js, check for specific condition patterns + // like the following: + if (freeExports && freeModule) { + if (module.exports == freeExports) { // in Node.js or RingoJS v0.8.0+ + freeModule.exports = punycode; + } else { // in Narwhal or RingoJS v0.7.0- + for (key in punycode) { + punycode.hasOwnProperty(key) && (freeExports[key] = punycode[key]); + } + } + } else { // in Rhino or a web browser + root.punycode = punycode; + } + + }(commonjsGlobal)); + }); + + // Copyright Joyent, Inc. and other Node contributors. + + // If obj.hasOwnProperty has been overridden, then calling + // obj.hasOwnProperty(prop) will break. + // See: https://github.com/joyent/node/issues/1707 + function hasOwnProperty(obj, prop) { + return Object.prototype.hasOwnProperty.call(obj, prop); + } + + var decode = function(qs, sep, eq, options) { + sep = sep || '&'; + eq = eq || '='; + var obj = {}; + + if (typeof qs !== 'string' || qs.length === 0) { + return obj; + } + + var regexp = /\+/g; + qs = qs.split(sep); + + var maxKeys = 1000; + if (options && typeof options.maxKeys === 'number') { + maxKeys = options.maxKeys; + } + + var len = qs.length; + // maxKeys <= 0 means that we should not limit keys count + if (maxKeys > 0 && len > maxKeys) { + len = maxKeys; + } + + for (var i = 0; i < len; ++i) { + var x = qs[i].replace(regexp, '%20'), + idx = x.indexOf(eq), + kstr, vstr, k, v; + + if (idx >= 0) { + kstr = x.substr(0, idx); + vstr = x.substr(idx + 1); + } else { + kstr = x; + vstr = ''; + } + + k = decodeURIComponent(kstr); + v = decodeURIComponent(vstr); + + if (!hasOwnProperty(obj, k)) { + obj[k] = v; + } else if (Array.isArray(obj[k])) { + obj[k].push(v); + } else { + obj[k] = [obj[k], v]; + } + } + + return obj; + }; + + // Copyright Joyent, Inc. and other Node contributors. + + var stringifyPrimitive = function(v) { + switch (typeof v) { + case 'string': + return v; + + case 'boolean': + return v ? 'true' : 'false'; + + case 'number': + return isFinite(v) ? v : ''; + + default: + return ''; + } + }; + + var encode = function(obj, sep, eq, name) { + sep = sep || '&'; + eq = eq || '='; + if (obj === null) { + obj = undefined; + } + + if (typeof obj === 'object') { + return Object.keys(obj).map(function(k) { + var ks = encodeURIComponent(stringifyPrimitive(k)) + eq; + if (Array.isArray(obj[k])) { + return obj[k].map(function(v) { + return ks + encodeURIComponent(stringifyPrimitive(v)); + }).join(sep); + } else { + return ks + encodeURIComponent(stringifyPrimitive(obj[k])); + } + }).join(sep); + + } + + if (!name) { return ''; } + return encodeURIComponent(stringifyPrimitive(name)) + eq + + encodeURIComponent(stringifyPrimitive(obj)); + }; + + createCommonjsModule(function (module, exports) { + + exports.decode = exports.parse = decode; + exports.encode = exports.stringify = encode; + }); + + /*! + * @pixi/constants - v6.5.3 + * Compiled Fri, 09 Sep 2022 13:55:20 UTC + * + * @pixi/constants is licensed under the MIT License. + * http://www.opensource.org/licenses/mit-license + */ + /** + * Different types of environments for WebGL. + * @static + * @memberof PIXI + * @name ENV + * @enum {number} + * @property {number} WEBGL_LEGACY - Used for older v1 WebGL devices. PixiJS will aim to ensure compatibility + * with older / less advanced devices. If you experience unexplained flickering prefer this environment. + * @property {number} WEBGL - Version 1 of WebGL + * @property {number} WEBGL2 - Version 2 of WebGL + */ + var ENV; + (function (ENV) { + ENV[ENV["WEBGL_LEGACY"] = 0] = "WEBGL_LEGACY"; + ENV[ENV["WEBGL"] = 1] = "WEBGL"; + ENV[ENV["WEBGL2"] = 2] = "WEBGL2"; + })(ENV || (ENV = {})); + /** + * Constant to identify the Renderer Type. + * @static + * @memberof PIXI + * @name RENDERER_TYPE + * @enum {number} + * @property {number} UNKNOWN - Unknown render type. + * @property {number} WEBGL - WebGL render type. + * @property {number} CANVAS - Canvas render type. + */ + var RENDERER_TYPE; + (function (RENDERER_TYPE) { + RENDERER_TYPE[RENDERER_TYPE["UNKNOWN"] = 0] = "UNKNOWN"; + RENDERER_TYPE[RENDERER_TYPE["WEBGL"] = 1] = "WEBGL"; + RENDERER_TYPE[RENDERER_TYPE["CANVAS"] = 2] = "CANVAS"; + })(RENDERER_TYPE || (RENDERER_TYPE = {})); + /** + * Bitwise OR of masks that indicate the buffers to be cleared. + * @static + * @memberof PIXI + * @name BUFFER_BITS + * @enum {number} + * @property {number} COLOR - Indicates the buffers currently enabled for color writing. + * @property {number} DEPTH - Indicates the depth buffer. + * @property {number} STENCIL - Indicates the stencil buffer. + */ + var BUFFER_BITS; + (function (BUFFER_BITS) { + BUFFER_BITS[BUFFER_BITS["COLOR"] = 16384] = "COLOR"; + BUFFER_BITS[BUFFER_BITS["DEPTH"] = 256] = "DEPTH"; + BUFFER_BITS[BUFFER_BITS["STENCIL"] = 1024] = "STENCIL"; + })(BUFFER_BITS || (BUFFER_BITS = {})); + /** + * Various blend modes supported by PIXI. + * + * IMPORTANT - The WebGL renderer only supports the NORMAL, ADD, MULTIPLY and SCREEN blend modes. + * Anything else will silently act like NORMAL. + * @memberof PIXI + * @name BLEND_MODES + * @enum {number} + * @property {number} NORMAL - + * @property {number} ADD - + * @property {number} MULTIPLY - + * @property {number} SCREEN - + * @property {number} OVERLAY - + * @property {number} DARKEN - + * @property {number} LIGHTEN - + * @property {number} COLOR_DODGE - + * @property {number} COLOR_BURN - + * @property {number} HARD_LIGHT - + * @property {number} SOFT_LIGHT - + * @property {number} DIFFERENCE - + * @property {number} EXCLUSION - + * @property {number} HUE - + * @property {number} SATURATION - + * @property {number} COLOR - + * @property {number} LUMINOSITY - + * @property {number} NORMAL_NPM - + * @property {number} ADD_NPM - + * @property {number} SCREEN_NPM - + * @property {number} NONE - + * @property {number} SRC_IN - + * @property {number} SRC_OUT - + * @property {number} SRC_ATOP - + * @property {number} DST_OVER - + * @property {number} DST_IN - + * @property {number} DST_OUT - + * @property {number} DST_ATOP - + * @property {number} SUBTRACT - + * @property {number} SRC_OVER - + * @property {number} ERASE - + * @property {number} XOR - + */ + var BLEND_MODES; + (function (BLEND_MODES) { + BLEND_MODES[BLEND_MODES["NORMAL"] = 0] = "NORMAL"; + BLEND_MODES[BLEND_MODES["ADD"] = 1] = "ADD"; + BLEND_MODES[BLEND_MODES["MULTIPLY"] = 2] = "MULTIPLY"; + BLEND_MODES[BLEND_MODES["SCREEN"] = 3] = "SCREEN"; + BLEND_MODES[BLEND_MODES["OVERLAY"] = 4] = "OVERLAY"; + BLEND_MODES[BLEND_MODES["DARKEN"] = 5] = "DARKEN"; + BLEND_MODES[BLEND_MODES["LIGHTEN"] = 6] = "LIGHTEN"; + BLEND_MODES[BLEND_MODES["COLOR_DODGE"] = 7] = "COLOR_DODGE"; + BLEND_MODES[BLEND_MODES["COLOR_BURN"] = 8] = "COLOR_BURN"; + BLEND_MODES[BLEND_MODES["HARD_LIGHT"] = 9] = "HARD_LIGHT"; + BLEND_MODES[BLEND_MODES["SOFT_LIGHT"] = 10] = "SOFT_LIGHT"; + BLEND_MODES[BLEND_MODES["DIFFERENCE"] = 11] = "DIFFERENCE"; + BLEND_MODES[BLEND_MODES["EXCLUSION"] = 12] = "EXCLUSION"; + BLEND_MODES[BLEND_MODES["HUE"] = 13] = "HUE"; + BLEND_MODES[BLEND_MODES["SATURATION"] = 14] = "SATURATION"; + BLEND_MODES[BLEND_MODES["COLOR"] = 15] = "COLOR"; + BLEND_MODES[BLEND_MODES["LUMINOSITY"] = 16] = "LUMINOSITY"; + BLEND_MODES[BLEND_MODES["NORMAL_NPM"] = 17] = "NORMAL_NPM"; + BLEND_MODES[BLEND_MODES["ADD_NPM"] = 18] = "ADD_NPM"; + BLEND_MODES[BLEND_MODES["SCREEN_NPM"] = 19] = "SCREEN_NPM"; + BLEND_MODES[BLEND_MODES["NONE"] = 20] = "NONE"; + BLEND_MODES[BLEND_MODES["SRC_OVER"] = 0] = "SRC_OVER"; + BLEND_MODES[BLEND_MODES["SRC_IN"] = 21] = "SRC_IN"; + BLEND_MODES[BLEND_MODES["SRC_OUT"] = 22] = "SRC_OUT"; + BLEND_MODES[BLEND_MODES["SRC_ATOP"] = 23] = "SRC_ATOP"; + BLEND_MODES[BLEND_MODES["DST_OVER"] = 24] = "DST_OVER"; + BLEND_MODES[BLEND_MODES["DST_IN"] = 25] = "DST_IN"; + BLEND_MODES[BLEND_MODES["DST_OUT"] = 26] = "DST_OUT"; + BLEND_MODES[BLEND_MODES["DST_ATOP"] = 27] = "DST_ATOP"; + BLEND_MODES[BLEND_MODES["ERASE"] = 26] = "ERASE"; + BLEND_MODES[BLEND_MODES["SUBTRACT"] = 28] = "SUBTRACT"; + BLEND_MODES[BLEND_MODES["XOR"] = 29] = "XOR"; + })(BLEND_MODES || (BLEND_MODES = {})); + /** + * Various webgl draw modes. These can be used to specify which GL drawMode to use + * under certain situations and renderers. + * @memberof PIXI + * @static + * @name DRAW_MODES + * @enum {number} + * @property {number} POINTS - + * @property {number} LINES - + * @property {number} LINE_LOOP - + * @property {number} LINE_STRIP - + * @property {number} TRIANGLES - + * @property {number} TRIANGLE_STRIP - + * @property {number} TRIANGLE_FAN - + */ + var DRAW_MODES; + (function (DRAW_MODES) { + DRAW_MODES[DRAW_MODES["POINTS"] = 0] = "POINTS"; + DRAW_MODES[DRAW_MODES["LINES"] = 1] = "LINES"; + DRAW_MODES[DRAW_MODES["LINE_LOOP"] = 2] = "LINE_LOOP"; + DRAW_MODES[DRAW_MODES["LINE_STRIP"] = 3] = "LINE_STRIP"; + DRAW_MODES[DRAW_MODES["TRIANGLES"] = 4] = "TRIANGLES"; + DRAW_MODES[DRAW_MODES["TRIANGLE_STRIP"] = 5] = "TRIANGLE_STRIP"; + DRAW_MODES[DRAW_MODES["TRIANGLE_FAN"] = 6] = "TRIANGLE_FAN"; + })(DRAW_MODES || (DRAW_MODES = {})); + /** + * Various GL texture/resources formats. + * @memberof PIXI + * @static + * @name FORMATS + * @enum {number} + * @property {number} [RGBA=6408] - + * @property {number} [RGB=6407] - + * @property {number} [RG=33319] - + * @property {number} [RED=6403] - + * @property {number} [RGBA_INTEGER=36249] - + * @property {number} [RGB_INTEGER=36248] - + * @property {number} [RG_INTEGER=33320] - + * @property {number} [RED_INTEGER=36244] - + * @property {number} [ALPHA=6406] - + * @property {number} [LUMINANCE=6409] - + * @property {number} [LUMINANCE_ALPHA=6410] - + * @property {number} [DEPTH_COMPONENT=6402] - + * @property {number} [DEPTH_STENCIL=34041] - + */ + var FORMATS; + (function (FORMATS) { + FORMATS[FORMATS["RGBA"] = 6408] = "RGBA"; + FORMATS[FORMATS["RGB"] = 6407] = "RGB"; + FORMATS[FORMATS["RG"] = 33319] = "RG"; + FORMATS[FORMATS["RED"] = 6403] = "RED"; + FORMATS[FORMATS["RGBA_INTEGER"] = 36249] = "RGBA_INTEGER"; + FORMATS[FORMATS["RGB_INTEGER"] = 36248] = "RGB_INTEGER"; + FORMATS[FORMATS["RG_INTEGER"] = 33320] = "RG_INTEGER"; + FORMATS[FORMATS["RED_INTEGER"] = 36244] = "RED_INTEGER"; + FORMATS[FORMATS["ALPHA"] = 6406] = "ALPHA"; + FORMATS[FORMATS["LUMINANCE"] = 6409] = "LUMINANCE"; + FORMATS[FORMATS["LUMINANCE_ALPHA"] = 6410] = "LUMINANCE_ALPHA"; + FORMATS[FORMATS["DEPTH_COMPONENT"] = 6402] = "DEPTH_COMPONENT"; + FORMATS[FORMATS["DEPTH_STENCIL"] = 34041] = "DEPTH_STENCIL"; + })(FORMATS || (FORMATS = {})); + /** + * Various GL target types. + * @memberof PIXI + * @static + * @name TARGETS + * @enum {number} + * @property {number} [TEXTURE_2D=3553] - + * @property {number} [TEXTURE_CUBE_MAP=34067] - + * @property {number} [TEXTURE_2D_ARRAY=35866] - + * @property {number} [TEXTURE_CUBE_MAP_POSITIVE_X=34069] - + * @property {number} [TEXTURE_CUBE_MAP_NEGATIVE_X=34070] - + * @property {number} [TEXTURE_CUBE_MAP_POSITIVE_Y=34071] - + * @property {number} [TEXTURE_CUBE_MAP_NEGATIVE_Y=34072] - + * @property {number} [TEXTURE_CUBE_MAP_POSITIVE_Z=34073] - + * @property {number} [TEXTURE_CUBE_MAP_NEGATIVE_Z=34074] - + */ + var TARGETS; + (function (TARGETS) { + TARGETS[TARGETS["TEXTURE_2D"] = 3553] = "TEXTURE_2D"; + TARGETS[TARGETS["TEXTURE_CUBE_MAP"] = 34067] = "TEXTURE_CUBE_MAP"; + TARGETS[TARGETS["TEXTURE_2D_ARRAY"] = 35866] = "TEXTURE_2D_ARRAY"; + TARGETS[TARGETS["TEXTURE_CUBE_MAP_POSITIVE_X"] = 34069] = "TEXTURE_CUBE_MAP_POSITIVE_X"; + TARGETS[TARGETS["TEXTURE_CUBE_MAP_NEGATIVE_X"] = 34070] = "TEXTURE_CUBE_MAP_NEGATIVE_X"; + TARGETS[TARGETS["TEXTURE_CUBE_MAP_POSITIVE_Y"] = 34071] = "TEXTURE_CUBE_MAP_POSITIVE_Y"; + TARGETS[TARGETS["TEXTURE_CUBE_MAP_NEGATIVE_Y"] = 34072] = "TEXTURE_CUBE_MAP_NEGATIVE_Y"; + TARGETS[TARGETS["TEXTURE_CUBE_MAP_POSITIVE_Z"] = 34073] = "TEXTURE_CUBE_MAP_POSITIVE_Z"; + TARGETS[TARGETS["TEXTURE_CUBE_MAP_NEGATIVE_Z"] = 34074] = "TEXTURE_CUBE_MAP_NEGATIVE_Z"; + })(TARGETS || (TARGETS = {})); + /** + * Various GL data format types. + * @memberof PIXI + * @static + * @name TYPES + * @enum {number} + * @property {number} [UNSIGNED_BYTE=5121] - + * @property {number} [UNSIGNED_SHORT=5123] - + * @property {number} [UNSIGNED_SHORT_5_6_5=33635] - + * @property {number} [UNSIGNED_SHORT_4_4_4_4=32819] - + * @property {number} [UNSIGNED_SHORT_5_5_5_1=32820] - + * @property {number} [UNSIGNED_INT=5125] - + * @property {number} [UNSIGNED_INT_10F_11F_11F_REV=35899] - + * @property {number} [UNSIGNED_INT_2_10_10_10_REV=33640] - + * @property {number} [UNSIGNED_INT_24_8=34042] - + * @property {number} [UNSIGNED_INT_5_9_9_9_REV=35902] - + * @property {number} [BYTE=5120] - + * @property {number} [SHORT=5122] - + * @property {number} [INT=5124] - + * @property {number} [FLOAT=5126] - + * @property {number} [FLOAT_32_UNSIGNED_INT_24_8_REV=36269] - + * @property {number} [HALF_FLOAT=36193] - + */ + var TYPES; + (function (TYPES) { + TYPES[TYPES["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE"; + TYPES[TYPES["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT"; + TYPES[TYPES["UNSIGNED_SHORT_5_6_5"] = 33635] = "UNSIGNED_SHORT_5_6_5"; + TYPES[TYPES["UNSIGNED_SHORT_4_4_4_4"] = 32819] = "UNSIGNED_SHORT_4_4_4_4"; + TYPES[TYPES["UNSIGNED_SHORT_5_5_5_1"] = 32820] = "UNSIGNED_SHORT_5_5_5_1"; + TYPES[TYPES["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT"; + TYPES[TYPES["UNSIGNED_INT_10F_11F_11F_REV"] = 35899] = "UNSIGNED_INT_10F_11F_11F_REV"; + TYPES[TYPES["UNSIGNED_INT_2_10_10_10_REV"] = 33640] = "UNSIGNED_INT_2_10_10_10_REV"; + TYPES[TYPES["UNSIGNED_INT_24_8"] = 34042] = "UNSIGNED_INT_24_8"; + TYPES[TYPES["UNSIGNED_INT_5_9_9_9_REV"] = 35902] = "UNSIGNED_INT_5_9_9_9_REV"; + TYPES[TYPES["BYTE"] = 5120] = "BYTE"; + TYPES[TYPES["SHORT"] = 5122] = "SHORT"; + TYPES[TYPES["INT"] = 5124] = "INT"; + TYPES[TYPES["FLOAT"] = 5126] = "FLOAT"; + TYPES[TYPES["FLOAT_32_UNSIGNED_INT_24_8_REV"] = 36269] = "FLOAT_32_UNSIGNED_INT_24_8_REV"; + TYPES[TYPES["HALF_FLOAT"] = 36193] = "HALF_FLOAT"; + })(TYPES || (TYPES = {})); + /** + * Various sampler types. Correspond to `sampler`, `isampler`, `usampler` GLSL types respectively. + * WebGL1 works only with FLOAT. + * @memberof PIXI + * @static + * @name SAMPLER_TYPES + * @enum {number} + * @property {number} [FLOAT=0] - + * @property {number} [INT=1] - + * @property {number} [UINT=2] - + */ + var SAMPLER_TYPES; + (function (SAMPLER_TYPES) { + SAMPLER_TYPES[SAMPLER_TYPES["FLOAT"] = 0] = "FLOAT"; + SAMPLER_TYPES[SAMPLER_TYPES["INT"] = 1] = "INT"; + SAMPLER_TYPES[SAMPLER_TYPES["UINT"] = 2] = "UINT"; + })(SAMPLER_TYPES || (SAMPLER_TYPES = {})); + /** + * The scale modes that are supported by pixi. + * + * The {@link PIXI.settings.SCALE_MODE} scale mode affects the default scaling mode of future operations. + * It can be re-assigned to either LINEAR or NEAREST, depending upon suitability. + * @memberof PIXI + * @static + * @name SCALE_MODES + * @enum {number} + * @property {number} LINEAR Smooth scaling + * @property {number} NEAREST Pixelating scaling + */ + var SCALE_MODES; + (function (SCALE_MODES) { + SCALE_MODES[SCALE_MODES["NEAREST"] = 0] = "NEAREST"; + SCALE_MODES[SCALE_MODES["LINEAR"] = 1] = "LINEAR"; + })(SCALE_MODES || (SCALE_MODES = {})); + /** + * The wrap modes that are supported by pixi. + * + * The {@link PIXI.settings.WRAP_MODE} wrap mode affects the default wrapping mode of future operations. + * It can be re-assigned to either CLAMP or REPEAT, depending upon suitability. + * If the texture is non power of two then clamp will be used regardless as WebGL can + * only use REPEAT if the texture is po2. + * + * This property only affects WebGL. + * @name WRAP_MODES + * @memberof PIXI + * @static + * @enum {number} + * @property {number} CLAMP - The textures uvs are clamped + * @property {number} REPEAT - The texture uvs tile and repeat + * @property {number} MIRRORED_REPEAT - The texture uvs tile and repeat with mirroring + */ + var WRAP_MODES; + (function (WRAP_MODES) { + WRAP_MODES[WRAP_MODES["CLAMP"] = 33071] = "CLAMP"; + WRAP_MODES[WRAP_MODES["REPEAT"] = 10497] = "REPEAT"; + WRAP_MODES[WRAP_MODES["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT"; + })(WRAP_MODES || (WRAP_MODES = {})); + /** + * Mipmap filtering modes that are supported by pixi. + * + * The {@link PIXI.settings.MIPMAP_TEXTURES} affects default texture filtering. + * Mipmaps are generated for a baseTexture if its `mipmap` field is `ON`, + * or its `POW2` and texture dimensions are powers of 2. + * Due to platform restriction, `ON` option will work like `POW2` for webgl-1. + * + * This property only affects WebGL. + * @name MIPMAP_MODES + * @memberof PIXI + * @static + * @enum {number} + * @property {number} OFF - No mipmaps + * @property {number} POW2 - Generate mipmaps if texture dimensions are pow2 + * @property {number} ON - Always generate mipmaps + * @property {number} ON_MANUAL - Use mipmaps, but do not auto-generate them; this is used with a resource + * that supports buffering each level-of-detail. + */ + var MIPMAP_MODES; + (function (MIPMAP_MODES) { + MIPMAP_MODES[MIPMAP_MODES["OFF"] = 0] = "OFF"; + MIPMAP_MODES[MIPMAP_MODES["POW2"] = 1] = "POW2"; + MIPMAP_MODES[MIPMAP_MODES["ON"] = 2] = "ON"; + MIPMAP_MODES[MIPMAP_MODES["ON_MANUAL"] = 3] = "ON_MANUAL"; + })(MIPMAP_MODES || (MIPMAP_MODES = {})); + /** + * How to treat textures with premultiplied alpha + * @name ALPHA_MODES + * @memberof PIXI + * @static + * @enum {number} + * @property {number} NO_PREMULTIPLIED_ALPHA - Source is not premultiplied, leave it like that. + * Option for compressed and data textures that are created from typed arrays. + * @property {number} PREMULTIPLY_ON_UPLOAD - Source is not premultiplied, premultiply on upload. + * Default option, used for all loaded images. + * @property {number} PREMULTIPLIED_ALPHA - Source is already premultiplied + * Example: spine atlases with `_pma` suffix. + * @property {number} NPM - Alias for NO_PREMULTIPLIED_ALPHA. + * @property {number} UNPACK - Default option, alias for PREMULTIPLY_ON_UPLOAD. + * @property {number} PMA - Alias for PREMULTIPLIED_ALPHA. + */ + var ALPHA_MODES; + (function (ALPHA_MODES) { + ALPHA_MODES[ALPHA_MODES["NPM"] = 0] = "NPM"; + ALPHA_MODES[ALPHA_MODES["UNPACK"] = 1] = "UNPACK"; + ALPHA_MODES[ALPHA_MODES["PMA"] = 2] = "PMA"; + ALPHA_MODES[ALPHA_MODES["NO_PREMULTIPLIED_ALPHA"] = 0] = "NO_PREMULTIPLIED_ALPHA"; + ALPHA_MODES[ALPHA_MODES["PREMULTIPLY_ON_UPLOAD"] = 1] = "PREMULTIPLY_ON_UPLOAD"; + ALPHA_MODES[ALPHA_MODES["PREMULTIPLY_ALPHA"] = 2] = "PREMULTIPLY_ALPHA"; + ALPHA_MODES[ALPHA_MODES["PREMULTIPLIED_ALPHA"] = 2] = "PREMULTIPLIED_ALPHA"; + })(ALPHA_MODES || (ALPHA_MODES = {})); + /** + * Configure whether filter textures are cleared after binding. + * + * Filter textures need not be cleared if the filter does not use pixel blending. {@link CLEAR_MODES.BLIT} will detect + * this and skip clearing as an optimization. + * @name CLEAR_MODES + * @memberof PIXI + * @static + * @enum {number} + * @property {number} BLEND - Do not clear the filter texture. The filter's output will blend on top of the output texture. + * @property {number} CLEAR - Always clear the filter texture. + * @property {number} BLIT - Clear only if {@link FilterSystem.forceClear} is set or if the filter uses pixel blending. + * @property {number} NO - Alias for BLEND, same as `false` in earlier versions + * @property {number} YES - Alias for CLEAR, same as `true` in earlier versions + * @property {number} AUTO - Alias for BLIT + */ + var CLEAR_MODES; + (function (CLEAR_MODES) { + CLEAR_MODES[CLEAR_MODES["NO"] = 0] = "NO"; + CLEAR_MODES[CLEAR_MODES["YES"] = 1] = "YES"; + CLEAR_MODES[CLEAR_MODES["AUTO"] = 2] = "AUTO"; + CLEAR_MODES[CLEAR_MODES["BLEND"] = 0] = "BLEND"; + CLEAR_MODES[CLEAR_MODES["CLEAR"] = 1] = "CLEAR"; + CLEAR_MODES[CLEAR_MODES["BLIT"] = 2] = "BLIT"; + })(CLEAR_MODES || (CLEAR_MODES = {})); + /** + * The gc modes that are supported by pixi. + * + * The {@link PIXI.settings.GC_MODE} Garbage Collection mode for PixiJS textures is AUTO + * If set to GC_MODE, the renderer will occasionally check textures usage. If they are not + * used for a specified period of time they will be removed from the GPU. They will of course + * be uploaded again when they are required. This is a silent behind the scenes process that + * should ensure that the GPU does not get filled up. + * + * Handy for mobile devices! + * This property only affects WebGL. + * @name GC_MODES + * @enum {number} + * @static + * @memberof PIXI + * @property {number} AUTO - Garbage collection will happen periodically automatically + * @property {number} MANUAL - Garbage collection will need to be called manually + */ + var GC_MODES; + (function (GC_MODES) { + GC_MODES[GC_MODES["AUTO"] = 0] = "AUTO"; + GC_MODES[GC_MODES["MANUAL"] = 1] = "MANUAL"; + })(GC_MODES || (GC_MODES = {})); + /** + * Constants that specify float precision in shaders. + * @name PRECISION + * @memberof PIXI + * @constant + * @static + * @enum {string} + * @property {string} [LOW='lowp'] - + * @property {string} [MEDIUM='mediump'] - + * @property {string} [HIGH='highp'] - + */ + var PRECISION; + (function (PRECISION) { + PRECISION["LOW"] = "lowp"; + PRECISION["MEDIUM"] = "mediump"; + PRECISION["HIGH"] = "highp"; + })(PRECISION || (PRECISION = {})); + /** + * Constants for mask implementations. + * We use `type` suffix because it leads to very different behaviours + * @name MASK_TYPES + * @memberof PIXI + * @static + * @enum {number} + * @property {number} NONE - Mask is ignored + * @property {number} SCISSOR - Scissor mask, rectangle on screen, cheap + * @property {number} STENCIL - Stencil mask, 1-bit, medium, works only if renderer supports stencil + * @property {number} SPRITE - Mask that uses SpriteMaskFilter, uses temporary RenderTexture + * @property {number} COLOR - Color mask (RGBA) + */ + var MASK_TYPES; + (function (MASK_TYPES) { + MASK_TYPES[MASK_TYPES["NONE"] = 0] = "NONE"; + MASK_TYPES[MASK_TYPES["SCISSOR"] = 1] = "SCISSOR"; + MASK_TYPES[MASK_TYPES["STENCIL"] = 2] = "STENCIL"; + MASK_TYPES[MASK_TYPES["SPRITE"] = 3] = "SPRITE"; + MASK_TYPES[MASK_TYPES["COLOR"] = 4] = "COLOR"; + })(MASK_TYPES || (MASK_TYPES = {})); + /** + * Bitwise OR of masks that indicate the color channels that are rendered to. + * @static + * @memberof PIXI + * @name COLOR_MASK_BITS + * @enum {number} + * @property {number} RED - Red channel. + * @property {number} GREEN - Green channel + * @property {number} BLUE - Blue channel. + * @property {number} ALPHA - Alpha channel. + */ + var COLOR_MASK_BITS; + (function (COLOR_MASK_BITS) { + COLOR_MASK_BITS[COLOR_MASK_BITS["RED"] = 1] = "RED"; + COLOR_MASK_BITS[COLOR_MASK_BITS["GREEN"] = 2] = "GREEN"; + COLOR_MASK_BITS[COLOR_MASK_BITS["BLUE"] = 4] = "BLUE"; + COLOR_MASK_BITS[COLOR_MASK_BITS["ALPHA"] = 8] = "ALPHA"; + })(COLOR_MASK_BITS || (COLOR_MASK_BITS = {})); + /** + * Constants for multi-sampling antialiasing. + * @see PIXI.Framebuffer#multisample + * @name MSAA_QUALITY + * @memberof PIXI + * @static + * @enum {number} + * @property {number} NONE - No multisampling for this renderTexture + * @property {number} LOW - Try 2 samples + * @property {number} MEDIUM - Try 4 samples + * @property {number} HIGH - Try 8 samples + */ + var MSAA_QUALITY; + (function (MSAA_QUALITY) { + MSAA_QUALITY[MSAA_QUALITY["NONE"] = 0] = "NONE"; + MSAA_QUALITY[MSAA_QUALITY["LOW"] = 2] = "LOW"; + MSAA_QUALITY[MSAA_QUALITY["MEDIUM"] = 4] = "MEDIUM"; + MSAA_QUALITY[MSAA_QUALITY["HIGH"] = 8] = "HIGH"; + })(MSAA_QUALITY || (MSAA_QUALITY = {})); + /** + * Constants for various buffer types in Pixi + * @see PIXI.BUFFER_TYPE + * @name BUFFER_TYPE + * @memberof PIXI + * @static + * @enum {number} + * @property {number} ELEMENT_ARRAY_BUFFER - buffer type for using as an index buffer + * @property {number} ARRAY_BUFFER - buffer type for using attribute data + * @property {number} UNIFORM_BUFFER - the buffer type is for uniform buffer objects + */ + var BUFFER_TYPE; + (function (BUFFER_TYPE) { + BUFFER_TYPE[BUFFER_TYPE["ELEMENT_ARRAY_BUFFER"] = 34963] = "ELEMENT_ARRAY_BUFFER"; + BUFFER_TYPE[BUFFER_TYPE["ARRAY_BUFFER"] = 34962] = "ARRAY_BUFFER"; + // NOT YET SUPPORTED + BUFFER_TYPE[BUFFER_TYPE["UNIFORM_BUFFER"] = 35345] = "UNIFORM_BUFFER"; + })(BUFFER_TYPE || (BUFFER_TYPE = {})); + + /*! + * @pixi/utils - v6.5.3 + * Compiled Fri, 09 Sep 2022 13:55:20 UTC + * + * @pixi/utils is licensed under the MIT License. + * http://www.opensource.org/licenses/mit-license + */ + + /** + * The prefix that denotes a URL is for a retina asset. + * @static + * @name RETINA_PREFIX + * @memberof PIXI.settings + * @type {RegExp} + * @default /@([0-9\.]+)x/ + * @example `@2x` + */ + settings.RETINA_PREFIX = /@([0-9\.]+)x/; + /** + * Should the `failIfMajorPerformanceCaveat` flag be enabled as a context option used in the `isWebGLSupported` function. + * If set to true, a WebGL renderer can fail to be created if the browser thinks there could be performance issues when + * using WebGL. + * + * In PixiJS v6 this has changed from true to false by default, to allow WebGL to work in as many scenarios as possible. + * However, some users may have a poor experience, for example, if a user has a gpu or driver version blacklisted by the + * browser. + * + * If your application requires high performance rendering, you may wish to set this to false. + * We recommend one of two options if you decide to set this flag to false: + * + * 1: Use the `pixi.js-legacy` package, which includes a Canvas renderer as a fallback in case high performance WebGL is + * not supported. + * + * 2: Call `isWebGLSupported` (which if found in the PIXI.utils package) in your code before attempting to create a PixiJS + * renderer, and show an error message to the user if the function returns false, explaining that their device & browser + * combination does not support high performance WebGL. + * This is a much better strategy than trying to create a PixiJS renderer and finding it then fails. + * @static + * @name FAIL_IF_MAJOR_PERFORMANCE_CAVEAT + * @memberof PIXI.settings + * @type {boolean} + * @default false + */ + settings.FAIL_IF_MAJOR_PERFORMANCE_CAVEAT = false; + + /** + * Corrects PixiJS blend, takes premultiplied alpha into account + * @memberof PIXI.utils + * @function mapPremultipliedBlendModes + * @private + * @returns {Array} Mapped modes. + */ + function mapPremultipliedBlendModes() { + var pm = []; + var npm = []; + for (var i = 0; i < 32; i++) { + pm[i] = i; + npm[i] = i; + } + pm[BLEND_MODES.NORMAL_NPM] = BLEND_MODES.NORMAL; + pm[BLEND_MODES.ADD_NPM] = BLEND_MODES.ADD; + pm[BLEND_MODES.SCREEN_NPM] = BLEND_MODES.SCREEN; + npm[BLEND_MODES.NORMAL] = BLEND_MODES.NORMAL_NPM; + npm[BLEND_MODES.ADD] = BLEND_MODES.ADD_NPM; + npm[BLEND_MODES.SCREEN] = BLEND_MODES.SCREEN_NPM; + var array = []; + array.push(npm); + array.push(pm); + return array; + } + /** + * maps premultiply flag and blendMode to adjusted blendMode + * @memberof PIXI.utils + * @constant premultiplyBlendMode + * @type {Array} + */ + mapPremultipliedBlendModes(); + + // A map of warning messages already fired + var warnings = {}; + /** + * Helper for warning developers about deprecated features & settings. + * A stack track for warnings is given; useful for tracking-down where + * deprecated methods/properties/classes are being used within the code. + * @memberof PIXI.utils + * @function deprecation + * @param {string} version - The version where the feature became deprecated + * @param {string} message - Message should include what is deprecated, where, and the new solution + * @param {number} [ignoreDepth=3] - The number of steps to ignore at the top of the error stack + * this is mostly to ignore internal deprecation calls. + */ + function deprecation(version, message, ignoreDepth) { + if (ignoreDepth === void 0) { ignoreDepth = 3; } + // Ignore duplicat + if (warnings[message]) { + return; + } + /* eslint-disable no-console */ + var stack = new Error().stack; + // Handle IE < 10 and Safari < 6 + if (typeof stack === 'undefined') { + console.warn('PixiJS Deprecation Warning: ', message + "\nDeprecated since v" + version); + } + else { + // chop off the stack trace which includes PixiJS internal calls + stack = stack.split('\n').splice(ignoreDepth).join('\n'); + if (console.groupCollapsed) { + console.groupCollapsed('%cPixiJS Deprecation Warning: %c%s', 'color:#614108;background:#fffbe6', 'font-weight:normal;color:#614108;background:#fffbe6', message + "\nDeprecated since v" + version); + console.warn(stack); + console.groupEnd(); + } + else { + console.warn('PixiJS Deprecation Warning: ', message + "\nDeprecated since v" + version); + console.warn(stack); + } + } + /* eslint-enable no-console */ + warnings[message] = true; + } + + /** + * Creates a Canvas element of the given size to be used as a target for rendering to. + * @class + * @memberof PIXI.utils + */ + /** @class */ ((function () { + /** + * @param width - the width for the newly created canvas + * @param height - the height for the newly created canvas + * @param {number} [resolution=PIXI.settings.RESOLUTION] - The resolution / device pixel ratio of the canvas + */ + function CanvasRenderTarget(width, height, resolution) { + this.canvas = settings.ADAPTER.createCanvas(); + this.context = this.canvas.getContext('2d'); + this.resolution = resolution || settings.RESOLUTION; + this.resize(width, height); + } + /** + * Clears the canvas that was created by the CanvasRenderTarget class. + * @private + */ + CanvasRenderTarget.prototype.clear = function () { + this.context.setTransform(1, 0, 0, 1, 0, 0); + this.context.clearRect(0, 0, this.canvas.width, this.canvas.height); + }; + /** + * Resizes the canvas to the specified width and height. + * @param desiredWidth - the desired width of the canvas + * @param desiredHeight - the desired height of the canvas + */ + CanvasRenderTarget.prototype.resize = function (desiredWidth, desiredHeight) { + this.canvas.width = Math.round(desiredWidth * this.resolution); + this.canvas.height = Math.round(desiredHeight * this.resolution); + }; + /** Destroys this canvas. */ + CanvasRenderTarget.prototype.destroy = function () { + this.context = null; + this.canvas = null; + }; + Object.defineProperty(CanvasRenderTarget.prototype, "width", { + /** + * The width of the canvas buffer in pixels. + * @member {number} + */ + get: function () { + return this.canvas.width; + }, + set: function (val) { + this.canvas.width = Math.round(val); + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(CanvasRenderTarget.prototype, "height", { + /** + * The height of the canvas buffer in pixels. + * @member {number} + */ + get: function () { + return this.canvas.height; + }, + set: function (val) { + this.canvas.height = Math.round(val); + }, + enumerable: false, + configurable: true + }); + return CanvasRenderTarget; + })()); + + /** + * Convenience class to create a new PIXI application. + * + * This class automatically creates the renderer, ticker and root container. + * @example + * // Create the application + * const app = new PIXI.Application(); + * + * // Add the view to the DOM + * document.body.appendChild(app.view); + * + * // ex, add display objects + * app.stage.addChild(PIXI.Sprite.from('something.png')); + * @class + * @memberof PIXI + */ + var Application = /** @class */ (function () { + /** + * @param {object} [options] - The optional renderer parameters. + * @param {boolean} [options.autoStart=true] - Automatically starts the rendering after the construction. + * **Note**: Setting this parameter to false does NOT stop the shared ticker even if you set + * options.sharedTicker to true in case that it is already started. Stop it by your own. + * @param {number} [options.width=800] - The width of the renderers view. + * @param {number} [options.height=600] - The height of the renderers view. + * @param {HTMLCanvasElement} [options.view] - The canvas to use as a view, optional. + * @param {boolean} [options.useContextAlpha=true] - Pass-through value for canvas' context `alpha` property. + * If you want to set transparency, please use `backgroundAlpha`. This option is for cases where the + * canvas needs to be opaque, possibly for performance reasons on some older devices. + * @param {boolean} [options.autoDensity=false] - Resizes renderer view in CSS pixels to allow for + * resolutions other than 1. + * @param {boolean} [options.antialias=false] - Sets antialias + * @param {boolean} [options.preserveDrawingBuffer=false] - Enables drawing buffer preservation, enable this if you + * need to call toDataUrl on the WebGL context. + * @param {number} [options.resolution=PIXI.settings.RESOLUTION] - The resolution / device pixel ratio of the renderer. + * @param {boolean} [options.forceCanvas=false] - prevents selection of WebGL renderer, even if such is present, this + * option only is available when using **pixi.js-legacy** or **@pixi/canvas-renderer** modules, otherwise + * it is ignored. + * @param {number} [options.backgroundColor=0x000000] - The background color of the rendered area + * (shown if not transparent). + * @param {number} [options.backgroundAlpha=1] - Value from 0 (fully transparent) to 1 (fully opaque). + * @param {boolean} [options.clearBeforeRender=true] - This sets if the renderer will clear the canvas or + * not before the new render pass. + * @param {string} [options.powerPreference] - Parameter passed to webgl context, set to "high-performance" + * for devices with dual graphics card. **(WebGL only)**. + * @param {boolean} [options.sharedTicker=false] - `true` to use PIXI.Ticker.shared, `false` to create new ticker. + * If set to false, you cannot register a handler to occur before anything that runs on the shared ticker. + * The system ticker will always run before both the shared ticker and the app ticker. + * @param {boolean} [options.sharedLoader=false] - `true` to use PIXI.Loader.shared, `false` to create new Loader. + * @param {Window|HTMLElement} [options.resizeTo] - Element to automatically resize stage to. + */ + function Application(options) { + var _this = this; + /** + * The root display container that's rendered. + * @member {PIXI.Container} + */ + this.stage = new Container(); + // The default options + options = Object.assign({ + forceCanvas: false, + }, options); + this.renderer = autoDetectRenderer(options); + // install plugins here + Application._plugins.forEach(function (plugin) { + plugin.init.call(_this, options); + }); + } + /** + * Use the {@link PIXI.extensions.add} API to register plugins. + * @deprecated since 6.5.0 + * @static + * @param {PIXI.IApplicationPlugin} plugin - Plugin being installed + */ + Application.registerPlugin = function (plugin) { + deprecation('6.5.0', 'Application.registerPlugin() is deprecated, use extensions.add()'); + extensions.add({ + type: exports.ExtensionType.Application, + ref: plugin, + }); + }; + /** Render the current stage. */ + Application.prototype.render = function () { + this.renderer.render(this.stage); + }; + Object.defineProperty(Application.prototype, "view", { + /** + * Reference to the renderer's canvas element. + * @member {HTMLCanvasElement} + * @readonly + */ + get: function () { + return this.renderer.view; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(Application.prototype, "screen", { + /** + * Reference to the renderer's screen rectangle. Its safe to use as `filterArea` or `hitArea` for the whole screen. + * @member {PIXI.Rectangle} + * @readonly + */ + get: function () { + return this.renderer.screen; + }, + enumerable: false, + configurable: true + }); + /** + * Destroy and don't use after this. + * @param {boolean} [removeView=false] - Automatically remove canvas from DOM. + * @param {object|boolean} [stageOptions] - Options parameter. A boolean will act as if all options + * have been set to that value + * @param {boolean} [stageOptions.children=false] - if set to true, all the children will have their destroy + * method called as well. 'stageOptions' will be passed on to those calls. + * @param {boolean} [stageOptions.texture=false] - Only used for child Sprites if stageOptions.children is set + * to true. Should it destroy the texture of the child sprite + * @param {boolean} [stageOptions.baseTexture=false] - Only used for child Sprites if stageOptions.children is set + * to true. Should it destroy the base texture of the child sprite + */ + Application.prototype.destroy = function (removeView, stageOptions) { + var _this = this; + // Destroy plugins in the opposite order + // which they were constructed + var plugins = Application._plugins.slice(0); + plugins.reverse(); + plugins.forEach(function (plugin) { + plugin.destroy.call(_this); + }); + this.stage.destroy(stageOptions); + this.stage = null; + this.renderer.destroy(removeView); + this.renderer = null; + }; + /** Collection of installed plugins. */ + Application._plugins = []; + return Application; + }()); + extensions.handleByList(exports.ExtensionType.Application, Application._plugins); + + extensions.add(ResizePlugin); + + /*! + * @pixi/mesh-extras - v6.5.3 + * Compiled Fri, 09 Sep 2022 13:55:20 UTC + * + * @pixi/mesh-extras is licensed under the MIT License. + * http://www.opensource.org/licenses/mit-license + */ + + /*! ***************************************************************************** + Copyright (c) Microsoft Corporation. - THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED - WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, - MERCHANTABLITY OR NON-INFRINGEMENT. + Permission to use, copy, modify, and/or distribute this software for any + purpose with or without fee is hereby granted. - See the Apache Version 2.0 License for specific language governing permissions - and limitations under the License. - ***************************************************************************** */ - /* global Reflect, Promise */ + THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH + REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY + AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, + INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM + LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR + OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR + PERFORMANCE OF THIS SOFTWARE. + ***************************************************************************** */ + /* global Reflect, Promise */ - var extendStatics$j = function(d, b) { - extendStatics$j = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) { if (b.hasOwnProperty(p)) { d[p] = b[p]; } } }; - return extendStatics$j(d, b); - }; + var extendStatics$1 = function(d, b) { + extendStatics$1 = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) { if (b.hasOwnProperty(p)) { d[p] = b[p]; } } }; + return extendStatics$1(d, b); + }; - function __extends$j(d, b) { - extendStatics$j(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - } - - var PlaneGeometry = /** @class */ (function (_super) { - __extends$j(PlaneGeometry, _super); - function PlaneGeometry(width, height, segWidth, segHeight) { - if (width === void 0) { width = 100; } - if (height === void 0) { height = 100; } - if (segWidth === void 0) { segWidth = 10; } - if (segHeight === void 0) { segHeight = 10; } - var _this = _super.call(this) || this; - _this.segWidth = segWidth; - _this.segHeight = segHeight; - _this.width = width; - _this.height = height; - _this.build(); - return _this; - } - /** - * Refreshes plane coordinates - * @private - */ - PlaneGeometry.prototype.build = function () { - var total = this.segWidth * this.segHeight; - var verts = []; - var uvs = []; - var indices = []; - var segmentsX = this.segWidth - 1; - var segmentsY = this.segHeight - 1; - var sizeX = (this.width) / segmentsX; - var sizeY = (this.height) / segmentsY; - for (var i = 0; i < total; i++) { - var x = (i % this.segWidth); - var y = ((i / this.segWidth) | 0); - verts.push(x * sizeX, y * sizeY); - uvs.push(x / segmentsX, y / segmentsY); - } - var totalSub = segmentsX * segmentsY; - for (var i = 0; i < totalSub; i++) { - var xpos = i % segmentsX; - var ypos = (i / segmentsX) | 0; - var value = (ypos * this.segWidth) + xpos; - var value2 = (ypos * this.segWidth) + xpos + 1; - var value3 = ((ypos + 1) * this.segWidth) + xpos; - var value4 = ((ypos + 1) * this.segWidth) + xpos + 1; - indices.push(value, value2, value3, value2, value4, value3); - } - this.buffers[0].data = new Float32Array(verts); - this.buffers[1].data = new Float32Array(uvs); - this.indexBuffer.data = new Uint16Array(indices); - // ensure that the changes are uploaded - this.buffers[0].update(); - this.buffers[1].update(); - this.indexBuffer.update(); - }; - return PlaneGeometry; - }(MeshGeometry)); - - /** - * RopeGeometry allows you to draw a geometry across several points and then manipulate these points. - * - * ```js - * for (let i = 0; i < 20; i++) { - * points.push(new PIXI.Point(i * 50, 0)); - * }; - * const rope = new PIXI.RopeGeometry(100, points); - * ``` - * - * @class - * @extends PIXI.MeshGeometry - * @memberof PIXI - * - */ - var RopeGeometry = /** @class */ (function (_super) { - __extends$j(RopeGeometry, _super); - /** - * @param {number} [width=200] - The width (i.e., thickness) of the rope. - * @param {PIXI.Point[]} [points] - An array of {@link PIXI.Point} objects to construct this rope. - * @param {number} [textureScale=0] - By default the rope texture will be stretched to match - * rope length. If textureScale is positive this value will be treated as a scaling - * factor and the texture will preserve its aspect ratio instead. To create a tiling rope - * set baseTexture.wrapMode to {@link PIXI.WRAP_MODES.REPEAT} and use a power of two texture, - * then set textureScale=1 to keep the original texture pixel size. - * In order to reduce alpha channel artifacts provide a larger texture and downsample - - * i.e. set textureScale=0.5 to scale it down twice. - */ - function RopeGeometry(width, points, textureScale) { - if (width === void 0) { width = 200; } - if (textureScale === void 0) { textureScale = 0; } - var _this = _super.call(this, new Float32Array(points.length * 4), new Float32Array(points.length * 4), new Uint16Array((points.length - 1) * 6)) || this; - /** - * An array of points that determine the rope - * @member {PIXI.Point[]} - */ - _this.points = points; - /** - * The width (i.e., thickness) of the rope. - * @member {number} - * @readOnly - */ - _this._width = width; - /** - * Rope texture scale, if zero then the rope texture is stretched. - * @member {number} - * @readOnly - */ - _this.textureScale = textureScale; - _this.build(); - return _this; - } - Object.defineProperty(RopeGeometry.prototype, "width", { - /** - * The width (i.e., thickness) of the rope. - * @member {number} - * @readOnly - */ - get: function () { - return this._width; - }, - enumerable: false, - configurable: true - }); - /** - * Refreshes Rope indices and uvs - * @private - */ - RopeGeometry.prototype.build = function () { - var points = this.points; - if (!points) - { return; } - var vertexBuffer = this.getBuffer('aVertexPosition'); - var uvBuffer = this.getBuffer('aTextureCoord'); - var indexBuffer = this.getIndex(); - // if too little points, or texture hasn't got UVs set yet just move on. - if (points.length < 1) { - return; - } - // if the number of points has changed we will need to recreate the arraybuffers - if (vertexBuffer.data.length / 4 !== points.length) { - vertexBuffer.data = new Float32Array(points.length * 4); - uvBuffer.data = new Float32Array(points.length * 4); - indexBuffer.data = new Uint16Array((points.length - 1) * 6); - } - var uvs = uvBuffer.data; - var indices = indexBuffer.data; - uvs[0] = 0; - uvs[1] = 0; - uvs[2] = 0; - uvs[3] = 1; - var amount = 0; - var prev = points[0]; - var textureWidth = this._width * this.textureScale; - var total = points.length; // - 1; - for (var i = 0; i < total; i++) { - // time to do some smart drawing! - var index = i * 4; - if (this.textureScale > 0) { - // calculate pixel distance from previous point - var dx = prev.x - points[i].x; - var dy = prev.y - points[i].y; - var distance = Math.sqrt((dx * dx) + (dy * dy)); - prev = points[i]; - amount += distance / textureWidth; - } - else { - // stretch texture - amount = i / (total - 1); - } - uvs[index] = amount; - uvs[index + 1] = 0; - uvs[index + 2] = amount; - uvs[index + 3] = 1; - } - var indexCount = 0; - for (var i = 0; i < total - 1; i++) { - var index = i * 2; - indices[indexCount++] = index; - indices[indexCount++] = index + 1; - indices[indexCount++] = index + 2; - indices[indexCount++] = index + 2; - indices[indexCount++] = index + 1; - indices[indexCount++] = index + 3; - } - // ensure that the changes are uploaded - uvBuffer.update(); - indexBuffer.update(); - this.updateVertices(); - }; - /** - * refreshes vertices of Rope mesh - */ - RopeGeometry.prototype.updateVertices = function () { - var points = this.points; - if (points.length < 1) { - return; - } - var lastPoint = points[0]; - var nextPoint; - var perpX = 0; - var perpY = 0; - var vertices = this.buffers[0].data; - var total = points.length; - for (var i = 0; i < total; i++) { - var point = points[i]; - var index = i * 4; - if (i < points.length - 1) { - nextPoint = points[i + 1]; - } - else { - nextPoint = point; - } - perpY = -(nextPoint.x - lastPoint.x); - perpX = nextPoint.y - lastPoint.y; - var perpLength = Math.sqrt((perpX * perpX) + (perpY * perpY)); - var num = this.textureScale > 0 ? this.textureScale * this._width / 2 : this._width / 2; - perpX /= perpLength; - perpY /= perpLength; - perpX *= num; - perpY *= num; - vertices[index] = point.x + perpX; - vertices[index + 1] = point.y + perpY; - vertices[index + 2] = point.x - perpX; - vertices[index + 3] = point.y - perpY; - lastPoint = point; - } - this.buffers[0].update(); - }; - RopeGeometry.prototype.update = function () { - if (this.textureScale > 0) { - this.build(); // we need to update UVs - } - else { - this.updateVertices(); - } - }; - return RopeGeometry; - }(MeshGeometry)); - - /** - * The rope allows you to draw a texture across several points and then manipulate these points - * - *```js - * for (let i = 0; i < 20; i++) { - * points.push(new PIXI.Point(i * 50, 0)); - * }; - * let rope = new PIXI.SimpleRope(PIXI.Texture.from("snake.png"), points); - * ``` - * - * @class - * @extends PIXI.Mesh - * @memberof PIXI - * - */ - var SimpleRope = /** @class */ (function (_super) { - __extends$j(SimpleRope, _super); - /** - * @param {PIXI.Texture} texture - The texture to use on the rope. - * @param {PIXI.Point[]} points - An array of {@link PIXI.Point} objects to construct this rope. - * @param {number} [textureScale=0] - Optional. Positive values scale rope texture - * keeping its aspect ratio. You can reduce alpha channel artifacts by providing a larger texture - * and downsampling here. If set to zero, texture will be streched instead. - */ - function SimpleRope(texture, points, textureScale) { - if (textureScale === void 0) { textureScale = 0; } - var _this = this; - var ropeGeometry = new RopeGeometry(texture.height, points, textureScale); - var meshMaterial = new MeshMaterial(texture); - if (textureScale > 0) { - // attempt to set UV wrapping, will fail on non-power of two textures - texture.baseTexture.wrapMode = exports.WRAP_MODES.REPEAT; - } - _this = _super.call(this, ropeGeometry, meshMaterial) || this; - /** - * re-calculate vertices by rope points each frame - * - * @member {boolean} - */ - _this.autoUpdate = true; - return _this; - } - SimpleRope.prototype._render = function (renderer) { - var geometry = this.geometry; - if (this.autoUpdate || geometry._width !== this.shader.texture.height) { - geometry._width = this.shader.texture.height; - geometry.update(); - } - _super.prototype._render.call(this, renderer); - }; - return SimpleRope; - }(Mesh)); - - /** - * The SimplePlane allows you to draw a texture across several points and then manipulate these points - * - *```js - * for (let i = 0; i < 20; i++) { - * points.push(new PIXI.Point(i * 50, 0)); - * }; - * let SimplePlane = new PIXI.SimplePlane(PIXI.Texture.from("snake.png"), points); - * ``` - * - * @class - * @extends PIXI.Mesh - * @memberof PIXI - * - */ - var SimplePlane = /** @class */ (function (_super) { - __extends$j(SimplePlane, _super); - /** - * @param {PIXI.Texture} texture - The texture to use on the SimplePlane. - * @param {number} verticesX - The number of vertices in the x-axis - * @param {number} verticesY - The number of vertices in the y-axis - */ - function SimplePlane(texture, verticesX, verticesY) { - var _this = this; - var planeGeometry = new PlaneGeometry(texture.width, texture.height, verticesX, verticesY); - var meshMaterial = new MeshMaterial(Texture.WHITE); - _this = _super.call(this, planeGeometry, meshMaterial) || this; - // lets call the setter to ensure all necessary updates are performed - _this.texture = texture; - return _this; - } - /** - * Method used for overrides, to do something in case texture frame was changed. - * Meshes based on plane can override it and change more details based on texture. - */ - SimplePlane.prototype.textureUpdated = function () { - this._textureID = this.shader.texture._updateID; - var geometry = this.geometry; - geometry.width = this.shader.texture.width; - geometry.height = this.shader.texture.height; - geometry.build(); - }; - Object.defineProperty(SimplePlane.prototype, "texture", { - get: function () { - return this.shader.texture; - }, - set: function (value) { - // Track texture same way sprite does. - // For generated meshes like NineSlicePlane it can change the geometry. - // Unfortunately, this method might not work if you directly change texture in material. - if (this.shader.texture === value) { - return; - } - this.shader.texture = value; - this._textureID = -1; - if (value.baseTexture.valid) { - this.textureUpdated(); - } - else { - value.once('update', this.textureUpdated, this); - } - }, - enumerable: false, - configurable: true - }); - SimplePlane.prototype._render = function (renderer) { - if (this._textureID !== this.shader.texture._updateID) { - this.textureUpdated(); - } - _super.prototype._render.call(this, renderer); - }; - return SimplePlane; - }(Mesh)); - - /** - * The Simple Mesh class mimics Mesh in PixiJS v4, providing easy-to-use constructor arguments. - * For more robust customization, use {@link PIXI.Mesh}. - * - * @class - * @extends PIXI.Mesh - * @memberof PIXI - */ - var SimpleMesh = /** @class */ (function (_super) { - __extends$j(SimpleMesh, _super); - /** - * @param {PIXI.Texture} [texture=Texture.EMPTY] - The texture to use - * @param {Float32Array} [vertices] - if you want to specify the vertices - * @param {Float32Array} [uvs] - if you want to specify the uvs - * @param {Uint16Array} [indices] - if you want to specify the indices - * @param {number} [drawMode] - the drawMode, can be any of the Mesh.DRAW_MODES consts - */ - function SimpleMesh(texture, vertices, uvs, indices, drawMode) { - if (texture === void 0) { texture = Texture.EMPTY; } - var _this = this; - var geometry = new MeshGeometry(vertices, uvs, indices); - geometry.getBuffer('aVertexPosition').static = false; - var meshMaterial = new MeshMaterial(texture); - _this = _super.call(this, geometry, meshMaterial, null, drawMode) || this; - /** - * upload vertices buffer each frame - * @member {boolean} - */ - _this.autoUpdate = true; - return _this; - } - Object.defineProperty(SimpleMesh.prototype, "vertices", { - /** - * Collection of vertices data. - * @member {Float32Array} - */ - get: function () { - return this.geometry.getBuffer('aVertexPosition').data; - }, - set: function (value) { - this.geometry.getBuffer('aVertexPosition').data = value; - }, - enumerable: false, - configurable: true - }); - SimpleMesh.prototype._render = function (renderer) { - if (this.autoUpdate) { - this.geometry.getBuffer('aVertexPosition').update(); - } - _super.prototype._render.call(this, renderer); - }; - return SimpleMesh; - }(Mesh)); - - var DEFAULT_BORDER_SIZE = 10; - /** - * The NineSlicePlane allows you to stretch a texture using 9-slice scaling. The corners will remain unscaled (useful - * for buttons with rounded corners for example) and the other areas will be scaled horizontally and or vertically - * - *```js - * let Plane9 = new PIXI.NineSlicePlane(PIXI.Texture.from('BoxWithRoundedCorners.png'), 15, 15, 15, 15); - * ``` - *
-	 *      A                          B
-	 *    +---+----------------------+---+
-	 *  C | 1 |          2           | 3 |
-	 *    +---+----------------------+---+
-	 *    |   |                      |   |
-	 *    | 4 |          5           | 6 |
-	 *    |   |                      |   |
-	 *    +---+----------------------+---+
-	 *  D | 7 |          8           | 9 |
-	 *    +---+----------------------+---+
-
-	 *  When changing this objects width and/or height:
-	 *     areas 1 3 7 and 9 will remain unscaled.
-	 *     areas 2 and 8 will be stretched horizontally
-	 *     areas 4 and 6 will be stretched vertically
-	 *     area 5 will be stretched both horizontally and vertically
-	 * 
- * - * @class - * @extends PIXI.SimplePlane - * @memberof PIXI - * - */ - var NineSlicePlane = /** @class */ (function (_super) { - __extends$j(NineSlicePlane, _super); - /** - * @param {PIXI.Texture} texture - The texture to use on the NineSlicePlane. - * @param {number} [leftWidth=10] - size of the left vertical bar (A) - * @param {number} [topHeight=10] - size of the top horizontal bar (C) - * @param {number} [rightWidth=10] - size of the right vertical bar (B) - * @param {number} [bottomHeight=10] - size of the bottom horizontal bar (D) - */ - function NineSlicePlane(texture, leftWidth, topHeight, rightWidth, bottomHeight) { - if (leftWidth === void 0) { leftWidth = DEFAULT_BORDER_SIZE; } - if (topHeight === void 0) { topHeight = DEFAULT_BORDER_SIZE; } - if (rightWidth === void 0) { rightWidth = DEFAULT_BORDER_SIZE; } - if (bottomHeight === void 0) { bottomHeight = DEFAULT_BORDER_SIZE; } - var _this = _super.call(this, Texture.WHITE, 4, 4) || this; - _this._origWidth = texture.orig.width; - _this._origHeight = texture.orig.height; - /** - * The width of the NineSlicePlane, setting this will actually modify the vertices and UV's of this plane - * - * @member {number} - * @override - */ - _this._width = _this._origWidth; - /** - * The height of the NineSlicePlane, setting this will actually modify the vertices and UV's of this plane - * - * @member {number} - * @override - */ - _this._height = _this._origHeight; - /** - * The width of the left column (a) - * - * @member {number} - * @private - */ - _this._leftWidth = leftWidth; - /** - * The width of the right column (b) - * - * @member {number} - * @private - */ - _this._rightWidth = rightWidth; - /** - * The height of the top row (c) - * - * @member {number} - * @private - */ - _this._topHeight = topHeight; - /** - * The height of the bottom row (d) - * - * @member {number} - * @private - */ - _this._bottomHeight = bottomHeight; - // lets call the setter to ensure all necessary updates are performed - _this.texture = texture; - return _this; - } - NineSlicePlane.prototype.textureUpdated = function () { - this._textureID = this.shader.texture._updateID; - this._refresh(); - }; - Object.defineProperty(NineSlicePlane.prototype, "vertices", { - get: function () { - return this.geometry.getBuffer('aVertexPosition').data; - }, - set: function (value) { - this.geometry.getBuffer('aVertexPosition').data = value; - }, - enumerable: false, - configurable: true - }); - /** - * Updates the horizontal vertices. - * - */ - NineSlicePlane.prototype.updateHorizontalVertices = function () { - var vertices = this.vertices; - var scale = this._getMinScale(); - vertices[9] = vertices[11] = vertices[13] = vertices[15] = this._topHeight * scale; - vertices[17] = vertices[19] = vertices[21] = vertices[23] = this._height - (this._bottomHeight * scale); - vertices[25] = vertices[27] = vertices[29] = vertices[31] = this._height; - }; - /** - * Updates the vertical vertices. - * - */ - NineSlicePlane.prototype.updateVerticalVertices = function () { - var vertices = this.vertices; - var scale = this._getMinScale(); - vertices[2] = vertices[10] = vertices[18] = vertices[26] = this._leftWidth * scale; - vertices[4] = vertices[12] = vertices[20] = vertices[28] = this._width - (this._rightWidth * scale); - vertices[6] = vertices[14] = vertices[22] = vertices[30] = this._width; - }; - /** - * Returns the smaller of a set of vertical and horizontal scale of nine slice corners. - * - * @return {number} Smaller number of vertical and horizontal scale. - * @private - */ - NineSlicePlane.prototype._getMinScale = function () { - var w = this._leftWidth + this._rightWidth; - var scaleW = this._width > w ? 1.0 : this._width / w; - var h = this._topHeight + this._bottomHeight; - var scaleH = this._height > h ? 1.0 : this._height / h; - var scale = Math.min(scaleW, scaleH); - return scale; - }; - Object.defineProperty(NineSlicePlane.prototype, "width", { - /** - * The width of the NineSlicePlane, setting this will actually modify the vertices and UV's of this plane - * - * @member {number} - */ - get: function () { - return this._width; - }, - set: function (value) { - this._width = value; - this._refresh(); - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(NineSlicePlane.prototype, "height", { - /** - * The height of the NineSlicePlane, setting this will actually modify the vertices and UV's of this plane - * - * @member {number} - */ - get: function () { - return this._height; - }, - set: function (value) { - this._height = value; - this._refresh(); - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(NineSlicePlane.prototype, "leftWidth", { - /** - * The width of the left column - * - * @member {number} - */ - get: function () { - return this._leftWidth; - }, - set: function (value) { - this._leftWidth = value; - this._refresh(); - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(NineSlicePlane.prototype, "rightWidth", { - /** - * The width of the right column - * - * @member {number} - */ - get: function () { - return this._rightWidth; - }, - set: function (value) { - this._rightWidth = value; - this._refresh(); - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(NineSlicePlane.prototype, "topHeight", { - /** - * The height of the top row - * - * @member {number} - */ - get: function () { - return this._topHeight; - }, - set: function (value) { - this._topHeight = value; - this._refresh(); - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(NineSlicePlane.prototype, "bottomHeight", { - /** - * The height of the bottom row - * - * @member {number} - */ - get: function () { - return this._bottomHeight; - }, - set: function (value) { - this._bottomHeight = value; - this._refresh(); - }, - enumerable: false, - configurable: true - }); - /** - * Refreshes NineSlicePlane coords. All of them. - */ - NineSlicePlane.prototype._refresh = function () { - var texture = this.texture; - var uvs = this.geometry.buffers[1].data; - this._origWidth = texture.orig.width; - this._origHeight = texture.orig.height; - var _uvw = 1.0 / this._origWidth; - var _uvh = 1.0 / this._origHeight; - uvs[0] = uvs[8] = uvs[16] = uvs[24] = 0; - uvs[1] = uvs[3] = uvs[5] = uvs[7] = 0; - uvs[6] = uvs[14] = uvs[22] = uvs[30] = 1; - uvs[25] = uvs[27] = uvs[29] = uvs[31] = 1; - uvs[2] = uvs[10] = uvs[18] = uvs[26] = _uvw * this._leftWidth; - uvs[4] = uvs[12] = uvs[20] = uvs[28] = 1 - (_uvw * this._rightWidth); - uvs[9] = uvs[11] = uvs[13] = uvs[15] = _uvh * this._topHeight; - uvs[17] = uvs[19] = uvs[21] = uvs[23] = 1 - (_uvh * this._bottomHeight); - this.updateHorizontalVertices(); - this.updateVerticalVertices(); - this.geometry.buffers[0].update(); - this.geometry.buffers[1].update(); - }; - return NineSlicePlane; - }(SimplePlane)); - - /*! - * @pixi/sprite-animated - v5.3.3 - * Compiled Tue, 04 Aug 2020 16:23:09 UTC - * - * @pixi/sprite-animated is licensed under the MIT License. - * http://www.opensource.org/licenses/mit-license - */ - - /*! ***************************************************************************** - Copyright (c) Microsoft Corporation. All rights reserved. - Licensed under the Apache License, Version 2.0 (the "License"); you may not use - this file except in compliance with the License. You may obtain a copy of the - License at http://www.apache.org/licenses/LICENSE-2.0 + function __extends$1(d, b) { + extendStatics$1(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + } + + /** + * @memberof PIXI + */ + var PlaneGeometry = /** @class */ (function (_super) { + __extends$1(PlaneGeometry, _super); + /** + * @param width - The width of the plane. + * @param height - The height of the plane. + * @param segWidth - Number of horizontal segments. + * @param segHeight - Number of vertical segments. + */ + function PlaneGeometry(width, height, segWidth, segHeight) { + if (width === void 0) { width = 100; } + if (height === void 0) { height = 100; } + if (segWidth === void 0) { segWidth = 10; } + if (segHeight === void 0) { segHeight = 10; } + var _this = _super.call(this) || this; + _this.segWidth = segWidth; + _this.segHeight = segHeight; + _this.width = width; + _this.height = height; + _this.build(); + return _this; + } + /** + * Refreshes plane coordinates + * @private + */ + PlaneGeometry.prototype.build = function () { + var total = this.segWidth * this.segHeight; + var verts = []; + var uvs = []; + var indices = []; + var segmentsX = this.segWidth - 1; + var segmentsY = this.segHeight - 1; + var sizeX = (this.width) / segmentsX; + var sizeY = (this.height) / segmentsY; + for (var i = 0; i < total; i++) { + var x = (i % this.segWidth); + var y = ((i / this.segWidth) | 0); + verts.push(x * sizeX, y * sizeY); + uvs.push(x / segmentsX, y / segmentsY); + } + var totalSub = segmentsX * segmentsY; + for (var i = 0; i < totalSub; i++) { + var xpos = i % segmentsX; + var ypos = (i / segmentsX) | 0; + var value = (ypos * this.segWidth) + xpos; + var value2 = (ypos * this.segWidth) + xpos + 1; + var value3 = ((ypos + 1) * this.segWidth) + xpos; + var value4 = ((ypos + 1) * this.segWidth) + xpos + 1; + indices.push(value, value2, value3, value2, value4, value3); + } + this.buffers[0].data = new Float32Array(verts); + this.buffers[1].data = new Float32Array(uvs); + this.indexBuffer.data = new Uint16Array(indices); + // ensure that the changes are uploaded + this.buffers[0].update(); + this.buffers[1].update(); + this.indexBuffer.update(); + }; + return PlaneGeometry; + }(MeshGeometry)); + + /** + * RopeGeometry allows you to draw a geometry across several points and then manipulate these points. + * + * ```js + * for (let i = 0; i < 20; i++) { + * points.push(new PIXI.Point(i * 50, 0)); + * }; + * const rope = new PIXI.RopeGeometry(100, points); + * ``` + * @memberof PIXI + */ + var RopeGeometry = /** @class */ (function (_super) { + __extends$1(RopeGeometry, _super); + /** + * @param width - The width (i.e., thickness) of the rope. + * @param points - An array of {@link PIXI.Point} objects to construct this rope. + * @param textureScale - By default the rope texture will be stretched to match + * rope length. If textureScale is positive this value will be treated as a scaling + * factor and the texture will preserve its aspect ratio instead. To create a tiling rope + * set baseTexture.wrapMode to {@link PIXI.WRAP_MODES.REPEAT} and use a power of two texture, + * then set textureScale=1 to keep the original texture pixel size. + * In order to reduce alpha channel artifacts provide a larger texture and downsample - + * i.e. set textureScale=0.5 to scale it down twice. + */ + function RopeGeometry(width, points, textureScale) { + if (width === void 0) { width = 200; } + if (textureScale === void 0) { textureScale = 0; } + var _this = _super.call(this, new Float32Array(points.length * 4), new Float32Array(points.length * 4), new Uint16Array((points.length - 1) * 6)) || this; + _this.points = points; + _this._width = width; + _this.textureScale = textureScale; + _this.build(); + return _this; + } + Object.defineProperty(RopeGeometry.prototype, "width", { + /** + * The width (i.e., thickness) of the rope. + * @readonly + */ + get: function () { + return this._width; + }, + enumerable: false, + configurable: true + }); + /** Refreshes Rope indices and uvs */ + RopeGeometry.prototype.build = function () { + var points = this.points; + if (!points) + { return; } + var vertexBuffer = this.getBuffer('aVertexPosition'); + var uvBuffer = this.getBuffer('aTextureCoord'); + var indexBuffer = this.getIndex(); + // if too little points, or texture hasn't got UVs set yet just move on. + if (points.length < 1) { + return; + } + // if the number of points has changed we will need to recreate the arraybuffers + if (vertexBuffer.data.length / 4 !== points.length) { + vertexBuffer.data = new Float32Array(points.length * 4); + uvBuffer.data = new Float32Array(points.length * 4); + indexBuffer.data = new Uint16Array((points.length - 1) * 6); + } + var uvs = uvBuffer.data; + var indices = indexBuffer.data; + uvs[0] = 0; + uvs[1] = 0; + uvs[2] = 0; + uvs[3] = 1; + var amount = 0; + var prev = points[0]; + var textureWidth = this._width * this.textureScale; + var total = points.length; // - 1; + for (var i = 0; i < total; i++) { + // time to do some smart drawing! + var index = i * 4; + if (this.textureScale > 0) { + // calculate pixel distance from previous point + var dx = prev.x - points[i].x; + var dy = prev.y - points[i].y; + var distance = Math.sqrt((dx * dx) + (dy * dy)); + prev = points[i]; + amount += distance / textureWidth; + } + else { + // stretch texture + amount = i / (total - 1); + } + uvs[index] = amount; + uvs[index + 1] = 0; + uvs[index + 2] = amount; + uvs[index + 3] = 1; + } + var indexCount = 0; + for (var i = 0; i < total - 1; i++) { + var index = i * 2; + indices[indexCount++] = index; + indices[indexCount++] = index + 1; + indices[indexCount++] = index + 2; + indices[indexCount++] = index + 2; + indices[indexCount++] = index + 1; + indices[indexCount++] = index + 3; + } + // ensure that the changes are uploaded + uvBuffer.update(); + indexBuffer.update(); + this.updateVertices(); + }; + /** refreshes vertices of Rope mesh */ + RopeGeometry.prototype.updateVertices = function () { + var points = this.points; + if (points.length < 1) { + return; + } + var lastPoint = points[0]; + var nextPoint; + var perpX = 0; + var perpY = 0; + var vertices = this.buffers[0].data; + var total = points.length; + for (var i = 0; i < total; i++) { + var point = points[i]; + var index = i * 4; + if (i < points.length - 1) { + nextPoint = points[i + 1]; + } + else { + nextPoint = point; + } + perpY = -(nextPoint.x - lastPoint.x); + perpX = nextPoint.y - lastPoint.y; + var perpLength = Math.sqrt((perpX * perpX) + (perpY * perpY)); + var num = this.textureScale > 0 ? this.textureScale * this._width / 2 : this._width / 2; + perpX /= perpLength; + perpY /= perpLength; + perpX *= num; + perpY *= num; + vertices[index] = point.x + perpX; + vertices[index + 1] = point.y + perpY; + vertices[index + 2] = point.x - perpX; + vertices[index + 3] = point.y - perpY; + lastPoint = point; + } + this.buffers[0].update(); + }; + RopeGeometry.prototype.update = function () { + if (this.textureScale > 0) { + this.build(); // we need to update UVs + } + else { + this.updateVertices(); + } + }; + return RopeGeometry; + }(MeshGeometry)); + + /** + * The rope allows you to draw a texture across several points and then manipulate these points + * + *```js + * for (let i = 0; i < 20; i++) { + * points.push(new PIXI.Point(i * 50, 0)); + * }; + * let rope = new PIXI.SimpleRope(PIXI.Texture.from("snake.png"), points); + * ``` + * @memberof PIXI + */ + var SimpleRope = /** @class */ (function (_super) { + __extends$1(SimpleRope, _super); + /** + * @param texture - The texture to use on the rope. + * @param points - An array of {@link PIXI.Point} objects to construct this rope. + * @param {number} textureScale - Optional. Positive values scale rope texture + * keeping its aspect ratio. You can reduce alpha channel artifacts by providing a larger texture + * and downsampling here. If set to zero, texture will be stretched instead. + */ + function SimpleRope(texture, points, textureScale) { + if (textureScale === void 0) { textureScale = 0; } + var _this = this; + var ropeGeometry = new RopeGeometry(texture.height, points, textureScale); + var meshMaterial = new MeshMaterial(texture); + if (textureScale > 0) { + // attempt to set UV wrapping, will fail on non-power of two textures + texture.baseTexture.wrapMode = exports.WRAP_MODES.REPEAT; + } + _this = _super.call(this, ropeGeometry, meshMaterial) || this; + /** + * re-calculate vertices by rope points each frame + * @member {boolean} + */ + _this.autoUpdate = true; + return _this; + } + SimpleRope.prototype._render = function (renderer) { + var geometry = this.geometry; + if (this.autoUpdate || geometry._width !== this.shader.texture.height) { + geometry._width = this.shader.texture.height; + geometry.update(); + } + _super.prototype._render.call(this, renderer); + }; + return SimpleRope; + }(Mesh)); + + /** + * The SimplePlane allows you to draw a texture across several points and then manipulate these points + * + *```js + * for (let i = 0; i < 20; i++) { + * points.push(new PIXI.Point(i * 50, 0)); + * }; + * let SimplePlane = new PIXI.SimplePlane(PIXI.Texture.from("snake.png"), points); + * ``` + * @memberof PIXI + */ + var SimplePlane = /** @class */ (function (_super) { + __extends$1(SimplePlane, _super); + /** + * @param texture - The texture to use on the SimplePlane. + * @param verticesX - The number of vertices in the x-axis + * @param verticesY - The number of vertices in the y-axis + */ + function SimplePlane(texture, verticesX, verticesY) { + var _this = this; + var planeGeometry = new PlaneGeometry(texture.width, texture.height, verticesX, verticesY); + var meshMaterial = new MeshMaterial(Texture.WHITE); + _this = _super.call(this, planeGeometry, meshMaterial) || this; + // lets call the setter to ensure all necessary updates are performed + _this.texture = texture; + _this.autoResize = true; + return _this; + } + /** + * Method used for overrides, to do something in case texture frame was changed. + * Meshes based on plane can override it and change more details based on texture. + */ + SimplePlane.prototype.textureUpdated = function () { + this._textureID = this.shader.texture._updateID; + var geometry = this.geometry; + var _a = this.shader.texture, width = _a.width, height = _a.height; + if (this.autoResize && (geometry.width !== width || geometry.height !== height)) { + geometry.width = this.shader.texture.width; + geometry.height = this.shader.texture.height; + geometry.build(); + } + }; + Object.defineProperty(SimplePlane.prototype, "texture", { + get: function () { + return this.shader.texture; + }, + set: function (value) { + // Track texture same way sprite does. + // For generated meshes like NineSlicePlane it can change the geometry. + // Unfortunately, this method might not work if you directly change texture in material. + if (this.shader.texture === value) { + return; + } + this.shader.texture = value; + this._textureID = -1; + if (value.baseTexture.valid) { + this.textureUpdated(); + } + else { + value.once('update', this.textureUpdated, this); + } + }, + enumerable: false, + configurable: true + }); + SimplePlane.prototype._render = function (renderer) { + if (this._textureID !== this.shader.texture._updateID) { + this.textureUpdated(); + } + _super.prototype._render.call(this, renderer); + }; + SimplePlane.prototype.destroy = function (options) { + this.shader.texture.off('update', this.textureUpdated, this); + _super.prototype.destroy.call(this, options); + }; + return SimplePlane; + }(Mesh)); + + /** + * The Simple Mesh class mimics Mesh in PixiJS v4, providing easy-to-use constructor arguments. + * For more robust customization, use {@link PIXI.Mesh}. + * @memberof PIXI + */ + var SimpleMesh = /** @class */ (function (_super) { + __extends$1(SimpleMesh, _super); + /** + * @param texture - The texture to use + * @param {Float32Array} [vertices] - if you want to specify the vertices + * @param {Float32Array} [uvs] - if you want to specify the uvs + * @param {Uint16Array} [indices] - if you want to specify the indices + * @param drawMode - the drawMode, can be any of the Mesh.DRAW_MODES consts + */ + function SimpleMesh(texture, vertices, uvs, indices, drawMode) { + if (texture === void 0) { texture = Texture.EMPTY; } + var _this = this; + var geometry = new MeshGeometry(vertices, uvs, indices); + geometry.getBuffer('aVertexPosition').static = false; + var meshMaterial = new MeshMaterial(texture); + _this = _super.call(this, geometry, meshMaterial, null, drawMode) || this; + _this.autoUpdate = true; + return _this; + } + Object.defineProperty(SimpleMesh.prototype, "vertices", { + /** + * Collection of vertices data. + * @type {Float32Array} + */ + get: function () { + return this.geometry.getBuffer('aVertexPosition').data; + }, + set: function (value) { + this.geometry.getBuffer('aVertexPosition').data = value; + }, + enumerable: false, + configurable: true + }); + SimpleMesh.prototype._render = function (renderer) { + if (this.autoUpdate) { + this.geometry.getBuffer('aVertexPosition').update(); + } + _super.prototype._render.call(this, renderer); + }; + return SimpleMesh; + }(Mesh)); + + var DEFAULT_BORDER_SIZE = 10; + /** + * The NineSlicePlane allows you to stretch a texture using 9-slice scaling. The corners will remain unscaled (useful + * for buttons with rounded corners for example) and the other areas will be scaled horizontally and or vertically + * + *```js + * let Plane9 = new PIXI.NineSlicePlane(PIXI.Texture.from('BoxWithRoundedCorners.png'), 15, 15, 15, 15); + * ``` + *
+   *      A                          B
+   *    +---+----------------------+---+
+   *  C | 1 |          2           | 3 |
+   *    +---+----------------------+---+
+   *    |   |                      |   |
+   *    | 4 |          5           | 6 |
+   *    |   |                      |   |
+   *    +---+----------------------+---+
+   *  D | 7 |          8           | 9 |
+   *    +---+----------------------+---+
+   *  When changing this objects width and/or height:
+   *     areas 1 3 7 and 9 will remain unscaled.
+   *     areas 2 and 8 will be stretched horizontally
+   *     areas 4 and 6 will be stretched vertically
+   *     area 5 will be stretched both horizontally and vertically
+   * 
+ * @memberof PIXI + */ + var NineSlicePlane = /** @class */ (function (_super) { + __extends$1(NineSlicePlane, _super); + /** + * @param texture - The texture to use on the NineSlicePlane. + * @param {number} [leftWidth=10] - size of the left vertical bar (A) + * @param {number} [topHeight=10] - size of the top horizontal bar (C) + * @param {number} [rightWidth=10] - size of the right vertical bar (B) + * @param {number} [bottomHeight=10] - size of the bottom horizontal bar (D) + */ + function NineSlicePlane(texture, leftWidth, topHeight, rightWidth, bottomHeight) { + if (leftWidth === void 0) { leftWidth = DEFAULT_BORDER_SIZE; } + if (topHeight === void 0) { topHeight = DEFAULT_BORDER_SIZE; } + if (rightWidth === void 0) { rightWidth = DEFAULT_BORDER_SIZE; } + if (bottomHeight === void 0) { bottomHeight = DEFAULT_BORDER_SIZE; } + var _this = _super.call(this, Texture.WHITE, 4, 4) || this; + _this._origWidth = texture.orig.width; + _this._origHeight = texture.orig.height; + /** The width of the NineSlicePlane, setting this will actually modify the vertices and UV's of this plane. */ + _this._width = _this._origWidth; + /** The height of the NineSlicePlane, setting this will actually modify the vertices and UV's of this plane. */ + _this._height = _this._origHeight; + _this._leftWidth = leftWidth; + _this._rightWidth = rightWidth; + _this._topHeight = topHeight; + _this._bottomHeight = bottomHeight; + // lets call the setter to ensure all necessary updates are performed + _this.texture = texture; + return _this; + } + NineSlicePlane.prototype.textureUpdated = function () { + this._textureID = this.shader.texture._updateID; + this._refresh(); + }; + Object.defineProperty(NineSlicePlane.prototype, "vertices", { + get: function () { + return this.geometry.getBuffer('aVertexPosition').data; + }, + set: function (value) { + this.geometry.getBuffer('aVertexPosition').data = value; + }, + enumerable: false, + configurable: true + }); + /** Updates the horizontal vertices. */ + NineSlicePlane.prototype.updateHorizontalVertices = function () { + var vertices = this.vertices; + var scale = this._getMinScale(); + vertices[9] = vertices[11] = vertices[13] = vertices[15] = this._topHeight * scale; + vertices[17] = vertices[19] = vertices[21] = vertices[23] = this._height - (this._bottomHeight * scale); + vertices[25] = vertices[27] = vertices[29] = vertices[31] = this._height; + }; + /** Updates the vertical vertices. */ + NineSlicePlane.prototype.updateVerticalVertices = function () { + var vertices = this.vertices; + var scale = this._getMinScale(); + vertices[2] = vertices[10] = vertices[18] = vertices[26] = this._leftWidth * scale; + vertices[4] = vertices[12] = vertices[20] = vertices[28] = this._width - (this._rightWidth * scale); + vertices[6] = vertices[14] = vertices[22] = vertices[30] = this._width; + }; + /** + * Returns the smaller of a set of vertical and horizontal scale of nine slice corners. + * @returns Smaller number of vertical and horizontal scale. + */ + NineSlicePlane.prototype._getMinScale = function () { + var w = this._leftWidth + this._rightWidth; + var scaleW = this._width > w ? 1.0 : this._width / w; + var h = this._topHeight + this._bottomHeight; + var scaleH = this._height > h ? 1.0 : this._height / h; + var scale = Math.min(scaleW, scaleH); + return scale; + }; + Object.defineProperty(NineSlicePlane.prototype, "width", { + /** The width of the NineSlicePlane, setting this will actually modify the vertices and UV's of this plane. */ + get: function () { + return this._width; + }, + set: function (value) { + this._width = value; + this._refresh(); + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(NineSlicePlane.prototype, "height", { + /** The height of the NineSlicePlane, setting this will actually modify the vertices and UV's of this plane. */ + get: function () { + return this._height; + }, + set: function (value) { + this._height = value; + this._refresh(); + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(NineSlicePlane.prototype, "leftWidth", { + /** The width of the left column. */ + get: function () { + return this._leftWidth; + }, + set: function (value) { + this._leftWidth = value; + this._refresh(); + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(NineSlicePlane.prototype, "rightWidth", { + /** The width of the right column. */ + get: function () { + return this._rightWidth; + }, + set: function (value) { + this._rightWidth = value; + this._refresh(); + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(NineSlicePlane.prototype, "topHeight", { + /** The height of the top row. */ + get: function () { + return this._topHeight; + }, + set: function (value) { + this._topHeight = value; + this._refresh(); + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(NineSlicePlane.prototype, "bottomHeight", { + /** The height of the bottom row. */ + get: function () { + return this._bottomHeight; + }, + set: function (value) { + this._bottomHeight = value; + this._refresh(); + }, + enumerable: false, + configurable: true + }); + /** Refreshes NineSlicePlane coords. All of them. */ + NineSlicePlane.prototype._refresh = function () { + var texture = this.texture; + var uvs = this.geometry.buffers[1].data; + this._origWidth = texture.orig.width; + this._origHeight = texture.orig.height; + var _uvw = 1.0 / this._origWidth; + var _uvh = 1.0 / this._origHeight; + uvs[0] = uvs[8] = uvs[16] = uvs[24] = 0; + uvs[1] = uvs[3] = uvs[5] = uvs[7] = 0; + uvs[6] = uvs[14] = uvs[22] = uvs[30] = 1; + uvs[25] = uvs[27] = uvs[29] = uvs[31] = 1; + uvs[2] = uvs[10] = uvs[18] = uvs[26] = _uvw * this._leftWidth; + uvs[4] = uvs[12] = uvs[20] = uvs[28] = 1 - (_uvw * this._rightWidth); + uvs[9] = uvs[11] = uvs[13] = uvs[15] = _uvh * this._topHeight; + uvs[17] = uvs[19] = uvs[21] = uvs[23] = 1 - (_uvh * this._bottomHeight); + this.updateHorizontalVertices(); + this.updateVerticalVertices(); + this.geometry.buffers[0].update(); + this.geometry.buffers[1].update(); + }; + return NineSlicePlane; + }(SimplePlane)); + + /*! + * @pixi/sprite-animated - v6.5.3 + * Compiled Fri, 09 Sep 2022 13:55:20 UTC + * + * @pixi/sprite-animated is licensed under the MIT License. + * http://www.opensource.org/licenses/mit-license + */ + + /*! ***************************************************************************** + Copyright (c) Microsoft Corporation. - THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED - WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, - MERCHANTABLITY OR NON-INFRINGEMENT. + Permission to use, copy, modify, and/or distribute this software for any + purpose with or without fee is hereby granted. - See the Apache Version 2.0 License for specific language governing permissions - and limitations under the License. - ***************************************************************************** */ - /* global Reflect, Promise */ + THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH + REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY + AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, + INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM + LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR + OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR + PERFORMANCE OF THIS SOFTWARE. + ***************************************************************************** */ + /* global Reflect, Promise */ - var extendStatics$k = function(d, b) { - extendStatics$k = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) { if (b.hasOwnProperty(p)) { d[p] = b[p]; } } }; - return extendStatics$k(d, b); - }; + var extendStatics = function(d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) { if (b.hasOwnProperty(p)) { d[p] = b[p]; } } }; + return extendStatics(d, b); + }; - function __extends$k(d, b) { - extendStatics$k(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - } - - /** - * An AnimatedSprite is a simple way to display an animation depicted by a list of textures. - * - * ```js - * let alienImages = ["image_sequence_01.png","image_sequence_02.png","image_sequence_03.png","image_sequence_04.png"]; - * let textureArray = []; - * - * for (let i=0; i < 4; i++) - * { - * let texture = PIXI.Texture.from(alienImages[i]); - * textureArray.push(texture); - * }; - * - * let animatedSprite = new PIXI.AnimatedSprite(textureArray); - * ``` - * - * The more efficient and simpler way to create an animated sprite is using a {@link PIXI.Spritesheet} - * containing the animation definitions: - * - * ```js - * PIXI.Loader.shared.add("assets/spritesheet.json").load(setup); - * - * function setup() { - * let sheet = PIXI.Loader.shared.resources["assets/spritesheet.json"].spritesheet; - * animatedSprite = new PIXI.AnimatedSprite(sheet.animations["image_sequence"]); - * ... - * } - * ``` - * - * @class - * @extends PIXI.Sprite - * @memberof PIXI - */ - var AnimatedSprite = /** @class */ (function (_super) { - __extends$k(AnimatedSprite, _super); - /** - * @param {PIXI.Texture[]|PIXI.AnimatedSprite.FrameObject[]} textures - An array of {@link PIXI.Texture} or frame - * objects that make up the animation. - * @param {boolean} [autoUpdate=true] - Whether to use PIXI.Ticker.shared to auto update animation time. - */ - function AnimatedSprite(textures, autoUpdate) { - if (autoUpdate === void 0) { autoUpdate = true; } - var _this = _super.call(this, textures[0] instanceof Texture ? textures[0] : textures[0].texture) || this; - /** - * @type {PIXI.Texture[]} - * @private - */ - _this._textures = null; - /** - * @type {number[]} - * @private - */ - _this._durations = null; - /** - * `true` uses PIXI.Ticker.shared to auto update animation time. - * - * @type {boolean} - * @default true - * @private - */ - _this._autoUpdate = autoUpdate; - /** - * `true` if the instance is currently connected to PIXI.Ticker.shared to auto update animation time. - * - * @type {boolean} - * @default false - * @private - */ - _this._isConnectedToTicker = false; - /** - * The speed that the AnimatedSprite will play at. Higher is faster, lower is slower. - * - * @member {number} - * @default 1 - */ - _this.animationSpeed = 1; - /** - * Whether or not the animate sprite repeats after playing. - * - * @member {boolean} - * @default true - */ - _this.loop = true; - /** - * Update anchor to [Texture's defaultAnchor]{@link PIXI.Texture#defaultAnchor} when frame changes. - * - * Useful with [sprite sheet animations]{@link PIXI.Spritesheet#animations} created with tools. - * Changing anchor for each frame allows to pin sprite origin to certain moving feature - * of the frame (e.g. left foot). - * - * Note: Enabling this will override any previously set `anchor` on each frame change. - * - * @member {boolean} - * @default false - */ - _this.updateAnchor = false; - /** - * User-assigned function to call when an AnimatedSprite finishes playing. - * - * @example - * animation.onComplete = function () { - * // finished! - * }; - * @member {Function} - */ - _this.onComplete = null; - /** - * User-assigned function to call when an AnimatedSprite changes which texture is being rendered. - * - * @example - * animation.onFrameChange = function () { - * // updated! - * }; - * @member {Function} - */ - _this.onFrameChange = null; - /** - * User-assigned function to call when `loop` is true, and an AnimatedSprite is played and - * loops around to start again. - * - * @example - * animation.onLoop = function () { - * // looped! - * }; - * @member {Function} - */ - _this.onLoop = null; - /** - * Elapsed time since animation has been started, used internally to display current texture. - * - * @member {number} - * @private - */ - _this._currentTime = 0; - _this._playing = false; - /** - * The texture index that was displayed last time - * - * @member {number} - * @private - */ - _this._previousFrame = null; - _this.textures = textures; - return _this; - } - /** - * Stops the AnimatedSprite. - * - */ - AnimatedSprite.prototype.stop = function () { - if (!this._playing) { - return; - } - this._playing = false; - if (this._autoUpdate && this._isConnectedToTicker) { - Ticker.shared.remove(this.update, this); - this._isConnectedToTicker = false; - } - }; - /** - * Plays the AnimatedSprite. - * - */ - AnimatedSprite.prototype.play = function () { - if (this._playing) { - return; - } - this._playing = true; - if (this._autoUpdate && !this._isConnectedToTicker) { - Ticker.shared.add(this.update, this, exports.UPDATE_PRIORITY.HIGH); - this._isConnectedToTicker = true; - } - }; - /** - * Stops the AnimatedSprite and goes to a specific frame. - * - * @param {number} frameNumber - Frame index to stop at. - */ - AnimatedSprite.prototype.gotoAndStop = function (frameNumber) { - this.stop(); - var previousFrame = this.currentFrame; - this._currentTime = frameNumber; - if (previousFrame !== this.currentFrame) { - this.updateTexture(); - } - }; - /** - * Goes to a specific frame and begins playing the AnimatedSprite. - * - * @param {number} frameNumber - Frame index to start at. - */ - AnimatedSprite.prototype.gotoAndPlay = function (frameNumber) { - var previousFrame = this.currentFrame; - this._currentTime = frameNumber; - if (previousFrame !== this.currentFrame) { - this.updateTexture(); - } - this.play(); - }; - /** - * Updates the object transform for rendering. - * - * @param {number} deltaTime - Time since last tick. - */ - AnimatedSprite.prototype.update = function (deltaTime) { - var elapsed = this.animationSpeed * deltaTime; - var previousFrame = this.currentFrame; - if (this._durations !== null) { - var lag = this._currentTime % 1 * this._durations[this.currentFrame]; - lag += elapsed / 60 * 1000; - while (lag < 0) { - this._currentTime--; - lag += this._durations[this.currentFrame]; - } - var sign = Math.sign(this.animationSpeed * deltaTime); - this._currentTime = Math.floor(this._currentTime); - while (lag >= this._durations[this.currentFrame]) { - lag -= this._durations[this.currentFrame] * sign; - this._currentTime += sign; - } - this._currentTime += lag / this._durations[this.currentFrame]; - } - else { - this._currentTime += elapsed; - } - if (this._currentTime < 0 && !this.loop) { - this.gotoAndStop(0); - if (this.onComplete) { - this.onComplete(); - } - } - else if (this._currentTime >= this._textures.length && !this.loop) { - this.gotoAndStop(this._textures.length - 1); - if (this.onComplete) { - this.onComplete(); - } - } - else if (previousFrame !== this.currentFrame) { - if (this.loop && this.onLoop) { - if (this.animationSpeed > 0 && this.currentFrame < previousFrame) { - this.onLoop(); - } - else if (this.animationSpeed < 0 && this.currentFrame > previousFrame) { - this.onLoop(); - } - } - this.updateTexture(); - } - }; - /** - * Updates the displayed texture to match the current frame index. - * - * @private - */ - AnimatedSprite.prototype.updateTexture = function () { - var currentFrame = this.currentFrame; - if (this._previousFrame === currentFrame) { - return; - } - this._previousFrame = currentFrame; - this._texture = this._textures[currentFrame]; - this._textureID = -1; - this._textureTrimmedID = -1; - this._cachedTint = 0xFFFFFF; - this.uvs = this._texture._uvs.uvsFloat32; - if (this.updateAnchor) { - this._anchor.copyFrom(this._texture.defaultAnchor); - } - if (this.onFrameChange) { - this.onFrameChange(this.currentFrame); - } - }; - /** - * Stops the AnimatedSprite and destroys it. - * - * @param {object|boolean} [options] - Options parameter. A boolean will act as if all options - * have been set to that value. - * @param {boolean} [options.children=false] - If set to true, all the children will have their destroy - * method called as well. 'options' will be passed on to those calls. - * @param {boolean} [options.texture=false] - Should it destroy the current texture of the sprite as well. - * @param {boolean} [options.baseTexture=false] - Should it destroy the base texture of the sprite as well. - */ - AnimatedSprite.prototype.destroy = function (options) { - this.stop(); - _super.prototype.destroy.call(this, options); - this.onComplete = null; - this.onFrameChange = null; - this.onLoop = null; - }; - /** - * A short hand way of creating an AnimatedSprite from an array of frame ids. - * - * @static - * @param {string[]} frames - The array of frames ids the AnimatedSprite will use as its texture frames. - * @return {PIXI.AnimatedSprite} The new animated sprite with the specified frames. - */ - AnimatedSprite.fromFrames = function (frames) { - var textures = []; - for (var i = 0; i < frames.length; ++i) { - textures.push(Texture.from(frames[i])); - } - return new AnimatedSprite(textures); - }; - /** - * A short hand way of creating an AnimatedSprite from an array of image ids. - * - * @static - * @param {string[]} images - The array of image urls the AnimatedSprite will use as its texture frames. - * @return {PIXI.AnimatedSprite} The new animate sprite with the specified images as frames. - */ - AnimatedSprite.fromImages = function (images) { - var textures = []; - for (var i = 0; i < images.length; ++i) { - textures.push(Texture.from(images[i])); - } - return new AnimatedSprite(textures); - }; - Object.defineProperty(AnimatedSprite.prototype, "totalFrames", { - /** - * The total number of frames in the AnimatedSprite. This is the same as number of textures - * assigned to the AnimatedSprite. - * - * @readonly - * @member {number} - * @default 0 - */ - get: function () { - return this._textures.length; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(AnimatedSprite.prototype, "textures", { - /** - * The array of textures used for this AnimatedSprite. - * - * @member {PIXI.Texture[]} - */ - get: function () { - return this._textures; - }, - set: function (value) { - if (value[0] instanceof Texture) { - this._textures = value; - this._durations = null; - } - else { - this._textures = []; - this._durations = []; - for (var i = 0; i < value.length; i++) { - this._textures.push(value[i].texture); - this._durations.push(value[i].time); - } - } - this._previousFrame = null; - this.gotoAndStop(0); - this.updateTexture(); - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(AnimatedSprite.prototype, "currentFrame", { - /** - * The AnimatedSprites current frame index. - * - * @member {number} - * @readonly - */ - get: function () { - var currentFrame = Math.floor(this._currentTime) % this._textures.length; - if (currentFrame < 0) { - currentFrame += this._textures.length; - } - return currentFrame; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(AnimatedSprite.prototype, "playing", { - /** - * Indicates if the AnimatedSprite is currently playing. - * - * @member {boolean} - * @readonly - */ - get: function () { - return this._playing; - }, - enumerable: false, - configurable: true - }); - Object.defineProperty(AnimatedSprite.prototype, "autoUpdate", { - /** - * Whether to use PIXI.Ticker.shared to auto update animation time - * - * @member {boolean} - */ - get: function () { - return this._autoUpdate; - }, - set: function (value) { - if (value !== this._autoUpdate) { - this._autoUpdate = value; - if (!this._autoUpdate && this._isConnectedToTicker) { - Ticker.shared.remove(this.update, this); - this._isConnectedToTicker = false; - } - else if (this._autoUpdate && !this._isConnectedToTicker && this._playing) { - Ticker.shared.add(this.update, this); - this._isConnectedToTicker = true; - } - } - }, - enumerable: false, - configurable: true - }); - return AnimatedSprite; - }(Sprite)); - - // Install renderer plugins - Renderer.registerPlugin('accessibility', AccessibilityManager); - Renderer.registerPlugin('extract', Extract); - Renderer.registerPlugin('interaction', InteractionManager); - Renderer.registerPlugin('particle', ParticleRenderer); - Renderer.registerPlugin('prepare', Prepare); - Renderer.registerPlugin('batch', BatchRenderer); - Renderer.registerPlugin('tilingSprite', TilingSpriteRenderer); - Loader$1.registerPlugin(BitmapFontLoader); - Loader$1.registerPlugin(SpritesheetLoader); - Application.registerPlugin(TickerPlugin); - Application.registerPlugin(AppLoaderPlugin); - /** - * String of the current PIXI version. - * - * @static - * @constant - * @memberof PIXI - * @name VERSION - * @type {string} - */ - var VERSION$1 = '5.3.3'; - /** - * @namespace PIXI - */ - /** - * This namespace contains WebGL-only display filters that can be applied - * to DisplayObjects using the {@link PIXI.DisplayObject#filters filters} property. - * - * Since PixiJS only had a handful of built-in filters, additional filters - * can be downloaded {@link https://github.com/pixijs/pixi-filters here} from the - * PixiJS Filters repository. - * - * All filters must extend {@link PIXI.Filter}. - * - * @example - * // Create a new application - * const app = new PIXI.Application(); - * - * // Draw a green rectangle - * const rect = new PIXI.Graphics() - * .beginFill(0x00ff00) - * .drawRect(40, 40, 200, 200); - * - * // Add a blur filter - * rect.filters = [new PIXI.filters.BlurFilter()]; - * - * // Display rectangle - * app.stage.addChild(rect); - * document.body.appendChild(app.view); - * @namespace PIXI.filters - */ - var filters = { - AlphaFilter: AlphaFilter, - BlurFilter: BlurFilter, - BlurFilterPass: BlurFilterPass, - ColorMatrixFilter: ColorMatrixFilter, - DisplacementFilter: DisplacementFilter, - FXAAFilter: FXAAFilter, - NoiseFilter: NoiseFilter, - }; - - exports.AbstractBatchRenderer = AbstractBatchRenderer; - exports.AbstractRenderer = AbstractRenderer; - exports.AccessibilityManager = AccessibilityManager; - exports.AnimatedSprite = AnimatedSprite; - exports.AppLoaderPlugin = AppLoaderPlugin; - exports.Application = Application; - exports.Attribute = Attribute; - exports.BasePrepare = BasePrepare; - exports.BaseRenderTexture = BaseRenderTexture; - exports.BaseTexture = BaseTexture; - exports.BatchDrawCall = BatchDrawCall; - exports.BatchGeometry = BatchGeometry; - exports.BatchPluginFactory = BatchPluginFactory; - exports.BatchRenderer = BatchRenderer; - exports.BatchShaderGenerator = BatchShaderGenerator; - exports.BatchTextureArray = BatchTextureArray; - exports.BitmapFont = BitmapFont; - exports.BitmapFontData = BitmapFontData; - exports.BitmapFontLoader = BitmapFontLoader; - exports.BitmapText = BitmapText; - exports.Bounds = Bounds; - exports.Buffer = Buffer; - exports.Circle = Circle; - exports.Container = Container; - exports.CountLimiter = CountLimiter; - exports.DEG_TO_RAD = DEG_TO_RAD; - exports.DisplayObject = DisplayObject; - exports.Ellipse = Ellipse; - exports.Extract = Extract; - exports.FillStyle = FillStyle; - exports.Filter = Filter; - exports.FilterState = FilterState; - exports.Framebuffer = Framebuffer; - exports.GLFramebuffer = GLFramebuffer; - exports.GLProgram = GLProgram; - exports.GLTexture = GLTexture; - exports.GRAPHICS_CURVES = GRAPHICS_CURVES; - exports.Geometry = Geometry; - exports.Graphics = Graphics; - exports.GraphicsData = GraphicsData; - exports.GraphicsGeometry = GraphicsGeometry; - exports.IGLUniformData = IGLUniformData; - exports.InteractionData = InteractionData; - exports.InteractionEvent = InteractionEvent; - exports.InteractionManager = InteractionManager; - exports.InteractionTrackingData = InteractionTrackingData; - exports.LineStyle = LineStyle; - exports.Loader = Loader$1; - exports.LoaderResource = LoaderResource; - exports.MaskData = MaskData; - exports.Matrix = Matrix; - exports.Mesh = Mesh; - exports.MeshBatchUvs = MeshBatchUvs; - exports.MeshGeometry = MeshGeometry; - exports.MeshMaterial = MeshMaterial; - exports.NineSlicePlane = NineSlicePlane; - exports.ObjectRenderer = ObjectRenderer; - exports.ObservablePoint = ObservablePoint; - exports.PI_2 = PI_2; - exports.ParticleContainer = ParticleContainer; - exports.ParticleRenderer = ParticleRenderer; - exports.PlaneGeometry = PlaneGeometry; - exports.Point = Point; - exports.Polygon = Polygon; - exports.Prepare = Prepare; - exports.Program = Program; - exports.Quad = Quad; - exports.QuadUv = QuadUv; - exports.RAD_TO_DEG = RAD_TO_DEG; - exports.Rectangle = Rectangle; - exports.RenderTexture = RenderTexture; - exports.RenderTexturePool = RenderTexturePool; - exports.Renderer = Renderer; - exports.RopeGeometry = RopeGeometry; - exports.RoundedRectangle = RoundedRectangle; - exports.Runner = Runner; - exports.Shader = Shader; - exports.SimpleMesh = SimpleMesh; - exports.SimplePlane = SimplePlane; - exports.SimpleRope = SimpleRope; - exports.Sprite = Sprite; - exports.SpriteMaskFilter = SpriteMaskFilter; - exports.Spritesheet = Spritesheet; - exports.SpritesheetLoader = SpritesheetLoader; - exports.State = State; - exports.System = System; - exports.TemporaryDisplayObject = TemporaryDisplayObject; - exports.Text = Text; - exports.TextMetrics = TextMetrics; - exports.TextStyle = TextStyle; - exports.Texture = Texture; - exports.TextureLoader = TextureLoader; - exports.TextureMatrix = TextureMatrix; - exports.TextureUvs = TextureUvs; - exports.Ticker = Ticker; - exports.TickerPlugin = TickerPlugin; - exports.TilingSprite = TilingSprite; - exports.TilingSpriteRenderer = TilingSpriteRenderer; - exports.TimeLimiter = TimeLimiter; - exports.Transform = Transform; - exports.UniformGroup = UniformGroup; - exports.VERSION = VERSION$1; - exports.ViewableBuffer = ViewableBuffer; - exports.accessibleTarget = accessibleTarget; - exports.autoDetectRenderer = autoDetectRenderer; - exports.checkMaxIfStatementsInShader = checkMaxIfStatementsInShader; - exports.defaultFilterVertex = defaultFilter; - exports.defaultVertex = _default; - exports.filters = filters; - exports.graphicsUtils = index$2; - exports.groupD8 = groupD8; - exports.interactiveTarget = interactiveTarget; - exports.isMobile = isMobile$1; - exports.resources = index; - exports.settings = settings; - exports.systems = systems; - exports.uniformParsers = uniformParsers; - exports.useDeprecated = useDeprecated; - exports.utils = utils_es; - - return exports; - -}({})); -PIXI.useDeprecated(); + function __extends(d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + } + + /** + * An AnimatedSprite is a simple way to display an animation depicted by a list of textures. + * + * ```js + * let alienImages = ["image_sequence_01.png","image_sequence_02.png","image_sequence_03.png","image_sequence_04.png"]; + * let textureArray = []; + * + * for (let i=0; i < 4; i++) + * { + * let texture = PIXI.Texture.from(alienImages[i]); + * textureArray.push(texture); + * }; + * + * let animatedSprite = new PIXI.AnimatedSprite(textureArray); + * ``` + * + * The more efficient and simpler way to create an animated sprite is using a {@link PIXI.Spritesheet} + * containing the animation definitions: + * + * ```js + * PIXI.Loader.shared.add("assets/spritesheet.json").load(setup); + * + * function setup() { + * let sheet = PIXI.Loader.shared.resources["assets/spritesheet.json"].spritesheet; + * animatedSprite = new PIXI.AnimatedSprite(sheet.animations["image_sequence"]); + * ... + * } + * ``` + * @memberof PIXI + */ + var AnimatedSprite = /** @class */ (function (_super) { + __extends(AnimatedSprite, _super); + /** + * @param textures - An array of {@link PIXI.Texture} or frame + * objects that make up the animation. + * @param {boolean} [autoUpdate=true] - Whether to use PIXI.Ticker.shared to auto update animation time. + */ + function AnimatedSprite(textures, autoUpdate) { + if (autoUpdate === void 0) { autoUpdate = true; } + var _this = _super.call(this, textures[0] instanceof Texture ? textures[0] : textures[0].texture) || this; + _this._textures = null; + _this._durations = null; + _this._autoUpdate = autoUpdate; + _this._isConnectedToTicker = false; + _this.animationSpeed = 1; + _this.loop = true; + _this.updateAnchor = false; + _this.onComplete = null; + _this.onFrameChange = null; + _this.onLoop = null; + _this._currentTime = 0; + _this._playing = false; + _this._previousFrame = null; + _this.textures = textures; + return _this; + } + /** Stops the AnimatedSprite. */ + AnimatedSprite.prototype.stop = function () { + if (!this._playing) { + return; + } + this._playing = false; + if (this._autoUpdate && this._isConnectedToTicker) { + Ticker.shared.remove(this.update, this); + this._isConnectedToTicker = false; + } + }; + /** Plays the AnimatedSprite. */ + AnimatedSprite.prototype.play = function () { + if (this._playing) { + return; + } + this._playing = true; + if (this._autoUpdate && !this._isConnectedToTicker) { + Ticker.shared.add(this.update, this, exports.UPDATE_PRIORITY.HIGH); + this._isConnectedToTicker = true; + } + }; + /** + * Stops the AnimatedSprite and goes to a specific frame. + * @param frameNumber - Frame index to stop at. + */ + AnimatedSprite.prototype.gotoAndStop = function (frameNumber) { + this.stop(); + var previousFrame = this.currentFrame; + this._currentTime = frameNumber; + if (previousFrame !== this.currentFrame) { + this.updateTexture(); + } + }; + /** + * Goes to a specific frame and begins playing the AnimatedSprite. + * @param frameNumber - Frame index to start at. + */ + AnimatedSprite.prototype.gotoAndPlay = function (frameNumber) { + var previousFrame = this.currentFrame; + this._currentTime = frameNumber; + if (previousFrame !== this.currentFrame) { + this.updateTexture(); + } + this.play(); + }; + /** + * Updates the object transform for rendering. + * @param deltaTime - Time since last tick. + */ + AnimatedSprite.prototype.update = function (deltaTime) { + if (!this._playing) { + return; + } + var elapsed = this.animationSpeed * deltaTime; + var previousFrame = this.currentFrame; + if (this._durations !== null) { + var lag = this._currentTime % 1 * this._durations[this.currentFrame]; + lag += elapsed / 60 * 1000; + while (lag < 0) { + this._currentTime--; + lag += this._durations[this.currentFrame]; + } + var sign = Math.sign(this.animationSpeed * deltaTime); + this._currentTime = Math.floor(this._currentTime); + while (lag >= this._durations[this.currentFrame]) { + lag -= this._durations[this.currentFrame] * sign; + this._currentTime += sign; + } + this._currentTime += lag / this._durations[this.currentFrame]; + } + else { + this._currentTime += elapsed; + } + if (this._currentTime < 0 && !this.loop) { + this.gotoAndStop(0); + if (this.onComplete) { + this.onComplete(); + } + } + else if (this._currentTime >= this._textures.length && !this.loop) { + this.gotoAndStop(this._textures.length - 1); + if (this.onComplete) { + this.onComplete(); + } + } + else if (previousFrame !== this.currentFrame) { + if (this.loop && this.onLoop) { + if (this.animationSpeed > 0 && this.currentFrame < previousFrame) { + this.onLoop(); + } + else if (this.animationSpeed < 0 && this.currentFrame > previousFrame) { + this.onLoop(); + } + } + this.updateTexture(); + } + }; + /** Updates the displayed texture to match the current frame index. */ + AnimatedSprite.prototype.updateTexture = function () { + var currentFrame = this.currentFrame; + if (this._previousFrame === currentFrame) { + return; + } + this._previousFrame = currentFrame; + this._texture = this._textures[currentFrame]; + this._textureID = -1; + this._textureTrimmedID = -1; + this._cachedTint = 0xFFFFFF; + this.uvs = this._texture._uvs.uvsFloat32; + if (this.updateAnchor) { + this._anchor.copyFrom(this._texture.defaultAnchor); + } + if (this.onFrameChange) { + this.onFrameChange(this.currentFrame); + } + }; + /** + * Stops the AnimatedSprite and destroys it. + * @param {object|boolean} [options] - Options parameter. A boolean will act as if all options + * have been set to that value. + * @param {boolean} [options.children=false] - If set to true, all the children will have their destroy + * method called as well. 'options' will be passed on to those calls. + * @param {boolean} [options.texture=false] - Should it destroy the current texture of the sprite as well. + * @param {boolean} [options.baseTexture=false] - Should it destroy the base texture of the sprite as well. + */ + AnimatedSprite.prototype.destroy = function (options) { + this.stop(); + _super.prototype.destroy.call(this, options); + this.onComplete = null; + this.onFrameChange = null; + this.onLoop = null; + }; + /** + * A short hand way of creating an AnimatedSprite from an array of frame ids. + * @param frames - The array of frames ids the AnimatedSprite will use as its texture frames. + * @returns - The new animated sprite with the specified frames. + */ + AnimatedSprite.fromFrames = function (frames) { + var textures = []; + for (var i = 0; i < frames.length; ++i) { + textures.push(Texture.from(frames[i])); + } + return new AnimatedSprite(textures); + }; + /** + * A short hand way of creating an AnimatedSprite from an array of image ids. + * @param images - The array of image urls the AnimatedSprite will use as its texture frames. + * @returns The new animate sprite with the specified images as frames. + */ + AnimatedSprite.fromImages = function (images) { + var textures = []; + for (var i = 0; i < images.length; ++i) { + textures.push(Texture.from(images[i])); + } + return new AnimatedSprite(textures); + }; + Object.defineProperty(AnimatedSprite.prototype, "totalFrames", { + /** + * The total number of frames in the AnimatedSprite. This is the same as number of textures + * assigned to the AnimatedSprite. + * @readonly + * @default 0 + */ + get: function () { + return this._textures.length; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(AnimatedSprite.prototype, "textures", { + /** The array of textures used for this AnimatedSprite. */ + get: function () { + return this._textures; + }, + set: function (value) { + if (value[0] instanceof Texture) { + this._textures = value; + this._durations = null; + } + else { + this._textures = []; + this._durations = []; + for (var i = 0; i < value.length; i++) { + this._textures.push(value[i].texture); + this._durations.push(value[i].time); + } + } + this._previousFrame = null; + this.gotoAndStop(0); + this.updateTexture(); + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(AnimatedSprite.prototype, "currentFrame", { + /** + * The AnimatedSprites current frame index. + * @readonly + */ + get: function () { + var currentFrame = Math.floor(this._currentTime) % this._textures.length; + if (currentFrame < 0) { + currentFrame += this._textures.length; + } + return currentFrame; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(AnimatedSprite.prototype, "playing", { + /** + * Indicates if the AnimatedSprite is currently playing. + * @readonly + */ + get: function () { + return this._playing; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(AnimatedSprite.prototype, "autoUpdate", { + /** Whether to use PIXI.Ticker.shared to auto update animation time. */ + get: function () { + return this._autoUpdate; + }, + set: function (value) { + if (value !== this._autoUpdate) { + this._autoUpdate = value; + if (!this._autoUpdate && this._isConnectedToTicker) { + Ticker.shared.remove(this.update, this); + this._isConnectedToTicker = false; + } + else if (this._autoUpdate && !this._isConnectedToTicker && this._playing) { + Ticker.shared.add(this.update, this); + this._isConnectedToTicker = true; + } + } + }, + enumerable: false, + configurable: true + }); + return AnimatedSprite; + }(Sprite)); + + extensions.add( + // Install renderer plugins + AccessibilityManager, Extract, InteractionManager, ParticleRenderer, Prepare, BatchRenderer, TilingSpriteRenderer, + // Install loader plugins + BitmapFontLoader, CompressedTextureLoader, DDSLoader, KTXLoader, SpritesheetLoader, + // Install application plugins + TickerPlugin, AppLoaderPlugin); + /** + * This namespace contains WebGL-only display filters that can be applied + * to DisplayObjects using the {@link PIXI.DisplayObject#filters filters} property. + * + * Since PixiJS only had a handful of built-in filters, additional filters + * can be downloaded {@link https://github.com/pixijs/pixi-filters here} from the + * PixiJS Filters repository. + * + * All filters must extend {@link PIXI.Filter}. + * @example + * // Create a new application + * const app = new PIXI.Application(); + * + * // Draw a green rectangle + * const rect = new PIXI.Graphics() + * .beginFill(0x00ff00) + * .drawRect(40, 40, 200, 200); + * + * // Add a blur filter + * rect.filters = [new PIXI.filters.BlurFilter()]; + * + * // Display rectangle + * app.stage.addChild(rect); + * document.body.appendChild(app.view); + * @namespace PIXI.filters + */ + var filters = { + AlphaFilter: AlphaFilter, + BlurFilter: BlurFilter, + BlurFilterPass: BlurFilterPass, + ColorMatrixFilter: ColorMatrixFilter, + DisplacementFilter: DisplacementFilter, + FXAAFilter: FXAAFilter, + NoiseFilter: NoiseFilter, + }; + + exports.AbstractBatchRenderer = AbstractBatchRenderer; + exports.AbstractMultiResource = AbstractMultiResource; + exports.AbstractRenderer = AbstractRenderer; + exports.AccessibilityManager = AccessibilityManager; + exports.AnimatedSprite = AnimatedSprite; + exports.AppLoaderPlugin = AppLoaderPlugin; + exports.Application = Application; + exports.ArrayResource = ArrayResource; + exports.Attribute = Attribute; + exports.BaseImageResource = BaseImageResource; + exports.BasePrepare = BasePrepare; + exports.BaseRenderTexture = BaseRenderTexture; + exports.BaseTexture = BaseTexture; + exports.BatchDrawCall = BatchDrawCall; + exports.BatchGeometry = BatchGeometry; + exports.BatchPluginFactory = BatchPluginFactory; + exports.BatchRenderer = BatchRenderer; + exports.BatchShaderGenerator = BatchShaderGenerator; + exports.BatchSystem = BatchSystem; + exports.BatchTextureArray = BatchTextureArray; + exports.BitmapFont = BitmapFont; + exports.BitmapFontData = BitmapFontData; + exports.BitmapFontLoader = BitmapFontLoader; + exports.BitmapText = BitmapText; + exports.BlobResource = BlobResource; + exports.Bounds = Bounds; + exports.BrowserAdapter = BrowserAdapter$1; + exports.Buffer = Buffer; + exports.BufferResource = BufferResource; + exports.CanvasResource = CanvasResource; + exports.Circle = Circle; + exports.CompressedTextureLoader = CompressedTextureLoader; + exports.CompressedTextureResource = CompressedTextureResource; + exports.Container = Container; + exports.ContextSystem = ContextSystem; + exports.CountLimiter = CountLimiter; + exports.CubeResource = CubeResource; + exports.DDSLoader = DDSLoader; + exports.DEG_TO_RAD = DEG_TO_RAD; + exports.DisplayObject = DisplayObject; + exports.Ellipse = Ellipse; + exports.Extract = Extract; + exports.FORMATS_TO_COMPONENTS = FORMATS_TO_COMPONENTS; + exports.FillStyle = FillStyle; + exports.Filter = Filter; + exports.FilterState = FilterState; + exports.FilterSystem = FilterSystem; + exports.Framebuffer = Framebuffer; + exports.FramebufferSystem = FramebufferSystem; + exports.GLFramebuffer = GLFramebuffer; + exports.GLProgram = GLProgram; + exports.GLTexture = GLTexture; + exports.GRAPHICS_CURVES = GRAPHICS_CURVES; + exports.Geometry = Geometry; + exports.GeometrySystem = GeometrySystem; + exports.Graphics = Graphics; + exports.GraphicsData = GraphicsData; + exports.GraphicsGeometry = GraphicsGeometry; + exports.IGLUniformData = IGLUniformData; + exports.INSTALLED = INSTALLED; + exports.INTERNAL_FORMAT_TO_BYTES_PER_PIXEL = INTERNAL_FORMAT_TO_BYTES_PER_PIXEL; + exports.ImageBitmapResource = ImageBitmapResource; + exports.ImageResource = ImageResource; + exports.InteractionData = InteractionData; + exports.InteractionEvent = InteractionEvent; + exports.InteractionManager = InteractionManager; + exports.InteractionTrackingData = InteractionTrackingData; + exports.KTXLoader = KTXLoader; + exports.LineStyle = LineStyle; + exports.Loader = Loader; + exports.MaskData = MaskData; + exports.MaskSystem = MaskSystem; + exports.Matrix = Matrix; + exports.Mesh = Mesh; + exports.MeshBatchUvs = MeshBatchUvs; + exports.MeshGeometry = MeshGeometry; + exports.MeshMaterial = MeshMaterial; + exports.NineSlicePlane = NineSlicePlane; + exports.ObjectRenderer = ObjectRenderer; + exports.ObservablePoint = ObservablePoint; + exports.PI_2 = PI_2; + exports.ParticleContainer = ParticleContainer; + exports.ParticleRenderer = ParticleRenderer; + exports.PlaneGeometry = PlaneGeometry; + exports.Point = Point; + exports.Polygon = Polygon; + exports.Prepare = Prepare; + exports.Program = Program; + exports.ProjectionSystem = ProjectionSystem; + exports.Quad = Quad; + exports.QuadUv = QuadUv; + exports.RAD_TO_DEG = RAD_TO_DEG; + exports.Rectangle = Rectangle; + exports.RenderTexture = RenderTexture; + exports.RenderTexturePool = RenderTexturePool; + exports.RenderTextureSystem = RenderTextureSystem; + exports.Renderer = Renderer; + exports.ResizePlugin = ResizePlugin; + exports.Resource = Resource; + exports.RopeGeometry = RopeGeometry; + exports.RoundedRectangle = RoundedRectangle; + exports.Runner = Runner; + exports.SVGResource = SVGResource; + exports.ScissorSystem = ScissorSystem; + exports.Shader = Shader; + exports.ShaderSystem = ShaderSystem; + exports.SimpleMesh = SimpleMesh; + exports.SimplePlane = SimplePlane; + exports.SimpleRope = SimpleRope; + exports.Sprite = Sprite; + exports.SpriteMaskFilter = SpriteMaskFilter; + exports.Spritesheet = Spritesheet; + exports.SpritesheetLoader = SpritesheetLoader; + exports.State = State; + exports.StateSystem = StateSystem; + exports.StencilSystem = StencilSystem; + exports.System = System; + exports.TYPES_TO_BYTES_PER_COMPONENT = TYPES_TO_BYTES_PER_COMPONENT; + exports.TYPES_TO_BYTES_PER_PIXEL = TYPES_TO_BYTES_PER_PIXEL; + exports.TemporaryDisplayObject = TemporaryDisplayObject; + exports.Text = Text; + exports.TextFormat = TextFormat; + exports.TextMetrics = TextMetrics; + exports.TextStyle = TextStyle; + exports.Texture = Texture; + exports.TextureGCSystem = TextureGCSystem; + exports.TextureLoader = TextureLoader; + exports.TextureMatrix = TextureMatrix; + exports.TextureSystem = TextureSystem; + exports.TextureUvs = TextureUvs; + exports.Ticker = Ticker; + exports.TickerPlugin = TickerPlugin; + exports.TilingSprite = TilingSprite; + exports.TilingSpriteRenderer = TilingSpriteRenderer; + exports.TimeLimiter = TimeLimiter; + exports.Transform = Transform; + exports.UniformGroup = UniformGroup; + exports.VERSION = VERSION; + exports.VideoResource = VideoResource; + exports.ViewableBuffer = ViewableBuffer; + exports.XMLFormat = XMLFormat; + exports.XMLStringFormat = XMLStringFormat; + exports.accessibleTarget = accessibleTarget; + exports.autoDetectFormat = autoDetectFormat; + exports.autoDetectRenderer = autoDetectRenderer; + exports.autoDetectResource = autoDetectResource; + exports.checkMaxIfStatementsInShader = checkMaxIfStatementsInShader; + exports.createUBOElements = createUBOElements; + exports.defaultFilterVertex = defaultFilterVertex; + exports.defaultVertex = defaultVertex$1; + exports.extensions = extensions; + exports.filters = filters; + exports.generateProgram = generateProgram; + exports.generateUniformBufferSync = generateUniformBufferSync; + exports.getTestContext = getTestContext; + exports.getUBOData = getUBOData; + exports.graphicsUtils = graphicsUtils; + exports.groupD8 = groupD8; + exports.interactiveTarget = interactiveTarget; + exports.isMobile = isMobile$2; + exports.parseDDS = parseDDS; + exports.parseKTX = parseKTX; + exports.resources = resources; + exports.settings = settings$1; + exports.systems = systems; + exports.uniformParsers = uniformParsers; + exports.utils = utils; + + Object.defineProperty(exports, '__esModule', { value: true }); + + return exports; + +})({}); var e;e||(e=eval("(function() { try { return Module || {} } catch(e) { return {} } })()"));var aa={},k;for(k in e)e.hasOwnProperty(k)&&(aa[k]=e[k]);var ba="object"===typeof window,ca="function"===typeof importScripts,da="object"===typeof process&&"function"===typeof require&&!ba&&!ca,ea=!ba&&!da&&!ca; @@ -47565,5874 +49114,8252 @@ var pixi_compressed_textures; })(pixi_compressed_textures || (pixi_compressed_textures = {})); /*! - * pixi-filters - v3.0.3 - * Compiled Wed, 29 May 2019 03:04:05 UTC + * pixi-filters - v4.2.0 + * Compiled Fri, 05 Aug 2022 19:53:35 UTC * * pixi-filters is licensed under the MIT License. * http://www.opensource.org/licenses/mit-license */ -var __filters=function(e,t,n,r,o,i,l,s){"use strict";var a="attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n vTextureCoord = aTextureCoord;\n}",u="varying vec2 vTextureCoord;\nuniform sampler2D uSampler;\n\nuniform float gamma;\nuniform float contrast;\nuniform float saturation;\nuniform float brightness;\nuniform float red;\nuniform float green;\nuniform float blue;\nuniform float alpha;\n\nvoid main(void)\n{\n vec4 c = texture2D(uSampler, vTextureCoord);\n\n if (c.a > 0.0) {\n c.rgb /= c.a;\n\n vec3 rgb = pow(c.rgb, vec3(1. / gamma));\n rgb = mix(vec3(.5), mix(vec3(dot(vec3(.2125, .7154, .0721), rgb)), rgb, saturation), contrast);\n rgb.r *= red;\n rgb.g *= green;\n rgb.b *= blue;\n c.rgb = rgb * brightness;\n\n c.rgb *= c.a;\n }\n\n gl_FragColor = c * alpha;\n}\n",c=function(e){function t(t){e.call(this,a,u),Object.assign(this,{gamma:1,saturation:1,contrast:1,brightness:1,red:1,green:1,blue:1,alpha:1},t)}return e&&(t.__proto__=e),t.prototype=Object.create(e&&e.prototype),t.prototype.constructor=t,t.prototype.apply=function(e,t,n,r){this.uniforms.gamma=Math.max(this.gamma,1e-4),this.uniforms.saturation=this.saturation,this.uniforms.contrast=this.contrast,this.uniforms.brightness=this.brightness,this.uniforms.red=this.red,this.uniforms.green=this.green,this.uniforms.blue=this.blue,this.uniforms.alpha=this.alpha,e.applyFilter(this,t,n,r)},t}(t.Filter),f=a,h="\nvarying vec2 vTextureCoord;\nuniform sampler2D uSampler;\n\nuniform vec2 uOffset;\n\nvoid main(void)\n{\n vec4 color = vec4(0.0);\n\n // Sample top left pixel\n color += texture2D(uSampler, vec2(vTextureCoord.x - uOffset.x, vTextureCoord.y + uOffset.y));\n\n // Sample top right pixel\n color += texture2D(uSampler, vec2(vTextureCoord.x + uOffset.x, vTextureCoord.y + uOffset.y));\n\n // Sample bottom right pixel\n color += texture2D(uSampler, vec2(vTextureCoord.x + uOffset.x, vTextureCoord.y - uOffset.y));\n\n // Sample bottom left pixel\n color += texture2D(uSampler, vec2(vTextureCoord.x - uOffset.x, vTextureCoord.y - uOffset.y));\n\n // Average\n color *= 0.25;\n\n gl_FragColor = color;\n}",p="\nvarying vec2 vTextureCoord;\nuniform sampler2D uSampler;\n\nuniform vec2 uOffset;\nuniform vec4 filterClamp;\n\nvoid main(void)\n{\n vec4 color = vec4(0.0);\n\n // Sample top left pixel\n color += texture2D(uSampler, clamp(vec2(vTextureCoord.x - uOffset.x, vTextureCoord.y + uOffset.y), filterClamp.xy, filterClamp.zw));\n\n // Sample top right pixel\n color += texture2D(uSampler, clamp(vec2(vTextureCoord.x + uOffset.x, vTextureCoord.y + uOffset.y), filterClamp.xy, filterClamp.zw));\n\n // Sample bottom right pixel\n color += texture2D(uSampler, clamp(vec2(vTextureCoord.x + uOffset.x, vTextureCoord.y - uOffset.y), filterClamp.xy, filterClamp.zw));\n\n // Sample bottom left pixel\n color += texture2D(uSampler, clamp(vec2(vTextureCoord.x - uOffset.x, vTextureCoord.y - uOffset.y), filterClamp.xy, filterClamp.zw));\n\n // Average\n color *= 0.25;\n\n gl_FragColor = color;\n}\n",d=function(e){function t(t,r,o){void 0===t&&(t=4),void 0===r&&(r=3),void 0===o&&(o=!1),e.call(this,f,o?p:h),this.uniforms.uOffset=new Float32Array(2),this._pixelSize=new n.Point,this.pixelSize=1,this._clamp=o,this._kernels=null,Array.isArray(t)?this.kernels=t:(this._blur=t,this.quality=r)}e&&(t.__proto__=e),t.prototype=Object.create(e&&e.prototype),t.prototype.constructor=t;var r={kernels:{configurable:!0},clamp:{configurable:!0},pixelSize:{configurable:!0},quality:{configurable:!0},blur:{configurable:!0}};return t.prototype.apply=function(e,t,n,r){var o,i=this.pixelSize.x/t._frame.width,l=this.pixelSize.y/t._frame.height;if(1===this._quality||0===this._blur)o=this._kernels[0]+.5,this.uniforms.uOffset[0]=o*i,this.uniforms.uOffset[1]=o*l,e.applyFilter(this,t,n,r);else{for(var s,a=e.getFilterTexture(),u=t,c=a,f=this._quality-1,h=0;h0)for(var r=e,o=e/t,i=1;i0?(this._kernels=e,this._quality=e.length,this._blur=Math.max.apply(Math,e)):(this._kernels=[0],this._quality=1)},r.clamp.get=function(){return this._clamp},r.pixelSize.set=function(e){"number"==typeof e?(this._pixelSize.x=e,this._pixelSize.y=e):Array.isArray(e)?(this._pixelSize.x=e[0],this._pixelSize.y=e[1]):e instanceof n.Point?(this._pixelSize.x=e.x,this._pixelSize.y=e.y):(this._pixelSize.x=1,this._pixelSize.y=1)},r.pixelSize.get=function(){return this._pixelSize},r.quality.get=function(){return this._quality},r.quality.set=function(e){this._quality=Math.max(1,Math.round(e)),this._generateKernels()},r.blur.get=function(){return this._blur},r.blur.set=function(e){this._blur=e,this._generateKernels()},Object.defineProperties(t.prototype,r),t}(t.Filter),m=a,g="\nuniform sampler2D uSampler;\nvarying vec2 vTextureCoord;\n\nuniform float threshold;\n\nvoid main() {\n vec4 color = texture2D(uSampler, vTextureCoord);\n\n // A simple & fast algorithm for getting brightness.\n // It's inaccuracy , but good enought for this feature.\n float _max = max(max(color.r, color.g), color.b);\n float _min = min(min(color.r, color.g), color.b);\n float brightness = (_max + _min) * 0.5;\n\n if(brightness > threshold) {\n gl_FragColor = color;\n } else {\n gl_FragColor = vec4(0.0, 0.0, 0.0, 0.0);\n }\n}\n",v=function(e){function t(t){void 0===t&&(t=.5),e.call(this,m,g),this.threshold=t}e&&(t.__proto__=e),t.prototype=Object.create(e&&e.prototype),t.prototype.constructor=t;var n={threshold:{configurable:!0}};return n.threshold.get=function(){return this.uniforms.threshold},n.threshold.set=function(e){this.uniforms.threshold=e},Object.defineProperties(t.prototype,n),t}(t.Filter),x="uniform sampler2D uSampler;\nvarying vec2 vTextureCoord;\n\nuniform sampler2D bloomTexture;\nuniform float bloomScale;\nuniform float brightness;\n\nvoid main() {\n vec4 color = texture2D(uSampler, vTextureCoord);\n color.rgb *= brightness;\n vec4 bloomColor = vec4(texture2D(bloomTexture, vTextureCoord).rgb, 0.0);\n bloomColor.rgb *= bloomScale;\n gl_FragColor = color + bloomColor;\n}\n",y=function(e){function t(t){e.call(this,m,x),"number"==typeof t&&(t={threshold:t}),t=Object.assign({threshold:.5,bloomScale:1,brightness:1,kernels:null,blur:8,quality:4,pixelSize:1,resolution:r.settings.RESOLUTION},t),this.bloomScale=t.bloomScale,this.brightness=t.brightness;var n=t.kernels,o=t.blur,i=t.quality,l=t.pixelSize,s=t.resolution;this._extractFilter=new v(t.threshold),this._extractFilter.resolution=s,this._blurFilter=n?new d(n):new d(o,i),this.pixelSize=l,this.resolution=s}e&&(t.__proto__=e),t.prototype=Object.create(e&&e.prototype),t.prototype.constructor=t;var n={resolution:{configurable:!0},threshold:{configurable:!0},kernels:{configurable:!0},blur:{configurable:!0},quality:{configurable:!0},pixelSize:{configurable:!0}};return t.prototype.apply=function(e,t,n,r,o){var i=e.getFilterTexture();this._extractFilter.apply(e,t,i,!0,o);var l=e.getFilterTexture();this._blurFilter.apply(e,i,l,!0,o),this.uniforms.bloomScale=this.bloomScale,this.uniforms.brightness=this.brightness,this.uniforms.bloomTexture=l,e.applyFilter(this,t,n,r),e.returnFilterTexture(l),e.returnFilterTexture(i)},n.resolution.get=function(){return this._resolution},n.resolution.set=function(e){this._resolution=e,this._extractFilter&&(this._extractFilter.resolution=e),this._blurFilter&&(this._blurFilter.resolution=e)},n.threshold.get=function(){return this._extractFilter.threshold},n.threshold.set=function(e){this._extractFilter.threshold=e},n.kernels.get=function(){return this._blurFilter.kernels},n.kernels.set=function(e){this._blurFilter.kernels=e},n.blur.get=function(){return this._blurFilter.blur},n.blur.set=function(e){this._blurFilter.blur=e},n.quality.get=function(){return this._blurFilter.quality},n.quality.set=function(e){this._blurFilter.quality=e},n.pixelSize.get=function(){return this._blurFilter.pixelSize},n.pixelSize.set=function(e){this._blurFilter.pixelSize=e},Object.defineProperties(t.prototype,n),t}(t.Filter),b=a,_="varying vec2 vTextureCoord;\n\nuniform vec4 filterArea;\nuniform float pixelSize;\nuniform sampler2D uSampler;\n\nvec2 mapCoord( vec2 coord )\n{\n coord *= filterArea.xy;\n coord += filterArea.zw;\n\n return coord;\n}\n\nvec2 unmapCoord( vec2 coord )\n{\n coord -= filterArea.zw;\n coord /= filterArea.xy;\n\n return coord;\n}\n\nvec2 pixelate(vec2 coord, vec2 size)\n{\n return floor( coord / size ) * size;\n}\n\nvec2 getMod(vec2 coord, vec2 size)\n{\n return mod( coord , size) / size;\n}\n\nfloat character(float n, vec2 p)\n{\n p = floor(p*vec2(4.0, -4.0) + 2.5);\n\n if (clamp(p.x, 0.0, 4.0) == p.x)\n {\n if (clamp(p.y, 0.0, 4.0) == p.y)\n {\n if (int(mod(n/exp2(p.x + 5.0*p.y), 2.0)) == 1) return 1.0;\n }\n }\n return 0.0;\n}\n\nvoid main()\n{\n vec2 coord = mapCoord(vTextureCoord);\n\n // get the rounded color..\n vec2 pixCoord = pixelate(coord, vec2(pixelSize));\n pixCoord = unmapCoord(pixCoord);\n\n vec4 color = texture2D(uSampler, pixCoord);\n\n // determine the character to use\n float gray = (color.r + color.g + color.b) / 3.0;\n\n float n = 65536.0; // .\n if (gray > 0.2) n = 65600.0; // :\n if (gray > 0.3) n = 332772.0; // *\n if (gray > 0.4) n = 15255086.0; // o\n if (gray > 0.5) n = 23385164.0; // &\n if (gray > 0.6) n = 15252014.0; // 8\n if (gray > 0.7) n = 13199452.0; // @\n if (gray > 0.8) n = 11512810.0; // #\n\n // get the mod..\n vec2 modd = getMod(coord, vec2(pixelSize));\n\n gl_FragColor = color * character( n, vec2(-1.0) + modd * 2.0);\n\n}\n",C=function(e){function t(t){void 0===t&&(t=8),e.call(this,b,_),this.size=t}e&&(t.__proto__=e),t.prototype=Object.create(e&&e.prototype),t.prototype.constructor=t;var n={size:{configurable:!0}};return n.size.get=function(){return this.uniforms.pixelSize},n.size.set=function(e){this.uniforms.pixelSize=e},Object.defineProperties(t.prototype,n),t}(t.Filter),S=a,F="precision mediump float;\n\nvarying vec2 vTextureCoord;\nuniform sampler2D uSampler;\nuniform vec4 filterArea;\n\nuniform float transformX;\nuniform float transformY;\nuniform vec3 lightColor;\nuniform float lightAlpha;\nuniform vec3 shadowColor;\nuniform float shadowAlpha;\n\nvoid main(void) {\n vec2 transform = vec2(1.0 / filterArea) * vec2(transformX, transformY);\n vec4 color = texture2D(uSampler, vTextureCoord);\n float light = texture2D(uSampler, vTextureCoord - transform).a;\n float shadow = texture2D(uSampler, vTextureCoord + transform).a;\n\n color.rgb = mix(color.rgb, lightColor, clamp((color.a - light) * lightAlpha, 0.0, 1.0));\n color.rgb = mix(color.rgb, shadowColor, clamp((color.a - shadow) * shadowAlpha, 0.0, 1.0));\n gl_FragColor = vec4(color.rgb * color.a, color.a);\n}\n",z=function(e){function t(t){void 0===t&&(t={}),e.call(this,S,F),this.uniforms.lightColor=new Float32Array(3),this.uniforms.shadowColor=new Float32Array(3),t=Object.assign({rotation:45,thickness:2,lightColor:16777215,lightAlpha:.7,shadowColor:0,shadowAlpha:.7},t),this.rotation=t.rotation,this.thickness=t.thickness,this.lightColor=t.lightColor,this.lightAlpha=t.lightAlpha,this.shadowColor=t.shadowColor,this.shadowAlpha=t.shadowAlpha}e&&(t.__proto__=e),t.prototype=Object.create(e&&e.prototype),t.prototype.constructor=t;var r={rotation:{configurable:!0},thickness:{configurable:!0},lightColor:{configurable:!0},lightAlpha:{configurable:!0},shadowColor:{configurable:!0},shadowAlpha:{configurable:!0}};return t.prototype._updateTransform=function(){this.uniforms.transformX=this._thickness*Math.cos(this._angle),this.uniforms.transformY=this._thickness*Math.sin(this._angle)},r.rotation.get=function(){return this._angle/n.DEG_TO_RAD},r.rotation.set=function(e){this._angle=e*n.DEG_TO_RAD,this._updateTransform()},r.thickness.get=function(){return this._thickness},r.thickness.set=function(e){this._thickness=e,this._updateTransform()},r.lightColor.get=function(){return o.rgb2hex(this.uniforms.lightColor)},r.lightColor.set=function(e){o.hex2rgb(e,this.uniforms.lightColor)},r.lightAlpha.get=function(){return this.uniforms.lightAlpha},r.lightAlpha.set=function(e){this.uniforms.lightAlpha=e},r.shadowColor.get=function(){return o.rgb2hex(this.uniforms.shadowColor)},r.shadowColor.set=function(e){o.hex2rgb(e,this.uniforms.shadowColor)},r.shadowAlpha.get=function(){return this.uniforms.shadowAlpha},r.shadowAlpha.set=function(e){this.uniforms.shadowAlpha=e},Object.defineProperties(t.prototype,r),t}(t.Filter),A=function(e){function t(t,o,a,u){var c,f;void 0===t&&(t=2),void 0===o&&(o=4),void 0===a&&(a=r.settings.RESOLUTION),void 0===u&&(u=5),e.call(this),"number"==typeof t?(c=t,f=t):t instanceof n.Point?(c=t.x,f=t.y):Array.isArray(t)&&(c=t[0],f=t[1]),this.blurXFilter=new s.BlurFilterPass(!0,c,o,a,u),this.blurYFilter=new s.BlurFilterPass(!1,f,o,a,u),this.blurYFilter.blendMode=i.BLEND_MODES.SCREEN,this.defaultFilter=new l.AlphaFilter}e&&(t.__proto__=e),t.prototype=Object.create(e&&e.prototype),t.prototype.constructor=t;var o={blur:{configurable:!0},blurX:{configurable:!0},blurY:{configurable:!0}};return t.prototype.apply=function(e,t,n){var r=e.getFilterTexture(!0);this.defaultFilter.apply(e,t,n),this.blurXFilter.apply(e,t,r),this.blurYFilter.apply(e,r,n),e.returnFilterTexture(r)},o.blur.get=function(){return this.blurXFilter.blur},o.blur.set=function(e){this.blurXFilter.blur=this.blurYFilter.blur=e},o.blurX.get=function(){return this.blurXFilter.blur},o.blurX.set=function(e){this.blurXFilter.blur=e},o.blurY.get=function(){return this.blurYFilter.blur},o.blurY.set=function(e){this.blurYFilter.blur=e},Object.defineProperties(t.prototype,o),t}(t.Filter),w=a,T="uniform float radius;\nuniform float strength;\nuniform vec2 center;\nuniform sampler2D uSampler;\nvarying vec2 vTextureCoord;\n\nuniform vec4 filterArea;\nuniform vec4 filterClamp;\nuniform vec2 dimensions;\n\nvoid main()\n{\n vec2 coord = vTextureCoord * filterArea.xy;\n coord -= center * dimensions.xy;\n float distance = length(coord);\n if (distance < radius) {\n float percent = distance / radius;\n if (strength > 0.0) {\n coord *= mix(1.0, smoothstep(0.0, radius / distance, percent), strength * 0.75);\n } else {\n coord *= mix(1.0, pow(percent, 1.0 + strength * 0.75) * radius / distance, 1.0 - percent);\n }\n }\n coord += center * dimensions.xy;\n coord /= filterArea.xy;\n vec2 clampedCoord = clamp(coord, filterClamp.xy, filterClamp.zw);\n vec4 color = texture2D(uSampler, clampedCoord);\n if (coord != clampedCoord) {\n color *= max(0.0, 1.0 - length(coord - clampedCoord));\n }\n\n gl_FragColor = color;\n}\n",D=function(e){function t(t,n,r){e.call(this,w,T),this.uniforms.dimensions=new Float32Array(2),this.center=t||[.5,.5],this.radius="number"==typeof n?n:100,this.strength="number"==typeof r?r:1}e&&(t.__proto__=e),t.prototype=Object.create(e&&e.prototype),t.prototype.constructor=t;var n={radius:{configurable:!0},strength:{configurable:!0},center:{configurable:!0}};return t.prototype.apply=function(e,t,n,r){this.uniforms.dimensions[0]=t.filterFrame.width,this.uniforms.dimensions[1]=t.filterFrame.height,e.applyFilter(this,t,n,r)},n.radius.get=function(){return this.uniforms.radius},n.radius.set=function(e){this.uniforms.radius=e},n.strength.get=function(){return this.uniforms.strength},n.strength.set=function(e){this.uniforms.strength=e},n.center.get=function(){return this.uniforms.center},n.center.set=function(e){this.uniforms.center=e},Object.defineProperties(t.prototype,n),t}(t.Filter),O=a,P="varying vec2 vTextureCoord;\nuniform sampler2D uSampler;\nuniform sampler2D colorMap;\nuniform float _mix;\nuniform float _size;\nuniform float _sliceSize;\nuniform float _slicePixelSize;\nuniform float _sliceInnerSize;\nvoid main() {\n vec4 color = texture2D(uSampler, vTextureCoord.xy);\n\n vec4 adjusted;\n if (color.a > 0.0) {\n color.rgb /= color.a;\n float innerWidth = _size - 1.0;\n float zSlice0 = min(floor(color.b * innerWidth), innerWidth);\n float zSlice1 = min(zSlice0 + 1.0, innerWidth);\n float xOffset = _slicePixelSize * 0.5 + color.r * _sliceInnerSize;\n float s0 = xOffset + (zSlice0 * _sliceSize);\n float s1 = xOffset + (zSlice1 * _sliceSize);\n float yOffset = _sliceSize * 0.5 + color.g * (1.0 - _sliceSize);\n vec4 slice0Color = texture2D(colorMap, vec2(s0,yOffset));\n vec4 slice1Color = texture2D(colorMap, vec2(s1,yOffset));\n float zOffset = fract(color.b * innerWidth);\n adjusted = mix(slice0Color, slice1Color, zOffset);\n\n color.rgb *= color.a;\n }\n gl_FragColor = vec4(mix(color, adjusted, _mix).rgb, color.a);\n\n}",M=function(e){function n(t,n,r){void 0===n&&(n=!1),void 0===r&&(r=1),e.call(this,O,P),this._size=0,this._sliceSize=0,this._slicePixelSize=0,this._sliceInnerSize=0,this._scaleMode=null,this._nearest=!1,this.nearest=n,this.mix=r,this.colorMap=t}e&&(n.__proto__=e),n.prototype=Object.create(e&&e.prototype),n.prototype.constructor=n;var r={colorSize:{configurable:!0},colorMap:{configurable:!0},nearest:{configurable:!0}};return n.prototype.apply=function(e,t,n,r){this.uniforms._mix=this.mix,e.applyFilter(this,t,n,r)},r.colorSize.get=function(){return this._size},r.colorMap.get=function(){return this._colorMap},r.colorMap.set=function(e){e instanceof t.Texture||(e=t.Texture.from(e)),e&&e.baseTexture&&(e.baseTexture.scaleMode=this._scaleMode,e.baseTexture.mipmap=!1,this._size=e.height,this._sliceSize=1/this._size,this._slicePixelSize=this._sliceSize/this._size,this._sliceInnerSize=this._slicePixelSize*(this._size-1),this.uniforms._size=this._size,this.uniforms._sliceSize=this._sliceSize,this.uniforms._slicePixelSize=this._slicePixelSize,this.uniforms._sliceInnerSize=this._sliceInnerSize,this.uniforms.colorMap=e),this._colorMap=e},r.nearest.get=function(){return this._nearest},r.nearest.set=function(e){this._nearest=e,this._scaleMode=e?i.SCALE_MODES.NEAREST:i.SCALE_MODES.LINEAR;var t=this._colorMap;t&&t.baseTexture&&(t.baseTexture._glTextures={},t.baseTexture.scaleMode=this._scaleMode,t.baseTexture.mipmap=!1,t._updateID++,t.baseTexture.emit("update",t.baseTexture))},n.prototype.updateColorMap=function(){var e=this._colorMap;e&&e.baseTexture&&(e._updateID++,e.baseTexture.emit("update",e.baseTexture),this.colorMap=e)},n.prototype.destroy=function(t){this._colorMap&&this._colorMap.destroy(t),e.prototype.destroy.call(this)},Object.defineProperties(n.prototype,r),n}(t.Filter),R=a,j="varying vec2 vTextureCoord;\nuniform sampler2D uSampler;\nuniform vec3 originalColor;\nuniform vec3 newColor;\nuniform float epsilon;\nvoid main(void) {\n vec4 currentColor = texture2D(uSampler, vTextureCoord);\n vec3 colorDiff = originalColor - (currentColor.rgb / max(currentColor.a, 0.0000000001));\n float colorDistance = length(colorDiff);\n float doReplace = step(colorDistance, epsilon);\n gl_FragColor = vec4(mix(currentColor.rgb, (newColor + colorDiff) * currentColor.a, doReplace), currentColor.a);\n}\n",k=function(e){function t(t,n,r){void 0===t&&(t=16711680),void 0===n&&(n=0),void 0===r&&(r=.4),e.call(this,R,j),this.uniforms.originalColor=new Float32Array(3),this.uniforms.newColor=new Float32Array(3),this.originalColor=t,this.newColor=n,this.epsilon=r}e&&(t.__proto__=e),t.prototype=Object.create(e&&e.prototype),t.prototype.constructor=t;var n={originalColor:{configurable:!0},newColor:{configurable:!0},epsilon:{configurable:!0}};return n.originalColor.set=function(e){var t=this.uniforms.originalColor;"number"==typeof e?(o.hex2rgb(e,t),this._originalColor=e):(t[0]=e[0],t[1]=e[1],t[2]=e[2],this._originalColor=o.rgb2hex(t))},n.originalColor.get=function(){return this._originalColor},n.newColor.set=function(e){var t=this.uniforms.newColor;"number"==typeof e?(o.hex2rgb(e,t),this._newColor=e):(t[0]=e[0],t[1]=e[1],t[2]=e[2],this._newColor=o.rgb2hex(t))},n.newColor.get=function(){return this._newColor},n.epsilon.set=function(e){this.uniforms.epsilon=e},n.epsilon.get=function(){return this.uniforms.epsilon},Object.defineProperties(t.prototype,n),t}(t.Filter),L=a,I="precision mediump float;\n\nvarying mediump vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\nuniform vec2 texelSize;\nuniform float matrix[9];\n\nvoid main(void)\n{\n vec4 c11 = texture2D(uSampler, vTextureCoord - texelSize); // top left\n vec4 c12 = texture2D(uSampler, vec2(vTextureCoord.x, vTextureCoord.y - texelSize.y)); // top center\n vec4 c13 = texture2D(uSampler, vec2(vTextureCoord.x + texelSize.x, vTextureCoord.y - texelSize.y)); // top right\n\n vec4 c21 = texture2D(uSampler, vec2(vTextureCoord.x - texelSize.x, vTextureCoord.y)); // mid left\n vec4 c22 = texture2D(uSampler, vTextureCoord); // mid center\n vec4 c23 = texture2D(uSampler, vec2(vTextureCoord.x + texelSize.x, vTextureCoord.y)); // mid right\n\n vec4 c31 = texture2D(uSampler, vec2(vTextureCoord.x - texelSize.x, vTextureCoord.y + texelSize.y)); // bottom left\n vec4 c32 = texture2D(uSampler, vec2(vTextureCoord.x, vTextureCoord.y + texelSize.y)); // bottom center\n vec4 c33 = texture2D(uSampler, vTextureCoord + texelSize); // bottom right\n\n gl_FragColor =\n c11 * matrix[0] + c12 * matrix[1] + c13 * matrix[2] +\n c21 * matrix[3] + c22 * matrix[4] + c23 * matrix[5] +\n c31 * matrix[6] + c32 * matrix[7] + c33 * matrix[8];\n\n gl_FragColor.a = c22.a;\n}\n",E=function(e){function t(t,n,r){void 0===n&&(n=200),void 0===r&&(r=200),e.call(this,L,I),this.uniforms.texelSize=new Float32Array(2),this.uniforms.matrix=new Float32Array(9),void 0!==t&&(this.matrix=t),this.width=n,this.height=r}e&&(t.__proto__=e),t.prototype=Object.create(e&&e.prototype),t.prototype.constructor=t;var n={matrix:{configurable:!0},width:{configurable:!0},height:{configurable:!0}};return n.matrix.get=function(){return this.uniforms.matrix},n.matrix.set=function(e){var t=this;e.forEach(function(e,n){return t.uniforms.matrix[n]=e})},n.width.get=function(){return 1/this.uniforms.texelSize[0]},n.width.set=function(e){this.uniforms.texelSize[0]=1/e},n.height.get=function(){return 1/this.uniforms.texelSize[1]},n.height.set=function(e){this.uniforms.texelSize[1]=1/e},Object.defineProperties(t.prototype,n),t}(t.Filter),B=a,X="precision mediump float;\n\nvarying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\n\nvoid main(void)\n{\n float lum = length(texture2D(uSampler, vTextureCoord.xy).rgb);\n\n gl_FragColor = vec4(1.0, 1.0, 1.0, 1.0);\n\n if (lum < 1.00)\n {\n if (mod(gl_FragCoord.x + gl_FragCoord.y, 10.0) == 0.0)\n {\n gl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);\n }\n }\n\n if (lum < 0.75)\n {\n if (mod(gl_FragCoord.x - gl_FragCoord.y, 10.0) == 0.0)\n {\n gl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);\n }\n }\n\n if (lum < 0.50)\n {\n if (mod(gl_FragCoord.x + gl_FragCoord.y - 5.0, 10.0) == 0.0)\n {\n gl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);\n }\n }\n\n if (lum < 0.3)\n {\n if (mod(gl_FragCoord.x - gl_FragCoord.y - 5.0, 10.0) == 0.0)\n {\n gl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);\n }\n }\n}\n",N=function(e){function t(){e.call(this,B,X)}return e&&(t.__proto__=e),t.prototype=Object.create(e&&e.prototype),t.prototype.constructor=t,t}(t.Filter),q=a,W="varying vec2 vTextureCoord;\nuniform sampler2D uSampler;\n\nuniform vec4 filterArea;\nuniform vec2 dimensions;\n\nconst float SQRT_2 = 1.414213;\n\nconst float light = 1.0;\n\nuniform float curvature;\nuniform float lineWidth;\nuniform float lineContrast;\nuniform bool verticalLine;\nuniform float noise;\nuniform float noiseSize;\n\nuniform float vignetting;\nuniform float vignettingAlpha;\nuniform float vignettingBlur;\n\nuniform float seed;\nuniform float time;\n\nfloat rand(vec2 co) {\n return fract(sin(dot(co.xy, vec2(12.9898, 78.233))) * 43758.5453);\n}\n\nvoid main(void)\n{\n vec2 pixelCoord = vTextureCoord.xy * filterArea.xy;\n vec2 coord = pixelCoord / dimensions;\n\n vec2 dir = vec2(coord - vec2(0.5, 0.5));\n\n float _c = curvature > 0. ? curvature : 1.;\n float k = curvature > 0. ?(length(dir * dir) * 0.25 * _c * _c + 0.935 * _c) : 1.;\n vec2 uv = dir * k;\n\n gl_FragColor = texture2D(uSampler, vTextureCoord);\n vec3 rgb = gl_FragColor.rgb;\n\n\n if (noise > 0.0 && noiseSize > 0.0)\n {\n pixelCoord.x = floor(pixelCoord.x / noiseSize);\n pixelCoord.y = floor(pixelCoord.y / noiseSize);\n float _noise = rand(pixelCoord * noiseSize * seed) - 0.5;\n rgb += _noise * noise;\n }\n\n if (lineWidth > 0.0) {\n float v = (verticalLine ? uv.x * dimensions.x : uv.y * dimensions.y) * min(1.0, 2.0 / lineWidth ) / _c;\n float j = 1. + cos(v * 1.2 - time) * 0.5 * lineContrast;\n rgb *= j;\n float segment = verticalLine ? mod((dir.x + .5) * dimensions.x, 4.) : mod((dir.y + .5) * dimensions.y, 4.);\n rgb *= 0.99 + ceil(segment) * 0.015;\n }\n\n if (vignetting > 0.0)\n {\n float outter = SQRT_2 - vignetting * SQRT_2;\n float darker = clamp((outter - length(dir) * SQRT_2) / ( 0.00001 + vignettingBlur * SQRT_2), 0.0, 1.0);\n rgb *= darker + (1.0 - darker) * (1.0 - vignettingAlpha);\n }\n\n gl_FragColor.rgb = rgb;\n}\n",K=function(e){function t(t){e.call(this,q,W),this.uniforms.dimensions=new Float32Array(2),this.time=0,this.seed=0,Object.assign(this,{curvature:1,lineWidth:1,lineContrast:.25,verticalLine:!1,noise:0,noiseSize:1,seed:0,vignetting:.3,vignettingAlpha:1,vignettingBlur:.3,time:0},t)}e&&(t.__proto__=e),t.prototype=Object.create(e&&e.prototype),t.prototype.constructor=t;var n={curvature:{configurable:!0},lineWidth:{configurable:!0},lineContrast:{configurable:!0},verticalLine:{configurable:!0},noise:{configurable:!0},noiseSize:{configurable:!0},vignetting:{configurable:!0},vignettingAlpha:{configurable:!0},vignettingBlur:{configurable:!0}};return t.prototype.apply=function(e,t,n,r){this.uniforms.dimensions[0]=t.filterFrame.width,this.uniforms.dimensions[1]=t.filterFrame.height,this.uniforms.seed=this.seed,this.uniforms.time=this.time,e.applyFilter(this,t,n,r)},n.curvature.set=function(e){this.uniforms.curvature=e},n.curvature.get=function(){return this.uniforms.curvature},n.lineWidth.set=function(e){this.uniforms.lineWidth=e},n.lineWidth.get=function(){return this.uniforms.lineWidth},n.lineContrast.set=function(e){this.uniforms.lineContrast=e},n.lineContrast.get=function(){return this.uniforms.lineContrast},n.verticalLine.set=function(e){this.uniforms.verticalLine=e},n.verticalLine.get=function(){return this.uniforms.verticalLine},n.noise.set=function(e){this.uniforms.noise=e},n.noise.get=function(){return this.uniforms.noise},n.noiseSize.set=function(e){this.uniforms.noiseSize=e},n.noiseSize.get=function(){return this.uniforms.noiseSize},n.vignetting.set=function(e){this.uniforms.vignetting=e},n.vignetting.get=function(){return this.uniforms.vignetting},n.vignettingAlpha.set=function(e){this.uniforms.vignettingAlpha=e},n.vignettingAlpha.get=function(){return this.uniforms.vignettingAlpha},n.vignettingBlur.set=function(e){this.uniforms.vignettingBlur=e},n.vignettingBlur.get=function(){return this.uniforms.vignettingBlur},Object.defineProperties(t.prototype,n),t}(t.Filter),Y=a,G="precision mediump float;\n\nvarying vec2 vTextureCoord;\nvarying vec4 vColor;\n\nuniform vec4 filterArea;\nuniform sampler2D uSampler;\n\nuniform float angle;\nuniform float scale;\n\nfloat pattern()\n{\n float s = sin(angle), c = cos(angle);\n vec2 tex = vTextureCoord * filterArea.xy;\n vec2 point = vec2(\n c * tex.x - s * tex.y,\n s * tex.x + c * tex.y\n ) * scale;\n return (sin(point.x) * sin(point.y)) * 4.0;\n}\n\nvoid main()\n{\n vec4 color = texture2D(uSampler, vTextureCoord);\n float average = (color.r + color.g + color.b) / 3.0;\n gl_FragColor = vec4(vec3(average * 10.0 - 5.0 + pattern()), color.a);\n}\n",Q=function(e){function t(t,n){void 0===t&&(t=1),void 0===n&&(n=5),e.call(this,Y,G),this.scale=t,this.angle=n}e&&(t.__proto__=e),t.prototype=Object.create(e&&e.prototype),t.prototype.constructor=t;var n={scale:{configurable:!0},angle:{configurable:!0}};return n.scale.get=function(){return this.uniforms.scale},n.scale.set=function(e){this.uniforms.scale=e},n.angle.get=function(){return this.uniforms.angle},n.angle.set=function(e){this.uniforms.angle=e},Object.defineProperties(t.prototype,n),t}(t.Filter),U=a,Z="varying vec2 vTextureCoord;\nuniform sampler2D uSampler;\nuniform float alpha;\nuniform vec3 color;\n\nuniform vec2 shift;\nuniform vec4 inputSize;\n\nvoid main(void){\n vec4 sample = texture2D(uSampler, vTextureCoord - shift * inputSize.zw);\n\n // Un-premultiply alpha before applying the color\n if (sample.a > 0.0) {\n sample.rgb /= sample.a;\n }\n\n // Premultiply alpha again\n sample.rgb = color.rgb * sample.a;\n\n // alpha user alpha\n sample *= alpha;\n\n gl_FragColor = sample;\n}",V=function(e){function t(t){t&&t.constructor!==Object&&(console.warn("DropShadowFilter now uses options instead of (rotation, distance, blur, color, alpha)"),t={rotation:t},void 0!==arguments[1]&&(t.distance=arguments[1]),void 0!==arguments[2]&&(t.blur=arguments[2]),void 0!==arguments[3]&&(t.color=arguments[3]),void 0!==arguments[4]&&(t.alpha=arguments[4])),t=Object.assign({rotation:45,distance:5,color:0,alpha:.5,shadowOnly:!1,kernels:null,blur:2,quality:3,pixelSize:1,resolution:r.settings.RESOLUTION},t),e.call(this);var o=t.kernels,i=t.blur,l=t.quality,s=t.pixelSize,a=t.resolution;this._tintFilter=new e(U,Z),this._tintFilter.uniforms.color=new Float32Array(4),this._tintFilter.uniforms.shift=new n.Point,this._tintFilter.resolution=a,this._blurFilter=o?new d(o):new d(i,l),this.pixelSize=s,this.resolution=a;var u=t.shadowOnly,c=t.rotation,f=t.distance,h=t.alpha,p=t.color;this.shadowOnly=u,this.rotation=c,this.distance=f,this.alpha=h,this.color=p,this._updatePadding()}e&&(t.__proto__=e),t.prototype=Object.create(e&&e.prototype),t.prototype.constructor=t;var i={resolution:{configurable:!0},distance:{configurable:!0},rotation:{configurable:!0},alpha:{configurable:!0},color:{configurable:!0},kernels:{configurable:!0},blur:{configurable:!0},quality:{configurable:!0},pixelSize:{configurable:!0}};return t.prototype.apply=function(e,t,n,r){var o=e.getFilterTexture();this._tintFilter.apply(e,t,o,!0),this._blurFilter.apply(e,o,n,r),!0!==this.shadowOnly&&e.applyFilter(this,t,n,!1),e.returnFilterTexture(o)},t.prototype._updatePadding=function(){this.padding=this.distance+2*this.blur},t.prototype._updateShift=function(){this._tintFilter.uniforms.shift.set(this.distance*Math.cos(this.angle),this.distance*Math.sin(this.angle))},i.resolution.get=function(){return this._resolution},i.resolution.set=function(e){this._resolution=e,this._tintFilter&&(this._tintFilter.resolution=e),this._blurFilter&&(this._blurFilter.resolution=e)},i.distance.get=function(){return this._distance},i.distance.set=function(e){this._distance=e,this._updatePadding(),this._updateShift()},i.rotation.get=function(){return this.angle/n.DEG_TO_RAD},i.rotation.set=function(e){this.angle=e*n.DEG_TO_RAD,this._updateShift()},i.alpha.get=function(){return this._tintFilter.uniforms.alpha},i.alpha.set=function(e){this._tintFilter.uniforms.alpha=e},i.color.get=function(){return o.rgb2hex(this._tintFilter.uniforms.color)},i.color.set=function(e){o.hex2rgb(e,this._tintFilter.uniforms.color)},i.kernels.get=function(){return this._blurFilter.kernels},i.kernels.set=function(e){this._blurFilter.kernels=e},i.blur.get=function(){return this._blurFilter.blur},i.blur.set=function(e){this._blurFilter.blur=e,this._updatePadding()},i.quality.get=function(){return this._blurFilter.quality},i.quality.set=function(e){this._blurFilter.quality=e},i.pixelSize.get=function(){return this._blurFilter.pixelSize},i.pixelSize.set=function(e){this._blurFilter.pixelSize=e},Object.defineProperties(t.prototype,i),t}(t.Filter),H=a,$="precision mediump float;\n\nvarying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\nuniform float strength;\nuniform vec4 filterArea;\n\n\nvoid main(void)\n{\n\tvec2 onePixel = vec2(1.0 / filterArea);\n\n\tvec4 color;\n\n\tcolor.rgb = vec3(0.5);\n\n\tcolor -= texture2D(uSampler, vTextureCoord - onePixel) * strength;\n\tcolor += texture2D(uSampler, vTextureCoord + onePixel) * strength;\n\n\tcolor.rgb = vec3((color.r + color.g + color.b) / 3.0);\n\n\tfloat alpha = texture2D(uSampler, vTextureCoord).a;\n\n\tgl_FragColor = vec4(color.rgb * alpha, alpha);\n}\n",J=function(e){function t(t){void 0===t&&(t=5),e.call(this,H,$),this.strength=t}e&&(t.__proto__=e),t.prototype=Object.create(e&&e.prototype),t.prototype.constructor=t;var n={strength:{configurable:!0}};return n.strength.get=function(){return this.uniforms.strength},n.strength.set=function(e){this.uniforms.strength=e},Object.defineProperties(t.prototype,n),t}(t.Filter),ee=a,te="// precision highp float;\n\nvarying vec2 vTextureCoord;\nuniform sampler2D uSampler;\n\nuniform vec4 filterArea;\nuniform vec4 filterClamp;\nuniform vec2 dimensions;\nuniform float aspect;\n\nuniform sampler2D displacementMap;\nuniform float offset;\nuniform float sinDir;\nuniform float cosDir;\nuniform int fillMode;\n\nuniform float seed;\nuniform vec2 red;\nuniform vec2 green;\nuniform vec2 blue;\n\nconst int TRANSPARENT = 0;\nconst int ORIGINAL = 1;\nconst int LOOP = 2;\nconst int CLAMP = 3;\nconst int MIRROR = 4;\n\nvoid main(void)\n{\n vec2 coord = (vTextureCoord * filterArea.xy) / dimensions;\n\n if (coord.x > 1.0 || coord.y > 1.0) {\n return;\n }\n\n float cx = coord.x - 0.5;\n float cy = (coord.y - 0.5) * aspect;\n float ny = (-sinDir * cx + cosDir * cy) / aspect + 0.5;\n\n // displacementMap: repeat\n // ny = ny > 1.0 ? ny - 1.0 : (ny < 0.0 ? 1.0 + ny : ny);\n\n // displacementMap: mirror\n ny = ny > 1.0 ? 2.0 - ny : (ny < 0.0 ? -ny : ny);\n\n vec4 dc = texture2D(displacementMap, vec2(0.5, ny));\n\n float displacement = (dc.r - dc.g) * (offset / filterArea.x);\n\n coord = vTextureCoord + vec2(cosDir * displacement, sinDir * displacement * aspect);\n\n if (fillMode == CLAMP) {\n coord = clamp(coord, filterClamp.xy, filterClamp.zw);\n } else {\n if( coord.x > filterClamp.z ) {\n if (fillMode == TRANSPARENT) {\n discard;\n } else if (fillMode == LOOP) {\n coord.x -= filterClamp.z;\n } else if (fillMode == MIRROR) {\n coord.x = filterClamp.z * 2.0 - coord.x;\n }\n } else if( coord.x < filterClamp.x ) {\n if (fillMode == TRANSPARENT) {\n discard;\n } else if (fillMode == LOOP) {\n coord.x += filterClamp.z;\n } else if (fillMode == MIRROR) {\n coord.x *= -filterClamp.z;\n }\n }\n\n if( coord.y > filterClamp.w ) {\n if (fillMode == TRANSPARENT) {\n discard;\n } else if (fillMode == LOOP) {\n coord.y -= filterClamp.w;\n } else if (fillMode == MIRROR) {\n coord.y = filterClamp.w * 2.0 - coord.y;\n }\n } else if( coord.y < filterClamp.y ) {\n if (fillMode == TRANSPARENT) {\n discard;\n } else if (fillMode == LOOP) {\n coord.y += filterClamp.w;\n } else if (fillMode == MIRROR) {\n coord.y *= -filterClamp.w;\n }\n }\n }\n\n gl_FragColor.r = texture2D(uSampler, coord + red * (1.0 - seed * 0.4) / filterArea.xy).r;\n gl_FragColor.g = texture2D(uSampler, coord + green * (1.0 - seed * 0.3) / filterArea.xy).g;\n gl_FragColor.b = texture2D(uSampler, coord + blue * (1.0 - seed * 0.2) / filterArea.xy).b;\n gl_FragColor.a = texture2D(uSampler, coord).a;\n}\n",ne=function(e){function r(n){void 0===n&&(n={}),e.call(this,ee,te),this.uniforms.dimensions=new Float32Array(2),n=Object.assign({slices:5,offset:100,direction:0,fillMode:0,average:!1,seed:0,red:[0,0],green:[0,0],blue:[0,0],minSize:8,sampleSize:512},n),this.direction=n.direction,this.red=n.red,this.green=n.green,this.blue=n.blue,this.offset=n.offset,this.fillMode=n.fillMode,this.average=n.average,this.seed=n.seed,this.minSize=n.minSize,this.sampleSize=n.sampleSize,this._canvas=document.createElement("canvas"),this._canvas.width=4,this._canvas.height=this.sampleSize,this.texture=t.Texture.from(this._canvas,{scaleMode:i.SCALE_MODES.NEAREST}),this._slices=0,this.slices=n.slices}e&&(r.__proto__=e),r.prototype=Object.create(e&&e.prototype),r.prototype.constructor=r;var o={sizes:{configurable:!0},offsets:{configurable:!0},slices:{configurable:!0},direction:{configurable:!0},red:{configurable:!0},green:{configurable:!0},blue:{configurable:!0}};return r.prototype.apply=function(e,t,n,r){var o=t.filterFrame.width,i=t.filterFrame.height;this.uniforms.dimensions[0]=o,this.uniforms.dimensions[1]=i,this.uniforms.aspect=i/o,this.uniforms.seed=this.seed,this.uniforms.offset=this.offset,this.uniforms.fillMode=this.fillMode,e.applyFilter(this,t,n,r)},r.prototype._randomizeSizes=function(){var e=this._sizes,t=this._slices-1,n=this.sampleSize,r=Math.min(this.minSize/n,.9/this._slices);if(this.average){for(var o=this._slices,i=1,l=0;l0;t--){var n=Math.random()*t>>0,r=e[t];e[t]=e[n],e[n]=r}},r.prototype._randomizeOffsets=function(){for(var e=0;e0?e:0,a=e<0?-e:0;r.fillStyle="rgba("+s+", "+a+", 0, 1)",r.fillRect(0,o>>0,t,l+1>>0),o+=l}n.baseTexture.update(),this.uniforms.displacementMap=n},o.sizes.set=function(e){for(var t=Math.min(this._slices,e.length),n=0;nthis._maxColors)throw"Length of replacements ("+r+") exceeds the maximum colors length ("+this._maxColors+")";t[3*r]=-1;for(var i=0;i 0.5) then: 1 - 2 * (1 - dst) * (1 - src)\n return vec3((dst.x <= 0.5) ? (2.0 * src.x * dst.x) : (1.0 - 2.0 * (1.0 - dst.x) * (1.0 - src.x)),\n (dst.y <= 0.5) ? (2.0 * src.y * dst.y) : (1.0 - 2.0 * (1.0 - dst.y) * (1.0 - src.y)),\n (dst.z <= 0.5) ? (2.0 * src.z * dst.z) : (1.0 - 2.0 * (1.0 - dst.z) * (1.0 - src.z)));\n}\n\n\nvoid main()\n{\n gl_FragColor = texture2D(uSampler, vTextureCoord);\n vec3 color = gl_FragColor.rgb;\n\n if (sepia > 0.0)\n {\n float gray = (color.x + color.y + color.z) / 3.0;\n vec3 grayscale = vec3(gray);\n\n color = Overlay(SEPIA_RGB, grayscale);\n\n color = grayscale + sepia * (color - grayscale);\n }\n\n vec2 coord = vTextureCoord * filterArea.xy / dimensions.xy;\n\n if (vignetting > 0.0)\n {\n float outter = SQRT_2 - vignetting * SQRT_2;\n vec2 dir = vec2(vec2(0.5, 0.5) - coord);\n dir.y *= dimensions.y / dimensions.x;\n float darker = clamp((outter - length(dir) * SQRT_2) / ( 0.00001 + vignettingBlur * SQRT_2), 0.0, 1.0);\n color.rgb *= darker + (1.0 - darker) * (1.0 - vignettingAlpha);\n }\n\n if (scratchDensity > seed && scratch != 0.0)\n {\n float phase = seed * 256.0;\n float s = mod(floor(phase), 2.0);\n float dist = 1.0 / scratchDensity;\n float d = distance(coord, vec2(seed * dist, abs(s - seed * dist)));\n if (d < seed * 0.6 + 0.4)\n {\n highp float period = scratchDensity * 10.0;\n\n float xx = coord.x * period + phase;\n float aa = abs(mod(xx, 0.5) * 4.0);\n float bb = mod(floor(xx / 0.5), 2.0);\n float yy = (1.0 - bb) * aa + bb * (2.0 - aa);\n\n float kk = 2.0 * period;\n float dw = scratchWidth / dimensions.x * (0.75 + seed);\n float dh = dw * kk;\n\n float tine = (yy - (2.0 - dh));\n\n if (tine > 0.0) {\n float _sign = sign(scratch);\n\n tine = s * tine / period + scratch + 0.1;\n tine = clamp(tine + 1.0, 0.5 + _sign * 0.5, 1.5 + _sign * 0.5);\n\n color.rgb *= tine;\n }\n }\n }\n\n if (noise > 0.0 && noiseSize > 0.0)\n {\n vec2 pixelCoord = vTextureCoord.xy * filterArea.xy;\n pixelCoord.x = floor(pixelCoord.x / noiseSize);\n pixelCoord.y = floor(pixelCoord.y / noiseSize);\n // vec2 d = pixelCoord * noiseSize * vec2(1024.0 + seed * 512.0, 1024.0 - seed * 512.0);\n // float _noise = snoise(d) * 0.5;\n float _noise = rand(pixelCoord * noiseSize * seed) - 0.5;\n color += _noise * noise;\n }\n\n gl_FragColor.rgb = color;\n}\n",xe=function(e){function t(t,n){void 0===n&&(n=0),e.call(this,ge,ve),this.uniforms.dimensions=new Float32Array(2),"number"==typeof t?(this.seed=t,t=null):this.seed=n,Object.assign(this,{sepia:.3,noise:.3,noiseSize:1,scratch:.5,scratchDensity:.3,scratchWidth:1,vignetting:.3,vignettingAlpha:1,vignettingBlur:.3},t)}e&&(t.__proto__=e),t.prototype=Object.create(e&&e.prototype),t.prototype.constructor=t;var n={sepia:{configurable:!0},noise:{configurable:!0},noiseSize:{configurable:!0},scratch:{configurable:!0},scratchDensity:{configurable:!0},scratchWidth:{configurable:!0},vignetting:{configurable:!0},vignettingAlpha:{configurable:!0},vignettingBlur:{configurable:!0}};return t.prototype.apply=function(e,t,n,r){this.uniforms.dimensions[0]=t.filterFrame.width,this.uniforms.dimensions[1]=t.filterFrame.height,this.uniforms.seed=this.seed,e.applyFilter(this,t,n,r)},n.sepia.set=function(e){this.uniforms.sepia=e},n.sepia.get=function(){return this.uniforms.sepia},n.noise.set=function(e){this.uniforms.noise=e},n.noise.get=function(){return this.uniforms.noise},n.noiseSize.set=function(e){this.uniforms.noiseSize=e},n.noiseSize.get=function(){return this.uniforms.noiseSize},n.scratch.set=function(e){this.uniforms.scratch=e},n.scratch.get=function(){return this.uniforms.scratch},n.scratchDensity.set=function(e){this.uniforms.scratchDensity=e},n.scratchDensity.get=function(){return this.uniforms.scratchDensity},n.scratchWidth.set=function(e){this.uniforms.scratchWidth=e},n.scratchWidth.get=function(){return this.uniforms.scratchWidth},n.vignetting.set=function(e){this.uniforms.vignetting=e},n.vignetting.get=function(){return this.uniforms.vignetting},n.vignettingAlpha.set=function(e){this.uniforms.vignettingAlpha=e},n.vignettingAlpha.get=function(){return this.uniforms.vignettingAlpha},n.vignettingBlur.set=function(e){this.uniforms.vignettingBlur=e},n.vignettingBlur.get=function(){return this.uniforms.vignettingBlur},Object.defineProperties(t.prototype,n),t}(t.Filter),ye=a,be="varying vec2 vTextureCoord;\nuniform sampler2D uSampler;\n\nuniform vec2 thickness;\nuniform vec4 outlineColor;\nuniform vec4 filterClamp;\n\nconst float DOUBLE_PI = 3.14159265358979323846264 * 2.;\n\nvoid main(void) {\n vec4 ownColor = texture2D(uSampler, vTextureCoord);\n vec4 curColor;\n float maxAlpha = 0.;\n vec2 displaced;\n for (float angle = 0.; angle <= DOUBLE_PI; angle += ${angleStep}) {\n displaced.x = vTextureCoord.x + thickness.x * cos(angle);\n displaced.y = vTextureCoord.y + thickness.y * sin(angle);\n curColor = texture2D(uSampler, clamp(displaced, filterClamp.xy, filterClamp.zw));\n maxAlpha = max(maxAlpha, curColor.a);\n }\n float resultAlpha = max(maxAlpha, ownColor.a);\n gl_FragColor = vec4((ownColor.rgb + outlineColor.rgb * (1. - ownColor.a)) * resultAlpha, resultAlpha);\n}\n",_e=function(e){function t(n,r,o){void 0===n&&(n=1),void 0===r&&(r=0),void 0===o&&(o=.1);var i=Math.max(o*t.MAX_SAMPLES,t.MIN_SAMPLES),l=(2*Math.PI/i).toFixed(7);e.call(this,ye,be.replace(/\$\{angleStep\}/,l)),this.uniforms.thickness=new Float32Array([0,0]),this.thickness=n,this.uniforms.outlineColor=new Float32Array([0,0,0,1]),this.color=r,this.quality=o}e&&(t.__proto__=e),t.prototype=Object.create(e&&e.prototype),t.prototype.constructor=t;var n={color:{configurable:!0}};return t.prototype.apply=function(e,t,n,r){this.uniforms.thickness[0]=this.thickness/t._frame.width,this.uniforms.thickness[1]=this.thickness/t._frame.height,e.applyFilter(this,t,n,r)},n.color.get=function(){return o.rgb2hex(this.uniforms.outlineColor)},n.color.set=function(e){o.hex2rgb(e,this.uniforms.outlineColor)},Object.defineProperties(t.prototype,n),t}(t.Filter);_e.MIN_SAMPLES=1,_e.MAX_SAMPLES=100;var Ce=a,Se="precision mediump float;\n\nvarying vec2 vTextureCoord;\n\nuniform vec2 size;\nuniform sampler2D uSampler;\n\nuniform vec4 filterArea;\n\nvec2 mapCoord( vec2 coord )\n{\n coord *= filterArea.xy;\n coord += filterArea.zw;\n\n return coord;\n}\n\nvec2 unmapCoord( vec2 coord )\n{\n coord -= filterArea.zw;\n coord /= filterArea.xy;\n\n return coord;\n}\n\nvec2 pixelate(vec2 coord, vec2 size)\n{\n\treturn floor( coord / size ) * size;\n}\n\nvoid main(void)\n{\n vec2 coord = mapCoord(vTextureCoord);\n\n coord = pixelate(coord, size);\n\n coord = unmapCoord(coord);\n\n gl_FragColor = texture2D(uSampler, coord);\n}\n",Fe=function(e){function t(t){void 0===t&&(t=10),e.call(this,Ce,Se),this.size=t}e&&(t.__proto__=e),t.prototype=Object.create(e&&e.prototype),t.prototype.constructor=t;var n={size:{configurable:!0}};return n.size.get=function(){return this.uniforms.size},n.size.set=function(e){"number"==typeof e&&(e=[e,e]),this.uniforms.size=e},Object.defineProperties(t.prototype,n),t}(t.Filter),ze=a,Ae="varying vec2 vTextureCoord;\nuniform sampler2D uSampler;\nuniform vec4 filterArea;\n\nuniform float uRadian;\nuniform vec2 uCenter;\nuniform float uRadius;\nuniform int uKernelSize;\n\nconst int MAX_KERNEL_SIZE = 2048;\n\nvoid main(void)\n{\n vec4 color = texture2D(uSampler, vTextureCoord);\n\n if (uKernelSize == 0)\n {\n gl_FragColor = color;\n return;\n }\n\n float aspect = filterArea.y / filterArea.x;\n vec2 center = uCenter.xy / filterArea.xy;\n float gradient = uRadius / filterArea.x * 0.3;\n float radius = uRadius / filterArea.x - gradient * 0.5;\n int k = uKernelSize - 1;\n\n vec2 coord = vTextureCoord;\n vec2 dir = vec2(center - coord);\n float dist = length(vec2(dir.x, dir.y * aspect));\n\n float radianStep = uRadian;\n if (radius >= 0.0 && dist > radius) {\n float delta = dist - radius;\n float gap = gradient;\n float scale = 1.0 - abs(delta / gap);\n if (scale <= 0.0) {\n gl_FragColor = color;\n return;\n }\n radianStep *= scale;\n }\n radianStep /= float(k);\n\n float s = sin(radianStep);\n float c = cos(radianStep);\n mat2 rotationMatrix = mat2(vec2(c, -s), vec2(s, c));\n\n for(int i = 0; i < MAX_KERNEL_SIZE - 1; i++) {\n if (i == k) {\n break;\n }\n\n coord -= center;\n coord.y *= aspect;\n coord = rotationMatrix * coord;\n coord.y /= aspect;\n coord += center;\n\n vec4 sample = texture2D(uSampler, coord);\n\n // switch to pre-multiplied alpha to correctly blur transparent images\n // sample.rgb *= sample.a;\n\n color += sample;\n }\n\n gl_FragColor = color / float(uKernelSize);\n}\n",we=function(e){function t(t,n,r,o){void 0===t&&(t=0),void 0===n&&(n=[0,0]),void 0===r&&(r=5),void 0===o&&(o=-1),e.call(this,ze,Ae),this._angle=0,this.angle=t,this.center=n,this.kernelSize=r,this.radius=o}e&&(t.__proto__=e),t.prototype=Object.create(e&&e.prototype),t.prototype.constructor=t;var n={angle:{configurable:!0},center:{configurable:!0},radius:{configurable:!0}};return t.prototype.apply=function(e,t,n,r){this.uniforms.uKernelSize=0!==this._angle?this.kernelSize:0,e.applyFilter(this,t,n,r)},n.angle.set=function(e){this._angle=e,this.uniforms.uRadian=e*Math.PI/180},n.angle.get=function(){return this._angle},n.center.get=function(){return this.uniforms.uCenter},n.center.set=function(e){this.uniforms.uCenter=e},n.radius.get=function(){return this.uniforms.uRadius},n.radius.set=function(e){(e<0||e===1/0)&&(e=-1),this.uniforms.uRadius=e},Object.defineProperties(t.prototype,n),t}(t.Filter),Te=a,De="varying vec2 vTextureCoord;\nuniform sampler2D uSampler;\n\nuniform vec4 filterArea;\nuniform vec4 filterClamp;\nuniform vec2 dimensions;\n\nuniform bool mirror;\nuniform float boundary;\nuniform vec2 amplitude;\nuniform vec2 waveLength;\nuniform vec2 alpha;\nuniform float time;\n\nfloat rand(vec2 co) {\n return fract(sin(dot(co.xy, vec2(12.9898, 78.233))) * 43758.5453);\n}\n\nvoid main(void)\n{\n vec2 pixelCoord = vTextureCoord.xy * filterArea.xy;\n vec2 coord = pixelCoord / dimensions;\n\n if (coord.y < boundary) {\n gl_FragColor = texture2D(uSampler, vTextureCoord);\n return;\n }\n\n float k = (coord.y - boundary) / (1. - boundary + 0.0001);\n float areaY = boundary * dimensions.y / filterArea.y;\n float v = areaY + areaY - vTextureCoord.y;\n float y = mirror ? v : vTextureCoord.y;\n\n float _amplitude = ((amplitude.y - amplitude.x) * k + amplitude.x ) / filterArea.x;\n float _waveLength = ((waveLength.y - waveLength.x) * k + waveLength.x) / filterArea.y;\n float _alpha = (alpha.y - alpha.x) * k + alpha.x;\n\n float x = vTextureCoord.x + cos(v * 6.28 / _waveLength - time) * _amplitude;\n x = clamp(x, filterClamp.x, filterClamp.z);\n\n vec4 color = texture2D(uSampler, vec2(x, y));\n\n gl_FragColor = color * _alpha;\n}\n",Oe=function(e){function t(t){e.call(this,Te,De),this.uniforms.amplitude=new Float32Array(2),this.uniforms.waveLength=new Float32Array(2),this.uniforms.alpha=new Float32Array(2),this.uniforms.dimensions=new Float32Array(2),Object.assign(this,{mirror:!0,boundary:.5,amplitude:[0,20],waveLength:[30,100],alpha:[1,1],time:0},t)}e&&(t.__proto__=e),t.prototype=Object.create(e&&e.prototype),t.prototype.constructor=t;var n={mirror:{configurable:!0},boundary:{configurable:!0},amplitude:{configurable:!0},waveLength:{configurable:!0},alpha:{configurable:!0}};return t.prototype.apply=function(e,t,n,r){this.uniforms.dimensions[0]=t.filterFrame.width,this.uniforms.dimensions[1]=t.filterFrame.height,this.uniforms.time=this.time,e.applyFilter(this,t,n,r)},n.mirror.set=function(e){this.uniforms.mirror=e},n.mirror.get=function(){return this.uniforms.mirror},n.boundary.set=function(e){this.uniforms.boundary=e},n.boundary.get=function(){return this.uniforms.boundary},n.amplitude.set=function(e){this.uniforms.amplitude[0]=e[0],this.uniforms.amplitude[1]=e[1]},n.amplitude.get=function(){return this.uniforms.amplitude},n.waveLength.set=function(e){this.uniforms.waveLength[0]=e[0],this.uniforms.waveLength[1]=e[1]},n.waveLength.get=function(){return this.uniforms.waveLength},n.alpha.set=function(e){this.uniforms.alpha[0]=e[0],this.uniforms.alpha[1]=e[1]},n.alpha.get=function(){return this.uniforms.alpha},Object.defineProperties(t.prototype,n),t}(t.Filter),Pe=a,Me="precision mediump float;\n\nvarying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\nuniform vec4 filterArea;\nuniform vec2 red;\nuniform vec2 green;\nuniform vec2 blue;\n\nvoid main(void)\n{\n gl_FragColor.r = texture2D(uSampler, vTextureCoord + red/filterArea.xy).r;\n gl_FragColor.g = texture2D(uSampler, vTextureCoord + green/filterArea.xy).g;\n gl_FragColor.b = texture2D(uSampler, vTextureCoord + blue/filterArea.xy).b;\n gl_FragColor.a = texture2D(uSampler, vTextureCoord).a;\n}\n",Re=function(e){function t(t,n,r){void 0===t&&(t=[-10,0]),void 0===n&&(n=[0,10]),void 0===r&&(r=[0,0]),e.call(this,Pe,Me),this.red=t,this.green=n,this.blue=r}e&&(t.__proto__=e),t.prototype=Object.create(e&&e.prototype),t.prototype.constructor=t;var n={red:{configurable:!0},green:{configurable:!0},blue:{configurable:!0}};return n.red.get=function(){return this.uniforms.red},n.red.set=function(e){this.uniforms.red=e},n.green.get=function(){return this.uniforms.green},n.green.set=function(e){this.uniforms.green=e},n.blue.get=function(){return this.uniforms.blue},n.blue.set=function(e){this.uniforms.blue=e},Object.defineProperties(t.prototype,n),t}(t.Filter),je=a,ke="varying vec2 vTextureCoord;\nuniform sampler2D uSampler;\nuniform vec4 filterArea;\nuniform vec4 filterClamp;\n\nuniform vec2 center;\n\nuniform float amplitude;\nuniform float wavelength;\n// uniform float power;\nuniform float brightness;\nuniform float speed;\nuniform float radius;\n\nuniform float time;\n\nconst float PI = 3.14159;\n\nvoid main()\n{\n float halfWavelength = wavelength * 0.5 / filterArea.x;\n float maxRadius = radius / filterArea.x;\n float currentRadius = time * speed / filterArea.x;\n\n float fade = 1.0;\n\n if (maxRadius > 0.0) {\n if (currentRadius > maxRadius) {\n gl_FragColor = texture2D(uSampler, vTextureCoord);\n return;\n }\n fade = 1.0 - pow(currentRadius / maxRadius, 2.0);\n }\n\n vec2 dir = vec2(vTextureCoord - center / filterArea.xy);\n dir.y *= filterArea.y / filterArea.x;\n float dist = length(dir);\n\n if (dist <= 0.0 || dist < currentRadius - halfWavelength || dist > currentRadius + halfWavelength) {\n gl_FragColor = texture2D(uSampler, vTextureCoord);\n return;\n }\n\n vec2 diffUV = normalize(dir);\n\n float diff = (dist - currentRadius) / halfWavelength;\n\n float p = 1.0 - pow(abs(diff), 2.0);\n\n // float powDiff = diff * pow(p, 2.0) * ( amplitude * fade );\n float powDiff = 1.25 * sin(diff * PI) * p * ( amplitude * fade );\n\n vec2 offset = diffUV * powDiff / filterArea.xy;\n\n // Do clamp :\n vec2 coord = vTextureCoord + offset;\n vec2 clampedCoord = clamp(coord, filterClamp.xy, filterClamp.zw);\n vec4 color = texture2D(uSampler, clampedCoord);\n if (coord != clampedCoord) {\n color *= max(0.0, 1.0 - length(coord - clampedCoord));\n }\n\n // No clamp :\n // gl_FragColor = texture2D(uSampler, vTextureCoord + offset);\n\n color.rgb *= 1.0 + (brightness - 1.0) * p * fade;\n\n gl_FragColor = color;\n}\n",Le=function(e){function t(t,n,r){void 0===t&&(t=[0,0]),void 0===n&&(n={}),void 0===r&&(r=0),e.call(this,je,ke),this.center=t,Array.isArray(n)&&(console.warn("Deprecated Warning: ShockwaveFilter params Array has been changed to options Object."),n={}),n=Object.assign({amplitude:30,wavelength:160,brightness:1,speed:500,radius:-1},n),this.amplitude=n.amplitude,this.wavelength=n.wavelength,this.brightness=n.brightness,this.speed=n.speed,this.radius=n.radius,this.time=r}e&&(t.__proto__=e),t.prototype=Object.create(e&&e.prototype),t.prototype.constructor=t;var n={center:{configurable:!0},amplitude:{configurable:!0},wavelength:{configurable:!0},brightness:{configurable:!0},speed:{configurable:!0},radius:{configurable:!0}};return t.prototype.apply=function(e,t,n,r){this.uniforms.time=this.time,e.applyFilter(this,t,n,r)},n.center.get=function(){return this.uniforms.center},n.center.set=function(e){this.uniforms.center=e},n.amplitude.get=function(){return this.uniforms.amplitude},n.amplitude.set=function(e){this.uniforms.amplitude=e},n.wavelength.get=function(){return this.uniforms.wavelength},n.wavelength.set=function(e){this.uniforms.wavelength=e},n.brightness.get=function(){return this.uniforms.brightness},n.brightness.set=function(e){this.uniforms.brightness=e},n.speed.get=function(){return this.uniforms.speed},n.speed.set=function(e){this.uniforms.speed=e},n.radius.get=function(){return this.uniforms.radius},n.radius.set=function(e){this.uniforms.radius=e},Object.defineProperties(t.prototype,n),t}(t.Filter),Ie=a,Ee="varying vec2 vTextureCoord;\nuniform sampler2D uSampler;\nuniform sampler2D uLightmap;\nuniform vec4 filterArea;\nuniform vec2 dimensions;\nuniform vec4 ambientColor;\nvoid main() {\n vec4 diffuseColor = texture2D(uSampler, vTextureCoord);\n vec2 lightCoord = (vTextureCoord * filterArea.xy) / dimensions;\n vec4 light = texture2D(uLightmap, lightCoord);\n vec3 ambient = ambientColor.rgb * ambientColor.a;\n vec3 intensity = ambient + light.rgb;\n vec3 finalColor = diffuseColor.rgb * intensity;\n gl_FragColor = vec4(finalColor, diffuseColor.a);\n}\n",Be=function(e){function t(t,n,r){void 0===n&&(n=0),void 0===r&&(r=1),e.call(this,Ie,Ee),this.uniforms.dimensions=new Float32Array(2),this.uniforms.ambientColor=new Float32Array([0,0,0,r]),this.texture=t,this.color=n}e&&(t.__proto__=e),t.prototype=Object.create(e&&e.prototype),t.prototype.constructor=t;var n={texture:{configurable:!0},color:{configurable:!0},alpha:{configurable:!0}};return t.prototype.apply=function(e,t,n,r){this.uniforms.dimensions[0]=t.filterFrame.width,this.uniforms.dimensions[1]=t.filterFrame.height,e.applyFilter(this,t,n,r)},n.texture.get=function(){return this.uniforms.uLightmap},n.texture.set=function(e){this.uniforms.uLightmap=e},n.color.set=function(e){var t=this.uniforms.ambientColor;"number"==typeof e?(o.hex2rgb(e,t),this._color=e):(t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=e[3],this._color=o.rgb2hex(t))},n.color.get=function(){return this._color},n.alpha.get=function(){return this.uniforms.ambientColor[3]},n.alpha.set=function(e){this.uniforms.ambientColor[3]=e},Object.defineProperties(t.prototype,n),t}(t.Filter),Xe=a,Ne="varying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\nuniform float blur;\nuniform float gradientBlur;\nuniform vec2 start;\nuniform vec2 end;\nuniform vec2 delta;\nuniform vec2 texSize;\n\nfloat random(vec3 scale, float seed)\n{\n return fract(sin(dot(gl_FragCoord.xyz + seed, scale)) * 43758.5453 + seed);\n}\n\nvoid main(void)\n{\n vec4 color = vec4(0.0);\n float total = 0.0;\n\n float offset = random(vec3(12.9898, 78.233, 151.7182), 0.0);\n vec2 normal = normalize(vec2(start.y - end.y, end.x - start.x));\n float radius = smoothstep(0.0, 1.0, abs(dot(vTextureCoord * texSize - start, normal)) / gradientBlur) * blur;\n\n for (float t = -30.0; t <= 30.0; t++)\n {\n float percent = (t + offset - 0.5) / 30.0;\n float weight = 1.0 - abs(percent);\n vec4 sample = texture2D(uSampler, vTextureCoord + delta / texSize * percent * radius);\n sample.rgb *= sample.a;\n color += sample * weight;\n total += weight;\n }\n\n color /= total;\n color.rgb /= color.a + 0.00001;\n\n gl_FragColor = color;\n}\n",qe=function(e){function t(t,r,o,i){void 0===t&&(t=100),void 0===r&&(r=600),void 0===o&&(o=null),void 0===i&&(i=null),e.call(this,Xe,Ne),this.uniforms.blur=t,this.uniforms.gradientBlur=r,this.uniforms.start=o||new n.Point(0,window.innerHeight/2),this.uniforms.end=i||new n.Point(600,window.innerHeight/2),this.uniforms.delta=new n.Point(30,30),this.uniforms.texSize=new n.Point(window.innerWidth,window.innerHeight),this.updateDelta()}e&&(t.__proto__=e),t.prototype=Object.create(e&&e.prototype),t.prototype.constructor=t;var r={blur:{configurable:!0},gradientBlur:{configurable:!0},start:{configurable:!0},end:{configurable:!0}};return t.prototype.updateDelta=function(){this.uniforms.delta.x=0,this.uniforms.delta.y=0},r.blur.get=function(){return this.uniforms.blur},r.blur.set=function(e){this.uniforms.blur=e},r.gradientBlur.get=function(){return this.uniforms.gradientBlur},r.gradientBlur.set=function(e){this.uniforms.gradientBlur=e},r.start.get=function(){return this.uniforms.start},r.start.set=function(e){this.uniforms.start=e,this.updateDelta()},r.end.get=function(){return this.uniforms.end},r.end.set=function(e){this.uniforms.end=e,this.updateDelta()},Object.defineProperties(t.prototype,r),t}(t.Filter),We=function(e){function t(){e.apply(this,arguments)}return e&&(t.__proto__=e),t.prototype=Object.create(e&&e.prototype),t.prototype.constructor=t,t.prototype.updateDelta=function(){var e=this.uniforms.end.x-this.uniforms.start.x,t=this.uniforms.end.y-this.uniforms.start.y,n=Math.sqrt(e*e+t*t);this.uniforms.delta.x=e/n,this.uniforms.delta.y=t/n},t}(qe),Ke=function(e){function t(){e.apply(this,arguments)}return e&&(t.__proto__=e),t.prototype=Object.create(e&&e.prototype),t.prototype.constructor=t,t.prototype.updateDelta=function(){var e=this.uniforms.end.x-this.uniforms.start.x,t=this.uniforms.end.y-this.uniforms.start.y,n=Math.sqrt(e*e+t*t);this.uniforms.delta.x=-t/n,this.uniforms.delta.y=e/n},t}(qe),Ye=function(e){function t(t,n,r,o){void 0===t&&(t=100),void 0===n&&(n=600),void 0===r&&(r=null),void 0===o&&(o=null),e.call(this),this.tiltShiftXFilter=new We(t,n,r,o),this.tiltShiftYFilter=new Ke(t,n,r,o)}e&&(t.__proto__=e),t.prototype=Object.create(e&&e.prototype),t.prototype.constructor=t;var n={blur:{configurable:!0},gradientBlur:{configurable:!0},start:{configurable:!0},end:{configurable:!0}};return t.prototype.apply=function(e,t,n){var r=e.getFilterTexture();this.tiltShiftXFilter.apply(e,t,r),this.tiltShiftYFilter.apply(e,r,n),e.returnFilterTexture(r)},n.blur.get=function(){return this.tiltShiftXFilter.blur},n.blur.set=function(e){this.tiltShiftXFilter.blur=this.tiltShiftYFilter.blur=e},n.gradientBlur.get=function(){return this.tiltShiftXFilter.gradientBlur},n.gradientBlur.set=function(e){this.tiltShiftXFilter.gradientBlur=this.tiltShiftYFilter.gradientBlur=e},n.start.get=function(){return this.tiltShiftXFilter.start},n.start.set=function(e){this.tiltShiftXFilter.start=this.tiltShiftYFilter.start=e},n.end.get=function(){return this.tiltShiftXFilter.end},n.end.set=function(e){this.tiltShiftXFilter.end=this.tiltShiftYFilter.end=e},Object.defineProperties(t.prototype,n),t}(t.Filter),Ge=a,Qe="varying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\nuniform float radius;\nuniform float angle;\nuniform vec2 offset;\nuniform vec4 filterArea;\n\nvec2 mapCoord( vec2 coord )\n{\n coord *= filterArea.xy;\n coord += filterArea.zw;\n\n return coord;\n}\n\nvec2 unmapCoord( vec2 coord )\n{\n coord -= filterArea.zw;\n coord /= filterArea.xy;\n\n return coord;\n}\n\nvec2 twist(vec2 coord)\n{\n coord -= offset;\n\n float dist = length(coord);\n\n if (dist < radius)\n {\n float ratioDist = (radius - dist) / radius;\n float angleMod = ratioDist * ratioDist * angle;\n float s = sin(angleMod);\n float c = cos(angleMod);\n coord = vec2(coord.x * c - coord.y * s, coord.x * s + coord.y * c);\n }\n\n coord += offset;\n\n return coord;\n}\n\nvoid main(void)\n{\n\n vec2 coord = mapCoord(vTextureCoord);\n\n coord = twist(coord);\n\n coord = unmapCoord(coord);\n\n gl_FragColor = texture2D(uSampler, coord );\n\n}\n",Ue=function(e){function t(t,n,r){void 0===t&&(t=200),void 0===n&&(n=4),void 0===r&&(r=20),e.call(this,Ge,Qe),this.radius=t,this.angle=n,this.padding=r}e&&(t.__proto__=e),t.prototype=Object.create(e&&e.prototype),t.prototype.constructor=t;var n={offset:{configurable:!0},radius:{configurable:!0},angle:{configurable:!0}};return n.offset.get=function(){return this.uniforms.offset},n.offset.set=function(e){this.uniforms.offset=e},n.radius.get=function(){return this.uniforms.radius},n.radius.set=function(e){this.uniforms.radius=e},n.angle.get=function(){return this.uniforms.angle},n.angle.set=function(e){this.uniforms.angle=e},Object.defineProperties(t.prototype,n),t}(t.Filter),Ze=a,Ve="varying vec2 vTextureCoord;\nuniform sampler2D uSampler;\nuniform vec4 filterArea;\n\nuniform vec2 uCenter;\nuniform float uStrength;\nuniform float uInnerRadius;\nuniform float uRadius;\n\nconst float MAX_KERNEL_SIZE = 32.0;\n\n// author: http://byteblacksmith.com/improvements-to-the-canonical-one-liner-glsl-rand-for-opengl-es-2-0/\nhighp float rand(vec2 co, float seed) {\n const highp float a = 12.9898, b = 78.233, c = 43758.5453;\n highp float dt = dot(co + seed, vec2(a, b)), sn = mod(dt, 3.14159);\n return fract(sin(sn) * c + seed);\n}\n\nvoid main() {\n\n float minGradient = uInnerRadius * 0.3;\n float innerRadius = (uInnerRadius + minGradient * 0.5) / filterArea.x;\n\n float gradient = uRadius * 0.3;\n float radius = (uRadius - gradient * 0.5) / filterArea.x;\n\n float countLimit = MAX_KERNEL_SIZE;\n\n vec2 dir = vec2(uCenter.xy / filterArea.xy - vTextureCoord);\n float dist = length(vec2(dir.x, dir.y * filterArea.y / filterArea.x));\n\n float strength = uStrength;\n\n float delta = 0.0;\n float gap;\n if (dist < innerRadius) {\n delta = innerRadius - dist;\n gap = minGradient;\n } else if (radius >= 0.0 && dist > radius) { // radius < 0 means it's infinity\n delta = dist - radius;\n gap = gradient;\n }\n\n if (delta > 0.0) {\n float normalCount = gap / filterArea.x;\n delta = (normalCount - delta) / normalCount;\n countLimit *= delta;\n strength *= delta;\n if (countLimit < 1.0)\n {\n gl_FragColor = texture2D(uSampler, vTextureCoord);\n return;\n }\n }\n\n // randomize the lookup values to hide the fixed number of samples\n float offset = rand(vTextureCoord, 0.0);\n\n float total = 0.0;\n vec4 color = vec4(0.0);\n\n dir *= strength;\n\n for (float t = 0.0; t < MAX_KERNEL_SIZE; t++) {\n float percent = (t + offset) / MAX_KERNEL_SIZE;\n float weight = 4.0 * (percent - percent * percent);\n vec2 p = vTextureCoord + dir * percent;\n vec4 sample = texture2D(uSampler, p);\n\n // switch to pre-multiplied alpha to correctly blur transparent images\n // sample.rgb *= sample.a;\n\n color += sample * weight;\n total += weight;\n\n if (t > countLimit){\n break;\n }\n }\n\n color /= total;\n // switch back from pre-multiplied alpha\n // color.rgb /= color.a + 0.00001;\n\n gl_FragColor = color;\n}\n",He=function(e){function t(t,n,r,o){void 0===t&&(t=.1),void 0===n&&(n=[0,0]),void 0===r&&(r=0),void 0===o&&(o=-1),e.call(this,Ze,Ve),this.center=n,this.strength=t,this.innerRadius=r,this.radius=o}e&&(t.__proto__=e),t.prototype=Object.create(e&&e.prototype),t.prototype.constructor=t;var n={center:{configurable:!0},strength:{configurable:!0},innerRadius:{configurable:!0},radius:{configurable:!0}};return n.center.get=function(){return this.uniforms.uCenter},n.center.set=function(e){this.uniforms.uCenter=e},n.strength.get=function(){return this.uniforms.uStrength},n.strength.set=function(e){this.uniforms.uStrength=e},n.innerRadius.get=function(){return this.uniforms.uInnerRadius},n.innerRadius.set=function(e){this.uniforms.uInnerRadius=e},n.radius.get=function(){return this.uniforms.uRadius},n.radius.set=function(e){(e<0||e===1/0)&&(e=-1),this.uniforms.uRadius=e},Object.defineProperties(t.prototype,n),t}(t.Filter);return e.AdjustmentFilter=c,e.AdvancedBloomFilter=y,e.AsciiFilter=C,e.BevelFilter=z,e.BloomFilter=A,e.BulgePinchFilter=D,e.CRTFilter=K,e.ColorMapFilter=M,e.ColorReplaceFilter=k,e.ConvolutionFilter=E,e.CrossHatchFilter=N,e.DotFilter=Q,e.DropShadowFilter=V,e.EmbossFilter=J,e.GlitchFilter=ne,e.GlowFilter=ie,e.GodrayFilter=ue,e.KawaseBlurFilter=d,e.MotionBlurFilter=he,e.MultiColorReplaceFilter=me,e.OldFilmFilter=xe,e.OutlineFilter=_e,e.PixelateFilter=Fe,e.RGBSplitFilter=Re,e.RadialBlurFilter=we,e.ReflectionFilter=Oe,e.ShockwaveFilter=Le,e.SimpleLightmapFilter=Be,e.TiltShiftAxisFilter=qe,e.TiltShiftFilter=Ye,e.TiltShiftXFilter=We,e.TiltShiftYFilter=Ke,e.TwistFilter=Ue,e.ZoomBlurFilter=He,e}({},PIXI,PIXI,PIXI,PIXI.utils,PIXI,PIXI.filters,PIXI.filters);Object.assign(PIXI.filters,__filters); +var __filters=function(e,n,t,r,o,i,l,a){"use strict";var s=function(e,n){return(s=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,n){e.__proto__=n}||function(e,n){for(var t in n)Object.prototype.hasOwnProperty.call(n,t)&&(e[t]=n[t])})(e,n)};function u(e,n){function t(){this.constructor=e}s(e,n),e.prototype=null===n?Object.create(n):(t.prototype=n.prototype,new t)}var f=function(){return(f=Object.assign||function(e){for(var n,t=arguments,r=1,o=arguments.length;r 0.0) {\n c.rgb /= c.a;\n\n vec3 rgb = pow(c.rgb, vec3(1. / gamma));\n rgb = mix(vec3(.5), mix(vec3(dot(vec3(.2125, .7154, .0721), rgb)), rgb, saturation), contrast);\n rgb.r *= red;\n rgb.g *= green;\n rgb.b *= blue;\n c.rgb = rgb * brightness;\n\n c.rgb *= c.a;\n }\n\n gl_FragColor = c * alpha;\n}\n")||this;return t.gamma=1,t.saturation=1,t.contrast=1,t.brightness=1,t.red=1,t.green=1,t.blue=1,t.alpha=1,Object.assign(t,n),t}return u(n,e),n.prototype.apply=function(e,n,t,r){this.uniforms.gamma=Math.max(this.gamma,1e-4),this.uniforms.saturation=this.saturation,this.uniforms.contrast=this.contrast,this.uniforms.brightness=this.brightness,this.uniforms.red=this.red,this.uniforms.green=this.green,this.uniforms.blue=this.blue,this.uniforms.alpha=this.alpha,e.applyFilter(this,n,t,r)},n}(n.Filter),p=function(e){function n(n){void 0===n&&(n=.5);var t=e.call(this,c,"\nuniform sampler2D uSampler;\nvarying vec2 vTextureCoord;\n\nuniform float threshold;\n\nvoid main() {\n vec4 color = texture2D(uSampler, vTextureCoord);\n\n // A simple & fast algorithm for getting brightness.\n // It's inaccuracy , but good enought for this feature.\n float _max = max(max(color.r, color.g), color.b);\n float _min = min(min(color.r, color.g), color.b);\n float brightness = (_max + _min) * 0.5;\n\n if(brightness > threshold) {\n gl_FragColor = color;\n } else {\n gl_FragColor = vec4(0.0, 0.0, 0.0, 0.0);\n }\n}\n")||this;return t.threshold=n,t}return u(n,e),Object.defineProperty(n.prototype,"threshold",{get:function(){return this.uniforms.threshold},set:function(e){this.uniforms.threshold=e},enumerable:!1,configurable:!0}),n}(n.Filter),d=function(e){function n(n,r,o){void 0===n&&(n=4),void 0===r&&(r=3),void 0===o&&(o=!1);var i=e.call(this,c,o?"\nvarying vec2 vTextureCoord;\nuniform sampler2D uSampler;\n\nuniform vec2 uOffset;\nuniform vec4 filterClamp;\n\nvoid main(void)\n{\n vec4 color = vec4(0.0);\n\n // Sample top left pixel\n color += texture2D(uSampler, clamp(vec2(vTextureCoord.x - uOffset.x, vTextureCoord.y + uOffset.y), filterClamp.xy, filterClamp.zw));\n\n // Sample top right pixel\n color += texture2D(uSampler, clamp(vec2(vTextureCoord.x + uOffset.x, vTextureCoord.y + uOffset.y), filterClamp.xy, filterClamp.zw));\n\n // Sample bottom right pixel\n color += texture2D(uSampler, clamp(vec2(vTextureCoord.x + uOffset.x, vTextureCoord.y - uOffset.y), filterClamp.xy, filterClamp.zw));\n\n // Sample bottom left pixel\n color += texture2D(uSampler, clamp(vec2(vTextureCoord.x - uOffset.x, vTextureCoord.y - uOffset.y), filterClamp.xy, filterClamp.zw));\n\n // Average\n color *= 0.25;\n\n gl_FragColor = color;\n}\n":"\nvarying vec2 vTextureCoord;\nuniform sampler2D uSampler;\n\nuniform vec2 uOffset;\n\nvoid main(void)\n{\n vec4 color = vec4(0.0);\n\n // Sample top left pixel\n color += texture2D(uSampler, vec2(vTextureCoord.x - uOffset.x, vTextureCoord.y + uOffset.y));\n\n // Sample top right pixel\n color += texture2D(uSampler, vec2(vTextureCoord.x + uOffset.x, vTextureCoord.y + uOffset.y));\n\n // Sample bottom right pixel\n color += texture2D(uSampler, vec2(vTextureCoord.x + uOffset.x, vTextureCoord.y - uOffset.y));\n\n // Sample bottom left pixel\n color += texture2D(uSampler, vec2(vTextureCoord.x - uOffset.x, vTextureCoord.y - uOffset.y));\n\n // Average\n color *= 0.25;\n\n gl_FragColor = color;\n}")||this;return i._kernels=[],i._blur=4,i._quality=3,i.uniforms.uOffset=new Float32Array(2),i._pixelSize=new t.Point,i.pixelSize=1,i._clamp=o,Array.isArray(n)?i.kernels=n:(i._blur=n,i.quality=r),i}return u(n,e),n.prototype.apply=function(e,n,t,r){var o,i=this._pixelSize.x/n._frame.width,l=this._pixelSize.y/n._frame.height;if(1===this._quality||0===this._blur)o=this._kernels[0]+.5,this.uniforms.uOffset[0]=o*i,this.uniforms.uOffset[1]=o*l,e.applyFilter(this,n,t,r);else{for(var a=e.getFilterTexture(),s=n,u=a,f=void 0,c=this._quality-1,m=0;m0)for(var r=e,o=e/n,i=1;i0?(this._kernels=e,this._quality=e.length,this._blur=Math.max.apply(Math,e)):(this._kernels=[0],this._quality=1)},enumerable:!1,configurable:!0}),Object.defineProperty(n.prototype,"clamp",{get:function(){return this._clamp},enumerable:!1,configurable:!0}),Object.defineProperty(n.prototype,"pixelSize",{get:function(){return this._pixelSize},set:function(e){"number"==typeof e?(this._pixelSize.x=e,this._pixelSize.y=e):Array.isArray(e)?(this._pixelSize.x=e[0],this._pixelSize.y=e[1]):e instanceof t.Point?(this._pixelSize.x=e.x,this._pixelSize.y=e.y):(this._pixelSize.x=1,this._pixelSize.y=1)},enumerable:!1,configurable:!0}),Object.defineProperty(n.prototype,"quality",{get:function(){return this._quality},set:function(e){this._quality=Math.max(1,Math.round(e)),this._generateKernels()},enumerable:!1,configurable:!0}),Object.defineProperty(n.prototype,"blur",{get:function(){return this._blur},set:function(e){this._blur=e,this._generateKernels()},enumerable:!1,configurable:!0}),n}(n.Filter),h=function(e){function n(t){var o=e.call(this,c,"uniform sampler2D uSampler;\nvarying vec2 vTextureCoord;\n\nuniform sampler2D bloomTexture;\nuniform float bloomScale;\nuniform float brightness;\n\nvoid main() {\n vec4 color = texture2D(uSampler, vTextureCoord);\n color.rgb *= brightness;\n vec4 bloomColor = vec4(texture2D(bloomTexture, vTextureCoord).rgb, 0.0);\n bloomColor.rgb *= bloomScale;\n gl_FragColor = color + bloomColor;\n}\n")||this;o.bloomScale=1,o.brightness=1,o._resolution=r.settings.FILTER_RESOLUTION,"number"==typeof t&&(t={threshold:t});var i=Object.assign(n.defaults,t);o.bloomScale=i.bloomScale,o.brightness=i.brightness;var l=i.kernels,a=i.blur,s=i.quality,u=i.pixelSize,f=i.resolution;return o._extractFilter=new p(i.threshold),o._extractFilter.resolution=f,o._blurFilter=l?new d(l):new d(a,s),o.pixelSize=u,o.resolution=f,o}return u(n,e),n.prototype.apply=function(e,n,t,r,o){var i=e.getFilterTexture();this._extractFilter.apply(e,n,i,1,o);var l=e.getFilterTexture();this._blurFilter.apply(e,i,l,1),this.uniforms.bloomScale=this.bloomScale,this.uniforms.brightness=this.brightness,this.uniforms.bloomTexture=l,e.applyFilter(this,n,t,r),e.returnFilterTexture(l),e.returnFilterTexture(i)},Object.defineProperty(n.prototype,"resolution",{get:function(){return this._resolution},set:function(e){this._resolution=e,this._extractFilter&&(this._extractFilter.resolution=e),this._blurFilter&&(this._blurFilter.resolution=e)},enumerable:!1,configurable:!0}),Object.defineProperty(n.prototype,"threshold",{get:function(){return this._extractFilter.threshold},set:function(e){this._extractFilter.threshold=e},enumerable:!1,configurable:!0}),Object.defineProperty(n.prototype,"kernels",{get:function(){return this._blurFilter.kernels},set:function(e){this._blurFilter.kernels=e},enumerable:!1,configurable:!0}),Object.defineProperty(n.prototype,"blur",{get:function(){return this._blurFilter.blur},set:function(e){this._blurFilter.blur=e},enumerable:!1,configurable:!0}),Object.defineProperty(n.prototype,"quality",{get:function(){return this._blurFilter.quality},set:function(e){this._blurFilter.quality=e},enumerable:!1,configurable:!0}),Object.defineProperty(n.prototype,"pixelSize",{get:function(){return this._blurFilter.pixelSize},set:function(e){this._blurFilter.pixelSize=e},enumerable:!1,configurable:!0}),n.defaults={threshold:.5,bloomScale:1,brightness:1,kernels:null,blur:8,quality:4,pixelSize:1,resolution:r.settings.FILTER_RESOLUTION},n}(n.Filter),g=function(e){function n(n){void 0===n&&(n=8);var t=e.call(this,c,"varying vec2 vTextureCoord;\n\nuniform vec4 filterArea;\nuniform float pixelSize;\nuniform sampler2D uSampler;\n\nvec2 mapCoord( vec2 coord )\n{\n coord *= filterArea.xy;\n coord += filterArea.zw;\n\n return coord;\n}\n\nvec2 unmapCoord( vec2 coord )\n{\n coord -= filterArea.zw;\n coord /= filterArea.xy;\n\n return coord;\n}\n\nvec2 pixelate(vec2 coord, vec2 size)\n{\n return floor( coord / size ) * size;\n}\n\nvec2 getMod(vec2 coord, vec2 size)\n{\n return mod( coord , size) / size;\n}\n\nfloat character(float n, vec2 p)\n{\n p = floor(p*vec2(4.0, -4.0) + 2.5);\n\n if (clamp(p.x, 0.0, 4.0) == p.x)\n {\n if (clamp(p.y, 0.0, 4.0) == p.y)\n {\n if (int(mod(n/exp2(p.x + 5.0*p.y), 2.0)) == 1) return 1.0;\n }\n }\n return 0.0;\n}\n\nvoid main()\n{\n vec2 coord = mapCoord(vTextureCoord);\n\n // get the rounded color..\n vec2 pixCoord = pixelate(coord, vec2(pixelSize));\n pixCoord = unmapCoord(pixCoord);\n\n vec4 color = texture2D(uSampler, pixCoord);\n\n // determine the character to use\n float gray = (color.r + color.g + color.b) / 3.0;\n\n float n = 65536.0; // .\n if (gray > 0.2) n = 65600.0; // :\n if (gray > 0.3) n = 332772.0; // *\n if (gray > 0.4) n = 15255086.0; // o\n if (gray > 0.5) n = 23385164.0; // &\n if (gray > 0.6) n = 15252014.0; // 8\n if (gray > 0.7) n = 13199452.0; // @\n if (gray > 0.8) n = 11512810.0; // #\n\n // get the mod..\n vec2 modd = getMod(coord, vec2(pixelSize));\n\n gl_FragColor = color * character( n, vec2(-1.0) + modd * 2.0);\n\n}\n")||this;return t.size=n,t}return u(n,e),Object.defineProperty(n.prototype,"size",{get:function(){return this.uniforms.pixelSize},set:function(e){this.uniforms.pixelSize=e},enumerable:!1,configurable:!0}),n}(n.Filter),v=function(e){function n(n){var t=e.call(this,c,"precision mediump float;\n\nvarying vec2 vTextureCoord;\nuniform sampler2D uSampler;\nuniform vec4 filterArea;\n\nuniform float transformX;\nuniform float transformY;\nuniform vec3 lightColor;\nuniform float lightAlpha;\nuniform vec3 shadowColor;\nuniform float shadowAlpha;\n\nvoid main(void) {\n vec2 transform = vec2(1.0 / filterArea) * vec2(transformX, transformY);\n vec4 color = texture2D(uSampler, vTextureCoord);\n float light = texture2D(uSampler, vTextureCoord - transform).a;\n float shadow = texture2D(uSampler, vTextureCoord + transform).a;\n\n color.rgb = mix(color.rgb, lightColor, clamp((color.a - light) * lightAlpha, 0.0, 1.0));\n color.rgb = mix(color.rgb, shadowColor, clamp((color.a - shadow) * shadowAlpha, 0.0, 1.0));\n gl_FragColor = vec4(color.rgb * color.a, color.a);\n}\n")||this;return t._thickness=2,t._angle=0,t.uniforms.lightColor=new Float32Array(3),t.uniforms.shadowColor=new Float32Array(3),Object.assign(t,{rotation:45,thickness:2,lightColor:16777215,lightAlpha:.7,shadowColor:0,shadowAlpha:.7},n),t.padding=1,t}return u(n,e),n.prototype._updateTransform=function(){this.uniforms.transformX=this._thickness*Math.cos(this._angle),this.uniforms.transformY=this._thickness*Math.sin(this._angle)},Object.defineProperty(n.prototype,"rotation",{get:function(){return this._angle/t.DEG_TO_RAD},set:function(e){this._angle=e*t.DEG_TO_RAD,this._updateTransform()},enumerable:!1,configurable:!0}),Object.defineProperty(n.prototype,"thickness",{get:function(){return this._thickness},set:function(e){this._thickness=e,this._updateTransform()},enumerable:!1,configurable:!0}),Object.defineProperty(n.prototype,"lightColor",{get:function(){return o.rgb2hex(this.uniforms.lightColor)},set:function(e){o.hex2rgb(e,this.uniforms.lightColor)},enumerable:!1,configurable:!0}),Object.defineProperty(n.prototype,"lightAlpha",{get:function(){return this.uniforms.lightAlpha},set:function(e){this.uniforms.lightAlpha=e},enumerable:!1,configurable:!0}),Object.defineProperty(n.prototype,"shadowColor",{get:function(){return o.rgb2hex(this.uniforms.shadowColor)},set:function(e){o.hex2rgb(e,this.uniforms.shadowColor)},enumerable:!1,configurable:!0}),Object.defineProperty(n.prototype,"shadowAlpha",{get:function(){return this.uniforms.shadowAlpha},set:function(e){this.uniforms.shadowAlpha=e},enumerable:!1,configurable:!0}),n}(n.Filter),y=function(e){function n(n,o,s,u){void 0===n&&(n=2),void 0===o&&(o=4),void 0===s&&(s=r.settings.FILTER_RESOLUTION),void 0===u&&(u=5);var f,c,m=e.call(this)||this;return"number"==typeof n?(f=n,c=n):n instanceof t.Point?(f=n.x,c=n.y):Array.isArray(n)&&(f=n[0],c=n[1]),m.blurXFilter=new a.BlurFilterPass(!0,f,o,s,u),m.blurYFilter=new a.BlurFilterPass(!1,c,o,s,u),m.blurYFilter.blendMode=i.BLEND_MODES.SCREEN,m.defaultFilter=new l.AlphaFilter,m}return u(n,e),n.prototype.apply=function(e,n,t,r){var o=e.getFilterTexture();this.defaultFilter.apply(e,n,t,r),this.blurXFilter.apply(e,n,o,1),this.blurYFilter.apply(e,o,t,0),e.returnFilterTexture(o)},Object.defineProperty(n.prototype,"blur",{get:function(){return this.blurXFilter.blur},set:function(e){this.blurXFilter.blur=this.blurYFilter.blur=e},enumerable:!1,configurable:!0}),Object.defineProperty(n.prototype,"blurX",{get:function(){return this.blurXFilter.blur},set:function(e){this.blurXFilter.blur=e},enumerable:!1,configurable:!0}),Object.defineProperty(n.prototype,"blurY",{get:function(){return this.blurYFilter.blur},set:function(e){this.blurYFilter.blur=e},enumerable:!1,configurable:!0}),n}(n.Filter),b=function(e){function n(t){var r=e.call(this,c,"uniform float radius;\nuniform float strength;\nuniform vec2 center;\nuniform sampler2D uSampler;\nvarying vec2 vTextureCoord;\n\nuniform vec4 filterArea;\nuniform vec4 filterClamp;\nuniform vec2 dimensions;\n\nvoid main()\n{\n vec2 coord = vTextureCoord * filterArea.xy;\n coord -= center * dimensions.xy;\n float distance = length(coord);\n if (distance < radius) {\n float percent = distance / radius;\n if (strength > 0.0) {\n coord *= mix(1.0, smoothstep(0.0, radius / distance, percent), strength * 0.75);\n } else {\n coord *= mix(1.0, pow(percent, 1.0 + strength * 0.75) * radius / distance, 1.0 - percent);\n }\n }\n coord += center * dimensions.xy;\n coord /= filterArea.xy;\n vec2 clampedCoord = clamp(coord, filterClamp.xy, filterClamp.zw);\n vec4 color = texture2D(uSampler, clampedCoord);\n if (coord != clampedCoord) {\n color *= max(0.0, 1.0 - length(coord - clampedCoord));\n }\n\n gl_FragColor = color;\n}\n")||this;return r.uniforms.dimensions=new Float32Array(2),Object.assign(r,n.defaults,t),r}return u(n,e),n.prototype.apply=function(e,n,t,r){var o=n.filterFrame,i=o.width,l=o.height;this.uniforms.dimensions[0]=i,this.uniforms.dimensions[1]=l,e.applyFilter(this,n,t,r)},Object.defineProperty(n.prototype,"radius",{get:function(){return this.uniforms.radius},set:function(e){this.uniforms.radius=e},enumerable:!1,configurable:!0}),Object.defineProperty(n.prototype,"strength",{get:function(){return this.uniforms.strength},set:function(e){this.uniforms.strength=e},enumerable:!1,configurable:!0}),Object.defineProperty(n.prototype,"center",{get:function(){return this.uniforms.center},set:function(e){this.uniforms.center=e},enumerable:!1,configurable:!0}),n.defaults={center:[.5,.5],radius:100,strength:1},n}(n.Filter),x=function(e){function t(n,t,r){void 0===t&&(t=!1),void 0===r&&(r=1);var o=e.call(this,c,"varying vec2 vTextureCoord;\nuniform sampler2D uSampler;\nuniform sampler2D colorMap;\nuniform float _mix;\nuniform float _size;\nuniform float _sliceSize;\nuniform float _slicePixelSize;\nuniform float _sliceInnerSize;\nvoid main() {\n vec4 color = texture2D(uSampler, vTextureCoord.xy);\n\n vec4 adjusted;\n if (color.a > 0.0) {\n color.rgb /= color.a;\n float innerWidth = _size - 1.0;\n float zSlice0 = min(floor(color.b * innerWidth), innerWidth);\n float zSlice1 = min(zSlice0 + 1.0, innerWidth);\n float xOffset = _slicePixelSize * 0.5 + color.r * _sliceInnerSize;\n float s0 = xOffset + (zSlice0 * _sliceSize);\n float s1 = xOffset + (zSlice1 * _sliceSize);\n float yOffset = _sliceSize * 0.5 + color.g * (1.0 - _sliceSize);\n vec4 slice0Color = texture2D(colorMap, vec2(s0,yOffset));\n vec4 slice1Color = texture2D(colorMap, vec2(s1,yOffset));\n float zOffset = fract(color.b * innerWidth);\n adjusted = mix(slice0Color, slice1Color, zOffset);\n\n color.rgb *= color.a;\n }\n gl_FragColor = vec4(mix(color, adjusted, _mix).rgb, color.a);\n\n}")||this;return o.mix=1,o._size=0,o._sliceSize=0,o._slicePixelSize=0,o._sliceInnerSize=0,o._nearest=!1,o._scaleMode=null,o._colorMap=null,o._scaleMode=null,o.nearest=t,o.mix=r,o.colorMap=n,o}return u(t,e),t.prototype.apply=function(e,n,t,r){this.uniforms._mix=this.mix,e.applyFilter(this,n,t,r)},Object.defineProperty(t.prototype,"colorSize",{get:function(){return this._size},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"colorMap",{get:function(){return this._colorMap},set:function(e){var t;e&&(e instanceof n.Texture||(e=n.Texture.from(e)),(null===(t=e)||void 0===t?void 0:t.baseTexture)&&(e.baseTexture.scaleMode=this._scaleMode,e.baseTexture.mipmap=i.MIPMAP_MODES.OFF,this._size=e.height,this._sliceSize=1/this._size,this._slicePixelSize=this._sliceSize/this._size,this._sliceInnerSize=this._slicePixelSize*(this._size-1),this.uniforms._size=this._size,this.uniforms._sliceSize=this._sliceSize,this.uniforms._slicePixelSize=this._slicePixelSize,this.uniforms._sliceInnerSize=this._sliceInnerSize,this.uniforms.colorMap=e),this._colorMap=e)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"nearest",{get:function(){return this._nearest},set:function(e){this._nearest=e,this._scaleMode=e?i.SCALE_MODES.NEAREST:i.SCALE_MODES.LINEAR;var n=this._colorMap;n&&n.baseTexture&&(n.baseTexture._glTextures={},n.baseTexture.scaleMode=this._scaleMode,n.baseTexture.mipmap=i.MIPMAP_MODES.OFF,n._updateID++,n.baseTexture.emit("update",n.baseTexture))},enumerable:!1,configurable:!0}),t.prototype.updateColorMap=function(){var e=this._colorMap;e&&e.baseTexture&&(e._updateID++,e.baseTexture.emit("update",e.baseTexture),this.colorMap=e)},t.prototype.destroy=function(n){void 0===n&&(n=!1),this._colorMap&&this._colorMap.destroy(n),e.prototype.destroy.call(this)},t}(n.Filter),_=function(e){function n(n,t){void 0===n&&(n=0),void 0===t&&(t=1);var r=e.call(this,c,"varying vec2 vTextureCoord;\nuniform sampler2D uSampler;\nuniform vec3 color;\nuniform float alpha;\n\nvoid main(void) {\n vec4 currentColor = texture2D(uSampler, vTextureCoord);\n gl_FragColor = vec4(mix(currentColor.rgb, color.rgb, currentColor.a * alpha), currentColor.a);\n}\n")||this;return r._color=0,r._alpha=1,r.uniforms.color=new Float32Array(3),r.color=n,r.alpha=t,r}return u(n,e),Object.defineProperty(n.prototype,"color",{get:function(){return this._color},set:function(e){var n=this.uniforms.color;"number"==typeof e?(o.hex2rgb(e,n),this._color=e):(n[0]=e[0],n[1]=e[1],n[2]=e[2],this._color=o.rgb2hex(n))},enumerable:!1,configurable:!0}),Object.defineProperty(n.prototype,"alpha",{get:function(){return this._alpha},set:function(e){this.uniforms.alpha=e,this._alpha=e},enumerable:!1,configurable:!0}),n}(n.Filter),C=function(e){function n(n,t,r){void 0===n&&(n=16711680),void 0===t&&(t=0),void 0===r&&(r=.4);var o=e.call(this,c,"varying vec2 vTextureCoord;\nuniform sampler2D uSampler;\nuniform vec3 originalColor;\nuniform vec3 newColor;\nuniform float epsilon;\nvoid main(void) {\n vec4 currentColor = texture2D(uSampler, vTextureCoord);\n vec3 colorDiff = originalColor - (currentColor.rgb / max(currentColor.a, 0.0000000001));\n float colorDistance = length(colorDiff);\n float doReplace = step(colorDistance, epsilon);\n gl_FragColor = vec4(mix(currentColor.rgb, (newColor + colorDiff) * currentColor.a, doReplace), currentColor.a);\n}\n")||this;return o._originalColor=16711680,o._newColor=0,o.uniforms.originalColor=new Float32Array(3),o.uniforms.newColor=new Float32Array(3),o.originalColor=n,o.newColor=t,o.epsilon=r,o}return u(n,e),Object.defineProperty(n.prototype,"originalColor",{get:function(){return this._originalColor},set:function(e){var n=this.uniforms.originalColor;"number"==typeof e?(o.hex2rgb(e,n),this._originalColor=e):(n[0]=e[0],n[1]=e[1],n[2]=e[2],this._originalColor=o.rgb2hex(n))},enumerable:!1,configurable:!0}),Object.defineProperty(n.prototype,"newColor",{get:function(){return this._newColor},set:function(e){var n=this.uniforms.newColor;"number"==typeof e?(o.hex2rgb(e,n),this._newColor=e):(n[0]=e[0],n[1]=e[1],n[2]=e[2],this._newColor=o.rgb2hex(n))},enumerable:!1,configurable:!0}),Object.defineProperty(n.prototype,"epsilon",{get:function(){return this.uniforms.epsilon},set:function(e){this.uniforms.epsilon=e},enumerable:!1,configurable:!0}),n}(n.Filter),S=function(e){function n(n,t,r){void 0===t&&(t=200),void 0===r&&(r=200);var o=e.call(this,c,"precision mediump float;\n\nvarying mediump vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\nuniform vec2 texelSize;\nuniform float matrix[9];\n\nvoid main(void)\n{\n vec4 c11 = texture2D(uSampler, vTextureCoord - texelSize); // top left\n vec4 c12 = texture2D(uSampler, vec2(vTextureCoord.x, vTextureCoord.y - texelSize.y)); // top center\n vec4 c13 = texture2D(uSampler, vec2(vTextureCoord.x + texelSize.x, vTextureCoord.y - texelSize.y)); // top right\n\n vec4 c21 = texture2D(uSampler, vec2(vTextureCoord.x - texelSize.x, vTextureCoord.y)); // mid left\n vec4 c22 = texture2D(uSampler, vTextureCoord); // mid center\n vec4 c23 = texture2D(uSampler, vec2(vTextureCoord.x + texelSize.x, vTextureCoord.y)); // mid right\n\n vec4 c31 = texture2D(uSampler, vec2(vTextureCoord.x - texelSize.x, vTextureCoord.y + texelSize.y)); // bottom left\n vec4 c32 = texture2D(uSampler, vec2(vTextureCoord.x, vTextureCoord.y + texelSize.y)); // bottom center\n vec4 c33 = texture2D(uSampler, vTextureCoord + texelSize); // bottom right\n\n gl_FragColor =\n c11 * matrix[0] + c12 * matrix[1] + c13 * matrix[2] +\n c21 * matrix[3] + c22 * matrix[4] + c23 * matrix[5] +\n c31 * matrix[6] + c32 * matrix[7] + c33 * matrix[8];\n\n gl_FragColor.a = c22.a;\n}\n")||this;return o.uniforms.texelSize=new Float32Array(2),o.uniforms.matrix=new Float32Array(9),void 0!==n&&(o.matrix=n),o.width=t,o.height=r,o}return u(n,e),Object.defineProperty(n.prototype,"matrix",{get:function(){return this.uniforms.matrix},set:function(e){var n=this;e.forEach((function(e,t){n.uniforms.matrix[t]=e}))},enumerable:!1,configurable:!0}),Object.defineProperty(n.prototype,"width",{get:function(){return 1/this.uniforms.texelSize[0]},set:function(e){this.uniforms.texelSize[0]=1/e},enumerable:!1,configurable:!0}),Object.defineProperty(n.prototype,"height",{get:function(){return 1/this.uniforms.texelSize[1]},set:function(e){this.uniforms.texelSize[1]=1/e},enumerable:!1,configurable:!0}),n}(n.Filter),F=function(e){function n(){return e.call(this,c,"precision mediump float;\n\nvarying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\n\nvoid main(void)\n{\n float lum = length(texture2D(uSampler, vTextureCoord.xy).rgb);\n\n gl_FragColor = vec4(1.0, 1.0, 1.0, 1.0);\n\n if (lum < 1.00)\n {\n if (mod(gl_FragCoord.x + gl_FragCoord.y, 10.0) == 0.0)\n {\n gl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);\n }\n }\n\n if (lum < 0.75)\n {\n if (mod(gl_FragCoord.x - gl_FragCoord.y, 10.0) == 0.0)\n {\n gl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);\n }\n }\n\n if (lum < 0.50)\n {\n if (mod(gl_FragCoord.x + gl_FragCoord.y - 5.0, 10.0) == 0.0)\n {\n gl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);\n }\n }\n\n if (lum < 0.3)\n {\n if (mod(gl_FragCoord.x - gl_FragCoord.y - 5.0, 10.0) == 0.0)\n {\n gl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);\n }\n }\n}\n")||this}return u(n,e),n}(n.Filter),z=function(e){function n(t){var r=e.call(this,c,"varying vec2 vTextureCoord;\nuniform sampler2D uSampler;\n\nuniform vec4 filterArea;\nuniform vec2 dimensions;\n\nconst float SQRT_2 = 1.414213;\n\nconst float light = 1.0;\n\nuniform float curvature;\nuniform float lineWidth;\nuniform float lineContrast;\nuniform bool verticalLine;\nuniform float noise;\nuniform float noiseSize;\n\nuniform float vignetting;\nuniform float vignettingAlpha;\nuniform float vignettingBlur;\n\nuniform float seed;\nuniform float time;\n\nfloat rand(vec2 co) {\n return fract(sin(dot(co.xy, vec2(12.9898, 78.233))) * 43758.5453);\n}\n\nvoid main(void)\n{\n vec2 pixelCoord = vTextureCoord.xy * filterArea.xy;\n vec2 dir = vec2(vTextureCoord.xy * filterArea.xy / dimensions - vec2(0.5, 0.5));\n \n gl_FragColor = texture2D(uSampler, vTextureCoord);\n vec3 rgb = gl_FragColor.rgb;\n\n if (noise > 0.0 && noiseSize > 0.0)\n {\n pixelCoord.x = floor(pixelCoord.x / noiseSize);\n pixelCoord.y = floor(pixelCoord.y / noiseSize);\n float _noise = rand(pixelCoord * noiseSize * seed) - 0.5;\n rgb += _noise * noise;\n }\n\n if (lineWidth > 0.0)\n {\n float _c = curvature > 0. ? curvature : 1.;\n float k = curvature > 0. ?(length(dir * dir) * 0.25 * _c * _c + 0.935 * _c) : 1.;\n vec2 uv = dir * k;\n\n float v = (verticalLine ? uv.x * dimensions.x : uv.y * dimensions.y) * min(1.0, 2.0 / lineWidth ) / _c;\n float j = 1. + cos(v * 1.2 - time) * 0.5 * lineContrast;\n rgb *= j;\n float segment = verticalLine ? mod((dir.x + .5) * dimensions.x, 4.) : mod((dir.y + .5) * dimensions.y, 4.);\n rgb *= 0.99 + ceil(segment) * 0.015;\n }\n\n if (vignetting > 0.0)\n {\n float outter = SQRT_2 - vignetting * SQRT_2;\n float darker = clamp((outter - length(dir) * SQRT_2) / ( 0.00001 + vignettingBlur * SQRT_2), 0.0, 1.0);\n rgb *= darker + (1.0 - darker) * (1.0 - vignettingAlpha);\n }\n\n gl_FragColor.rgb = rgb;\n}\n")||this;return r.time=0,r.seed=0,r.uniforms.dimensions=new Float32Array(2),Object.assign(r,n.defaults,t),r}return u(n,e),n.prototype.apply=function(e,n,t,r){var o=n.filterFrame,i=o.width,l=o.height;this.uniforms.dimensions[0]=i,this.uniforms.dimensions[1]=l,this.uniforms.seed=this.seed,this.uniforms.time=this.time,e.applyFilter(this,n,t,r)},Object.defineProperty(n.prototype,"curvature",{get:function(){return this.uniforms.curvature},set:function(e){this.uniforms.curvature=e},enumerable:!1,configurable:!0}),Object.defineProperty(n.prototype,"lineWidth",{get:function(){return this.uniforms.lineWidth},set:function(e){this.uniforms.lineWidth=e},enumerable:!1,configurable:!0}),Object.defineProperty(n.prototype,"lineContrast",{get:function(){return this.uniforms.lineContrast},set:function(e){this.uniforms.lineContrast=e},enumerable:!1,configurable:!0}),Object.defineProperty(n.prototype,"verticalLine",{get:function(){return this.uniforms.verticalLine},set:function(e){this.uniforms.verticalLine=e},enumerable:!1,configurable:!0}),Object.defineProperty(n.prototype,"noise",{get:function(){return this.uniforms.noise},set:function(e){this.uniforms.noise=e},enumerable:!1,configurable:!0}),Object.defineProperty(n.prototype,"noiseSize",{get:function(){return this.uniforms.noiseSize},set:function(e){this.uniforms.noiseSize=e},enumerable:!1,configurable:!0}),Object.defineProperty(n.prototype,"vignetting",{get:function(){return this.uniforms.vignetting},set:function(e){this.uniforms.vignetting=e},enumerable:!1,configurable:!0}),Object.defineProperty(n.prototype,"vignettingAlpha",{get:function(){return this.uniforms.vignettingAlpha},set:function(e){this.uniforms.vignettingAlpha=e},enumerable:!1,configurable:!0}),Object.defineProperty(n.prototype,"vignettingBlur",{get:function(){return this.uniforms.vignettingBlur},set:function(e){this.uniforms.vignettingBlur=e},enumerable:!1,configurable:!0}),n.defaults={curvature:1,lineWidth:1,lineContrast:.25,verticalLine:!1,noise:0,noiseSize:1,seed:0,vignetting:.3,vignettingAlpha:1,vignettingBlur:.3,time:0},n}(n.Filter),O=function(e){function n(n,t){void 0===n&&(n=1),void 0===t&&(t=5);var r=e.call(this,c,"precision mediump float;\n\nvarying vec2 vTextureCoord;\nvarying vec4 vColor;\n\nuniform vec4 filterArea;\nuniform sampler2D uSampler;\n\nuniform float angle;\nuniform float scale;\n\nfloat pattern()\n{\n float s = sin(angle), c = cos(angle);\n vec2 tex = vTextureCoord * filterArea.xy;\n vec2 point = vec2(\n c * tex.x - s * tex.y,\n s * tex.x + c * tex.y\n ) * scale;\n return (sin(point.x) * sin(point.y)) * 4.0;\n}\n\nvoid main()\n{\n vec4 color = texture2D(uSampler, vTextureCoord);\n float average = (color.r + color.g + color.b) / 3.0;\n gl_FragColor = vec4(vec3(average * 10.0 - 5.0 + pattern()), color.a);\n}\n")||this;return r.scale=n,r.angle=t,r}return u(n,e),Object.defineProperty(n.prototype,"scale",{get:function(){return this.uniforms.scale},set:function(e){this.uniforms.scale=e},enumerable:!1,configurable:!0}),Object.defineProperty(n.prototype,"angle",{get:function(){return this.uniforms.angle},set:function(e){this.uniforms.angle=e},enumerable:!1,configurable:!0}),n}(n.Filter),P=function(e){function i(o){var l=e.call(this)||this;l.angle=45,l._distance=5,l._resolution=r.settings.FILTER_RESOLUTION;var a=o?f(f({},i.defaults),o):i.defaults,s=a.kernels,u=a.blur,m=a.quality,p=a.pixelSize,h=a.resolution;l._tintFilter=new n.Filter(c,"varying vec2 vTextureCoord;\nuniform sampler2D uSampler;\nuniform float alpha;\nuniform vec3 color;\n\nuniform vec2 shift;\nuniform vec4 inputSize;\n\nvoid main(void){\n vec4 sample = texture2D(uSampler, vTextureCoord - shift * inputSize.zw);\n\n // Premultiply alpha\n sample.rgb = color.rgb * sample.a;\n\n // alpha user alpha\n sample *= alpha;\n\n gl_FragColor = sample;\n}"),l._tintFilter.uniforms.color=new Float32Array(4),l._tintFilter.uniforms.shift=new t.Point,l._tintFilter.resolution=h,l._blurFilter=s?new d(s):new d(u,m),l.pixelSize=p,l.resolution=h;var g=a.shadowOnly,v=a.rotation,y=a.distance,b=a.alpha,x=a.color;return l.shadowOnly=g,l.rotation=v,l.distance=y,l.alpha=b,l.color=x,l._updatePadding(),l}return u(i,e),i.prototype.apply=function(e,n,t,r){var o=e.getFilterTexture();this._tintFilter.apply(e,n,o,1),this._blurFilter.apply(e,o,t,r),!0!==this.shadowOnly&&e.applyFilter(this,n,t,0),e.returnFilterTexture(o)},i.prototype._updatePadding=function(){this.padding=this.distance+2*this.blur},i.prototype._updateShift=function(){this._tintFilter.uniforms.shift.set(this.distance*Math.cos(this.angle),this.distance*Math.sin(this.angle))},Object.defineProperty(i.prototype,"resolution",{get:function(){return this._resolution},set:function(e){this._resolution=e,this._tintFilter&&(this._tintFilter.resolution=e),this._blurFilter&&(this._blurFilter.resolution=e)},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"distance",{get:function(){return this._distance},set:function(e){this._distance=e,this._updatePadding(),this._updateShift()},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"rotation",{get:function(){return this.angle/t.DEG_TO_RAD},set:function(e){this.angle=e*t.DEG_TO_RAD,this._updateShift()},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"alpha",{get:function(){return this._tintFilter.uniforms.alpha},set:function(e){this._tintFilter.uniforms.alpha=e},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"color",{get:function(){return o.rgb2hex(this._tintFilter.uniforms.color)},set:function(e){o.hex2rgb(e,this._tintFilter.uniforms.color)},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"kernels",{get:function(){return this._blurFilter.kernels},set:function(e){this._blurFilter.kernels=e},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"blur",{get:function(){return this._blurFilter.blur},set:function(e){this._blurFilter.blur=e,this._updatePadding()},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"quality",{get:function(){return this._blurFilter.quality},set:function(e){this._blurFilter.quality=e},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"pixelSize",{get:function(){return this._blurFilter.pixelSize},set:function(e){this._blurFilter.pixelSize=e},enumerable:!1,configurable:!0}),i.defaults={rotation:45,distance:5,color:0,alpha:.5,shadowOnly:!1,kernels:null,blur:2,quality:3,pixelSize:1,resolution:r.settings.FILTER_RESOLUTION},i}(n.Filter),A=function(e){function n(n){void 0===n&&(n=5);var t=e.call(this,c,"precision mediump float;\n\nvarying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\nuniform float strength;\nuniform vec4 filterArea;\n\n\nvoid main(void)\n{\n\tvec2 onePixel = vec2(1.0 / filterArea);\n\n\tvec4 color;\n\n\tcolor.rgb = vec3(0.5);\n\n\tcolor -= texture2D(uSampler, vTextureCoord - onePixel) * strength;\n\tcolor += texture2D(uSampler, vTextureCoord + onePixel) * strength;\n\n\tcolor.rgb = vec3((color.r + color.g + color.b) / 3.0);\n\n\tfloat alpha = texture2D(uSampler, vTextureCoord).a;\n\n\tgl_FragColor = vec4(color.rgb * alpha, alpha);\n}\n")||this;return t.strength=n,t}return u(n,e),Object.defineProperty(n.prototype,"strength",{get:function(){return this.uniforms.strength},set:function(e){this.uniforms.strength=e},enumerable:!1,configurable:!0}),n}(n.Filter),T=function(e){function r(t){var o=e.call(this,c,"// precision highp float;\n\nvarying vec2 vTextureCoord;\nuniform sampler2D uSampler;\n\nuniform vec4 filterArea;\nuniform vec4 filterClamp;\nuniform vec2 dimensions;\nuniform float aspect;\n\nuniform sampler2D displacementMap;\nuniform float offset;\nuniform float sinDir;\nuniform float cosDir;\nuniform int fillMode;\n\nuniform float seed;\nuniform vec2 red;\nuniform vec2 green;\nuniform vec2 blue;\n\nconst int TRANSPARENT = 0;\nconst int ORIGINAL = 1;\nconst int LOOP = 2;\nconst int CLAMP = 3;\nconst int MIRROR = 4;\n\nvoid main(void)\n{\n vec2 coord = (vTextureCoord * filterArea.xy) / dimensions;\n\n if (coord.x > 1.0 || coord.y > 1.0) {\n return;\n }\n\n float cx = coord.x - 0.5;\n float cy = (coord.y - 0.5) * aspect;\n float ny = (-sinDir * cx + cosDir * cy) / aspect + 0.5;\n\n // displacementMap: repeat\n // ny = ny > 1.0 ? ny - 1.0 : (ny < 0.0 ? 1.0 + ny : ny);\n\n // displacementMap: mirror\n ny = ny > 1.0 ? 2.0 - ny : (ny < 0.0 ? -ny : ny);\n\n vec4 dc = texture2D(displacementMap, vec2(0.5, ny));\n\n float displacement = (dc.r - dc.g) * (offset / filterArea.x);\n\n coord = vTextureCoord + vec2(cosDir * displacement, sinDir * displacement * aspect);\n\n if (fillMode == CLAMP) {\n coord = clamp(coord, filterClamp.xy, filterClamp.zw);\n } else {\n if( coord.x > filterClamp.z ) {\n if (fillMode == TRANSPARENT) {\n discard;\n } else if (fillMode == LOOP) {\n coord.x -= filterClamp.z;\n } else if (fillMode == MIRROR) {\n coord.x = filterClamp.z * 2.0 - coord.x;\n }\n } else if( coord.x < filterClamp.x ) {\n if (fillMode == TRANSPARENT) {\n discard;\n } else if (fillMode == LOOP) {\n coord.x += filterClamp.z;\n } else if (fillMode == MIRROR) {\n coord.x *= -filterClamp.z;\n }\n }\n\n if( coord.y > filterClamp.w ) {\n if (fillMode == TRANSPARENT) {\n discard;\n } else if (fillMode == LOOP) {\n coord.y -= filterClamp.w;\n } else if (fillMode == MIRROR) {\n coord.y = filterClamp.w * 2.0 - coord.y;\n }\n } else if( coord.y < filterClamp.y ) {\n if (fillMode == TRANSPARENT) {\n discard;\n } else if (fillMode == LOOP) {\n coord.y += filterClamp.w;\n } else if (fillMode == MIRROR) {\n coord.y *= -filterClamp.w;\n }\n }\n }\n\n gl_FragColor.r = texture2D(uSampler, coord + red * (1.0 - seed * 0.4) / filterArea.xy).r;\n gl_FragColor.g = texture2D(uSampler, coord + green * (1.0 - seed * 0.3) / filterArea.xy).g;\n gl_FragColor.b = texture2D(uSampler, coord + blue * (1.0 - seed * 0.2) / filterArea.xy).b;\n gl_FragColor.a = texture2D(uSampler, coord).a;\n}\n")||this;return o.offset=100,o.fillMode=r.TRANSPARENT,o.average=!1,o.seed=0,o.minSize=8,o.sampleSize=512,o._slices=0,o._offsets=new Float32Array(1),o._sizes=new Float32Array(1),o._direction=-1,o.uniforms.dimensions=new Float32Array(2),o._canvas=document.createElement("canvas"),o._canvas.width=4,o._canvas.height=o.sampleSize,o.texture=n.Texture.from(o._canvas,{scaleMode:i.SCALE_MODES.NEAREST}),Object.assign(o,r.defaults,t),o}return u(r,e),r.prototype.apply=function(e,n,t,r){var o=n.filterFrame,i=o.width,l=o.height;this.uniforms.dimensions[0]=i,this.uniforms.dimensions[1]=l,this.uniforms.aspect=l/i,this.uniforms.seed=this.seed,this.uniforms.offset=this.offset,this.uniforms.fillMode=this.fillMode,e.applyFilter(this,n,t,r)},r.prototype._randomizeSizes=function(){var e=this._sizes,n=this._slices-1,t=this.sampleSize,r=Math.min(this.minSize/t,.9/this._slices);if(this.average){for(var o=this._slices,i=1,l=0;l0;n--){var t=Math.random()*n>>0,r=e[n];e[n]=e[t],e[t]=r}},r.prototype._randomizeOffsets=function(){for(var e=0;e0?e:0,s=e<0?-e:0;r.fillStyle="rgba("+a+", "+s+", 0, 1)",r.fillRect(0,o>>0,n,l+1>>0),o+=l}t.baseTexture.update(),this.uniforms.displacementMap=t},Object.defineProperty(r.prototype,"sizes",{get:function(){return this._sizes},set:function(e){for(var n=Math.min(this._slices,e.length),t=0;t>0)},Object.defineProperty(n.prototype,"offset",{get:function(){return this.uniforms.uOffset},set:function(e){this.uniforms.uOffset=e},enumerable:!1,configurable:!0}),n}(n.Filter),M=function(e){function n(n,t,r){void 0===t&&(t=.05),void 0===r&&(r=n.length);var o=e.call(this,c,"varying vec2 vTextureCoord;\nuniform sampler2D uSampler;\n\nuniform float epsilon;\n\nconst int MAX_COLORS = %maxColors%;\n\nuniform vec3 originalColors[MAX_COLORS];\nuniform vec3 targetColors[MAX_COLORS];\n\nvoid main(void)\n{\n gl_FragColor = texture2D(uSampler, vTextureCoord);\n\n float alpha = gl_FragColor.a;\n if (alpha < 0.0001)\n {\n return;\n }\n\n vec3 color = gl_FragColor.rgb / alpha;\n\n for(int i = 0; i < MAX_COLORS; i++)\n {\n vec3 origColor = originalColors[i];\n if (origColor.r < 0.0)\n {\n break;\n }\n vec3 colorDiff = origColor - color;\n if (length(colorDiff) < epsilon)\n {\n vec3 targetColor = targetColors[i];\n gl_FragColor = vec4((targetColor + colorDiff) * alpha, alpha);\n return;\n }\n }\n}\n".replace(/%maxColors%/g,r.toFixed(0)))||this;return o._replacements=[],o._maxColors=0,o.epsilon=t,o._maxColors=r,o.uniforms.originalColors=new Float32Array(3*r),o.uniforms.targetColors=new Float32Array(3*r),o.replacements=n,o}return u(n,e),Object.defineProperty(n.prototype,"replacements",{get:function(){return this._replacements},set:function(e){var n=this.uniforms.originalColors,t=this.uniforms.targetColors,r=e.length;if(r>this._maxColors)throw new Error("Length of replacements ("+r+") exceeds the maximum colors length ("+this._maxColors+")");n[3*r]=-1;for(var i=0;i 0.5) then: 1 - 2 * (1 - dst) * (1 - src)\n return vec3((dst.x <= 0.5) ? (2.0 * src.x * dst.x) : (1.0 - 2.0 * (1.0 - dst.x) * (1.0 - src.x)),\n (dst.y <= 0.5) ? (2.0 * src.y * dst.y) : (1.0 - 2.0 * (1.0 - dst.y) * (1.0 - src.y)),\n (dst.z <= 0.5) ? (2.0 * src.z * dst.z) : (1.0 - 2.0 * (1.0 - dst.z) * (1.0 - src.z)));\n}\n\n\nvoid main()\n{\n gl_FragColor = texture2D(uSampler, vTextureCoord);\n vec3 color = gl_FragColor.rgb;\n\n if (sepia > 0.0)\n {\n float gray = (color.x + color.y + color.z) / 3.0;\n vec3 grayscale = vec3(gray);\n\n color = Overlay(SEPIA_RGB, grayscale);\n\n color = grayscale + sepia * (color - grayscale);\n }\n\n vec2 coord = vTextureCoord * filterArea.xy / dimensions.xy;\n\n if (vignetting > 0.0)\n {\n float outter = SQRT_2 - vignetting * SQRT_2;\n vec2 dir = vec2(vec2(0.5, 0.5) - coord);\n dir.y *= dimensions.y / dimensions.x;\n float darker = clamp((outter - length(dir) * SQRT_2) / ( 0.00001 + vignettingBlur * SQRT_2), 0.0, 1.0);\n color.rgb *= darker + (1.0 - darker) * (1.0 - vignettingAlpha);\n }\n\n if (scratchDensity > seed && scratch != 0.0)\n {\n float phase = seed * 256.0;\n float s = mod(floor(phase), 2.0);\n float dist = 1.0 / scratchDensity;\n float d = distance(coord, vec2(seed * dist, abs(s - seed * dist)));\n if (d < seed * 0.6 + 0.4)\n {\n highp float period = scratchDensity * 10.0;\n\n float xx = coord.x * period + phase;\n float aa = abs(mod(xx, 0.5) * 4.0);\n float bb = mod(floor(xx / 0.5), 2.0);\n float yy = (1.0 - bb) * aa + bb * (2.0 - aa);\n\n float kk = 2.0 * period;\n float dw = scratchWidth / dimensions.x * (0.75 + seed);\n float dh = dw * kk;\n\n float tine = (yy - (2.0 - dh));\n\n if (tine > 0.0) {\n float _sign = sign(scratch);\n\n tine = s * tine / period + scratch + 0.1;\n tine = clamp(tine + 1.0, 0.5 + _sign * 0.5, 1.5 + _sign * 0.5);\n\n color.rgb *= tine;\n }\n }\n }\n\n if (noise > 0.0 && noiseSize > 0.0)\n {\n vec2 pixelCoord = vTextureCoord.xy * filterArea.xy;\n pixelCoord.x = floor(pixelCoord.x / noiseSize);\n pixelCoord.y = floor(pixelCoord.y / noiseSize);\n // vec2 d = pixelCoord * noiseSize * vec2(1024.0 + seed * 512.0, 1024.0 - seed * 512.0);\n // float _noise = snoise(d) * 0.5;\n float _noise = rand(pixelCoord * noiseSize * seed) - 0.5;\n color += _noise * noise;\n }\n\n gl_FragColor.rgb = color;\n}\n")||this;return o.seed=0,o.uniforms.dimensions=new Float32Array(2),"number"==typeof t?(o.seed=t,t=void 0):o.seed=r,Object.assign(o,n.defaults,t),o}return u(n,e),n.prototype.apply=function(e,n,t,r){var o,i;this.uniforms.dimensions[0]=null===(o=n.filterFrame)||void 0===o?void 0:o.width,this.uniforms.dimensions[1]=null===(i=n.filterFrame)||void 0===i?void 0:i.height,this.uniforms.seed=this.seed,e.applyFilter(this,n,t,r)},Object.defineProperty(n.prototype,"sepia",{get:function(){return this.uniforms.sepia},set:function(e){this.uniforms.sepia=e},enumerable:!1,configurable:!0}),Object.defineProperty(n.prototype,"noise",{get:function(){return this.uniforms.noise},set:function(e){this.uniforms.noise=e},enumerable:!1,configurable:!0}),Object.defineProperty(n.prototype,"noiseSize",{get:function(){return this.uniforms.noiseSize},set:function(e){this.uniforms.noiseSize=e},enumerable:!1,configurable:!0}),Object.defineProperty(n.prototype,"scratch",{get:function(){return this.uniforms.scratch},set:function(e){this.uniforms.scratch=e},enumerable:!1,configurable:!0}),Object.defineProperty(n.prototype,"scratchDensity",{get:function(){return this.uniforms.scratchDensity},set:function(e){this.uniforms.scratchDensity=e},enumerable:!1,configurable:!0}),Object.defineProperty(n.prototype,"scratchWidth",{get:function(){return this.uniforms.scratchWidth},set:function(e){this.uniforms.scratchWidth=e},enumerable:!1,configurable:!0}),Object.defineProperty(n.prototype,"vignetting",{get:function(){return this.uniforms.vignetting},set:function(e){this.uniforms.vignetting=e},enumerable:!1,configurable:!0}),Object.defineProperty(n.prototype,"vignettingAlpha",{get:function(){return this.uniforms.vignettingAlpha},set:function(e){this.uniforms.vignettingAlpha=e},enumerable:!1,configurable:!0}),Object.defineProperty(n.prototype,"vignettingBlur",{get:function(){return this.uniforms.vignettingBlur},set:function(e){this.uniforms.vignettingBlur=e},enumerable:!1,configurable:!0}),n.defaults={sepia:.3,noise:.3,noiseSize:1,scratch:.5,scratchDensity:.3,scratchWidth:1,vignetting:.3,vignettingAlpha:1,vignettingBlur:.3},n}(n.Filter),E=function(e){function n(t,r,o){void 0===t&&(t=1),void 0===r&&(r=0),void 0===o&&(o=.1);var i=e.call(this,c,"varying vec2 vTextureCoord;\nuniform sampler2D uSampler;\n\nuniform vec2 thickness;\nuniform vec4 outlineColor;\nuniform vec4 filterClamp;\n\nconst float DOUBLE_PI = 3.14159265358979323846264 * 2.;\n\nvoid main(void) {\n vec4 ownColor = texture2D(uSampler, vTextureCoord);\n vec4 curColor;\n float maxAlpha = 0.;\n vec2 displaced;\n for (float angle = 0.; angle <= DOUBLE_PI; angle += ${angleStep}) {\n displaced.x = vTextureCoord.x + thickness.x * cos(angle);\n displaced.y = vTextureCoord.y + thickness.y * sin(angle);\n curColor = texture2D(uSampler, clamp(displaced, filterClamp.xy, filterClamp.zw));\n maxAlpha = max(maxAlpha, curColor.a);\n }\n float resultAlpha = max(maxAlpha, ownColor.a);\n gl_FragColor = vec4((ownColor.rgb + outlineColor.rgb * (1. - ownColor.a)) * resultAlpha, resultAlpha);\n}\n".replace(/\$\{angleStep\}/,n.getAngleStep(o)))||this;return i._thickness=1,i.uniforms.thickness=new Float32Array([0,0]),i.uniforms.outlineColor=new Float32Array([0,0,0,1]),Object.assign(i,{thickness:t,color:r,quality:o}),i}return u(n,e),n.getAngleStep=function(e){var t=Math.max(e*n.MAX_SAMPLES,n.MIN_SAMPLES);return(2*Math.PI/t).toFixed(7)},n.prototype.apply=function(e,n,t,r){this.uniforms.thickness[0]=this._thickness/n._frame.width,this.uniforms.thickness[1]=this._thickness/n._frame.height,e.applyFilter(this,n,t,r)},Object.defineProperty(n.prototype,"color",{get:function(){return o.rgb2hex(this.uniforms.outlineColor)},set:function(e){o.hex2rgb(e,this.uniforms.outlineColor)},enumerable:!1,configurable:!0}),Object.defineProperty(n.prototype,"thickness",{get:function(){return this._thickness},set:function(e){this._thickness=e,this.padding=e},enumerable:!1,configurable:!0}),n.MIN_SAMPLES=1,n.MAX_SAMPLES=100,n}(n.Filter),I=function(e){function n(n){void 0===n&&(n=10);var t=e.call(this,c,"precision mediump float;\n\nvarying vec2 vTextureCoord;\n\nuniform vec2 size;\nuniform sampler2D uSampler;\n\nuniform vec4 filterArea;\n\nvec2 mapCoord( vec2 coord )\n{\n coord *= filterArea.xy;\n coord += filterArea.zw;\n\n return coord;\n}\n\nvec2 unmapCoord( vec2 coord )\n{\n coord -= filterArea.zw;\n coord /= filterArea.xy;\n\n return coord;\n}\n\nvec2 pixelate(vec2 coord, vec2 size)\n{\n\treturn floor( coord / size ) * size;\n}\n\nvoid main(void)\n{\n vec2 coord = mapCoord(vTextureCoord);\n\n coord = pixelate(coord, size);\n\n coord = unmapCoord(coord);\n\n gl_FragColor = texture2D(uSampler, coord);\n}\n")||this;return t.size=n,t}return u(n,e),Object.defineProperty(n.prototype,"size",{get:function(){return this.uniforms.size},set:function(e){"number"==typeof e&&(e=[e,e]),this.uniforms.size=e},enumerable:!1,configurable:!0}),n}(n.Filter),k=function(e){function n(n,t,r,o){void 0===n&&(n=0),void 0===t&&(t=[0,0]),void 0===r&&(r=5),void 0===o&&(o=-1);var i=e.call(this,c,"varying vec2 vTextureCoord;\nuniform sampler2D uSampler;\nuniform vec4 filterArea;\n\nuniform float uRadian;\nuniform vec2 uCenter;\nuniform float uRadius;\nuniform int uKernelSize;\n\nconst int MAX_KERNEL_SIZE = 2048;\n\nvoid main(void)\n{\n vec4 color = texture2D(uSampler, vTextureCoord);\n\n if (uKernelSize == 0)\n {\n gl_FragColor = color;\n return;\n }\n\n float aspect = filterArea.y / filterArea.x;\n vec2 center = uCenter.xy / filterArea.xy;\n float gradient = uRadius / filterArea.x * 0.3;\n float radius = uRadius / filterArea.x - gradient * 0.5;\n int k = uKernelSize - 1;\n\n vec2 coord = vTextureCoord;\n vec2 dir = vec2(center - coord);\n float dist = length(vec2(dir.x, dir.y * aspect));\n\n float radianStep = uRadian;\n if (radius >= 0.0 && dist > radius) {\n float delta = dist - radius;\n float gap = gradient;\n float scale = 1.0 - abs(delta / gap);\n if (scale <= 0.0) {\n gl_FragColor = color;\n return;\n }\n radianStep *= scale;\n }\n radianStep /= float(k);\n\n float s = sin(radianStep);\n float c = cos(radianStep);\n mat2 rotationMatrix = mat2(vec2(c, -s), vec2(s, c));\n\n for(int i = 0; i < MAX_KERNEL_SIZE - 1; i++) {\n if (i == k) {\n break;\n }\n\n coord -= center;\n coord.y *= aspect;\n coord = rotationMatrix * coord;\n coord.y /= aspect;\n coord += center;\n\n vec4 sample = texture2D(uSampler, coord);\n\n // switch to pre-multiplied alpha to correctly blur transparent images\n // sample.rgb *= sample.a;\n\n color += sample;\n }\n\n gl_FragColor = color / float(uKernelSize);\n}\n")||this;return i._angle=0,i.angle=n,i.center=t,i.kernelSize=r,i.radius=o,i}return u(n,e),n.prototype.apply=function(e,n,t,r){this.uniforms.uKernelSize=0!==this._angle?this.kernelSize:0,e.applyFilter(this,n,t,r)},Object.defineProperty(n.prototype,"angle",{get:function(){return this._angle},set:function(e){this._angle=e,this.uniforms.uRadian=e*Math.PI/180},enumerable:!1,configurable:!0}),Object.defineProperty(n.prototype,"center",{get:function(){return this.uniforms.uCenter},set:function(e){this.uniforms.uCenter=e},enumerable:!1,configurable:!0}),Object.defineProperty(n.prototype,"radius",{get:function(){return this.uniforms.uRadius},set:function(e){(e<0||e===1/0)&&(e=-1),this.uniforms.uRadius=e},enumerable:!1,configurable:!0}),n}(n.Filter),L=function(e){function n(t){var r=e.call(this,c,"varying vec2 vTextureCoord;\nuniform sampler2D uSampler;\n\nuniform vec4 filterArea;\nuniform vec4 filterClamp;\nuniform vec2 dimensions;\n\nuniform bool mirror;\nuniform float boundary;\nuniform vec2 amplitude;\nuniform vec2 waveLength;\nuniform vec2 alpha;\nuniform float time;\n\nfloat rand(vec2 co) {\n return fract(sin(dot(co.xy, vec2(12.9898, 78.233))) * 43758.5453);\n}\n\nvoid main(void)\n{\n vec2 pixelCoord = vTextureCoord.xy * filterArea.xy;\n vec2 coord = pixelCoord / dimensions;\n\n if (coord.y < boundary) {\n gl_FragColor = texture2D(uSampler, vTextureCoord);\n return;\n }\n\n float k = (coord.y - boundary) / (1. - boundary + 0.0001);\n float areaY = boundary * dimensions.y / filterArea.y;\n float v = areaY + areaY - vTextureCoord.y;\n float y = mirror ? v : vTextureCoord.y;\n\n float _amplitude = ((amplitude.y - amplitude.x) * k + amplitude.x ) / filterArea.x;\n float _waveLength = ((waveLength.y - waveLength.x) * k + waveLength.x) / filterArea.y;\n float _alpha = (alpha.y - alpha.x) * k + alpha.x;\n\n float x = vTextureCoord.x + cos(v * 6.28 / _waveLength - time) * _amplitude;\n x = clamp(x, filterClamp.x, filterClamp.z);\n\n vec4 color = texture2D(uSampler, vec2(x, y));\n\n gl_FragColor = color * _alpha;\n}\n")||this;return r.time=0,r.uniforms.amplitude=new Float32Array(2),r.uniforms.waveLength=new Float32Array(2),r.uniforms.alpha=new Float32Array(2),r.uniforms.dimensions=new Float32Array(2),Object.assign(r,n.defaults,t),r}return u(n,e),n.prototype.apply=function(e,n,t,r){var o,i;this.uniforms.dimensions[0]=null===(o=n.filterFrame)||void 0===o?void 0:o.width,this.uniforms.dimensions[1]=null===(i=n.filterFrame)||void 0===i?void 0:i.height,this.uniforms.time=this.time,e.applyFilter(this,n,t,r)},Object.defineProperty(n.prototype,"mirror",{get:function(){return this.uniforms.mirror},set:function(e){this.uniforms.mirror=e},enumerable:!1,configurable:!0}),Object.defineProperty(n.prototype,"boundary",{get:function(){return this.uniforms.boundary},set:function(e){this.uniforms.boundary=e},enumerable:!1,configurable:!0}),Object.defineProperty(n.prototype,"amplitude",{get:function(){return this.uniforms.amplitude},set:function(e){this.uniforms.amplitude[0]=e[0],this.uniforms.amplitude[1]=e[1]},enumerable:!1,configurable:!0}),Object.defineProperty(n.prototype,"waveLength",{get:function(){return this.uniforms.waveLength},set:function(e){this.uniforms.waveLength[0]=e[0],this.uniforms.waveLength[1]=e[1]},enumerable:!1,configurable:!0}),Object.defineProperty(n.prototype,"alpha",{get:function(){return this.uniforms.alpha},set:function(e){this.uniforms.alpha[0]=e[0],this.uniforms.alpha[1]=e[1]},enumerable:!1,configurable:!0}),n.defaults={mirror:!0,boundary:.5,amplitude:[0,20],waveLength:[30,100],alpha:[1,1],time:0},n}(n.Filter),N=function(e){function n(n,t,r){void 0===n&&(n=[-10,0]),void 0===t&&(t=[0,10]),void 0===r&&(r=[0,0]);var o=e.call(this,c,"precision mediump float;\n\nvarying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\nuniform vec4 filterArea;\nuniform vec2 red;\nuniform vec2 green;\nuniform vec2 blue;\n\nvoid main(void)\n{\n gl_FragColor.r = texture2D(uSampler, vTextureCoord + red/filterArea.xy).r;\n gl_FragColor.g = texture2D(uSampler, vTextureCoord + green/filterArea.xy).g;\n gl_FragColor.b = texture2D(uSampler, vTextureCoord + blue/filterArea.xy).b;\n gl_FragColor.a = texture2D(uSampler, vTextureCoord).a;\n}\n")||this;return o.red=n,o.green=t,o.blue=r,o}return u(n,e),Object.defineProperty(n.prototype,"red",{get:function(){return this.uniforms.red},set:function(e){this.uniforms.red=e},enumerable:!1,configurable:!0}),Object.defineProperty(n.prototype,"green",{get:function(){return this.uniforms.green},set:function(e){this.uniforms.green=e},enumerable:!1,configurable:!0}),Object.defineProperty(n.prototype,"blue",{get:function(){return this.uniforms.blue},set:function(e){this.uniforms.blue=e},enumerable:!1,configurable:!0}),n}(n.Filter),X=function(e){function n(t,r,o){void 0===t&&(t=[0,0]),void 0===o&&(o=0);var i=e.call(this,c,"varying vec2 vTextureCoord;\nuniform sampler2D uSampler;\nuniform vec4 filterArea;\nuniform vec4 filterClamp;\n\nuniform vec2 center;\n\nuniform float amplitude;\nuniform float wavelength;\n// uniform float power;\nuniform float brightness;\nuniform float speed;\nuniform float radius;\n\nuniform float time;\n\nconst float PI = 3.14159;\n\nvoid main()\n{\n float halfWavelength = wavelength * 0.5 / filterArea.x;\n float maxRadius = radius / filterArea.x;\n float currentRadius = time * speed / filterArea.x;\n\n float fade = 1.0;\n\n if (maxRadius > 0.0) {\n if (currentRadius > maxRadius) {\n gl_FragColor = texture2D(uSampler, vTextureCoord);\n return;\n }\n fade = 1.0 - pow(currentRadius / maxRadius, 2.0);\n }\n\n vec2 dir = vec2(vTextureCoord - center / filterArea.xy);\n dir.y *= filterArea.y / filterArea.x;\n float dist = length(dir);\n\n if (dist <= 0.0 || dist < currentRadius - halfWavelength || dist > currentRadius + halfWavelength) {\n gl_FragColor = texture2D(uSampler, vTextureCoord);\n return;\n }\n\n vec2 diffUV = normalize(dir);\n\n float diff = (dist - currentRadius) / halfWavelength;\n\n float p = 1.0 - pow(abs(diff), 2.0);\n\n // float powDiff = diff * pow(p, 2.0) * ( amplitude * fade );\n float powDiff = 1.25 * sin(diff * PI) * p * ( amplitude * fade );\n\n vec2 offset = diffUV * powDiff / filterArea.xy;\n\n // Do clamp :\n vec2 coord = vTextureCoord + offset;\n vec2 clampedCoord = clamp(coord, filterClamp.xy, filterClamp.zw);\n vec4 color = texture2D(uSampler, clampedCoord);\n if (coord != clampedCoord) {\n color *= max(0.0, 1.0 - length(coord - clampedCoord));\n }\n\n // No clamp :\n // gl_FragColor = texture2D(uSampler, vTextureCoord + offset);\n\n color.rgb *= 1.0 + (brightness - 1.0) * p * fade;\n\n gl_FragColor = color;\n}\n")||this;return i.center=t,Object.assign(i,n.defaults,r),i.time=o,i}return u(n,e),n.prototype.apply=function(e,n,t,r){this.uniforms.time=this.time,e.applyFilter(this,n,t,r)},Object.defineProperty(n.prototype,"center",{get:function(){return this.uniforms.center},set:function(e){this.uniforms.center=e},enumerable:!1,configurable:!0}),Object.defineProperty(n.prototype,"amplitude",{get:function(){return this.uniforms.amplitude},set:function(e){this.uniforms.amplitude=e},enumerable:!1,configurable:!0}),Object.defineProperty(n.prototype,"wavelength",{get:function(){return this.uniforms.wavelength},set:function(e){this.uniforms.wavelength=e},enumerable:!1,configurable:!0}),Object.defineProperty(n.prototype,"brightness",{get:function(){return this.uniforms.brightness},set:function(e){this.uniforms.brightness=e},enumerable:!1,configurable:!0}),Object.defineProperty(n.prototype,"speed",{get:function(){return this.uniforms.speed},set:function(e){this.uniforms.speed=e},enumerable:!1,configurable:!0}),Object.defineProperty(n.prototype,"radius",{get:function(){return this.uniforms.radius},set:function(e){this.uniforms.radius=e},enumerable:!1,configurable:!0}),n.defaults={amplitude:30,wavelength:160,brightness:1,speed:500,radius:-1},n}(n.Filter),B=function(e){function n(n,t,r){void 0===t&&(t=0),void 0===r&&(r=1);var o=e.call(this,c,"varying vec2 vTextureCoord;\nuniform sampler2D uSampler;\nuniform sampler2D uLightmap;\nuniform vec4 filterArea;\nuniform vec2 dimensions;\nuniform vec4 ambientColor;\nvoid main() {\n vec4 diffuseColor = texture2D(uSampler, vTextureCoord);\n vec2 lightCoord = (vTextureCoord * filterArea.xy) / dimensions;\n vec4 light = texture2D(uLightmap, lightCoord);\n vec3 ambient = ambientColor.rgb * ambientColor.a;\n vec3 intensity = ambient + light.rgb;\n vec3 finalColor = diffuseColor.rgb * intensity;\n gl_FragColor = vec4(finalColor, diffuseColor.a);\n}\n")||this;return o._color=0,o.uniforms.dimensions=new Float32Array(2),o.uniforms.ambientColor=new Float32Array([0,0,0,r]),o.texture=n,o.color=t,o}return u(n,e),n.prototype.apply=function(e,n,t,r){var o,i;this.uniforms.dimensions[0]=null===(o=n.filterFrame)||void 0===o?void 0:o.width,this.uniforms.dimensions[1]=null===(i=n.filterFrame)||void 0===i?void 0:i.height,e.applyFilter(this,n,t,r)},Object.defineProperty(n.prototype,"texture",{get:function(){return this.uniforms.uLightmap},set:function(e){this.uniforms.uLightmap=e},enumerable:!1,configurable:!0}),Object.defineProperty(n.prototype,"color",{get:function(){return this._color},set:function(e){var n=this.uniforms.ambientColor;"number"==typeof e?(o.hex2rgb(e,n),this._color=e):(n[0]=e[0],n[1]=e[1],n[2]=e[2],n[3]=e[3],this._color=o.rgb2hex(n))},enumerable:!1,configurable:!0}),Object.defineProperty(n.prototype,"alpha",{get:function(){return this.uniforms.ambientColor[3]},set:function(e){this.uniforms.ambientColor[3]=e},enumerable:!1,configurable:!0}),n}(n.Filter),G=function(e){function n(n,r,o,i){void 0===n&&(n=100),void 0===r&&(r=600);var l=e.call(this,c,"varying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\nuniform float blur;\nuniform float gradientBlur;\nuniform vec2 start;\nuniform vec2 end;\nuniform vec2 delta;\nuniform vec2 texSize;\n\nfloat random(vec3 scale, float seed)\n{\n return fract(sin(dot(gl_FragCoord.xyz + seed, scale)) * 43758.5453 + seed);\n}\n\nvoid main(void)\n{\n vec4 color = vec4(0.0);\n float total = 0.0;\n\n float offset = random(vec3(12.9898, 78.233, 151.7182), 0.0);\n vec2 normal = normalize(vec2(start.y - end.y, end.x - start.x));\n float radius = smoothstep(0.0, 1.0, abs(dot(vTextureCoord * texSize - start, normal)) / gradientBlur) * blur;\n\n for (float t = -30.0; t <= 30.0; t++)\n {\n float percent = (t + offset - 0.5) / 30.0;\n float weight = 1.0 - abs(percent);\n vec4 sample = texture2D(uSampler, vTextureCoord + delta / texSize * percent * radius);\n sample.rgb *= sample.a;\n color += sample * weight;\n total += weight;\n }\n\n color /= total;\n color.rgb /= color.a + 0.00001;\n\n gl_FragColor = color;\n}\n")||this;return l.uniforms.blur=n,l.uniforms.gradientBlur=r,l.uniforms.start=o||new t.Point(0,window.innerHeight/2),l.uniforms.end=i||new t.Point(600,window.innerHeight/2),l.uniforms.delta=new t.Point(30,30),l.uniforms.texSize=new t.Point(window.innerWidth,window.innerHeight),l.updateDelta(),l}return u(n,e),n.prototype.updateDelta=function(){this.uniforms.delta.x=0,this.uniforms.delta.y=0},Object.defineProperty(n.prototype,"blur",{get:function(){return this.uniforms.blur},set:function(e){this.uniforms.blur=e},enumerable:!1,configurable:!0}),Object.defineProperty(n.prototype,"gradientBlur",{get:function(){return this.uniforms.gradientBlur},set:function(e){this.uniforms.gradientBlur=e},enumerable:!1,configurable:!0}),Object.defineProperty(n.prototype,"start",{get:function(){return this.uniforms.start},set:function(e){this.uniforms.start=e,this.updateDelta()},enumerable:!1,configurable:!0}),Object.defineProperty(n.prototype,"end",{get:function(){return this.uniforms.end},set:function(e){this.uniforms.end=e,this.updateDelta()},enumerable:!1,configurable:!0}),n}(n.Filter),K=function(e){function n(){return null!==e&&e.apply(this,arguments)||this}return u(n,e),n.prototype.updateDelta=function(){var e=this.uniforms.end.x-this.uniforms.start.x,n=this.uniforms.end.y-this.uniforms.start.y,t=Math.sqrt(e*e+n*n);this.uniforms.delta.x=e/t,this.uniforms.delta.y=n/t},n}(G),q=function(e){function n(){return null!==e&&e.apply(this,arguments)||this}return u(n,e),n.prototype.updateDelta=function(){var e=this.uniforms.end.x-this.uniforms.start.x,n=this.uniforms.end.y-this.uniforms.start.y,t=Math.sqrt(e*e+n*n);this.uniforms.delta.x=-n/t,this.uniforms.delta.y=e/t},n}(G),W=function(e){function n(n,t,r,o){void 0===n&&(n=100),void 0===t&&(t=600);var i=e.call(this)||this;return i.tiltShiftXFilter=new K(n,t,r,o),i.tiltShiftYFilter=new q(n,t,r,o),i}return u(n,e),n.prototype.apply=function(e,n,t,r){var o=e.getFilterTexture();this.tiltShiftXFilter.apply(e,n,o,1),this.tiltShiftYFilter.apply(e,o,t,r),e.returnFilterTexture(o)},Object.defineProperty(n.prototype,"blur",{get:function(){return this.tiltShiftXFilter.blur},set:function(e){this.tiltShiftXFilter.blur=this.tiltShiftYFilter.blur=e},enumerable:!1,configurable:!0}),Object.defineProperty(n.prototype,"gradientBlur",{get:function(){return this.tiltShiftXFilter.gradientBlur},set:function(e){this.tiltShiftXFilter.gradientBlur=this.tiltShiftYFilter.gradientBlur=e},enumerable:!1,configurable:!0}),Object.defineProperty(n.prototype,"start",{get:function(){return this.tiltShiftXFilter.start},set:function(e){this.tiltShiftXFilter.start=this.tiltShiftYFilter.start=e},enumerable:!1,configurable:!0}),Object.defineProperty(n.prototype,"end",{get:function(){return this.tiltShiftXFilter.end},set:function(e){this.tiltShiftXFilter.end=this.tiltShiftYFilter.end=e},enumerable:!1,configurable:!0}),n}(n.Filter),Y=function(e){function n(t){var r=e.call(this,c,"varying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\nuniform float radius;\nuniform float angle;\nuniform vec2 offset;\nuniform vec4 filterArea;\n\nvec2 mapCoord( vec2 coord )\n{\n coord *= filterArea.xy;\n coord += filterArea.zw;\n\n return coord;\n}\n\nvec2 unmapCoord( vec2 coord )\n{\n coord -= filterArea.zw;\n coord /= filterArea.xy;\n\n return coord;\n}\n\nvec2 twist(vec2 coord)\n{\n coord -= offset;\n\n float dist = length(coord);\n\n if (dist < radius)\n {\n float ratioDist = (radius - dist) / radius;\n float angleMod = ratioDist * ratioDist * angle;\n float s = sin(angleMod);\n float c = cos(angleMod);\n coord = vec2(coord.x * c - coord.y * s, coord.x * s + coord.y * c);\n }\n\n coord += offset;\n\n return coord;\n}\n\nvoid main(void)\n{\n\n vec2 coord = mapCoord(vTextureCoord);\n\n coord = twist(coord);\n\n coord = unmapCoord(coord);\n\n gl_FragColor = texture2D(uSampler, coord );\n\n}\n")||this;return Object.assign(r,n.defaults,t),r}return u(n,e),Object.defineProperty(n.prototype,"offset",{get:function(){return this.uniforms.offset},set:function(e){this.uniforms.offset=e},enumerable:!1,configurable:!0}),Object.defineProperty(n.prototype,"radius",{get:function(){return this.uniforms.radius},set:function(e){this.uniforms.radius=e},enumerable:!1,configurable:!0}),Object.defineProperty(n.prototype,"angle",{get:function(){return this.uniforms.angle},set:function(e){this.uniforms.angle=e},enumerable:!1,configurable:!0}),n.defaults={radius:200,angle:4,padding:20,offset:new t.Point},n}(n.Filter),Z=function(e){function n(t){var r,o=Object.assign(n.defaults,t),i=o.maxKernelSize,l=function(e,n){var t={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&n.indexOf(r)<0&&(t[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var o=0;for(r=Object.getOwnPropertySymbols(e);o= 0.0 && dist > radius) { // radius < 0 means it's infinity\n delta = dist - radius;\n gap = gradient;\n }\n\n if (delta > 0.0) {\n float normalCount = gap / filterArea.x;\n delta = (normalCount - delta) / normalCount;\n countLimit *= delta;\n strength *= delta;\n if (countLimit < 1.0)\n {\n gl_FragColor = texture2D(uSampler, vTextureCoord);\n return;\n }\n }\n\n // randomize the lookup values to hide the fixed number of samples\n float offset = rand(vTextureCoord, 0.0);\n\n float total = 0.0;\n vec4 color = vec4(0.0);\n\n dir *= strength;\n\n for (float t = 0.0; t < MAX_KERNEL_SIZE; t++) {\n float percent = (t + offset) / MAX_KERNEL_SIZE;\n float weight = 4.0 * (percent - percent * percent);\n vec2 p = vTextureCoord + dir * percent;\n vec4 sample = texture2D(uSampler, p);\n\n // switch to pre-multiplied alpha to correctly blur transparent images\n // sample.rgb *= sample.a;\n\n color += sample * weight;\n total += weight;\n\n if (t > countLimit){\n break;\n }\n }\n\n color /= total;\n // switch back from pre-multiplied alpha\n // color.rgb /= color.a + 0.00001;\n\n gl_FragColor = color;\n}\n".replace("${maxKernelSize}",i.toFixed(1)))||this,Object.assign(r,l),r}return u(n,e),Object.defineProperty(n.prototype,"center",{get:function(){return this.uniforms.uCenter},set:function(e){this.uniforms.uCenter=e},enumerable:!1,configurable:!0}),Object.defineProperty(n.prototype,"strength",{get:function(){return this.uniforms.uStrength},set:function(e){this.uniforms.uStrength=e},enumerable:!1,configurable:!0}),Object.defineProperty(n.prototype,"innerRadius",{get:function(){return this.uniforms.uInnerRadius},set:function(e){this.uniforms.uInnerRadius=e},enumerable:!1,configurable:!0}),Object.defineProperty(n.prototype,"radius",{get:function(){return this.uniforms.uRadius},set:function(e){(e<0||e===1/0)&&(e=-1),this.uniforms.uRadius=e},enumerable:!1,configurable:!0}),n.defaults={strength:.1,center:[0,0],innerRadius:0,radius:-1,maxKernelSize:32},n}(n.Filter);return e.AdjustmentFilter=m,e.AdvancedBloomFilter=h,e.AsciiFilter=g,e.BevelFilter=v,e.BloomFilter=y,e.BulgePinchFilter=b,e.CRTFilter=z,e.ColorMapFilter=x,e.ColorOverlayFilter=_,e.ColorReplaceFilter=C,e.ConvolutionFilter=S,e.CrossHatchFilter=F,e.DotFilter=O,e.DropShadowFilter=P,e.EmbossFilter=A,e.GlitchFilter=T,e.GlowFilter=w,e.GodrayFilter=D,e.KawaseBlurFilter=d,e.MotionBlurFilter=j,e.MultiColorReplaceFilter=M,e.OldFilmFilter=R,e.OutlineFilter=E,e.PixelateFilter=I,e.RGBSplitFilter=N,e.RadialBlurFilter=k,e.ReflectionFilter=L,e.ShockwaveFilter=X,e.SimpleLightmapFilter=B,e.TiltShiftAxisFilter=G,e.TiltShiftFilter=W,e.TiltShiftXFilter=K,e.TiltShiftYFilter=q,e.TwistFilter=Y,e.ZoomBlurFilter=Z,Object.defineProperty(e,"__esModule",{value:!0}),e}({},PIXI,PIXI,PIXI,PIXI.utils,PIXI,PIXI.filters,PIXI.filters);Object.assign(PIXI.filters,__filters); /*! - * pixi-particles - v4.2.0 - * Compiled Sat, 26 Oct 2019 14:40:23 UTC + * pixi-particles - v4.3.1 + * Compiled Wed, 09 Jun 2021 13:12:54 UTC * * pixi-particles is licensed under the MIT License. * http://www.opensource.org/licenses/mit-license */ this.PIXI = this.PIXI || {}; (function (exports, pixi) { - 'use strict'; + 'use strict'; - /** - * A single node in a PropertyList. - */ - var PropertyNode = /** @class */ (function () { - /** - * @param value The value for this node - * @param time The time for this node, between 0-1 - * @param [ease] Custom ease for this list. Only relevant for the first node. - */ - function PropertyNode(value, time, ease) { - this.value = value; - this.time = time; - this.next = null; - this.isStepped = false; - if (ease) { - this.ease = typeof ease == "function" ? ease : exports.ParticleUtils.generateEase(ease); - } - else { - this.ease = null; - } - } - /** - * Creates a list of property values from a data object {list, isStepped} with a list of objects in - * the form {value, time}. Alternatively, the data object can be in the deprecated form of - * {start, end}. - * @param data The data for the list. - * @param data.list The array of value and time objects. - * @param data.isStepped If the list is stepped rather than interpolated. - * @param data.ease Custom ease for this list. - * @return The first node in the list - */ - PropertyNode.createList = function (data) { - if ("list" in data) { - var array = data.list; - var node = void 0, first = void 0; - var _a = array[0], value = _a.value, time = _a.time; - first = node = new PropertyNode(typeof value === 'string' ? exports.ParticleUtils.hexToRGB(value) : value, time, data.ease); - //only set up subsequent nodes if there are a bunch or the 2nd one is different from the first - if (array.length > 2 || (array.length === 2 && array[1].value !== value)) { - for (var i = 1; i < array.length; ++i) { - var _b = array[i], value_1 = _b.value, time_1 = _b.time; - node.next = new PropertyNode(typeof value_1 === 'string' ? exports.ParticleUtils.hexToRGB(value_1) : value_1, time_1); - node = node.next; - } - } - first.isStepped = !!data.isStepped; - return first; - } - else { - //Handle deprecated version here - var start = new PropertyNode(typeof data.start === 'string' ? exports.ParticleUtils.hexToRGB(data.start) : data.start, 0); - //only set up a next value if it is different from the starting value - if (data.end !== data.start) - start.next = new PropertyNode(typeof data.end === 'string' ? exports.ParticleUtils.hexToRGB(data.end) : data.end, 1); - return start; - } - }; - return PropertyNode; - }()); - - // get Texture.from()/Texture.fromImage(), in V4 and V5 friendly methods - /** - * @hidden - */ - var TextureFromString; - // to avoid Rollup transforming our import, save pixi namespace in a variable - var pixiNS = pixi; - if (parseInt(/^(\d+)\./.exec(pixi.VERSION)[1]) < 5) { - TextureFromString = pixiNS.Texture.fromImage; - } - else { - TextureFromString = pixiNS.Texture.from; - } - function GetTextureFromString(s) { - return TextureFromString(s); - } - (function (ParticleUtils) { - /** - * If errors and warnings should be logged within the library. - */ - ParticleUtils.verbose = false; - ParticleUtils.DEG_TO_RADS = Math.PI / 180; - /** - * Rotates a point by a given angle. - * @param angle The angle to rotate by in degrees - * @param p The point to rotate around 0,0. - */ - function rotatePoint(angle, p) { - if (!angle) - return; - angle *= ParticleUtils.DEG_TO_RADS; - var s = Math.sin(angle); - var c = Math.cos(angle); - var xnew = p.x * c - p.y * s; - var ynew = p.x * s + p.y * c; - p.x = xnew; - p.y = ynew; - } - ParticleUtils.rotatePoint = rotatePoint; - /** - * Combines separate color components (0-255) into a single uint color. - * @param r The red value of the color - * @param g The green value of the color - * @param b The blue value of the color - * @return The color in the form of 0xRRGGBB - */ - function combineRGBComponents(r, g, b /*, a*/) { - return /*a << 24 |*/ r << 16 | g << 8 | b; - } - ParticleUtils.combineRGBComponents = combineRGBComponents; - /** - * Reduces the point to a length of 1. - * @param point The point to normalize - */ - function normalize(point) { - var oneOverLen = 1 / ParticleUtils.length(point); - point.x *= oneOverLen; - point.y *= oneOverLen; - } - ParticleUtils.normalize = normalize; - /** - * Multiplies the x and y values of this point by a value. - * @param point The point to scaleBy - * @param value The value to scale by. - */ - function scaleBy(point, value) { - point.x *= value; - point.y *= value; - } - ParticleUtils.scaleBy = scaleBy; - /** - * Returns the length (or magnitude) of this point. - * @param point The point to measure length - * @return The length of this point. - */ - function length(point) { - return Math.sqrt(point.x * point.x + point.y * point.y); - } - ParticleUtils.length = length; - /** - * Converts a hex string from "#AARRGGBB", "#RRGGBB", "0xAARRGGBB", "0xRRGGBB", - * "AARRGGBB", or "RRGGBB" to an object of ints of 0-255, as - * {r, g, b, (a)}. - * @param color The input color string. - * @param output An object to put the output in. If omitted, a new object is created. - * @return The object with r, g, and b properties, possibly with an a property. - */ - function hexToRGB(color, output) { - if (!output) - output = {}; - if (color.charAt(0) == "#") - color = color.substr(1); - else if (color.indexOf("0x") === 0) - color = color.substr(2); - var alpha; - if (color.length == 8) { - alpha = color.substr(0, 2); - color = color.substr(2); - } - output.r = parseInt(color.substr(0, 2), 16); //Red - output.g = parseInt(color.substr(2, 2), 16); //Green - output.b = parseInt(color.substr(4, 2), 16); //Blue - if (alpha) - output.a = parseInt(alpha, 16); - return output; - } - ParticleUtils.hexToRGB = hexToRGB; - /** - * Generates a custom ease function, based on the GreenSock custom ease, as demonstrated - * by the related tool at http://www.greensock.com/customease/. - * @param segments An array of segments, as created by - * http://www.greensock.com/customease/. - * @return A function that calculates the percentage of change at - * a given point in time (0-1 inclusive). - */ - function generateEase(segments) { - var qty = segments.length; - var oneOverQty = 1 / qty; - /* - * Calculates the percentage of change at a given point in time (0-1 inclusive). - * @param {Number} time The time of the ease, 0-1 inclusive. - * @return {Number} The percentage of the change, 0-1 inclusive (unless your - * ease goes outside those bounds). - */ - return function (time) { - var t, s; - var i = (qty * time) | 0; //do a quick floor operation - t = (time - (i * oneOverQty)) * qty; - s = segments[i] || segments[qty - 1]; - return (s.s + t * (2 * (1 - t) * (s.cp - s.s) + t * (s.e - s.s))); - }; - } - ParticleUtils.generateEase = generateEase; - /** - * Gets a blend mode, ensuring that it is valid. - * @param name The name of the blend mode to get. - * @return The blend mode as specified in the PIXI.BLEND_MODES enumeration. - */ - function getBlendMode(name) { - if (!name) - return pixi.BLEND_MODES.NORMAL; - name = name.toUpperCase(); - while (name.indexOf(" ") >= 0) - name = name.replace(" ", "_"); - return pixi.BLEND_MODES[name] || pixi.BLEND_MODES.NORMAL; - } - ParticleUtils.getBlendMode = getBlendMode; - /** - * Converts a list of {value, time} objects starting at time 0 and ending at time 1 into an evenly - * spaced stepped list of PropertyNodes for color values. This is primarily to handle conversion of - * linear gradients to fewer colors, allowing for some optimization for Canvas2d fallbacks. - * @param list The list of data to convert. - * @param [numSteps=10] The number of steps to use. - * @return The blend mode as specified in the PIXI.blendModes enumeration. - */ - function createSteppedGradient(list, numSteps) { - if (numSteps === void 0) { numSteps = 10; } - if (typeof numSteps !== 'number' || numSteps <= 0) - numSteps = 10; - var first = new PropertyNode(ParticleUtils.hexToRGB(list[0].value), list[0].time); - first.isStepped = true; - var currentNode = first; - var current = list[0]; - var nextIndex = 1; - var next = list[nextIndex]; - for (var i = 1; i < numSteps; ++i) { - var lerp = i / numSteps; - //ensure we are on the right segment, if multiple - while (lerp > next.time) { - current = next; - next = list[++nextIndex]; - } - //convert the lerp value to the segment range - lerp = (lerp - current.time) / (next.time - current.time); - var curVal = ParticleUtils.hexToRGB(current.value); - var nextVal = ParticleUtils.hexToRGB(next.value); - var output = { - r: (nextVal.r - curVal.r) * lerp + curVal.r, - g: (nextVal.g - curVal.g) * lerp + curVal.g, - b: (nextVal.b - curVal.b) * lerp + curVal.b, - }; - currentNode.next = new PropertyNode(output, i / numSteps); - currentNode = currentNode.next; - } - //we don't need to have a PropertyNode for time of 1, because in a stepped version at that point - //the particle has died of old age - return first; - } - ParticleUtils.createSteppedGradient = createSteppedGradient; - })(exports.ParticleUtils || (exports.ParticleUtils = {})); - - /*! ***************************************************************************** - Copyright (c) Microsoft Corporation. All rights reserved. - Licensed under the Apache License, Version 2.0 (the "License"); you may not use - this file except in compliance with the License. You may obtain a copy of the - License at http://www.apache.org/licenses/LICENSE-2.0 - - THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED - WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, - MERCHANTABLITY OR NON-INFRINGEMENT. - - See the Apache Version 2.0 License for specific language governing permissions - and limitations under the License. - ***************************************************************************** */ - /* global Reflect, Promise */ - - var extendStatics = function(d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; - return extendStatics(d, b); - }; - - function __extends(d, b) { - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - } - - var __assign = function() { - __assign = Object.assign || function __assign(t) { - for (var s, i = 1, n = arguments.length; i < n; i++) { - s = arguments[i]; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; - } - return t; - }; - return __assign.apply(this, arguments); - }; - - function __rest(s, e) { - var t = {}; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) - t[p] = s[p]; - if (s != null && typeof Object.getOwnPropertySymbols === "function") - for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) if (e.indexOf(p[i]) < 0) - t[p[i]] = s[p[i]]; - return t; - } - - function __decorate(decorators, target, key, desc) { - var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; - if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); - else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; - return c > 3 && r && Object.defineProperty(target, key, r), r; - } - - function __param(paramIndex, decorator) { - return function (target, key) { decorator(target, key, paramIndex); } - } - - function __metadata(metadataKey, metadataValue) { - if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue); - } - - function __awaiter(thisArg, _arguments, P, generator) { - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - } - - function __generator(thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (_) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; - } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; - } - } - - function __exportStar(m, exports) { - for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p]; - } - - function __values(o) { - var m = typeof Symbol === "function" && o[Symbol.iterator], i = 0; - if (m) return m.call(o); - return { - next: function () { - if (o && i >= o.length) o = void 0; - return { value: o && o[i++], done: !o }; - } - }; - } - - function __read(o, n) { - var m = typeof Symbol === "function" && o[Symbol.iterator]; - if (!m) return o; - var i = m.call(o), r, ar = [], e; - try { - while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); - } - catch (error) { e = { error: error }; } - finally { - try { - if (r && !r.done && (m = i["return"])) m.call(i); - } - finally { if (e) throw e.error; } - } - return ar; - } - - function __spread() { - for (var ar = [], i = 0; i < arguments.length; i++) - ar = ar.concat(__read(arguments[i])); - return ar; - } - - function __await(v) { - return this instanceof __await ? (this.v = v, this) : new __await(v); - } - - function __asyncGenerator(thisArg, _arguments, generator) { - if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var g = generator.apply(thisArg, _arguments || []), i, q = []; - return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; - function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } - function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } - function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } - function fulfill(value) { resume("next", value); } - function reject(value) { resume("throw", value); } - function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } - } - - function __asyncDelegator(o) { - var i, p; - return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i; - function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; } : f; } - } - - function __asyncValues(o) { - if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var m = o[Symbol.asyncIterator], i; - return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i); - function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; } - function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); } - } - - function __makeTemplateObject(cooked, raw) { - if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; } - return cooked; - }; - - function __importStar(mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; - result.default = mod; - return result; - } - - function __importDefault(mod) { - return (mod && mod.__esModule) ? mod : { default: mod }; - } - - /** - * Singly linked list container for keeping track of interpolated properties for particles. - * Each Particle will have one of these for each interpolated property. - */ - var PropertyList = /** @class */ (function () { - /** - * @param isColor If this list handles color values - */ - function PropertyList(isColor) { - if (isColor === void 0) { isColor = false; } - this.current = null; - this.next = null; - this.isColor = !!isColor; - this.interpolate = null; - this.ease = null; - } - /** - * Resets the list for use. - * @param first The first node in the list. - * @param first.isStepped If the values should be stepped instead of interpolated linearly. - */ - PropertyList.prototype.reset = function (first) { - this.current = first; - this.next = first.next; - var isSimple = this.next && this.next.time >= 1; - if (isSimple) { - this.interpolate = this.isColor ? intColorSimple : intValueSimple; - } - else if (first.isStepped) { - this.interpolate = this.isColor ? intColorStepped : intValueStepped; - } - else { - this.interpolate = this.isColor ? intColorComplex : intValueComplex; - } - this.ease = this.current.ease; - }; - return PropertyList; - }()); - function intValueSimple(lerp) { - if (this.ease) - lerp = this.ease(lerp); - return (this.next.value - this.current.value) * lerp + this.current.value; - } - function intColorSimple(lerp) { - if (this.ease) - lerp = this.ease(lerp); - var curVal = this.current.value, nextVal = this.next.value; - var r = (nextVal.r - curVal.r) * lerp + curVal.r; - var g = (nextVal.g - curVal.g) * lerp + curVal.g; - var b = (nextVal.b - curVal.b) * lerp + curVal.b; - return exports.ParticleUtils.combineRGBComponents(r, g, b); - } - function intValueComplex(lerp) { - if (this.ease) - lerp = this.ease(lerp); - //make sure we are on the right segment - while (lerp > this.next.time) { - this.current = this.next; - this.next = this.next.next; - } - //convert the lerp value to the segment range - lerp = (lerp - this.current.time) / (this.next.time - this.current.time); - return (this.next.value - this.current.value) * lerp + this.current.value; - } - function intColorComplex(lerp) { - if (this.ease) - lerp = this.ease(lerp); - //make sure we are on the right segment - while (lerp > this.next.time) { - this.current = this.next; - this.next = this.next.next; - } - //convert the lerp value to the segment range - lerp = (lerp - this.current.time) / (this.next.time - this.current.time); - var curVal = this.current.value, nextVal = this.next.value; - var r = (nextVal.r - curVal.r) * lerp + curVal.r; - var g = (nextVal.g - curVal.g) * lerp + curVal.g; - var b = (nextVal.b - curVal.b) * lerp + curVal.b; - return exports.ParticleUtils.combineRGBComponents(r, g, b); - } - function intValueStepped(lerp) { - if (this.ease) - lerp = this.ease(lerp); - //make sure we are on the right segment - while (this.next && lerp > this.next.time) { - this.current = this.next; - this.next = this.next.next; - } - return this.current.value; - } - function intColorStepped(lerp) { - if (this.ease) - lerp = this.ease(lerp); - //make sure we are on the right segment - while (this.next && lerp > this.next.time) { - this.current = this.next; - this.next = this.next.next; - } - var curVal = this.current.value; - return exports.ParticleUtils.combineRGBComponents(curVal.r, curVal.g, curVal.b); - } - - /** - * An individual particle image. You shouldn't have to deal with these. - */ - var Particle = /** @class */ (function (_super) { - __extends(Particle, _super); - /** - * @param {PIXI.particles.Emitter} emitter The emitter that controls this particle. - */ - function Particle(emitter) { - var _this = - //start off the sprite with a blank texture, since we are going to replace it - //later when the particle is initialized. - _super.call(this) || this; - _this.emitter = emitter; - //particles should be centered - _this.anchor.x = _this.anchor.y = 0.5; - _this.velocity = new pixi.Point(); - _this.rotationSpeed = 0; - _this.rotationAcceleration = 0; - _this.maxLife = 0; - _this.age = 0; - _this.ease = null; - _this.extraData = null; - _this.alphaList = new PropertyList(); - _this.speedList = new PropertyList(); - _this.speedMultiplier = 1; - _this.acceleration = new pixi.Point(); - _this.maxSpeed = NaN; - _this.scaleList = new PropertyList(); - _this.scaleMultiplier = 1; - _this.colorList = new PropertyList(true); - _this._doAlpha = false; - _this._doScale = false; - _this._doSpeed = false; - _this._doAcceleration = false; - _this._doColor = false; - _this._doNormalMovement = false; - _this._oneOverLife = 0; - _this.next = null; - _this.prev = null; - //save often used functions on the instance instead of the prototype for better speed - _this.init = _this.init; - _this.Particle_init = Particle.prototype.init; - _this.update = _this.update; - _this.Particle_update = Particle.prototype.update; - _this.Sprite_destroy = _super.prototype.destroy; - _this.Particle_destroy = Particle.prototype.destroy; - _this.applyArt = _this.applyArt; - _this.kill = _this.kill; - return _this; - } - /** - * Initializes the particle for use, based on the properties that have to - * have been set already on the particle. - */ - Particle.prototype.init = function () { - //reset the age - this.age = 0; - //set up the velocity based on the start speed and rotation - this.velocity.x = this.speedList.current.value * this.speedMultiplier; - this.velocity.y = 0; - exports.ParticleUtils.rotatePoint(this.rotation, this.velocity); - if (this.noRotation) { - this.rotation = 0; - } - else { - //convert rotation to Radians from Degrees - this.rotation *= exports.ParticleUtils.DEG_TO_RADS; - } - //convert rotation speed to Radians from Degrees - this.rotationSpeed *= exports.ParticleUtils.DEG_TO_RADS; - this.rotationAcceleration *= exports.ParticleUtils.DEG_TO_RADS; - //set alpha to inital alpha - this.alpha = this.alphaList.current.value; - //set scale to initial scale - this.scale.x = this.scale.y = this.scaleList.current.value; - //figure out what we need to interpolate - this._doAlpha = !!this.alphaList.current.next; - this._doSpeed = !!this.speedList.current.next; - this._doScale = !!this.scaleList.current.next; - this._doColor = !!this.colorList.current.next; - this._doAcceleration = this.acceleration.x !== 0 || this.acceleration.y !== 0; - //_doNormalMovement can be cancelled by subclasses - this._doNormalMovement = this._doSpeed || this.speedList.current.value !== 0 || this._doAcceleration; - //save our lerp helper - this._oneOverLife = 1 / this.maxLife; - //set the inital color - var color = this.colorList.current.value; - this.tint = exports.ParticleUtils.combineRGBComponents(color.r, color.g, color.b); - //ensure visibility - this.visible = true; - }; - /** - * Sets the texture for the particle. This can be overridden to allow - * for an animated particle. - * @param art The texture to set. - */ - Particle.prototype.applyArt = function (art) { - this.texture = art || pixi.Texture.EMPTY; - }; - /** - * Updates the particle. - * @param delta Time elapsed since the previous frame, in __seconds__. - * @return The standard interpolation multiplier (0-1) used for all - * relevant particle properties. A value of -1 means the particle - * died of old age instead. - */ - Particle.prototype.update = function (delta) { - //increase age - this.age += delta; - //recycle particle if it is too old - if (this.age >= this.maxLife || this.age < 0) { - this.kill(); - return -1; - } - //determine our interpolation value - var lerp = this.age * this._oneOverLife; //lifetime / maxLife; - if (this.ease) { - if (this.ease.length == 4) { - //the t, b, c, d parameters that some tween libraries use - //(time, initial value, end value, duration) - lerp = this.ease(lerp, 0, 1, 1); - } - else { - //the simplified version that we like that takes - //one parameter, time from 0-1. TweenJS eases provide this usage. - lerp = this.ease(lerp); - } - } - //interpolate alpha - if (this._doAlpha) - this.alpha = this.alphaList.interpolate(lerp); - //interpolate scale - if (this._doScale) { - var scale = this.scaleList.interpolate(lerp) * this.scaleMultiplier; - this.scale.x = this.scale.y = scale; - } - //handle movement - if (this._doNormalMovement) { - var deltaX = void 0; - var deltaY = void 0; - //interpolate speed - if (this._doSpeed) { - var speed = this.speedList.interpolate(lerp) * this.speedMultiplier; - exports.ParticleUtils.normalize(this.velocity); - exports.ParticleUtils.scaleBy(this.velocity, speed); - deltaX = this.velocity.x * delta; - deltaY = this.velocity.y * delta; - } - else if (this._doAcceleration) { - var oldVX = this.velocity.x; - var oldVY = this.velocity.y; - this.velocity.x += this.acceleration.x * delta; - this.velocity.y += this.acceleration.y * delta; - if (this.maxSpeed) { - var currentSpeed = exports.ParticleUtils.length(this.velocity); - //if we are going faster than we should, clamp at the max speed - //DO NOT recalculate vector length - if (currentSpeed > this.maxSpeed) { - exports.ParticleUtils.scaleBy(this.velocity, this.maxSpeed / currentSpeed); - } - } - // calculate position delta by the midpoint between our old velocity and our new velocity - deltaX = (oldVX + this.velocity.x) / 2 * delta; - deltaY = (oldVY + this.velocity.y) / 2 * delta; - } - else { - deltaX = this.velocity.x * delta; - deltaY = this.velocity.y * delta; - } - //adjust position based on velocity - this.position.x += deltaX; - this.position.y += deltaY; - } - //interpolate color - if (this._doColor) { - this.tint = this.colorList.interpolate(lerp); - } - //update rotation - if (this.rotationAcceleration !== 0) { - var newRotationSpeed = this.rotationSpeed + this.rotationAcceleration * delta; - this.rotation += (this.rotationSpeed + newRotationSpeed) / 2 * delta; - this.rotationSpeed = newRotationSpeed; - } - else if (this.rotationSpeed !== 0) { - this.rotation += this.rotationSpeed * delta; - } - else if (this.acceleration && !this.noRotation) { - this.rotation = Math.atan2(this.velocity.y, this.velocity.x); // + Math.PI / 2; - } - return lerp; - }; - /** - * Kills the particle, removing it from the display list - * and telling the emitter to recycle it. - */ - Particle.prototype.kill = function () { - this.emitter.recycle(this); - }; - /** - * Destroys the particle, removing references and preventing future use. - */ - Particle.prototype.destroy = function () { - if (this.parent) - this.parent.removeChild(this); - this.Sprite_destroy(); - this.emitter = this.velocity = this.colorList = this.scaleList = this.alphaList = - this.speedList = this.ease = this.next = this.prev = null; - }; - /** - * Checks over the art that was passed to the Emitter's init() function, to do any special - * modifications to prepare it ahead of time. - * @param art The array of art data. For Particle, it should be an array of - * Textures. Any strings in the array will be converted to - * Textures via Texture.from(). - * @return The art, after any needed modifications. - */ - Particle.parseArt = function (art) { - //convert any strings to Textures. - var i; - for (i = art.length; i >= 0; --i) { - if (typeof art[i] == "string") - art[i] = GetTextureFromString(art[i]); - } - //particles from different base textures will be slower in WebGL than if they - //were from one spritesheet - if (exports.ParticleUtils.verbose) { - for (i = art.length - 1; i > 0; --i) { - if (art[i].baseTexture != art[i - 1].baseTexture) { - if (window.console) - console.warn("PixiParticles: using particle textures from different images may hinder performance in WebGL"); - break; - } - } - } - return art; - }; - /** - * Parses extra emitter data to ensure it is set up for this particle class. - * Particle does nothing to the extra data. - * @param extraData The extra data from the particle config. - * @return The parsed extra data. - */ - Particle.parseData = function (extraData) { - return extraData; - }; - return Particle; - }(pixi.Sprite)); - - /** - * Chain of line segments for generating spawn positions. - */ - var PolygonalChain = /** @class */ (function () { - /** - * @param data Point data for polygon chains. Either a list of points for a single chain, or a list of chains. - */ - function PolygonalChain(data) { - this.segments = []; - this.countingLengths = []; - this.totalLength = 0; - this.init(data); - } - /** - * @param data Point data for polygon chains. Either a list of points for a single chain, or a list of chains. - */ - PolygonalChain.prototype.init = function (data) { - // if data is not present, set up a segment of length 0 - if (!data || !data.length) { - this.segments.push({ p1: { x: 0, y: 0 }, p2: { x: 0, y: 0 }, l: 0 }); - } - else { - if (Array.isArray(data[0])) { - // list of segment chains, each defined as a list of points - for (var i = 0; i < data.length; ++i) { - // loop through the chain, connecting points - var chain = data[i]; - var prevPoint = chain[0]; - for (var j = 1; j < chain.length; ++j) { - var second = chain[j]; - this.segments.push({ p1: prevPoint, p2: second, l: 0 }); - prevPoint = second; - } - } - } - else { - var prevPoint = data[0]; - // list of points - for (var i = 1; i < data.length; ++i) { - var second = data[i]; - this.segments.push({ p1: prevPoint, p2: second, l: 0 }); - prevPoint = second; - } - } - } - // now go through our segments to calculate the lengths so that we - // can set up a nice weighted random distribution - for (var i = 0; i < this.segments.length; ++i) { - var _a = this.segments[i], p1 = _a.p1, p2 = _a.p2; - var segLength = Math.sqrt((p2.x - p1.x) * (p2.x - p1.x) + (p2.y - p1.y) * (p2.y - p1.y)); - // save length so we can turn a random number into a 0-1 interpolation value later - this.segments[i].l = segLength; - this.totalLength += segLength; - // keep track of the length so far, counting up - this.countingLengths.push(this.totalLength); - } - }; - /** - * Gets a random point in the chain. - * @param out The point to store the selected position in. - */ - PolygonalChain.prototype.getRandomPoint = function (out) { - // select a random spot in the length of the chain - var rand = Math.random() * this.totalLength; - var chosenSeg; - var lerp; - // if only one segment, it wins - if (this.segments.length === 1) { - chosenSeg = this.segments[0]; - lerp = rand; - } - else { - // otherwise, go through countingLengths until we have determined - // which segment we chose - for (var i = 0; i < this.countingLengths.length; ++i) { - if (rand < this.countingLengths[i]) { - chosenSeg = this.segments[i]; - // set lerp equal to the length into that segment (i.e. the remainder after subtracting all the segments before it) - lerp = i === 0 ? rand : rand - this.countingLengths[i - 1]; - break; - } - } - } - // divide lerp by the segment length, to result in a 0-1 number. - lerp /= chosenSeg.l || 1; - var p1 = chosenSeg.p1, p2 = chosenSeg.p2; - // now calculate the position in the segment that the lerp value represents - out.x = p1.x + lerp * (p2.x - p1.x); - out.y = p1.y + lerp * (p2.y - p1.y); - }; - return PolygonalChain; - }()); - - // get the shared ticker, in V4 and V5 friendly methods - /** - * @hidden - */ - var ticker; - // to avoid Rollup transforming our import, save pixi namespace in a variable - var pixiNS$1 = pixi; - if (parseInt(/^(\d+)\./.exec(pixi.VERSION)[1]) < 5) { - ticker = pixiNS$1.ticker.shared; - } - else { - ticker = pixiNS$1.Ticker.shared; - } - /** - * @hidden - */ - var helperPoint = new pixi.Point(); - /** - * A particle emitter. - */ - var Emitter = /** @class */ (function () { - /** - * @param particleParent The container to add the particles to. - * @param particleImages A texture or array of textures to use - * for the particles. Strings will be turned - * into textures via Texture.fromImage(). - * @param config A configuration object containing settings for the emitter. - * @param config.emit If config.emit is explicitly passed as false, the - * Emitter will start disabled. - * @param config.autoUpdate If config.autoUpdate is explicitly passed as - * true, the Emitter will automatically call - * update via the PIXI shared ticker. - */ - function Emitter(particleParent, particleImages, config) { - /** - * A number keeping index of currently applied image. Used to emit arts in order. - */ - this._currentImageIndex = -1; - this._particleConstructor = Particle; - //properties for individual particles - this.particleImages = null; - this.startAlpha = null; - this.startSpeed = null; - this.minimumSpeedMultiplier = 1; - this.acceleration = null; - this.maxSpeed = NaN; - this.startScale = null; - this.minimumScaleMultiplier = 1; - this.startColor = null; - this.minLifetime = 0; - this.maxLifetime = 0; - this.minStartRotation = 0; - this.maxStartRotation = 0; - this.noRotation = false; - this.minRotationSpeed = 0; - this.maxRotationSpeed = 0; - this.particleBlendMode = 0; - this.customEase = null; - this.extraData = null; - //properties for spawning particles - this._frequency = 1; - this.spawnChance = 1; - this.maxParticles = 1000; - this.emitterLifetime = -1; - this.spawnPos = null; - this.spawnType = null; - this._spawnFunc = null; - this.spawnRect = null; - this.spawnCircle = null; - this.spawnPolygonalChain = null; - this.particlesPerWave = 1; - this.particleSpacing = 0; - this.angleStart = 0; - //emitter properties - this.rotation = 0; - this.ownerPos = null; - this._prevEmitterPos = null; - this._prevPosIsValid = false; - this._posChanged = false; - this._parent = null; - this.addAtBack = false; - this.particleCount = 0; - this._emit = false; - this._spawnTimer = 0; - this._emitterLife = -1; - this._activeParticlesFirst = null; - this._activeParticlesLast = null; - this._poolFirst = null; - this._origConfig = null; - this._origArt = null; - this._autoUpdate = false; - this._currentImageIndex = -1; - this._destroyWhenComplete = false; - this._completeCallback = null; - //set the initial parent - this.parent = particleParent; - if (particleImages && config) - this.init(particleImages, config); - //save often used functions on the instance instead of the prototype for better speed - this.recycle = this.recycle; - this.update = this.update; - this.rotate = this.rotate; - this.updateSpawnPos = this.updateSpawnPos; - this.updateOwnerPos = this.updateOwnerPos; - } - Object.defineProperty(Emitter.prototype, "orderedArt", { - /** - * If the emitter is using particle art in order as provided in `particleImages`. - * Effective only when `particleImages` has multiple art options. - * This is particularly useful ensuring that each art shows up once, in case you need to emit a body in an order. - * For example: dragon - [Head, body1, body2, ..., tail] - */ - get: function () { return this._currentImageIndex !== -1; }, - set: function (value) { - this._currentImageIndex = value ? 0 : -1; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Emitter.prototype, "frequency", { - /** - * Time between particle spawns in seconds. If this value is not a number greater than 0, - * it will be set to 1 (particle per second) to prevent infinite loops. - */ - get: function () { return this._frequency; }, - set: function (value) { - //do some error checking to prevent infinite loops - if (typeof value == "number" && value > 0) - this._frequency = value; - else - this._frequency = 1; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Emitter.prototype, "particleConstructor", { - /** - * The constructor used to create new particles. The default is - * the built in Particle class. Setting this will dump any active or - * pooled particles, if the emitter has already been used. - */ - get: function () { return this._particleConstructor; }, - set: function (value) { - if (value != this._particleConstructor) { - this._particleConstructor = value; - //clean up existing particles - this.cleanup(); - //scrap all the particles - for (var particle = this._poolFirst; particle; particle = particle.next) { - particle.destroy(); - } - this._poolFirst = null; - //re-initialize the emitter so that the new constructor can do anything it needs to - if (this._origConfig && this._origArt) - this.init(this._origArt, this._origConfig); - } - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Emitter.prototype, "parent", { - /** - * The container to add particles to. Settings this will dump any active particles. - */ - get: function () { return this._parent; }, - set: function (value) { - this.cleanup(); - this._parent = value; - }, - enumerable: true, - configurable: true - }); - /** - * Sets up the emitter based on the config settings. - * @param art A texture or array of textures to use for the particles. - * @param config A configuration object containing settings for the emitter. - */ - Emitter.prototype.init = function (art, config) { - if (!art || !config) - return; - //clean up any existing particles - this.cleanup(); - //store the original config and particle images, in case we need to re-initialize - //when the particle constructor is changed - this._origConfig = config; - this._origArt = art; - //set up the array of data, also ensuring that it is an array - art = Array.isArray(art) ? art.slice() : [art]; - //run the art through the particle class's parsing function - var partClass = this._particleConstructor; - this.particleImages = partClass.parseArt ? partClass.parseArt(art) : art; - /////////////////////////// - // Particle Properties // - /////////////////////////// - //set up the alpha - if (config.alpha) { - this.startAlpha = PropertyNode.createList(config.alpha); - } - else - this.startAlpha = new PropertyNode(1, 0); - //set up the speed - if (config.speed) { - this.startSpeed = PropertyNode.createList(config.speed); - this.minimumSpeedMultiplier = ('minimumSpeedMultiplier' in config ? config.minimumSpeedMultiplier : config.speed.minimumSpeedMultiplier) || 1; - } - else { - this.minimumSpeedMultiplier = 1; - this.startSpeed = new PropertyNode(0, 0); - } - //set up acceleration - var acceleration = config.acceleration; - if (acceleration && (acceleration.x || acceleration.y)) { - //make sure we disable speed interpolation - this.startSpeed.next = null; - this.acceleration = new pixi.Point(acceleration.x, acceleration.y); - this.maxSpeed = config.maxSpeed || NaN; - } - else - this.acceleration = new pixi.Point(); - //set up the scale - if (config.scale) { - this.startScale = PropertyNode.createList(config.scale); - this.minimumScaleMultiplier = ('minimumScaleMultiplier' in config ? config.minimumScaleMultiplier : config.scale.minimumScaleMultiplier) || 1; - } - else { - this.startScale = new PropertyNode(1, 0); - this.minimumScaleMultiplier = 1; - } - //set up the color - if (config.color) { - this.startColor = PropertyNode.createList(config.color); - } - else { - this.startColor = new PropertyNode({ r: 0xFF, g: 0xFF, b: 0xFF }, 0); - } - //set up the start rotation - if (config.startRotation) { - this.minStartRotation = config.startRotation.min; - this.maxStartRotation = config.startRotation.max; - } - else - this.minStartRotation = this.maxStartRotation = 0; - if (config.noRotation && - (this.minStartRotation || this.maxStartRotation)) { - this.noRotation = !!config.noRotation; - } - else - this.noRotation = false; - //set up the rotation speed - if (config.rotationSpeed) { - this.minRotationSpeed = config.rotationSpeed.min; - this.maxRotationSpeed = config.rotationSpeed.max; - } - else - this.minRotationSpeed = this.maxRotationSpeed = 0; - this.rotationAcceleration = config.rotationAcceleration || 0; - //set up the lifetime - this.minLifetime = config.lifetime.min; - this.maxLifetime = config.lifetime.max; - //get the blend mode - this.particleBlendMode = exports.ParticleUtils.getBlendMode(config.blendMode); - //use the custom ease if provided - if (config.ease) { - this.customEase = typeof config.ease == "function" ? - config.ease : exports.ParticleUtils.generateEase(config.ease); - } - else - this.customEase = null; - //set up the extra data, running it through the particle class's parseData function. - if (partClass.parseData) - this.extraData = partClass.parseData(config.extraData); - else - this.extraData = config.extraData || null; - ////////////////////////// - // Emitter Properties // - ////////////////////////// - //reset spawn type specific settings - this.spawnRect = this.spawnCircle = null; - this.particlesPerWave = 1; - if (config.particlesPerWave && config.particlesPerWave > 1) - this.particlesPerWave = config.particlesPerWave; - this.particleSpacing = 0; - this.angleStart = 0; - //determine the spawn function to use - this.parseSpawnType(config); - //set the spawning frequency - this.frequency = config.frequency; - this.spawnChance = (typeof config.spawnChance === 'number' && config.spawnChance > 0) ? config.spawnChance : 1; - //set the emitter lifetime - this.emitterLifetime = config.emitterLifetime || -1; - //set the max particles - this.maxParticles = config.maxParticles > 0 ? config.maxParticles : 1000; - //determine if we should add the particle at the back of the list or not - this.addAtBack = !!config.addAtBack; - //reset the emitter position and rotation variables - this.rotation = 0; - this.ownerPos = new pixi.Point(); - this.spawnPos = new pixi.Point(config.pos.x, config.pos.y); - this.initAdditional(art, config); - this._prevEmitterPos = this.spawnPos.clone(); - //previous emitter position is invalid and should not be used for interpolation - this._prevPosIsValid = false; - //start emitting - this._spawnTimer = 0; - this.emit = config.emit === undefined ? true : !!config.emit; - this.autoUpdate = !!config.autoUpdate; - this.orderedArt = !!config.orderedArt; - }; - /** - * Sets up additional parameters to the emitter from config settings. - * Using for parsing additional parameters on classes that extend from Emitter - * @param art A texture or array of textures to use for the particles. - * @param config A configuration object containing settings for the emitter. - */ - Emitter.prototype.initAdditional = function (art, config) { - }; - /** - * Parsing emitter spawn type from config settings. - * Place for override and add new kind of spawn type - * @param config A configuration object containing settings for the emitter. - */ - Emitter.prototype.parseSpawnType = function (config) { - var spawnCircle; - switch (config.spawnType) { - case "rect": - this.spawnType = "rect"; - this._spawnFunc = this._spawnRect; - var spawnRect = config.spawnRect; - this.spawnRect = new pixi.Rectangle(spawnRect.x, spawnRect.y, spawnRect.w, spawnRect.h); - break; - case "circle": - this.spawnType = "circle"; - this._spawnFunc = this._spawnCircle; - spawnCircle = config.spawnCircle; - this.spawnCircle = new pixi.Circle(spawnCircle.x, spawnCircle.y, spawnCircle.r); - break; - case "ring": - this.spawnType = "ring"; - this._spawnFunc = this._spawnRing; - spawnCircle = config.spawnCircle; - this.spawnCircle = new pixi.Circle(spawnCircle.x, spawnCircle.y, spawnCircle.r); - this.spawnCircle.minRadius = spawnCircle.minR; - break; - case "burst": - this.spawnType = "burst"; - this._spawnFunc = this._spawnBurst; - this.particleSpacing = config.particleSpacing; - this.angleStart = config.angleStart ? config.angleStart : 0; - break; - case "point": - this.spawnType = "point"; - this._spawnFunc = this._spawnPoint; - break; - case "polygonalChain": - this.spawnType = "polygonalChain"; - this._spawnFunc = this._spawnPolygonalChain; - this.spawnPolygonalChain = new PolygonalChain(config.spawnPolygon); - break; - default: - this.spawnType = "point"; - this._spawnFunc = this._spawnPoint; - break; - } - }; - /** - * Recycles an individual particle. For internal use only. - * @param particle The particle to recycle. - * @internal - */ - Emitter.prototype.recycle = function (particle) { - if (particle.next) - particle.next.prev = particle.prev; - if (particle.prev) - particle.prev.next = particle.next; - if (particle == this._activeParticlesLast) - this._activeParticlesLast = particle.prev; - if (particle == this._activeParticlesFirst) - this._activeParticlesFirst = particle.next; - //add to pool - particle.prev = null; - particle.next = this._poolFirst; - this._poolFirst = particle; - //remove child from display, or make it invisible if it is in a ParticleContainer - if (particle.parent) - particle.parent.removeChild(particle); - //decrease count - --this.particleCount; - }; - /** - * Sets the rotation of the emitter to a new value. - * @param newRot The new rotation, in degrees. - */ - Emitter.prototype.rotate = function (newRot) { - if (this.rotation == newRot) - return; - //caclulate the difference in rotation for rotating spawnPos - var diff = newRot - this.rotation; - this.rotation = newRot; - //rotate spawnPos - exports.ParticleUtils.rotatePoint(diff, this.spawnPos); - //mark the position as having changed - this._posChanged = true; - }; - /** - * Changes the spawn position of the emitter. - * @param x The new x value of the spawn position for the emitter. - * @param y The new y value of the spawn position for the emitter. - */ - Emitter.prototype.updateSpawnPos = function (x, y) { - this._posChanged = true; - this.spawnPos.x = x; - this.spawnPos.y = y; - }; - /** - * Changes the position of the emitter's owner. You should call this if you are adding - * particles to the world container that your emitter's owner is moving around in. - * @param x The new x value of the emitter's owner. - * @param y The new y value of the emitter's owner. - */ - Emitter.prototype.updateOwnerPos = function (x, y) { - this._posChanged = true; - this.ownerPos.x = x; - this.ownerPos.y = y; - }; - /** - * Prevents emitter position interpolation in the next update. - * This should be used if you made a major position change of your emitter's owner - * that was not normal movement. - */ - Emitter.prototype.resetPositionTracking = function () { - this._prevPosIsValid = false; - }; - Object.defineProperty(Emitter.prototype, "emit", { - /** - * If particles should be emitted during update() calls. Setting this to false - * stops new particles from being created, but allows existing ones to die out. - */ - get: function () { return this._emit; }, - set: function (value) { - this._emit = !!value; - this._emitterLife = this.emitterLifetime; - }, - enumerable: true, - configurable: true - }); - ; - Object.defineProperty(Emitter.prototype, "autoUpdate", { - /** - * If the update function is called automatically from the shared ticker. - * Setting this to false requires calling the update function manually. - */ - get: function () { return this._autoUpdate; }, - set: function (value) { - if (this._autoUpdate && !value) { - ticker.remove(this.update, this); - } - else if (!this._autoUpdate && value) { - ticker.add(this.update, this); - } - this._autoUpdate = !!value; - }, - enumerable: true, - configurable: true - }); - /** - * Starts emitting particles, sets autoUpdate to true, and sets up the Emitter to destroy itself - * when particle emission is complete. - * @param callback Callback for when emission is complete (all particles have died off) - */ - Emitter.prototype.playOnceAndDestroy = function (callback) { - this.autoUpdate = true; - this.emit = true; - this._destroyWhenComplete = true; - this._completeCallback = callback; - }; - /** - * Starts emitting particles and optionally calls a callback when particle emission is complete. - * @param callback Callback for when emission is complete (all particles have died off) - */ - Emitter.prototype.playOnce = function (callback) { - this.emit = true; - this._completeCallback = callback; - }; - /** - * Updates all particles spawned by this emitter and emits new ones. - * @param delta Time elapsed since the previous frame, in __seconds__. - */ - Emitter.prototype.update = function (delta) { - if (this._autoUpdate) { - delta = delta / pixi.settings.TARGET_FPMS / 1000; - } - //if we don't have a parent to add particles to, then don't do anything. - //this also works as a isDestroyed check - if (!this._parent) - return; - //update existing particles - var i, particle, next; - for (particle = this._activeParticlesFirst; particle; particle = next) { - next = particle.next; - particle.update(delta); - } - var prevX, prevY; - //if the previous position is valid, store these for later interpolation - if (this._prevPosIsValid) { - prevX = this._prevEmitterPos.x; - prevY = this._prevEmitterPos.y; - } - //store current position of the emitter as local variables - var curX = this.ownerPos.x + this.spawnPos.x; - var curY = this.ownerPos.y + this.spawnPos.y; - //spawn new particles - if (this._emit) { - //decrease spawn timer - this._spawnTimer -= delta < 0 ? 0 : delta; - //while _spawnTimer < 0, we have particles to spawn - while (this._spawnTimer <= 0) { - //determine if the emitter should stop spawning - if (this._emitterLife > 0) { - this._emitterLife -= this._frequency; - if (this._emitterLife <= 0) { - this._spawnTimer = 0; - this._emitterLife = 0; - this.emit = false; - break; - } - } - //determine if we have hit the particle limit - if (this.particleCount >= this.maxParticles) { - this._spawnTimer += this._frequency; - continue; - } - //determine the particle lifetime - var lifetime = void 0; - if (this.minLifetime == this.maxLifetime) - lifetime = this.minLifetime; - else - lifetime = Math.random() * (this.maxLifetime - this.minLifetime) + this.minLifetime; - //only make the particle if it wouldn't immediately destroy itself - if (-this._spawnTimer < lifetime) { - //If the position has changed and this isn't the first spawn, - //interpolate the spawn position - var emitPosX = void 0, emitPosY = void 0; - if (this._prevPosIsValid && this._posChanged) { - //1 - _spawnTimer / delta, but _spawnTimer is negative - var lerp = 1 + this._spawnTimer / delta; - emitPosX = (curX - prevX) * lerp + prevX; - emitPosY = (curY - prevY) * lerp + prevY; - } - else //otherwise just set to the spawn position - { - emitPosX = curX; - emitPosY = curY; - } - //create enough particles to fill the wave (non-burst types have a wave of 1) - i = 0; - for (var len = Math.min(this.particlesPerWave, this.maxParticles - this.particleCount); i < len; ++i) { - //see if we actually spawn one - if (this.spawnChance < 1 && Math.random() >= this.spawnChance) - continue; - //create particle - var p = void 0; - if (this._poolFirst) { - p = this._poolFirst; - this._poolFirst = this._poolFirst.next; - p.next = null; - } - else { - p = new this.particleConstructor(this); - } - //set a random texture if we have more than one - if (this.particleImages.length > 1) { - // if using ordered art - if (this._currentImageIndex !== -1) { - // get current art index, then increment for the next particle - p.applyArt(this.particleImages[this._currentImageIndex++]); - // loop around if needed - if (this._currentImageIndex < 0 || this._currentImageIndex >= this.particleImages.length) { - this._currentImageIndex = 0; - } - } - // otherwise grab a random one - else { - p.applyArt(this.particleImages[Math.floor(Math.random() * this.particleImages.length)]); - } - } - else { - //if they are actually the same texture, a standard particle - //will quit early from the texture setting in setTexture(). - p.applyArt(this.particleImages[0]); - } - //set up the start and end values - p.alphaList.reset(this.startAlpha); - if (this.minimumSpeedMultiplier != 1) { - p.speedMultiplier = Math.random() * (1 - this.minimumSpeedMultiplier) + this.minimumSpeedMultiplier; - } - p.speedList.reset(this.startSpeed); - p.acceleration.x = this.acceleration.x; - p.acceleration.y = this.acceleration.y; - p.maxSpeed = this.maxSpeed; - if (this.minimumScaleMultiplier != 1) { - p.scaleMultiplier = Math.random() * (1 - this.minimumScaleMultiplier) + this.minimumScaleMultiplier; - } - p.scaleList.reset(this.startScale); - p.colorList.reset(this.startColor); - //randomize the rotation speed - if (this.minRotationSpeed == this.maxRotationSpeed) - p.rotationSpeed = this.minRotationSpeed; - else - p.rotationSpeed = Math.random() * (this.maxRotationSpeed - this.minRotationSpeed) + this.minRotationSpeed; - p.rotationAcceleration = this.rotationAcceleration; - p.noRotation = this.noRotation; - //set up the lifetime - p.maxLife = lifetime; - //set the blend mode - p.blendMode = this.particleBlendMode; - //set the custom ease, if any - p.ease = this.customEase; - //set the extra data, if any - p.extraData = this.extraData; - //set additional properties to particle - this.applyAdditionalProperties(p); - //call the proper function to handle rotation and position of particle - this._spawnFunc(p, emitPosX, emitPosY, i); - //initialize particle - p.init(); - //update the particle by the time passed, so the particles are spread out properly - p.update(-this._spawnTimer); //we want a positive delta, because a negative delta messes things up - //add the particle to the display list - if (!p.parent) { - if (this.addAtBack) - this._parent.addChildAt(p, 0); - else - this._parent.addChild(p); - } - else { - //kind of hacky, but performance friendly - //shuffle children to correct place - var children = this._parent.children; - //avoid using splice if possible - if (children[0] == p) - children.shift(); - else if (children[children.length - 1] == p) - children.pop(); - else { - var index = children.indexOf(p); - children.splice(index, 1); - } - if (this.addAtBack) - children.unshift(p); - else - children.push(p); - } - //add particle to list of active particles - if (this._activeParticlesLast) { - this._activeParticlesLast.next = p; - p.prev = this._activeParticlesLast; - this._activeParticlesLast = p; - } - else { - this._activeParticlesLast = this._activeParticlesFirst = p; - } - ++this.particleCount; - } - } - //increase timer and continue on to any other particles that need to be created - this._spawnTimer += this._frequency; - } - } - //if the position changed before this update, then keep track of that - if (this._posChanged) { - this._prevEmitterPos.x = curX; - this._prevEmitterPos.y = curY; - this._prevPosIsValid = true; - this._posChanged = false; - } - //if we are all done and should destroy ourselves, take care of that - if (!this._emit && !this._activeParticlesFirst) { - if (this._completeCallback) { - var cb = this._completeCallback; - this._completeCallback = null; - cb(); - } - if (this._destroyWhenComplete) { - this.destroy(); - } - } - }; - /** - * Set additional properties to new particle. - * Using on classes that extend from Emitter - * @param p The particle - */ - Emitter.prototype.applyAdditionalProperties = function (p) { - }; - /** - * Positions a particle for a point type emitter. - * @param p The particle to position and rotate. - * @param emitPosX The emitter's x position - * @param emitPosY The emitter's y position - * @param i The particle number in the current wave. Not used for this function. - */ - Emitter.prototype._spawnPoint = function (p, emitPosX, emitPosY) { - //set the initial rotation/direction of the particle based on - //starting particle angle and rotation of emitter - if (this.minStartRotation == this.maxStartRotation) - p.rotation = this.minStartRotation + this.rotation; - else - p.rotation = Math.random() * (this.maxStartRotation - this.minStartRotation) + this.minStartRotation + this.rotation; - //drop the particle at the emitter's position - p.position.x = emitPosX; - p.position.y = emitPosY; - }; - /** - * Positions a particle for a rectangle type emitter. - * @param p The particle to position and rotate. - * @param emitPosX The emitter's x position - * @param emitPosY The emitter's y position - * @param i The particle number in the current wave. Not used for this function. - */ - Emitter.prototype._spawnRect = function (p, emitPosX, emitPosY) { - //set the initial rotation/direction of the particle based on starting - //particle angle and rotation of emitter - if (this.minStartRotation == this.maxStartRotation) - p.rotation = this.minStartRotation + this.rotation; - else - p.rotation = Math.random() * (this.maxStartRotation - this.minStartRotation) + this.minStartRotation + this.rotation; - //place the particle at a random point in the rectangle - helperPoint.x = Math.random() * this.spawnRect.width + this.spawnRect.x; - helperPoint.y = Math.random() * this.spawnRect.height + this.spawnRect.y; - if (this.rotation !== 0) - exports.ParticleUtils.rotatePoint(this.rotation, helperPoint); - p.position.x = emitPosX + helperPoint.x; - p.position.y = emitPosY + helperPoint.y; - }; - /** - * Positions a particle for a circle type emitter. - * @param p The particle to position and rotate. - * @param emitPosX The emitter's x position - * @param emitPosY The emitter's y position - * @param i The particle number in the current wave. Not used for this function. - */ - Emitter.prototype._spawnCircle = function (p, emitPosX, emitPosY) { - //set the initial rotation/direction of the particle based on starting - //particle angle and rotation of emitter - if (this.minStartRotation == this.maxStartRotation) - p.rotation = this.minStartRotation + this.rotation; - else - p.rotation = Math.random() * (this.maxStartRotation - this.minStartRotation) + - this.minStartRotation + this.rotation; - //place the particle at a random radius in the circle - helperPoint.x = Math.random() * this.spawnCircle.radius; - helperPoint.y = 0; - //rotate the point to a random angle in the circle - exports.ParticleUtils.rotatePoint(Math.random() * 360, helperPoint); - //offset by the circle's center - helperPoint.x += this.spawnCircle.x; - helperPoint.y += this.spawnCircle.y; - //rotate the point by the emitter's rotation - if (this.rotation !== 0) - exports.ParticleUtils.rotatePoint(this.rotation, helperPoint); - //set the position, offset by the emitter's position - p.position.x = emitPosX + helperPoint.x; - p.position.y = emitPosY + helperPoint.y; - }; - /** - * Positions a particle for a ring type emitter. - * @param p The particle to position and rotate. - * @param emitPosX The emitter's x position - * @param emitPosY The emitter's y position - * @param i The particle number in the current wave. Not used for this function. - */ - Emitter.prototype._spawnRing = function (p, emitPosX, emitPosY) { - var spawnCircle = this.spawnCircle; - //set the initial rotation/direction of the particle based on starting - //particle angle and rotation of emitter - if (this.minStartRotation == this.maxStartRotation) - p.rotation = this.minStartRotation + this.rotation; - else - p.rotation = Math.random() * (this.maxStartRotation - this.minStartRotation) + - this.minStartRotation + this.rotation; - //place the particle at a random radius in the ring - if (spawnCircle.minRadius !== spawnCircle.radius) { - helperPoint.x = Math.random() * (spawnCircle.radius - spawnCircle.minRadius) + - spawnCircle.minRadius; - } - else - helperPoint.x = spawnCircle.radius; - helperPoint.y = 0; - //rotate the point to a random angle in the circle - var angle = Math.random() * 360; - p.rotation += angle; - exports.ParticleUtils.rotatePoint(angle, helperPoint); - //offset by the circle's center - helperPoint.x += this.spawnCircle.x; - helperPoint.y += this.spawnCircle.y; - //rotate the point by the emitter's rotation - if (this.rotation !== 0) - exports.ParticleUtils.rotatePoint(this.rotation, helperPoint); - //set the position, offset by the emitter's position - p.position.x = emitPosX + helperPoint.x; - p.position.y = emitPosY + helperPoint.y; - }; - /** - * Positions a particle for polygonal chain. - * @param p The particle to position and rotate. - * @param emitPosX The emitter's x position - * @param emitPosY The emitter's y position - * @param i The particle number in the current wave. Not used for this function. - */ - Emitter.prototype._spawnPolygonalChain = function (p, emitPosX, emitPosY) { - //set the initial rotation/direction of the particle based on starting - //particle angle and rotation of emitter - if (this.minStartRotation == this.maxStartRotation) - p.rotation = this.minStartRotation + this.rotation; - else - p.rotation = Math.random() * (this.maxStartRotation - this.minStartRotation) + - this.minStartRotation + this.rotation; - // get random point on the polygon chain - this.spawnPolygonalChain.getRandomPoint(helperPoint); - //rotate the point by the emitter's rotation - if (this.rotation !== 0) - exports.ParticleUtils.rotatePoint(this.rotation, helperPoint); - //set the position, offset by the emitter's position - p.position.x = emitPosX + helperPoint.x; - p.position.y = emitPosY + helperPoint.y; - }; - /** - * Positions a particle for a burst type emitter. - * @param p The particle to position and rotate. - * @param emitPosX The emitter's x position - * @param emitPosY The emitter's y position - * @param i The particle number in the current wave. - */ - Emitter.prototype._spawnBurst = function (p, emitPosX, emitPosY, i) { - //set the initial rotation/direction of the particle based on spawn - //angle and rotation of emitter - if (this.particleSpacing === 0) - p.rotation = Math.random() * 360; - else - p.rotation = this.angleStart + (this.particleSpacing * i) + this.rotation; - //drop the particle at the emitter's position - p.position.x = emitPosX; - p.position.y = emitPosY; - }; - /** - * Kills all active particles immediately. - */ - Emitter.prototype.cleanup = function () { - var particle, next; - for (particle = this._activeParticlesFirst; particle; particle = next) { - next = particle.next; - this.recycle(particle); - if (particle.parent) - particle.parent.removeChild(particle); - } - this._activeParticlesFirst = this._activeParticlesLast = null; - this.particleCount = 0; - }; - /** - * Destroys the emitter and all of its particles. - */ - Emitter.prototype.destroy = function () { - //make sure we aren't still listening to any tickers - this.autoUpdate = false; - //puts all active particles in the pool, and removes them from the particle parent - this.cleanup(); - //wipe the pool clean - var next; - for (var particle = this._poolFirst; particle; particle = next) { - //store next value so we don't lose it in our destroy call - next = particle.next; - particle.destroy(); - } - this._poolFirst = this._parent = this.particleImages = this.spawnPos = this.ownerPos = - this.startColor = this.startScale = this.startAlpha = this.startSpeed = - this.customEase = this._completeCallback = null; - }; - return Emitter; - }()); - - /** - * A helper point for math things. - * @hidden - */ - var helperPoint$1 = new pixi.Point(); - /** - * A hand picked list of Math functions (and a couple properties) that are - * allowable. They should be used without the preceding "Math." - * @hidden - */ - var MATH_FUNCS = [ - "pow", - "sqrt", - "abs", - "floor", - "round", - "ceil", - "E", - "PI", - "sin", - "cos", - "tan", - "asin", - "acos", - "atan", - "atan2", - "log" - ]; - /** - * create an actual regular expression object from the string - * @hidden - */ - var WHITELISTER = new RegExp([ - //Allow the 4 basic operations, parentheses and all numbers/decimals, as well - //as 'x', for the variable usage. - "[01234567890\\.\\*\\-\\+\\/\\(\\)x ,]", - ].concat(MATH_FUNCS).join("|"), "g"); - /** - * Parses a string into a function for path following. - * This involves whitelisting the string for safety, inserting "Math." to math function - * names, and using `new Function()` to generate a function. - * @hidden - * @param pathString The string to parse. - * @return The path function - takes x, outputs y. - */ - var parsePath = function (pathString) { - var matches = pathString.match(WHITELISTER); - for (var i = matches.length - 1; i >= 0; --i) { - if (MATH_FUNCS.indexOf(matches[i]) >= 0) - matches[i] = "Math." + matches[i]; - } - pathString = matches.join(""); - return new Function("x", "return " + pathString + ";"); - }; - /** - * An particle that follows a path defined by an algebraic expression, e.g. "sin(x)" or - * "5x + 3". - * To use this class, the particle config must have a "path" string in the - * "extraData" parameter. This string should have "x" in it to represent movement (from the - * speed settings of the particle). It may have numbers, parentheses, the four basic - * operations, and the following Math functions or properties (without the preceding "Math."): - * "pow", "sqrt", "abs", "floor", "round", "ceil", "E", "PI", "sin", "cos", "tan", "asin", - * "acos", "atan", "atan2", "log". - * The overall movement of the particle and the expression value become x and y positions for - * the particle, respectively. The final position is rotated by the spawn rotation/angle of - * the particle. - * - * Some example paths: - * - * "sin(x/10) * 20" // A sine wave path. - * "cos(x/100) * 30" // Particles curve counterclockwise (for medium speed/low lifetime particles) - * "pow(x/10, 2) / 2" // Particles curve clockwise (remember, +y is down). - */ - var PathParticle = /** @class */ (function (_super) { - __extends(PathParticle, _super); - /** - * @param {PIXI.particles.Emitter} emitter The emitter that controls this PathParticle. - */ - function PathParticle(emitter) { - var _this = _super.call(this, emitter) || this; - _this.path = null; - _this.initialRotation = 0; - _this.initialPosition = new pixi.Point(); - _this.movement = 0; - return _this; - } - /** - * Initializes the particle for use, based on the properties that have to - * have been set already on the particle. - */ - PathParticle.prototype.init = function () { - //get initial rotation before it is converted to radians - this.initialRotation = this.rotation; - //standard init - this.Particle_init(); - //set the path for the particle - this.path = this.extraData.path; - //cancel the normal movement behavior - this._doNormalMovement = !this.path; - //reset movement - this.movement = 0; - //grab position - this.initialPosition.x = this.position.x; - this.initialPosition.y = this.position.y; - }; - /** - * Updates the particle. - * @param delta Time elapsed since the previous frame, in __seconds__. - */ - PathParticle.prototype.update = function (delta) { - var lerp = this.Particle_update(delta); - //if the particle died during the update, then don't bother - if (lerp >= 0 && this.path) { - //increase linear movement based on speed - var speed = this.speedList.interpolate(lerp) * this.speedMultiplier; - this.movement += speed * delta; - //set up the helper point for rotation - helperPoint$1.x = this.movement; - helperPoint$1.y = this.path(this.movement); - exports.ParticleUtils.rotatePoint(this.initialRotation, helperPoint$1); - this.position.x = this.initialPosition.x + helperPoint$1.x; - this.position.y = this.initialPosition.y + helperPoint$1.y; - } - return lerp; - }; - /** - * Destroys the particle, removing references and preventing future use. - */ - PathParticle.prototype.destroy = function () { - this.Particle_destroy(); - this.path = this.initialPosition = null; - }; - /** - * Checks over the art that was passed to the Emitter's init() function, to do any special - * modifications to prepare it ahead of time. This just runs Particle.parseArt(). - * @param art The array of art data. For Particle, it should be an array of - * Textures. Any strings in the array will be converted to - * Textures via Texture.fromImage(). - * @return The art, after any needed modifications. - */ - PathParticle.parseArt = function (art) { - return Particle.parseArt(art); - }; - /** - * Parses extra emitter data to ensure it is set up for this particle class. - * PathParticle checks for the existence of path data, and parses the path data for use - * by particle instances. - * @param extraData The extra data from the particle config. - * @return The parsed extra data. - */ - PathParticle.parseData = function (extraData) { - var output = {}; - if (extraData && extraData.path) { - try { - output.path = parsePath(extraData.path); - } - catch (e) { - if (exports.ParticleUtils.verbose) - console.error("PathParticle: error in parsing path expression"); - output.path = null; - } - } - else { - if (exports.ParticleUtils.verbose) - console.error("PathParticle requires a path string in extraData!"); - output.path = null; - } - return output; - }; - return PathParticle; - }(Particle)); - - /** - * An individual particle image with an animation. Art data passed to the emitter must be - * formatted in a particular way for AnimatedParticle to be able to handle it: - * - * ```typescript - * { - * //framerate is required. It is the animation speed of the particle in frames per - * //second. - * //A value of "matchLife" causes the animation to match the lifetime of an individual - * //particle, instead of at a constant framerate. This causes the animation to play - * //through one time, completing when the particle expires. - * framerate: 6, - * //loop is optional, and defaults to false. - * loop: true, - * //textures is required, and can be an array of any (non-zero) length. - * textures: [ - * //each entry represents a single texture that should be used for one or more - * //frames. Any strings will be converted to Textures with Texture.from(). - * //Instances of PIXI.Texture will be used directly. - * "animFrame1.png", - * //entries can be an object with a 'count' property, telling AnimatedParticle to - * //use that texture for 'count' frames sequentially. - * { - * texture: "animFrame2.png", - * count: 3 - * }, - * "animFrame3.png" - * ] - * } - * ``` - */ - var AnimatedParticle = /** @class */ (function (_super) { - __extends(AnimatedParticle, _super); - /** - * @param emitter The emitter that controls this AnimatedParticle. - */ - function AnimatedParticle(emitter) { - var _this = _super.call(this, emitter) || this; - _this.textures = null; - _this.duration = 0; - _this.framerate = 0; - _this.elapsed = 0; - _this.loop = false; - return _this; - } - /** - * Initializes the particle for use, based on the properties that have to - * have been set already on the particle. - */ - AnimatedParticle.prototype.init = function () { - this.Particle_init(); - this.elapsed = 0; - //if the animation needs to match the particle's life, then cacluate variables - if (this.framerate < 0) { - this.duration = this.maxLife; - this.framerate = this.textures.length / this.duration; - } - }; - /** - * Sets the textures for the particle. - * @param art An array of PIXI.Texture objects for this animated particle. - */ - AnimatedParticle.prototype.applyArt = function (art) { - this.textures = art.textures; - this.framerate = art.framerate; - this.duration = art.duration; - this.loop = art.loop; - }; - /** - * Updates the particle. - * @param delta Time elapsed since the previous frame, in __seconds__. - */ - AnimatedParticle.prototype.update = function (delta) { - var lerp = this.Particle_update(delta); - //only animate the particle if it is still alive - if (lerp >= 0) { - this.elapsed += delta; - if (this.elapsed > this.duration) { - //loop elapsed back around - if (this.loop) - this.elapsed = this.elapsed % this.duration; - //subtract a small amount to prevent attempting to go past the end of the animation - else - this.elapsed = this.duration - 0.000001; - } - // add a very small number to the frame and then floor it to avoid - // the frame being one short due to floating point errors. - var frame = (this.elapsed * this.framerate + 0.0000001) | 0; - this.texture = this.textures[frame] || pixi.Texture.EMPTY; - } - return lerp; - }; - /** - * Destroys the particle, removing references and preventing future use. - */ - AnimatedParticle.prototype.destroy = function () { - this.Particle_destroy(); - this.textures = null; - }; - /** - * Checks over the art that was passed to the Emitter's init() function, to do any special - * modifications to prepare it ahead of time. - * @param art The array of art data, properly formatted for AnimatedParticle. - * @return The art, after any needed modifications. - */ - AnimatedParticle.parseArt = function (art) { - var data, output, textures, tex, outTextures; - var outArr = []; - for (var i = 0; i < art.length; ++i) { - data = art[i]; - outArr[i] = output = {}; - output.textures = outTextures = []; - textures = data.textures; - for (var j = 0; j < textures.length; ++j) { - tex = textures[j]; - if (typeof tex == "string") - outTextures.push(GetTextureFromString(tex)); - else if (tex instanceof pixi.Texture) - outTextures.push(tex); - //assume an object with extra data determining duplicate frame data - else { - var dupe = tex.count || 1; - if (typeof tex.texture == "string") - tex = GetTextureFromString(tex.texture); - else // if(tex.texture instanceof Texture) - tex = tex.texture; - for (; dupe > 0; --dupe) { - outTextures.push(tex); - } - } - } - //use these values to signify that the animation should match the particle life time. - if (data.framerate == "matchLife") { - //-1 means that it should be calculated - output.framerate = -1; - output.duration = 0; - output.loop = false; - } - else { - //determine if the animation should loop - output.loop = !!data.loop; - //get the framerate, default to 60 - output.framerate = data.framerate > 0 ? data.framerate : 60; - //determine the duration - output.duration = outTextures.length / output.framerate; - } - } - return outArr; - }; - return AnimatedParticle; - }(Particle)); - - exports.GetTextureFromString = GetTextureFromString; - exports.Particle = Particle; - exports.Emitter = Emitter; - exports.PathParticle = PathParticle; - exports.AnimatedParticle = AnimatedParticle; - exports.PolygonalChain = PolygonalChain; - exports.PropertyList = PropertyList; - exports.PropertyNode = PropertyNode; - -}(this.PIXI.particles = this.PIXI.particles || {}, PIXI)); - - -var pixi_projection; -(function (pixi_projection) { - var utils; - (function (utils) { - function getIntersectionFactor(p1, p2, p3, p4, out) { - var A1 = p2.x - p1.x, B1 = p3.x - p4.x, C1 = p3.x - p1.x; - var A2 = p2.y - p1.y, B2 = p3.y - p4.y, C2 = p3.y - p1.y; - var D = A1 * B2 - A2 * B1; - if (Math.abs(D) < 1e-7) { - out.x = A1; - out.y = A2; - return 0; + /** + * A single node in a PropertyList. + */ + var PropertyNode = /** @class */ (function () { + /** + * @param value The value for this node + * @param time The time for this node, between 0-1 + * @param [ease] Custom ease for this list. Only relevant for the first node. + */ + function PropertyNode(value, time, ease) { + this.value = value; + this.time = time; + this.next = null; + this.isStepped = false; + if (ease) { + this.ease = typeof ease === 'function' ? ease : exports.ParticleUtils.generateEase(ease); } - var T = C1 * B2 - C2 * B1; - var U = A1 * C2 - A2 * C1; - var t = T / D, u = U / D; - if (u < (1e-6) || u - 1 > -1e-6) { - return -1; + else { + this.ease = null; } - out.x = p1.x + t * (p2.x - p1.x); - out.y = p1.y + t * (p2.y - p1.y); - return 1; } - utils.getIntersectionFactor = getIntersectionFactor; - function getPositionFromQuad(p, anchor, out) { - out = out || new PIXI.Point(); - var a1 = 1.0 - anchor.x, a2 = 1.0 - a1; - var b1 = 1.0 - anchor.y, b2 = 1.0 - b1; - out.x = (p[0].x * a1 + p[1].x * a2) * b1 + (p[3].x * a1 + p[2].x * a2) * b2; - out.y = (p[0].y * a1 + p[1].y * a2) * b1 + (p[3].y * a1 + p[2].y * a2) * b2; - return out; - } - utils.getPositionFromQuad = getPositionFromQuad; - })(utils = pixi_projection.utils || (pixi_projection.utils = {})); -})(pixi_projection || (pixi_projection = {})); -PIXI.projection = pixi_projection; -var pixi_projection; -(function (pixi_projection) { - var AbstractProjection = (function () { - function AbstractProjection(legacy, enable) { - if (enable === void 0) { enable = true; } - this._enabled = false; - this.legacy = legacy; - if (enable) { - this.enabled = true; + /** + * Creates a list of property values from a data object {list, isStepped} with a list of objects in + * the form {value, time}. Alternatively, the data object can be in the deprecated form of + * {start, end}. + * @param data The data for the list. + * @param data.list The array of value and time objects. + * @param data.isStepped If the list is stepped rather than interpolated. + * @param data.ease Custom ease for this list. + * @return The first node in the list + */ + // eslint-disable-next-line max-len + PropertyNode.createList = function (data) { + if ('list' in data) { + var array = data.list; + var node = void 0; + var _a = array[0], value = _a.value, time = _a.time; + // eslint-disable-next-line max-len + var first = node = new PropertyNode(typeof value === 'string' ? exports.ParticleUtils.hexToRGB(value) : value, time, data.ease); + // only set up subsequent nodes if there are a bunch or the 2nd one is different from the first + if (array.length > 2 || (array.length === 2 && array[1].value !== value)) { + for (var i = 1; i < array.length; ++i) { + var _b = array[i], value_1 = _b.value, time_1 = _b.time; + node.next = new PropertyNode(typeof value_1 === 'string' ? exports.ParticleUtils.hexToRGB(value_1) : value_1, time_1); + node = node.next; + } + } + first.isStepped = !!data.isStepped; + return first; } - this.legacy.proj = this; - } - Object.defineProperty(AbstractProjection.prototype, "enabled", { - get: function () { - return this._enabled; - }, - set: function (value) { - this._enabled = value; - }, - enumerable: true, - configurable: true - }); - AbstractProjection.prototype.clear = function () { + // Handle deprecated version here + var start = new PropertyNode(typeof data.start === 'string' ? exports.ParticleUtils.hexToRGB(data.start) : data.start, 0); + // only set up a next value if it is different from the starting value + if (data.end !== data.start) { + start.next = new PropertyNode(typeof data.end === 'string' ? exports.ParticleUtils.hexToRGB(data.end) : data.end, 1); + } + return start; }; - return AbstractProjection; - }()); - pixi_projection.AbstractProjection = AbstractProjection; - var TRANSFORM_STEP; - (function (TRANSFORM_STEP) { - TRANSFORM_STEP[TRANSFORM_STEP["NONE"] = 0] = "NONE"; - TRANSFORM_STEP[TRANSFORM_STEP["BEFORE_PROJ"] = 4] = "BEFORE_PROJ"; - TRANSFORM_STEP[TRANSFORM_STEP["PROJ"] = 5] = "PROJ"; - TRANSFORM_STEP[TRANSFORM_STEP["ALL"] = 9] = "ALL"; - })(TRANSFORM_STEP = pixi_projection.TRANSFORM_STEP || (pixi_projection.TRANSFORM_STEP = {})); -})(pixi_projection || (pixi_projection = {})); -var __extends = (this && this.__extends) || (function () { - var extendStatics = function (d, b) { + return PropertyNode; + }()); + + // get Texture.from()/Texture.fromImage(), in V4 and V5 friendly methods + /** + * @hidden + */ + var TextureFromString; + // to avoid Rollup transforming our import, save pixi namespace in a variable + var pixiNS = pixi; + if (parseInt((/^(\d+)\./).exec(pixi.VERSION)[1], 10) < 5) { + TextureFromString = pixiNS.Texture.fromImage; + } + else { + TextureFromString = pixiNS.Texture.from; + } + function GetTextureFromString(s) { + return TextureFromString(s); + } + (function (ParticleUtils) { + /** + * If errors and warnings should be logged within the library. + */ + ParticleUtils.verbose = false; + ParticleUtils.DEG_TO_RADS = Math.PI / 180; + /** + * Rotates a point by a given angle. + * @param angle The angle to rotate by in degrees + * @param p The point to rotate around 0,0. + */ + function rotatePoint(angle, p) { + if (!angle) + return; + angle *= ParticleUtils.DEG_TO_RADS; + var s = Math.sin(angle); + var c = Math.cos(angle); + var xnew = (p.x * c) - (p.y * s); + var ynew = (p.x * s) + (p.y * c); + p.x = xnew; + p.y = ynew; + } + ParticleUtils.rotatePoint = rotatePoint; + /** + * Combines separate color components (0-255) into a single uint color. + * @param r The red value of the color + * @param g The green value of the color + * @param b The blue value of the color + * @return The color in the form of 0xRRGGBB + */ + function combineRGBComponents(r, g, b /* , a*/) { + return /* a << 24 |*/ (r << 16) | (g << 8) | b; + } + ParticleUtils.combineRGBComponents = combineRGBComponents; + /** + * Reduces the point to a length of 1. + * @param point The point to normalize + */ + function normalize(point) { + var oneOverLen = 1 / ParticleUtils.length(point); + point.x *= oneOverLen; + point.y *= oneOverLen; + } + ParticleUtils.normalize = normalize; + /** + * Multiplies the x and y values of this point by a value. + * @param point The point to scaleBy + * @param value The value to scale by. + */ + function scaleBy(point, value) { + point.x *= value; + point.y *= value; + } + ParticleUtils.scaleBy = scaleBy; + /** + * Returns the length (or magnitude) of this point. + * @param point The point to measure length + * @return The length of this point. + */ + function length(point) { + return Math.sqrt((point.x * point.x) + (point.y * point.y)); + } + ParticleUtils.length = length; + /** + * Converts a hex string from "#AARRGGBB", "#RRGGBB", "0xAARRGGBB", "0xRRGGBB", + * "AARRGGBB", or "RRGGBB" to an object of ints of 0-255, as + * {r, g, b, (a)}. + * @param color The input color string. + * @param output An object to put the output in. If omitted, a new object is created. + * @return The object with r, g, and b properties, possibly with an a property. + */ + function hexToRGB(color, output) { + if (!output) { + output = {}; + } + if (color.charAt(0) === '#') { + color = color.substr(1); + } + else if (color.indexOf('0x') === 0) { + color = color.substr(2); + } + var alpha; + if (color.length === 8) { + alpha = color.substr(0, 2); + color = color.substr(2); + } + output.r = parseInt(color.substr(0, 2), 16); // Red + output.g = parseInt(color.substr(2, 2), 16); // Green + output.b = parseInt(color.substr(4, 2), 16); // Blue + if (alpha) { + output.a = parseInt(alpha, 16); + } + return output; + } + ParticleUtils.hexToRGB = hexToRGB; + /** + * Generates a custom ease function, based on the GreenSock custom ease, as demonstrated + * by the related tool at http://www.greensock.com/customease/. + * @param segments An array of segments, as created by + * http://www.greensock.com/customease/. + * @return A function that calculates the percentage of change at + * a given point in time (0-1 inclusive). + */ + function generateEase(segments) { + var qty = segments.length; + var oneOverQty = 1 / qty; + /* + * Calculates the percentage of change at a given point in time (0-1 inclusive). + * @param {Number} time The time of the ease, 0-1 inclusive. + * @return {Number} The percentage of the change, 0-1 inclusive (unless your + * ease goes outside those bounds). + */ + // eslint-disable-next-line func-names + return function (time) { + var i = (qty * time) | 0; // do a quick floor operation + var t = (time - (i * oneOverQty)) * qty; + var s = segments[i] || segments[qty - 1]; + return (s.s + (t * ((2 * (1 - t) * (s.cp - s.s)) + (t * (s.e - s.s))))); + }; + } + ParticleUtils.generateEase = generateEase; + /** + * Gets a blend mode, ensuring that it is valid. + * @param name The name of the blend mode to get. + * @return The blend mode as specified in the PIXI.BLEND_MODES enumeration. + */ + function getBlendMode(name) { + if (!name) + return pixi.BLEND_MODES.NORMAL; + name = name.toUpperCase(); + while (name.indexOf(' ') >= 0) { + name = name.replace(' ', '_'); + } + return pixi.BLEND_MODES[name] || pixi.BLEND_MODES.NORMAL; + } + ParticleUtils.getBlendMode = getBlendMode; + /** + * Converts a list of {value, time} objects starting at time 0 and ending at time 1 into an evenly + * spaced stepped list of PropertyNodes for color values. This is primarily to handle conversion of + * linear gradients to fewer colors, allowing for some optimization for Canvas2d fallbacks. + * @param list The list of data to convert. + * @param [numSteps=10] The number of steps to use. + * @return The blend mode as specified in the PIXI.blendModes enumeration. + */ + function createSteppedGradient(list, numSteps) { + if (numSteps === void 0) { numSteps = 10; } + if (typeof numSteps !== 'number' || numSteps <= 0) { + numSteps = 10; + } + var first = new PropertyNode(ParticleUtils.hexToRGB(list[0].value), list[0].time); + first.isStepped = true; + var currentNode = first; + var current = list[0]; + var nextIndex = 1; + var next = list[nextIndex]; + for (var i = 1; i < numSteps; ++i) { + var lerp = i / numSteps; + // ensure we are on the right segment, if multiple + while (lerp > next.time) { + current = next; + next = list[++nextIndex]; + } + // convert the lerp value to the segment range + lerp = (lerp - current.time) / (next.time - current.time); + var curVal = ParticleUtils.hexToRGB(current.value); + var nextVal = ParticleUtils.hexToRGB(next.value); + var output = { + r: ((nextVal.r - curVal.r) * lerp) + curVal.r, + g: ((nextVal.g - curVal.g) * lerp) + curVal.g, + b: ((nextVal.b - curVal.b) * lerp) + curVal.b, + }; + currentNode.next = new PropertyNode(output, i / numSteps); + currentNode = currentNode.next; + } + // we don't need to have a PropertyNode for time of 1, because in a stepped version at that point + // the particle has died of old age + return first; + } + ParticleUtils.createSteppedGradient = createSteppedGradient; + })(exports.ParticleUtils || (exports.ParticleUtils = {})); + + /*! ***************************************************************************** + Copyright (c) Microsoft Corporation. All rights reserved. + Licensed under the Apache License, Version 2.0 (the "License"); you may not use + this file except in compliance with the License. You may obtain a copy of the + License at http://www.apache.org/licenses/LICENSE-2.0 + + THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED + WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, + MERCHANTABLITY OR NON-INFRINGEMENT. + + See the Apache Version 2.0 License for specific language governing permissions + and limitations under the License. + ***************************************************************************** */ + /* global Reflect, Promise */ + + var extendStatics = function(d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); }; - return function (d, b) { + + function __extends(d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + } + + var __assign = function() { + __assign = Object.assign || function __assign(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; + } + return t; + }; + return __assign.apply(this, arguments); }; -})(); -var pixi_projection; -(function (pixi_projection) { - function transformHack(parentTransform) { - var proj = this.proj; - var ta = this; - var pwid = parentTransform._worldID; - var lt = ta.localTransform; - var scaleAfterAffine = proj.scaleAfterAffine && proj.affine >= 2; - if (ta._localID !== ta._currentLocalID) { - if (scaleAfterAffine) { - lt.a = ta._cx; - lt.b = ta._sx; - lt.c = ta._cy; - lt.d = ta._sy; - lt.tx = ta.position._x; - lt.ty = ta.position._y; + + function __rest(s, e) { + var t = {}; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) + t[p] = s[p]; + if (s != null && typeof Object.getOwnPropertySymbols === "function") + for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { + if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) + t[p[i]] = s[p[i]]; } - else { - lt.a = ta._cx * ta.scale._x; - lt.b = ta._sx * ta.scale._x; - lt.c = ta._cy * ta.scale._y; - lt.d = ta._sy * ta.scale._y; - lt.tx = ta.position._x - ((ta.pivot._x * lt.a) + (ta.pivot._y * lt.c)); - lt.ty = ta.position._y - ((ta.pivot._x * lt.b) + (ta.pivot._y * lt.d)); - } - ta._currentLocalID = ta._localID; - proj._currentProjID = -1; - } - var _matrixID = proj._projID; - if (proj._currentProjID !== _matrixID) { - proj._currentProjID = _matrixID; - proj.updateLocalTransform(lt); - ta._parentID = -1; - } - if (ta._parentID !== pwid) { - var pp = parentTransform.proj; - if (pp && !pp._affine) { - proj.world.setToMult(pp.world, proj.local); - } - else { - proj.world.setToMultLegacy(parentTransform.worldTransform, proj.local); - } - var wa = ta.worldTransform; - proj.world.copyTo(wa, proj._affine, proj.affinePreserveOrientation); - if (scaleAfterAffine) { - wa.a *= ta.scale._x; - wa.b *= ta.scale._x; - wa.c *= ta.scale._y; - wa.d *= ta.scale._y; - wa.tx -= ((ta.pivot._x * wa.a) + (ta.pivot._y * wa.c)); - wa.ty -= ((ta.pivot._x * wa.b) + (ta.pivot._y * wa.d)); - } - ta._parentID = pwid; - ta._worldID++; + return t; + } + + function __decorate(decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + } + + function __param(paramIndex, decorator) { + return function (target, key) { decorator(target, key, paramIndex); } + } + + function __metadata(metadataKey, metadataValue) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue); + } + + function __awaiter(thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + } + + function __generator(thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } } - var LinearProjection = (function (_super) { - __extends(LinearProjection, _super); - function LinearProjection() { - var _this = _super !== null && _super.apply(this, arguments) || this; - _this._projID = 0; - _this._currentProjID = -1; - _this._affine = pixi_projection.AFFINE.NONE; - _this.affinePreserveOrientation = false; - _this.scaleAfterAffine = true; + + function __exportStar(m, exports) { + for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p]; + } + + function __values(o) { + var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; + if (m) return m.call(o); + if (o && typeof o.length === "number") return { + next: function () { + if (o && i >= o.length) o = void 0; + return { value: o && o[i++], done: !o }; + } + }; + throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); + } + + function __read(o, n) { + var m = typeof Symbol === "function" && o[Symbol.iterator]; + if (!m) return o; + var i = m.call(o), r, ar = [], e; + try { + while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); + } + catch (error) { e = { error: error }; } + finally { + try { + if (r && !r.done && (m = i["return"])) m.call(i); + } + finally { if (e) throw e.error; } + } + return ar; + } + + function __spread() { + for (var ar = [], i = 0; i < arguments.length; i++) + ar = ar.concat(__read(arguments[i])); + return ar; + } + + function __spreadArrays() { + for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length; + for (var r = Array(s), k = 0, i = 0; i < il; i++) + for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++) + r[k] = a[j]; + return r; + }; + + function __await(v) { + return this instanceof __await ? (this.v = v, this) : new __await(v); + } + + function __asyncGenerator(thisArg, _arguments, generator) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } + function fulfill(value) { resume("next", value); } + function reject(value) { resume("throw", value); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } + } + + function __asyncDelegator(o) { + var i, p; + return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i; + function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; } : f; } + } + + function __asyncValues(o) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var m = o[Symbol.asyncIterator], i; + return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i); + function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; } + function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); } + } + + function __makeTemplateObject(cooked, raw) { + if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; } + return cooked; + }; + + function __importStar(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; + result.default = mod; + return result; + } + + function __importDefault(mod) { + return (mod && mod.__esModule) ? mod : { default: mod }; + } + + function __classPrivateFieldGet(receiver, privateMap) { + if (!privateMap.has(receiver)) { + throw new TypeError("attempted to get private field on non-instance"); + } + return privateMap.get(receiver); + } + + function __classPrivateFieldSet(receiver, privateMap, value) { + if (!privateMap.has(receiver)) { + throw new TypeError("attempted to set private field on non-instance"); + } + privateMap.set(receiver, value); + return value; + } + + function intValueSimple(lerp) { + if (this.ease) { + lerp = this.ease(lerp); + } + return ((this.next.value - this.current.value) * lerp) + this.current.value; + } + function intColorSimple(lerp) { + if (this.ease) { + lerp = this.ease(lerp); + } + var curVal = this.current.value; + var nextVal = this.next.value; + var r = ((nextVal.r - curVal.r) * lerp) + curVal.r; + var g = ((nextVal.g - curVal.g) * lerp) + curVal.g; + var b = ((nextVal.b - curVal.b) * lerp) + curVal.b; + return exports.ParticleUtils.combineRGBComponents(r, g, b); + } + function intValueComplex(lerp) { + if (this.ease) { + lerp = this.ease(lerp); + } + // make sure we are on the right segment + while (lerp > this.next.time) { + this.current = this.next; + this.next = this.next.next; + } + // convert the lerp value to the segment range + lerp = (lerp - this.current.time) / (this.next.time - this.current.time); + return ((this.next.value - this.current.value) * lerp) + this.current.value; + } + function intColorComplex(lerp) { + if (this.ease) { + lerp = this.ease(lerp); + } + // make sure we are on the right segment + while (lerp > this.next.time) { + this.current = this.next; + this.next = this.next.next; + } + // convert the lerp value to the segment range + lerp = (lerp - this.current.time) / (this.next.time - this.current.time); + var curVal = this.current.value; + var nextVal = this.next.value; + var r = ((nextVal.r - curVal.r) * lerp) + curVal.r; + var g = ((nextVal.g - curVal.g) * lerp) + curVal.g; + var b = ((nextVal.b - curVal.b) * lerp) + curVal.b; + return exports.ParticleUtils.combineRGBComponents(r, g, b); + } + function intValueStepped(lerp) { + if (this.ease) { + lerp = this.ease(lerp); + } + // make sure we are on the right segment + while (this.next && lerp > this.next.time) { + this.current = this.next; + this.next = this.next.next; + } + return this.current.value; + } + function intColorStepped(lerp) { + if (this.ease) { + lerp = this.ease(lerp); + } + // make sure we are on the right segment + while (this.next && lerp > this.next.time) { + this.current = this.next; + this.next = this.next.next; + } + var curVal = this.current.value; + return exports.ParticleUtils.combineRGBComponents(curVal.r, curVal.g, curVal.b); + } + /** + * Singly linked list container for keeping track of interpolated properties for particles. + * Each Particle will have one of these for each interpolated property. + */ + var PropertyList = /** @class */ (function () { + /** + * @param isColor If this list handles color values + */ + function PropertyList(isColor) { + if (isColor === void 0) { isColor = false; } + this.current = null; + this.next = null; + this.isColor = !!isColor; + this.interpolate = null; + this.ease = null; + } + /** + * Resets the list for use. + * @param first The first node in the list. + * @param first.isStepped If the values should be stepped instead of interpolated linearly. + */ + PropertyList.prototype.reset = function (first) { + this.current = first; + this.next = first.next; + var isSimple = this.next && this.next.time >= 1; + if (isSimple) { + this.interpolate = this.isColor ? intColorSimple : intValueSimple; + } + else if (first.isStepped) { + this.interpolate = this.isColor ? intColorStepped : intValueStepped; + } + else { + this.interpolate = this.isColor ? intColorComplex : intValueComplex; + } + this.ease = this.current.ease; + }; + return PropertyList; + }()); + + /** + * An individual particle image. You shouldn't have to deal with these. + */ + var Particle = /** @class */ (function (_super) { + __extends(Particle, _super); + /** + * @param {PIXI.particles.Emitter} emitter The emitter that controls this particle. + */ + function Particle(emitter) { + var _this = + // start off the sprite with a blank texture, since we are going to replace it + // later when the particle is initialized. + _super.call(this) || this; + // initialize LinkedListChild props so they are included in underlying JS class definition + _this.prevChild = _this.nextChild = null; + _this.emitter = emitter; + // particles should be centered + _this.anchor.x = _this.anchor.y = 0.5; + _this.velocity = new pixi.Point(); + _this.rotationSpeed = 0; + _this.rotationAcceleration = 0; + _this.maxLife = 0; + _this.age = 0; + _this.ease = null; + _this.extraData = null; + _this.alphaList = new PropertyList(); + _this.speedList = new PropertyList(); + _this.speedMultiplier = 1; + _this.acceleration = new pixi.Point(); + _this.maxSpeed = NaN; + _this.scaleList = new PropertyList(); + _this.scaleMultiplier = 1; + _this.colorList = new PropertyList(true); + _this._doAlpha = false; + _this._doScale = false; + _this._doSpeed = false; + _this._doAcceleration = false; + _this._doColor = false; + _this._doNormalMovement = false; + _this._oneOverLife = 0; + _this.next = null; + _this.prev = null; + // save often used functions on the instance instead of the prototype for better speed + _this.init = _this.init; + _this.Particle_init = Particle.prototype.init; + _this.update = _this.update; + _this.Particle_update = Particle.prototype.update; + _this.Sprite_destroy = _super.prototype.destroy; + _this.Particle_destroy = Particle.prototype.destroy; + _this.applyArt = _this.applyArt; + _this.kill = _this.kill; return _this; } - LinearProjection.prototype.updateLocalTransform = function (lt) { + /** + * Initializes the particle for use, based on the properties that have to + * have been set already on the particle. + */ + Particle.prototype.init = function () { + // reset the age + this.age = 0; + // set up the velocity based on the start speed and rotation + this.velocity.x = this.speedList.current.value * this.speedMultiplier; + this.velocity.y = 0; + exports.ParticleUtils.rotatePoint(this.rotation, this.velocity); + if (this.noRotation) { + this.rotation = 0; + } + else { + // convert rotation to Radians from Degrees + this.rotation *= exports.ParticleUtils.DEG_TO_RADS; + } + // convert rotation speed to Radians from Degrees + this.rotationSpeed *= exports.ParticleUtils.DEG_TO_RADS; + this.rotationAcceleration *= exports.ParticleUtils.DEG_TO_RADS; + // set alpha to inital alpha + this.alpha = this.alphaList.current.value; + // set scale to initial scale + this.scale.x = this.scale.y = this.scaleList.current.value; + // figure out what we need to interpolate + this._doAlpha = !!this.alphaList.current.next; + this._doSpeed = !!this.speedList.current.next; + this._doScale = !!this.scaleList.current.next; + this._doColor = !!this.colorList.current.next; + this._doAcceleration = this.acceleration.x !== 0 || this.acceleration.y !== 0; + // _doNormalMovement can be cancelled by subclasses + this._doNormalMovement = this._doSpeed || this.speedList.current.value !== 0 || this._doAcceleration; + // save our lerp helper + this._oneOverLife = 1 / this.maxLife; + // set the inital color + var color = this.colorList.current.value; + this.tint = exports.ParticleUtils.combineRGBComponents(color.r, color.g, color.b); + // ensure visibility + this.visible = true; }; - Object.defineProperty(LinearProjection.prototype, "affine", { - get: function () { - return this._affine; - }, - set: function (value) { - if (this._affine == value) - return; - this._affine = value; - this._currentProjID = -1; - this.legacy._currentLocalID = -1; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(LinearProjection.prototype, "enabled", { - set: function (value) { - if (value === this._enabled) { - return; - } - this._enabled = value; - if (value) { - this.legacy.updateTransform = transformHack; - this.legacy._parentID = -1; + /** + * Sets the texture for the particle. This can be overridden to allow + * for an animated particle. + * @param art The texture to set. + */ + Particle.prototype.applyArt = function (art) { + this.texture = art || pixi.Texture.EMPTY; + }; + /** + * Updates the particle. + * @param delta Time elapsed since the previous frame, in __seconds__. + * @return The standard interpolation multiplier (0-1) used for all + * relevant particle properties. A value of -1 means the particle + * died of old age instead. + */ + Particle.prototype.update = function (delta) { + // increase age + this.age += delta; + // recycle particle if it is too old + if (this.age >= this.maxLife || this.age < 0) { + this.kill(); + return -1; + } + // determine our interpolation value + var lerp = this.age * this._oneOverLife; // lifetime / maxLife; + if (this.ease) { + if (this.ease.length === 4) { + // the t, b, c, d parameters that some tween libraries use + // (time, initial value, end value, duration) + lerp = this.ease(lerp, 0, 1, 1); } else { - this.legacy.updateTransform = PIXI.Transform.prototype.updateTransform; - this.legacy._parentID = -1; + // the simplified version that we like that takes + // one parameter, time from 0-1. TweenJS eases provide this usage. + lerp = this.ease(lerp); + } + } + // interpolate alpha + if (this._doAlpha) { + this.alpha = this.alphaList.interpolate(lerp); + } + // interpolate scale + if (this._doScale) { + var scale = this.scaleList.interpolate(lerp) * this.scaleMultiplier; + this.scale.x = this.scale.y = scale; + } + // handle movement + if (this._doNormalMovement) { + var deltaX = void 0; + var deltaY = void 0; + // interpolate speed + if (this._doSpeed) { + var speed = this.speedList.interpolate(lerp) * this.speedMultiplier; + exports.ParticleUtils.normalize(this.velocity); + exports.ParticleUtils.scaleBy(this.velocity, speed); + deltaX = this.velocity.x * delta; + deltaY = this.velocity.y * delta; + } + else if (this._doAcceleration) { + var oldVX = this.velocity.x; + var oldVY = this.velocity.y; + this.velocity.x += this.acceleration.x * delta; + this.velocity.y += this.acceleration.y * delta; + if (this.maxSpeed) { + var currentSpeed = exports.ParticleUtils.length(this.velocity); + // if we are going faster than we should, clamp at the max speed + // DO NOT recalculate vector length + if (currentSpeed > this.maxSpeed) { + exports.ParticleUtils.scaleBy(this.velocity, this.maxSpeed / currentSpeed); + } + } + // calculate position delta by the midpoint between our old velocity and our new velocity + deltaX = (oldVX + this.velocity.x) / 2 * delta; + deltaY = (oldVY + this.velocity.y) / 2 * delta; + } + else { + deltaX = this.velocity.x * delta; + deltaY = this.velocity.y * delta; + } + // adjust position based on velocity + this.position.x += deltaX; + this.position.y += deltaY; + } + // interpolate color + if (this._doColor) { + this.tint = this.colorList.interpolate(lerp); + } + // update rotation + if (this.rotationAcceleration !== 0) { + var newRotationSpeed = this.rotationSpeed + (this.rotationAcceleration * delta); + this.rotation += (this.rotationSpeed + newRotationSpeed) / 2 * delta; + this.rotationSpeed = newRotationSpeed; + } + else if (this.rotationSpeed !== 0) { + this.rotation += this.rotationSpeed * delta; + } + else if (this.acceleration && !this.noRotation) { + this.rotation = Math.atan2(this.velocity.y, this.velocity.x); // + Math.PI / 2; + } + return lerp; + }; + /** + * Kills the particle, removing it from the display list + * and telling the emitter to recycle it. + */ + Particle.prototype.kill = function () { + this.emitter.recycle(this); + }; + /** + * Destroys the particle, removing references and preventing future use. + */ + Particle.prototype.destroy = function () { + if (this.parent) { + this.parent.removeChild(this); + } + this.Sprite_destroy(); + this.emitter = this.velocity = this.colorList = this.scaleList = this.alphaList + = this.speedList = this.ease = this.next = this.prev = null; + }; + /** + * Checks over the art that was passed to the Emitter's init() function, to do any special + * modifications to prepare it ahead of time. + * @param art The array of art data. For Particle, it should be an array of + * Textures. Any strings in the array will be converted to + * Textures via Texture.from(). + * @return The art, after any needed modifications. + */ + Particle.parseArt = function (art) { + // convert any strings to Textures. + var i; + for (i = art.length; i >= 0; --i) { + if (typeof art[i] === 'string') { + art[i] = GetTextureFromString(art[i]); + } + } + // particles from different base textures will be slower in WebGL than if they + // were from one spritesheet + if (exports.ParticleUtils.verbose) { + for (i = art.length - 1; i > 0; --i) { + if (art[i].baseTexture !== art[i - 1].baseTexture) { + if (window.console) { + // eslint-disable-next-line max-len + console.warn('PixiParticles: using particle textures from different images may hinder performance in WebGL'); + } + break; + } + } + } + return art; + }; + /** + * Parses extra emitter data to ensure it is set up for this particle class. + * Particle does nothing to the extra data. + * @param extraData The extra data from the particle config. + * @return The parsed extra data. + */ + Particle.parseData = function (extraData) { + return extraData; + }; + return Particle; + }(pixi.Sprite)); + + /** + * Chain of line segments for generating spawn positions. + */ + var PolygonalChain = /** @class */ (function () { + /** + * @param data Point data for polygon chains. Either a list of points for a single chain, or a list of chains. + */ + function PolygonalChain(data) { + this.segments = []; + this.countingLengths = []; + this.totalLength = 0; + this.init(data); + } + /** + * @param data Point data for polygon chains. Either a list of points for a single chain, or a list of chains. + */ + PolygonalChain.prototype.init = function (data) { + // if data is not present, set up a segment of length 0 + if (!data || !data.length) { + this.segments.push({ p1: { x: 0, y: 0 }, p2: { x: 0, y: 0 }, l: 0 }); + } + else if (Array.isArray(data[0])) { + // list of segment chains, each defined as a list of points + for (var i = 0; i < data.length; ++i) { + // loop through the chain, connecting points + var chain = data[i]; + var prevPoint = chain[0]; + for (var j = 1; j < chain.length; ++j) { + var second = chain[j]; + this.segments.push({ p1: prevPoint, p2: second, l: 0 }); + prevPoint = second; + } + } + } + else { + var prevPoint = data[0]; + // list of points + for (var i = 1; i < data.length; ++i) { + var second = data[i]; + this.segments.push({ p1: prevPoint, p2: second, l: 0 }); + prevPoint = second; + } + } + // now go through our segments to calculate the lengths so that we + // can set up a nice weighted random distribution + for (var i = 0; i < this.segments.length; ++i) { + var _a = this.segments[i], p1 = _a.p1, p2 = _a.p2; + var segLength = Math.sqrt(((p2.x - p1.x) * (p2.x - p1.x)) + ((p2.y - p1.y) * (p2.y - p1.y))); + // save length so we can turn a random number into a 0-1 interpolation value later + this.segments[i].l = segLength; + this.totalLength += segLength; + // keep track of the length so far, counting up + this.countingLengths.push(this.totalLength); + } + }; + /** + * Gets a random point in the chain. + * @param out The point to store the selected position in. + */ + PolygonalChain.prototype.getRandomPoint = function (out) { + // select a random spot in the length of the chain + var rand = Math.random() * this.totalLength; + var chosenSeg; + var lerp; + // if only one segment, it wins + if (this.segments.length === 1) { + chosenSeg = this.segments[0]; + lerp = rand; + } + else { + // otherwise, go through countingLengths until we have determined + // which segment we chose + for (var i = 0; i < this.countingLengths.length; ++i) { + if (rand < this.countingLengths[i]) { + chosenSeg = this.segments[i]; + // set lerp equal to the length into that segment + // (i.e. the remainder after subtracting all the segments before it) + lerp = i === 0 ? rand : rand - this.countingLengths[i - 1]; + break; + } + } + } + // divide lerp by the segment length, to result in a 0-1 number. + lerp /= chosenSeg.l || 1; + var p1 = chosenSeg.p1, p2 = chosenSeg.p2; + // now calculate the position in the segment that the lerp value represents + out.x = p1.x + (lerp * (p2.x - p1.x)); + out.y = p1.y + (lerp * (p2.y - p1.y)); + }; + return PolygonalChain; + }()); + + // get the shared ticker, in V4 and V5 friendly methods + /** + * @hidden + */ + var ticker; + // to avoid Rollup transforming our import, save pixi namespace in a variable + var pixiNS$1 = pixi; + if (parseInt((/^(\d+)\./).exec(pixi.VERSION)[1], 10) < 5) { + ticker = pixiNS$1.ticker.shared; + } + else { + ticker = pixiNS$1.Ticker.shared; + } + /** + * @hidden + */ + var helperPoint = new pixi.Point(); + /** + * A particle emitter. + */ + var Emitter = /** @class */ (function () { + /** + * @param particleParent The container to add the particles to. + * @param particleImages A texture or array of textures to use + * for the particles. Strings will be turned + * into textures via Texture.fromImage(). + * @param config A configuration object containing settings for the emitter. + * @param config.emit If config.emit is explicitly passed as false, the + * Emitter will start disabled. + * @param config.autoUpdate If config.autoUpdate is explicitly passed as + * true, the Emitter will automatically call + * update via the PIXI shared ticker. + */ + function Emitter(particleParent, particleImages, config) { + /** + * A number keeping index of currently applied image. Used to emit arts in order. + */ + this._currentImageIndex = -1; + this._particleConstructor = Particle; + // properties for individual particles + this.particleImages = null; + this.startAlpha = null; + this.startSpeed = null; + this.minimumSpeedMultiplier = 1; + this.acceleration = null; + this.maxSpeed = NaN; + this.startScale = null; + this.minimumScaleMultiplier = 1; + this.startColor = null; + this.minLifetime = 0; + this.maxLifetime = 0; + this.minStartRotation = 0; + this.maxStartRotation = 0; + this.noRotation = false; + this.minRotationSpeed = 0; + this.maxRotationSpeed = 0; + this.particleBlendMode = 0; + this.customEase = null; + this.extraData = null; + // properties for spawning particles + this._frequency = 1; + this.spawnChance = 1; + this.maxParticles = 1000; + this.emitterLifetime = -1; + this.spawnPos = null; + this.spawnType = null; + this._spawnFunc = null; + this.spawnRect = null; + this.spawnCircle = null; + this.spawnPolygonalChain = null; + this.particlesPerWave = 1; + this.particleSpacing = 0; + this.angleStart = 0; + // emitter properties + this.rotation = 0; + this.ownerPos = null; + this._prevEmitterPos = null; + this._prevPosIsValid = false; + this._posChanged = false; + this._parent = null; + this.addAtBack = false; + this.particleCount = 0; + this._emit = false; + this._spawnTimer = 0; + this._emitterLife = -1; + this._activeParticlesFirst = null; + this._activeParticlesLast = null; + this._poolFirst = null; + this._origConfig = null; + this._origArt = null; + this._autoUpdate = false; + this._currentImageIndex = -1; + this._destroyWhenComplete = false; + this._completeCallback = null; + // set the initial parent + this.parent = particleParent; + if (particleImages && config) { + this.init(particleImages, config); + } + // save often used functions on the instance instead of the prototype for better speed + this.recycle = this.recycle; + this.update = this.update; + this.rotate = this.rotate; + this.updateSpawnPos = this.updateSpawnPos; + this.updateOwnerPos = this.updateOwnerPos; + } + Object.defineProperty(Emitter.prototype, "orderedArt", { + /** + * If the emitter is using particle art in order as provided in `particleImages`. + * Effective only when `particleImages` has multiple art options. + * This is particularly useful ensuring that each art shows up once, in case you need to emit a body in an order. + * For example: dragon - [Head, body1, body2, ..., tail] + */ + get: function () { return this._currentImageIndex !== -1; }, + set: function (value) { + this._currentImageIndex = value ? 0 : -1; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Emitter.prototype, "frequency", { + /** + * Time between particle spawns in seconds. If this value is not a number greater than 0, + * it will be set to 1 (particle per second) to prevent infinite loops. + */ + get: function () { return this._frequency; }, + set: function (value) { + // do some error checking to prevent infinite loops + if (typeof value === 'number' && value > 0) { + this._frequency = value; + } + else { + this._frequency = 1; } }, enumerable: true, configurable: true }); - LinearProjection.prototype.clear = function () { - this._currentProjID = -1; - this._projID = 0; - }; - return LinearProjection; - }(pixi_projection.AbstractProjection)); - pixi_projection.LinearProjection = LinearProjection; -})(pixi_projection || (pixi_projection = {})); -var pixi_projection; -(function (pixi_projection) { - var TYPES = PIXI.TYPES; - var premultiplyTint = PIXI.utils.premultiplyTint; - var shaderVert = "precision highp float;\nattribute vec3 aVertexPosition;\nattribute vec2 aTextureCoord;\nattribute vec4 aColor;\nattribute float aTextureId;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 vTextureCoord;\nvarying vec4 vColor;\nvarying float vTextureId;\n\nvoid main(void){\n gl_Position.xyw = projectionMatrix * aVertexPosition;\n gl_Position.z = 0.0;\n \n vTextureCoord = aTextureCoord;\n vTextureId = aTextureId;\n vColor = aColor;\n}\n"; - var shaderFrag = "\nvarying vec2 vTextureCoord;\nvarying vec4 vColor;\nvarying float vTextureId;\nuniform sampler2D uSamplers[%count%];\n\nvoid main(void){\nvec4 color;\n%forloop%\ngl_FragColor = color * vColor;\n}"; - var Batch3dGeometry = (function (_super) { - __extends(Batch3dGeometry, _super); - function Batch3dGeometry(_static) { - if (_static === void 0) { _static = false; } - var _this = _super.call(this) || this; - _this._buffer = new PIXI.Buffer(null, _static, false); - _this._indexBuffer = new PIXI.Buffer(null, _static, true); - _this.addAttribute('aVertexPosition', _this._buffer, 3, false, TYPES.FLOAT) - .addAttribute('aTextureCoord', _this._buffer, 2, false, TYPES.FLOAT) - .addAttribute('aColor', _this._buffer, 4, true, TYPES.UNSIGNED_BYTE) - .addAttribute('aTextureId', _this._buffer, 1, true, TYPES.FLOAT) - .addIndex(_this._indexBuffer); - return _this; - } - return Batch3dGeometry; - }(PIXI.Geometry)); - pixi_projection.Batch3dGeometry = Batch3dGeometry; - var Batch2dPluginFactory = (function () { - function Batch2dPluginFactory() { - } - Batch2dPluginFactory.create = function (options) { - var _a = Object.assign({ - vertex: shaderVert, - fragment: shaderFrag, - geometryClass: Batch3dGeometry, - vertexSize: 7, - }, options), vertex = _a.vertex, fragment = _a.fragment, vertexSize = _a.vertexSize, geometryClass = _a.geometryClass; - return (function (_super) { - __extends(BatchPlugin, _super); - function BatchPlugin(renderer) { - var _this = _super.call(this, renderer) || this; - _this.shaderGenerator = new PIXI.BatchShaderGenerator(vertex, fragment); - _this.geometryClass = geometryClass; - _this.vertexSize = vertexSize; - return _this; + Object.defineProperty(Emitter.prototype, "particleConstructor", { + /** + * The constructor used to create new particles. The default is + * the built in Particle class. Setting this will dump any active or + * pooled particles, if the emitter has already been used. + */ + get: function () { return this._particleConstructor; }, + set: function (value) { + if (value !== this._particleConstructor) { + this._particleConstructor = value; + // clean up existing particles + this.cleanup(); + // scrap all the particles + for (var particle = this._poolFirst; particle; particle = particle.next) { + particle.destroy(); + } + this._poolFirst = null; + // re-initialize the emitter so that the new constructor can do anything it needs to + if (this._origConfig && this._origArt) { + this.init(this._origArt, this._origConfig); + } } - BatchPlugin.prototype.packInterleavedGeometry = function (element, attributeBuffer, indexBuffer, aIndex, iIndex) { - var uint32View = attributeBuffer.uint32View, float32View = attributeBuffer.float32View; - var p = aIndex / this.vertexSize; - var uvs = element.uvs; - var indices = element.indices; - var vertexData = element.vertexData; - var vertexData2d = element.vertexData2d; - var textureId = element._texture.baseTexture._batchLocation; - var alpha = Math.min(element.worldAlpha, 1.0); - var argb = alpha < 1.0 && element._texture.baseTexture.alphaMode ? premultiplyTint(element._tintRGB, alpha) - : element._tintRGB + (alpha * 255 << 24); - if (vertexData2d) { - var j = 0; - for (var i = 0; i < vertexData2d.length; i += 3, j += 2) { - float32View[aIndex++] = vertexData2d[i]; - float32View[aIndex++] = vertexData2d[i + 1]; - float32View[aIndex++] = vertexData2d[i + 2]; - float32View[aIndex++] = uvs[j]; - float32View[aIndex++] = uvs[j + 1]; - uint32View[aIndex++] = argb; - float32View[aIndex++] = textureId; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Emitter.prototype, "parent", { + /** + * The container to add particles to. Settings this will dump any active particles. + */ + get: function () { return this._parent; }, + set: function (value) { + this.cleanup(); + this._parent = value; + }, + enumerable: true, + configurable: true + }); + /** + * Sets up the emitter based on the config settings. + * @param art A texture or array of textures to use for the particles. + * @param config A configuration object containing settings for the emitter. + */ + Emitter.prototype.init = function (art, config) { + if (!art || !config) { + return; + } + // clean up any existing particles + this.cleanup(); + // store the original config and particle images, in case we need to re-initialize + // when the particle constructor is changed + this._origConfig = config; + this._origArt = art; + // set up the array of data, also ensuring that it is an array + art = Array.isArray(art) ? art.slice() : [art]; + // run the art through the particle class's parsing function + var partClass = this._particleConstructor; + this.particleImages = partClass.parseArt ? partClass.parseArt(art) : art; + // ///////////////////////// + // Particle Properties // + // ///////////////////////// + // set up the alpha + if (config.alpha) { + this.startAlpha = PropertyNode.createList(config.alpha); + } + else { + this.startAlpha = new PropertyNode(1, 0); + } + // set up the speed + if (config.speed) { + this.startSpeed = PropertyNode.createList(config.speed); + // eslint-disable-next-line max-len + this.minimumSpeedMultiplier = ('minimumSpeedMultiplier' in config ? config.minimumSpeedMultiplier : config.speed.minimumSpeedMultiplier) || 1; + } + else { + this.minimumSpeedMultiplier = 1; + this.startSpeed = new PropertyNode(0, 0); + } + // set up acceleration + var acceleration = config.acceleration; + if (acceleration && (acceleration.x || acceleration.y)) { + // make sure we disable speed interpolation + this.startSpeed.next = null; + this.acceleration = new pixi.Point(acceleration.x, acceleration.y); + this.maxSpeed = config.maxSpeed || NaN; + } + else { + this.acceleration = new pixi.Point(); + } + // set up the scale + if (config.scale) { + this.startScale = PropertyNode.createList(config.scale); + // eslint-disable-next-line max-len + this.minimumScaleMultiplier = ('minimumScaleMultiplier' in config ? config.minimumScaleMultiplier : config.scale.minimumScaleMultiplier) || 1; + } + else { + this.startScale = new PropertyNode(1, 0); + this.minimumScaleMultiplier = 1; + } + // set up the color + if (config.color) { + this.startColor = PropertyNode.createList(config.color); + } + else { + this.startColor = new PropertyNode({ r: 0xFF, g: 0xFF, b: 0xFF }, 0); + } + // set up the start rotation + if (config.startRotation) { + this.minStartRotation = config.startRotation.min; + this.maxStartRotation = config.startRotation.max; + } + else { + this.minStartRotation = this.maxStartRotation = 0; + } + if (config.noRotation + && (this.minStartRotation || this.maxStartRotation)) { + this.noRotation = !!config.noRotation; + } + else { + this.noRotation = false; + } + // set up the rotation speed + if (config.rotationSpeed) { + this.minRotationSpeed = config.rotationSpeed.min; + this.maxRotationSpeed = config.rotationSpeed.max; + } + else { + this.minRotationSpeed = this.maxRotationSpeed = 0; + } + this.rotationAcceleration = config.rotationAcceleration || 0; + // set up the lifetime + this.minLifetime = config.lifetime.min; + this.maxLifetime = config.lifetime.max; + // get the blend mode + this.particleBlendMode = exports.ParticleUtils.getBlendMode(config.blendMode); + // use the custom ease if provided + if (config.ease) { + this.customEase = typeof config.ease === 'function' + ? config.ease : exports.ParticleUtils.generateEase(config.ease); + } + else { + this.customEase = null; + } + // set up the extra data, running it through the particle class's parseData function. + if (partClass.parseData) { + this.extraData = partClass.parseData(config.extraData); + } + else { + this.extraData = config.extraData || null; + } + // //////////////////////// + // Emitter Properties // + // //////////////////////// + // reset spawn type specific settings + this.spawnRect = this.spawnCircle = null; + this.particlesPerWave = 1; + if (config.particlesPerWave && config.particlesPerWave > 1) { + this.particlesPerWave = config.particlesPerWave; + } + this.particleSpacing = 0; + this.angleStart = 0; + // determine the spawn function to use + this.parseSpawnType(config); + // set the spawning frequency + this.frequency = config.frequency; + this.spawnChance = (typeof config.spawnChance === 'number' && config.spawnChance > 0) ? config.spawnChance : 1; + // set the emitter lifetime + this.emitterLifetime = config.emitterLifetime || -1; + // set the max particles + this.maxParticles = config.maxParticles > 0 ? config.maxParticles : 1000; + // determine if we should add the particle at the back of the list or not + this.addAtBack = !!config.addAtBack; + // reset the emitter position and rotation variables + this.rotation = 0; + this.ownerPos = new pixi.Point(); + this.spawnPos = new pixi.Point(config.pos.x, config.pos.y); + this.initAdditional(art, config); + this._prevEmitterPos = this.spawnPos.clone(); + // previous emitter position is invalid and should not be used for interpolation + this._prevPosIsValid = false; + // start emitting + this._spawnTimer = 0; + this.emit = config.emit === undefined ? true : !!config.emit; + this.autoUpdate = !!config.autoUpdate; + this.orderedArt = !!config.orderedArt; + }; + /** + * Sets up additional parameters to the emitter from config settings. + * Using for parsing additional parameters on classes that extend from Emitter + * @param art A texture or array of textures to use for the particles. + * @param config A configuration object containing settings for the emitter. + */ + // eslint-disable-next-line @typescript-eslint/no-unused-vars + Emitter.prototype.initAdditional = function (art, config) { + // override in subclasses + }; + /** + * Parsing emitter spawn type from config settings. + * Place for override and add new kind of spawn type + * @param config A configuration object containing settings for the emitter. + */ + Emitter.prototype.parseSpawnType = function (config) { + var spawnCircle; + switch (config.spawnType) { + case 'rect': + this.spawnType = 'rect'; + this._spawnFunc = this._spawnRect; + var spawnRect = config.spawnRect; + this.spawnRect = new pixi.Rectangle(spawnRect.x, spawnRect.y, spawnRect.w, spawnRect.h); + break; + case 'circle': + this.spawnType = 'circle'; + this._spawnFunc = this._spawnCircle; + spawnCircle = config.spawnCircle; + this.spawnCircle = new pixi.Circle(spawnCircle.x, spawnCircle.y, spawnCircle.r); + break; + case 'ring': + this.spawnType = 'ring'; + this._spawnFunc = this._spawnRing; + spawnCircle = config.spawnCircle; + this.spawnCircle = new pixi.Circle(spawnCircle.x, spawnCircle.y, spawnCircle.r); + this.spawnCircle.minRadius = spawnCircle.minR; + break; + case 'burst': + this.spawnType = 'burst'; + this._spawnFunc = this._spawnBurst; + this.particleSpacing = config.particleSpacing; + this.angleStart = config.angleStart ? config.angleStart : 0; + break; + case 'point': + this.spawnType = 'point'; + this._spawnFunc = this._spawnPoint; + break; + case 'polygonalChain': + this.spawnType = 'polygonalChain'; + this._spawnFunc = this._spawnPolygonalChain; + this.spawnPolygonalChain = new PolygonalChain(config.spawnPolygon); + break; + default: + this.spawnType = 'point'; + this._spawnFunc = this._spawnPoint; + break; + } + }; + /** + * Recycles an individual particle. For internal use only. + * @param particle The particle to recycle. + * @internal + */ + Emitter.prototype.recycle = function (particle) { + if (particle.next) { + particle.next.prev = particle.prev; + } + if (particle.prev) { + particle.prev.next = particle.next; + } + if (particle === this._activeParticlesLast) { + this._activeParticlesLast = particle.prev; + } + if (particle === this._activeParticlesFirst) { + this._activeParticlesFirst = particle.next; + } + // add to pool + particle.prev = null; + particle.next = this._poolFirst; + this._poolFirst = particle; + // remove child from display, or make it invisible if it is in a ParticleContainer + if (particle.parent) { + particle.parent.removeChild(particle); + } + // decrease count + --this.particleCount; + }; + /** + * Sets the rotation of the emitter to a new value. + * @param newRot The new rotation, in degrees. + */ + Emitter.prototype.rotate = function (newRot) { + if (this.rotation === newRot) + return; + // caclulate the difference in rotation for rotating spawnPos + var diff = newRot - this.rotation; + this.rotation = newRot; + // rotate spawnPos + exports.ParticleUtils.rotatePoint(diff, this.spawnPos); + // mark the position as having changed + this._posChanged = true; + }; + /** + * Changes the spawn position of the emitter. + * @param x The new x value of the spawn position for the emitter. + * @param y The new y value of the spawn position for the emitter. + */ + Emitter.prototype.updateSpawnPos = function (x, y) { + this._posChanged = true; + this.spawnPos.x = x; + this.spawnPos.y = y; + }; + /** + * Changes the position of the emitter's owner. You should call this if you are adding + * particles to the world container that your emitter's owner is moving around in. + * @param x The new x value of the emitter's owner. + * @param y The new y value of the emitter's owner. + */ + Emitter.prototype.updateOwnerPos = function (x, y) { + this._posChanged = true; + this.ownerPos.x = x; + this.ownerPos.y = y; + }; + /** + * Prevents emitter position interpolation in the next update. + * This should be used if you made a major position change of your emitter's owner + * that was not normal movement. + */ + Emitter.prototype.resetPositionTracking = function () { + this._prevPosIsValid = false; + }; + Object.defineProperty(Emitter.prototype, "emit", { + /** + * If particles should be emitted during update() calls. Setting this to false + * stops new particles from being created, but allows existing ones to die out. + */ + get: function () { return this._emit; }, + set: function (value) { + this._emit = !!value; + this._emitterLife = this.emitterLifetime; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Emitter.prototype, "autoUpdate", { + /** + * If the update function is called automatically from the shared ticker. + * Setting this to false requires calling the update function manually. + */ + get: function () { return this._autoUpdate; }, + set: function (value) { + if (this._autoUpdate && !value) { + ticker.remove(this.update, this); + } + else if (!this._autoUpdate && value) { + ticker.add(this.update, this); + } + this._autoUpdate = !!value; + }, + enumerable: true, + configurable: true + }); + /** + * Starts emitting particles, sets autoUpdate to true, and sets up the Emitter to destroy itself + * when particle emission is complete. + * @param callback Callback for when emission is complete (all particles have died off) + */ + Emitter.prototype.playOnceAndDestroy = function (callback) { + this.autoUpdate = true; + this.emit = true; + this._destroyWhenComplete = true; + this._completeCallback = callback; + }; + /** + * Starts emitting particles and optionally calls a callback when particle emission is complete. + * @param callback Callback for when emission is complete (all particles have died off) + */ + Emitter.prototype.playOnce = function (callback) { + this.emit = true; + this._completeCallback = callback; + }; + /** + * Updates all particles spawned by this emitter and emits new ones. + * @param delta Time elapsed since the previous frame, in __seconds__. + */ + Emitter.prototype.update = function (delta) { + if (this._autoUpdate) { + delta = delta / pixi.settings.TARGET_FPMS / 1000; + } + // if we don't have a parent to add particles to, then don't do anything. + // this also works as a isDestroyed check + if (!this._parent) + return; + // update existing particles + var i; + var particle; + var next; + for (particle = this._activeParticlesFirst; particle; particle = next) { + next = particle.next; + particle.update(delta); + } + var prevX; + var prevY; + // if the previous position is valid, store these for later interpolation + if (this._prevPosIsValid) { + prevX = this._prevEmitterPos.x; + prevY = this._prevEmitterPos.y; + } + // store current position of the emitter as local variables + var curX = this.ownerPos.x + this.spawnPos.x; + var curY = this.ownerPos.y + this.spawnPos.y; + // spawn new particles + if (this._emit) { + // decrease spawn timer + this._spawnTimer -= delta < 0 ? 0 : delta; + // while _spawnTimer < 0, we have particles to spawn + while (this._spawnTimer <= 0) { + // determine if the emitter should stop spawning + if (this._emitterLife >= 0) { + this._emitterLife -= this._frequency; + if (this._emitterLife <= 0) { + this._spawnTimer = 0; + this._emitterLife = 0; + this.emit = false; + break; } } + // determine if we have hit the particle limit + if (this.particleCount >= this.maxParticles) { + this._spawnTimer += this._frequency; + continue; + } + // determine the particle lifetime + var lifetime = void 0; + if (this.minLifetime === this.maxLifetime) { + lifetime = this.minLifetime; + } else { - for (var i = 0; i < vertexData.length; i += 2) { - float32View[aIndex++] = vertexData[i]; - float32View[aIndex++] = vertexData[i + 1]; - float32View[aIndex++] = 1.0; - float32View[aIndex++] = uvs[i]; - float32View[aIndex++] = uvs[i + 1]; - uint32View[aIndex++] = argb; - float32View[aIndex++] = textureId; + lifetime = (Math.random() * (this.maxLifetime - this.minLifetime)) + this.minLifetime; + } + // only make the particle if it wouldn't immediately destroy itself + if (-this._spawnTimer < lifetime) { + // If the position has changed and this isn't the first spawn, + // interpolate the spawn position + var emitPosX = void 0; + var emitPosY = void 0; + if (this._prevPosIsValid && this._posChanged) { + // 1 - _spawnTimer / delta, but _spawnTimer is negative + var lerp = 1 + (this._spawnTimer / delta); + emitPosX = ((curX - prevX) * lerp) + prevX; + emitPosY = ((curY - prevY) * lerp) + prevY; + } + else // otherwise just set to the spawn position + { + emitPosX = curX; + emitPosY = curY; + } + // create enough particles to fill the wave (non-burst types have a wave of 1) + i = 0; + for (var len = Math.min(this.particlesPerWave, this.maxParticles - this.particleCount); i < len; ++i) { + // see if we actually spawn one + if (this.spawnChance < 1 && Math.random() >= this.spawnChance) { + continue; + } + // create particle + var p = void 0; + if (this._poolFirst) { + p = this._poolFirst; + this._poolFirst = this._poolFirst.next; + p.next = null; + } + else { + p = new this.particleConstructor(this); + } + // set a random texture if we have more than one + if (this.particleImages.length > 1) { + // if using ordered art + if (this._currentImageIndex !== -1) { + // get current art index, then increment for the next particle + p.applyArt(this.particleImages[this._currentImageIndex++]); + // loop around if needed + if (this._currentImageIndex < 0 || this._currentImageIndex >= this.particleImages.length) { + this._currentImageIndex = 0; + } + } + // otherwise grab a random one + else { + p.applyArt(this.particleImages[Math.floor(Math.random() * this.particleImages.length)]); + } + } + else { + // if they are actually the same texture, a standard particle + // will quit early from the texture setting in setTexture(). + p.applyArt(this.particleImages[0]); + } + // set up the start and end values + p.alphaList.reset(this.startAlpha); + if (this.minimumSpeedMultiplier !== 1) { + // eslint-disable-next-line max-len + p.speedMultiplier = (Math.random() * (1 - this.minimumSpeedMultiplier)) + this.minimumSpeedMultiplier; + } + p.speedList.reset(this.startSpeed); + p.acceleration.x = this.acceleration.x; + p.acceleration.y = this.acceleration.y; + p.maxSpeed = this.maxSpeed; + if (this.minimumScaleMultiplier !== 1) { + // eslint-disable-next-line max-len + p.scaleMultiplier = (Math.random() * (1 - this.minimumScaleMultiplier)) + this.minimumScaleMultiplier; + } + p.scaleList.reset(this.startScale); + p.colorList.reset(this.startColor); + // randomize the rotation speed + if (this.minRotationSpeed === this.maxRotationSpeed) { + p.rotationSpeed = this.minRotationSpeed; + } + else { + // eslint-disable-next-line max-len + p.rotationSpeed = (Math.random() * (this.maxRotationSpeed - this.minRotationSpeed)) + this.minRotationSpeed; + } + p.rotationAcceleration = this.rotationAcceleration; + p.noRotation = this.noRotation; + // set up the lifetime + p.maxLife = lifetime; + // set the blend mode + p.blendMode = this.particleBlendMode; + // set the custom ease, if any + p.ease = this.customEase; + // set the extra data, if any + p.extraData = this.extraData; + // set additional properties to particle + this.applyAdditionalProperties(p); + // call the proper function to handle rotation and position of particle + this._spawnFunc(p, emitPosX, emitPosY, i); + // initialize particle + p.init(); + // add the particle to the display list + if (this.addAtBack) { + this._parent.addChildAt(p, 0); + } + else { + this._parent.addChild(p); + } + // add particle to list of active particles + if (this._activeParticlesLast) { + this._activeParticlesLast.next = p; + p.prev = this._activeParticlesLast; + this._activeParticlesLast = p; + } + else { + this._activeParticlesLast = this._activeParticlesFirst = p; + } + ++this.particleCount; + // update the particle by the time passed, so the particles are spread out properly + p.update(-this._spawnTimer); // we want a positive delta, because a negative delta messes things up } } - for (var i = 0; i < indices.length; i++) { - indexBuffer[iIndex++] = p + indices[i]; - } - }; - return BatchPlugin; - }(PIXI.AbstractBatchRenderer)); + // increase timer and continue on to any other particles that need to be created + this._spawnTimer += this._frequency; + } + } + // if the position changed before this update, then keep track of that + if (this._posChanged) { + this._prevEmitterPos.x = curX; + this._prevEmitterPos.y = curY; + this._prevPosIsValid = true; + this._posChanged = false; + } + // if we are all done and should destroy ourselves, take care of that + if (!this._emit && !this._activeParticlesFirst) { + if (this._completeCallback) { + var cb = this._completeCallback; + this._completeCallback = null; + cb(); + } + if (this._destroyWhenComplete) { + this.destroy(); + } + } }; - return Batch2dPluginFactory; - }()); - pixi_projection.Batch2dPluginFactory = Batch2dPluginFactory; - PIXI.Renderer.registerPlugin('batch2d', Batch2dPluginFactory.create({})); -})(pixi_projection || (pixi_projection = {})); -var pixi_projection; -(function (pixi_projection) { - var AbstractBatchRenderer = PIXI.AbstractBatchRenderer; - var premultiplyBlendMode = PIXI.utils.premultiplyBlendMode; - var UniformBatchRenderer = (function (_super) { - __extends(UniformBatchRenderer, _super); - function UniformBatchRenderer() { + /** + * Set additional properties to new particle. + * Using on classes that extend from Emitter + * @param p The particle + */ + // eslint-disable-next-line @typescript-eslint/no-unused-vars + Emitter.prototype.applyAdditionalProperties = function (p) { + // for override in subclass + }; + /** + * Positions a particle for a point type emitter. + * @param p The particle to position and rotate. + * @param emitPosX The emitter's x position + * @param emitPosY The emitter's y position + * @param i The particle number in the current wave. Not used for this function. + */ + Emitter.prototype._spawnPoint = function (p, emitPosX, emitPosY) { + // set the initial rotation/direction of the particle based on + // starting particle angle and rotation of emitter + if (this.minStartRotation === this.maxStartRotation) { + p.rotation = this.minStartRotation + this.rotation; + } + else { + // eslint-disable-next-line max-len + p.rotation = (Math.random() * (this.maxStartRotation - this.minStartRotation)) + this.minStartRotation + this.rotation; + } + // drop the particle at the emitter's position + p.position.x = emitPosX; + p.position.y = emitPosY; + }; + /** + * Positions a particle for a rectangle type emitter. + * @param p The particle to position and rotate. + * @param emitPosX The emitter's x position + * @param emitPosY The emitter's y position + * @param i The particle number in the current wave. Not used for this function. + */ + Emitter.prototype._spawnRect = function (p, emitPosX, emitPosY) { + // set the initial rotation/direction of the particle based on starting + // particle angle and rotation of emitter + if (this.minStartRotation === this.maxStartRotation) { + p.rotation = this.minStartRotation + this.rotation; + } + else { + // eslint-disable-next-line max-len + p.rotation = (Math.random() * (this.maxStartRotation - this.minStartRotation)) + this.minStartRotation + this.rotation; + } + // place the particle at a random point in the rectangle + helperPoint.x = (Math.random() * this.spawnRect.width) + this.spawnRect.x; + helperPoint.y = (Math.random() * this.spawnRect.height) + this.spawnRect.y; + if (this.rotation !== 0) { + exports.ParticleUtils.rotatePoint(this.rotation, helperPoint); + } + p.position.x = emitPosX + helperPoint.x; + p.position.y = emitPosY + helperPoint.y; + }; + /** + * Positions a particle for a circle type emitter. + * @param p The particle to position and rotate. + * @param emitPosX The emitter's x position + * @param emitPosY The emitter's y position + * @param i The particle number in the current wave. Not used for this function. + */ + Emitter.prototype._spawnCircle = function (p, emitPosX, emitPosY) { + // set the initial rotation/direction of the particle based on starting + // particle angle and rotation of emitter + if (this.minStartRotation === this.maxStartRotation) { + p.rotation = this.minStartRotation + this.rotation; + } + else { + // eslint-disable-next-line max-len + p.rotation = (Math.random() * (this.maxStartRotation - this.minStartRotation)) + this.minStartRotation + this.rotation; + } + // place the particle at a random radius in the circle + helperPoint.x = Math.random() * this.spawnCircle.radius; + helperPoint.y = 0; + // rotate the point to a random angle in the circle + exports.ParticleUtils.rotatePoint(Math.random() * 360, helperPoint); + // offset by the circle's center + helperPoint.x += this.spawnCircle.x; + helperPoint.y += this.spawnCircle.y; + // rotate the point by the emitter's rotation + if (this.rotation !== 0) { + exports.ParticleUtils.rotatePoint(this.rotation, helperPoint); + } + // set the position, offset by the emitter's position + p.position.x = emitPosX + helperPoint.x; + p.position.y = emitPosY + helperPoint.y; + }; + /** + * Positions a particle for a ring type emitter. + * @param p The particle to position and rotate. + * @param emitPosX The emitter's x position + * @param emitPosY The emitter's y position + * @param i The particle number in the current wave. Not used for this function. + */ + Emitter.prototype._spawnRing = function (p, emitPosX, emitPosY) { + var spawnCircle = this.spawnCircle; + // set the initial rotation/direction of the particle based on starting + // particle angle and rotation of emitter + if (this.minStartRotation === this.maxStartRotation) { + p.rotation = this.minStartRotation + this.rotation; + } + else { + p.rotation = (Math.random() * (this.maxStartRotation - this.minStartRotation)) + + this.minStartRotation + this.rotation; + } + // place the particle at a random radius in the ring + if (spawnCircle.minRadius !== spawnCircle.radius) { + helperPoint.x = (Math.random() * (spawnCircle.radius - spawnCircle.minRadius)) + + spawnCircle.minRadius; + } + else { + helperPoint.x = spawnCircle.radius; + } + helperPoint.y = 0; + // rotate the point to a random angle in the circle + var angle = Math.random() * 360; + p.rotation += angle; + exports.ParticleUtils.rotatePoint(angle, helperPoint); + // offset by the circle's center + helperPoint.x += this.spawnCircle.x; + helperPoint.y += this.spawnCircle.y; + // rotate the point by the emitter's rotation + if (this.rotation !== 0) { + exports.ParticleUtils.rotatePoint(this.rotation, helperPoint); + } + // set the position, offset by the emitter's position + p.position.x = emitPosX + helperPoint.x; + p.position.y = emitPosY + helperPoint.y; + }; + /** + * Positions a particle for polygonal chain. + * @param p The particle to position and rotate. + * @param emitPosX The emitter's x position + * @param emitPosY The emitter's y position + * @param i The particle number in the current wave. Not used for this function. + */ + Emitter.prototype._spawnPolygonalChain = function (p, emitPosX, emitPosY) { + // set the initial rotation/direction of the particle based on starting + // particle angle and rotation of emitter + if (this.minStartRotation === this.maxStartRotation) { + p.rotation = this.minStartRotation + this.rotation; + } + else { + p.rotation = (Math.random() * (this.maxStartRotation - this.minStartRotation)) + + this.minStartRotation + this.rotation; + } + // get random point on the polygon chain + this.spawnPolygonalChain.getRandomPoint(helperPoint); + // rotate the point by the emitter's rotation + if (this.rotation !== 0) { + exports.ParticleUtils.rotatePoint(this.rotation, helperPoint); + } + // set the position, offset by the emitter's position + p.position.x = emitPosX + helperPoint.x; + p.position.y = emitPosY + helperPoint.y; + }; + /** + * Positions a particle for a burst type emitter. + * @param p The particle to position and rotate. + * @param emitPosX The emitter's x position + * @param emitPosY The emitter's y position + * @param i The particle number in the current wave. + */ + Emitter.prototype._spawnBurst = function (p, emitPosX, emitPosY, i) { + // set the initial rotation/direction of the particle based on spawn + // angle and rotation of emitter + if (this.particleSpacing === 0) { + p.rotation = Math.random() * 360; + } + else { + p.rotation = this.angleStart + (this.particleSpacing * i) + this.rotation; + } + // drop the particle at the emitter's position + p.position.x = emitPosX; + p.position.y = emitPosY; + }; + /** + * Kills all active particles immediately. + */ + Emitter.prototype.cleanup = function () { + var particle; + var next; + for (particle = this._activeParticlesFirst; particle; particle = next) { + next = particle.next; + this.recycle(particle); + if (particle.parent) { + particle.parent.removeChild(particle); + } + } + this._activeParticlesFirst = this._activeParticlesLast = null; + this.particleCount = 0; + }; + /** + * Destroys the emitter and all of its particles. + */ + Emitter.prototype.destroy = function () { + // make sure we aren't still listening to any tickers + this.autoUpdate = false; + // puts all active particles in the pool, and removes them from the particle parent + this.cleanup(); + // wipe the pool clean + var next; + for (var particle = this._poolFirst; particle; particle = next) { + // store next value so we don't lose it in our destroy call + next = particle.next; + particle.destroy(); + } + this._poolFirst = this._parent = this.particleImages = this.spawnPos = this.ownerPos + = this.startColor = this.startScale = this.startAlpha = this.startSpeed + = this.customEase = this._completeCallback = null; + }; + return Emitter; + }()); + + /** + * A helper point for math things. + * @hidden + */ + var helperPoint$1 = new pixi.Point(); + /** + * A hand picked list of Math functions (and a couple properties) that are + * allowable. They should be used without the preceding "Math." + * @hidden + */ + var MATH_FUNCS = [ + 'pow', + 'sqrt', + 'abs', + 'floor', + 'round', + 'ceil', + 'E', + 'PI', + 'sin', + 'cos', + 'tan', + 'asin', + 'acos', + 'atan', + 'atan2', + 'log', + ]; + /** + * create an actual regular expression object from the string + * @hidden + */ + var WHITELISTER = new RegExp([ + // Allow the 4 basic operations, parentheses and all numbers/decimals, as well + // as 'x', for the variable usage. + '[01234567890\\.\\*\\-\\+\\/\\(\\)x ,]', + ].concat(MATH_FUNCS).join('|'), 'g'); + /** + * Parses a string into a function for path following. + * This involves whitelisting the string for safety, inserting "Math." to math function + * names, and using `new Function()` to generate a function. + * @hidden + * @param pathString The string to parse. + * @return The path function - takes x, outputs y. + */ + function parsePath(pathString) { + var matches = pathString.match(WHITELISTER); + for (var i = matches.length - 1; i >= 0; --i) { + if (MATH_FUNCS.indexOf(matches[i]) >= 0) { + matches[i] = "Math." + matches[i]; + } + } + pathString = matches.join(''); + // eslint-disable-next-line no-new-func + return new Function('x', "return " + pathString + ";"); + } + /** + * An particle that follows a path defined by an algebraic expression, e.g. "sin(x)" or + * "5x + 3". + * To use this class, the particle config must have a "path" string in the + * "extraData" parameter. This string should have "x" in it to represent movement (from the + * speed settings of the particle). It may have numbers, parentheses, the four basic + * operations, and the following Math functions or properties (without the preceding "Math."): + * "pow", "sqrt", "abs", "floor", "round", "ceil", "E", "PI", "sin", "cos", "tan", "asin", + * "acos", "atan", "atan2", "log". + * The overall movement of the particle and the expression value become x and y positions for + * the particle, respectively. The final position is rotated by the spawn rotation/angle of + * the particle. + * + * Some example paths: + * + * "sin(x/10) * 20" // A sine wave path. + * "cos(x/100) * 30" // Particles curve counterclockwise (for medium speed/low lifetime particles) + * "pow(x/10, 2) / 2" // Particles curve clockwise (remember, +y is down). + */ + var PathParticle = /** @class */ (function (_super) { + __extends(PathParticle, _super); + /** + * @param {PIXI.particles.Emitter} emitter The emitter that controls this PathParticle. + */ + function PathParticle(emitter) { + var _this = _super.call(this, emitter) || this; + _this.path = null; + _this.initialRotation = 0; + _this.initialPosition = new pixi.Point(); + _this.movement = 0; + return _this; + } + /** + * Initializes the particle for use, based on the properties that have to + * have been set already on the particle. + */ + PathParticle.prototype.init = function () { + // get initial rotation before it is converted to radians + this.initialRotation = this.rotation; + // standard init + this.Particle_init(); + // set the path for the particle + this.path = this.extraData.path; + // cancel the normal movement behavior + this._doNormalMovement = !this.path; + // reset movement + this.movement = 0; + // grab position + this.initialPosition.x = this.position.x; + this.initialPosition.y = this.position.y; + }; + /** + * Updates the particle. + * @param delta Time elapsed since the previous frame, in __seconds__. + */ + PathParticle.prototype.update = function (delta) { + var lerp = this.Particle_update(delta); + // if the particle died during the update, then don't bother + if (lerp >= 0 && this.path) { + // increase linear movement based on speed + if (this._doSpeed) { + var speed = this.speedList.interpolate(lerp) * this.speedMultiplier; + this.movement += speed * delta; + } + else { + var speed = this.speedList.current.value * this.speedMultiplier; + this.movement += speed * delta; + } + // set up the helper point for rotation + helperPoint$1.x = this.movement; + helperPoint$1.y = this.path(this.movement); + exports.ParticleUtils.rotatePoint(this.initialRotation, helperPoint$1); + this.position.x = this.initialPosition.x + helperPoint$1.x; + this.position.y = this.initialPosition.y + helperPoint$1.y; + } + return lerp; + }; + /** + * Destroys the particle, removing references and preventing future use. + */ + PathParticle.prototype.destroy = function () { + this.Particle_destroy(); + this.path = this.initialPosition = null; + }; + /** + * Checks over the art that was passed to the Emitter's init() function, to do any special + * modifications to prepare it ahead of time. This just runs Particle.parseArt(). + * @param art The array of art data. For Particle, it should be an array of + * Textures. Any strings in the array will be converted to + * Textures via Texture.fromImage(). + * @return The art, after any needed modifications. + */ + PathParticle.parseArt = function (art) { + return Particle.parseArt(art); + }; + /** + * Parses extra emitter data to ensure it is set up for this particle class. + * PathParticle checks for the existence of path data, and parses the path data for use + * by particle instances. + * @param extraData The extra data from the particle config. + * @return The parsed extra data. + */ + PathParticle.parseData = function (extraData) { + var output = {}; + if (extraData && extraData.path) { + try { + output.path = parsePath(extraData.path); + } + catch (e) { + if (exports.ParticleUtils.verbose) { + console.error('PathParticle: error in parsing path expression'); + } + output.path = null; + } + } + else { + if (exports.ParticleUtils.verbose) { + console.error('PathParticle requires a path string in extraData!'); + } + output.path = null; + } + return output; + }; + return PathParticle; + }(Particle)); + + /** + * An individual particle image with an animation. Art data passed to the emitter must be + * formatted in a particular way for AnimatedParticle to be able to handle it: + * + * ```typescript + * { + * //framerate is required. It is the animation speed of the particle in frames per + * //second. + * //A value of "matchLife" causes the animation to match the lifetime of an individual + * //particle, instead of at a constant framerate. This causes the animation to play + * //through one time, completing when the particle expires. + * framerate: 6, + * //loop is optional, and defaults to false. + * loop: true, + * //textures is required, and can be an array of any (non-zero) length. + * textures: [ + * //each entry represents a single texture that should be used for one or more + * //frames. Any strings will be converted to Textures with Texture.from(). + * //Instances of PIXI.Texture will be used directly. + * "animFrame1.png", + * //entries can be an object with a 'count' property, telling AnimatedParticle to + * //use that texture for 'count' frames sequentially. + * { + * texture: "animFrame2.png", + * count: 3 + * }, + * "animFrame3.png" + * ] + * } + * ``` + */ + var AnimatedParticle = /** @class */ (function (_super) { + __extends(AnimatedParticle, _super); + /** + * @param emitter The emitter that controls this AnimatedParticle. + */ + function AnimatedParticle(emitter) { + var _this = _super.call(this, emitter) || this; + _this.textures = null; + _this.duration = 0; + _this.framerate = 0; + _this.elapsed = 0; + _this.loop = false; + return _this; + } + /** + * Initializes the particle for use, based on the properties that have to + * have been set already on the particle. + */ + AnimatedParticle.prototype.init = function () { + this.Particle_init(); + this.elapsed = 0; + // if the animation needs to match the particle's life, then cacluate variables + if (this.framerate < 0) { + this.duration = this.maxLife; + this.framerate = this.textures.length / this.duration; + } + }; + /** + * Sets the textures for the particle. + * @param art An array of PIXI.Texture objects for this animated particle. + */ + AnimatedParticle.prototype.applyArt = function (art) { + this.textures = art.textures; + this.framerate = art.framerate; + this.duration = art.duration; + this.loop = art.loop; + }; + /** + * Updates the particle. + * @param delta Time elapsed since the previous frame, in __seconds__. + */ + AnimatedParticle.prototype.update = function (delta) { + var lerp = this.Particle_update(delta); + // only animate the particle if it is still alive + if (lerp >= 0) { + this.elapsed += delta; + if (this.elapsed >= this.duration) { + // loop elapsed back around + if (this.loop) { + this.elapsed = this.elapsed % this.duration; + } + // subtract a small amount to prevent attempting to go past the end of the animation + else { + this.elapsed = this.duration - 0.000001; + } + } + // add a very small number to the frame and then floor it to avoid + // the frame being one short due to floating point errors. + var frame = ((this.elapsed * this.framerate) + 0.0000001) | 0; + // in the very rare case that framerate * elapsed math ends up going past the end, use the last texture + this.texture = this.textures[frame] || this.textures[this.textures.length - 1] || pixi.Texture.EMPTY; + } + return lerp; + }; + /** + * Destroys the particle, removing references and preventing future use. + */ + AnimatedParticle.prototype.destroy = function () { + this.Particle_destroy(); + this.textures = null; + }; + /** + * Checks over the art that was passed to the Emitter's init() function, to do any special + * modifications to prepare it ahead of time. + * @param art The array of art data, properly formatted for AnimatedParticle. + * @return The art, after any needed modifications. + */ + AnimatedParticle.parseArt = function (art) { + var outArr = []; + for (var i = 0; i < art.length; ++i) { + var data = art[i]; + var output = outArr[i] = {}; + var outTextures = output.textures = []; + var textures = data.textures; + for (var j = 0; j < textures.length; ++j) { + var tex = textures[j]; + if (typeof tex === 'string') { + outTextures.push(GetTextureFromString(tex)); + } + else if (tex instanceof pixi.Texture) { + outTextures.push(tex); + } + // assume an object with extra data determining duplicate frame data + else { + var dupe = tex.count || 1; + if (typeof tex.texture === 'string') { + tex = GetTextureFromString(tex.texture); + } + else // if(tex.texture instanceof Texture) + { + tex = tex.texture; + } + for (; dupe > 0; --dupe) { + outTextures.push(tex); + } + } + } + // use these values to signify that the animation should match the particle life time. + if (data.framerate === 'matchLife') { + // -1 means that it should be calculated + output.framerate = -1; + output.duration = 0; + output.loop = false; + } + else { + // determine if the animation should loop + output.loop = !!data.loop; + // get the framerate, default to 60 + output.framerate = data.framerate > 0 ? data.framerate : 60; + // determine the duration + output.duration = outTextures.length / output.framerate; + } + } + return outArr; + }; + return AnimatedParticle; + }(Particle)); + + /** + * A semi-experimental Container that uses a doubly linked list to manage children instead of an + * array. This means that adding/removing children often is not the same performance hit that + * it would to be continually pushing/splicing. + * However, this is primarily intended to be used for heavy particle usage, and may not handle + * edge cases well if used as a complete Container replacement. + */ + var LinkedListContainer = /** @class */ (function (_super) { + __extends(LinkedListContainer, _super); + function LinkedListContainer() { var _this = _super !== null && _super.apply(this, arguments) || this; - _this.forceMaxTextures = 0; - _this.defUniforms = {}; + _this._firstChild = null; + _this._lastChild = null; + _this._childCount = 0; return _this; } - UniformBatchRenderer.prototype.getUniforms = function (sprite) { - return this.defUniforms; - }; - UniformBatchRenderer.prototype.syncUniforms = function (obj) { - if (!obj) - return; - var sh = this._shader; - for (var key in obj) { - sh.uniforms[key] = obj[key]; + Object.defineProperty(LinkedListContainer.prototype, "firstChild", { + get: function () { + return this._firstChild; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(LinkedListContainer.prototype, "lastChild", { + get: function () { + return this._lastChild; + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(LinkedListContainer.prototype, "childCount", { + get: function () { + return this._childCount; + }, + enumerable: true, + configurable: true + }); + LinkedListContainer.prototype.addChild = function () { + var children = []; + for (var _i = 0; _i < arguments.length; _i++) { + children[_i] = arguments[_i]; } - }; - UniformBatchRenderer.prototype.buildDrawCalls = function (texArray, start, finish) { - var thisAny = this; - var _a = this, elements = _a._bufferedElements, _attributeBuffer = _a._attributeBuffer, _indexBuffer = _a._indexBuffer, vertexSize = _a.vertexSize; - var drawCalls = AbstractBatchRenderer._drawCallPool; - var dcIndex = this._dcIndex; - var aIndex = this._aIndex; - var iIndex = this._iIndex; - var drawCall = drawCalls[dcIndex]; - drawCall.start = this._iIndex; - drawCall.texArray = texArray; - for (var i = start; i < finish; ++i) { - var sprite = elements[i]; - var tex = sprite._texture.baseTexture; - var spriteBlendMode = premultiplyBlendMode[tex.alphaMode ? 1 : 0][sprite.blendMode]; - var uniforms = this.getUniforms(sprite); - elements[i] = null; - if (start < i && (drawCall.blend !== spriteBlendMode || drawCall.uniforms !== uniforms)) { - drawCall.size = iIndex - drawCall.start; - start = i; - drawCall = drawCalls[++dcIndex]; - drawCall.texArray = texArray; - drawCall.start = iIndex; + // if there is only one argument we can bypass looping through the them + if (children.length > 1) { + // loop through the array and add all children + for (var i = 0; i < children.length; i++) { + // eslint-disable-next-line prefer-rest-params + this.addChild(children[i]); } - this.packInterleavedGeometry(sprite, _attributeBuffer, _indexBuffer, aIndex, iIndex); - aIndex += sprite.vertexData.length / 2 * vertexSize; - iIndex += sprite.indices.length; - drawCall.blend = spriteBlendMode; - drawCall.uniforms = uniforms; - } - if (start < finish) { - drawCall.size = iIndex - drawCall.start; - ++dcIndex; - } - thisAny._dcIndex = dcIndex; - thisAny._aIndex = aIndex; - thisAny._iIndex = iIndex; - }; - UniformBatchRenderer.prototype.drawBatches = function () { - var dcCount = this._dcIndex; - var _a = this.renderer, gl = _a.gl, stateSystem = _a.state, shaderSystem = _a.shader; - var drawCalls = AbstractBatchRenderer._drawCallPool; - var curUniforms = null; - var curTexArray = null; - for (var i = 0; i < dcCount; i++) { - var _b = drawCalls[i], texArray = _b.texArray, type = _b.type, size = _b.size, start = _b.start, blend = _b.blend, uniforms = _b.uniforms; - if (curTexArray !== texArray) { - curTexArray = texArray; - this.bindAndClearTexArray(texArray); - } - if (curUniforms !== uniforms) { - curUniforms = uniforms; - this.syncUniforms(uniforms); - shaderSystem.syncUniformGroup(this._shader.uniformGroup); - } - stateSystem.setBlendMode(blend); - gl.drawElements(type, size, gl.UNSIGNED_SHORT, start * 2); - } - }; - UniformBatchRenderer.prototype.contextChange = function () { - if (!this.forceMaxTextures) { - _super.prototype.contextChange.call(this); - this.syncUniforms(this.defUniforms); - return; - } - var gl = this.renderer.gl; - var thisAny = this; - thisAny.MAX_TEXTURES = this.forceMaxTextures; - this._shader = thisAny.shaderGenerator.generateShader(this.MAX_TEXTURES); - this.syncUniforms(this.defUniforms); - for (var i = 0; i < thisAny._packedGeometryPoolSize; i++) { - thisAny._packedGeometries[i] = new (this.geometryClass)(); - } - this.initFlushBuffers(); - }; - return UniformBatchRenderer; - }(AbstractBatchRenderer)); - pixi_projection.UniformBatchRenderer = UniformBatchRenderer; -})(pixi_projection || (pixi_projection = {})); -var pixi_projection; -(function (pixi_projection) { - var p = [new PIXI.Point(), new PIXI.Point(), new PIXI.Point(), new PIXI.Point()]; - var a = [0, 0, 0, 0]; - var Surface = (function () { - function Surface() { - this.surfaceID = "default"; - this._updateID = 0; - this.vertexSrc = ""; - this.fragmentSrc = ""; - } - Surface.prototype.fillUniforms = function (uniforms) { - }; - Surface.prototype.clear = function () { - }; - Surface.prototype.boundsQuad = function (v, out, after) { - var minX = out[0], minY = out[1]; - var maxX = out[0], maxY = out[1]; - for (var i = 2; i < 8; i += 2) { - if (minX > out[i]) - minX = out[i]; - if (maxX < out[i]) - maxX = out[i]; - if (minY > out[i + 1]) - minY = out[i + 1]; - if (maxY < out[i + 1]) - maxY = out[i + 1]; - } - p[0].set(minX, minY); - this.apply(p[0], p[0]); - p[1].set(maxX, minY); - this.apply(p[1], p[1]); - p[2].set(maxX, maxY); - this.apply(p[2], p[2]); - p[3].set(minX, maxY); - this.apply(p[3], p[3]); - if (after) { - after.apply(p[0], p[0]); - after.apply(p[1], p[1]); - after.apply(p[2], p[2]); - after.apply(p[3], p[3]); - out[0] = p[0].x; - out[1] = p[0].y; - out[2] = p[1].x; - out[3] = p[1].y; - out[4] = p[2].x; - out[5] = p[2].y; - out[6] = p[3].x; - out[7] = p[3].y; } else { - for (var i = 1; i <= 3; i++) { - if (p[i].y < p[0].y || p[i].y == p[0].y && p[i].x < p[0].x) { - var t = p[0]; - p[0] = p[i]; - p[i] = t; - } + var child = children[0]; + // if the child has a parent then lets remove it as PixiJS objects can only exist in one place + if (child.parent) { + child.parent.removeChild(child); } - for (var i = 1; i <= 3; i++) { - a[i] = Math.atan2(p[i].y - p[0].y, p[i].x - p[0].x); + child.parent = this; + this.sortDirty = true; + // ensure child transform will be recalculated + child.transform._parentID = -1; + // add to list if we have a list + if (this._lastChild) { + this._lastChild.nextChild = child; + child.prevChild = this._lastChild; + this._lastChild = child; } - for (var i = 1; i <= 3; i++) { - for (var j = i + 1; j <= 3; j++) { - if (a[i] > a[j]) { - var t = p[i]; - p[i] = p[j]; - p[j] = t; - var t2 = a[i]; - a[i] = a[j]; - a[j] = t2; - } - } - } - out[0] = p[0].x; - out[1] = p[0].y; - out[2] = p[1].x; - out[3] = p[1].y; - out[4] = p[2].x; - out[5] = p[2].y; - out[6] = p[3].x; - out[7] = p[3].y; - if ((p[3].x - p[2].x) * (p[1].y - p[2].y) - (p[1].x - p[2].x) * (p[3].y - p[2].y) < 0) { - out[4] = p[3].x; - out[5] = p[3].y; - return; + // otherwise initialize the list + else { + this._firstChild = this._lastChild = child; } + // update child count + ++this._childCount; + // ensure bounds will be recalculated + this._boundsID++; + // TODO - lets either do all callbacks or all events.. not both! + this.onChildrenChange(); + this.emit('childAdded', child, this, this._childCount); + child.emit('added', this); } + return children[0]; }; - return Surface; - }()); - pixi_projection.Surface = Surface; -})(pixi_projection || (pixi_projection = {})); -var pixi_projection; -(function (pixi_projection) { - var tempMat = new PIXI.Matrix(); - var tempRect = new PIXI.Rectangle(); - var tempPoint = new PIXI.Point(); - var BilinearSurface = (function (_super) { - __extends(BilinearSurface, _super); - function BilinearSurface() { - var _this = _super.call(this) || this; - _this.distortion = new PIXI.Point(); - return _this; - } - BilinearSurface.prototype.clear = function () { - this.distortion.set(0, 0); - }; - BilinearSurface.prototype.apply = function (pos, newPos) { - newPos = newPos || new PIXI.Point(); - var d = this.distortion; - var m = pos.x * pos.y; - newPos.x = pos.x + d.x * m; - newPos.y = pos.y + d.y * m; - return newPos; - }; - BilinearSurface.prototype.applyInverse = function (pos, newPos) { - newPos = newPos || new PIXI.Point(); - var vx = pos.x, vy = pos.y; - var dx = this.distortion.x, dy = this.distortion.y; - if (dx == 0.0) { - newPos.x = vx; - newPos.y = vy / (1.0 + dy * vx); + LinkedListContainer.prototype.addChildAt = function (child, index) { + if (index < 0 || index > this._childCount) { + throw new Error("addChildAt: The index " + index + " supplied is out of bounds " + this._childCount); } - else if (dy == 0.0) { - newPos.y = vy; - newPos.x = vx / (1.0 + dx * vy); + if (child.parent) { + child.parent.removeChild(child); + } + child.parent = this; + this.sortDirty = true; + // ensure child transform will be recalculated + child.transform._parentID = -1; + var c = child; + // if no children, do basic initialization + if (!this._firstChild) { + this._firstChild = this._lastChild = c; + } + // add at beginning (back) + else if (index === 0) { + this._firstChild.prevChild = c; + c.nextChild = this._firstChild; + this._firstChild = c; + } + // add at end (front) + else if (index === this._childCount) { + this._lastChild.nextChild = c; + c.prevChild = this._lastChild; + this._lastChild = c; + } + // otherwise we have to start counting through the children to find the right one + // - SLOW, only provided to fully support the possibility of use + else { + var i = 0; + var target = this._firstChild; + while (i < index) { + target = target.nextChild; + ++i; + } + // insert before the target that we found at the specified index + target.prevChild.nextChild = c; + c.prevChild = target.prevChild; + c.nextChild = target; + target.prevChild = c; + } + // update child count + ++this._childCount; + // ensure bounds will be recalculated + this._boundsID++; + // TODO - lets either do all callbacks or all events.. not both! + this.onChildrenChange(index); // the PixiJS types say this has no arguments + child.emit('added', this); + this.emit('childAdded', child, this, index); + return child; + }; + /** + * Adds a child to the container to be rendered below another child. + * + * @param child The child to add + * @param relative - The current child to add the new child relative to. + * @return The child that was added. + */ + LinkedListContainer.prototype.addChildBelow = function (child, relative) { + if (relative.parent !== this) { + throw new Error("addChildBelow: The relative target must be a child of this parent"); + } + if (child.parent) { + child.parent.removeChild(child); + } + child.parent = this; + this.sortDirty = true; + // ensure child transform will be recalculated + child.transform._parentID = -1; + // insert before the target that we were given + relative.prevChild.nextChild = child; + child.prevChild = relative.prevChild; + child.nextChild = relative; + relative.prevChild = child; + if (this._firstChild === relative) { + this._firstChild = child; + } + // update child count + ++this._childCount; + // ensure bounds will be recalculated + this._boundsID++; + // TODO - lets either do all callbacks or all events.. not both! + this.onChildrenChange(); + this.emit('childAdded', child, this, this._childCount); + child.emit('added', this); + return child; + }; + /** + * Adds a child to the container to be rendered above another child. + * + * @param child The child to add + * @param relative - The current child to add the new child relative to. + * @return The child that was added. + */ + LinkedListContainer.prototype.addChildAbove = function (child, relative) { + if (relative.parent !== this) { + throw new Error("addChildBelow: The relative target must be a child of this parent"); + } + if (child.parent) { + child.parent.removeChild(child); + } + child.parent = this; + this.sortDirty = true; + // ensure child transform will be recalculated + child.transform._parentID = -1; + // insert after the target that we were given + relative.nextChild.prevChild = child; + child.nextChild = relative.nextChild; + child.prevChild = relative; + relative.nextChild = child; + if (this._lastChild === relative) { + this._lastChild = child; + } + // update child count + ++this._childCount; + // ensure bounds will be recalculated + this._boundsID++; + // TODO - lets either do all callbacks or all events.. not both! + this.onChildrenChange(); + this.emit('childAdded', child, this, this._childCount); + child.emit('added', this); + return child; + }; + LinkedListContainer.prototype.swapChildren = function (child, child2) { + if (child === child2 || child.parent !== this || child2.parent !== this) { + return; + } + var _a = child, prevChild = _a.prevChild, nextChild = _a.nextChild; + child.prevChild = child2.prevChild; + child.nextChild = child2.nextChild; + child2.prevChild = prevChild; + child2.nextChild = nextChild; + if (this._firstChild === child) { + this._firstChild = child2; + } + else if (this._firstChild === child2) { + this._firstChild = child; + } + if (this._lastChild === child) { + this._lastChild = child2; + } + else if (this._lastChild === child2) { + this._lastChild = child; + } + this.onChildrenChange(); + }; + LinkedListContainer.prototype.getChildIndex = function (child) { + var index = 0; + var test = this._firstChild; + while (test) { + if (test === child) { + break; + } + test = test.nextChild; + ++index; + } + if (!test) { + throw new Error('The supplied DisplayObject must be a child of the caller'); + } + return index; + }; + LinkedListContainer.prototype.setChildIndex = function (child, index) { + if (index < 0 || index >= this._childCount) { + throw new Error("The index " + index + " supplied is out of bounds " + this._childCount); + } + if (child.parent !== this) { + throw new Error('The supplied DisplayObject must be a child of the caller'); + } + // remove child + if (child.nextChild) { + child.nextChild.prevChild = child.prevChild; + } + if (child.prevChild) { + child.prevChild.nextChild = child.nextChild; + } + if (this._firstChild === child) { + this._firstChild = child.nextChild; + } + if (this._lastChild === child) { + this._lastChild = child.prevChild; + } + child.nextChild = null; + child.prevChild = null; + // do addChildAt + if (!this._firstChild) { + this._firstChild = this._lastChild = child; + } + else if (index === 0) { + this._firstChild.prevChild = child; + child.nextChild = this._firstChild; + this._firstChild = child; + } + else if (index === this._childCount) { + this._lastChild.nextChild = child; + child.prevChild = this._lastChild; + this._lastChild = child; } else { - var b = (vy * dx - vx * dy + 1.0) * 0.5 / dy; - var d = b * b + vx / dy; - if (d <= 0.00001) { - newPos.set(NaN, NaN); - return; + var i = 0; + var target = this._firstChild; + while (i < index) { + target = target.nextChild; + ++i; } - if (dy > 0.0) { - newPos.x = -b + Math.sqrt(d); + target.prevChild.nextChild = child; + child.prevChild = target.prevChild; + child.nextChild = target; + target.prevChild = child; + } + this.onChildrenChange(index); + }; + LinkedListContainer.prototype.removeChild = function () { + var children = []; + for (var _i = 0; _i < arguments.length; _i++) { + children[_i] = arguments[_i]; + } + // if there is only one argument we can bypass looping through the them + if (children.length > 1) { + // loop through the arguments property and remove all children + for (var i = 0; i < children.length; i++) { + this.removeChild(children[i]); + } + } + else { + var child = children[0]; + // bail if not actually our child + if (child.parent !== this) + return null; + child.parent = null; + // ensure child transform will be recalculated + child.transform._parentID = -1; + // swap out child references + if (child.nextChild) { + child.nextChild.prevChild = child.prevChild; + } + if (child.prevChild) { + child.prevChild.nextChild = child.nextChild; + } + if (this._firstChild === child) { + this._firstChild = child.nextChild; + } + if (this._lastChild === child) { + this._lastChild = child.prevChild; + } + // clear sibling references + child.nextChild = null; + child.prevChild = null; + // update child count + --this._childCount; + // ensure bounds will be recalculated + this._boundsID++; + // TODO - lets either do all callbacks or all events.. not both! + this.onChildrenChange(); + child.emit('removed', this); + this.emit('childRemoved', child, this); + } + return children[0]; + }; + LinkedListContainer.prototype.getChildAt = function (index) { + if (index < 0 || index >= this._childCount) { + throw new Error("getChildAt: Index (" + index + ") does not exist."); + } + if (index === 0) { + return this._firstChild; + } + // add at end (front) + else if (index === this._childCount) { + return this._lastChild; + } + // otherwise we have to start counting through the children to find the right one + // - SLOW, only provided to fully support the possibility of use + var i = 0; + var target = this._firstChild; + while (i < index) { + target = target.nextChild; + ++i; + } + return target; + }; + LinkedListContainer.prototype.removeChildAt = function (index) { + var child = this.getChildAt(index); + // ensure child transform will be recalculated.. + child.parent = null; + child.transform._parentID = -1; + // swap out child references + if (child.nextChild) { + child.nextChild.prevChild = child.prevChild; + } + if (child.prevChild) { + child.prevChild.nextChild = child.nextChild; + } + if (this._firstChild === child) { + this._firstChild = child.nextChild; + } + if (this._lastChild === child) { + this._lastChild = child.prevChild; + } + // clear sibling references + child.nextChild = null; + child.prevChild = null; + // update child count + --this._childCount; + // ensure bounds will be recalculated + this._boundsID++; + // TODO - lets either do all callbacks or all events.. not both! + this.onChildrenChange(index); // the PixiJS types say this has no arguments + child.emit('removed', this); + this.emit('childRemoved', child, this, index); + return child; + }; + LinkedListContainer.prototype.removeChildren = function (beginIndex, endIndex) { + if (beginIndex === void 0) { beginIndex = 0; } + if (endIndex === void 0) { endIndex = this._childCount; } + var begin = beginIndex; + var end = endIndex; + var range = end - begin; + if (range > 0 && range <= end) { + var removed = []; + var child = this._firstChild; + for (var i = 0; i <= end && child; ++i, child = child.nextChild) { + if (i >= begin) { + removed.push(child); + } + } + // child before removed section + var prevChild = removed[0].prevChild; + // child after removed section + var nextChild = removed[removed.length - 1].nextChild; + if (!nextChild) { + // if we removed the last child, then the new last child is the one before + // the removed section + this._lastChild = prevChild; } else { - newPos.x = -b - Math.sqrt(d); + // otherwise, stitch the child before the section to the child after + nextChild.prevChild = prevChild; } - newPos.y = (vx / newPos.x - 1.0) / dx; - } - return newPos; - }; - BilinearSurface.prototype.mapSprite = function (sprite, quad, outTransform) { - var tex = sprite.texture; - tempRect.x = -sprite.anchor.x * tex.orig.width; - tempRect.y = -sprite.anchor.y * tex.orig.height; - tempRect.width = tex.orig.width; - tempRect.height = tex.orig.height; - return this.mapQuad(tempRect, quad, outTransform || sprite.transform); - }; - BilinearSurface.prototype.mapQuad = function (rect, quad, outTransform) { - var ax = -rect.x / rect.width; - var ay = -rect.y / rect.height; - var ax2 = (1.0 - rect.x) / rect.width; - var ay2 = (1.0 - rect.y) / rect.height; - var up1x = (quad[0].x * (1.0 - ax) + quad[1].x * ax); - var up1y = (quad[0].y * (1.0 - ax) + quad[1].y * ax); - var up2x = (quad[0].x * (1.0 - ax2) + quad[1].x * ax2); - var up2y = (quad[0].y * (1.0 - ax2) + quad[1].y * ax2); - var down1x = (quad[3].x * (1.0 - ax) + quad[2].x * ax); - var down1y = (quad[3].y * (1.0 - ax) + quad[2].y * ax); - var down2x = (quad[3].x * (1.0 - ax2) + quad[2].x * ax2); - var down2y = (quad[3].y * (1.0 - ax2) + quad[2].y * ax2); - var x00 = up1x * (1.0 - ay) + down1x * ay; - var y00 = up1y * (1.0 - ay) + down1y * ay; - var x10 = up2x * (1.0 - ay) + down2x * ay; - var y10 = up2y * (1.0 - ay) + down2y * ay; - var x01 = up1x * (1.0 - ay2) + down1x * ay2; - var y01 = up1y * (1.0 - ay2) + down1y * ay2; - var x11 = up2x * (1.0 - ay2) + down2x * ay2; - var y11 = up2y * (1.0 - ay2) + down2y * ay2; - var mat = tempMat; - mat.tx = x00; - mat.ty = y00; - mat.a = x10 - x00; - mat.b = y10 - y00; - mat.c = x01 - x00; - mat.d = y01 - y00; - tempPoint.set(x11, y11); - mat.applyInverse(tempPoint, tempPoint); - this.distortion.set(tempPoint.x - 1, tempPoint.y - 1); - outTransform.setFromMatrix(mat); - return this; - }; - BilinearSurface.prototype.fillUniforms = function (uniforms) { - uniforms.distortion = uniforms.distortion || new Float32Array([0, 0, 0, 0]); - var ax = Math.abs(this.distortion.x); - var ay = Math.abs(this.distortion.y); - uniforms.distortion[0] = ax * 10000 <= ay ? 0 : this.distortion.x; - uniforms.distortion[1] = ay * 10000 <= ax ? 0 : this.distortion.y; - uniforms.distortion[2] = 1.0 / uniforms.distortion[0]; - uniforms.distortion[3] = 1.0 / uniforms.distortion[1]; - }; - return BilinearSurface; - }(pixi_projection.Surface)); - pixi_projection.BilinearSurface = BilinearSurface; -})(pixi_projection || (pixi_projection = {})); -var pixi_projection; -(function (pixi_projection) { - var Container2s = (function (_super) { - __extends(Container2s, _super); - function Container2s() { - var _this = _super.call(this) || this; - _this.proj = new pixi_projection.ProjectionSurface(_this.transform); - return _this; - } - Object.defineProperty(Container2s.prototype, "worldTransform", { - get: function () { - return this.proj; - }, - enumerable: true, - configurable: true - }); - return Container2s; - }(PIXI.Container)); - pixi_projection.Container2s = Container2s; -})(pixi_projection || (pixi_projection = {})); -var pixi_projection; -(function (pixi_projection) { - var fun = PIXI.Transform.prototype.updateTransform; - function transformHack(parentTransform) { - var proj = this.proj; - var pp = parentTransform.proj; - var ta = this; - if (!pp) { - fun.call(this, parentTransform); - proj._activeProjection = null; - return; - } - if (pp._surface) { - proj._activeProjection = pp; - this.updateLocalTransform(); - this.localTransform.copyFrom(this.worldTransform); - if (ta._parentID < 0) { - ++ta._worldID; - } - return; - } - fun.call(this, parentTransform); - proj._activeProjection = pp._activeProjection; - } - var ProjectionSurface = (function (_super) { - __extends(ProjectionSurface, _super); - function ProjectionSurface(legacy, enable) { - var _this = _super.call(this, legacy, enable) || this; - _this._surface = null; - _this._activeProjection = null; - _this._currentSurfaceID = -1; - _this._currentLegacyID = -1; - _this._lastUniforms = null; - return _this; - } - Object.defineProperty(ProjectionSurface.prototype, "enabled", { - set: function (value) { - if (value === this._enabled) { - return; - } - this._enabled = value; - if (value) { - this.legacy.updateTransform = transformHack; - this.legacy._parentID = -1; + if (!prevChild) { + // if we removed the first child, then the new first child is the one after + // the removed section + this._firstChild = nextChild; } else { - this.legacy.updateTransform = PIXI.Transform.prototype.updateTransform; - this.legacy._parentID = -1; + // otherwise stich the child after the section to the one before + prevChild.nextChild = nextChild; } - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(ProjectionSurface.prototype, "surface", { - get: function () { - return this._surface; - }, - set: function (value) { - if (this._surface == value) { - return; - } - this._surface = value || null; - this.legacy._parentID = -1; - }, - enumerable: true, - configurable: true - }); - ProjectionSurface.prototype.applyPartial = function (pos, newPos) { - if (this._activeProjection !== null) { - newPos = this.legacy.worldTransform.apply(pos, newPos); - return this._activeProjection.surface.apply(newPos, newPos); - } - if (this._surface !== null) { - return this.surface.apply(pos, newPos); - } - return this.legacy.worldTransform.apply(pos, newPos); - }; - ProjectionSurface.prototype.apply = function (pos, newPos) { - if (this._activeProjection !== null) { - newPos = this.legacy.worldTransform.apply(pos, newPos); - this._activeProjection.surface.apply(newPos, newPos); - return this._activeProjection.legacy.worldTransform.apply(newPos, newPos); - } - if (this._surface !== null) { - newPos = this.surface.apply(pos, newPos); - return this.legacy.worldTransform.apply(newPos, newPos); - } - return this.legacy.worldTransform.apply(pos, newPos); - }; - ProjectionSurface.prototype.applyInverse = function (pos, newPos) { - if (this._activeProjection !== null) { - newPos = this._activeProjection.legacy.worldTransform.applyInverse(pos, newPos); - this._activeProjection._surface.applyInverse(newPos, newPos); - return this.legacy.worldTransform.applyInverse(newPos, newPos); - } - if (this._surface !== null) { - newPos = this.legacy.worldTransform.applyInverse(pos, newPos); - return this._surface.applyInverse(newPos, newPos); - } - return this.legacy.worldTransform.applyInverse(pos, newPos); - }; - ProjectionSurface.prototype.mapBilinearSprite = function (sprite, quad) { - if (!(this._surface instanceof pixi_projection.BilinearSurface)) { - this.surface = new pixi_projection.BilinearSurface(); - } - this.surface.mapSprite(sprite, quad, this.legacy); - }; - ProjectionSurface.prototype.clear = function () { - if (this.surface) { - this.surface.clear(); - } - }; - Object.defineProperty(ProjectionSurface.prototype, "uniforms", { - get: function () { - if (this._currentLegacyID === this.legacy._worldID && - this._currentSurfaceID === this.surface._updateID) { - return this._lastUniforms; - } - this._lastUniforms = this._lastUniforms || {}; - this._lastUniforms.translationMatrix = this.legacy.worldTransform; - this._surface.fillUniforms(this._lastUniforms); - return this._lastUniforms; - }, - enumerable: true, - configurable: true - }); - return ProjectionSurface; - }(pixi_projection.AbstractProjection)); - pixi_projection.ProjectionSurface = ProjectionSurface; -})(pixi_projection || (pixi_projection = {})); -var pixi_projection; -(function (pixi_projection) { - var TYPES = PIXI.TYPES; - var premultiplyTint = PIXI.utils.premultiplyTint; - var shaderVert = "precision highp float;\nattribute vec2 aVertexPosition;\nattribute vec3 aTrans1;\nattribute vec3 aTrans2;\nattribute vec2 aSamplerSize;\nattribute vec4 aFrame;\nattribute vec4 aColor;\nattribute float aTextureId;\n\nuniform mat3 projectionMatrix;\nuniform mat3 translationMatrix;\n\nvarying vec2 vertexPosition;\nvarying vec3 vTrans1;\nvarying vec3 vTrans2;\nvarying vec2 vSamplerSize;\nvarying vec4 vFrame;\nvarying vec4 vColor;\nvarying float vTextureId;\n\nvoid main(void){\n gl_Position.xyw = projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0);\n gl_Position.z = 0.0;\n \n vertexPosition = aVertexPosition;\n vTrans1 = aTrans1;\n vTrans2 = aTrans2;\n vTextureId = aTextureId;\n vColor = aColor;\n vSamplerSize = aSamplerSize;\n vFrame = aFrame;\n}\n"; - var shaderFrag = "precision highp float;\nvarying vec2 vertexPosition;\nvarying vec3 vTrans1;\nvarying vec3 vTrans2;\nvarying vec2 vSamplerSize;\nvarying vec4 vFrame;\nvarying vec4 vColor;\nvarying float vTextureId;\n\nuniform sampler2D uSamplers[%count%];\nuniform vec4 distortion;\n\nvoid main(void){\nvec2 surface;\nvec2 surface2;\n\nfloat vx = vertexPosition.x;\nfloat vy = vertexPosition.y;\nfloat dx = distortion.x;\nfloat dy = distortion.y;\nfloat revx = distortion.z;\nfloat revy = distortion.w;\n\nif (distortion.x == 0.0) {\n surface.x = vx;\n surface.y = vy / (1.0 + dy * vx);\n surface2 = surface;\n} else\nif (distortion.y == 0.0) {\n surface.y = vy;\n surface.x = vx / (1.0 + dx * vy);\n surface2 = surface;\n} else {\n float c = vy * dx - vx * dy;\n float b = (c + 1.0) * 0.5;\n float b2 = (-c + 1.0) * 0.5;\n float d = b * b + vx * dy;\n //if (d < -0.00001) {\n // discard;\n //}\n d = sqrt(max(d, 0.0));\n surface.x = (- b + d) * revy;\n surface2.x = (- b - d) * revy;\n surface.y = (- b2 + d) * revx;\n surface2.y = (- b2 - d) * revx;\n}\n\nvec2 uv;\nuv.x = vTrans1.x * surface.x + vTrans1.y * surface.y + vTrans1.z;\nuv.y = vTrans2.x * surface.x + vTrans2.y * surface.y + vTrans2.z;\n\nvec2 pixels = uv * vSamplerSize;\n\nif (pixels.x < vFrame.x || pixels.x > vFrame.z ||\n pixels.y < vFrame.y || pixels.y > vFrame.w) {\n uv.x = vTrans1.x * surface2.x + vTrans1.y * surface2.y + vTrans1.z;\n uv.y = vTrans2.x * surface2.x + vTrans2.y * surface2.y + vTrans2.z;\n pixels = uv * vSamplerSize;\n \n// if (pixels.x < vFrame.x || pixels.x > vFrame.z ||\n// pixels.y < vFrame.y || pixels.y > vFrame.w) {\n// discard;\n// }\n}\n\nvec4 edge;\nedge.xy = clamp(pixels - vFrame.xy + 0.5, vec2(0.0, 0.0), vec2(1.0, 1.0));\nedge.zw = clamp(vFrame.zw - pixels + 0.5, vec2(0.0, 0.0), vec2(1.0, 1.0));\n\nfloat alpha = 1.0; //edge.x * edge.y * edge.z * edge.w;\nvec4 rColor = vColor * alpha;\n\nfloat textureId = floor(vTextureId+0.5);\nvec2 vTextureCoord = uv;\nvec4 color;\n%forloop%\ngl_FragColor = vec4(0.0, 1.0, 0.0, 1.0);\n//gl_FragColor = color * rColor;\n}"; - var BatchBilineardGeometry = (function (_super) { - __extends(BatchBilineardGeometry, _super); - function BatchBilineardGeometry(_static) { - if (_static === void 0) { _static = false; } - var _this = _super.call(this) || this; - _this._buffer = new PIXI.Buffer(null, _static, false); - _this._indexBuffer = new PIXI.Buffer(null, _static, true); - _this.addAttribute('aVertexPosition', _this._buffer, 2, false, TYPES.FLOAT) - .addAttribute('aTrans1', _this._buffer, 3, false, TYPES.FLOAT) - .addAttribute('aTrans2', _this._buffer, 3, false, TYPES.FLOAT) - .addAttribute('aSamplerSize', _this._buffer, 2, false, TYPES.FLOAT) - .addAttribute('aFrame', _this._buffer, 4, false, TYPES.FLOAT) - .addAttribute('aColor', _this._buffer, 4, true, TYPES.UNSIGNED_BYTE) - .addAttribute('aTextureId', _this._buffer, 1, true, TYPES.FLOAT) - .addIndex(_this._indexBuffer); - return _this; - } - return BatchBilineardGeometry; - }(PIXI.Geometry)); - pixi_projection.BatchBilineardGeometry = BatchBilineardGeometry; - var BatchBilinearPluginFactory = (function () { - function BatchBilinearPluginFactory() { - } - BatchBilinearPluginFactory.create = function (options) { - var _a = Object.assign({ - vertex: shaderVert, - fragment: shaderFrag, - geometryClass: BatchBilineardGeometry, - vertexSize: 16, - }, options), vertex = _a.vertex, fragment = _a.fragment, vertexSize = _a.vertexSize, geometryClass = _a.geometryClass; - return (function (_super) { - __extends(BatchPlugin, _super); - function BatchPlugin(renderer) { - var _this = _super.call(this, renderer) || this; - _this.defUniforms = { - translationMatrix: new PIXI.Matrix(), - distortion: new Float32Array([0, 0]) - }; - _this.size = 1000; - _this.forceMaxTextures = 1; - _this.shaderGenerator = new PIXI.BatchShaderGenerator(vertex, fragment); - _this.geometryClass = geometryClass; - _this.vertexSize = vertexSize; - return _this; - } - BatchPlugin.prototype.getUniforms = function (sprite) { - var proj = sprite.proj; - if (proj.surface !== null) { - return proj.uniforms; + for (var i = 0; i < removed.length; ++i) { + // clear parenting and sibling references for all removed children + removed[i].parent = null; + if (removed[i].transform) { + removed[i].transform._parentID = -1; } - if (proj._activeProjection !== null) { - return proj._activeProjection.uniforms; - } - return this.defUniforms; - }; - BatchPlugin.prototype.packInterleavedGeometry = function (element, attributeBuffer, indexBuffer, aIndex, iIndex) { - var uint32View = attributeBuffer.uint32View, float32View = attributeBuffer.float32View; - var p = aIndex / this.vertexSize; - var indices = element.indices; - var vertexData = element.vertexData; - var tex = element._texture; - var frame = tex._frame; - var aTrans = element.aTrans; - var _a = element._texture.baseTexture, _batchLocation = _a._batchLocation, realWidth = _a.realWidth, realHeight = _a.realHeight, resolution = _a.resolution; - var alpha = Math.min(element.worldAlpha, 1.0); - var argb = alpha < 1.0 && element._texture.baseTexture.alphaMode ? premultiplyTint(element._tintRGB, alpha) - : element._tintRGB + (alpha * 255 << 24); - for (var i = 0; i < vertexData.length; i += 2) { - float32View[aIndex] = vertexData[i * 2]; - float32View[aIndex + 1] = vertexData[i * 2 + 1]; - float32View[aIndex + 2] = aTrans.a; - float32View[aIndex + 3] = aTrans.c; - float32View[aIndex + 4] = aTrans.tx; - float32View[aIndex + 5] = aTrans.b; - float32View[aIndex + 6] = aTrans.d; - float32View[aIndex + 7] = aTrans.ty; - float32View[aIndex + 8] = realWidth; - float32View[aIndex + 9] = realHeight; - float32View[aIndex + 10] = frame.x * resolution; - float32View[aIndex + 11] = frame.y * resolution; - float32View[aIndex + 12] = (frame.x + frame.width) * resolution; - float32View[aIndex + 13] = (frame.y + frame.height) * resolution; - uint32View[aIndex + 14] = argb; - float32View[aIndex + 15] = _batchLocation; - aIndex += 16; - } - for (var i = 0; i < indices.length; i++) { - indexBuffer[iIndex++] = p + indices[i]; - } - }; - return BatchPlugin; - }(pixi_projection.UniformBatchRenderer)); - }; - return BatchBilinearPluginFactory; - }()); - pixi_projection.BatchBilinearPluginFactory = BatchBilinearPluginFactory; - PIXI.Renderer.registerPlugin('batch_bilinear', BatchBilinearPluginFactory.create({})); -})(pixi_projection || (pixi_projection = {})); -var pixi_projection; -(function (pixi_projection) { - var Sprite2s = (function (_super) { - __extends(Sprite2s, _super); - function Sprite2s(texture) { - var _this = _super.call(this, texture) || this; - _this.aTrans = new PIXI.Matrix(); - _this.proj = new pixi_projection.ProjectionSurface(_this.transform); - _this.pluginName = 'batch_bilinear'; - return _this; - } - Sprite2s.prototype._calculateBounds = function () { - this.calculateTrimmedVertices(); - this._bounds.addQuad(this.vertexTrimmedData); - }; - Sprite2s.prototype.calculateVertices = function () { - var wid = this.transform._worldID; - var tuid = this._texture._updateID; - if (this._transformID === wid && this._textureID === tuid) { - return; - } - this._transformID = wid; - this._textureID = tuid; - var texture = this._texture; - var vertexData = this.vertexData; - var trim = texture.trim; - var orig = texture.orig; - var anchor = this._anchor; - var w0 = 0; - var w1 = 0; - var h0 = 0; - var h1 = 0; - if (trim) { - w1 = trim.x - (anchor._x * orig.width); - w0 = w1 + trim.width; - h1 = trim.y - (anchor._y * orig.height); - h0 = h1 + trim.height; - } - else { - w1 = -anchor._x * orig.width; - w0 = w1 + orig.width; - h1 = -anchor._y * orig.height; - h0 = h1 + orig.height; - } - if (this.proj._surface) { - vertexData[0] = w1; - vertexData[1] = h1; - vertexData[2] = w0; - vertexData[3] = h1; - vertexData[4] = w0; - vertexData[5] = h0; - vertexData[6] = w1; - vertexData[7] = h0; - this.proj._surface.boundsQuad(vertexData, vertexData); - } - else { - var wt = this.transform.worldTransform; - var a = wt.a; - var b = wt.b; - var c = wt.c; - var d = wt.d; - var tx = wt.tx; - var ty = wt.ty; - vertexData[0] = (a * w1) + (c * h1) + tx; - vertexData[1] = (d * h1) + (b * w1) + ty; - vertexData[2] = (a * w0) + (c * h1) + tx; - vertexData[3] = (d * h1) + (b * w0) + ty; - vertexData[4] = (a * w0) + (c * h0) + tx; - vertexData[5] = (d * h0) + (b * w0) + ty; - vertexData[6] = (a * w1) + (c * h0) + tx; - vertexData[7] = (d * h0) + (b * w1) + ty; - if (this.proj._activeProjection) { - this.proj._activeProjection.surface.boundsQuad(vertexData, vertexData); + removed[i].nextChild = null; + removed[i].prevChild = null; } + this._boundsID++; + this.onChildrenChange(beginIndex); + for (var i = 0; i < removed.length; ++i) { + removed[i].emit('removed', this); + this.emit('childRemoved', removed[i], this, i); + } + return removed; } - if (!texture.uvMatrix) { - texture.uvMatrix = new PIXI.TextureMatrix(texture); + else if (range === 0 && this._childCount === 0) { + return []; } - texture.uvMatrix.update(); - var aTrans = this.aTrans; - aTrans.set(orig.width, 0, 0, orig.height, w1, h1); - if (this.proj._surface === null) { - aTrans.prepend(this.transform.worldTransform); - } - aTrans.invert(); - aTrans.prepend(texture.uvMatrix.mapCoord); + throw new RangeError('removeChildren: numeric values are outside the acceptable range.'); }; - Sprite2s.prototype.calculateTrimmedVertices = function () { - var wid = this.transform._worldID; - var tuid = this._texture._updateID; - if (!this.vertexTrimmedData) { - this.vertexTrimmedData = new Float32Array(8); - } - else if (this._transformTrimmedID === wid && this._textureTrimmedID === tuid) { - return; - } - this._transformTrimmedID = wid; - this._textureTrimmedID = tuid; - var texture = this._texture; - var vertexData = this.vertexTrimmedData; - var orig = texture.orig; - var anchor = this._anchor; - var w1 = -anchor._x * orig.width; - var w0 = w1 + orig.width; - var h1 = -anchor._y * orig.height; - var h0 = h1 + orig.height; - if (this.proj._surface) { - vertexData[0] = w1; - vertexData[1] = h1; - vertexData[2] = w0; - vertexData[3] = h1; - vertexData[4] = w0; - vertexData[5] = h0; - vertexData[6] = w1; - vertexData[7] = h0; - this.proj._surface.boundsQuad(vertexData, vertexData, this.transform.worldTransform); - } - else { - var wt = this.transform.worldTransform; - var a = wt.a; - var b = wt.b; - var c = wt.c; - var d = wt.d; - var tx = wt.tx; - var ty = wt.ty; - vertexData[0] = (a * w1) + (c * h1) + tx; - vertexData[1] = (d * h1) + (b * w1) + ty; - vertexData[2] = (a * w0) + (c * h1) + tx; - vertexData[3] = (d * h1) + (b * w0) + ty; - vertexData[4] = (a * w0) + (c * h0) + tx; - vertexData[5] = (d * h0) + (b * w0) + ty; - vertexData[6] = (a * w1) + (c * h0) + tx; - vertexData[7] = (d * h0) + (b * w1) + ty; - if (this.proj._activeProjection) { - this.proj._activeProjection.surface.boundsQuad(vertexData, vertexData, this.proj._activeProjection.legacy.worldTransform); + /** + * Updates the transform on all children of this container for rendering. + * Copied from and overrides PixiJS v5 method (v4 method is identical) + */ + LinkedListContainer.prototype.updateTransform = function () { + this._boundsID++; + this.transform.updateTransform(this.parent.transform); + // TODO: check render flags, how to process stuff here + this.worldAlpha = this.alpha * this.parent.worldAlpha; + var child; + var next; + for (child = this._firstChild; child; child = next) { + next = child.nextChild; + if (child.visible) { + child.updateTransform(); } } }; - Object.defineProperty(Sprite2s.prototype, "worldTransform", { - get: function () { - return this.proj; - }, - enumerable: true, - configurable: true - }); - return Sprite2s; - }(PIXI.Sprite)); - pixi_projection.Sprite2s = Sprite2s; -})(pixi_projection || (pixi_projection = {})); -var pixi_projection; -(function (pixi_projection) { - var Text2s = (function (_super) { - __extends(Text2s, _super); - function Text2s(text, style, canvas) { - var _this = _super.call(this, text, style, canvas) || this; - _this.aTrans = new PIXI.Matrix(); - _this.proj = new pixi_projection.ProjectionSurface(_this.transform); - _this.pluginName = 'batch_bilinear'; - return _this; - } - Object.defineProperty(Text2s.prototype, "worldTransform", { - get: function () { - return this.proj; - }, - enumerable: true, - configurable: true - }); - return Text2s; - }(PIXI.Text)); - pixi_projection.Text2s = Text2s; - Text2s.prototype.calculateVertices = pixi_projection.Sprite2s.prototype.calculateVertices; - Text2s.prototype.calculateTrimmedVertices = pixi_projection.Sprite2s.prototype.calculateTrimmedVertices; - Text2s.prototype._calculateBounds = pixi_projection.Sprite2s.prototype._calculateBounds; -})(pixi_projection || (pixi_projection = {})); -var pixi_projection; -(function (pixi_projection) { - PIXI.Sprite.prototype.convertTo2s = function () { - if (this.proj) - return; - this.pluginName = 'sprite_bilinear'; - this.aTrans = new PIXI.Matrix(); - this.calculateVertices = pixi_projection.Sprite2s.prototype.calculateVertices; - this.calculateTrimmedVertices = pixi_projection.Sprite2s.prototype.calculateTrimmedVertices; - this._calculateBounds = pixi_projection.Sprite2s.prototype._calculateBounds; - PIXI.Container.prototype.convertTo2s.call(this); - }; - PIXI.Container.prototype.convertTo2s = function () { - if (this.proj) - return; - this.proj = new pixi_projection.Projection2d(this.transform); - Object.defineProperty(this, "worldTransform", { - get: function () { - return this.proj; - }, - enumerable: true, - configurable: true - }); - }; - PIXI.Container.prototype.convertSubtreeTo2s = function () { - this.convertTo2s(); - for (var i = 0; i < this.children.length; i++) { - this.children[i].convertSubtreeTo2s(); - } - }; -})(pixi_projection || (pixi_projection = {})); -var pixi_projection; -(function (pixi_projection) { - function container2dWorldTransform() { - return this.proj.affine ? this.transform.worldTransform : this.proj.world; - } - pixi_projection.container2dWorldTransform = container2dWorldTransform; - var Container2d = (function (_super) { - __extends(Container2d, _super); - function Container2d() { - var _this = _super.call(this) || this; - _this.proj = new pixi_projection.Projection2d(_this.transform); - return _this; - } - Container2d.prototype.toLocal = function (position, from, point, skipUpdate, step) { - if (step === void 0) { step = pixi_projection.TRANSFORM_STEP.ALL; } - if (from) { - position = from.toGlobal(position, point, skipUpdate); - } - if (!skipUpdate) { - this._recursivePostUpdateTransform(); - } - if (step >= pixi_projection.TRANSFORM_STEP.PROJ) { - if (!skipUpdate) { - this.displayObjectUpdateTransform(); + /** + * Recalculates the bounds of the container. + * Copied from and overrides PixiJS v5 method (v4 method is identical) + */ + LinkedListContainer.prototype.calculateBounds = function () { + this._bounds.clear(); + this._calculateBounds(); + var child; + var next; + for (child = this._firstChild; child; child = next) { + next = child.nextChild; + if (!child.visible || !child.renderable) { + continue; } - if (this.proj.affine) { - return this.transform.worldTransform.applyInverse(position, point); + child.calculateBounds(); + // TODO: filter+mask, need to mask both somehow + if (child._mask) { + var maskObject = (child._mask.maskObject || child._mask); + maskObject.calculateBounds(); + this._bounds.addBoundsMask(child._bounds, maskObject._bounds); } - return this.proj.world.applyInverse(position, point); - } - if (this.parent) { - point = this.parent.worldTransform.applyInverse(position, point); - } - else { - point.copyFrom(position); - } - if (step === pixi_projection.TRANSFORM_STEP.NONE) { - return point; - } - return this.transform.localTransform.applyInverse(point, point); - }; - Object.defineProperty(Container2d.prototype, "worldTransform", { - get: function () { - return this.proj.affine ? this.transform.worldTransform : this.proj.world; - }, - enumerable: true, - configurable: true - }); - return Container2d; - }(PIXI.Container)); - pixi_projection.Container2d = Container2d; - pixi_projection.container2dToLocal = Container2d.prototype.toLocal; -})(pixi_projection || (pixi_projection = {})); -var pixi_projection; -(function (pixi_projection) { - var Point = PIXI.Point; - var mat3id = [1, 0, 0, 0, 1, 0, 0, 0, 1]; - var AFFINE; - (function (AFFINE) { - AFFINE[AFFINE["NONE"] = 0] = "NONE"; - AFFINE[AFFINE["FREE"] = 1] = "FREE"; - AFFINE[AFFINE["AXIS_X"] = 2] = "AXIS_X"; - AFFINE[AFFINE["AXIS_Y"] = 3] = "AXIS_Y"; - AFFINE[AFFINE["POINT"] = 4] = "POINT"; - AFFINE[AFFINE["AXIS_XR"] = 5] = "AXIS_XR"; - })(AFFINE = pixi_projection.AFFINE || (pixi_projection.AFFINE = {})); - var Matrix2d = (function () { - function Matrix2d(backingArray) { - this.floatArray = null; - this.mat3 = new Float64Array(backingArray || mat3id); - } - Object.defineProperty(Matrix2d.prototype, "a", { - get: function () { - return this.mat3[0] / this.mat3[8]; - }, - set: function (value) { - this.mat3[0] = value * this.mat3[8]; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Matrix2d.prototype, "b", { - get: function () { - return this.mat3[1] / this.mat3[8]; - }, - set: function (value) { - this.mat3[1] = value * this.mat3[8]; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Matrix2d.prototype, "c", { - get: function () { - return this.mat3[3] / this.mat3[8]; - }, - set: function (value) { - this.mat3[3] = value * this.mat3[8]; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Matrix2d.prototype, "d", { - get: function () { - return this.mat3[4] / this.mat3[8]; - }, - set: function (value) { - this.mat3[4] = value * this.mat3[8]; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Matrix2d.prototype, "tx", { - get: function () { - return this.mat3[6] / this.mat3[8]; - }, - set: function (value) { - this.mat3[6] = value * this.mat3[8]; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Matrix2d.prototype, "ty", { - get: function () { - return this.mat3[7] / this.mat3[8]; - }, - set: function (value) { - this.mat3[7] = value * this.mat3[8]; - }, - enumerable: true, - configurable: true - }); - Matrix2d.prototype.set = function (a, b, c, d, tx, ty) { - var mat3 = this.mat3; - mat3[0] = a; - mat3[1] = b; - mat3[2] = 0; - mat3[3] = c; - mat3[4] = d; - mat3[5] = 0; - mat3[6] = tx; - mat3[7] = ty; - mat3[8] = 1; - return this; - }; - Matrix2d.prototype.toArray = function (transpose, out) { - if (!this.floatArray) { - this.floatArray = new Float32Array(9); - } - var array = out || this.floatArray; - var mat3 = this.mat3; - if (transpose) { - array[0] = mat3[0]; - array[1] = mat3[1]; - array[2] = mat3[2]; - array[3] = mat3[3]; - array[4] = mat3[4]; - array[5] = mat3[5]; - array[6] = mat3[6]; - array[7] = mat3[7]; - array[8] = mat3[8]; - } - else { - array[0] = mat3[0]; - array[1] = mat3[3]; - array[2] = mat3[6]; - array[3] = mat3[1]; - array[4] = mat3[4]; - array[5] = mat3[7]; - array[6] = mat3[2]; - array[7] = mat3[5]; - array[8] = mat3[8]; - } - return array; - }; - Matrix2d.prototype.apply = function (pos, newPos) { - newPos = newPos || new PIXI.Point(); - var mat3 = this.mat3; - var x = pos.x; - var y = pos.y; - var z = 1.0 / (mat3[2] * x + mat3[5] * y + mat3[8]); - newPos.x = z * (mat3[0] * x + mat3[3] * y + mat3[6]); - newPos.y = z * (mat3[1] * x + mat3[4] * y + mat3[7]); - return newPos; - }; - Matrix2d.prototype.translate = function (tx, ty) { - var mat3 = this.mat3; - mat3[0] += tx * mat3[2]; - mat3[1] += ty * mat3[2]; - mat3[3] += tx * mat3[5]; - mat3[4] += ty * mat3[5]; - mat3[6] += tx * mat3[8]; - mat3[7] += ty * mat3[8]; - return this; - }; - Matrix2d.prototype.scale = function (x, y) { - var mat3 = this.mat3; - mat3[0] *= x; - mat3[1] *= y; - mat3[3] *= x; - mat3[4] *= y; - mat3[6] *= x; - mat3[7] *= y; - return this; - }; - Matrix2d.prototype.scaleAndTranslate = function (scaleX, scaleY, tx, ty) { - var mat3 = this.mat3; - mat3[0] = scaleX * mat3[0] + tx * mat3[2]; - mat3[1] = scaleY * mat3[1] + ty * mat3[2]; - mat3[3] = scaleX * mat3[3] + tx * mat3[5]; - mat3[4] = scaleY * mat3[4] + ty * mat3[5]; - mat3[6] = scaleX * mat3[6] + tx * mat3[8]; - mat3[7] = scaleY * mat3[7] + ty * mat3[8]; - }; - Matrix2d.prototype.applyInverse = function (pos, newPos) { - newPos = newPos || new Point(); - var a = this.mat3; - var x = pos.x; - var y = pos.y; - var a00 = a[0], a01 = a[3], a02 = a[6], a10 = a[1], a11 = a[4], a12 = a[7], a20 = a[2], a21 = a[5], a22 = a[8]; - var newX = (a22 * a11 - a12 * a21) * x + (-a22 * a01 + a02 * a21) * y + (a12 * a01 - a02 * a11); - var newY = (-a22 * a10 + a12 * a20) * x + (a22 * a00 - a02 * a20) * y + (-a12 * a00 + a02 * a10); - var newZ = (a21 * a10 - a11 * a20) * x + (-a21 * a00 + a01 * a20) * y + (a11 * a00 - a01 * a10); - newPos.x = newX / newZ; - newPos.y = newY / newZ; - return newPos; - }; - Matrix2d.prototype.invert = function () { - var a = this.mat3; - var a00 = a[0], a01 = a[1], a02 = a[2], a10 = a[3], a11 = a[4], a12 = a[5], a20 = a[6], a21 = a[7], a22 = a[8], b01 = a22 * a11 - a12 * a21, b11 = -a22 * a10 + a12 * a20, b21 = a21 * a10 - a11 * a20; - var det = a00 * b01 + a01 * b11 + a02 * b21; - if (!det) { - return this; - } - det = 1.0 / det; - a[0] = b01 * det; - a[1] = (-a22 * a01 + a02 * a21) * det; - a[2] = (a12 * a01 - a02 * a11) * det; - a[3] = b11 * det; - a[4] = (a22 * a00 - a02 * a20) * det; - a[5] = (-a12 * a00 + a02 * a10) * det; - a[6] = b21 * det; - a[7] = (-a21 * a00 + a01 * a20) * det; - a[8] = (a11 * a00 - a01 * a10) * det; - return this; - }; - Matrix2d.prototype.identity = function () { - var mat3 = this.mat3; - mat3[0] = 1; - mat3[1] = 0; - mat3[2] = 0; - mat3[3] = 0; - mat3[4] = 1; - mat3[5] = 0; - mat3[6] = 0; - mat3[7] = 0; - mat3[8] = 1; - return this; - }; - Matrix2d.prototype.clone = function () { - return new Matrix2d(this.mat3); - }; - Matrix2d.prototype.copyTo2dOr3d = function (matrix) { - var mat3 = this.mat3; - var ar2 = matrix.mat3; - ar2[0] = mat3[0]; - ar2[1] = mat3[1]; - ar2[2] = mat3[2]; - ar2[3] = mat3[3]; - ar2[4] = mat3[4]; - ar2[5] = mat3[5]; - ar2[6] = mat3[6]; - ar2[7] = mat3[7]; - ar2[8] = mat3[8]; - return matrix; - }; - Matrix2d.prototype.copyTo = function (matrix, affine, preserveOrientation) { - var mat3 = this.mat3; - var d = 1.0 / mat3[8]; - var tx = mat3[6] * d, ty = mat3[7] * d; - matrix.a = (mat3[0] - mat3[2] * tx) * d; - matrix.b = (mat3[1] - mat3[2] * ty) * d; - matrix.c = (mat3[3] - mat3[5] * tx) * d; - matrix.d = (mat3[4] - mat3[5] * ty) * d; - matrix.tx = tx; - matrix.ty = ty; - if (affine >= 2) { - var D = matrix.a * matrix.d - matrix.b * matrix.c; - if (!preserveOrientation) { - D = Math.abs(D); - } - if (affine === AFFINE.POINT) { - if (D > 0) { - D = 1; - } - else - D = -1; - matrix.a = D; - matrix.b = 0; - matrix.c = 0; - matrix.d = D; - } - else if (affine === AFFINE.AXIS_X) { - D /= Math.sqrt(matrix.b * matrix.b + matrix.d * matrix.d); - matrix.c = 0; - matrix.d = D; - } - else if (affine === AFFINE.AXIS_Y) { - D /= Math.sqrt(matrix.a * matrix.a + matrix.c * matrix.c); - matrix.a = D; - matrix.c = 0; - } - else if (affine === AFFINE.AXIS_XR) { - matrix.a = matrix.d * D; - matrix.c = -matrix.b * D; - } - } - return matrix; - }; - Matrix2d.prototype.copyFrom = function (matrix) { - var mat3 = this.mat3; - mat3[0] = matrix.a; - mat3[1] = matrix.b; - mat3[2] = 0; - mat3[3] = matrix.c; - mat3[4] = matrix.d; - mat3[5] = 0; - mat3[6] = matrix.tx; - mat3[7] = matrix.ty; - mat3[8] = 1.0; - return this; - }; - Matrix2d.prototype.setToMultLegacy = function (pt, lt) { - var out = this.mat3; - var b = lt.mat3; - var a00 = pt.a, a01 = pt.b, a10 = pt.c, a11 = pt.d, a20 = pt.tx, a21 = pt.ty, b00 = b[0], b01 = b[1], b02 = b[2], b10 = b[3], b11 = b[4], b12 = b[5], b20 = b[6], b21 = b[7], b22 = b[8]; - out[0] = b00 * a00 + b01 * a10 + b02 * a20; - out[1] = b00 * a01 + b01 * a11 + b02 * a21; - out[2] = b02; - out[3] = b10 * a00 + b11 * a10 + b12 * a20; - out[4] = b10 * a01 + b11 * a11 + b12 * a21; - out[5] = b12; - out[6] = b20 * a00 + b21 * a10 + b22 * a20; - out[7] = b20 * a01 + b21 * a11 + b22 * a21; - out[8] = b22; - return this; - }; - Matrix2d.prototype.setToMultLegacy2 = function (pt, lt) { - var out = this.mat3; - var a = pt.mat3; - var a00 = a[0], a01 = a[1], a02 = a[2], a10 = a[3], a11 = a[4], a12 = a[5], a20 = a[6], a21 = a[7], a22 = a[8], b00 = lt.a, b01 = lt.b, b10 = lt.c, b11 = lt.d, b20 = lt.tx, b21 = lt.ty; - out[0] = b00 * a00 + b01 * a10; - out[1] = b00 * a01 + b01 * a11; - out[2] = b00 * a02 + b01 * a12; - out[3] = b10 * a00 + b11 * a10; - out[4] = b10 * a01 + b11 * a11; - out[5] = b10 * a02 + b11 * a12; - out[6] = b20 * a00 + b21 * a10 + a20; - out[7] = b20 * a01 + b21 * a11 + a21; - out[8] = b20 * a02 + b21 * a12 + a22; - return this; - }; - Matrix2d.prototype.setToMult = function (pt, lt) { - var out = this.mat3; - var a = pt.mat3, b = lt.mat3; - var a00 = a[0], a01 = a[1], a02 = a[2], a10 = a[3], a11 = a[4], a12 = a[5], a20 = a[6], a21 = a[7], a22 = a[8], b00 = b[0], b01 = b[1], b02 = b[2], b10 = b[3], b11 = b[4], b12 = b[5], b20 = b[6], b21 = b[7], b22 = b[8]; - out[0] = b00 * a00 + b01 * a10 + b02 * a20; - out[1] = b00 * a01 + b01 * a11 + b02 * a21; - out[2] = b00 * a02 + b01 * a12 + b02 * a22; - out[3] = b10 * a00 + b11 * a10 + b12 * a20; - out[4] = b10 * a01 + b11 * a11 + b12 * a21; - out[5] = b10 * a02 + b11 * a12 + b12 * a22; - out[6] = b20 * a00 + b21 * a10 + b22 * a20; - out[7] = b20 * a01 + b21 * a11 + b22 * a21; - out[8] = b20 * a02 + b21 * a12 + b22 * a22; - return this; - }; - Matrix2d.prototype.prepend = function (lt) { - if (lt.mat3) { - return this.setToMult(lt, this); - } - else { - return this.setToMultLegacy(lt, this); - } - }; - Matrix2d.IDENTITY = new Matrix2d(); - Matrix2d.TEMP_MATRIX = new Matrix2d(); - return Matrix2d; - }()); - pixi_projection.Matrix2d = Matrix2d; -})(pixi_projection || (pixi_projection = {})); -var pixi_projection; -(function (pixi_projection) { - var t0 = new PIXI.Point(); - var tt = [new PIXI.Point(), new PIXI.Point(), new PIXI.Point(), new PIXI.Point()]; - var tempRect = new PIXI.Rectangle(); - var tempMat = new pixi_projection.Matrix2d(); - var Projection2d = (function (_super) { - __extends(Projection2d, _super); - function Projection2d(legacy, enable) { - var _this = _super.call(this, legacy, enable) || this; - _this.matrix = new pixi_projection.Matrix2d(); - _this.pivot = new PIXI.ObservablePoint(_this.onChange, _this, 0, 0); - _this.reverseLocalOrder = false; - _this.local = new pixi_projection.Matrix2d(); - _this.world = new pixi_projection.Matrix2d(); - return _this; - } - Projection2d.prototype.onChange = function () { - var pivot = this.pivot; - var mat3 = this.matrix.mat3; - mat3[6] = -(pivot._x * mat3[0] + pivot._y * mat3[3]); - mat3[7] = -(pivot._x * mat3[1] + pivot._y * mat3[4]); - this._projID++; - }; - Projection2d.prototype.setAxisX = function (p, factor) { - if (factor === void 0) { factor = 1; } - var x = p.x, y = p.y; - var d = Math.sqrt(x * x + y * y); - var mat3 = this.matrix.mat3; - mat3[0] = x / d; - mat3[1] = y / d; - mat3[2] = factor / d; - this.onChange(); - }; - Projection2d.prototype.setAxisY = function (p, factor) { - if (factor === void 0) { factor = 1; } - var x = p.x, y = p.y; - var d = Math.sqrt(x * x + y * y); - var mat3 = this.matrix.mat3; - mat3[3] = x / d; - mat3[4] = y / d; - mat3[5] = factor / d; - this.onChange(); - }; - Projection2d.prototype.mapSprite = function (sprite, quad) { - var tex = sprite.texture; - tempRect.x = -sprite.anchor.x * tex.orig.width; - tempRect.y = -sprite.anchor.y * tex.orig.height; - tempRect.width = tex.orig.width; - tempRect.height = tex.orig.height; - return this.mapQuad(tempRect, quad); - }; - Projection2d.prototype.mapQuad = function (rect, p) { - tt[0].set(rect.x, rect.y); - tt[1].set(rect.x + rect.width, rect.y); - tt[2].set(rect.x + rect.width, rect.y + rect.height); - tt[3].set(rect.x, rect.y + rect.height); - var k1 = 1, k2 = 2, k3 = 3; - var f = pixi_projection.utils.getIntersectionFactor(p[0], p[2], p[1], p[3], t0); - if (f !== 0) { - k1 = 1; - k2 = 3; - k3 = 2; - } - else { - return; - } - var d0 = Math.sqrt((p[0].x - t0.x) * (p[0].x - t0.x) + (p[0].y - t0.y) * (p[0].y - t0.y)); - var d1 = Math.sqrt((p[k1].x - t0.x) * (p[k1].x - t0.x) + (p[k1].y - t0.y) * (p[k1].y - t0.y)); - var d2 = Math.sqrt((p[k2].x - t0.x) * (p[k2].x - t0.x) + (p[k2].y - t0.y) * (p[k2].y - t0.y)); - var d3 = Math.sqrt((p[k3].x - t0.x) * (p[k3].x - t0.x) + (p[k3].y - t0.y) * (p[k3].y - t0.y)); - var q0 = (d0 + d3) / d3; - var q1 = (d1 + d2) / d2; - var q2 = (d1 + d2) / d1; - var mat3 = this.matrix.mat3; - mat3[0] = tt[0].x * q0; - mat3[1] = tt[0].y * q0; - mat3[2] = q0; - mat3[3] = tt[k1].x * q1; - mat3[4] = tt[k1].y * q1; - mat3[5] = q1; - mat3[6] = tt[k2].x * q2; - mat3[7] = tt[k2].y * q2; - mat3[8] = q2; - this.matrix.invert(); - mat3 = tempMat.mat3; - mat3[0] = p[0].x; - mat3[1] = p[0].y; - mat3[2] = 1; - mat3[3] = p[k1].x; - mat3[4] = p[k1].y; - mat3[5] = 1; - mat3[6] = p[k2].x; - mat3[7] = p[k2].y; - mat3[8] = 1; - this.matrix.setToMult(tempMat, this.matrix); - this._projID++; - }; - Projection2d.prototype.updateLocalTransform = function (lt) { - if (this._projID !== 0) { - if (this.reverseLocalOrder) { - this.local.setToMultLegacy2(this.matrix, lt); + else if (child.filterArea) { + this._bounds.addBoundsArea(child._bounds, child.filterArea); } else { - this.local.setToMultLegacy(lt, this.matrix); + this._bounds.addBounds(child._bounds); } } + this._bounds.updateID = this._boundsID; + }; + /** + * Retrieves the local bounds of the displayObject as a rectangle object. Copied from and overrides PixiJS v5 method + */ + LinkedListContainer.prototype.getLocalBounds = function (rect, skipChildrenUpdate) { + if (skipChildrenUpdate === void 0) { skipChildrenUpdate = false; } + // skip Container's getLocalBounds, go directly to DisplayObject + var result = pixi.DisplayObject.prototype.getLocalBounds.call(this, rect); + if (!skipChildrenUpdate) { + var child = void 0; + var next = void 0; + for (child = this._firstChild; child; child = next) { + next = child.nextChild; + if (child.visible) { + child.updateTransform(); + } + } + } + return result; + }; + /** + * Renders the object using the WebGL renderer. Copied from and overrides PixiJS v5 method + */ + LinkedListContainer.prototype.render = function (renderer) { + // if the object is not visible or the alpha is 0 then no need to render this element + if (!this.visible || this.worldAlpha <= 0 || !this.renderable) { + return; + } + // do a quick check to see if this element has a mask or a filter. + if (this._mask || (this.filters && this.filters.length)) { + this.renderAdvanced(renderer); + } else { - this.local.copyFrom(lt); + this._render(renderer); + var child = void 0; + var next = void 0; + // simple render children! + for (child = this._firstChild; child; child = next) { + next = child.nextChild; + child.render(renderer); + } } }; - Projection2d.prototype.clear = function () { - _super.prototype.clear.call(this); - this.matrix.identity(); - this.pivot.set(0, 0); - }; - return Projection2d; - }(pixi_projection.LinearProjection)); - pixi_projection.Projection2d = Projection2d; -})(pixi_projection || (pixi_projection = {})); -var pixi_projection; -(function (pixi_projection) { - var Mesh2d = (function (_super) { - __extends(Mesh2d, _super); - function Mesh2d(geometry, shader, state, drawMode) { - var _this = _super.call(this, geometry, shader, state, drawMode) || this; - _this.vertexData2d = null; - _this.proj = new pixi_projection.Projection2d(_this.transform); - return _this; - } - Mesh2d.prototype.calculateVertices = function () { - if (this.proj._affine) { - this.vertexData2d = null; - _super.prototype.calculateVertices.call(this); - return; + /** + * Render the object using the WebGL renderer and advanced features. Copied from and overrides PixiJS v5 method + */ + LinkedListContainer.prototype.renderAdvanced = function (renderer) { + renderer.batch.flush(); + var filters = this.filters; + var mask = this._mask; + // _enabledFilters note: As of development, _enabledFilters is not documented in pixi.js + // types but is in code of current release (5.2.4). + // push filter first as we need to ensure the stencil buffer is correct for any masking + if (filters) { + if (!this._enabledFilters) { + this._enabledFilters = []; + } + this._enabledFilters.length = 0; + for (var i = 0; i < filters.length; i++) { + if (filters[i].enabled) { + this._enabledFilters.push(filters[i]); + } + } + if (this._enabledFilters.length) { + renderer.filter.push(this, this._enabledFilters); + } } - var geometry = this.geometry; - var vertices = geometry.buffers[0].data; - var thisAny = this; - if (geometry.vertexDirtyId === thisAny.vertexDirty && thisAny._transformID === thisAny.transform._worldID) { - return; + if (mask) { + renderer.mask.push(this, this._mask); } - thisAny._transformID = thisAny.transform._worldID; - if (thisAny.vertexData.length !== vertices.length) { - thisAny.vertexData = new Float32Array(vertices.length); - } - if (this.vertexData2d.length !== vertices.length * 3 / 2) { - this.vertexData2d = new Float32Array(vertices.length * 3); - } - var wt = this.proj.world.mat3; - var vertexData2d = this.vertexData2d; - var vertexData = thisAny.vertexData; - for (var i = 0; i < vertexData.length / 2; i++) { - var x = vertices[(i * 2)]; - var y = vertices[(i * 2) + 1]; - var xx = (wt[0] * x) + (wt[3] * y) + wt[6]; - var yy = (wt[1] * x) + (wt[4] * y) + wt[7]; - var ww = (wt[2] * x) + (wt[5] * y) + wt[8]; - vertexData2d[i * 3] = xx; - vertexData2d[i * 3 + 1] = yy; - vertexData2d[i * 3 + 2] = ww; - vertexData[(i * 2)] = xx / ww; - vertexData[(i * 2) + 1] = yy / ww; - } - thisAny.vertexDirty = geometry.vertexDirtyId; - }; - Mesh2d.prototype._renderDefault = function (renderer) { - var shader = this.shader; - shader.alpha = this.worldAlpha; - if (shader.update) { - shader.update(); + // add this object to the batch, only rendered if it has a texture. + this._render(renderer); + var child; + var next; + // now loop through the children and make sure they get rendered + for (child = this._firstChild; child; child = next) { + next = child.nextChild; + child.render(renderer); } renderer.batch.flush(); - if (shader.program.uniformData.translationMatrix) { - shader.uniforms.translationMatrix = this.worldTransform.toArray(true); + if (mask) { + renderer.mask.pop(this); } - renderer.shader.bind(shader, false); - renderer.state.set(this.state); - renderer.geometry.bind(this.geometry, shader); - renderer.geometry.draw(this.drawMode, this.size, this.start, this.geometry.instanceCount); - }; - Mesh2d.prototype.toLocal = function (position, from, point, skipUpdate, step) { - if (step === void 0) { step = pixi_projection.TRANSFORM_STEP.ALL; } - return pixi_projection.container2dToLocal.call(this, position, from, point, skipUpdate, step); - }; - Object.defineProperty(Mesh2d.prototype, "worldTransform", { - get: function () { - return this.proj.affine ? this.transform.worldTransform : this.proj.world; - }, - enumerable: true, - configurable: true - }); - Mesh2d.defaultVertexShader = "precision highp float;\nattribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\nuniform mat3 translationMatrix;\nuniform mat3 uTransform;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position.xyw = projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0);\n gl_Position.z = 0.0;\n\n vTextureCoord = (uTransform * vec3(aTextureCoord, 1.0)).xy;\n}\n"; - Mesh2d.defaultFragmentShader = "\nvarying vec2 vTextureCoord;\nuniform vec4 uColor;\n\nuniform sampler2D uSampler;\n\nvoid main(void)\n{\n gl_FragColor = texture2D(uSampler, vTextureCoord) * uColor;\n}"; - return Mesh2d; - }(PIXI.Mesh)); - pixi_projection.Mesh2d = Mesh2d; - var SimpleMesh2d = (function (_super) { - __extends(SimpleMesh2d, _super); - function SimpleMesh2d(texture, vertices, uvs, indices, drawMode) { - var _this = _super.call(this, new PIXI.MeshGeometry(vertices, uvs, indices), new PIXI.MeshMaterial(texture, { - program: PIXI.Program.from(Mesh2d.defaultVertexShader, Mesh2d.defaultFragmentShader), - pluginName: 'batch2d' - }), null, drawMode) || this; - _this.autoUpdate = true; - _this.geometry.getBuffer('aVertexPosition').static = false; - return _this; - } - Object.defineProperty(SimpleMesh2d.prototype, "vertices", { - get: function () { - return this.geometry.getBuffer('aVertexPosition').data; - }, - set: function (value) { - this.geometry.getBuffer('aVertexPosition').data = value; - }, - enumerable: true, - configurable: true - }); - SimpleMesh2d.prototype._render = function (renderer) { - if (this.autoUpdate) { - this.geometry.getBuffer('aVertexPosition').update(); + if (filters && this._enabledFilters && this._enabledFilters.length) { + renderer.filter.pop(); } - _super.prototype._render.call(this, renderer); }; - return SimpleMesh2d; - }(Mesh2d)); - pixi_projection.SimpleMesh2d = SimpleMesh2d; -})(pixi_projection || (pixi_projection = {})); -var pixi_projection; -(function (pixi_projection) { - var Sprite2d = (function (_super) { - __extends(Sprite2d, _super); - function Sprite2d(texture) { - var _this = _super.call(this, texture) || this; - _this.vertexData2d = null; - _this.proj = new pixi_projection.Projection2d(_this.transform); - _this.pluginName = 'batch2d'; - return _this; - } - Sprite2d.prototype._calculateBounds = function () { - this.calculateTrimmedVertices(); - this._bounds.addQuad(this.vertexTrimmedData); - }; - Sprite2d.prototype.calculateVertices = function () { - var texture = this._texture; - if (this.proj._affine) { - this.vertexData2d = null; - _super.prototype.calculateVertices.call(this); + /** + * Renders the object using the WebGL renderer. Copied from and overrides PixiJS V4 method. + */ + LinkedListContainer.prototype.renderWebGL = function (renderer) { + // if the object is not visible or the alpha is 0 then no need to render this element + if (!this.visible || this.worldAlpha <= 0 || !this.renderable) { return; } - if (!this.vertexData2d) { - this.vertexData2d = new Float32Array(12); - } - var wid = this.transform._worldID; - var tuid = texture._updateID; - if (this._transformID === wid && this._textureID === tuid) { - return; - } - if (this._textureID !== tuid) { - this.uvs = texture._uvs.uvsFloat32; - } - this._transformID = wid; - this._textureID = tuid; - var wt = this.proj.world.mat3; - var vertexData2d = this.vertexData2d; - var vertexData = this.vertexData; - var trim = texture.trim; - var orig = texture.orig; - var anchor = this._anchor; - var w0 = 0; - var w1 = 0; - var h0 = 0; - var h1 = 0; - if (trim) { - w1 = trim.x - (anchor._x * orig.width); - w0 = w1 + trim.width; - h1 = trim.y - (anchor._y * orig.height); - h0 = h1 + trim.height; + // do a quick check to see if this element has a mask or a filter. + if (this._mask || (this.filters && this.filters.length)) { + this.renderAdvancedWebGL(renderer); } else { - w1 = -anchor._x * orig.width; - w0 = w1 + orig.width; - h1 = -anchor._y * orig.height; - h0 = h1 + orig.height; + this._renderWebGL(renderer); + var child = void 0; + var next = void 0; + // simple render children! + for (child = this._firstChild; child; child = next) { + next = child.nextChild; + child.renderWebGL(renderer); + } } - vertexData2d[0] = (wt[0] * w1) + (wt[3] * h1) + wt[6]; - vertexData2d[1] = (wt[1] * w1) + (wt[4] * h1) + wt[7]; - vertexData2d[2] = (wt[2] * w1) + (wt[5] * h1) + wt[8]; - vertexData2d[3] = (wt[0] * w0) + (wt[3] * h1) + wt[6]; - vertexData2d[4] = (wt[1] * w0) + (wt[4] * h1) + wt[7]; - vertexData2d[5] = (wt[2] * w0) + (wt[5] * h1) + wt[8]; - vertexData2d[6] = (wt[0] * w0) + (wt[3] * h0) + wt[6]; - vertexData2d[7] = (wt[1] * w0) + (wt[4] * h0) + wt[7]; - vertexData2d[8] = (wt[2] * w0) + (wt[5] * h0) + wt[8]; - vertexData2d[9] = (wt[0] * w1) + (wt[3] * h0) + wt[6]; - vertexData2d[10] = (wt[1] * w1) + (wt[4] * h0) + wt[7]; - vertexData2d[11] = (wt[2] * w1) + (wt[5] * h0) + wt[8]; - vertexData[0] = vertexData2d[0] / vertexData2d[2]; - vertexData[1] = vertexData2d[1] / vertexData2d[2]; - vertexData[2] = vertexData2d[3] / vertexData2d[5]; - vertexData[3] = vertexData2d[4] / vertexData2d[5]; - vertexData[4] = vertexData2d[6] / vertexData2d[8]; - vertexData[5] = vertexData2d[7] / vertexData2d[8]; - vertexData[6] = vertexData2d[9] / vertexData2d[11]; - vertexData[7] = vertexData2d[10] / vertexData2d[11]; }; - Sprite2d.prototype.calculateTrimmedVertices = function () { - if (this.proj._affine) { - _super.prototype.calculateTrimmedVertices.call(this); - return; - } - var wid = this.transform._worldID; - var tuid = this._texture._updateID; - if (!this.vertexTrimmedData) { - this.vertexTrimmedData = new Float32Array(8); - } - else if (this._transformTrimmedID === wid && this._textureTrimmedID === tuid) { - return; - } - this._transformTrimmedID = wid; - this._textureTrimmedID = tuid; - var texture = this._texture; - var vertexData = this.vertexTrimmedData; - var orig = texture.orig; - var anchor = this._anchor; - var wt = this.proj.world.mat3; - var w1 = -anchor._x * orig.width; - var w0 = w1 + orig.width; - var h1 = -anchor._y * orig.height; - var h0 = h1 + orig.height; - var z = 1.0 / (wt[2] * w1 + wt[5] * h1 + wt[8]); - vertexData[0] = z * ((wt[0] * w1) + (wt[3] * h1) + wt[6]); - vertexData[1] = z * ((wt[1] * w1) + (wt[4] * h1) + wt[7]); - z = 1.0 / (wt[2] * w0 + wt[5] * h1 + wt[8]); - vertexData[2] = z * ((wt[0] * w0) + (wt[3] * h1) + wt[6]); - vertexData[3] = z * ((wt[1] * w0) + (wt[4] * h1) + wt[7]); - z = 1.0 / (wt[2] * w0 + wt[5] * h0 + wt[8]); - vertexData[4] = z * ((wt[0] * w0) + (wt[3] * h0) + wt[6]); - vertexData[5] = z * ((wt[1] * w0) + (wt[4] * h0) + wt[7]); - z = 1.0 / (wt[2] * w1 + wt[5] * h0 + wt[8]); - vertexData[6] = z * ((wt[0] * w1) + (wt[3] * h0) + wt[6]); - vertexData[7] = z * ((wt[1] * w1) + (wt[4] * h0) + wt[7]); - }; - Sprite2d.prototype.toLocal = function (position, from, point, skipUpdate, step) { - if (step === void 0) { step = pixi_projection.TRANSFORM_STEP.ALL; } - return pixi_projection.container2dToLocal.call(this, position, from, point, skipUpdate, step); - }; - Object.defineProperty(Sprite2d.prototype, "worldTransform", { - get: function () { - return this.proj.affine ? this.transform.worldTransform : this.proj.world; - }, - enumerable: true, - configurable: true - }); - return Sprite2d; - }(PIXI.Sprite)); - pixi_projection.Sprite2d = Sprite2d; -})(pixi_projection || (pixi_projection = {})); -var pixi_projection; -(function (pixi_projection) { - var Text2d = (function (_super) { - __extends(Text2d, _super); - function Text2d(text, style, canvas) { - var _this = _super.call(this, text, style, canvas) || this; - _this.vertexData2d = null; - _this.proj = new pixi_projection.Projection2d(_this.transform); - _this.pluginName = 'batch2d'; - return _this; - } - Object.defineProperty(Text2d.prototype, "worldTransform", { - get: function () { - return this.proj.affine ? this.transform.worldTransform : this.proj.world; - }, - enumerable: true, - configurable: true - }); - return Text2d; - }(PIXI.Text)); - pixi_projection.Text2d = Text2d; - Text2d.prototype.calculateVertices = pixi_projection.Sprite2d.prototype.calculateVertices; - Text2d.prototype.calculateTrimmedVertices = pixi_projection.Sprite2d.prototype.calculateTrimmedVertices; - Text2d.prototype._calculateBounds = pixi_projection.Sprite2d.prototype._calculateBounds; -})(pixi_projection || (pixi_projection = {})); -var pixi_projection; -(function (pixi_projection) { - function convertTo2d() { - if (this.proj) - return; - this.proj = new pixi_projection.Projection2d(this.transform); - this.toLocal = pixi_projection.Container2d.prototype.toLocal; - Object.defineProperty(this, "worldTransform", { - get: pixi_projection.container2dWorldTransform, - enumerable: true, - configurable: true - }); - } - PIXI.Container.prototype.convertTo2d = convertTo2d; - PIXI.Sprite.prototype.convertTo2d = function () { - if (this.proj) - return; - this.calculateVertices = pixi_projection.Sprite2d.prototype.calculateVertices; - this.calculateTrimmedVertices = pixi_projection.Sprite2d.prototype.calculateTrimmedVertices; - this._calculateBounds = pixi_projection.Sprite2d.prototype._calculateBounds; - this.pluginName = 'sprite2d'; - convertTo2d.call(this); - }; - PIXI.Container.prototype.convertSubtreeTo2d = function () { - this.convertTo2d(); - for (var i = 0; i < this.children.length; i++) { - this.children[i].convertSubtreeTo2d(); - } - }; - if (PIXI.SimpleMesh) { - PIXI.SimpleMesh.prototype.convertTo2d = - PIXI.SimpleRope.prototype.convertTo2d = - function () { - if (this.proj) - return; - this.calculateVertices = pixi_projection.Mesh2d.prototype.calculateVertices; - this._renderDefault = pixi_projection.Mesh2d.prototype._renderDefault; - if (this.material.pluginName !== 'batch2d') { - this.material = new PIXI.MeshMaterial(this.material.texture, { - program: PIXI.Program.from(pixi_projection.Mesh2d.defaultVertexShader, pixi_projection.Mesh2d.defaultFragmentShader), - pluginName: 'batch2d' - }); - } - convertTo2d.call(this); - }; - } -})(pixi_projection || (pixi_projection = {})); -var pixi_projection; -(function (pixi_projection) { - var tempTransform = new PIXI.Transform(); - var TilingSprite2d = (function (_super) { - __extends(TilingSprite2d, _super); - function TilingSprite2d(texture, width, height) { - var _this = _super.call(this, texture, width, height) || this; - _this.tileProj = new pixi_projection.Projection2d(_this.tileTransform); - _this.tileProj.reverseLocalOrder = true; - _this.proj = new pixi_projection.Projection2d(_this.transform); - _this.pluginName = 'tilingSprite2d'; - _this.uvRespectAnchor = true; - return _this; - } - Object.defineProperty(TilingSprite2d.prototype, "worldTransform", { - get: function () { - return this.proj.affine ? this.transform.worldTransform : this.proj.world; - }, - enumerable: true, - configurable: true - }); - TilingSprite2d.prototype.toLocal = function (position, from, point, skipUpdate, step) { - if (step === void 0) { step = pixi_projection.TRANSFORM_STEP.ALL; } - return pixi_projection.container2dToLocal.call(this, position, from, point, skipUpdate, step); - }; - TilingSprite2d.prototype._render = function (renderer) { - var texture = this._texture; - if (!texture || !texture.valid) { - return; - } - this.tileTransform.updateTransform(tempTransform); - this.uvMatrix.update(); - renderer.batch.setObjectRenderer(renderer.plugins[this.pluginName]); - renderer.plugins[this.pluginName].render(this); - }; - return TilingSprite2d; - }(PIXI.TilingSprite)); - pixi_projection.TilingSprite2d = TilingSprite2d; -})(pixi_projection || (pixi_projection = {})); -var pixi_projection; -(function (pixi_projection) { - var shaderVert = "attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\nuniform mat3 translationMatrix;\nuniform mat3 uTransform;\n\nvarying vec3 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position.xyw = projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0);\n\n vTextureCoord = uTransform * vec3(aTextureCoord, 1.0);\n}\n"; - var shaderFrag = "\nvarying vec3 vTextureCoord;\n\nuniform sampler2D uSampler;\nuniform vec4 uColor;\nuniform mat3 uMapCoord;\nuniform vec4 uClampFrame;\nuniform vec2 uClampOffset;\n\nvoid main(void)\n{\n vec2 coord = mod(vTextureCoord.xy / vTextureCoord.z - uClampOffset, vec2(1.0, 1.0)) + uClampOffset;\n coord = (uMapCoord * vec3(coord, 1.0)).xy;\n coord = clamp(coord, uClampFrame.xy, uClampFrame.zw);\n\n vec4 sample = texture2D(uSampler, coord);\n gl_FragColor = sample * uColor;\n}\n"; - var shaderSimpleFrag = "\n\tvarying vec3 vTextureCoord;\n\nuniform sampler2D uSampler;\nuniform vec4 uColor;\n\nvoid main(void)\n{\n vec4 sample = texture2D(uSampler, vTextureCoord.xy / vTextureCoord.z);\n gl_FragColor = sample * uColor;\n}\n"; - var tempMat = new pixi_projection.Matrix2d(); - var WRAP_MODES = PIXI.WRAP_MODES; - var utils = PIXI.utils; - var TilingSprite2dRenderer = (function (_super) { - __extends(TilingSprite2dRenderer, _super); - function TilingSprite2dRenderer(renderer) { - var _this = _super.call(this, renderer) || this; - _this.quad = new PIXI.QuadUv(); - var uniforms = { globals: _this.renderer.globalUniforms }; - _this.shader = PIXI.Shader.from(shaderVert, shaderFrag, uniforms); - _this.simpleShader = PIXI.Shader.from(shaderVert, shaderSimpleFrag, uniforms); - return _this; - } - TilingSprite2dRenderer.prototype.render = function (ts) { - var renderer = this.renderer; - var quad = this.quad; - var vertices = quad.vertices; - vertices[0] = vertices[6] = (ts._width) * -ts.anchor.x; - vertices[1] = vertices[3] = ts._height * -ts.anchor.y; - vertices[2] = vertices[4] = (ts._width) * (1.0 - ts.anchor.x); - vertices[5] = vertices[7] = ts._height * (1.0 - ts.anchor.y); - if (ts.uvRespectAnchor) { - vertices = quad.uvs; - vertices[0] = vertices[6] = -ts.anchor.x; - vertices[1] = vertices[3] = -ts.anchor.y; - vertices[2] = vertices[4] = 1.0 - ts.anchor.x; - vertices[5] = vertices[7] = 1.0 - ts.anchor.y; - } - quad.invalidate(); - var tex = ts._texture; - var baseTex = tex.baseTexture; - var lt = ts.tileProj.world; - var uv = ts.uvMatrix; - var isSimple = baseTex.isPowerOfTwo - && tex.frame.width === baseTex.width && tex.frame.height === baseTex.height; - if (isSimple) { - if (!baseTex._glTextures[renderer.CONTEXT_UID]) { - if (baseTex.wrapMode === WRAP_MODES.CLAMP) { - baseTex.wrapMode = WRAP_MODES.REPEAT; + /** + * Render the object using the WebGL renderer and advanced features. Copied from and overrides PixiJS V4 method. + */ + LinkedListContainer.prototype.renderAdvancedWebGL = function (renderer) { + renderer.flush(); + // _filters is a v4 specific property + var filters = this._filters; + var mask = this._mask; + // push filter first as we need to ensure the stencil buffer is correct for any masking + if (filters) { + if (!this._enabledFilters) { + this._enabledFilters = []; + } + this._enabledFilters.length = 0; + for (var i = 0; i < filters.length; i++) { + if (filters[i].enabled) { + this._enabledFilters.push(filters[i]); } } - else { - isSimple = baseTex.wrapMode !== WRAP_MODES.CLAMP; + if (this._enabledFilters.length) { + renderer.filterManager.pushFilter(this, this._enabledFilters); } } - var shader = isSimple ? this.simpleShader : this.shader; - tempMat.identity(); - tempMat.scale(tex.width, tex.height); - tempMat.prepend(lt); - tempMat.scale(1.0 / ts._width, 1.0 / ts._height); - tempMat.invert(); - if (isSimple) { - tempMat.prepend(uv.mapCoord); + if (mask) { + renderer.maskManager.pushMask(this, this._mask); } - else { - shader.uniforms.uMapCoord = uv.mapCoord.toArray(true); - shader.uniforms.uClampFrame = uv.uClampFrame; - shader.uniforms.uClampOffset = uv.uClampOffset; + // add this object to the batch, only rendered if it has a texture. + this._renderWebGL(renderer); + var child; + var next; + // now loop through the children and make sure they get rendered + for (child = this._firstChild; child; child = next) { + next = child.nextChild; + child.renderWebGL(renderer); + } + renderer.flush(); + if (mask) { + renderer.maskManager.popMask(this, this._mask); + } + if (filters && this._enabledFilters && this._enabledFilters.length) { + renderer.filterManager.popFilter(); } - shader.uniforms.uTransform = tempMat.toArray(true); - shader.uniforms.uColor = utils.premultiplyTintToRgba(ts.tint, ts.worldAlpha, shader.uniforms.uColor, baseTex.premultiplyAlpha); - shader.uniforms.translationMatrix = ts.transform.worldTransform.toArray(true); - shader.uniforms.uSampler = tex; - renderer.shader.bind(shader, false); - renderer.geometry.bind(quad, undefined); - renderer.state.setBlendMode(utils.correctBlendMode(ts.blendMode, baseTex.premultiplyAlpha)); - renderer.geometry.draw(PIXI.DRAW_MODES.TRIANGLES, 6, 0); }; - return TilingSprite2dRenderer; - }(PIXI.ObjectRenderer)); - pixi_projection.TilingSprite2dRenderer = TilingSprite2dRenderer; - PIXI.Renderer.registerPlugin('tilingSprite2d', TilingSprite2dRenderer); -})(pixi_projection || (pixi_projection = {})); -var pixi_projection; -(function (pixi_projection) { - PIXI.systems.MaskSystem.prototype.pushSpriteMask = function (maskData) { - var maskObject = maskData.maskObject; - var target = maskData._target; - var alphaMaskFilter = this.alphaMaskPool[this.alphaMaskIndex]; - if (!alphaMaskFilter) { - alphaMaskFilter = this.alphaMaskPool[this.alphaMaskIndex] = [new pixi_projection.SpriteMaskFilter2d(maskObject)]; - } - alphaMaskFilter[0].resolution = this.renderer.resolution; - alphaMaskFilter[0].maskSprite = maskObject; - var stashFilterArea = target.filterArea; - target.filterArea = maskObject.getBounds(true); - this.renderer.filter.push(target, alphaMaskFilter); - target.filterArea = stashFilterArea; - this.renderer.filter.push(target, alphaMaskFilter); - this.alphaMaskIndex++; - }; -})(pixi_projection || (pixi_projection = {})); -var pixi_projection; -(function (pixi_projection) { - var spriteMaskVert = "\nattribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\nuniform mat3 otherMatrix;\n\nvarying vec3 vMaskCoord;\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n\tgl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n\tvTextureCoord = aTextureCoord;\n\tvMaskCoord = otherMatrix * vec3( aTextureCoord, 1.0);\n}\n"; - var spriteMaskFrag = "\nvarying vec3 vMaskCoord;\nvarying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\nuniform sampler2D mask;\nuniform float alpha;\nuniform vec4 maskClamp;\n\nvoid main(void)\n{\n vec2 uv = vMaskCoord.xy / vMaskCoord.z;\n \n float clip = step(3.5,\n step(maskClamp.x, uv.x) +\n step(maskClamp.y, uv.y) +\n step(uv.x, maskClamp.z) +\n step(uv.y, maskClamp.w));\n\n vec4 original = texture2D(uSampler, vTextureCoord);\n vec4 masky = texture2D(mask, uv);\n \n original *= (masky.r * masky.a * alpha * clip);\n\n gl_FragColor = original;\n}\n"; - var tempMat = new pixi_projection.Matrix2d(); - var SpriteMaskFilter2d = (function (_super) { - __extends(SpriteMaskFilter2d, _super); - function SpriteMaskFilter2d(sprite) { - var _this = _super.call(this, spriteMaskVert, spriteMaskFrag) || this; - _this.maskMatrix = new pixi_projection.Matrix2d(); - sprite.renderable = false; - _this.maskSprite = sprite; - return _this; - } - SpriteMaskFilter2d.prototype.apply = function (filterManager, input, output, clear) { - var maskSprite = this.maskSprite; - var tex = this.maskSprite.texture; - if (!tex.valid) { + /** + * Renders the object using the Canvas renderer. Copied from and overrides PixiJS V4 method or Canvas mixin in V5. + */ + LinkedListContainer.prototype.renderCanvas = function (renderer) { + // if not visible or the alpha is 0 then no need to render this + if (!this.visible || this.worldAlpha <= 0 || !this.renderable) { return; } - if (!tex.uvMatrix) { - tex.uvMatrix = new PIXI.TextureMatrix(tex, 0.0); + if (this._mask) { + renderer.maskManager.pushMask(this._mask); } - tex.uvMatrix.update(); - this.uniforms.mask = maskSprite.texture; - this.uniforms.otherMatrix = SpriteMaskFilter2d.calculateSpriteMatrix(input, this.maskMatrix, maskSprite) - .prepend(tex.uvMatrix.mapCoord); - this.uniforms.alpha = maskSprite.worldAlpha; - this.uniforms.maskClamp = tex.uvMatrix.uClampFrame; - filterManager.applyFilter(this, input, output, clear); - }; - SpriteMaskFilter2d.calculateSpriteMatrix = function (input, mappedMatrix, sprite) { - var proj = sprite.proj; - var filterArea = input.filterFrame; - var worldTransform = proj && !proj._affine ? proj.world.copyTo2dOr3d(tempMat) : tempMat.copyFrom(sprite.transform.worldTransform); - var texture = sprite.texture.orig; - mappedMatrix.set(input.width, 0, 0, input.height, filterArea.x, filterArea.y); - worldTransform.invert(); - mappedMatrix.setToMult(worldTransform, mappedMatrix); - mappedMatrix.scaleAndTranslate(1.0 / texture.width, 1.0 / texture.height, sprite.anchor.x, sprite.anchor.y); - return mappedMatrix; - }; - return SpriteMaskFilter2d; - }(PIXI.Filter)); - pixi_projection.SpriteMaskFilter2d = SpriteMaskFilter2d; -})(pixi_projection || (pixi_projection = {})); -var pixi_projection; -(function (pixi_projection) { - function container3dWorldTransform() { - return this.proj.affine ? this.transform.worldTransform : this.proj.world; - } - pixi_projection.container3dWorldTransform = container3dWorldTransform; - var Container3d = (function (_super) { - __extends(Container3d, _super); - function Container3d() { - var _this = _super.call(this) || this; - _this.proj = new pixi_projection.Projection3d(_this.transform); - return _this; - } - Container3d.prototype.isFrontFace = function (forceUpdate) { - if (forceUpdate === void 0) { forceUpdate = false; } - if (forceUpdate) { - this._recursivePostUpdateTransform(); - this.displayObjectUpdateTransform(); + this._renderCanvas(renderer); + var child; + var next; + for (child = this._firstChild; child; child = next) { + next = child.nextChild; + child.renderCanvas(renderer); } - var mat = this.proj.world.mat4; - var dx1 = mat[0] * mat[15] - mat[3] * mat[12]; - var dy1 = mat[1] * mat[15] - mat[3] * mat[13]; - var dx2 = mat[4] * mat[15] - mat[7] * mat[12]; - var dy2 = mat[5] * mat[15] - mat[7] * mat[13]; - return dx1 * dy2 - dx2 * dy1 > 0; - }; - Container3d.prototype.getDepth = function (forceUpdate) { - if (forceUpdate === void 0) { forceUpdate = false; } - if (forceUpdate) { - this._recursivePostUpdateTransform(); - this.displayObjectUpdateTransform(); - } - var mat4 = this.proj.world.mat4; - return mat4[14] / mat4[15]; - }; - Container3d.prototype.toLocal = function (position, from, point, skipUpdate, step) { - if (step === void 0) { step = pixi_projection.TRANSFORM_STEP.ALL; } - if (from) { - position = from.toGlobal(position, point, skipUpdate); - } - if (!skipUpdate) { - this._recursivePostUpdateTransform(); - } - if (step === pixi_projection.TRANSFORM_STEP.ALL) { - if (!skipUpdate) { - this.displayObjectUpdateTransform(); - } - if (this.proj.affine) { - return this.transform.worldTransform.applyInverse(position, point); - } - return this.proj.world.applyInverse(position, point); - } - if (this.parent) { - point = this.parent.worldTransform.applyInverse(position, point); - } - else { - point.copyFrom(position); - } - if (step === pixi_projection.TRANSFORM_STEP.NONE) { - return point; - } - point = this.transform.localTransform.applyInverse(point, point); - if (step === pixi_projection.TRANSFORM_STEP.PROJ && this.proj.cameraMode) { - point = this.proj.cameraMatrix.applyInverse(point, point); - } - return point; - }; - Object.defineProperty(Container3d.prototype, "worldTransform", { - get: function () { - return this.proj.affine ? this.transform.worldTransform : this.proj.world; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Container3d.prototype, "position3d", { - get: function () { - return this.proj.position; - }, - set: function (value) { - this.proj.position.copyFrom(value); - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Container3d.prototype, "scale3d", { - get: function () { - return this.proj.scale; - }, - set: function (value) { - this.proj.scale.copyFrom(value); - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Container3d.prototype, "euler", { - get: function () { - return this.proj.euler; - }, - set: function (value) { - this.proj.euler.copyFrom(value); - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Container3d.prototype, "pivot3d", { - get: function () { - return this.proj.pivot; - }, - set: function (value) { - this.proj.pivot.copyFrom(value); - }, - enumerable: true, - configurable: true - }); - return Container3d; - }(PIXI.Container)); - pixi_projection.Container3d = Container3d; - pixi_projection.container3dToLocal = Container3d.prototype.toLocal; - pixi_projection.container3dGetDepth = Container3d.prototype.getDepth; - pixi_projection.container3dIsFrontFace = Container3d.prototype.isFrontFace; -})(pixi_projection || (pixi_projection = {})); -var pixi_projection; -(function (pixi_projection) { - var Camera3d = (function (_super) { - __extends(Camera3d, _super); - function Camera3d() { - var _this = _super.call(this) || this; - _this._far = 0; - _this._near = 0; - _this._focus = 0; - _this._orthographic = false; - _this.proj.cameraMode = true; - _this.setPlanes(400, 10, 10000, false); - return _this; - } - Object.defineProperty(Camera3d.prototype, "far", { - get: function () { - return this._far; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Camera3d.prototype, "near", { - get: function () { - return this._near; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Camera3d.prototype, "focus", { - get: function () { - return this._focus; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Camera3d.prototype, "ortographic", { - get: function () { - return this._orthographic; - }, - enumerable: true, - configurable: true - }); - Camera3d.prototype.setPlanes = function (focus, near, far, orthographic) { - if (near === void 0) { near = 10; } - if (far === void 0) { far = 10000; } - if (orthographic === void 0) { orthographic = false; } - this._focus = focus; - this._near = near; - this._far = far; - this._orthographic = orthographic; - var proj = this.proj; - var mat4 = proj.cameraMatrix.mat4; - proj._projID++; - mat4[10] = 1.0 / (far - near); - mat4[14] = (focus - near) / (far - near); - if (this._orthographic) { - mat4[11] = 0; - } - else { - mat4[11] = 1.0 / focus; + if (this._mask) { + renderer.maskManager.popMask(renderer); } }; - return Camera3d; - }(pixi_projection.Container3d)); - pixi_projection.Camera3d = Camera3d; -})(pixi_projection || (pixi_projection = {})); -var pixi_projection; -(function (pixi_projection) { - var Euler = (function () { - function Euler(x, y, z) { - this._quatUpdateId = -1; - this._quatDirtyId = 0; - this._sign = 1; - this._x = x || 0; - this._y = y || 0; - this._z = z || 0; - this.quaternion = new Float64Array(4); - this.quaternion[3] = 1; - this.update(); - } - Object.defineProperty(Euler.prototype, "x", { - get: function () { - return this._x; - }, - set: function (value) { - if (this._x !== value) { - this._x = value; - this._quatDirtyId++; - } - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Euler.prototype, "y", { - get: function () { - return this._y; - }, - set: function (value) { - if (this._y !== value) { - this._y = value; - this._quatDirtyId++; - } - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Euler.prototype, "z", { - get: function () { - return this._z; - }, - set: function (value) { - if (this._z !== value) { - this._z = value; - this._quatDirtyId++; - } - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Euler.prototype, "pitch", { - get: function () { - return this._x; - }, - set: function (value) { - if (this._x !== value) { - this._x = value; - this._quatDirtyId++; - } - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Euler.prototype, "yaw", { - get: function () { - return this._y; - }, - set: function (value) { - if (this._y !== value) { - this._y = value; - this._quatDirtyId++; - } - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Euler.prototype, "roll", { - get: function () { - return this._z; - }, - set: function (value) { - if (this._z !== value) { - this._z = value; - this._quatDirtyId++; - } - }, - enumerable: true, - configurable: true - }); - Euler.prototype.set = function (x, y, z) { - var _x = x || 0; - var _y = y || 0; - var _z = z || 0; - if (this._x !== _x || this._y !== _y || this._z !== _z) { - this._x = _x; - this._y = _y; - this._z = _z; - this._quatDirtyId++; - } - }; - ; - Euler.prototype.copyFrom = function (euler) { - var _x = euler.x; - var _y = euler.y; - var _z = euler.z; - if (this._x !== _x || this._y !== _y || this._z !== _z) { - this._x = _x; - this._y = _y; - this._z = _z; - this._quatDirtyId++; - } - }; - Euler.prototype.copyTo = function (p) { - p.set(this._x, this._y, this._z); - return p; - }; - Euler.prototype.equals = function (euler) { - return this._x === euler.x - && this._y === euler.y - && this._z === euler.z; - }; - Euler.prototype.clone = function () { - return new Euler(this._x, this._y, this._z); - }; - Euler.prototype.update = function () { - if (this._quatUpdateId === this._quatDirtyId) { - return false; - } - this._quatUpdateId = this._quatDirtyId; - var c1 = Math.cos(this._x / 2); - var c2 = Math.cos(this._y / 2); - var c3 = Math.cos(this._z / 2); - var s = this._sign; - var s1 = s * Math.sin(this._x / 2); - var s2 = s * Math.sin(this._y / 2); - var s3 = s * Math.sin(this._z / 2); - var q = this.quaternion; - q[0] = s1 * c2 * c3 + c1 * s2 * s3; - q[1] = c1 * s2 * c3 - s1 * c2 * s3; - q[2] = c1 * c2 * s3 + s1 * s2 * c3; - q[3] = c1 * c2 * c3 - s1 * s2 * s3; - return true; - }; - return Euler; - }()); - pixi_projection.Euler = Euler; -})(pixi_projection || (pixi_projection = {})); -var pixi_projection; -(function (pixi_projection) { - var mat4id = [1, 0, 0, 0, - 0, 1, 0, 0, - 0, 0, 1, 0, - 0, 0, 0, 1]; - var Matrix3d = (function () { - function Matrix3d(backingArray) { - this.floatArray = null; - this._dirtyId = 0; - this._updateId = -1; - this._mat4inv = null; - this.cacheInverse = false; - this.mat4 = new Float64Array(backingArray || mat4id); - } - Object.defineProperty(Matrix3d.prototype, "a", { - get: function () { - return this.mat4[0] / this.mat4[15]; - }, - set: function (value) { - this.mat4[0] = value * this.mat4[15]; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Matrix3d.prototype, "b", { - get: function () { - return this.mat4[1] / this.mat4[15]; - }, - set: function (value) { - this.mat4[1] = value * this.mat4[15]; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Matrix3d.prototype, "c", { - get: function () { - return this.mat4[4] / this.mat4[15]; - }, - set: function (value) { - this.mat4[4] = value * this.mat4[15]; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Matrix3d.prototype, "d", { - get: function () { - return this.mat4[5] / this.mat4[15]; - }, - set: function (value) { - this.mat4[5] = value * this.mat4[15]; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Matrix3d.prototype, "tx", { - get: function () { - return this.mat4[12] / this.mat4[15]; - }, - set: function (value) { - this.mat4[12] = value * this.mat4[15]; - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Matrix3d.prototype, "ty", { - get: function () { - return this.mat4[13] / this.mat4[15]; - }, - set: function (value) { - this.mat4[13] = value * this.mat4[15]; - }, - enumerable: true, - configurable: true - }); - Matrix3d.prototype.set = function (a, b, c, d, tx, ty) { - var mat4 = this.mat4; - mat4[0] = a; - mat4[1] = b; - mat4[2] = 0; - mat4[3] = 0; - mat4[4] = c; - mat4[5] = d; - mat4[6] = 0; - mat4[7] = 0; - mat4[8] = 0; - mat4[9] = 0; - mat4[10] = 1; - mat4[11] = 0; - mat4[12] = tx; - mat4[13] = ty; - mat4[14] = 0; - mat4[15] = 1; - return this; - }; - Matrix3d.prototype.toArray = function (transpose, out) { - if (!this.floatArray) { - this.floatArray = new Float32Array(9); - } - var array = out || this.floatArray; - var mat3 = this.mat4; - if (transpose) { - array[0] = mat3[0]; - array[1] = mat3[1]; - array[2] = mat3[3]; - array[3] = mat3[4]; - array[4] = mat3[5]; - array[5] = mat3[7]; - array[6] = mat3[12]; - array[7] = mat3[13]; - array[8] = mat3[15]; - } - else { - array[0] = mat3[0]; - array[1] = mat3[4]; - array[2] = mat3[12]; - array[3] = mat3[2]; - array[4] = mat3[6]; - array[5] = mat3[13]; - array[6] = mat3[3]; - array[7] = mat3[7]; - array[8] = mat3[15]; - } - return array; - }; - Matrix3d.prototype.setToTranslation = function (tx, ty, tz) { - var mat4 = this.mat4; - mat4[0] = 1; - mat4[1] = 0; - mat4[2] = 0; - mat4[3] = 0; - mat4[4] = 0; - mat4[5] = 1; - mat4[6] = 0; - mat4[7] = 0; - mat4[8] = 0; - mat4[9] = 0; - mat4[10] = 1; - mat4[11] = 0; - mat4[12] = tx; - mat4[13] = ty; - mat4[14] = tz; - mat4[15] = 1; - }; - Matrix3d.prototype.setToRotationTranslationScale = function (quat, tx, ty, tz, sx, sy, sz) { - var out = this.mat4; - var x = quat[0], y = quat[1], z = quat[2], w = quat[3]; - var x2 = x + x; - var y2 = y + y; - var z2 = z + z; - var xx = x * x2; - var xy = x * y2; - var xz = x * z2; - var yy = y * y2; - var yz = y * z2; - var zz = z * z2; - var wx = w * x2; - var wy = w * y2; - var wz = w * z2; - out[0] = (1 - (yy + zz)) * sx; - out[1] = (xy + wz) * sx; - out[2] = (xz - wy) * sx; - out[3] = 0; - out[4] = (xy - wz) * sy; - out[5] = (1 - (xx + zz)) * sy; - out[6] = (yz + wx) * sy; - out[7] = 0; - out[8] = (xz + wy) * sz; - out[9] = (yz - wx) * sz; - out[10] = (1 - (xx + yy)) * sz; - out[11] = 0; - out[12] = tx; - out[13] = ty; - out[14] = tz; - out[15] = 1; - return out; - }; - Matrix3d.prototype.apply = function (pos, newPos) { - newPos = newPos || new pixi_projection.Point3d(); - var mat4 = this.mat4; - var x = pos.x; - var y = pos.y; - var z = pos.z || 0; - var w = 1.0 / (mat4[3] * x + mat4[7] * y + mat4[11] * z + mat4[15]); - newPos.x = w * (mat4[0] * x + mat4[4] * y + mat4[8] * z + mat4[12]); - newPos.y = w * (mat4[1] * x + mat4[5] * y + mat4[9] * z + mat4[13]); - newPos.z = w * (mat4[2] * x + mat4[6] * y + mat4[10] * z + mat4[14]); - return newPos; - }; - Matrix3d.prototype.translate = function (tx, ty, tz) { - var a = this.mat4; - a[12] = a[0] * tx + a[4] * ty + a[8] * tz + a[12]; - a[13] = a[1] * tx + a[5] * ty + a[9] * tz + a[13]; - a[14] = a[2] * tx + a[6] * ty + a[10] * tz + a[14]; - a[15] = a[3] * tx + a[7] * ty + a[11] * tz + a[15]; - return this; - }; - Matrix3d.prototype.scale = function (x, y, z) { - var mat4 = this.mat4; - mat4[0] *= x; - mat4[1] *= x; - mat4[2] *= x; - mat4[3] *= x; - mat4[4] *= y; - mat4[5] *= y; - mat4[6] *= y; - mat4[7] *= y; - if (z !== undefined) { - mat4[8] *= z; - mat4[9] *= z; - mat4[10] *= z; - mat4[11] *= z; - } - return this; - }; - Matrix3d.prototype.scaleAndTranslate = function (scaleX, scaleY, scaleZ, tx, ty, tz) { - var mat4 = this.mat4; - mat4[0] = scaleX * mat4[0] + tx * mat4[3]; - mat4[1] = scaleY * mat4[1] + ty * mat4[3]; - mat4[2] = scaleZ * mat4[2] + tz * mat4[3]; - mat4[4] = scaleX * mat4[4] + tx * mat4[7]; - mat4[5] = scaleY * mat4[5] + ty * mat4[7]; - mat4[6] = scaleZ * mat4[6] + tz * mat4[7]; - mat4[8] = scaleX * mat4[8] + tx * mat4[11]; - mat4[9] = scaleY * mat4[9] + ty * mat4[11]; - mat4[10] = scaleZ * mat4[10] + tz * mat4[11]; - mat4[12] = scaleX * mat4[12] + tx * mat4[15]; - mat4[13] = scaleY * mat4[13] + ty * mat4[15]; - mat4[14] = scaleZ * mat4[14] + tz * mat4[15]; - }; - Matrix3d.prototype.applyInverse = function (pos, newPos) { - newPos = newPos || new pixi_projection.Point3d(); - if (!this._mat4inv) { - this._mat4inv = new Float64Array(16); - } - var mat4 = this._mat4inv; - var a = this.mat4; - var x = pos.x; - var y = pos.y; - var z = pos.z || 0; - if (!this.cacheInverse || this._updateId !== this._dirtyId) { - this._updateId = this._dirtyId; - Matrix3d.glMatrixMat4Invert(mat4, a); - } - var w1 = 1.0 / (mat4[3] * x + mat4[7] * y + mat4[11] * z + mat4[15]); - var x1 = w1 * (mat4[0] * x + mat4[4] * y + mat4[8] * z + mat4[12]); - var y1 = w1 * (mat4[1] * x + mat4[5] * y + mat4[9] * z + mat4[13]); - var z1 = w1 * (mat4[2] * x + mat4[6] * y + mat4[10] * z + mat4[14]); - z += 1.0; - var w2 = 1.0 / (mat4[3] * x + mat4[7] * y + mat4[11] * z + mat4[15]); - var x2 = w2 * (mat4[0] * x + mat4[4] * y + mat4[8] * z + mat4[12]); - var y2 = w2 * (mat4[1] * x + mat4[5] * y + mat4[9] * z + mat4[13]); - var z2 = w2 * (mat4[2] * x + mat4[6] * y + mat4[10] * z + mat4[14]); - if (Math.abs(z1 - z2) < 1e-10) { - newPos.set(NaN, NaN, 0); - } - var alpha = (0 - z1) / (z2 - z1); - newPos.set((x2 - x1) * alpha + x1, (y2 - y1) * alpha + y1, 0.0); - return newPos; - }; - Matrix3d.prototype.invert = function () { - Matrix3d.glMatrixMat4Invert(this.mat4, this.mat4); - return this; - }; - Matrix3d.prototype.invertCopyTo = function (matrix) { - if (!this._mat4inv) { - this._mat4inv = new Float64Array(16); - } - var mat4 = this._mat4inv; - var a = this.mat4; - if (!this.cacheInverse || this._updateId !== this._dirtyId) { - this._updateId = this._dirtyId; - Matrix3d.glMatrixMat4Invert(mat4, a); - } - matrix.mat4.set(mat4); - }; - Matrix3d.prototype.identity = function () { - var mat3 = this.mat4; - mat3[0] = 1; - mat3[1] = 0; - mat3[2] = 0; - mat3[3] = 0; - mat3[4] = 0; - mat3[5] = 1; - mat3[6] = 0; - mat3[7] = 0; - mat3[8] = 0; - mat3[9] = 0; - mat3[10] = 1; - mat3[11] = 0; - mat3[12] = 0; - mat3[13] = 0; - mat3[14] = 0; - mat3[15] = 1; - return this; - }; - Matrix3d.prototype.clone = function () { - return new Matrix3d(this.mat4); - }; - Matrix3d.prototype.copyTo3d = function (matrix) { - var mat3 = this.mat4; - var ar2 = matrix.mat4; - ar2[0] = mat3[0]; - ar2[1] = mat3[1]; - ar2[2] = mat3[2]; - ar2[3] = mat3[3]; - ar2[4] = mat3[4]; - ar2[5] = mat3[5]; - ar2[6] = mat3[6]; - ar2[7] = mat3[7]; - ar2[8] = mat3[8]; - return matrix; - }; - Matrix3d.prototype.copyTo2d = function (matrix) { - var mat3 = this.mat4; - var ar2 = matrix.mat3; - ar2[0] = mat3[0]; - ar2[1] = mat3[1]; - ar2[2] = mat3[3]; - ar2[3] = mat3[4]; - ar2[4] = mat3[5]; - ar2[5] = mat3[7]; - ar2[6] = mat3[12]; - ar2[7] = mat3[13]; - ar2[8] = mat3[15]; - return matrix; - }; - Matrix3d.prototype.copyTo2dOr3d = function (matrix) { - if (matrix instanceof pixi_projection.Matrix2d) { - return this.copyTo2d(matrix); - } - else { - return this.copyTo3d(matrix); - } - }; - Matrix3d.prototype.copyTo = function (matrix, affine, preserveOrientation) { - var mat3 = this.mat4; - var d = 1.0 / mat3[15]; - var tx = mat3[12] * d, ty = mat3[13] * d; - matrix.a = (mat3[0] - mat3[3] * tx) * d; - matrix.b = (mat3[1] - mat3[3] * ty) * d; - matrix.c = (mat3[4] - mat3[7] * tx) * d; - matrix.d = (mat3[5] - mat3[7] * ty) * d; - matrix.tx = tx; - matrix.ty = ty; - if (affine >= 2) { - var D = matrix.a * matrix.d - matrix.b * matrix.c; - if (!preserveOrientation) { - D = Math.abs(D); - } - if (affine === pixi_projection.AFFINE.POINT) { - if (D > 0) { - D = 1; - } - else - D = -1; - matrix.a = D; - matrix.b = 0; - matrix.c = 0; - matrix.d = D; - } - else if (affine === pixi_projection.AFFINE.AXIS_X) { - D /= Math.sqrt(matrix.b * matrix.b + matrix.d * matrix.d); - matrix.c = 0; - matrix.d = D; - } - else if (affine === pixi_projection.AFFINE.AXIS_Y) { - D /= Math.sqrt(matrix.a * matrix.a + matrix.c * matrix.c); - matrix.a = D; - matrix.c = 0; - } - } - return matrix; - }; - Matrix3d.prototype.copyFrom = function (matrix) { - var mat3 = this.mat4; - mat3[0] = matrix.a; - mat3[1] = matrix.b; - mat3[2] = 0; - mat3[3] = 0; - mat3[4] = matrix.c; - mat3[5] = matrix.d; - mat3[6] = 0; - mat3[7] = 0; - mat3[8] = 0; - mat3[9] = 0; - mat3[10] = 1; - mat3[11] = 0; - mat3[12] = matrix.tx; - mat3[13] = matrix.ty; - mat3[14] = 0; - mat3[15] = 1; - this._dirtyId++; - return this; - }; - Matrix3d.prototype.setToMultLegacy = function (pt, lt) { - var out = this.mat4; - var b = lt.mat4; - var a00 = pt.a, a01 = pt.b, a10 = pt.c, a11 = pt.d, a30 = pt.tx, a31 = pt.ty; - var b0 = b[0], b1 = b[1], b2 = b[2], b3 = b[3]; - out[0] = b0 * a00 + b1 * a10 + b3 * a30; - out[1] = b0 * a01 + b1 * a11 + b3 * a31; - out[2] = b2; - out[3] = b3; - b0 = b[4]; - b1 = b[5]; - b2 = b[6]; - b3 = b[7]; - out[4] = b0 * a00 + b1 * a10 + b3 * a30; - out[5] = b0 * a01 + b1 * a11 + b3 * a31; - out[6] = b2; - out[7] = b3; - b0 = b[8]; - b1 = b[9]; - b2 = b[10]; - b3 = b[11]; - out[8] = b0 * a00 + b1 * a10 + b3 * a30; - out[9] = b0 * a01 + b1 * a11 + b3 * a31; - out[10] = b2; - out[11] = b3; - b0 = b[12]; - b1 = b[13]; - b2 = b[14]; - b3 = b[15]; - out[12] = b0 * a00 + b1 * a10 + b3 * a30; - out[13] = b0 * a01 + b1 * a11 + b3 * a31; - out[14] = b2; - out[15] = b3; - this._dirtyId++; - return this; - }; - Matrix3d.prototype.setToMultLegacy2 = function (pt, lt) { - var out = this.mat4; - var a = pt.mat4; - var a00 = a[0], a01 = a[1], a02 = a[2], a03 = a[3]; - var a10 = a[4], a11 = a[5], a12 = a[6], a13 = a[7]; - var b00 = lt.a, b01 = lt.b, b10 = lt.c, b11 = lt.d, b30 = lt.tx, b31 = lt.ty; - out[0] = b00 * a00 + b01 * a10; - out[1] = b00 * a01 + b01 * a11; - out[2] = b00 * a02 + b01 * a12; - out[3] = b00 * a03 + b01 * a13; - out[4] = b10 * a00 + b11 * a10; - out[5] = b10 * a01 + b11 * a11; - out[6] = b10 * a02 + b11 * a12; - out[7] = b10 * a03 + b11 * a13; - out[8] = a[8]; - out[9] = a[9]; - out[10] = a[10]; - out[11] = a[11]; - out[12] = b30 * a00 + b31 * a10 + a[12]; - out[13] = b30 * a01 + b31 * a11 + a[13]; - out[14] = b30 * a02 + b31 * a12 + a[14]; - out[15] = b30 * a03 + b31 * a13 + a[15]; - this._dirtyId++; - return this; - }; - Matrix3d.prototype.setToMult = function (pt, lt) { - Matrix3d.glMatrixMat4Multiply(this.mat4, pt.mat4, lt.mat4); - this._dirtyId++; - return this; - }; - Matrix3d.prototype.prepend = function (lt) { - if (lt.mat4) { - this.setToMult(lt, this); - } - else { - this.setToMultLegacy(lt, this); - } - }; - Matrix3d.glMatrixMat4Invert = function (out, a) { - var a00 = a[0], a01 = a[1], a02 = a[2], a03 = a[3]; - var a10 = a[4], a11 = a[5], a12 = a[6], a13 = a[7]; - var a20 = a[8], a21 = a[9], a22 = a[10], a23 = a[11]; - var a30 = a[12], a31 = a[13], a32 = a[14], a33 = a[15]; - var b00 = a00 * a11 - a01 * a10; - var b01 = a00 * a12 - a02 * a10; - var b02 = a00 * a13 - a03 * a10; - var b03 = a01 * a12 - a02 * a11; - var b04 = a01 * a13 - a03 * a11; - var b05 = a02 * a13 - a03 * a12; - var b06 = a20 * a31 - a21 * a30; - var b07 = a20 * a32 - a22 * a30; - var b08 = a20 * a33 - a23 * a30; - var b09 = a21 * a32 - a22 * a31; - var b10 = a21 * a33 - a23 * a31; - var b11 = a22 * a33 - a23 * a32; - var det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06; - if (!det) { - return null; - } - det = 1.0 / det; - out[0] = (a11 * b11 - a12 * b10 + a13 * b09) * det; - out[1] = (a02 * b10 - a01 * b11 - a03 * b09) * det; - out[2] = (a31 * b05 - a32 * b04 + a33 * b03) * det; - out[3] = (a22 * b04 - a21 * b05 - a23 * b03) * det; - out[4] = (a12 * b08 - a10 * b11 - a13 * b07) * det; - out[5] = (a00 * b11 - a02 * b08 + a03 * b07) * det; - out[6] = (a32 * b02 - a30 * b05 - a33 * b01) * det; - out[7] = (a20 * b05 - a22 * b02 + a23 * b01) * det; - out[8] = (a10 * b10 - a11 * b08 + a13 * b06) * det; - out[9] = (a01 * b08 - a00 * b10 - a03 * b06) * det; - out[10] = (a30 * b04 - a31 * b02 + a33 * b00) * det; - out[11] = (a21 * b02 - a20 * b04 - a23 * b00) * det; - out[12] = (a11 * b07 - a10 * b09 - a12 * b06) * det; - out[13] = (a00 * b09 - a01 * b07 + a02 * b06) * det; - out[14] = (a31 * b01 - a30 * b03 - a32 * b00) * det; - out[15] = (a20 * b03 - a21 * b01 + a22 * b00) * det; - return out; - }; - Matrix3d.glMatrixMat4Multiply = function (out, a, b) { - var a00 = a[0], a01 = a[1], a02 = a[2], a03 = a[3]; - var a10 = a[4], a11 = a[5], a12 = a[6], a13 = a[7]; - var a20 = a[8], a21 = a[9], a22 = a[10], a23 = a[11]; - var a30 = a[12], a31 = a[13], a32 = a[14], a33 = a[15]; - var b0 = b[0], b1 = b[1], b2 = b[2], b3 = b[3]; - out[0] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30; - out[1] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31; - out[2] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32; - out[3] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33; - b0 = b[4]; - b1 = b[5]; - b2 = b[6]; - b3 = b[7]; - out[4] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30; - out[5] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31; - out[6] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32; - out[7] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33; - b0 = b[8]; - b1 = b[9]; - b2 = b[10]; - b3 = b[11]; - out[8] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30; - out[9] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31; - out[10] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32; - out[11] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33; - b0 = b[12]; - b1 = b[13]; - b2 = b[14]; - b3 = b[15]; - out[12] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30; - out[13] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31; - out[14] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32; - out[15] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33; - return out; - }; - Matrix3d.IDENTITY = new Matrix3d(); - Matrix3d.TEMP_MATRIX = new Matrix3d(); - return Matrix3d; - }()); - pixi_projection.Matrix3d = Matrix3d; -})(pixi_projection || (pixi_projection = {})); -var pixi_projection; -(function (pixi_projection) { - var ObservableEuler = (function () { - function ObservableEuler(cb, scope, x, y, z) { - this.cb = cb; - this.scope = scope; - this._quatUpdateId = -1; - this._quatDirtyId = 0; - this._sign = 1; - this._x = x || 0; - this._y = y || 0; - this._z = z || 0; - this.quaternion = new Float64Array(4); - this.quaternion[3] = 1; - this.update(); - } - Object.defineProperty(ObservableEuler.prototype, "x", { - get: function () { - return this._x; - }, - set: function (value) { - if (this._x !== value) { - this._x = value; - this._quatDirtyId++; - this.cb.call(this.scope); - } - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(ObservableEuler.prototype, "y", { - get: function () { - return this._y; - }, - set: function (value) { - if (this._y !== value) { - this._y = value; - this._quatDirtyId++; - this.cb.call(this.scope); - } - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(ObservableEuler.prototype, "z", { - get: function () { - return this._z; - }, - set: function (value) { - if (this._z !== value) { - this._z = value; - this._quatDirtyId++; - this.cb.call(this.scope); - } - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(ObservableEuler.prototype, "pitch", { - get: function () { - return this._x; - }, - set: function (value) { - if (this._x !== value) { - this._x = value; - this._quatDirtyId++; - this.cb.call(this.scope); - } - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(ObservableEuler.prototype, "yaw", { - get: function () { - return this._y; - }, - set: function (value) { - if (this._y !== value) { - this._y = value; - this._quatDirtyId++; - this.cb.call(this.scope); - } - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(ObservableEuler.prototype, "roll", { - get: function () { - return this._z; - }, - set: function (value) { - if (this._z !== value) { - this._z = value; - this._quatDirtyId++; - this.cb.call(this.scope); - } - }, - enumerable: true, - configurable: true - }); - ObservableEuler.prototype.set = function (x, y, z) { - var _x = x || 0; - var _y = y || 0; - var _z = z || 0; - if (this._x !== _x || this._y !== _y || this._z !== _z) { - this._x = _x; - this._y = _y; - this._z = _z; - this._quatDirtyId++; - this.cb.call(this.scope); - } - }; - ; - ObservableEuler.prototype.copyFrom = function (euler) { - var _x = euler.x; - var _y = euler.y; - var _z = euler.z; - if (this._x !== _x || this._y !== _y || this._z !== _z) { - this._x = _x; - this._y = _y; - this._z = _z; - this._quatDirtyId++; - this.cb.call(this.scope); - } - }; - ObservableEuler.prototype.copyTo = function (p) { - p.set(this._x, this._y, this._z); - return p; - }; - ObservableEuler.prototype.equals = function (euler) { - return this._x === euler.x - && this._y === euler.y - && this._z === euler.z; - }; - ObservableEuler.prototype.clone = function () { - return new pixi_projection.Euler(this._x, this._y, this._z); - }; - ObservableEuler.prototype.update = function () { - if (this._quatUpdateId === this._quatDirtyId) { - return false; - } - this._quatUpdateId = this._quatDirtyId; - var c1 = Math.cos(this._x / 2); - var c2 = Math.cos(this._y / 2); - var c3 = Math.cos(this._z / 2); - var s = this._sign; - var s1 = s * Math.sin(this._x / 2); - var s2 = s * Math.sin(this._y / 2); - var s3 = s * Math.sin(this._z / 2); - var q = this.quaternion; - q[0] = s1 * c2 * c3 + c1 * s2 * s3; - q[1] = c1 * s2 * c3 - s1 * c2 * s3; - q[2] = c1 * c2 * s3 + s1 * s2 * c3; - q[3] = c1 * c2 * c3 - s1 * s2 * s3; - return true; - }; - return ObservableEuler; - }()); - pixi_projection.ObservableEuler = ObservableEuler; -})(pixi_projection || (pixi_projection = {})); -var pixi_projection; -(function (pixi_projection) { - var Point3d = (function (_super) { - __extends(Point3d, _super); - function Point3d(x, y, z) { - var _this = _super.call(this, x, y) || this; - _this.z = z; - return _this; - } - Point3d.prototype.set = function (x, y, z) { - this.x = x || 0; - this.y = (y === undefined) ? this.x : (y || 0); - this.z = (y === undefined) ? this.x : (z || 0); - }; - Point3d.prototype.copyFrom = function (p) { - this.set(p.x, p.y, p.z || 0); - return this; - }; - Point3d.prototype.copyTo = function (p) { - p.set(this.x, this.y, this.z); - return p; - }; - return Point3d; - }(PIXI.Point)); - pixi_projection.Point3d = Point3d; - var ObservablePoint3d = (function (_super) { - __extends(ObservablePoint3d, _super); - function ObservablePoint3d() { - var _this = _super !== null && _super.apply(this, arguments) || this; - _this._z = 0; - return _this; - } - Object.defineProperty(ObservablePoint3d.prototype, "z", { - get: function () { - return this._z; - }, - set: function (value) { - if (this._z !== value) { - this._z = value; - this.cb.call(this.scope); - } - }, - enumerable: true, - configurable: true - }); - ObservablePoint3d.prototype.set = function (x, y, z) { - var _x = x || 0; - var _y = (y === undefined) ? _x : (y || 0); - var _z = (y === undefined) ? _x : (z || 0); - if (this._x !== _x || this._y !== _y || this._z !== _z) { - this._x = _x; - this._y = _y; - this._z = _z; - this.cb.call(this.scope); - } - }; - ObservablePoint3d.prototype.copyFrom = function (p) { - this.set(p.x, p.y, p.z || 0); - return this; - }; - ObservablePoint3d.prototype.copyTo = function (p) { - p.set(this._x, this._y, this._z); - return p; - }; - return ObservablePoint3d; - }(PIXI.ObservablePoint)); - pixi_projection.ObservablePoint3d = ObservablePoint3d; -})(pixi_projection || (pixi_projection = {})); -var pixi_projection; -(function (pixi_projection) { - var tempMat = new pixi_projection.Matrix3d(); - var Projection3d = (function (_super) { - __extends(Projection3d, _super); - function Projection3d(legacy, enable) { - var _this = _super.call(this, legacy, enable) || this; - _this.cameraMatrix = null; - _this._cameraMode = false; - _this.position = new pixi_projection.ObservablePoint3d(_this.onChange, _this, 0, 0); - _this.scale = new pixi_projection.ObservablePoint3d(_this.onChange, _this, 1, 1); - _this.euler = new pixi_projection.ObservableEuler(_this.onChange, _this, 0, 0, 0); - _this.pivot = new pixi_projection.ObservablePoint3d(_this.onChange, _this, 0, 0); - _this.local = new pixi_projection.Matrix3d(); - _this.world = new pixi_projection.Matrix3d(); - _this.local.cacheInverse = true; - _this.world.cacheInverse = true; - _this.position._z = 0; - _this.scale._z = 1; - _this.pivot._z = 0; - return _this; - } - Object.defineProperty(Projection3d.prototype, "cameraMode", { - get: function () { - return this._cameraMode; - }, - set: function (value) { - if (this._cameraMode === value) { - return; - } - this._cameraMode = value; - this.euler._sign = this._cameraMode ? -1 : 1; - this.euler._quatDirtyId++; - if (value) { - this.cameraMatrix = new pixi_projection.Matrix3d(); - } - }, - enumerable: true, - configurable: true - }); - Projection3d.prototype.onChange = function () { - this._projID++; - }; - Projection3d.prototype.clear = function () { - if (this.cameraMatrix) { - this.cameraMatrix.identity(); - } - this.position.set(0, 0, 0); - this.scale.set(1, 1, 1); - this.euler.set(0, 0, 0); - this.pivot.set(0, 0, 0); - _super.prototype.clear.call(this); - }; - Projection3d.prototype.updateLocalTransform = function (lt) { - if (this._projID === 0) { - this.local.copyFrom(lt); - return; - } - var matrix = this.local; - var euler = this.euler; - var pos = this.position; - var scale = this.scale; - var pivot = this.pivot; - euler.update(); - if (!this.cameraMode) { - matrix.setToRotationTranslationScale(euler.quaternion, pos._x, pos._y, pos._z, scale._x, scale._y, scale._z); - matrix.translate(-pivot._x, -pivot._y, -pivot._z); - matrix.setToMultLegacy(lt, matrix); - return; - } - matrix.setToMultLegacy(lt, this.cameraMatrix); - matrix.translate(pivot._x, pivot._y, pivot._z); - matrix.scale(1.0 / scale._x, 1.0 / scale._y, 1.0 / scale._z); - tempMat.setToRotationTranslationScale(euler.quaternion, 0, 0, 0, 1, 1, 1); - matrix.setToMult(matrix, tempMat); - matrix.translate(-pos._x, -pos._y, -pos._z); - this.local._dirtyId++; - }; - return Projection3d; - }(pixi_projection.LinearProjection)); - pixi_projection.Projection3d = Projection3d; -})(pixi_projection || (pixi_projection = {})); -var pixi_projection; -(function (pixi_projection) { - var Mesh3d2d = (function (_super) { - __extends(Mesh3d2d, _super); - function Mesh3d2d(geometry, shader, state, drawMode) { - var _this = _super.call(this, geometry, shader, state, drawMode) || this; - _this.vertexData2d = null; - _this.proj = new pixi_projection.Projection3d(_this.transform); - return _this; - } - Mesh3d2d.prototype.calculateVertices = function () { - if (this.proj._affine) { - this.vertexData2d = null; - _super.prototype.calculateVertices.call(this); - return; - } - var geometry = this.geometry; - var vertices = geometry.buffers[0].data; - var thisAny = this; - if (geometry.vertexDirtyId === thisAny.vertexDirty && thisAny._transformID === thisAny.transform._worldID) { - return; - } - thisAny._transformID = thisAny.transform._worldID; - if (thisAny.vertexData.length !== vertices.length) { - thisAny.vertexData = new Float32Array(vertices.length); - } - if (this.vertexData2d.length !== vertices.length * 3 / 2) { - this.vertexData2d = new Float32Array(vertices.length * 3); - } - var wt = this.proj.world.mat4; - var vertexData2d = this.vertexData2d; - var vertexData = thisAny.vertexData; - for (var i = 0; i < vertexData.length / 2; i++) { - var x = vertices[(i * 2)]; - var y = vertices[(i * 2) + 1]; - var xx = (wt[0] * x) + (wt[4] * y) + wt[12]; - var yy = (wt[1] * x) + (wt[5] * y) + wt[13]; - var ww = (wt[3] * x) + (wt[7] * y) + wt[15]; - vertexData2d[i * 3] = xx; - vertexData2d[i * 3 + 1] = yy; - vertexData2d[i * 3 + 2] = ww; - vertexData[(i * 2)] = xx / ww; - vertexData[(i * 2) + 1] = yy / ww; - } - thisAny.vertexDirty = geometry.vertexDirtyId; - }; - Object.defineProperty(Mesh3d2d.prototype, "worldTransform", { - get: function () { - return this.proj.affine ? this.transform.worldTransform : this.proj.world; - }, - enumerable: true, - configurable: true - }); - Mesh3d2d.prototype.toLocal = function (position, from, point, skipUpdate, step) { - if (step === void 0) { step = pixi_projection.TRANSFORM_STEP.ALL; } - return pixi_projection.container3dToLocal.call(this, position, from, point, skipUpdate, step); - }; - Mesh3d2d.prototype.isFrontFace = function (forceUpdate) { - return pixi_projection.container3dIsFrontFace.call(this, forceUpdate); - }; - Mesh3d2d.prototype.getDepth = function (forceUpdate) { - return pixi_projection.container3dGetDepth.call(this, forceUpdate); - }; - Object.defineProperty(Mesh3d2d.prototype, "position3d", { - get: function () { - return this.proj.position; - }, - set: function (value) { - this.proj.position.copyFrom(value); - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Mesh3d2d.prototype, "scale3d", { - get: function () { - return this.proj.scale; - }, - set: function (value) { - this.proj.scale.copyFrom(value); - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Mesh3d2d.prototype, "euler", { - get: function () { - return this.proj.euler; - }, - set: function (value) { - this.proj.euler.copyFrom(value); - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Mesh3d2d.prototype, "pivot3d", { - get: function () { - return this.proj.pivot; - }, - set: function (value) { - this.proj.pivot.copyFrom(value); - }, - enumerable: true, - configurable: true - }); - return Mesh3d2d; - }(PIXI.Mesh)); - pixi_projection.Mesh3d2d = Mesh3d2d; - Mesh3d2d.prototype._renderDefault = pixi_projection.Mesh2d.prototype._renderDefault; - var SimpleMesh3d2d = (function (_super) { - __extends(SimpleMesh3d2d, _super); - function SimpleMesh3d2d(texture, vertices, uvs, indices, drawMode) { - var _this = _super.call(this, new PIXI.MeshGeometry(vertices, uvs, indices), new PIXI.MeshMaterial(texture, { - program: PIXI.Program.from(pixi_projection.Mesh2d.defaultVertexShader, pixi_projection.Mesh2d.defaultFragmentShader), - pluginName: 'batch2d' - }), null, drawMode) || this; - _this.autoUpdate = true; - _this.geometry.getBuffer('aVertexPosition').static = false; - return _this; - } - Object.defineProperty(SimpleMesh3d2d.prototype, "vertices", { - get: function () { - return this.geometry.getBuffer('aVertexPosition').data; - }, - set: function (value) { - this.geometry.getBuffer('aVertexPosition').data = value; - }, - enumerable: true, - configurable: true - }); - SimpleMesh3d2d.prototype._render = function (renderer) { - if (this.autoUpdate) { - this.geometry.getBuffer('aVertexPosition').update(); - } - _super.prototype._render.call(this, renderer); - }; - return SimpleMesh3d2d; - }(Mesh3d2d)); - pixi_projection.SimpleMesh3d2d = SimpleMesh3d2d; -})(pixi_projection || (pixi_projection = {})); -var pixi_projection; -(function (pixi_projection) { - var Sprite3d = (function (_super) { - __extends(Sprite3d, _super); - function Sprite3d(texture) { - var _this = _super.call(this, texture) || this; - _this.vertexData2d = null; - _this.culledByFrustrum = false; - _this.trimmedCulledByFrustrum = false; - _this.proj = new pixi_projection.Projection3d(_this.transform); - _this.pluginName = 'batch2d'; - return _this; - } - Sprite3d.prototype.calculateVertices = function () { - var texture = this._texture; - if (this.proj._affine) { - this.vertexData2d = null; - _super.prototype.calculateVertices.call(this); - return; - } - if (!this.vertexData2d) { - this.vertexData2d = new Float32Array(12); - } - var wid = this.transform._worldID; - var tuid = texture._updateID; - if (this._transformID === wid && this._textureID === tuid) { - return; - } - if (this._textureID !== tuid) { - this.uvs = texture._uvs.uvsFloat32; - } - this._transformID = wid; - this._textureID = tuid; - var wt = this.proj.world.mat4; - var vertexData2d = this.vertexData2d; - var vertexData = this.vertexData; - var trim = texture.trim; - var orig = texture.orig; - var anchor = this._anchor; - var w0 = 0; - var w1 = 0; - var h0 = 0; - var h1 = 0; - if (trim) { - w1 = trim.x - (anchor._x * orig.width); - w0 = w1 + trim.width; - h1 = trim.y - (anchor._y * orig.height); - h0 = h1 + trim.height; - } - else { - w1 = -anchor._x * orig.width; - w0 = w1 + orig.width; - h1 = -anchor._y * orig.height; - h0 = h1 + orig.height; - } - var culled = false; - var z; - vertexData2d[0] = (wt[0] * w1) + (wt[4] * h1) + wt[12]; - vertexData2d[1] = (wt[1] * w1) + (wt[5] * h1) + wt[13]; - z = (wt[2] * w1) + (wt[6] * h1) + wt[14]; - vertexData2d[2] = (wt[3] * w1) + (wt[7] * h1) + wt[15]; - culled = culled || z < 0; - vertexData2d[3] = (wt[0] * w0) + (wt[4] * h1) + wt[12]; - vertexData2d[4] = (wt[1] * w0) + (wt[5] * h1) + wt[13]; - z = (wt[2] * w0) + (wt[6] * h1) + wt[14]; - vertexData2d[5] = (wt[3] * w0) + (wt[7] * h1) + wt[15]; - culled = culled || z < 0; - vertexData2d[6] = (wt[0] * w0) + (wt[4] * h0) + wt[12]; - vertexData2d[7] = (wt[1] * w0) + (wt[5] * h0) + wt[13]; - z = (wt[2] * w0) + (wt[6] * h0) + wt[14]; - vertexData2d[8] = (wt[3] * w0) + (wt[7] * h0) + wt[15]; - culled = culled || z < 0; - vertexData2d[9] = (wt[0] * w1) + (wt[4] * h0) + wt[12]; - vertexData2d[10] = (wt[1] * w1) + (wt[5] * h0) + wt[13]; - z = (wt[2] * w1) + (wt[6] * h0) + wt[14]; - vertexData2d[11] = (wt[3] * w1) + (wt[7] * h0) + wt[15]; - culled = culled || z < 0; - this.culledByFrustrum = culled; - vertexData[0] = vertexData2d[0] / vertexData2d[2]; - vertexData[1] = vertexData2d[1] / vertexData2d[2]; - vertexData[2] = vertexData2d[3] / vertexData2d[5]; - vertexData[3] = vertexData2d[4] / vertexData2d[5]; - vertexData[4] = vertexData2d[6] / vertexData2d[8]; - vertexData[5] = vertexData2d[7] / vertexData2d[8]; - vertexData[6] = vertexData2d[9] / vertexData2d[11]; - vertexData[7] = vertexData2d[10] / vertexData2d[11]; - }; - Sprite3d.prototype.calculateTrimmedVertices = function () { - if (this.proj._affine) { - _super.prototype.calculateTrimmedVertices.call(this); - return; - } - var wid = this.transform._worldID; - var tuid = this._texture._updateID; - if (!this.vertexTrimmedData) { - this.vertexTrimmedData = new Float32Array(8); - } - else if (this._transformTrimmedID === wid && this._textureTrimmedID === tuid) { - return; - } - this._transformTrimmedID = wid; - this._textureTrimmedID = tuid; - var texture = this._texture; - var vertexData = this.vertexTrimmedData; - var orig = texture.orig; - var anchor = this._anchor; - var wt = this.proj.world.mat4; - var w1 = -anchor._x * orig.width; - var w0 = w1 + orig.width; - var h1 = -anchor._y * orig.height; - var h0 = h1 + orig.height; - var culled = false; - var z; - var w = 1.0 / ((wt[3] * w1) + (wt[7] * h1) + wt[15]); - vertexData[0] = w * ((wt[0] * w1) + (wt[4] * h1) + wt[12]); - vertexData[1] = w * ((wt[1] * w1) + (wt[5] * h1) + wt[13]); - z = (wt[2] * w1) + (wt[6] * h1) + wt[14]; - culled = culled || z < 0; - w = 1.0 / ((wt[3] * w0) + (wt[7] * h1) + wt[15]); - vertexData[2] = w * ((wt[0] * w0) + (wt[4] * h1) + wt[12]); - vertexData[3] = w * ((wt[1] * w0) + (wt[5] * h1) + wt[13]); - z = (wt[2] * w0) + (wt[6] * h1) + wt[14]; - culled = culled || z < 0; - w = 1.0 / ((wt[3] * w0) + (wt[7] * h0) + wt[15]); - vertexData[4] = w * ((wt[0] * w0) + (wt[4] * h0) + wt[12]); - vertexData[5] = w * ((wt[1] * w0) + (wt[5] * h0) + wt[13]); - z = (wt[2] * w0) + (wt[6] * h0) + wt[14]; - culled = culled || z < 0; - w = 1.0 / ((wt[3] * w1) + (wt[7] * h0) + wt[15]); - vertexData[6] = w * ((wt[0] * w1) + (wt[4] * h0) + wt[12]); - vertexData[7] = w * ((wt[1] * w1) + (wt[5] * h0) + wt[13]); - z = (wt[2] * w1) + (wt[6] * h0) + wt[14]; - culled = culled || z < 0; - this.culledByFrustrum = culled; - }; - Sprite3d.prototype._calculateBounds = function () { - this.calculateVertices(); - if (this.culledByFrustrum) { - return; - } - var trim = this._texture.trim; - var orig = this._texture.orig; - if (!trim || (trim.width === orig.width && trim.height === orig.height)) { - this._bounds.addQuad(this.vertexData); - return; - } - this.calculateTrimmedVertices(); - if (!this.trimmedCulledByFrustrum) { - this._bounds.addQuad(this.vertexTrimmedData); - } - }; - Sprite3d.prototype._render = function (renderer) { - this.calculateVertices(); - if (this.culledByFrustrum) { - return; - } - renderer.batch.setObjectRenderer(renderer.plugins[this.pluginName]); - renderer.plugins[this.pluginName].render(this); - }; - Sprite3d.prototype.containsPoint = function (point) { - if (this.culledByFrustrum) { - return false; - } - return _super.prototype.containsPoint.call(this, point); - }; - Object.defineProperty(Sprite3d.prototype, "worldTransform", { - get: function () { - return this.proj.affine ? this.transform.worldTransform : this.proj.world; - }, - enumerable: true, - configurable: true - }); - Sprite3d.prototype.toLocal = function (position, from, point, skipUpdate, step) { - if (step === void 0) { step = pixi_projection.TRANSFORM_STEP.ALL; } - return pixi_projection.container3dToLocal.call(this, position, from, point, skipUpdate, step); - }; - Sprite3d.prototype.isFrontFace = function (forceUpdate) { - return pixi_projection.container3dIsFrontFace.call(this, forceUpdate); - }; - Sprite3d.prototype.getDepth = function (forceUpdate) { - return pixi_projection.container3dGetDepth.call(this, forceUpdate); - }; - Object.defineProperty(Sprite3d.prototype, "position3d", { - get: function () { - return this.proj.position; - }, - set: function (value) { - this.proj.position.copyFrom(value); - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Sprite3d.prototype, "scale3d", { - get: function () { - return this.proj.scale; - }, - set: function (value) { - this.proj.scale.copyFrom(value); - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Sprite3d.prototype, "euler", { - get: function () { - return this.proj.euler; - }, - set: function (value) { - this.proj.euler.copyFrom(value); - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Sprite3d.prototype, "pivot3d", { - get: function () { - return this.proj.pivot; - }, - set: function (value) { - this.proj.pivot.copyFrom(value); - }, - enumerable: true, - configurable: true - }); - return Sprite3d; - }(PIXI.Sprite)); - pixi_projection.Sprite3d = Sprite3d; -})(pixi_projection || (pixi_projection = {})); -var pixi_projection; -(function (pixi_projection) { - var Text3d = (function (_super) { - __extends(Text3d, _super); - function Text3d(text, style, canvas) { - var _this = _super.call(this, text, style, canvas) || this; - _this.vertexData2d = null; - _this.proj = new pixi_projection.Projection3d(_this.transform); - _this.pluginName = 'batch2d'; - return _this; - } - Object.defineProperty(Text3d.prototype, "worldTransform", { - get: function () { - return this.proj.affine ? this.transform.worldTransform : this.proj.world; - }, - enumerable: true, - configurable: true - }); - Text3d.prototype.toLocal = function (position, from, point, skipUpdate, step) { - if (step === void 0) { step = pixi_projection.TRANSFORM_STEP.ALL; } - return pixi_projection.container3dToLocal.call(this, position, from, point, skipUpdate, step); - }; - Text3d.prototype.isFrontFace = function (forceUpdate) { - return pixi_projection.container3dIsFrontFace.call(this, forceUpdate); - }; - Text3d.prototype.getDepth = function (forceUpdate) { - return pixi_projection.container3dGetDepth.call(this, forceUpdate); - }; - Object.defineProperty(Text3d.prototype, "position3d", { - get: function () { - return this.proj.position; - }, - set: function (value) { - this.proj.position.copyFrom(value); - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Text3d.prototype, "scale3d", { - get: function () { - return this.proj.scale; - }, - set: function (value) { - this.proj.scale.copyFrom(value); - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Text3d.prototype, "euler", { - get: function () { - return this.proj.euler; - }, - set: function (value) { - this.proj.euler.copyFrom(value); - }, - enumerable: true, - configurable: true - }); - Object.defineProperty(Text3d.prototype, "pivot3d", { - get: function () { - return this.proj.pivot; - }, - set: function (value) { - this.proj.pivot.copyFrom(value); - }, - enumerable: true, - configurable: true - }); - return Text3d; - }(PIXI.Text)); - pixi_projection.Text3d = Text3d; - Text3d.prototype.calculateVertices = pixi_projection.Sprite3d.prototype.calculateVertices; - Text3d.prototype.calculateTrimmedVertices = pixi_projection.Sprite3d.prototype.calculateTrimmedVertices; - Text3d.prototype._calculateBounds = pixi_projection.Sprite3d.prototype._calculateBounds; - Text3d.prototype.containsPoint = pixi_projection.Sprite3d.prototype.containsPoint; - Text3d.prototype._render = pixi_projection.Sprite3d.prototype._render; -})(pixi_projection || (pixi_projection = {})); -var pixi_projection; -(function (pixi_projection) { - var containerProps = { - worldTransform: { - get: pixi_projection.container3dWorldTransform, - enumerable: true, - configurable: true - }, - position3d: { - get: function () { return this.proj.position; }, - set: function (value) { this.proj.position.copy(value); } - }, - scale3d: { - get: function () { return this.proj.scale; }, - set: function (value) { this.proj.scale.copy(value); } - }, - pivot3d: { - get: function () { return this.proj.pivot; }, - set: function (value) { this.proj.pivot.copy(value); } - }, - euler: { - get: function () { return this.proj.euler; }, - set: function (value) { this.proj.euler.copy(value); } - } - }; - function convertTo3d() { - if (this.proj) - return; - this.proj = new pixi_projection.Projection3d(this.transform); - this.toLocal = pixi_projection.Container3d.prototype.toLocal; - this.isFrontFace = pixi_projection.Container3d.prototype.isFrontFace; - this.getDepth = pixi_projection.Container3d.prototype.getDepth; - Object.defineProperties(this, containerProps); - } - PIXI.Container.prototype.convertTo3d = convertTo3d; - PIXI.Sprite.prototype.convertTo3d = function () { - if (this.proj) - return; - this.calculateVertices = pixi_projection.Sprite3d.prototype.calculateVertices; - this.calculateTrimmedVertices = pixi_projection.Sprite3d.prototype.calculateTrimmedVertices; - this._calculateBounds = pixi_projection.Sprite3d.prototype._calculateBounds; - this.containsPoint = pixi_projection.Sprite3d.prototype.containsPoint; - this.pluginName = 'batch2d'; - convertTo3d.call(this); - }; - PIXI.Container.prototype.convertSubtreeTo3d = function () { - this.convertTo3d(); - for (var i = 0; i < this.children.length; i++) { - this.children[i].convertSubtreeTo3d(); - } - }; - if (PIXI.SimpleMesh) { - PIXI.SimpleMesh.prototype.convertTo3d = - PIXI.SimpleRope.prototype.convertTo3d = - function () { - if (this.proj) - return; - this.calculateVertices = pixi_projection.Mesh3d2d.prototype.calculateVertices; - this._renderDefault = pixi_projection.Mesh3d2d.prototype._renderDefault; - if (this.material.pluginName !== 'batch2d') { - this.material = new PIXI.MeshMaterial(this.material.texture, { - program: PIXI.Program.from(pixi_projection.Mesh2d.defaultVertexShader, pixi_projection.Mesh2d.defaultFragmentShader), - pluginName: 'batch2d' - }); - } - convertTo3d.call(this); - }; - } -})(pixi_projection || (pixi_projection = {})); + return LinkedListContainer; + }(pixi.Container)); + + exports.AnimatedParticle = AnimatedParticle; + exports.Emitter = Emitter; + exports.GetTextureFromString = GetTextureFromString; + exports.LinkedListContainer = LinkedListContainer; + exports.Particle = Particle; + exports.PathParticle = PathParticle; + exports.PolygonalChain = PolygonalChain; + exports.PropertyList = PropertyList; + exports.PropertyNode = PropertyNode; + +}(this.PIXI.particles = this.PIXI.particles || {}, PIXI)); + + +/* eslint-disable */ + +/*! + * pixi-projection - v0.4.4 + * Compiled Mon, 10 Jan 2022 19:51:04 UTC + * + * pixi-projection is licensed under the MIT License. + * http://www.opensource.org/licenses/mit-license + * + * Copyright 2019-2020, Ivan Popelyshev, All Rights Reserved + */ +this.PIXI = this.PIXI || {}; +this.PIXI.projection = this.PIXI.projection || {}; +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('@pixi/core'), require('@pixi/constants'), require('@pixi/utils'), require('@pixi/math'), require('@pixi/display'), require('@pixi/sprite-tiling'), require('@pixi/mesh'), require('@pixi/mesh-extras'), require('@pixi/sprite'), require('@pixi/text'), require('@pixi/graphics')) : + typeof define === 'function' && define.amd ? define(['exports', '@pixi/core', '@pixi/constants', '@pixi/utils', '@pixi/math', '@pixi/display', '@pixi/sprite-tiling', '@pixi/mesh', '@pixi/mesh-extras', '@pixi/sprite', '@pixi/text', '@pixi/graphics'], factory) : + (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.pixi_projection = {}, global.PIXI, global.PIXI, global.PIXI.utils, global.PIXI, global.PIXI, global.PIXI, global.PIXI, global.PIXI, global.PIXI, global.PIXI, global.PIXI)); +}(this, (function (exports, core, constants, utils, math, display, spriteTiling, mesh, meshExtras, sprite, text, graphics) { 'use strict'; + + const shaderVert$2 + = `precision highp float; +attribute vec3 aVertexPosition; +attribute vec2 aTextureCoord; +attribute vec4 aColor; +attribute float aTextureId; + +uniform mat3 projectionMatrix; + +varying vec2 vTextureCoord; +varying vec4 vColor; +varying float vTextureId; + +void main(void){ +gl_Position.xyw = projectionMatrix * aVertexPosition; +gl_Position.z = 0.0; + +vTextureCoord = aTextureCoord; +vTextureId = aTextureId; +vColor = aColor; +} +`; + const shaderFrag$2 = ` +varying vec2 vTextureCoord; +varying vec4 vColor; +varying float vTextureId; +uniform sampler2D uSamplers[%count%]; + +void main(void){ +vec4 color; +%forloop% +gl_FragColor = color * vColor; +}`; + + class Batch3dGeometry extends core.Geometry + { + + + + constructor(_static = false) + { + super(); + + this._buffer = new core.Buffer(null, _static, false); + + this._indexBuffer = new core.Buffer(null, _static, true); + + this.addAttribute('aVertexPosition', this._buffer, 3, false, constants.TYPES.FLOAT) + .addAttribute('aTextureCoord', this._buffer, 2, false, constants.TYPES.FLOAT) + .addAttribute('aColor', this._buffer, 4, true, constants.TYPES.UNSIGNED_BYTE) + .addAttribute('aTextureId', this._buffer, 1, true, constants.TYPES.FLOAT) + .addIndex(this._indexBuffer); + } + } + + class Batch2dPluginFactory + { + // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types + static create(options) + { + const { vertex, fragment, vertexSize, geometryClass } = (Object ).assign({ + vertex: shaderVert$2, + fragment: shaderFrag$2, + geometryClass: Batch3dGeometry, + vertexSize: 7, + }, options); + + return class BatchPlugin extends core.AbstractBatchRenderer + { + constructor(renderer) + { + super(renderer); + + this.shaderGenerator = new core.BatchShaderGenerator(vertex, fragment); + this.geometryClass = geometryClass; + this.vertexSize = vertexSize; + } + + + + // eslint-disable-next-line max-len + packInterleavedGeometry(element, attributeBuffer, indexBuffer, aIndex, iIndex) + { + const { + uint32View, + float32View, + } = attributeBuffer; + + const p = aIndex / this.vertexSize;// float32View.length / 6 / 2; + const uvs = element.uvs; + const indices = element.indices;// geometry.getIndex().data;// indicies; + const vertexData = element.vertexData; + const vertexData2d = element.vertexData2d; + const textureId = element._texture.baseTexture._batchLocation; + + const alpha = Math.min(element.worldAlpha, 1.0); + + const argb = alpha < 1.0 && element._texture.baseTexture.alphaMode ? utils.premultiplyTint(element._tintRGB, alpha) + : element._tintRGB + (alpha * 255 << 24); + + if (vertexData2d) + { + let j = 0; + + for (let i = 0; i < vertexData2d.length; i += 3, j += 2) + { + float32View[aIndex++] = vertexData2d[i]; + float32View[aIndex++] = vertexData2d[i + 1]; + float32View[aIndex++] = vertexData2d[i + 2]; + float32View[aIndex++] = uvs[j]; + float32View[aIndex++] = uvs[j + 1]; + uint32View[aIndex++] = argb; + float32View[aIndex++] = textureId; + } + } + else + { + for (let i = 0; i < vertexData.length; i += 2) + { + float32View[aIndex++] = vertexData[i]; + float32View[aIndex++] = vertexData[i + 1]; + float32View[aIndex++] = 1.0; + float32View[aIndex++] = uvs[i]; + float32View[aIndex++] = uvs[i + 1]; + uint32View[aIndex++] = argb; + float32View[aIndex++] = textureId; + } + } + + for (let i = 0; i < indices.length; i++) + { + indexBuffer[iIndex++] = p + indices[i]; + } + } + }; + } + } + + class AbstractProjection + { + constructor(legacy, enable = true) + {;AbstractProjection.prototype.__init.call(this); + this.legacy = legacy; + + if (enable) + { + this.enabled = true; + } + + // sorry for hidden class, it would be good to have special projection field in official pixi + // TODO: pixi 6.1.0 global mixin + (this.legacy ).proj = this; + } + + + + __init() {this._enabled = false;} + + get enabled() + { + return this._enabled; + } + + set enabled(value) + { + this._enabled = value; + } + + clear() + // eslint-disable-next-line @typescript-eslint/no-empty-function + { + } + } + + exports.TRANSFORM_STEP = void 0; (function (TRANSFORM_STEP) { + const NONE = 0; TRANSFORM_STEP[TRANSFORM_STEP["NONE"] = NONE] = "NONE"; + // POS = 1, + // ROT = 2, + // SCALE = 3, + // PIVOT = 4, + const BEFORE_PROJ = 4; TRANSFORM_STEP[TRANSFORM_STEP["BEFORE_PROJ"] = BEFORE_PROJ] = "BEFORE_PROJ"; + const PROJ = 5; TRANSFORM_STEP[TRANSFORM_STEP["PROJ"] = PROJ] = "PROJ"; + // POS_2 = 6, + // ROT_2 = 7, + // SCALE_2 = 8, + // PIVOT_2 = 9, + const ALL = 9; TRANSFORM_STEP[TRANSFORM_STEP["ALL"] = ALL] = "ALL"; + })(exports.TRANSFORM_STEP || (exports.TRANSFORM_STEP = {})); + + exports.AFFINE = void 0; (function (AFFINE) { + const NONE = 0; AFFINE[AFFINE["NONE"] = NONE] = "NONE"; + const FREE = 1; AFFINE[AFFINE["FREE"] = FREE] = "FREE"; + const AXIS_X = 2; AFFINE[AFFINE["AXIS_X"] = AXIS_X] = "AXIS_X"; + const AXIS_Y = 3; AFFINE[AFFINE["AXIS_Y"] = AXIS_Y] = "AXIS_Y"; + const POINT = 4; AFFINE[AFFINE["POINT"] = POINT] = "POINT"; + const AXIS_XR = 5; AFFINE[AFFINE["AXIS_XR"] = AXIS_XR] = "AXIS_XR"; + })(exports.AFFINE || (exports.AFFINE = {})); + + function transformHack$1( parentTransform) + { + // implementation here + // TODO: pixi 6.1.0 global mixin + const proj = (this ).proj ; + const ta = this ; + const pwid = (parentTransform )._worldID; + + const lt = ta.localTransform; + const scaleAfterAffine = proj.scaleAfterAffine && proj.affine >= 2; + + // this part is copied from + if (ta._localID !== ta._currentLocalID) + { + // get the matrix values of the displayobject based on its transform properties.. + if (scaleAfterAffine) + { + lt.a = ta._cx; + lt.b = ta._sx; + lt.c = ta._cy; + lt.d = ta._sy; + + lt.tx = ta.position._x; + lt.ty = ta.position._y; + } + else + { + lt.a = ta._cx * ta.scale._x; + lt.b = ta._sx * ta.scale._x; + lt.c = ta._cy * ta.scale._y; + lt.d = ta._sy * ta.scale._y; + + lt.tx = ta.position._x - ((ta.pivot._x * lt.a) + (ta.pivot._y * lt.c)); + lt.ty = ta.position._y - ((ta.pivot._x * lt.b) + (ta.pivot._y * lt.d)); + } + + ta._currentLocalID = ta._localID; + + // force an update.. + proj._currentProjID = -1; + } + + const _matrixID = proj._projID; + + if (proj._currentProjID !== _matrixID) + { + proj._currentProjID = _matrixID; + proj.updateLocalTransform(lt); + ta._parentID = -1; + } + + if (ta._parentID !== pwid) + { + // TODO: pixi 6.1.0 global mixin + const pp = (parentTransform ).proj ; + + if (pp && !pp._affine) + { + proj.world.setToMult(pp.world, proj.local); + } + else + { + proj.world.setToMultLegacy(parentTransform.worldTransform, proj.local); + } + + const wa = ta.worldTransform; + + proj.world.copyTo(wa, proj._affine, proj.affinePreserveOrientation); + + if (scaleAfterAffine) + { + wa.a *= ta.scale._x; + wa.b *= ta.scale._x; + wa.c *= ta.scale._y; + wa.d *= ta.scale._y; + + wa.tx -= ((ta.pivot._x * wa.a) + (ta.pivot._y * wa.c)); + wa.ty -= ((ta.pivot._x * wa.b) + (ta.pivot._y * wa.d)); + } + ta._parentID = pwid; + ta._worldID++; + } + } + + class LinearProjection extends AbstractProjection + {constructor(...args) { super(...args); LinearProjection.prototype.__init.call(this);LinearProjection.prototype.__init2.call(this);LinearProjection.prototype.__init3.call(this);LinearProjection.prototype.__init4.call(this);LinearProjection.prototype.__init5.call(this); } + // eslint-disable-next-line @typescript-eslint/no-unused-vars + updateLocalTransform(lt) + // eslint-disable-next-line @typescript-eslint/no-empty-function + { + } + + __init() {this._projID = 0;} + __init2() {this._currentProjID = -1;} + __init3() {this._affine = exports.AFFINE.NONE;} + __init4() {this.affinePreserveOrientation = false;} + __init5() {this.scaleAfterAffine = true;} + + set affine(value) + { + if (this._affine === value) return; + this._affine = value; + this._currentProjID = -1; + // this is because scaleAfterAffine + (this.legacy )._currentLocalID = -1; + } + + get affine() + { + return this._affine; + } + + + + + // eslint-disable-next-line accessor-pairs + set enabled(value) + { + if (value === this._enabled) + { + return; + } + this._enabled = value; + if (value) + { + this.legacy.updateTransform = transformHack$1; + (this.legacy )._parentID = -1; + } + else + { + this.legacy.updateTransform = math.Transform.prototype.updateTransform; + (this.legacy )._parentID = -1; + } + } + + clear() + { + this._currentProjID = -1; + this._projID = 0; + } + } + + class UniformBatchRenderer extends core.AbstractBatchRenderer + {constructor(...args) { super(...args); UniformBatchRenderer.prototype.__init.call(this);UniformBatchRenderer.prototype.__init2.call(this); } + + + + + + + + __init() {this.forceMaxTextures = 0;} + + // eslint-disable-next-line @typescript-eslint/no-unused-vars + getUniforms(sprite) + { + return this.defUniforms; + } + + syncUniforms(obj) + { + if (!obj) return; + const sh = this._shader; + + for (const key in obj) + { + sh.uniforms[key] = obj[key]; + } + } + + __init2() {this.defUniforms = {};} + + buildDrawCalls(texArray, start, finish) + { + const thisAny = this ; + + const { + _bufferedElements: elements, + _attributeBuffer, + _indexBuffer, + vertexSize, + } = this; + const drawCalls = core.AbstractBatchRenderer._drawCallPool; + + let dcIndex = this._dcIndex; + let aIndex = this._aIndex; + let iIndex = this._iIndex; + + let drawCall = drawCalls[dcIndex] ; + + drawCall.start = this._iIndex; + drawCall.texArray = texArray; + + for (let i = start; i < finish; ++i) + { + const sprite = elements[i]; + const tex = sprite._texture.baseTexture; + const spriteBlendMode = utils.premultiplyBlendMode[ + tex.alphaMode ? 1 : 0][sprite.blendMode]; + const uniforms = this.getUniforms(sprite); + + elements[i] = null; + + // here is the difference + if (start < i && (drawCall.blend !== spriteBlendMode || drawCall.uniforms !== uniforms)) + { + drawCall.size = iIndex - drawCall.start; + start = i; + drawCall = drawCalls[++dcIndex]; + drawCall.texArray = texArray; + drawCall.start = iIndex; + } + + this.packInterleavedGeometry(sprite, _attributeBuffer, _indexBuffer, aIndex, iIndex); + aIndex += sprite.vertexData.length / 2 * vertexSize; + iIndex += sprite.indices.length; + + drawCall.blend = spriteBlendMode; + // here is the difference + drawCall.uniforms = uniforms; + } + + if (start < finish) + { + drawCall.size = iIndex - drawCall.start; + ++dcIndex; + } + + thisAny._dcIndex = dcIndex; + thisAny._aIndex = aIndex; + thisAny._iIndex = iIndex; + } + + drawBatches() + { + const dcCount = this._dcIndex; + const { gl, state: stateSystem, shader: shaderSystem } = this.renderer; + const drawCalls = core.AbstractBatchRenderer._drawCallPool; + let curUniforms = null; + let curTexArray = null; + + for (let i = 0; i < dcCount; i++) + { + const { texArray, type, size, start, blend, uniforms } = drawCalls[i] ; + + if (curTexArray !== texArray) + { + curTexArray = texArray; + this.bindAndClearTexArray(texArray); + } + // here is the difference + if (curUniforms !== uniforms) + { + curUniforms = uniforms; + this.syncUniforms(uniforms); + (shaderSystem ).syncUniformGroup((this._shader ).uniformGroup); + } + + this.state.blendMode = blend; + stateSystem.set(this.state); + gl.drawElements(type, size, gl.UNSIGNED_SHORT, start * 2); + } + } + + contextChange() + { + if (!this.forceMaxTextures) + { + super.contextChange(); + this.syncUniforms(this.defUniforms); + + return; + } + + // we can override MAX_TEXTURES with this hack + + const thisAny = this ; + + thisAny.MAX_TEXTURES = this.forceMaxTextures; + this._shader = thisAny.shaderGenerator.generateShader(this.MAX_TEXTURES); + this.syncUniforms(this.defUniforms); + for (let i = 0; i < thisAny._packedGeometryPoolSize; i++) + { + /* eslint-disable max-len */ + thisAny._packedGeometries[i] = new (this.geometryClass)(); + } + this.initFlushBuffers(); + } + } + + core.Renderer.registerPlugin('batch2d', Batch2dPluginFactory.create({})); + + /* eslint-disable no-mixed-operators */ + + // eslint-disable-next-line max-len + function getIntersectionFactor(p1, p2, p3, p4, out) + { + const A1 = p2.x - p1.x; const B1 = p3.x - p4.x; + const C1 = p3.x - p1.x; + const A2 = p2.y - p1.y; const B2 = p3.y - p4.y; + const C2 = p3.y - p1.y; + const D = A1 * B2 - A2 * B1; + + if (Math.abs(D) < 1e-7) + { + out.x = A1; + out.y = A2; + + return 0; + } + const T = C1 * B2 - C2 * B1; + const U = A1 * C2 - A2 * C1; + + const t = T / D; const + u = U / D; + + if (u < (1e-6) || u - 1 > -1e-6) + { + return -1; + } + + out.x = p1.x + t * (p2.x - p1.x); + out.y = p1.y + t * (p2.y - p1.y); + + return 1; + } + + function getPositionFromQuad(p, anchor, out) + { + out = out || new math.Point(); + const a1 = 1.0 - anchor.x; const + a2 = 1.0 - a1; + const b1 = 1.0 - anchor.y; const + b2 = 1.0 - b1; + + out.x = (p[0].x * a1 + p[1].x * a2) * b1 + (p[3].x * a1 + p[2].x * a2) * b2; + out.y = (p[0].y * a1 + p[1].y * a2) * b1 + (p[3].y * a1 + p[2].y * a2) * b2; + + return out; + } + + /* eslint-disable no-mixed-operators,max-statements-per-line */ + + const mat3id = [1, 0, 0, 0, 1, 0, 0, 0, 1]; + + class Matrix2d + { + /** + * A default (identity) matrix + * + * @static + * @const + */ + static __initStatic() {this.IDENTITY = new Matrix2d();} + + /** + * A temp matrix + * + * @static + * @const + */ + static __initStatic2() {this.TEMP_MATRIX = new Matrix2d();} + + /** + * mat3 implementation through array of 9 elements + */ + + + __init() {this.floatArray = null;} + + constructor(backingArray) + {;Matrix2d.prototype.__init.call(this); + this.mat3 = new Float64Array(backingArray || mat3id); + } + + get a() + { + return this.mat3[0] / this.mat3[8]; + } + + set a(value) + { + this.mat3[0] = value * this.mat3[8]; + } + + get b() + { + return this.mat3[1] / this.mat3[8]; + } + + set b(value) + { + this.mat3[1] = value * this.mat3[8]; + } + + get c() + { + return this.mat3[3] / this.mat3[8]; + } + + set c(value) + { + this.mat3[3] = value * this.mat3[8]; + } + + get d() + { + return this.mat3[4] / this.mat3[8]; + } + + set d(value) + { + this.mat3[4] = value * this.mat3[8]; + } + + get tx() + { + return this.mat3[6] / this.mat3[8]; + } + + set tx(value) + { + this.mat3[6] = value * this.mat3[8]; + } + + get ty() + { + return this.mat3[7] / this.mat3[8]; + } + + set ty(value) + { + this.mat3[7] = value * this.mat3[8]; + } + + set(a, b, c, d, tx, ty) + { + const mat3 = this.mat3; + + mat3[0] = a; + mat3[1] = b; + mat3[2] = 0; + mat3[3] = c; + mat3[4] = d; + mat3[5] = 0; + mat3[6] = tx; + mat3[7] = ty; + mat3[8] = 1; + + return this; + } + + toArray(transpose, out) + { + if (!this.floatArray) + { + this.floatArray = new Float32Array(9); + } + + const array = out || this.floatArray; + const mat3 = this.mat3; + + if (transpose) + { + array[0] = mat3[0]; + array[1] = mat3[1]; + array[2] = mat3[2]; + array[3] = mat3[3]; + array[4] = mat3[4]; + array[5] = mat3[5]; + array[6] = mat3[6]; + array[7] = mat3[7]; + array[8] = mat3[8]; + } + else + { + // this branch is NEVER USED in pixi + array[0] = mat3[0]; + array[1] = mat3[3]; + array[2] = mat3[6]; + array[3] = mat3[1]; + array[4] = mat3[4]; + array[5] = mat3[7]; + array[6] = mat3[2]; + array[7] = mat3[5]; + array[8] = mat3[8]; + } + + return array; + } + + // TODO: remove props + apply(pos, newPos) + { + newPos = newPos || new math.Point(); + + const mat3 = this.mat3; + const x = pos.x; + const y = pos.y; + + const z = 1.0 / (mat3[2] * x + mat3[5] * y + mat3[8]); + + newPos.x = z * (mat3[0] * x + mat3[3] * y + mat3[6]); + newPos.y = z * (mat3[1] * x + mat3[4] * y + mat3[7]); + + return newPos; + } + + translate(tx, ty) + { + const mat3 = this.mat3; + + mat3[0] += tx * mat3[2]; + mat3[1] += ty * mat3[2]; + mat3[3] += tx * mat3[5]; + mat3[4] += ty * mat3[5]; + mat3[6] += tx * mat3[8]; + mat3[7] += ty * mat3[8]; + + return this; + } + + scale(x, y) + { + const mat3 = this.mat3; + + mat3[0] *= x; + mat3[1] *= y; + mat3[3] *= x; + mat3[4] *= y; + mat3[6] *= x; + mat3[7] *= y; + + return this; + } + + scaleAndTranslate(scaleX, scaleY, tx, ty) + { + const mat3 = this.mat3; + + mat3[0] = scaleX * mat3[0] + tx * mat3[2]; + mat3[1] = scaleY * mat3[1] + ty * mat3[2]; + mat3[3] = scaleX * mat3[3] + tx * mat3[5]; + mat3[4] = scaleY * mat3[4] + ty * mat3[5]; + mat3[6] = scaleX * mat3[6] + tx * mat3[8]; + mat3[7] = scaleY * mat3[7] + ty * mat3[8]; + } + + // TODO: remove props + applyInverse(pos, newPos) + { + newPos = newPos || new math.Point(); + + const a = this.mat3; + const x = pos.x; + const y = pos.y; + + const a00 = a[0]; const a01 = a[3]; const a02 = a[6]; + const a10 = a[1]; const a11 = a[4]; const a12 = a[7]; + const a20 = a[2]; const a21 = a[5]; const + a22 = a[8]; + + const newX = (a22 * a11 - a12 * a21) * x + (-a22 * a01 + a02 * a21) * y + (a12 * a01 - a02 * a11); + const newY = (-a22 * a10 + a12 * a20) * x + (a22 * a00 - a02 * a20) * y + (-a12 * a00 + a02 * a10); + const newZ = (a21 * a10 - a11 * a20) * x + (-a21 * a00 + a01 * a20) * y + (a11 * a00 - a01 * a10); + + newPos.x = newX / newZ; + newPos.y = newY / newZ; + + return newPos; + } + + invert() + { + const a = this.mat3; + + const a00 = a[0]; const a01 = a[1]; const a02 = a[2]; + const a10 = a[3]; const a11 = a[4]; const a12 = a[5]; + const a20 = a[6]; const a21 = a[7]; const a22 = a[8]; + + const b01 = a22 * a11 - a12 * a21; + const b11 = -a22 * a10 + a12 * a20; + const b21 = a21 * a10 - a11 * a20; + + // Calculate the determinant + let det = a00 * b01 + a01 * b11 + a02 * b21; + + if (!det) + { + return this; + } + det = 1.0 / det; + + a[0] = b01 * det; + a[1] = (-a22 * a01 + a02 * a21) * det; + a[2] = (a12 * a01 - a02 * a11) * det; + a[3] = b11 * det; + a[4] = (a22 * a00 - a02 * a20) * det; + a[5] = (-a12 * a00 + a02 * a10) * det; + a[6] = b21 * det; + a[7] = (-a21 * a00 + a01 * a20) * det; + a[8] = (a11 * a00 - a01 * a10) * det; + + return this; + } + + identity() + { + const mat3 = this.mat3; + + mat3[0] = 1; + mat3[1] = 0; + mat3[2] = 0; + mat3[3] = 0; + mat3[4] = 1; + mat3[5] = 0; + mat3[6] = 0; + mat3[7] = 0; + mat3[8] = 1; + + return this; + } + + clone() + { + return new Matrix2d(this.mat3); + } + + copyTo2dOr3d(matrix) + { + const mat3 = this.mat3; + const ar2 = matrix.mat3; + + ar2[0] = mat3[0]; + ar2[1] = mat3[1]; + ar2[2] = mat3[2]; + ar2[3] = mat3[3]; + ar2[4] = mat3[4]; + ar2[5] = mat3[5]; + ar2[6] = mat3[6]; + ar2[7] = mat3[7]; + ar2[8] = mat3[8]; + + return matrix; + } + + /** + * legacy method, change the values of given pixi matrix + * @param matrix + * @param affine + * @param preserveOrientation + * @return matrix + */ + copyTo(matrix, affine, preserveOrientation) + { + const mat3 = this.mat3; + const d = 1.0 / mat3[8]; + const tx = mat3[6] * d; const + ty = mat3[7] * d; + + matrix.a = (mat3[0] - mat3[2] * tx) * d; + matrix.b = (mat3[1] - mat3[2] * ty) * d; + matrix.c = (mat3[3] - mat3[5] * tx) * d; + matrix.d = (mat3[4] - mat3[5] * ty) * d; + matrix.tx = tx; + matrix.ty = ty; + + if (affine >= 2) + { + let D = matrix.a * matrix.d - matrix.b * matrix.c; + + if (!preserveOrientation) + { + D = Math.abs(D); + } + if (affine === exports.AFFINE.POINT) + { + if (D > 0) + { + D = 1; + } + else D = -1; + matrix.a = D; + matrix.b = 0; + matrix.c = 0; + matrix.d = D; + } + else if (affine === exports.AFFINE.AXIS_X) + { + D /= Math.sqrt(matrix.b * matrix.b + matrix.d * matrix.d); + matrix.c = 0; + matrix.d = D; + } + else if (affine === exports.AFFINE.AXIS_Y) + { + D /= Math.sqrt(matrix.a * matrix.a + matrix.c * matrix.c); + matrix.a = D; + matrix.c = 0; + } + else if (affine === exports.AFFINE.AXIS_XR) + { + matrix.a = matrix.d * D; + matrix.c = -matrix.b * D; + } + } + + return matrix; + } + + /** + * legacy method, change the values of given pixi matrix + * @param matrix + * @return + */ + copyFrom(matrix) + { + const mat3 = this.mat3; + + mat3[0] = matrix.a; + mat3[1] = matrix.b; + mat3[2] = 0; + mat3[3] = matrix.c; + mat3[4] = matrix.d; + mat3[5] = 0; + mat3[6] = matrix.tx; + mat3[7] = matrix.ty; + mat3[8] = 1.0; + + return this; + } + + setToMultLegacy(pt, lt) + { + const out = this.mat3; + const b = lt.mat3; + + const a00 = pt.a; const a01 = pt.b; + const a10 = pt.c; const a11 = pt.d; + const a20 = pt.tx; const a21 = pt.ty; + + const b00 = b[0]; const b01 = b[1]; const b02 = b[2]; + const b10 = b[3]; const b11 = b[4]; const b12 = b[5]; + const b20 = b[6]; const b21 = b[7]; const + b22 = b[8]; + + out[0] = b00 * a00 + b01 * a10 + b02 * a20; + out[1] = b00 * a01 + b01 * a11 + b02 * a21; + out[2] = b02; + + out[3] = b10 * a00 + b11 * a10 + b12 * a20; + out[4] = b10 * a01 + b11 * a11 + b12 * a21; + out[5] = b12; + + out[6] = b20 * a00 + b21 * a10 + b22 * a20; + out[7] = b20 * a01 + b21 * a11 + b22 * a21; + out[8] = b22; + + return this; + } + + setToMultLegacy2(pt, lt) + { + const out = this.mat3; + const a = pt.mat3; + + const a00 = a[0]; const a01 = a[1]; const a02 = a[2]; + const a10 = a[3]; const a11 = a[4]; const a12 = a[5]; + const a20 = a[6]; const a21 = a[7]; const a22 = a[8]; + + const b00 = lt.a; const b01 = lt.b; + const b10 = lt.c; const b11 = lt.d; + const b20 = lt.tx; const + b21 = lt.ty; + + out[0] = b00 * a00 + b01 * a10; + out[1] = b00 * a01 + b01 * a11; + out[2] = b00 * a02 + b01 * a12; + + out[3] = b10 * a00 + b11 * a10; + out[4] = b10 * a01 + b11 * a11; + out[5] = b10 * a02 + b11 * a12; + + out[6] = b20 * a00 + b21 * a10 + a20; + out[7] = b20 * a01 + b21 * a11 + a21; + out[8] = b20 * a02 + b21 * a12 + a22; + + return this; + } + + // that's transform multiplication we use + setToMult(pt, lt) + { + const out = this.mat3; + const a = pt.mat3; const + b = lt.mat3; + + const a00 = a[0]; const a01 = a[1]; const a02 = a[2]; + const a10 = a[3]; const a11 = a[4]; const a12 = a[5]; + const a20 = a[6]; const a21 = a[7]; const a22 = a[8]; + + const b00 = b[0]; const b01 = b[1]; const b02 = b[2]; + const b10 = b[3]; const b11 = b[4]; const b12 = b[5]; + const b20 = b[6]; const b21 = b[7]; const + b22 = b[8]; + + out[0] = b00 * a00 + b01 * a10 + b02 * a20; + out[1] = b00 * a01 + b01 * a11 + b02 * a21; + out[2] = b00 * a02 + b01 * a12 + b02 * a22; + + out[3] = b10 * a00 + b11 * a10 + b12 * a20; + out[4] = b10 * a01 + b11 * a11 + b12 * a21; + out[5] = b10 * a02 + b11 * a12 + b12 * a22; + + out[6] = b20 * a00 + b21 * a10 + b22 * a20; + out[7] = b20 * a01 + b21 * a11 + b22 * a21; + out[8] = b20 * a02 + b21 * a12 + b22 * a22; + + return this; + } + + // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types + prepend(lt) + { + if (lt.mat3) + { + return this.setToMult(lt, this); + } + + return this.setToMultLegacy(lt, this); + } + } Matrix2d.__initStatic(); Matrix2d.__initStatic2(); + + const shaderVert$1 + = `attribute vec2 aVertexPosition; +attribute vec2 aTextureCoord; + +uniform mat3 projectionMatrix; +uniform mat3 translationMatrix; +uniform mat3 uTransform; + +varying vec3 vTextureCoord; + +void main(void) +{ +gl_Position.xyw = projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0); + +vTextureCoord = uTransform * vec3(aTextureCoord, 1.0); +} +`; + const shaderFrag$1 = ` +varying vec3 vTextureCoord; + +uniform sampler2D uSampler; +uniform vec4 uColor; +uniform mat3 uMapCoord; +uniform vec4 uClampFrame; +uniform vec2 uClampOffset; + +void main(void) +{ +vec2 coord = mod(vTextureCoord.xy / vTextureCoord.z - uClampOffset, vec2(1.0, 1.0)) + uClampOffset; +coord = (uMapCoord * vec3(coord, 1.0)).xy; +coord = clamp(coord, uClampFrame.xy, uClampFrame.zw); + +vec4 sample = texture2D(uSampler, coord); +gl_FragColor = sample * uColor; +} +`; + const shaderSimpleFrag = ` +varying vec3 vTextureCoord; + +uniform sampler2D uSampler; +uniform vec4 uColor; + +void main(void) +{ +vec4 sample = texture2D(uSampler, vTextureCoord.xy / vTextureCoord.z); +gl_FragColor = sample * uColor; +} +`; + + // changed + const tempMat$4 = new Matrix2d(); + + class TilingSprite2dRenderer extends core.ObjectRenderer + { + constructor(renderer) + { + super(renderer);TilingSprite2dRenderer.prototype.__init.call(this);; + + const uniforms = { globals: this.renderer.globalUniforms }; + + this.shader = core.Shader.from(shaderVert$1, shaderFrag$1, uniforms); + + this.simpleShader = core.Shader.from(shaderVert$1, shaderSimpleFrag, uniforms); + } + + + + __init() {this.quad = new core.QuadUv();} + + // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types + render(ts) + { + const renderer = this.renderer; + const quad = this.quad; + + let vertices = quad.vertices; + + vertices[0] = vertices[6] = (ts._width) * -ts.anchor.x; + vertices[1] = vertices[3] = ts._height * -ts.anchor.y; + + vertices[2] = vertices[4] = (ts._width) * (1.0 - ts.anchor.x); + vertices[5] = vertices[7] = ts._height * (1.0 - ts.anchor.y); + + if (ts.uvRespectAnchor) + { + vertices = quad.uvs; + + vertices[0] = vertices[6] = -ts.anchor.x; + vertices[1] = vertices[3] = -ts.anchor.y; + + vertices[2] = vertices[4] = 1.0 - ts.anchor.x; + vertices[5] = vertices[7] = 1.0 - ts.anchor.y; + } + + quad.invalidate(); + + const tex = ts._texture; + const baseTex = tex.baseTexture; + const lt = ts.tileProj.world; + const uv = ts.uvMatrix; + let isSimple = baseTex.isPowerOfTwo + && tex.frame.width === baseTex.width && tex.frame.height === baseTex.height; + + // auto, force repeat wrapMode for big tiling textures + if (isSimple) + { + if (!baseTex._glTextures[(renderer ).CONTEXT_UID]) + { + if (baseTex.wrapMode === constants.WRAP_MODES.CLAMP) + { + baseTex.wrapMode = constants.WRAP_MODES.REPEAT; + } + } + else + { + isSimple = baseTex.wrapMode !== constants.WRAP_MODES.CLAMP; + } + } + + const shader = isSimple ? this.simpleShader : this.shader; + + // changed + tempMat$4.identity(); + tempMat$4.scale(tex.width, tex.height); + tempMat$4.prepend(lt); + tempMat$4.scale(1.0 / ts._width, 1.0 / ts._height); + + tempMat$4.invert(); + if (isSimple) + { + tempMat$4.prepend(uv.mapCoord); + } + else + { + shader.uniforms.uMapCoord = uv.mapCoord.toArray(true); + shader.uniforms.uClampFrame = uv.uClampFrame; + shader.uniforms.uClampOffset = uv.uClampOffset; + } + + shader.uniforms.uTransform = tempMat$4.toArray(true); + shader.uniforms.uColor = utils.premultiplyTintToRgba(ts.tint, ts.worldAlpha, + shader.uniforms.uColor, baseTex.premultiplyAlpha); + shader.uniforms.translationMatrix = ts.worldTransform.toArray(true); + shader.uniforms.uSampler = tex; + + renderer.shader.bind(shader, false); + renderer.geometry.bind(quad , undefined);// , renderer.shader.getGLShader()); + + renderer.state.setBlendMode(utils.correctBlendMode(ts.blendMode, baseTex.premultiplyAlpha)); + renderer.geometry.draw(constants.DRAW_MODES.TRIANGLES, 6, 0); + } + } + + /* eslint-disable no-mixed-operators */ + + const t0 = new math.Point(); + const tt = [new math.Point(), new math.Point(), new math.Point(), new math.Point()]; + const tempRect$1 = new math.Rectangle(); + const tempMat$3 = new Matrix2d(); + + class Projection2d extends LinearProjection + { + constructor(legacy, enable) + { + super(legacy, enable);Projection2d.prototype.__init.call(this);Projection2d.prototype.__init2.call(this);Projection2d.prototype.__init3.call(this);; + this.local = new Matrix2d(); + this.world = new Matrix2d(); + } + + __init() {this.matrix = new Matrix2d();} + __init2() {this.pivot = new math.ObservablePoint(this.onChange, this, 0, 0);} + + __init3() {this.reverseLocalOrder = false;} + + onChange() + { + const pivot = this.pivot; + const mat3 = this.matrix.mat3; + + mat3[6] = -(pivot._x * mat3[0] + pivot._y * mat3[3]); + mat3[7] = -(pivot._x * mat3[1] + pivot._y * mat3[4]); + + this._projID++; + } + + setAxisX(p, factor = 1) + { + const x = p.x; const + y = p.y; + const d = Math.sqrt(x * x + y * y); + const mat3 = this.matrix.mat3; + + mat3[0] = x / d; + mat3[1] = y / d; + mat3[2] = factor / d; + + this.onChange(); + } + + setAxisY(p, factor = 1) + { + const x = p.x; const + y = p.y; + const d = Math.sqrt(x * x + y * y); + const mat3 = this.matrix.mat3; + + mat3[3] = x / d; + mat3[4] = y / d; + mat3[5] = factor / d; + this.onChange(); + } + + mapSprite(sprite, quad) + { + const tex = sprite.texture; + + tempRect$1.x = -sprite.anchor.x * tex.orig.width; + tempRect$1.y = -sprite.anchor.y * tex.orig.height; + tempRect$1.width = tex.orig.width; + tempRect$1.height = tex.orig.height; + + this.mapQuad(tempRect$1, quad); + } + + mapQuad(rect, p) + { + // utils.getPositionFromQuad(p, anchor, t0); + tt[0].set(rect.x, rect.y); + tt[1].set(rect.x + rect.width, rect.y); + tt[2].set(rect.x + rect.width, rect.y + rect.height); + tt[3].set(rect.x, rect.y + rect.height); + + let k1 = 1; let k2 = 2; + let k3 = 3; + const f = getIntersectionFactor(p[0], p[2], p[1], p[3], t0); + + if (f !== 0) + { + k1 = 1; + k2 = 3; + k3 = 2; + } + else + { + return; + /* f = utils.getIntersectionFactor(p[0], p[1], p[2], p[3], t0); + if (f > 0) { + k1 = 2; + k2 = 3; + k3 = 1; + } else { + f = utils.getIntersectionFactor(p[0], p[3], p[1], p[2], t0); + if (f > 0) { + // cant find it :( + k1 = 1; + k2 = 2; + k3 = 3; + } else { + return; + } + }*/ + } + const d0 = Math.sqrt((p[0].x - t0.x) * (p[0].x - t0.x) + (p[0].y - t0.y) * (p[0].y - t0.y)); + const d1 = Math.sqrt((p[k1].x - t0.x) * (p[k1].x - t0.x) + (p[k1].y - t0.y) * (p[k1].y - t0.y)); + const d2 = Math.sqrt((p[k2].x - t0.x) * (p[k2].x - t0.x) + (p[k2].y - t0.y) * (p[k2].y - t0.y)); + const d3 = Math.sqrt((p[k3].x - t0.x) * (p[k3].x - t0.x) + (p[k3].y - t0.y) * (p[k3].y - t0.y)); + + const q0 = (d0 + d3) / d3; + const q1 = (d1 + d2) / d2; + const q2 = (d1 + d2) / d1; + + let mat3 = this.matrix.mat3; + + mat3[0] = tt[0].x * q0; + mat3[1] = tt[0].y * q0; + mat3[2] = q0; + mat3[3] = tt[k1].x * q1; + mat3[4] = tt[k1].y * q1; + mat3[5] = q1; + mat3[6] = tt[k2].x * q2; + mat3[7] = tt[k2].y * q2; + mat3[8] = q2; + this.matrix.invert(); + + mat3 = tempMat$3.mat3; + mat3[0] = p[0].x; + mat3[1] = p[0].y; + mat3[2] = 1; + mat3[3] = p[k1].x; + mat3[4] = p[k1].y; + mat3[5] = 1; + mat3[6] = p[k2].x; + mat3[7] = p[k2].y; + mat3[8] = 1; + + this.matrix.setToMult(tempMat$3, this.matrix); + this._projID++; + } + + updateLocalTransform(lt) + { + if (this._projID !== 0) + { + if (this.reverseLocalOrder) + { + // tilingSprite inside order + this.local.setToMultLegacy2(this.matrix, lt); + } + else + { + // good order + this.local.setToMultLegacy(lt, this.matrix); + } + } + else + { + this.local.copyFrom(lt); + } + } + + clear() + { + super.clear(); + this.matrix.identity(); + this.pivot.set(0, 0); + } + } + + function container2dWorldTransform() + { + return this.proj.affine ? this.transform.worldTransform : this.proj.world ; + } + + class Container2d extends display.Container + { + constructor() + { + super(); + this.proj = new Projection2d(this.transform); + } + + + + toLocal(position, from, point, skipUpdate, + step = exports.TRANSFORM_STEP.ALL) + { + if (from) + { + position = from.toGlobal(position, point, skipUpdate); + } + + if (!skipUpdate) + { + this._recursivePostUpdateTransform(); + } + + if (step >= exports.TRANSFORM_STEP.PROJ) + { + if (!skipUpdate) + { + this.displayObjectUpdateTransform(); + } + if (this.proj.affine) + { + return this.transform.worldTransform.applyInverse(position, point) ; + } + + return this.proj.world.applyInverse(position, point) ; + } + + if (this.parent) + { + point = this.parent.worldTransform.applyInverse(position, point) ; + } + else + { + point.x = position.x; + point.y = position.y; + } + if (step === exports.TRANSFORM_STEP.NONE) + { + return point; + } + + return this.transform.localTransform.applyInverse(point, point) ; + } + + get worldTransform() + { + return this.proj.affine ? this.transform.worldTransform : this.proj.world ; + } + } + + const container2dToLocal = Container2d.prototype.toLocal; + + function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; } + class Mesh2d extends mesh.Mesh + { + static __initStatic() {this.defaultVertexShader = + `precision highp float; +attribute vec2 aVertexPosition; +attribute vec2 aTextureCoord; + +uniform mat3 projectionMatrix; +uniform mat3 translationMatrix; +uniform mat3 uTextureMatrix; + +varying vec2 vTextureCoord; + +void main(void) +{ +gl_Position.xyw = projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0); +gl_Position.z = 0.0; + +vTextureCoord = (uTextureMatrix * vec3(aTextureCoord, 1.0)).xy; +} +`;} + static __initStatic2() {this.defaultFragmentShader = ` +varying vec2 vTextureCoord; +uniform vec4 uColor; + +uniform sampler2D uSampler; + +void main(void) +{ +gl_FragColor = texture2D(uSampler, vTextureCoord) * uColor; +}`;} + constructor(geometry, shader, state, drawMode) + { + super(geometry, shader, state, drawMode);Mesh2d.prototype.__init.call(this);; + this.proj = new Projection2d(this.transform); + } + + __init() {this.vertexData2d = null;} + + + calculateVertices() + { + if (this.proj._affine) + { + this.vertexData2d = null; + super.calculateVertices(); + + return; + } + + const geometry = this.geometry ; + const vertices = geometry.buffers[0].data; + const thisAny = this ; + + if (geometry.vertexDirtyId === thisAny.vertexDirty && thisAny._transformID === thisAny.transform._worldID) + { + return; + } + + thisAny._transformID = thisAny.transform._worldID; + + if (thisAny.vertexData.length !== vertices.length) + { + thisAny.vertexData = new Float32Array(vertices.length); + } + + if (!this.vertexData2d || this.vertexData2d.length !== vertices.length * 3 / 2) + { + this.vertexData2d = new Float32Array(vertices.length * 3); + } + + const wt = this.proj.world.mat3; + + const vertexData2d = this.vertexData2d; + const vertexData = thisAny.vertexData; + + for (let i = 0; i < vertexData.length / 2; i++) + { + const x = vertices[(i * 2)]; + const y = vertices[(i * 2) + 1]; + + const xx = (wt[0] * x) + (wt[3] * y) + wt[6]; + const yy = (wt[1] * x) + (wt[4] * y) + wt[7]; + const ww = (wt[2] * x) + (wt[5] * y) + wt[8]; + + vertexData2d[i * 3] = xx; + vertexData2d[(i * 3) + 1] = yy; + vertexData2d[(i * 3) + 2] = ww; + + vertexData[(i * 2)] = xx / ww; + vertexData[(i * 2) + 1] = yy / ww; + } + + thisAny.vertexDirty = geometry.vertexDirtyId; + } + + _renderDefault(renderer) + { + const shader = this.shader ; + + shader.alpha = this.worldAlpha; + if (shader.update) + { + shader.update(); + } + + renderer.batch.flush(); + + if (_optionalChain([(shader ), 'access', _ => _.program, 'access', _2 => _2.uniformData, 'optionalAccess', _3 => _3.translationMatrix])) + { + shader.uniforms.translationMatrix = this.worldTransform.toArray(true); + } + + // bind and sync uniforms.. + renderer.shader.bind(shader, false); + + // set state.. + renderer.state.set(this.state); + + // bind the geometry... + renderer.geometry.bind(this.geometry, shader); + + // then render it + renderer.geometry.draw(this.drawMode, this.size, this.start, (this.geometry ).instanceCount); + } + + toLocal(position, from, + point, skipUpdate, + step = exports.TRANSFORM_STEP.ALL) + { + return container2dToLocal.call(this, position, from, point, skipUpdate, step); + } + + get worldTransform() + { + return this.proj.affine ? this.transform.worldTransform : this.proj.world ; + } + } Mesh2d.__initStatic(); Mesh2d.__initStatic2(); + + class SimpleMesh2d extends Mesh2d + { + constructor(texture, vertices, uvs, + indices, drawMode) + { + super(new mesh.MeshGeometry(vertices, uvs, indices), + new mesh.MeshMaterial(texture, { + program: core.Program.from(Mesh2d.defaultVertexShader, Mesh2d.defaultFragmentShader), + pluginName: 'batch2d' + }), + null, + drawMode);SimpleMesh2d.prototype.__init2.call(this);; + + (this.geometry.getBuffer('aVertexPosition') ).static = false; + } + + __init2() {this.autoUpdate = true;} + + get vertices() + { + return this.geometry.getBuffer('aVertexPosition').data ; + } + set vertices(value) + { + this.geometry.getBuffer('aVertexPosition').data = value; + } + + _render(renderer) + { + if (this.autoUpdate) + { + this.geometry.getBuffer('aVertexPosition').update(); + } + + (super._render )(renderer); + } + } + + /* eslint-disable no-mixed-operators */ + + class Sprite2d extends sprite.Sprite + { + constructor(texture) + { + super(texture);Sprite2d.prototype.__init.call(this);; + this.proj = new Projection2d(this.transform); + this.pluginName = 'batch2d'; + } + + __init() {this.vertexData2d = null;} + + + _calculateBounds() + { + this.calculateTrimmedVertices(); + this._bounds.addQuad((this ).vertexTrimmedData); + } + + calculateVertices() + { + const texture = this._texture; + const thisAny = this ; + + if (this.proj._affine) + { + this.vertexData2d = null; + super.calculateVertices(); + + return; + } + if (!this.vertexData2d) + { + this.vertexData2d = new Float32Array(12); + } + + const wid = (this.transform )._worldID; + const tuid = (texture )._updateID; + + if (thisAny._transformID === wid && this._textureID === tuid) + { + return; + } + // update texture UV here, because base texture can be changed without calling `_onTextureUpdate` + if (this._textureID !== tuid) + { + (this ).uvs = (texture )._uvs.uvsFloat32; + } + + thisAny._transformID = wid; + this._textureID = tuid; + + const wt = this.proj.world.mat3; + const vertexData2d = this.vertexData2d; + const vertexData = this.vertexData; + const trim = texture.trim; + const orig = texture.orig; + const anchor = this._anchor; + + let w0; + let w1; + let h0; + let h1; + + if (trim) + { + w1 = trim.x - (anchor._x * orig.width); + w0 = w1 + trim.width; + + h1 = trim.y - (anchor._y * orig.height); + h0 = h1 + trim.height; + } + else + { + w1 = -anchor._x * orig.width; + w0 = w1 + orig.width; + + h1 = -anchor._y * orig.height; + h0 = h1 + orig.height; + } + + vertexData2d[0] = (wt[0] * w1) + (wt[3] * h1) + wt[6]; + vertexData2d[1] = (wt[1] * w1) + (wt[4] * h1) + wt[7]; + vertexData2d[2] = (wt[2] * w1) + (wt[5] * h1) + wt[8]; + + vertexData2d[3] = (wt[0] * w0) + (wt[3] * h1) + wt[6]; + vertexData2d[4] = (wt[1] * w0) + (wt[4] * h1) + wt[7]; + vertexData2d[5] = (wt[2] * w0) + (wt[5] * h1) + wt[8]; + + vertexData2d[6] = (wt[0] * w0) + (wt[3] * h0) + wt[6]; + vertexData2d[7] = (wt[1] * w0) + (wt[4] * h0) + wt[7]; + vertexData2d[8] = (wt[2] * w0) + (wt[5] * h0) + wt[8]; + + vertexData2d[9] = (wt[0] * w1) + (wt[3] * h0) + wt[6]; + vertexData2d[10] = (wt[1] * w1) + (wt[4] * h0) + wt[7]; + vertexData2d[11] = (wt[2] * w1) + (wt[5] * h0) + wt[8]; + + vertexData[0] = vertexData2d[0] / vertexData2d[2]; + vertexData[1] = vertexData2d[1] / vertexData2d[2]; + + vertexData[2] = vertexData2d[3] / vertexData2d[5]; + vertexData[3] = vertexData2d[4] / vertexData2d[5]; + + vertexData[4] = vertexData2d[6] / vertexData2d[8]; + vertexData[5] = vertexData2d[7] / vertexData2d[8]; + + vertexData[6] = vertexData2d[9] / vertexData2d[11]; + vertexData[7] = vertexData2d[10] / vertexData2d[11]; + } + + calculateTrimmedVertices() + { + if (this.proj._affine) + { + super.calculateTrimmedVertices(); + + return; + } + + const wid = (this.transform )._worldID; + const tuid = (this._texture )._updateID; + const thisAny = this ; + + if (!thisAny.vertexTrimmedData) + { + thisAny.vertexTrimmedData = new Float32Array(8); + } + else if (thisAny._transformTrimmedID === wid && this._textureTrimmedID === tuid) + { + return; + } + + thisAny._transformTrimmedID = wid; + this._textureTrimmedID = tuid; + + // lets do some special trim code! + const texture = this._texture; + const vertexData = thisAny.vertexTrimmedData; + const orig = texture.orig; + const w = (this ).tileProj ? this._width : orig.width; + const h = (this ).tileProj ? this._height : orig.height; + const anchor = this._anchor; + + // lets calculate the new untrimmed bounds.. + const wt = this.proj.world.mat3; + + const w1 = -anchor._x * w; + const w0 = w1 + w; + + const h1 = -anchor._y * h; + const h0 = h1 + h; + + let z = 1.0 / (wt[2] * w1 + wt[5] * h1 + wt[8]); + + vertexData[0] = z * ((wt[0] * w1) + (wt[3] * h1) + wt[6]); + vertexData[1] = z * ((wt[1] * w1) + (wt[4] * h1) + wt[7]); + + z = 1.0 / (wt[2] * w0 + wt[5] * h1 + wt[8]); + vertexData[2] = z * ((wt[0] * w0) + (wt[3] * h1) + wt[6]); + vertexData[3] = z * ((wt[1] * w0) + (wt[4] * h1) + wt[7]); + + z = 1.0 / (wt[2] * w0 + wt[5] * h0 + wt[8]); + vertexData[4] = z * ((wt[0] * w0) + (wt[3] * h0) + wt[6]); + vertexData[5] = z * ((wt[1] * w0) + (wt[4] * h0) + wt[7]); + + z = 1.0 / (wt[2] * w1 + wt[5] * h0 + wt[8]); + vertexData[6] = z * ((wt[0] * w1) + (wt[3] * h0) + wt[6]); + vertexData[7] = z * ((wt[1] * w1) + (wt[4] * h0) + wt[7]); + } + + toLocal(position, from, point, skipUpdate, + step = exports.TRANSFORM_STEP.ALL) + { + return container2dToLocal.call(this, position, from, point, skipUpdate, step); + } + + get worldTransform() + { + return this.proj.affine ? this.transform.worldTransform : this.proj.world ; + } + } + + const tempTransform = new math.Transform(); + + class TilingSprite2d extends spriteTiling.TilingSprite + { + constructor(texture, width, height) + { + super(texture, width, height); + + this.tileProj = new Projection2d(this.tileTransform); + this.tileProj.reverseLocalOrder = true; + this.proj = new Projection2d(this.transform); + + this.pluginName = 'tilingSprite2d'; + this.uvRespectAnchor = true; + } + + + + + get worldTransform() + { + return this.proj.affine ? this.transform.worldTransform : this.proj.world ; + } + + toLocal(position, from, point, skipUpdate, + step = exports.TRANSFORM_STEP.ALL) + { + return container2dToLocal.call(this, position, from, point, skipUpdate, step); + } + + _render(renderer) + { + // tweak our texture temporarily.. + const texture = this._texture; + + if (!texture || !texture.valid) + { + return; + } + + // changed + this.tileTransform.updateTransform(tempTransform); + this.uvMatrix.update(); + + renderer.batch.setObjectRenderer((renderer.plugins )[this.pluginName]); + (renderer.plugins )[this.pluginName].render(this); + } + } + + function convertTo2d() + { + if (this.proj) return; + this.proj = new Projection2d(this.transform); + this.toLocal = Container2d.prototype.toLocal; + Object.defineProperty(this, 'worldTransform', { + get: container2dWorldTransform, + enumerable: true, + configurable: true + }); + } + + display.Container.prototype.convertTo2d = convertTo2d; + + sprite.Sprite.prototype.convertTo2d = function spriteConvertTo2d() + { + if (this.proj) return; + this.calculateVertices = Sprite2d.prototype.calculateVertices; + this.calculateTrimmedVertices = Sprite2d.prototype.calculateTrimmedVertices; + this._calculateBounds = Sprite2d.prototype._calculateBounds; + this.pluginName = 'batch2d'; + convertTo2d.call(this); + }; + + display.Container.prototype.convertSubtreeTo2d = function convertSubtreeTo2d() + { + this.convertTo2d(); + for (let i = 0; i < this.children.length; i++) + { + this.children[i].convertSubtreeTo2d(); + } + }; + + meshExtras.SimpleMesh.prototype.convertTo2d + = meshExtras.SimpleRope.prototype.convertTo2d + = function meshConvertTo2d() + { + if (this.proj) return; + this.calculateVertices = Mesh2d.prototype.calculateVertices; + this._renderDefault = Mesh2d.prototype._renderDefault; + if (this.material.pluginName !== 'batch2d') + { + this.material = new mesh.MeshMaterial(this.material.texture, { + program: core.Program.from(Mesh2d.defaultVertexShader, Mesh2d.defaultFragmentShader), + pluginName: 'batch2d' + }); + } + convertTo2d.call(this); + }; + + spriteTiling.TilingSprite.prototype.convertTo2d = function tilingConvertTo2d() + { + if (this.proj) return; + + this.tileProj = new Projection2d(this.tileTransform); + this.tileProj.reverseLocalOrder = true; + this.uvRespectAnchor = true; + + this.calculateTrimmedVertices = Sprite2d.prototype.calculateTrimmedVertices; + this._calculateBounds = Sprite2d.prototype._calculateBounds; + this._render = TilingSprite2d.prototype._render; + + this.pluginName = 'tilingSprite2d'; + convertTo2d.call(this); + }; + + class Text2d extends text.Text + { + constructor(text, style, canvas) + { + super(text, style, canvas);Text2d.prototype.__init.call(this);; + this.proj = new Projection2d(this.transform); + this.pluginName = 'batch2d'; + } + + + __init() {this.vertexData2d = null;} + + get worldTransform() + { + return this.proj.affine ? this.transform.worldTransform : this.proj.world ; + } + } + + Text2d.prototype.calculateVertices = Sprite2d.prototype.calculateVertices; + Text2d.prototype.calculateTrimmedVertices = Sprite2d.prototype.calculateTrimmedVertices; + (Text2d.prototype )._calculateBounds = Sprite2d.prototype._calculateBounds; + + const spriteMaskVert = ` +attribute vec2 aVertexPosition; +attribute vec2 aTextureCoord; + +uniform mat3 projectionMatrix; +uniform mat3 otherMatrix; + +varying vec3 vMaskCoord; +varying vec2 vTextureCoord; + +void main(void) +{ +gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0); + +vTextureCoord = aTextureCoord; +vMaskCoord = otherMatrix * vec3( aTextureCoord, 1.0); +} +`; + const spriteMaskFrag = ` +varying vec3 vMaskCoord; +varying vec2 vTextureCoord; + +uniform sampler2D uSampler; +uniform sampler2D mask; +uniform float alpha; +uniform vec4 maskClamp; + +void main(void) +{ +vec2 uv = vMaskCoord.xy / vMaskCoord.z; + +float clip = step(3.5, + step(maskClamp.x, uv.x) + + step(maskClamp.y, uv.y) + + step(uv.x, maskClamp.z) + + step(uv.y, maskClamp.w)); + +vec4 original = texture2D(uSampler, vTextureCoord); +vec4 masky = texture2D(mask, uv); + +original *= (masky.r * masky.a * alpha * clip); + +gl_FragColor = original; +} +`; + + const tempMat$2 = new Matrix2d(); + + class SpriteMaskFilter2d extends core.Filter + { + constructor(sprite) + { + super(spriteMaskVert, spriteMaskFrag);SpriteMaskFilter2d.prototype.__init.call(this);; + + sprite.renderable = false; + + this.maskSprite = sprite; + } + + + __init() {this.maskMatrix = new Matrix2d();} + + apply(filterManager, input, output, + clearMode) + { + const maskSprite = this.maskSprite; + const tex = this.maskSprite.texture; + + if (!tex.valid) + { + return; + } + if (!tex.uvMatrix) + { + // margin = 0.0, let it bleed a bit, shader code becomes easier + // assuming that atlas textures were made with 1-pixel padding + tex.uvMatrix = new core.TextureMatrix(tex, 0.0); + } + tex.uvMatrix.update(); + + this.uniforms.npmAlpha = tex.baseTexture.alphaMode ? 0.0 : 1.0; + this.uniforms.mask = maskSprite.texture; + this.uniforms.otherMatrix = SpriteMaskFilter2d.calculateSpriteMatrix(input, this.maskMatrix, maskSprite) + .prepend(tex.uvMatrix.mapCoord); + this.uniforms.alpha = maskSprite.worldAlpha; + this.uniforms.maskClamp = tex.uvMatrix.uClampFrame; + + filterManager.applyFilter(this, input, output, clearMode); + } + + static calculateSpriteMatrix(input, mappedMatrix, sprite) + { + const proj = (sprite ).proj ; + + const filterArea = (input ).filterFrame; + + // eslint-disable-next-line max-len + const worldTransform = proj && !proj._affine ? proj.world.copyTo2dOr3d(tempMat$2) : tempMat$2.copyFrom(sprite.transform.worldTransform); + const texture = sprite.texture.orig; + + mappedMatrix.set(input.width, 0, 0, input.height, filterArea.x, filterArea.y); + worldTransform.invert(); + mappedMatrix.setToMult(worldTransform, mappedMatrix); + mappedMatrix.scaleAndTranslate(1.0 / texture.width, 1.0 / texture.height, + sprite.anchor.x, sprite.anchor.y); + + return mappedMatrix; + } + } + + core.MaskSystem.prototype.pushSpriteMask = function pushSpriteMask(maskData) + { + const { maskObject } = maskData; + const target = (maskData )._target; + + let alphaMaskFilter = this.alphaMaskPool[this.alphaMaskIndex]; + + if (!alphaMaskFilter) + { + alphaMaskFilter = this.alphaMaskPool[this.alphaMaskIndex] = [new SpriteMaskFilter2d(maskObject )]; + } + + alphaMaskFilter[0].resolution = this.renderer.resolution; + alphaMaskFilter[0].maskSprite = maskObject; + + const stashFilterArea = target.filterArea; + + target.filterArea = maskObject.getBounds(true); + this.renderer.filter.push(target, alphaMaskFilter); + target.filterArea = stashFilterArea; + + this.alphaMaskIndex++; + }; + + core.Renderer.registerPlugin('tilingSprite2d', TilingSprite2dRenderer ); + + class Point3d extends math.Point + { + // TODO: pixi 6.1.0 global mixin + + constructor(x, y, z) + { + super(x, y); + this.z = z; + } + + set(x, y, z) + { + this.x = x || 0; + this.y = (y === undefined) ? this.x : (y || 0); + this.z = (y === undefined) ? this.x : (z || 0); + + return this; + } + + copyFrom(p) + { + // TODO: pixi 6.1.0 global mixin + this.set(p.x, p.y, (p ).z || 0); + + return this; + } + + copyTo(p) + { + (p ).set(this.x, this.y, this.z); + + return p; + } + } + + class ObservablePoint3d extends math.ObservablePoint + {constructor(...args) { super(...args); ObservablePoint3d.prototype.__init.call(this); } + __init() {this._z = 0;} + + get z() + { + return this._z; + } + + set z(value) + { + if (this._z !== value) + { + this._z = value; + this.cb.call(this.scope); + } + } + + set(x, y, z) + { + const _x = x || 0; + const _y = (y === undefined) ? _x : (y || 0); + const _z = (y === undefined) ? _x : (z || 0); + + if (this._x !== _x || this._y !== _y || this._z !== _z) + { + this._x = _x; + this._y = _y; + this._z = _z; + this.cb.call(this.scope); + } + + return this; + } + + copyFrom(p) + { + // TODO: pixi 6.1.0 global mixin + this.set(p.x, p.y, (p ).z || 0); + + return this; + } + + copyTo(p) + { + (p ).set(this._x, this._y, this._z); + + return p; + } + } + + class Euler + { + constructor(x, y, z) + {;Euler.prototype.__init.call(this);Euler.prototype.__init2.call(this);Euler.prototype.__init3.call(this); + /** + * @member {number} + * @default 0 + */ + this._x = x || 0; + + /** + * @member {number} + * @default 0 + */ + this._y = y || 0; + + /** + * @member {number} + * @default 0 + */ + this._z = z || 0; + + this.quaternion = new Float64Array(4); + this.quaternion[3] = 1; + + this.update(); + } + + __init() {this._quatUpdateId = -1;} + __init2() {this._quatDirtyId = 0;} + + + + + + + __init3() {this._sign = 1;} + + get x() + { + return this._x; + } + + set x(value) + { + if (this._x !== value) + { + this._x = value; + this._quatDirtyId++; + } + } + + get y() + { + return this._y; + } + + set y(value) + { + if (this._y !== value) + { + this._y = value; + this._quatDirtyId++; + } + } + + get z() + { + return this._z; + } + + set z(value) + { + if (this._z !== value) + { + this._z = value; + this._quatDirtyId++; + } + } + + get pitch() + { + return this._x; + } + + set pitch(value) + { + if (this._x !== value) + { + this._x = value; + this._quatDirtyId++; + } + } + + get yaw() + { + return this._y; + } + + set yaw(value) + { + if (this._y !== value) + { + this._y = value; + this._quatDirtyId++; + } + } + + get roll() + { + return this._z; + } + + set roll(value) + { + if (this._z !== value) + { + this._z = value; + this._quatDirtyId++; + } + } + + set(x, y, z) + { + const _x = x || 0; + const _y = y || 0; + const _z = z || 0; + + if (this._x !== _x || this._y !== _y || this._z !== _z) + { + this._x = _x; + this._y = _y; + this._z = _z; + this._quatDirtyId++; + } + } + + copyFrom(euler) + { + const _x = euler.x; + const _y = euler.y; + const _z = euler.z; + + if (this._x !== _x || this._y !== _y || this._z !== _z) + { + this._x = _x; + this._y = _y; + this._z = _z; + this._quatDirtyId++; + } + + return this; + } + + copyTo(p) + { + p.set(this._x, this._y, this._z); + + return p; + } + + equals(euler) + { + return this._x === euler.x + && this._y === euler.y + && this._z === euler.z; + } + + clone() + { + return new Euler(this._x, this._y, this._z); + } + + update() + { + if (this._quatUpdateId === this._quatDirtyId) + { + return false; + } + this._quatUpdateId = this._quatDirtyId; + + const c1 = Math.cos(this._x / 2); + const c2 = Math.cos(this._y / 2); + const c3 = Math.cos(this._z / 2); + + const s = this._sign; + const s1 = s * Math.sin(this._x / 2); + const s2 = s * Math.sin(this._y / 2); + const s3 = s * Math.sin(this._z / 2); + + const q = this.quaternion; + + q[0] = (s1 * c2 * c3) + (c1 * s2 * s3); + q[1] = (c1 * s2 * c3) - (s1 * c2 * s3); + q[2] = (c1 * c2 * s3) + (s1 * s2 * c3); + q[3] = (c1 * c2 * c3) - (s1 * s2 * s3); + + return true; + } + } + + /** + * The Euler angles, order is YZX. Except for projections (camera.lookEuler), its reversed XZY + * @class + * @namespace PIXI.projection + * @param x pitch + * @param y yaw + * @param z roll + * @constructor + */ + + class ObservableEuler + { + // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types + constructor( cb, scope, x, y, z) + {;this.cb = cb;this.scope = scope;ObservableEuler.prototype.__init.call(this);ObservableEuler.prototype.__init2.call(this);ObservableEuler.prototype.__init3.call(this); + /** + * @member {number} + * @default 0 + */ + this._x = x || 0; + + /** + * @member {number} + * @default 0 + */ + this._y = y || 0; + + /** + * @member {number} + * @default 0 + */ + this._z = z || 0; + + this.quaternion = new Float64Array(4); + this.quaternion[3] = 1; + + this.update(); + } + + __init() {this._quatUpdateId = -1;} + __init2() {this._quatDirtyId = 0;} + + + + + + + __init3() {this._sign = 1;} + + get x() + { + return this._x; + } + + set x(value) + { + if (this._x !== value) + { + this._x = value; + this._quatDirtyId++; + this.cb.call(this.scope); + } + } + + get y() + { + return this._y; + } + + set y(value) + { + if (this._y !== value) + { + this._y = value; + this._quatDirtyId++; + this.cb.call(this.scope); + } + } + + get z() + { + return this._z; + } + + set z(value) + { + if (this._z !== value) + { + this._z = value; + this._quatDirtyId++; + this.cb.call(this.scope); + } + } + + get pitch() + { + return this._x; + } + + set pitch(value) + { + if (this._x !== value) + { + this._x = value; + this._quatDirtyId++; + this.cb.call(this.scope); + } + } + + get yaw() + { + return this._y; + } + + set yaw(value) + { + if (this._y !== value) + { + this._y = value; + this._quatDirtyId++; + this.cb.call(this.scope); + } + } + + get roll() + { + return this._z; + } + + set roll(value) + { + if (this._z !== value) + { + this._z = value; + this._quatDirtyId++; + this.cb.call(this.scope); + } + } + + set(x, y, z) + { + const _x = x || 0; + const _y = y || 0; + const _z = z || 0; + + if (this._x !== _x || this._y !== _y || this._z !== _z) + { + this._x = _x; + this._y = _y; + this._z = _z; + this._quatDirtyId++; + this.cb.call(this.scope); + } + + return this; + } + + copyFrom(euler) + { + const _x = euler.x; + const _y = euler.y; + const _z = euler.z; + + if (this._x !== _x || this._y !== _y || this._z !== _z) + { + this._x = _x; + this._y = _y; + this._z = _z; + this._quatDirtyId++; + this.cb.call(this.scope); + } + + return this; + } + + copyTo(p) + { + p.set(this._x, this._y, this._z); + + return p; + } + + equals(euler) + { + return this._x === euler.x + && this._y === euler.y + && this._z === euler.z; + } + + clone() + { + return new Euler(this._x, this._y, this._z); + } + + update() + { + if (this._quatUpdateId === this._quatDirtyId) + { + return false; + } + this._quatUpdateId = this._quatDirtyId; + + const c1 = Math.cos(this._x / 2); + const c2 = Math.cos(this._y / 2); + const c3 = Math.cos(this._z / 2); + + const s = this._sign; + const s1 = s * Math.sin(this._x / 2); + const s2 = s * Math.sin(this._y / 2); + const s3 = s * Math.sin(this._z / 2); + + const q = this.quaternion; + + q[0] = (s1 * c2 * c3) + (c1 * s2 * s3); + q[1] = (c1 * s2 * c3) - (s1 * c2 * s3); + q[2] = (c1 * c2 * s3) + (s1 * s2 * c3); + q[3] = (c1 * c2 * c3) - (s1 * s2 * s3); + + return true; + } + } + + const mat4id = [1, 0, 0, 0, + 0, 1, 0, 0, + 0, 0, 1, 0, + 0, 0, 0, 1]; + + class Matrix3d + { + /** + * A default (identity) matrix + * + * @static + * @const + */ + static __initStatic() {this.IDENTITY = new Matrix3d();} + + /** + * A temp matrix + * + * @static + * @const + */ + static __initStatic2() {this.TEMP_MATRIX = new Matrix3d();} + + /** + * mat4 implementation through array of 16 elements + */ + + + __init() {this.floatArray = null;} + + __init2() {this._dirtyId = 0;} + __init3() {this._updateId = -1;} + __init4() {this._mat4inv = null;} + __init5() {this.cacheInverse = false;} + + constructor(backingArray) + {;Matrix3d.prototype.__init.call(this);Matrix3d.prototype.__init2.call(this);Matrix3d.prototype.__init3.call(this);Matrix3d.prototype.__init4.call(this);Matrix3d.prototype.__init5.call(this); + this.mat4 = new Float64Array(backingArray || mat4id); + } + + get a() + { + return this.mat4[0] / this.mat4[15]; + } + + set a(value) + { + this.mat4[0] = value * this.mat4[15]; + } + + get b() + { + return this.mat4[1] / this.mat4[15]; + } + + set b(value) + { + this.mat4[1] = value * this.mat4[15]; + } + + get c() + { + return this.mat4[4] / this.mat4[15]; + } + + set c(value) + { + this.mat4[4] = value * this.mat4[15]; + } + + get d() + { + return this.mat4[5] / this.mat4[15]; + } + + set d(value) + { + this.mat4[5] = value * this.mat4[15]; + } + + get tx() + { + return this.mat4[12] / this.mat4[15]; + } + + set tx(value) + { + this.mat4[12] = value * this.mat4[15]; + } + + get ty() + { + return this.mat4[13] / this.mat4[15]; + } + + set ty(value) + { + this.mat4[13] = value * this.mat4[15]; + } + + set(a, b, c, d, tx, ty) + { + const mat4 = this.mat4; + + mat4[0] = a; + mat4[1] = b; + mat4[2] = 0; + mat4[3] = 0; + mat4[4] = c; + mat4[5] = d; + mat4[6] = 0; + mat4[7] = 0; + mat4[8] = 0; + mat4[9] = 0; + mat4[10] = 1; + mat4[11] = 0; + mat4[12] = tx; + mat4[13] = ty; + mat4[14] = 0; + mat4[15] = 1; + + return this; + } + + toArray(transpose, out) + { + if (!this.floatArray) + { + this.floatArray = new Float32Array(9); + } + + const array = out || this.floatArray; + const mat3 = this.mat4; + + if (transpose) + { + array[0] = mat3[0]; + array[1] = mat3[1]; + array[2] = mat3[3]; + array[3] = mat3[4]; + array[4] = mat3[5]; + array[5] = mat3[7]; + array[6] = mat3[12]; + array[7] = mat3[13]; + array[8] = mat3[15]; + } + else + { + // this branch is NEVER USED in pixi + array[0] = mat3[0]; + array[1] = mat3[4]; + array[2] = mat3[12]; + array[3] = mat3[2]; + array[4] = mat3[6]; + array[5] = mat3[13]; + array[6] = mat3[3]; + array[7] = mat3[7]; + array[8] = mat3[15]; + } + + return array; + } + + setToTranslation(tx, ty, tz) + { + const mat4 = this.mat4; + + mat4[0] = 1; + mat4[1] = 0; + mat4[2] = 0; + mat4[3] = 0; + + mat4[4] = 0; + mat4[5] = 1; + mat4[6] = 0; + mat4[7] = 0; + + mat4[8] = 0; + mat4[9] = 0; + mat4[10] = 1; + mat4[11] = 0; + + mat4[12] = tx; + mat4[13] = ty; + mat4[14] = tz; + mat4[15] = 1; + } + + // eslint-disable-next-line max-len + setToRotationTranslationScale(quat, tx, ty, tz, sx, sy, sz) + { + const out = this.mat4; + + const x = quat[0]; const y = quat[1]; const z = quat[2]; const + w = quat[3]; + const x2 = x + x; + const y2 = y + y; + const z2 = z + z; + + const xx = x * x2; + const xy = x * y2; + const xz = x * z2; + const yy = y * y2; + const yz = y * z2; + const zz = z * z2; + const wx = w * x2; + const wy = w * y2; + const wz = w * z2; + + out[0] = (1 - (yy + zz)) * sx; + out[1] = (xy + wz) * sx; + out[2] = (xz - wy) * sx; + out[3] = 0; + out[4] = (xy - wz) * sy; + out[5] = (1 - (xx + zz)) * sy; + out[6] = (yz + wx) * sy; + out[7] = 0; + out[8] = (xz + wy) * sz; + out[9] = (yz - wx) * sz; + out[10] = (1 - (xx + yy)) * sz; + out[11] = 0; + out[12] = tx; + out[13] = ty; + out[14] = tz; + out[15] = 1; + + return out; + } + + apply(pos, newPos) + { + newPos = newPos || new Point3d(); + + const mat4 = this.mat4; + const x = pos.x; + const y = pos.y; + // TODO: pixi 6.1.0 global mixin + const z = (pos ).z || 0; + + // TODO: apply for 2d point + + const w = 1.0 / (mat4[3] * x + mat4[7] * y + mat4[11] * z + mat4[15]); + + newPos.x = w * (mat4[0] * x + mat4[4] * y + mat4[8] * z + mat4[12]); + newPos.y = w * (mat4[1] * x + mat4[5] * y + mat4[9] * z + mat4[13]); + // TODO: pixi 6.1.0 global mixin + (newPos ).z = w * (mat4[2] * x + mat4[6] * y + mat4[10] * z + mat4[14]); + + return newPos; + } + + translate(tx, ty, tz) + { + const a = this.mat4; + + a[12] = a[0] * tx + a[4] * ty + a[8] * tz + a[12]; + a[13] = a[1] * tx + a[5] * ty + a[9] * tz + a[13]; + a[14] = a[2] * tx + a[6] * ty + a[10] * tz + a[14]; + a[15] = a[3] * tx + a[7] * ty + a[11] * tz + a[15]; + + return this; + } + + scale(x, y, z) + { + const mat4 = this.mat4; + + mat4[0] *= x; + mat4[1] *= x; + mat4[2] *= x; + mat4[3] *= x; + + mat4[4] *= y; + mat4[5] *= y; + mat4[6] *= y; + mat4[7] *= y; + + if (z !== undefined) + { + mat4[8] *= z; + mat4[9] *= z; + mat4[10] *= z; + mat4[11] *= z; + } + + return this; + } + + scaleAndTranslate(scaleX, scaleY, scaleZ, tx, ty, tz) + { + const mat4 = this.mat4; + + mat4[0] = scaleX * mat4[0] + tx * mat4[3]; + mat4[1] = scaleY * mat4[1] + ty * mat4[3]; + mat4[2] = scaleZ * mat4[2] + tz * mat4[3]; + + mat4[4] = scaleX * mat4[4] + tx * mat4[7]; + mat4[5] = scaleY * mat4[5] + ty * mat4[7]; + mat4[6] = scaleZ * mat4[6] + tz * mat4[7]; + + mat4[8] = scaleX * mat4[8] + tx * mat4[11]; + mat4[9] = scaleY * mat4[9] + ty * mat4[11]; + mat4[10] = scaleZ * mat4[10] + tz * mat4[11]; + + mat4[12] = scaleX * mat4[12] + tx * mat4[15]; + mat4[13] = scaleY * mat4[13] + ty * mat4[15]; + mat4[14] = scaleZ * mat4[14] + tz * mat4[15]; + } + + // TODO: remove props + applyInverse(pos, newPos) + { + newPos = (newPos || new Point3d()) ; + if (!this._mat4inv) + { + this._mat4inv = new Float64Array(16); + } + + const mat4 = this._mat4inv; + const a = this.mat4; + const x = pos.x; + const y = pos.y; + // TODO: pixi 6.1.0 global mixin + let z = (pos ).z || 0; + + if (!this.cacheInverse || this._updateId !== this._dirtyId) + { + this._updateId = this._dirtyId; + Matrix3d.glMatrixMat4Invert(mat4, a); + } + + const w1 = 1.0 / (mat4[3] * x + mat4[7] * y + mat4[11] * z + mat4[15]); + const x1 = w1 * (mat4[0] * x + mat4[4] * y + mat4[8] * z + mat4[12]); + const y1 = w1 * (mat4[1] * x + mat4[5] * y + mat4[9] * z + mat4[13]); + const z1 = w1 * (mat4[2] * x + mat4[6] * y + mat4[10] * z + mat4[14]); + + z += 1.0; + + const w2 = 1.0 / (mat4[3] * x + mat4[7] * y + mat4[11] * z + mat4[15]); + const x2 = w2 * (mat4[0] * x + mat4[4] * y + mat4[8] * z + mat4[12]); + const y2 = w2 * (mat4[1] * x + mat4[5] * y + mat4[9] * z + mat4[13]); + const z2 = w2 * (mat4[2] * x + mat4[6] * y + mat4[10] * z + mat4[14]); + + if (Math.abs(z1 - z2) < 1e-10) + { + (newPos ).set(NaN, NaN, 0); + } + + const alpha = (0 - z1) / (z2 - z1); + + (newPos ).set((x2 - x1) * alpha + x1, (y2 - y1) * alpha + y1, 0.0); + + return newPos; + } + + invert() + { + Matrix3d.glMatrixMat4Invert(this.mat4, this.mat4); + + return this; + } + + invertCopyTo(matrix) + { + if (!this._mat4inv) + { + this._mat4inv = new Float64Array(16); + } + + const mat4 = this._mat4inv; + const a = this.mat4; + + if (!this.cacheInverse || this._updateId !== this._dirtyId) + { + this._updateId = this._dirtyId; + Matrix3d.glMatrixMat4Invert(mat4, a); + } + + matrix.mat4.set(mat4); + } + + identity() + { + const mat3 = this.mat4; + + mat3[0] = 1; + mat3[1] = 0; + mat3[2] = 0; + mat3[3] = 0; + + mat3[4] = 0; + mat3[5] = 1; + mat3[6] = 0; + mat3[7] = 0; + + mat3[8] = 0; + mat3[9] = 0; + mat3[10] = 1; + mat3[11] = 0; + + mat3[12] = 0; + mat3[13] = 0; + mat3[14] = 0; + mat3[15] = 1; + + return this; + } + + clone() + { + return new Matrix3d(this.mat4); + } + + copyTo3d(matrix) + { + const mat3 = this.mat4; + const ar2 = matrix.mat4; + + ar2[0] = mat3[0]; + ar2[1] = mat3[1]; + ar2[2] = mat3[2]; + ar2[3] = mat3[3]; + ar2[4] = mat3[4]; + ar2[5] = mat3[5]; + ar2[6] = mat3[6]; + ar2[7] = mat3[7]; + ar2[8] = mat3[8]; + + return matrix; + } + + copyTo2d(matrix) + { + const mat3 = this.mat4; + const ar2 = matrix.mat3; + + ar2[0] = mat3[0]; + ar2[1] = mat3[1]; + ar2[2] = mat3[3]; + ar2[3] = mat3[4]; + ar2[4] = mat3[5]; + ar2[5] = mat3[7]; + ar2[6] = mat3[12]; + ar2[7] = mat3[13]; + ar2[8] = mat3[15]; + + return matrix; + } + + copyTo2dOr3d(matrix) + { + if (matrix instanceof Matrix2d) + { + return this.copyTo2d(matrix) ; + } + + return this.copyTo3d(matrix ) ; + } + + /** + * legacy method, change the values of given pixi matrix + * @param matrix + * @param affine + * @param preserveOrientation + * @return matrix + */ + copyTo(matrix, affine, preserveOrientation) + { + const mat3 = this.mat4; + const d = 1.0 / mat3[15]; + const tx = mat3[12] * d; const + ty = mat3[13] * d; + + matrix.a = (mat3[0] - mat3[3] * tx) * d; + matrix.b = (mat3[1] - mat3[3] * ty) * d; + matrix.c = (mat3[4] - mat3[7] * tx) * d; + matrix.d = (mat3[5] - mat3[7] * ty) * d; + matrix.tx = tx; + matrix.ty = ty; + + if (affine >= 2) + { + let D = matrix.a * matrix.d - matrix.b * matrix.c; + + if (!preserveOrientation) + { + D = Math.abs(D); + } + if (affine === exports.AFFINE.POINT) + { + if (D > 0) + { + D = 1; + } + else D = -1; + matrix.a = D; + matrix.b = 0; + matrix.c = 0; + matrix.d = D; + } + else if (affine === exports.AFFINE.AXIS_X) + { + D /= Math.sqrt(matrix.b * matrix.b + matrix.d * matrix.d); + matrix.c = 0; + matrix.d = D; + } + else if (affine === exports.AFFINE.AXIS_Y) + { + D /= Math.sqrt(matrix.a * matrix.a + matrix.c * matrix.c); + matrix.a = D; + matrix.c = 0; + } + } + + return matrix; + } + + /** + * legacy method, change the values of given pixi matrix + * @param matrix + * @return + */ + copyFrom(matrix) + { + const mat3 = this.mat4; + + mat3[0] = matrix.a; + mat3[1] = matrix.b; + mat3[2] = 0; + mat3[3] = 0; + + mat3[4] = matrix.c; + mat3[5] = matrix.d; + mat3[6] = 0; + mat3[7] = 0; + + mat3[8] = 0; + mat3[9] = 0; + mat3[10] = 1; + mat3[11] = 0; + + mat3[12] = matrix.tx; + mat3[13] = matrix.ty; + mat3[14] = 0; + mat3[15] = 1; + + this._dirtyId++; + + return this; + } + + setToMultLegacy(pt, lt) + { + const out = this.mat4; + const b = lt.mat4; + + const a00 = pt.a; const a01 = pt.b; + const a10 = pt.c; const a11 = pt.d; + const a30 = pt.tx; const + a31 = pt.ty; + + let b0 = b[0]; let b1 = b[1]; let b2 = b[2]; let + b3 = b[3]; + + out[0] = b0 * a00 + b1 * a10 + b3 * a30; + out[1] = b0 * a01 + b1 * a11 + b3 * a31; + out[2] = b2; + out[3] = b3; + + b0 = b[4]; + b1 = b[5]; + b2 = b[6]; + b3 = b[7]; + out[4] = b0 * a00 + b1 * a10 + b3 * a30; + out[5] = b0 * a01 + b1 * a11 + b3 * a31; + out[6] = b2; + out[7] = b3; + + b0 = b[8]; + b1 = b[9]; + b2 = b[10]; + b3 = b[11]; + out[8] = b0 * a00 + b1 * a10 + b3 * a30; + out[9] = b0 * a01 + b1 * a11 + b3 * a31; + out[10] = b2; + out[11] = b3; + + b0 = b[12]; + b1 = b[13]; + b2 = b[14]; + b3 = b[15]; + out[12] = b0 * a00 + b1 * a10 + b3 * a30; + out[13] = b0 * a01 + b1 * a11 + b3 * a31; + out[14] = b2; + out[15] = b3; + + this._dirtyId++; + + return this; + } + + setToMultLegacy2(pt, lt) + { + const out = this.mat4; + const a = pt.mat4; + + const a00 = a[0]; const a01 = a[1]; const a02 = a[2]; const + a03 = a[3]; + const a10 = a[4]; const a11 = a[5]; const a12 = a[6]; const + a13 = a[7]; + + const b00 = lt.a; const b01 = lt.b; + const b10 = lt.c; const b11 = lt.d; + const b30 = lt.tx; const + b31 = lt.ty; + + out[0] = b00 * a00 + b01 * a10; + out[1] = b00 * a01 + b01 * a11; + out[2] = b00 * a02 + b01 * a12; + out[3] = b00 * a03 + b01 * a13; + + out[4] = b10 * a00 + b11 * a10; + out[5] = b10 * a01 + b11 * a11; + out[6] = b10 * a02 + b11 * a12; + out[7] = b10 * a03 + b11 * a13; + + out[8] = a[8]; + out[9] = a[9]; + out[10] = a[10]; + out[11] = a[11]; + + out[12] = b30 * a00 + b31 * a10 + a[12]; + out[13] = b30 * a01 + b31 * a11 + a[13]; + out[14] = b30 * a02 + b31 * a12 + a[14]; + out[15] = b30 * a03 + b31 * a13 + a[15]; + + this._dirtyId++; + + return this; + } + + // that's transform multiplication we use + setToMult(pt, lt) + { + Matrix3d.glMatrixMat4Multiply(this.mat4, pt.mat4, lt.mat4); + + this._dirtyId++; + + return this; + } + + // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types + prepend(lt) + { + if (lt.mat4) + { + this.setToMult(lt, this); + } + else + { + this.setToMultLegacy(lt, this); + } + } + + static glMatrixMat4Invert(out, a) + { + const a00 = a[0]; const a01 = a[1]; const a02 = a[2]; const + a03 = a[3]; + const a10 = a[4]; const a11 = a[5]; const a12 = a[6]; const + a13 = a[7]; + const a20 = a[8]; const a21 = a[9]; const a22 = a[10]; const + a23 = a[11]; + const a30 = a[12]; const a31 = a[13]; const a32 = a[14]; const + a33 = a[15]; + + const b00 = a00 * a11 - a01 * a10; + const b01 = a00 * a12 - a02 * a10; + const b02 = a00 * a13 - a03 * a10; + const b03 = a01 * a12 - a02 * a11; + const b04 = a01 * a13 - a03 * a11; + const b05 = a02 * a13 - a03 * a12; + const b06 = a20 * a31 - a21 * a30; + const b07 = a20 * a32 - a22 * a30; + const b08 = a20 * a33 - a23 * a30; + const b09 = a21 * a32 - a22 * a31; + const b10 = a21 * a33 - a23 * a31; + const b11 = a22 * a33 - a23 * a32; + + // Calculate the determinant + let det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06; + + if (!det) + { + return null; + } + det = 1.0 / det; + + out[0] = (a11 * b11 - a12 * b10 + a13 * b09) * det; + out[1] = (a02 * b10 - a01 * b11 - a03 * b09) * det; + out[2] = (a31 * b05 - a32 * b04 + a33 * b03) * det; + out[3] = (a22 * b04 - a21 * b05 - a23 * b03) * det; + out[4] = (a12 * b08 - a10 * b11 - a13 * b07) * det; + out[5] = (a00 * b11 - a02 * b08 + a03 * b07) * det; + out[6] = (a32 * b02 - a30 * b05 - a33 * b01) * det; + out[7] = (a20 * b05 - a22 * b02 + a23 * b01) * det; + out[8] = (a10 * b10 - a11 * b08 + a13 * b06) * det; + out[9] = (a01 * b08 - a00 * b10 - a03 * b06) * det; + out[10] = (a30 * b04 - a31 * b02 + a33 * b00) * det; + out[11] = (a21 * b02 - a20 * b04 - a23 * b00) * det; + out[12] = (a11 * b07 - a10 * b09 - a12 * b06) * det; + out[13] = (a00 * b09 - a01 * b07 + a02 * b06) * det; + out[14] = (a31 * b01 - a30 * b03 - a32 * b00) * det; + out[15] = (a20 * b03 - a21 * b01 + a22 * b00) * det; + + return out; + } + + static glMatrixMat4Multiply(out, a, b) + { + const a00 = a[0]; const a01 = a[1]; const a02 = a[2]; const + a03 = a[3]; + const a10 = a[4]; const a11 = a[5]; const a12 = a[6]; const + a13 = a[7]; + const a20 = a[8]; const a21 = a[9]; const a22 = a[10]; const + a23 = a[11]; + const a30 = a[12]; const a31 = a[13]; const a32 = a[14]; const + a33 = a[15]; + + // Cache only the current line of the second matrix + let b0 = b[0]; let b1 = b[1]; let b2 = b[2]; let + b3 = b[3]; + + out[0] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30; + out[1] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31; + out[2] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32; + out[3] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33; + + b0 = b[4]; + b1 = b[5]; + b2 = b[6]; + b3 = b[7]; + out[4] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30; + out[5] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31; + out[6] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32; + out[7] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33; + + b0 = b[8]; + b1 = b[9]; + b2 = b[10]; + b3 = b[11]; + out[8] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30; + out[9] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31; + out[10] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32; + out[11] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33; + + b0 = b[12]; + b1 = b[13]; + b2 = b[14]; + b3 = b[15]; + out[12] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30; + out[13] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31; + out[14] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32; + out[15] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33; + + return out; + } + } Matrix3d.__initStatic(); Matrix3d.__initStatic2(); + + const tempMat$1 = new Matrix3d(); + + class Projection3d extends LinearProjection + { + constructor(legacy, enable) + { + super(legacy, enable);Projection3d.prototype.__init.call(this);Projection3d.prototype.__init2.call(this);Projection3d.prototype.__init3.call(this);Projection3d.prototype.__init4.call(this);Projection3d.prototype.__init5.call(this);Projection3d.prototype.__init6.call(this);; + this.local = new Matrix3d(); + this.world = new Matrix3d(); + + this.local.cacheInverse = true; + this.world.cacheInverse = true; + + this.position._z = 0; + this.scale._z = 1; + this.pivot._z = 0; + } + + __init() {this.cameraMatrix = null;} + + __init2() {this._cameraMode = false;} + + get cameraMode() + { + return this._cameraMode; + } + + set cameraMode(value) + { + if (this._cameraMode === value) + { + return; + } + this._cameraMode = value; + + this.euler._sign = this._cameraMode ? -1 : 1; + this.euler._quatDirtyId++; + + if (value) + { + this.cameraMatrix = new Matrix3d(); + } + } + + __init3() {this.position = new ObservablePoint3d(this.onChange, this, 0, 0);} + __init4() {this.scale = new ObservablePoint3d(this.onChange, this, 1, 1);} + __init5() {this.euler = new ObservableEuler(this.onChange, this, 0, 0, 0);} + __init6() {this.pivot = new ObservablePoint3d(this.onChange, this, 0, 0);} + + onChange() + { + this._projID++; + } + + clear() + { + if (this.cameraMatrix) + { + this.cameraMatrix.identity(); + } + this.position.set(0, 0, 0); + this.scale.set(1, 1, 1); + this.euler.set(0, 0, 0); + this.pivot.set(0, 0, 0); + super.clear(); + } + + updateLocalTransform(lt) + { + if (this._projID === 0) + { + this.local.copyFrom(lt); + + return; + } + const matrix = this.local; + const euler = this.euler; + const pos = this.position; + const scale = this.scale; + const pivot = this.pivot; + + euler.update(); + + if (!this.cameraMode) + { + matrix.setToRotationTranslationScale(euler.quaternion, pos._x, pos._y, pos._z, scale._x, scale._y, scale._z); + matrix.translate(-pivot._x, -pivot._y, -pivot._z); + matrix.setToMultLegacy(lt, matrix); + + return; + } + + matrix.setToMultLegacy(lt, this.cameraMatrix); + matrix.translate(pivot._x, pivot._y, pivot._z); + matrix.scale(1.0 / scale._x, 1.0 / scale._y, 1.0 / scale._z); + tempMat$1.setToRotationTranslationScale(euler.quaternion, 0, 0, 0, 1, 1, 1); + matrix.setToMult(matrix, tempMat$1); + matrix.translate(-pos._x, -pos._y, -pos._z); + + this.local._dirtyId++; + } + } + + /* eslint-disable no-mixed-operators */ + + + function container3dWorldTransform() + { + return this.proj.affine ? this.transform.worldTransform : this.proj.world ; + } + + + + + + + + + + + + + class Container3d extends display.Container + { + constructor() + { + super(); + this.proj = new Projection3d(this.transform); + } + + + + isFrontFace(forceUpdate = false) + { + if (forceUpdate) + { + this._recursivePostUpdateTransform(); + this.displayObjectUpdateTransform(); + } + + const mat = this.proj.world.mat4; + const dx1 = mat[0] * mat[15] - mat[3] * mat[12]; + const dy1 = mat[1] * mat[15] - mat[3] * mat[13]; + const dx2 = mat[4] * mat[15] - mat[7] * mat[12]; + const dy2 = mat[5] * mat[15] - mat[7] * mat[13]; + + return dx1 * dy2 - dx2 * dy1 > 0; + } + + /** + * returns depth from 0 to 1 + * + * @param {boolean} forceUpdate whether to force matrix updates + * @returns {number} depth + */ + getDepth(forceUpdate = false) + { + if (forceUpdate) + { + this._recursivePostUpdateTransform(); + this.displayObjectUpdateTransform(); + } + + const mat4 = this.proj.world.mat4; + + return mat4[14] / mat4[15]; + } + + toLocal(position, from, point, skipUpdate, + step = exports.TRANSFORM_STEP.ALL) + { + if (from) + { + position = from.toGlobal(position, point, skipUpdate); + } + + if (!skipUpdate) + { + this._recursivePostUpdateTransform(); + } + + if (step === exports.TRANSFORM_STEP.ALL) + { + if (!skipUpdate) + { + this.displayObjectUpdateTransform(); + } + if (this.proj.affine) + { + return this.transform.worldTransform.applyInverse(position, point) ; + } + + return this.proj.world.applyInverse(position, point) ; + } + + if (this.parent) + { + point = this.parent.worldTransform.applyInverse(position, point) ; + } + else + { + point.x = position.x; + point.y = position.y; + // TODO: pixi 6.1.0 global mixin + (point ).z = (position ).z; + } + if (step === exports.TRANSFORM_STEP.NONE) + { + return point; + } + + point = this.transform.localTransform.applyInverse(point, point) ; + if (step === exports.TRANSFORM_STEP.PROJ && this.proj.cameraMode) + { + point = this.proj.cameraMatrix.applyInverse(point, point) ; + } + + return point; + } + + get worldTransform() + { + return this.proj.affine ? this.transform.worldTransform : this.proj.world ; + } + + get position3d() + { + return this.proj.position; + } + set position3d(value) + { + this.proj.position.copyFrom(value); + } + get scale3d() + { + return this.proj.scale; + } + set scale3d(value) + { + this.proj.scale.copyFrom(value); + } + get euler() + { + return this.proj.euler; + } + set euler(value) + { + this.proj.euler.copyFrom(value); + } + get pivot3d() + { + return this.proj.pivot; + } + set pivot3d(value) + { + this.proj.pivot.copyFrom(value); + } + } + + const container3dToLocal = Container3d.prototype.toLocal; + const container3dGetDepth = Container3d.prototype.getDepth; + const container3dIsFrontFace = Container3d.prototype.isFrontFace; + + class Camera3d extends Container3d + { + constructor() + { + super();Camera3d.prototype.__init.call(this);Camera3d.prototype.__init2.call(this);Camera3d.prototype.__init3.call(this);Camera3d.prototype.__init4.call(this);; + this.proj.cameraMode = true; + this.setPlanes(400, 10, 10000, false); + } + + __init() {this._far = 0;} + __init2() {this._near = 0;} + __init3() {this._focus = 0;} + __init4() {this._orthographic = false;} + + get far() + { + return this._far; + } + + get near() + { + return this._near; + } + + get focus() + { + return this._focus; + } + + get ortographic() + { + return this._orthographic; + } + + setPlanes(focus, near = 10, far = 10000, orthographic = false) + { + this._focus = focus; + this._near = near; + this._far = far; + this._orthographic = orthographic; + + const proj = this.proj; + const mat4 = proj.cameraMatrix.mat4; + + proj._projID++; + + mat4[10] = 1.0 / (far - near); + mat4[14] = (focus - near) / (far - near); + if (this._orthographic) + { + mat4[11] = 0; + } + else + { + mat4[11] = 1.0 / focus; + } + } + } + + class Mesh3d2d extends mesh.Mesh + { + constructor(geometry, shader, state, drawMode) + { + super(geometry, shader, state, drawMode);Mesh3d2d.prototype.__init.call(this);; + this.proj = new Projection3d(this.transform); + } + + __init() {this.vertexData2d = null;} + + + calculateVertices() + { + if (this.proj._affine) + { + this.vertexData2d = null; + super.calculateVertices(); + + return; + } + + const geometry = this.geometry ; + const vertices = geometry.buffers[0].data; + const thisAny = this ; + + if (geometry.vertexDirtyId === thisAny.vertexDirty && thisAny._transformID === thisAny.transform._worldID) + { + return; + } + + thisAny._transformID = thisAny.transform._worldID; + + if (thisAny.vertexData.length !== vertices.length) + { + thisAny.vertexData = new Float32Array(vertices.length); + } + if (!this.vertexData2d || this.vertexData2d.length !== vertices.length * 3 / 2) + { + this.vertexData2d = new Float32Array(vertices.length * 3); + } + + const wt = this.proj.world.mat4; + + const vertexData2d = this.vertexData2d; + const vertexData = thisAny.vertexData; + + for (let i = 0; i < vertexData.length / 2; i++) + { + const x = vertices[(i * 2)]; + const y = vertices[(i * 2) + 1]; + + const xx = (wt[0] * x) + (wt[4] * y) + wt[12]; + const yy = (wt[1] * x) + (wt[5] * y) + wt[13]; + const ww = (wt[3] * x) + (wt[7] * y) + wt[15]; + + vertexData2d[i * 3] = xx; + vertexData2d[(i * 3) + 1] = yy; + vertexData2d[(i * 3) + 2] = ww; + + vertexData[(i * 2)] = xx / ww; + vertexData[(i * 2) + 1] = yy / ww; + } + + thisAny.vertexDirty = geometry.vertexDirtyId; + } + + get worldTransform() + { + return this.proj.affine ? this.transform.worldTransform : this.proj.world ; + } + + toLocal(position, from, + point, skipUpdate, + step = exports.TRANSFORM_STEP.ALL) + { + return container3dToLocal.call(this, position, from, point, skipUpdate, step); + } + + isFrontFace(forceUpdate) + { + return container3dIsFrontFace.call(this, forceUpdate); + } + + getDepth(forceUpdate) + { + return container3dGetDepth.call(this, forceUpdate); + } + + get position3d() + { + return this.proj.position; + } + set position3d(value) + { + this.proj.position.copyFrom(value); + } + get scale3d() + { + return this.proj.scale; + } + set scale3d(value) + { + this.proj.scale.copyFrom(value); + } + get euler() + { + return this.proj.euler; + } + set euler(value) + { + this.proj.euler.copyFrom(value); + } + get pivot3d() + { + return this.proj.pivot; + } + set pivot3d(value) + { + this.proj.pivot.copyFrom(value); + } + } + + (Mesh3d2d.prototype )._renderDefault = Mesh2d.prototype._renderDefault; + + class SimpleMesh3d2d extends Mesh3d2d + { + constructor(texture, vertices, uvs, + indices, drawMode) + { + super(new mesh.MeshGeometry(vertices, uvs, indices), + new mesh.MeshMaterial(texture, { + program: core.Program.from(Mesh2d.defaultVertexShader, Mesh2d.defaultFragmentShader), + pluginName: 'batch2d' + }), + null, + drawMode);SimpleMesh3d2d.prototype.__init2.call(this);; + + (this.geometry.getBuffer('aVertexPosition') ).static = false; + } + + __init2() {this.autoUpdate = true;} + + get vertices() + { + return this.geometry.getBuffer('aVertexPosition').data ; + } + set vertices(value) + { + this.geometry.getBuffer('aVertexPosition').data = value; + } + + _render(renderer) + { + if (this.autoUpdate) + { + this.geometry.getBuffer('aVertexPosition').update(); + } + + (super._render )(renderer); + } + } + + /** + * Same as Sprite2d, but + * 1. uses Matrix3d in proj + * 2. does not render if at least one vertex is behind camera + */ + class Sprite3d extends sprite.Sprite + { + constructor(texture) + { + super(texture);Sprite3d.prototype.__init.call(this);Sprite3d.prototype.__init2.call(this);Sprite3d.prototype.__init3.call(this);; + this.proj = new Projection3d(this.transform); + this.pluginName = 'batch2d'; + } + + __init() {this.vertexData2d = null;} + + __init2() {this.culledByFrustrum = false;} + __init3() {this.trimmedCulledByFrustrum = false;} + + calculateVertices() + { + const texture = this._texture; + + if (this.proj._affine) + { + this.vertexData2d = null; + super.calculateVertices(); + + return; + } + if (!this.vertexData2d) + { + this.vertexData2d = new Float32Array(12); + } + + const wid = (this.transform )._worldID; + const tuid = (texture )._updateID; + const thisAny = this ; + + if (thisAny._transformID === wid && this._textureID === tuid) + { + return; + } + // update texture UV here, because base texture can be changed without calling `_onTextureUpdate` + if (this._textureID !== tuid) + { + (this ).uvs = (texture )._uvs.uvsFloat32; + } + + thisAny._transformID = wid; + this._textureID = tuid; + + const wt = this.proj.world.mat4; + const vertexData2d = this.vertexData2d; + const vertexData = this.vertexData; + const trim = texture.trim; + const orig = texture.orig; + const anchor = this._anchor; + + let w0; + let w1; + let h0; + let h1; + + if (trim) + { + w1 = trim.x - (anchor._x * orig.width); + w0 = w1 + trim.width; + + h1 = trim.y - (anchor._y * orig.height); + h0 = h1 + trim.height; + } + else + { + w1 = -anchor._x * orig.width; + w0 = w1 + orig.width; + + h1 = -anchor._y * orig.height; + h0 = h1 + orig.height; + } + + let culled = false; + + let z; + + vertexData2d[0] = (wt[0] * w1) + (wt[4] * h1) + wt[12]; + vertexData2d[1] = (wt[1] * w1) + (wt[5] * h1) + wt[13]; + z = (wt[2] * w1) + (wt[6] * h1) + wt[14]; + vertexData2d[2] = (wt[3] * w1) + (wt[7] * h1) + wt[15]; + culled = culled || z < 0; + + vertexData2d[3] = (wt[0] * w0) + (wt[4] * h1) + wt[12]; + vertexData2d[4] = (wt[1] * w0) + (wt[5] * h1) + wt[13]; + z = (wt[2] * w0) + (wt[6] * h1) + wt[14]; + vertexData2d[5] = (wt[3] * w0) + (wt[7] * h1) + wt[15]; + culled = culled || z < 0; + + vertexData2d[6] = (wt[0] * w0) + (wt[4] * h0) + wt[12]; + vertexData2d[7] = (wt[1] * w0) + (wt[5] * h0) + wt[13]; + z = (wt[2] * w0) + (wt[6] * h0) + wt[14]; + vertexData2d[8] = (wt[3] * w0) + (wt[7] * h0) + wt[15]; + culled = culled || z < 0; + + vertexData2d[9] = (wt[0] * w1) + (wt[4] * h0) + wt[12]; + vertexData2d[10] = (wt[1] * w1) + (wt[5] * h0) + wt[13]; + z = (wt[2] * w1) + (wt[6] * h0) + wt[14]; + vertexData2d[11] = (wt[3] * w1) + (wt[7] * h0) + wt[15]; + culled = culled || z < 0; + + this.culledByFrustrum = culled; + + vertexData[0] = vertexData2d[0] / vertexData2d[2]; + vertexData[1] = vertexData2d[1] / vertexData2d[2]; + + vertexData[2] = vertexData2d[3] / vertexData2d[5]; + vertexData[3] = vertexData2d[4] / vertexData2d[5]; + + vertexData[4] = vertexData2d[6] / vertexData2d[8]; + vertexData[5] = vertexData2d[7] / vertexData2d[8]; + + vertexData[6] = vertexData2d[9] / vertexData2d[11]; + vertexData[7] = vertexData2d[10] / vertexData2d[11]; + } + + calculateTrimmedVertices() + { + if (this.proj._affine) + { + super.calculateTrimmedVertices(); + + return; + } + + const wid = (this.transform )._worldID; + const tuid = (this._texture )._updateID; + const thisAny = this ; + + if (!thisAny.vertexTrimmedData) + { + thisAny.vertexTrimmedData = new Float32Array(8); + } + else if (thisAny._transformTrimmedID === wid && this._textureTrimmedID === tuid) + { + return; + } + + thisAny._transformTrimmedID = wid; + this._textureTrimmedID = tuid; + + // lets do some special trim code! + const texture = this._texture; + const vertexData = thisAny.vertexTrimmedData; + const orig = texture.orig; + const anchor = this._anchor; + + // lets calculate the new untrimmed bounds.. + const wt = this.proj.world.mat4; + + const w1 = -anchor._x * orig.width; + const w0 = w1 + orig.width; + + const h1 = -anchor._y * orig.height; + const h0 = h1 + orig.height; + + let culled = false; + + let z; + + let w = 1.0 / ((wt[3] * w1) + (wt[7] * h1) + wt[15]); + + vertexData[0] = w * ((wt[0] * w1) + (wt[4] * h1) + wt[12]); + vertexData[1] = w * ((wt[1] * w1) + (wt[5] * h1) + wt[13]); + z = (wt[2] * w1) + (wt[6] * h1) + wt[14]; + culled = culled || z < 0; + + w = 1.0 / ((wt[3] * w0) + (wt[7] * h1) + wt[15]); + vertexData[2] = w * ((wt[0] * w0) + (wt[4] * h1) + wt[12]); + vertexData[3] = w * ((wt[1] * w0) + (wt[5] * h1) + wt[13]); + z = (wt[2] * w0) + (wt[6] * h1) + wt[14]; + culled = culled || z < 0; + + w = 1.0 / ((wt[3] * w0) + (wt[7] * h0) + wt[15]); + vertexData[4] = w * ((wt[0] * w0) + (wt[4] * h0) + wt[12]); + vertexData[5] = w * ((wt[1] * w0) + (wt[5] * h0) + wt[13]); + z = (wt[2] * w0) + (wt[6] * h0) + wt[14]; + culled = culled || z < 0; + + w = 1.0 / ((wt[3] * w1) + (wt[7] * h0) + wt[15]); + vertexData[6] = w * ((wt[0] * w1) + (wt[4] * h0) + wt[12]); + vertexData[7] = w * ((wt[1] * w1) + (wt[5] * h0) + wt[13]); + z = (wt[2] * w1) + (wt[6] * h0) + wt[14]; + culled = culled || z < 0; + + this.culledByFrustrum = culled; + } + + _calculateBounds() + { + this.calculateVertices(); + if (this.culledByFrustrum) + { + return; + } + + const trim = this._texture.trim; + const orig = this._texture.orig; + + if (!trim || (trim.width === orig.width && trim.height === orig.height)) + { + // no trim! lets use the usual calculations.. + this._bounds.addQuad(this.vertexData); + + return; + } + + this.calculateTrimmedVertices(); + if (!this.trimmedCulledByFrustrum) + { + this._bounds.addQuad((this ).vertexTrimmedData ); + } + } + + _render(renderer) + { + this.calculateVertices(); + + if (this.culledByFrustrum) + { + return; + } + + renderer.batch.setObjectRenderer((renderer ).plugins[this.pluginName]); + (renderer ).plugins[this.pluginName].render(this); + } + + containsPoint(point) + { + if (this.culledByFrustrum) + { + return false; + } + + return super.containsPoint(point ); + } + + get worldTransform() + { + return this.proj.affine ? this.transform.worldTransform : this.proj.world ; + } + + toLocal(position, from, + point, skipUpdate, + step = exports.TRANSFORM_STEP.ALL) + { + return container3dToLocal.call(this, position, from, point, skipUpdate, step); + } + + isFrontFace(forceUpdate) + { + return container3dIsFrontFace.call(this, forceUpdate); + } + + getDepth(forceUpdate) + { + return container3dGetDepth.call(this, forceUpdate); + } + + get position3d() + { + return this.proj.position; + } + set position3d(value) + { + this.proj.position.copyFrom(value); + } + get scale3d() + { + return this.proj.scale; + } + set scale3d(value) + { + this.proj.scale.copyFrom(value); + } + get euler() + { + return this.proj.euler; + } + set euler(value) + { + this.proj.euler.copyFrom(value); + } + get pivot3d() + { + return this.proj.pivot; + } + set pivot3d(value) + { + this.proj.pivot.copyFrom(value); + } + } + + const containerProps = { + worldTransform: { + get: container3dWorldTransform, + enumerable: true, + configurable: true + }, + position3d: { + get() { return this.proj.position; }, + set(value) { this.proj.position.copy(value); } + }, + scale3d: { + get() { return this.proj.scale; }, + set(value) { this.proj.scale.copy(value); } + }, + pivot3d: { + get() { return this.proj.pivot; }, + set(value) { this.proj.pivot.copy(value); } + }, + euler: { + get() { return this.proj.euler; }, + set(value) { this.proj.euler.copy(value); } + } + }; + + function convertTo3d() + { + if (this.proj) return; + this.proj = new Projection3d(this.transform); + this.toLocal = Container3d.prototype.toLocal; + this.isFrontFace = Container3d.prototype.isFrontFace; + this.getDepth = Container3d.prototype.getDepth; + Object.defineProperties(this, containerProps); + } + + display.Container.prototype.convertTo3d = convertTo3d; + + sprite.Sprite.prototype.convertTo3d = function spriteConvertTo3d() + { + if (this.proj) return; + this.calculateVertices = Sprite3d.prototype.calculateVertices; + this.calculateTrimmedVertices = Sprite3d.prototype.calculateTrimmedVertices; + this._calculateBounds = Sprite3d.prototype._calculateBounds; + this.containsPoint = Sprite3d.prototype.containsPoint; + this.pluginName = 'batch2d'; + convertTo3d.call(this); + }; + + display.Container.prototype.convertSubtreeTo3d = function convertSubtreeTo3d() + { + this.convertTo3d(); + for (let i = 0; i < this.children.length; i++) + { + this.children[i].convertSubtreeTo3d(); + } + }; + + meshExtras.SimpleMesh.prototype.convertTo3d + = meshExtras.SimpleRope.prototype.convertTo3d + = function meshConvert3d() + { + if (this.proj) return; + this.calculateVertices = Mesh3d2d.prototype.calculateVertices; + this._renderDefault = (Mesh3d2d.prototype )._renderDefault; + if (this.material.pluginName !== 'batch2d') + { + this.material = new mesh.MeshMaterial(this.material.texture, { + program: core.Program.from(Mesh2d.defaultVertexShader, Mesh2d.defaultFragmentShader), + pluginName: 'batch2d' + }); + } + convertTo3d.call(this); + }; + + class Text3d extends text.Text + { + constructor(text, style, canvas) + { + super(text, style, canvas);Text3d.prototype.__init.call(this);; + this.proj = new Projection3d(this.transform); + this.pluginName = 'batch2d'; + } + + + __init() {this.vertexData2d = null;} + + get worldTransform() + { + return this.proj.affine ? this.transform.worldTransform : this.proj.world ; + } + + toLocal(position, from, + point, skipUpdate, + step = exports.TRANSFORM_STEP.ALL) + { + return container3dToLocal.call(this, position, from, point, skipUpdate, step); + } + + isFrontFace(forceUpdate) + { + return container3dIsFrontFace.call(this, forceUpdate); + } + + getDepth(forceUpdate) + { + return container3dGetDepth.call(this, forceUpdate); + } + + get position3d() + { + return this.proj.position; + } + set position3d(value) + { + this.proj.position.copyFrom(value); + } + get scale3d() + { + return this.proj.scale; + } + set scale3d(value) + { + this.proj.scale.copyFrom(value); + } + get euler() + { + return this.proj.euler; + } + set euler(value) + { + this.proj.euler.copyFrom(value); + } + get pivot3d() + { + return this.proj.pivot; + } + set pivot3d(value) + { + this.proj.pivot.copyFrom(value); + } + } + + Text3d.prototype.calculateVertices = Sprite3d.prototype.calculateVertices; + (Text3d.prototype ).calculateTrimmedVertices = Sprite3d.prototype.calculateTrimmedVertices; + (Text3d.prototype )._calculateBounds = Sprite3d.prototype._calculateBounds; + Text3d.prototype.containsPoint = Sprite3d.prototype.containsPoint; + (Text3d.prototype )._render = Sprite3d.prototype._render; + + var _class; + const shaderVert = `precision highp float; +attribute vec2 aVertexPosition; +attribute vec3 aTrans1; +attribute vec3 aTrans2; +attribute vec2 aSamplerSize; +attribute vec4 aFrame; +attribute vec4 aColor; +attribute float aTextureId; + +uniform mat3 projectionMatrix; +uniform mat3 translationMatrix; + +varying vec2 vertexPosition; +varying vec3 vTrans1; +varying vec3 vTrans2; +varying vec2 vSamplerSize; +varying vec4 vFrame; +varying vec4 vColor; +varying float vTextureId; + +void main(void){ +gl_Position.xyw = projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0); +gl_Position.z = 0.0; + +vertexPosition = aVertexPosition; +vTrans1 = aTrans1; +vTrans2 = aTrans2; +vTextureId = aTextureId; +vColor = aColor; +vSamplerSize = aSamplerSize; +vFrame = aFrame; +} +`; + + const shaderFrag = `precision highp float; +varying vec2 vertexPosition; +varying vec3 vTrans1; +varying vec3 vTrans2; +varying vec2 vSamplerSize; +varying vec4 vFrame; +varying vec4 vColor; +varying float vTextureId; + +uniform sampler2D uSamplers[%count%]; +uniform vec4 distortion; + +void main(void){ +vec2 surface; +vec2 surface2; + +float vx = vertexPosition.x; +float vy = vertexPosition.y; +float dx = distortion.x; +float dy = distortion.y; +float revx = distortion.z; +float revy = distortion.w; + +if (distortion.x == 0.0) { +surface.x = vx; +surface.y = vy / (1.0 + dy * vx); +surface2 = surface; +} else +if (distortion.y == 0.0) { +surface.y = vy; +surface.x = vx / (1.0 + dx * vy); +surface2 = surface; +} else { +float c = vy * dx - vx * dy; +float b = (c + 1.0) * 0.5; +float b2 = (-c + 1.0) * 0.5; +float d = b * b + vx * dy; +if (d < -0.00001) { + discard; +} +d = sqrt(max(d, 0.0)); +surface.x = (- b + d) * revy; +surface2.x = (- b - d) * revy; +surface.y = (- b2 + d) * revx; +surface2.y = (- b2 - d) * revx; +} + +vec2 uv; +uv.x = vTrans1.x * surface.x + vTrans1.y * surface.y + vTrans1.z; +uv.y = vTrans2.x * surface.x + vTrans2.y * surface.y + vTrans2.z; + +vec2 pixels = uv * vSamplerSize; + +if (pixels.x < vFrame.x || pixels.x > vFrame.z || +pixels.y < vFrame.y || pixels.y > vFrame.w) { +uv.x = vTrans1.x * surface2.x + vTrans1.y * surface2.y + vTrans1.z; +uv.y = vTrans2.x * surface2.x + vTrans2.y * surface2.y + vTrans2.z; +pixels = uv * vSamplerSize; + +if (pixels.x < vFrame.x || pixels.x > vFrame.z || + pixels.y < vFrame.y || pixels.y > vFrame.w) { + discard; +} +} + +vec4 edge; +edge.xy = clamp(pixels - vFrame.xy + 0.5, vec2(0.0, 0.0), vec2(1.0, 1.0)); +edge.zw = clamp(vFrame.zw - pixels + 0.5, vec2(0.0, 0.0), vec2(1.0, 1.0)); + +float alpha = 1.0; //edge.x * edge.y * edge.z * edge.w; +vec4 rColor = vColor * alpha; + +float textureId = floor(vTextureId+0.5); +vec2 vTextureCoord = uv; +vec4 color; +%forloop% +gl_FragColor = color * rColor; +}`; + + class BatchBilineardGeometry extends core.Geometry + { + + + + constructor(_static = false) + { + super(); + + this._buffer = new core.Buffer(null, _static, false); + + this._indexBuffer = new core.Buffer(null, _static, true); + + this.addAttribute('aVertexPosition', this._buffer, 2, false, constants.TYPES.FLOAT) + .addAttribute('aTrans1', this._buffer, 3, false, constants.TYPES.FLOAT) + .addAttribute('aTrans2', this._buffer, 3, false, constants.TYPES.FLOAT) + .addAttribute('aSamplerSize', this._buffer, 2, false, constants.TYPES.FLOAT) + .addAttribute('aFrame', this._buffer, 4, false, constants.TYPES.FLOAT) + .addAttribute('aColor', this._buffer, 4, true, constants.TYPES.UNSIGNED_BYTE) + .addAttribute('aTextureId', this._buffer, 1, true, constants.TYPES.FLOAT) + .addIndex(this._indexBuffer); + } + } + + class BatchBilinearPluginFactory + { + // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types + static create(options) + { + const { vertex, fragment, vertexSize, geometryClass } = (Object ).assign({ + vertex: shaderVert, + fragment: shaderFrag, + geometryClass: BatchBilineardGeometry, + vertexSize: 16, + }, options); + + return (_class = class BatchPlugin extends UniformBatchRenderer + { + constructor(renderer) + { + super(renderer);_class.prototype.__init.call(this);_class.prototype.__init2.call(this);_class.prototype.__init3.call(this);; + + this.shaderGenerator = new core.BatchShaderGenerator(vertex, fragment); + this.geometryClass = geometryClass; + this.vertexSize = vertexSize; + } + + __init() {this.defUniforms = { + translationMatrix: new math.Matrix(), + distortion: new Float32Array([0, 0, Infinity, Infinity]) + };} + __init2() {this.size = 1000;} + __init3() {this.forceMaxTextures = 1;} + + getUniforms(sprite) + { + const { proj } = sprite ; + + if (proj.surface !== null) + { + return proj.uniforms; + } + if (proj._activeProjection !== null) + { + return proj._activeProjection.uniforms; + } + + return this.defUniforms; + } + + // eslint-disable-next-line max-len + packInterleavedGeometry(element, attributeBuffer, indexBuffer, aIndex, iIndex) + { + const { + uint32View, + float32View, + } = attributeBuffer; + const p = aIndex / this.vertexSize; + const indices = element.indices; + const vertexData = element.vertexData; + const tex = element._texture; + const frame = tex._frame; + const aTrans = element.aTrans; + const { _batchLocation, realWidth, realHeight, resolution } = element._texture.baseTexture; + + const alpha = Math.min(element.worldAlpha, 1.0); + + const argb = alpha < 1.0 && element._texture.baseTexture.alphaMode ? utils.premultiplyTint(element._tintRGB, alpha) + : element._tintRGB + (alpha * 255 << 24); + + for (let i = 0; i < vertexData.length; i += 2) + { + float32View[aIndex] = vertexData[i]; + float32View[aIndex + 1] = vertexData[i + 1]; + + float32View[aIndex + 2] = aTrans.a; + float32View[aIndex + 3] = aTrans.c; + float32View[aIndex + 4] = aTrans.tx; + float32View[aIndex + 5] = aTrans.b; + float32View[aIndex + 6] = aTrans.d; + float32View[aIndex + 7] = aTrans.ty; + + float32View[aIndex + 8] = realWidth; + float32View[aIndex + 9] = realHeight; + float32View[aIndex + 10] = frame.x * resolution; + float32View[aIndex + 11] = frame.y * resolution; + float32View[aIndex + 12] = (frame.x + frame.width) * resolution; + float32View[aIndex + 13] = (frame.y + frame.height) * resolution; + + uint32View[aIndex + 14] = argb; + float32View[aIndex + 15] = _batchLocation; + aIndex += 16; + } + + for (let i = 0; i < indices.length; i++) + { + indexBuffer[iIndex++] = p + indices[i]; + } + } + }, _class); + } + } + + const p = [new math.Point(), new math.Point(), new math.Point(), new math.Point()]; + const a = [0, 0, 0, 0]; + + class Surface + {constructor() { Surface.prototype.__init.call(this);Surface.prototype.__init2.call(this);Surface.prototype.__init3.call(this);Surface.prototype.__init4.call(this); } + __init() {this.surfaceID = 'default';} + + __init2() {this._updateID = 0;} + + __init3() {this.vertexSrc = '';} + __init4() {this.fragmentSrc = '';} + + // eslint-disable-next-line @typescript-eslint/no-unused-vars + fillUniforms(uniforms) + // eslint-disable-next-line @typescript-eslint/no-empty-function + { + + } + + clear() + // eslint-disable-next-line @typescript-eslint/no-empty-function + { + + } + + /** + * made for bilinear, other things will need adjustments, like test if (0) is inside + * @param {ArrayLike} v + * @param out + * @param {Matrix} after + */ + // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types + boundsQuad(v, out, after) + { + let minX = out[0]; let + minY = out[1]; + let maxX = out[0]; let + maxY = out[1]; + + for (let i = 2; i < 8; i += 2) + { + if (minX > out[i]) minX = out[i]; + if (maxX < out[i]) maxX = out[i]; + if (minY > out[i + 1]) minY = out[i + 1]; + if (maxY < out[i + 1]) maxY = out[i + 1]; + } + + p[0].set(minX, minY); + this.apply(p[0], p[0]); + p[1].set(maxX, minY); + this.apply(p[1], p[1]); + p[2].set(maxX, maxY); + this.apply(p[2], p[2]); + p[3].set(minX, maxY); + this.apply(p[3], p[3]); + + if (after) + { + after.apply(p[0], p[0]); + after.apply(p[1], p[1]); + after.apply(p[2], p[2]); + after.apply(p[3], p[3]); + out[0] = p[0].x; + out[1] = p[0].y; + out[2] = p[1].x; + out[3] = p[1].y; + out[4] = p[2].x; + out[5] = p[2].y; + out[6] = p[3].x; + out[7] = p[3].y; + } + else + { + for (let i = 1; i <= 3; i++) + { + if (p[i].y < p[0].y || (p[i].y === p[0].y && p[i].x < p[0].x)) + { + const t = p[0]; + + p[0] = p[i]; + p[i] = t; + } + } + + for (let i = 1; i <= 3; i++) + { + a[i] = Math.atan2(p[i].y - p[0].y, p[i].x - p[0].x); + } + for (let i = 1; i <= 3; i++) + { + for (let j = i + 1; j <= 3; j++) + { + if (a[i] > a[j]) + { + const t = p[i]; + + p[i] = p[j]; + p[j] = t; + const t2 = a[i]; + + a[i] = a[j]; + a[j] = t2; + } + } + } + + out[0] = p[0].x; + out[1] = p[0].y; + out[2] = p[1].x; + out[3] = p[1].y; + out[4] = p[2].x; + out[5] = p[2].y; + out[6] = p[3].x; + out[7] = p[3].y; + + if (((p[3].x - p[2].x) * (p[1].y - p[2].y)) - ((p[1].x - p[2].x) * (p[3].y - p[2].y)) < 0) + { + // triangle!!! + out[4] = p[3].x; + out[5] = p[3].y; + + return; + } + } + } + + + + + + } + + /* eslint-disable no-mixed-operators */ + + + const tempMat = new math.Matrix(); + const tempRect = new math.Rectangle(); + const tempPoint = new math.Point(); + + class BilinearSurface extends Surface + {constructor(...args) { super(...args); BilinearSurface.prototype.__init.call(this); } + __init() {this.distortion = new math.Point();} + + clear() + { + this.distortion.set(0, 0); + } + + apply(pos, newPos) + { + newPos = newPos || new math.Point(); + const d = this.distortion; + const m = pos.x * pos.y; + + newPos.x = pos.x + d.x * m; + newPos.y = pos.y + d.y * m; + + return newPos; + } + + applyInverse(pos, newPos) + { + newPos = newPos || new math.Point(); + const vx = pos.x; const + vy = pos.y; + const dx = this.distortion.x; const + dy = this.distortion.y; + + if (dx === 0.0) + { + newPos.x = vx; + newPos.y = vy / (1.0 + dy * vx); + } + else + if (dy === 0.0) + { + newPos.y = vy; + newPos.x = vx / (1.0 + dx * vy); + } + else + { + const b = (vy * dx - vx * dy + 1.0) * 0.5 / dy; + const d = b * b + vx / dy; + + if (d <= 0.00001) + { + newPos.set(NaN, NaN); + + return newPos; + } + if (dy > 0.0) + { + newPos.x = -b + Math.sqrt(d); + } + else + { + newPos.x = -b - Math.sqrt(d); + } + newPos.y = (vx / newPos.x - 1.0) / dx; + } + + return newPos; + } + + mapSprite(sprite, quad, outTransform) + { + const tex = sprite.texture; + + tempRect.x = -sprite.anchor.x * tex.orig.width; + tempRect.y = -sprite.anchor.y * tex.orig.height; + tempRect.width = tex.orig.width; + tempRect.height = tex.orig.height; + + return this.mapQuad(tempRect, quad, outTransform || sprite.transform ); + } + + mapQuad(rect, quad, outTransform) + { + const ax = -rect.x / rect.width; + const ay = -rect.y / rect.height; + + const ax2 = (1.0 - rect.x) / rect.width; + const ay2 = (1.0 - rect.y) / rect.height; + + const up1x = (quad[0].x * (1.0 - ax) + quad[1].x * ax); + const up1y = (quad[0].y * (1.0 - ax) + quad[1].y * ax); + const up2x = (quad[0].x * (1.0 - ax2) + quad[1].x * ax2); + const up2y = (quad[0].y * (1.0 - ax2) + quad[1].y * ax2); + + const down1x = (quad[3].x * (1.0 - ax) + quad[2].x * ax); + const down1y = (quad[3].y * (1.0 - ax) + quad[2].y * ax); + const down2x = (quad[3].x * (1.0 - ax2) + quad[2].x * ax2); + const down2y = (quad[3].y * (1.0 - ax2) + quad[2].y * ax2); + + const x00 = up1x * (1.0 - ay) + down1x * ay; + const y00 = up1y * (1.0 - ay) + down1y * ay; + + const x10 = up2x * (1.0 - ay) + down2x * ay; + const y10 = up2y * (1.0 - ay) + down2y * ay; + + const x01 = up1x * (1.0 - ay2) + down1x * ay2; + const y01 = up1y * (1.0 - ay2) + down1y * ay2; + + const x11 = up2x * (1.0 - ay2) + down2x * ay2; + const y11 = up2y * (1.0 - ay2) + down2y * ay2; + + const mat = tempMat; + + mat.tx = x00; + mat.ty = y00; + mat.a = x10 - x00; + mat.b = y10 - y00; + mat.c = x01 - x00; + mat.d = y01 - y00; + tempPoint.set(x11, y11); + mat.applyInverse(tempPoint, tempPoint); + this.distortion.set(tempPoint.x - 1, tempPoint.y - 1); + + outTransform.setFromMatrix(mat); + + return this; + } + + fillUniforms(uniforms) + { + uniforms.distortion = uniforms.distortion || new Float32Array([0, 0, 0, 0]); + const ax = Math.abs(this.distortion.x); + const ay = Math.abs(this.distortion.y); + + uniforms.distortion[0] = ax * 10000 <= ay ? 0 : this.distortion.x; + uniforms.distortion[1] = ay * 10000 <= ax ? 0 : this.distortion.y; + uniforms.distortion[2] = 1.0 / uniforms.distortion[0]; + uniforms.distortion[3] = 1.0 / uniforms.distortion[1]; + } + } + + const fun = math.Transform.prototype.updateTransform; + + + + + + + + + function transformHack( parentTransform) + { + // TODO: pixi 6.1.0 global mixin + const proj = (this ).proj ; + + const pp = (parentTransform ).proj ; + const ta = this ; + + if (!pp) + { + fun.call(this, parentTransform); + proj._activeProjection = null; + + return; + } + + if (pp._surface) + { + proj._activeProjection = pp; + this.updateLocalTransform(); + this.localTransform.copyTo(this.worldTransform); + if (ta._parentID < 0) + { + ++ta._worldID; + } + + return; + } + + fun.call(this, parentTransform); + proj._activeProjection = pp._activeProjection; + } + + class ProjectionSurface extends AbstractProjection + {constructor(...args) { super(...args); ProjectionSurface.prototype.__init.call(this);ProjectionSurface.prototype.__init2.call(this);ProjectionSurface.prototype.__init3.call(this);ProjectionSurface.prototype.__init4.call(this);ProjectionSurface.prototype.__init5.call(this); } + __init() {this._surface = null;} + __init2() {this._activeProjection = null;} + + // eslint-disable-next-line accessor-pairs + set enabled(value) + { + if (value === this._enabled) + { + return; + } + this._enabled = value; + if (value) + { + this.legacy.updateTransform = transformHack; + (this.legacy )._parentID = -1; + } + else + { + this.legacy.updateTransform = math.Transform.prototype.updateTransform; + (this.legacy )._parentID = -1; + } + } + + get surface() + { + return this._surface; + } + + set surface(value) + { + if (this._surface === value) + { + return; + } + this._surface = value || null; + (this.legacy )._parentID = -1; + } + + applyPartial(pos, newPos) + { + if (this._activeProjection !== null) + { + newPos = this.legacy.worldTransform.apply(pos, newPos); + + return this._activeProjection.surface.apply(newPos, newPos); + } + if (this._surface !== null) + { + return this.surface.apply(pos, newPos); + } + + return this.legacy.worldTransform.apply(pos, newPos); + } + + apply(pos, newPos) + { + if (this._activeProjection !== null) + { + newPos = this.legacy.worldTransform.apply(pos, newPos); + this._activeProjection.surface.apply(newPos, newPos); + + return this._activeProjection.legacy.worldTransform.apply(newPos, newPos); + } + if (this._surface !== null) + { + newPos = this.surface.apply(pos, newPos); + + return this.legacy.worldTransform.apply(newPos, newPos); + } + + return this.legacy.worldTransform.apply(pos, newPos); + } + + applyInverse(pos, newPos) + { + if (this._activeProjection !== null) + { + newPos = this._activeProjection.legacy.worldTransform.applyInverse(pos, newPos); + this._activeProjection._surface.applyInverse(newPos, newPos); + + return this.legacy.worldTransform.applyInverse(newPos, newPos); + } + if (this._surface !== null) + { + newPos = this.legacy.worldTransform.applyInverse(pos, newPos); + + return this._surface.applyInverse(newPos, newPos); + } + + return this.legacy.worldTransform.applyInverse(pos, newPos); + } + + mapBilinearSprite(sprite, quad) + { + if (!(this._surface instanceof BilinearSurface)) + { + this.surface = new BilinearSurface(); + } + (this.surface ).mapSprite(sprite, quad, this.legacy); + } + + __init3() {this._currentSurfaceID = -1;} + __init4() {this._currentLegacyID = -1;} + __init5() {this._lastUniforms = null;} + + clear() + { + if (this.surface) + { + this.surface.clear(); + } + } + + get uniforms() + { + if (this._currentLegacyID === (this.legacy )._worldID + && this._currentSurfaceID === this.surface._updateID) + { + return this._lastUniforms; + } + + this._lastUniforms = this._lastUniforms || {}; + this._lastUniforms.translationMatrix = this.legacy.worldTransform; + this._surface.fillUniforms(this._lastUniforms); + + return this._lastUniforms; + } + } + + class Sprite2s extends sprite.Sprite + { + constructor(texture) + { + super(texture);Sprite2s.prototype.__init.call(this);; + this.proj = new ProjectionSurface(this.transform); + this.pluginName = 'batch_bilinear'; + } + + + __init() {this.aTrans = new math.Matrix();} + + _calculateBounds() + { + this.calculateTrimmedVertices(); + this._bounds.addQuad((this ).vertexTrimmedData ); + } + + calculateVertices() + { + const wid = (this.transform )._worldID; + const tuid = (this._texture )._updateID; + const thisAny = this ; + + if (thisAny._transformID === wid && this._textureID === tuid) + { + return; + } + + thisAny._transformID = wid; + this._textureID = tuid; + + const texture = this._texture; + const vertexData = this.vertexData; + const trim = texture.trim; + const orig = texture.orig; + const anchor = this._anchor; + + let w0; + let w1; + let h0; + let h1; + + if (trim) + { + w1 = trim.x - (anchor._x * orig.width); + w0 = w1 + trim.width; + + h1 = trim.y - (anchor._y * orig.height); + h0 = h1 + trim.height; + } + else + { + w1 = -anchor._x * orig.width; + w0 = w1 + orig.width; + + h1 = -anchor._y * orig.height; + h0 = h1 + orig.height; + } + + if (this.proj._surface) + { + vertexData[0] = w1; + vertexData[1] = h1; + vertexData[2] = w0; + vertexData[3] = h1; + vertexData[4] = w0; + vertexData[5] = h0; + vertexData[6] = w1; + vertexData[7] = h0; + this.proj._surface.boundsQuad(vertexData, vertexData); + } + else + { + const wt = this.transform.worldTransform; + const a = wt.a; + const b = wt.b; + const c = wt.c; + const d = wt.d; + const tx = wt.tx; + const ty = wt.ty; + + vertexData[0] = (a * w1) + (c * h1) + tx; + vertexData[1] = (d * h1) + (b * w1) + ty; + vertexData[2] = (a * w0) + (c * h1) + tx; + vertexData[3] = (d * h1) + (b * w0) + ty; + vertexData[4] = (a * w0) + (c * h0) + tx; + vertexData[5] = (d * h0) + (b * w0) + ty; + vertexData[6] = (a * w1) + (c * h0) + tx; + vertexData[7] = (d * h0) + (b * w1) + ty; + if (this.proj._activeProjection) + { + this.proj._activeProjection.surface.boundsQuad(vertexData, vertexData); + } + } + + if (!texture.uvMatrix) + { + texture.uvMatrix = new core.TextureMatrix(texture); + } + texture.uvMatrix.update(); + + const aTrans = this.aTrans; + + aTrans.set(orig.width, 0, 0, orig.height, w1, h1); + if (this.proj._surface === null) + { + aTrans.prepend(this.transform.worldTransform); + } + aTrans.invert(); + aTrans.prepend((texture.uvMatrix ).mapCoord); + } + + calculateTrimmedVertices() + { + const wid = (this.transform )._worldID; + const tuid = (this._texture )._updateID; + const thisAny = this ; + + if (!thisAny.vertexTrimmedData) + { + thisAny.vertexTrimmedData = new Float32Array(8); + } + else if (thisAny._transformTrimmedID === wid && this._textureTrimmedID === tuid) + { + return; + } + + thisAny._transformTrimmedID = wid; + this._textureTrimmedID = tuid; + + // lets do some special trim code! + const texture = this._texture; + const vertexData = thisAny.vertexTrimmedData; + const orig = texture.orig; + const anchor = this._anchor; + + // lets calculate the new untrimmed bounds.. + + const w1 = -anchor._x * orig.width; + const w0 = w1 + orig.width; + + const h1 = -anchor._y * orig.height; + const h0 = h1 + orig.height; + + // TODO: take rotations into account! form temporary bounds + + if (this.proj._surface) + { + vertexData[0] = w1; + vertexData[1] = h1; + vertexData[2] = w0; + vertexData[3] = h1; + vertexData[4] = w0; + vertexData[5] = h0; + vertexData[6] = w1; + vertexData[7] = h0; + this.proj._surface.boundsQuad(vertexData, vertexData, this.transform.worldTransform); + } + else + { + const wt = this.transform.worldTransform; + const a = wt.a; + const b = wt.b; + const c = wt.c; + const d = wt.d; + const tx = wt.tx; + const ty = wt.ty; + + vertexData[0] = (a * w1) + (c * h1) + tx; + vertexData[1] = (d * h1) + (b * w1) + ty; + vertexData[2] = (a * w0) + (c * h1) + tx; + vertexData[3] = (d * h1) + (b * w0) + ty; + vertexData[4] = (a * w0) + (c * h0) + tx; + vertexData[5] = (d * h0) + (b * w0) + ty; + vertexData[6] = (a * w1) + (c * h0) + tx; + vertexData[7] = (d * h0) + (b * w1) + ty; + if (this.proj._activeProjection) + { + this.proj._activeProjection.surface.boundsQuad(vertexData, vertexData, + this.proj._activeProjection.legacy.worldTransform); + } + } + } + + get worldTransform() + { + return this.proj ; + } + } + + sprite.Sprite.prototype.convertTo2s = function spriteConvertTo2s() + { + if (this.proj) return; + // container + this.pluginName = 'sprite_bilinear'; + this.aTrans = new math.Matrix(); + this.calculateVertices = Sprite2s.prototype.calculateVertices; + this.calculateTrimmedVertices = Sprite2s.prototype.calculateTrimmedVertices; + this._calculateBounds = Sprite2s.prototype._calculateBounds; + display.Container.prototype.convertTo2s.call(this); + }; + + display.Container.prototype.convertTo2s = function convertTo2s() + { + if (this.proj) return; + this.proj = new ProjectionSurface(this.transform); + Object.defineProperty(this, 'worldTransform', { + get() + { + return this.proj; + }, + enumerable: true, + configurable: true + }); + }; + + display.Container.prototype.convertSubtreeTo2s = function convertSubtreeTo2s() + { + this.convertTo2s(); + for (let i = 0; i < this.children.length; i++) + { + this.children[i].convertSubtreeTo2s(); + } + }; + + class Text2s extends text.Text + { + constructor(text, style, canvas) + { + super(text, style, canvas);Text2s.prototype.__init.call(this);; + this.proj = new ProjectionSurface(this.transform); + this.pluginName = 'batch_bilinear'; + } + + + + __init() {this.aTrans = new math.Matrix();} + + get worldTransform() + { + return this.proj ; + } + } + + (Text2s.prototype ).calculateVertices = Sprite2s.prototype.calculateVertices; + (Text2s.prototype ).calculateTrimmedVertices = Sprite2s.prototype.calculateTrimmedVertices; + (Text2s.prototype )._calculateBounds = Sprite2s.prototype._calculateBounds; + + core.Renderer.registerPlugin('batch_bilinear', BatchBilinearPluginFactory.create({})); + + function applySpine2dMixin(spineClassPrototype) + { + spineClassPrototype.newMesh = function newMesh(texture, vertices, + uvs, indices, drawMode) + { + return new SimpleMesh2d(texture, vertices, uvs, indices, drawMode) ; + }; + spineClassPrototype.newContainer = function newMesh() + { + if (!this.proj) + { + this.convertTo2d(); + } + + return new Container2d() ; + }; + spineClassPrototype.newSprite = function newSprite(texture) + { + return new Sprite2d(texture); + }; + spineClassPrototype.newGraphics = function newMesh() + { + const graphics$1 = new graphics.Graphics(); + // TODO: make Graphics2d + + graphics$1.convertTo2d(); + + return graphics$1; + }; + spineClassPrototype.transformHack = function transformHack() + { + return 2; + }; + } + + function applySpine3dMixin(spineClassPrototype) + { + spineClassPrototype.newMesh = function newMesh(texture, vertices, + uvs, indices, drawMode) + { + return new SimpleMesh3d2d(texture, vertices, uvs, indices, drawMode) ; + }; + spineClassPrototype.newContainer = function newMesh() + { + if (!this.proj) + { + this.convertTo3d(); + } + + return new Container3d() ; + }; + spineClassPrototype.newSprite = function newSprite(texture) + { + return new Sprite3d(texture); + }; + spineClassPrototype.newGraphics = function newMesh() + { + const graphics$1 = new graphics.Graphics(); + // TODO: make Graphics2d + + graphics$1.convertTo3d(); + + return graphics$1; + }; + spineClassPrototype.transformHack = function transformHack() + { + return 2; + }; + } + + // eslint-disable-next-line @typescript-eslint/triple-slash-reference,spaced-comment + + exports.AbstractProjection = AbstractProjection; + exports.Batch2dPluginFactory = Batch2dPluginFactory; + exports.Batch3dGeometry = Batch3dGeometry; + exports.BatchBilinearPluginFactory = BatchBilinearPluginFactory; + exports.BatchBilineardGeometry = BatchBilineardGeometry; + exports.BilinearSurface = BilinearSurface; + exports.Camera3d = Camera3d; + exports.Container2d = Container2d; + exports.Container3d = Container3d; + exports.Euler = Euler; + exports.LinearProjection = LinearProjection; + exports.Matrix2d = Matrix2d; + exports.Matrix3d = Matrix3d; + exports.Mesh2d = Mesh2d; + exports.Mesh3d2d = Mesh3d2d; + exports.ObservableEuler = ObservableEuler; + exports.ObservablePoint3d = ObservablePoint3d; + exports.Point3d = Point3d; + exports.Projection2d = Projection2d; + exports.Projection3d = Projection3d; + exports.ProjectionSurface = ProjectionSurface; + exports.SimpleMesh2d = SimpleMesh2d; + exports.SimpleMesh3d2d = SimpleMesh3d2d; + exports.Sprite2d = Sprite2d; + exports.Sprite2s = Sprite2s; + exports.Sprite3d = Sprite3d; + exports.SpriteMaskFilter2d = SpriteMaskFilter2d; + exports.Surface = Surface; + exports.Text2d = Text2d; + exports.Text2s = Text2s; + exports.Text3d = Text3d; + exports.TilingSprite2d = TilingSprite2d; + exports.TilingSprite2dRenderer = TilingSprite2dRenderer; + exports.UniformBatchRenderer = UniformBatchRenderer; + exports.applySpine2dMixin = applySpine2dMixin; + exports.applySpine3dMixin = applySpine3dMixin; + exports.container2dToLocal = container2dToLocal; + exports.container2dWorldTransform = container2dWorldTransform; + exports.container3dGetDepth = container3dGetDepth; + exports.container3dIsFrontFace = container3dIsFrontFace; + exports.container3dToLocal = container3dToLocal; + exports.container3dWorldTransform = container3dWorldTransform; + exports.getIntersectionFactor = getIntersectionFactor; + exports.getPositionFromQuad = getPositionFromQuad; + exports.transformHack = transformHack$1; + + Object.defineProperty(exports, '__esModule', { value: true }); + +}))); +if (typeof pixi_projection !== 'undefined') { Object.assign(this.PIXI.projection, pixi_projection); } + /*! * VERSION: 2.1.3 @@ -80851,10 +84778,10 @@ module.exports = function (_Plugin) { css transforms without perspective projection) */ -(function () { +;(function () { 'use strict' - var I = (typeof(WebKitCSSMatrix) == 'undefined') ? new DOMMatrix() : new WebKitCSSMatrix() + var I = typeof WebKitCSSMatrix == 'undefined' ? new DOMMatrix() : new WebKitCSSMatrix() function Point(x, y, z) { this.x = x @@ -80869,8 +84796,8 @@ module.exports = function (_Plugin) { function createMatrix(transform) { try { - return (typeof(WebKitCSSMatrix) == 'undefined') ? new DOMMatrix(transform) : new WebKitCSSMatrix(transform) - } catch(e) { + return typeof WebKitCSSMatrix == 'undefined' ? new DOMMatrix(transform) : new WebKitCSSMatrix(transform) + } catch (e) { console.warn(transform) console.warn(e.toString()) return I @@ -80895,8 +84822,9 @@ module.exports = function (_Plugin) { var left = +Infinity var top = +Infinity while (--i >= 0) { - var p = new Point(i === 0 || i === 1 ? 0 : w, i === 0 || i === 3 ? 0 : h, - 0).transformBy(transformationMatrix) + var p = new Point(i === 0 || i === 1 ? 0 : w, i === 0 || i === 3 ? 0 : h, 0).transformBy( + transformationMatrix + ) if (p.x < left) { left = p.x } @@ -80905,23 +84833,22 @@ module.exports = function (_Plugin) { } } var rect = element.getBoundingClientRect() - transformationMatrix = I.translate(window.pageXOffset + rect.left - left, - window.pageYOffset + rect.top - top, 0) - .multiply(transformationMatrix) + transformationMatrix = I.translate( + window.pageXOffset + rect.left - left, + window.pageYOffset + rect.top - top, + 0 + ).multiply(transformationMatrix) return transformationMatrix } window.convertPointFromPageToNode = function (element, pageX, pageY) { - return new Point(pageX, pageY, 0).transformBy( - getTransformationMatrix(element).inverse()) + return new Point(pageX, pageY, 0).transformBy(getTransformationMatrix(element).inverse()) } window.convertPointFromNodeToPage = function (element, offsetX, offsetY) { - return new Point(offsetX, offsetY, 0).transformBy( - getTransformationMatrix(element)) + return new Point(offsetX, offsetY, 0).transformBy(getTransformationMatrix(element)) } - -}()); +})() (function () { diff --git a/dist/iwmlib.3rdparty.min.js b/dist/iwmlib.3rdparty.min.js index e296eb4..fc03ff5 100644 --- a/dist/iwmlib.3rdparty.min.js +++ b/dist/iwmlib.3rdparty.min.js @@ -1 +1,253 @@ -!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.OptimalSelect=t():e.OptimalSelect=t()}(this,function(){return function(r){var i={};function n(e){if(i[e])return i[e].exports;var t=i[e]={i:e,l:!1,exports:{}};return r[e].call(t.exports,t,t.exports,n),t.l=!0,t.exports}return n.m=r,n.c=i,n.i=function(e){return e},n.d=function(e,t,r){n.o(e,t)||Object.defineProperty(e,t,{configurable:!1,enumerable:!0,get:r})},n.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return n.d(t,"a",t),t},n.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},n.p="",n(n.s=6)}([function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.convertNodeList=function(e){for(var t=e.length,r=new Array(t),i=0;i@~]/g,"\\$&").replace(/\n/g,"A")}},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getCommonAncestor=function(e){var t=(1 /g,">").split(/\s+(?=(?:(?:[^"]*"){2})*[^"]*$)/);if(i.length<2)return f("",e,"",t);var n=[i.pop()];for(;1/g,"> ").trim()};var i,n=r(3),h=(i=n)&&i.__esModule?i:{default:i},c=r(0);function f(r,i,n,o){if(r.length&&(r+=" "),n.length&&(n=" "+n),/\[*\]/.test(i)){var e=i.replace(/=.*$/,"]"),a=""+r+e+n;if(g(document.querySelectorAll(a),o))i=e;else for(var s=document.querySelectorAll(""+r+e),t=function(){var t=s[l];if(o.some(function(e){return t.contains(e)})){var e=t.tagName.toLowerCase();return a=""+r+e+n,g(document.querySelectorAll(a),o)&&(i=e),"break"}},l=0,u=s.length;l/.test(i)){var h=i.replace(/>/,"");a=""+r+h+n;g(document.querySelectorAll(a),o)&&(i=h)}if(/:nth-child/.test(i)){var c=i.replace(/nth-child/g,"nth-of-type");a=""+r+c+n;g(document.querySelectorAll(a),o)&&(i=c)}if(/\.\S+\.\S+/.test(i)){for(var f=i.trim().split(".").slice(1).map(function(e){return"."+e}).sort(function(e,t){return e.length-t.length});f.length;){var p=i.replace(f.shift(),"").trim();if(!(a=(""+r+p+n).trim()).length||">"===a.charAt(0)||">"===a.charAt(a.length-1))break;g(document.querySelectorAll(a),o)&&(i=p)}if((f=i&&i.match(/\./g))&&2/.test(s):u=function(t){return function(e){return e(t.parent)&&t.parent}};break;case/^\./.test(s):var r=s.substr(1).split(".");l=function(e){var t=e.attribs.class;return t&&r.every(function(e){return-1)(\S)/g,"$1 $2").trim()),t=i.shift(),n=i.length;return t(this).filter(function(e){for(var t=0;t\s*\(/gm,"{anonymous}()@"):"Unknown Stack Trace",r=o.console&&(o.console.warn||o.console.log);return r&&r.call(o.console,n,t),i.apply(this,arguments)}}a="function"!=typeof Object.assign?function(e){if(e===c||null===e)throw new TypeError("Cannot convert undefined or null to object");for(var t=Object(e),r=1;rt[r]}):i.sort()),i}function C(e,t){for(var r,i,n=t[0].toUpperCase()+t.slice(1),o=0;of(u.y)?u.x:u.y,t.scale=a?function(e,t){return ie(t[0],t[1],J)/ie(e[0],e[1],J)}(a.pointers,i):1,t.rotation=a?function(e,t){return ne(t[1],t[0],J)+ne(e[1],e[0],J)}(a.pointers,i):0,t.maxPointers=r.prevInput?t.pointers.length>r.prevInput.maxPointers?t.pointers.length:r.prevInput.maxPointers:t.pointers.length,function(e,t){var r,i,n,o,a=e.lastInterval||t,s=t.timeStamp-a.timeStamp;if(t.eventType!=B&&(Ff(h.y)?h.x:h.y,o=re(l,u),e.lastInterval=t}else r=a.velocity,i=a.velocityX,n=a.velocityY,o=a.direction;t.velocity=r,t.velocityX=i,t.velocityY=n,t.direction=o}(r,t);var h=e.element;T(t.srcEvent.target,h)&&(h=t.srcEvent.target);t.target=h}(e,r),e.emit("hammer.input",r),e.recognize(r),e.session.prevInput=r}function $(e){for(var t=[],r=0;r=f(t)?e<0?X:H:t<0?G:W}function ie(e,t,r){r||(r=Z);var i=t[r[0]]-e[r[0]],n=t[r[1]]-e[r[1]];return Math.sqrt(i*i+n*n)}function ne(e,t,r){r||(r=Z);var i=t[r[0]]-e[r[0]],n=t[r[1]]-e[r[1]];return 180*Math.atan2(n,i)/Math.PI}K.prototype={handler:function(){},init:function(){this.evEl&&x(this.element,this.evEl,this.domHandler),this.evTarget&&x(this.target,this.evTarget,this.domHandler),this.evWin&&x(O(this.element),this.evWin,this.domHandler)},destroy:function(){this.evEl&&w(this.element,this.evEl,this.domHandler),this.evTarget&&w(this.target,this.evTarget,this.domHandler),this.evWin&&w(O(this.element),this.evWin,this.domHandler)}};var oe={mousedown:j,mousemove:2,mouseup:N},ae="mousedown",se="mousemove mouseup";function le(){this.evEl=ae,this.evWin=se,this.pressed=!1,K.apply(this,arguments)}v(le,K,{handler:function(e){var t=oe[e.type];t&j&&0===e.button&&(this.pressed=!0),2&t&&1!==e.which&&(t=N),this.pressed&&(t&N&&(this.pressed=!1),this.callback(this.manager,t,{pointers:[e],changedPointers:[e],pointerType:L,srcEvent:e}))}});var ue={pointerdown:j,pointermove:2,pointerup:N,pointercancel:B,pointerout:B},he={2:z,3:"pen",4:L,5:"kinect"},ce="pointerdown",fe="pointermove pointerup pointercancel";function pe(){this.evEl=ce,this.evWin=fe,K.apply(this,arguments),this.store=this.manager.session.pointerEvents=[]}o.MSPointerEvent&&!o.PointerEvent&&(ce="MSPointerDown",fe="MSPointerMove MSPointerUp MSPointerCancel"),v(pe,K,{handler:function(e){var t=this.store,r=!1,i=e.type.toLowerCase().replace("ms",""),n=ue[i],o=he[e.pointerType]||e.pointerType,a=o==z,s=S(t,e.pointerId,"pointerId");n&j&&(0===e.button||a)?s<0&&(t.push(e),s=t.length-1):n&(N|B)&&(r=!0),s<0||(t[s]=e,this.callback(this.manager,n,{pointers:t,changedPointers:[e],pointerType:o,srcEvent:e}),r&&t.splice(s,1))}});var de={touchstart:j,touchmove:2,touchend:N,touchcancel:B};function me(){this.evTarget="touchstart",this.evWin="touchstart touchmove touchend touchcancel",this.started=!1,K.apply(this,arguments)}v(me,K,{handler:function(e){var t=de[e.type];if(t===j&&(this.started=!0),this.started){var r=function(e,t){var r=E(e.touches),i=E(e.changedTouches);t&(N|B)&&(r=A(r.concat(i),"identifier",!0));return[r,i]}.call(this,e,t);t&(N|B)&&r[0].length-r[1].length==0&&(this.started=!1),this.callback(this.manager,t,{pointers:r[0],changedPointers:r[1],pointerType:z,srcEvent:e})}}});var ge={touchstart:j,touchmove:2,touchend:N,touchcancel:B},ve="touchstart touchmove touchend touchcancel";function _e(){this.evTarget=ve,this.targetIds={},K.apply(this,arguments)}v(_e,K,{handler:function(e){var t=ge[e.type],r=function(e,t){var r=E(e.touches),i=this.targetIds;if(t&(2|j)&&1===r.length)return i[r[0].identifier]=!0,[r,r];var n,o,a=E(e.changedTouches),s=[],l=this.target;if(o=r.filter(function(e){return T(e.target,l)}),t===j)for(n=0;nt.threshold&&n&t.direction},attrTest:function(e){return Le.prototype.attrTest.call(this,e)&&(2&this.state||!(2&this.state)&&this.directionTest(e))},emit:function(e){this.pX=e.deltaX,this.pY=e.deltaY;var t=Re(e.direction);t&&(e.additionalEvent=this.options.event+t),this._super.emit.call(this,e)}}),v(je,Le,{defaults:{event:"pinch",threshold:0,pointers:2},getTouchAction:function(){return[Se]},attrTest:function(e){return this._super.attrTest.call(this,e)&&(Math.abs(e.scale-1)>this.options.threshold||2&this.state)},emit:function(e){if(1!==e.scale){var t=e.scale<1?"in":"out";e.additionalEvent=this.options.event+t}this._super.emit.call(this,e)}}),v(Ne,Me,{defaults:{event:"press",pointers:1,time:251,threshold:9},getTouchAction:function(){return["auto"]},process:function(e){var t=this.options,r=e.pointers.length===t.pointers,i=e.distancet.time;if(this._input=e,!i||!r||e.eventType&(N|B)&&!n)this.reset();else if(e.eventType&j)this.reset(),this._timer=u(function(){this.state=8,this.tryEmit()},t.time,this);else if(e.eventType&N)return 8;return 32},reset:function(){clearTimeout(this._timer)},emit:function(e){8===this.state&&(e&&e.eventType&N?this.manager.emit(this.options.event+"up",e):(this._input.timeStamp=p(),this.manager.emit(this.options.event,this._input)))}}),v(Be,Le,{defaults:{event:"rotate",threshold:0,pointers:2},getTouchAction:function(){return[Se]},attrTest:function(e){return this._super.attrTest.call(this,e)&&(Math.abs(e.rotation)>this.options.threshold||2&this.state)}}),v(Ue,Le,{defaults:{event:"swipe",threshold:10,velocity:.3,direction:q|V,pointers:1},getTouchAction:function(){return Fe.prototype.getTouchAction.call(this)},attrTest:function(e){var t,r=this.options.direction;return r&(q|V)?t=e.overallVelocity:r&q?t=e.overallVelocityX:r&V&&(t=e.overallVelocityY),this._super.attrTest.call(this,e)&&r&e.offsetDirection&&e.distance>this.options.threshold&&e.maxPointers==this.options.pointers&&f(t)>this.options.velocity&&e.eventType&N},emit:function(e){var t=Re(e.offsetDirection);t&&this.manager.emit(this.options.event+t,e),this.manager.emit(this.options.event,e)}}),v(Xe,Me,{defaults:{event:"tap",pointers:1,taps:1,interval:300,time:250,threshold:9,posThreshold:10},getTouchAction:function(){return[Pe]},process:function(e){var t=this.options,r=e.pointers.length===t.pointers,i=e.distance80*r){i=o=e[0],n=a=e[1];for(var d=r;do.x?n.x>a.x?n.x:a.x:o.x>a.x?o.x:a.x,h=n.y>o.y?n.y>a.y?n.y:a.y:o.y>a.y?o.y:a.y,c=G(s,l,t,r,i),f=G(u,h,t,r,i),p=e.prevZ,d=e.nextZ;p&&p.z>=c&&d&&d.z<=f;){if(p!==e.prev&&p!==e.next&&q(n.x,n.y,o.x,o.y,a.x,a.y,p.x,p.y)&&0<=V(p.prev,p,p.next))return!1;if(p=p.prevZ,d!==e.prev&&d!==e.next&&q(n.x,n.y,o.x,o.y,a.x,a.y,d.x,d.y)&&0<=V(d.prev,d,d.next))return!1;d=d.nextZ}for(;p&&p.z>=c;){if(p!==e.prev&&p!==e.next&&q(n.x,n.y,o.x,o.y,a.x,a.y,p.x,p.y)&&0<=V(p.prev,p,p.next))return!1;p=p.prevZ}for(;d&&d.z<=f;){if(d!==e.prev&&d!==e.next&&q(n.x,n.y,o.x,o.y,a.x,a.y,d.x,d.y)&&0<=V(d.prev,d,d.next))return!1;d=d.nextZ}return!0}function B(e,t,r){var i=e;do{var n=i.prev,o=i.next.next;!Y(n,o)&&Z(n,i,i.next,o)&&$(n,o)&&$(o,n)&&(t.push(n.i/r),t.push(i.i/r),t.push(o.i/r),re(i),re(i.next),i=e=o),i=i.next}while(i!==e);return L(i)}function U(e,t,r,i,n,o){var a,s,l=e;do{for(var u=l.next.next;u!==l.prev;){if(l.i!==u.i&&(s=u,(a=l).next.i!==s.i&&a.prev.i!==s.i&&!function(e,t){var r=e;do{if(r.i!==e.i&&r.next.i!==e.i&&r.i!==t.i&&r.next.i!==t.i&&Z(r,r.next,e,t))return!0;r=r.next}while(r!==e);return!1}(a,s)&&($(a,s)&&$(s,a)&&function(e,t){var r=e,i=!1,n=(e.x+t.x)/2,o=(e.y+t.y)/2;for(;r.y>o!=r.next.y>o&&r.next.y!==r.y&&n<(r.next.x-r.x)*(o-r.y)/(r.next.y-r.y)+r.x&&(i=!i),r=r.next,r!==e;);return i}(a,s)&&(V(a.prev,a,s.prev)||V(a,s.prev,s))||Y(a,s)&&0=i.next.y&&i.next.y!==i.y){var s=i.x+(o-i.y)*(i.next.x-i.x)/(i.next.y-i.y);if(s<=n&&a=i.x&&i.x>=h&&n!==i.x&&q(or.x||i.x===r.x&&(d=i,V((p=r).prev,p,d.prev)<0&&V(d.next,p,p.next)<0)))&&(r=i,f=l)),i=i.next,i!==u;);var p,d;return r}(e,t)){var r=ee(t,e);L(t,t.next),L(r,r.next)}}function G(e,t,r,i,n){return(e=1431655765&((e=858993459&((e=252645135&((e=16711935&((e=32767*(e-r)*n)|e<<8))|e<<4))|e<<2))|e<<1))|(t=1431655765&((t=858993459&((t=252645135&((t=16711935&((t=32767*(t-i)*n)|t<<8))|t<<4))|t<<2))|t<<1))<<1}function W(e){for(var t=e,r=e;(t.x=Math.min(e.x,r.x)&&t.y<=Math.max(e.y,r.y)&&t.y>=Math.min(e.y,r.y)}function Q(e){return 0= 0x80 (not a basic code point)","invalid-input":"Invalid input"},f=_-y,k=Math.floor,P=String.fromCharCode;function S(e){throw RangeError(c[e])}function p(e,t){for(var r=e.length,i=[];r--;)i[r]=t(e[r]);return i}function d(e,t){var r=e.split("@"),i="";return 1>>10&1023|55296),e=56320|1023&e),t+=P(e)}).join("")}function C(e,t){return e+22+75*(e<26)-((0!=t)<<5)}function I(e,t,r){var i=0;for(e=r?k(e/s):e>>1,e+=k(e/t);f*b>>1k((v-d)/a))&&S("overflow"),d+=l*a,!(l<(u=s<=g?y:g+b<=s?b:s-g));s+=_)a>k(v/(h=_-u))&&S("overflow"),a*=h;g=I(d-o,t=f.length+1,0==o),k(d/t)>v-m&&S("overflow"),m+=k(d/t),d%=t,f.splice(d++,0,m)}return A(f)}function g(e){var t,r,i,n,o,a,s,l,u,h,c,f,p,d,m,g=[];for(f=(e=E(e)).length,t=w,o=x,a=r=0;ak((v-r)/(p=i+1))&&S("overflow"),r+=(s-t)*p,t=s,a=0;av&&S("overflow"),c==t){for(l=r,u=_;!(l<(h=u<=o?y:o+b<=u?b:u-o));u+=_)m=l-h,d=_-h,g.push(P(C(h+m%d,0))),l=k(m/d);g.push(P(C(l,0))),o=I(r,p,i==n),r=0,++i}++r,++t}return g.join("")}if(n={version:"1.3.2",ucs2:{decode:E,encode:A},decode:m,encode:g,toASCII:function(e){return d(e,function(e){return u.test(e)?"xn--"+g(e):e})},toUnicode:function(e){return d(e,function(e){return l.test(e)?m(e.slice(4).toLowerCase()):e})}},t&&r)if(O.exports==t)r.exports=n;else for(o in n)n.hasOwnProperty(o)&&(t[o]=n[o]);else e.punycode=n}(D)}),ae={isString:function(e){return"string"==typeof e},isObject:function(e){return"object"==typeof e&&null!==e},isNull:function(e){return null===e},isNullOrUndefined:function(e){return null==e}};ae.isString,ae.isObject,ae.isNull,ae.isNullOrUndefined;var se=function(e,t,r,i){t=t||"&",r=r||"=";var n={};if("string"!=typeof e||0===e.length)return n;var o=/\+/g;e=e.split(t);var a=1e3;i&&"number"==typeof i.maxKeys&&(a=i.maxKeys);var s,l,u=e.length;0",'"',"`"," ","\r","\n","\t"]),xe=["'"].concat(be),we=["%","/","?",";","#"].concat(xe),Te=["/","?","#"],ke=/^[+a-z0-9A-Z_-]{0,63}$/,Pe=/^([+a-z0-9A-Z_-]{0,63})(.*)$/,Se={javascript:!0,"javascript:":!0},Ee={javascript:!0,"javascript:":!0},Ae={http:!0,https:!0,ftp:!0,gopher:!0,file:!0,"http:":!0,"https:":!0,"ftp:":!0,"gopher:":!0,"file:":!0};function Ce(e,t,r){if(e&&ae.isObject(e)&&e instanceof ge)return e;var i=new ge;return i.parse(e,t,r),i}ge.prototype.parse=function(e,t,r){if(!ae.isString(e))throw new TypeError("Parameter 'url' must be a string, not "+typeof e);var i=e.indexOf("?"),n=-1!==i&&i>16&255)/255,t[1]=(e>>8&255)/255,t[2]=(255&e)/255,t}function et(e){var t=e.toString(16);return"#"+(t="000000".substr(0,6-t.length)+t)}function tt(e){return"string"==typeof e&&"#"===e[0]&&(e=e.substr(1)),parseInt(e,16)}var rt=function(){for(var e=[],t=[],r=0;r<32;r++)t[e[r]=r]=r;e[K.BLEND_MODES.NORMAL_NPM]=K.BLEND_MODES.NORMAL,e[K.BLEND_MODES.ADD_NPM]=K.BLEND_MODES.ADD,e[K.BLEND_MODES.SCREEN_NPM]=K.BLEND_MODES.SCREEN,t[K.BLEND_MODES.NORMAL]=K.BLEND_MODES.NORMAL_NPM,t[K.BLEND_MODES.ADD]=K.BLEND_MODES.ADD_NPM,t[K.BLEND_MODES.SCREEN]=K.BLEND_MODES.SCREEN_NPM;var i=[];return i.push(t),i.push(e),i}();function it(e,t){return rt[t?1:0][e]}function nt(e,t,r,i){return r=r||new Float32Array(4),i||void 0===i?(r[0]=e[0]*t,r[1]=e[1]*t,r[2]=e[2]*t):(r[0]=e[0],r[1]=e[1],r[2]=e[2]),r[3]=t,r}function ot(e,t){if(1===t)return(255*t<<24)+e;if(0===t)return 0;var r=e>>16&255,i=e>>8&255,n=255&e;return(255*t<<24)+((r=r*t+.5|0)<<16)+((i=i*t+.5|0)<<8)+(n=n*t+.5|0)}function at(e,t,r,i){return(r=r||new Float32Array(4))[0]=(e>>16&255)/255,r[1]=(e>>8&255)/255,r[2]=(255&e)/255,(i||void 0===i)&&(r[0]*=t,r[1]*=t,r[2]*=t),r[3]=t,r}function st(e,t){void 0===t&&(t=null);var r=6*e;if((t=t||new Uint16Array(r)).length!==r)throw new Error("Out buffer length is incorrect, got "+t.length+" and expected "+r);for(var i=0,n=0;i>>1,e|=e>>>2,e|=e>>>4,e|=e>>>8,(e|=e>>>16)+1}function ct(e){return!(e&e-1||!e)}function ft(e){var t=(65535>>=t)?1:0)<<3;return t|=r,t|=r=(15<(e>>>=r)?1:0)<<2,(t|=r=(3<(e>>>=r)?1:0)<<1)|(e>>>=r)>>1}function pt(e,t,r){var i,n=e.length;if(!(n<=t||0===r)){var o=n-(r=n=this.x&&e=this.y&&t=this.x&&e<=this.x+this.width&&t>=this.y&&t<=this.y+this.height){if(t>=this.y+this.radius&&t<=this.y+this.height-this.radius||e>=this.x+this.radius&&e<=this.x+this.width-this.radius)return!0;var r=e-(this.x+this.radius),i=t-(this.y+this.radius),n=this.radius*this.radius;if(r*r+i*i<=n)return!0;if((r=e-(this.x+this.width-this.radius))*r+i*i<=n)return!0;if(r*r+(i=t-(this.y+this.height-this.radius))*i<=n)return!0;if((r=e-(this.x+this.radius))*r+i*i<=n)return!0}return!1},e}(),jt=function(){function e(e,t){void 0===e&&(e=0),void 0===t&&(t=0),this.x=e,this.y=t}return e.prototype.clone=function(){return new e(this.x,this.y)},e.prototype.copyFrom=function(e){return this.set(e.x,e.y),this},e.prototype.copyTo=function(e){return e.set(this.x,this.y),e},e.prototype.equals=function(e){return e.x===this.x&&e.y===this.y},e.prototype.set=function(e,t){return void 0===e&&(e=0),void 0===t&&(t=e),this.x=e,this.y=t,this},e}(),Nt=function(){function r(e,t,r,i){void 0===r&&(r=0),void 0===i&&(i=0),this._x=r,this._y=i,this.cb=e,this.scope=t}return r.prototype.clone=function(e,t){return void 0===e&&(e=this.cb),void 0===t&&(t=this.scope),new r(e,t,this._x,this._y)},r.prototype.set=function(e,t){return void 0===e&&(e=0),void 0===t&&(t=e),this._x===e&&this._y===t||(this._x=e,this._y=t,this.cb.call(this.scope)),this},r.prototype.copyFrom=function(e){return this._x===e.x&&this._y===e.y||(this._x=e.x,this._y=e.y,this.cb.call(this.scope)),this},r.prototype.copyTo=function(e){return e.set(this._x,this._y),e},r.prototype.equals=function(e){return e.x===this._x&&e.y===this._y},Object.defineProperty(r.prototype,"x",{get:function(){return this._x},set:function(e){this._x!==e&&(this._x=e,this.cb.call(this.scope))},enumerable:!1,configurable:!0}),Object.defineProperty(r.prototype,"y",{get:function(){return this._y},set:function(e){this._y!==e&&(this._y=e,this.cb.call(this.scope))},enumerable:!1,configurable:!0}),r}(),Bt=function(){function t(e,t,r,i,n,o){void 0===e&&(e=1),void 0===t&&(t=0),void 0===r&&(r=0),void 0===i&&(i=1),void 0===n&&(n=0),void 0===o&&(o=0),this.array=null,this.a=e,this.b=t,this.c=r,this.d=i,this.tx=n,this.ty=o}return t.prototype.fromArray=function(e){this.a=e[0],this.b=e[1],this.c=e[3],this.d=e[4],this.tx=e[2],this.ty=e[5]},t.prototype.set=function(e,t,r,i,n,o){return this.a=e,this.b=t,this.c=r,this.d=i,this.tx=n,this.ty=o,this},t.prototype.toArray=function(e,t){this.array||(this.array=new Float32Array(9));var r=t||this.array;return e?(r[0]=this.a,r[1]=this.b,r[2]=0,r[3]=this.c,r[4]=this.d,r[5]=0,r[6]=this.tx,r[7]=this.ty):(r[0]=this.a,r[1]=this.c,r[2]=this.tx,r[3]=this.b,r[4]=this.d,r[5]=this.ty,r[6]=0,r[7]=0),r[8]=1,r},t.prototype.apply=function(e,t){t=t||new jt;var r=e.x,i=e.y;return t.x=this.a*r+this.c*i+this.tx,t.y=this.b*r+this.d*i+this.ty,t},t.prototype.applyInverse=function(e,t){t=t||new jt;var r=1/(this.a*this.d+this.c*-this.b),i=e.x,n=e.y;return t.x=this.d*r*i+-this.c*r*n+(this.ty*this.c-this.tx*this.d)*r,t.y=this.a*r*n+-this.b*r*i+(-this.ty*this.a+this.tx*this.b)*r,t},t.prototype.translate=function(e,t){return this.tx+=e,this.ty+=t,this},t.prototype.scale=function(e,t){return this.a*=e,this.d*=t,this.c*=e,this.b*=t,this.tx*=e,this.ty*=t,this},t.prototype.rotate=function(e){var t=Math.cos(e),r=Math.sin(e),i=this.a,n=this.c,o=this.tx;return this.a=i*t-this.b*r,this.b=i*r+this.b*t,this.c=n*t-this.d*r,this.d=n*r+this.d*t,this.tx=o*t-this.ty*r,this.ty=o*r+this.ty*t,this},t.prototype.append=function(e){var t=this.a,r=this.b,i=this.c,n=this.d;return this.a=e.a*t+e.b*i,this.b=e.a*r+e.b*n,this.c=e.c*t+e.d*i,this.d=e.c*r+e.d*n,this.tx=e.tx*t+e.ty*i+this.tx,this.ty=e.tx*r+e.ty*n+this.ty,this},t.prototype.setTransform=function(e,t,r,i,n,o,a,s,l){return this.a=Math.cos(a+l)*n,this.b=Math.sin(a+l)*n,this.c=-Math.sin(a-s)*o,this.d=Math.cos(a-s)*o,this.tx=e-(r*this.a+i*this.c),this.ty=t-(r*this.b+i*this.d),this},t.prototype.prepend=function(e){var t=this.tx;if(1!==e.a||0!==e.b||0!==e.c||1!==e.d){var r=this.a,i=this.c;this.a=r*e.a+this.b*e.c,this.b=r*e.b+this.b*e.d,this.c=i*e.a+this.d*e.c,this.d=i*e.b+this.d*e.d}return this.tx=t*e.a+this.ty*e.c+e.tx,this.ty=t*e.b+this.ty*e.d+e.ty,this},t.prototype.decompose=function(e){var t=this.a,r=this.b,i=this.c,n=this.d,o=-Math.atan2(-i,n),a=Math.atan2(r,t),s=Math.abs(o+a);return s<1e-5||Math.abs(It-s)<1e-5?(e.rotation=a,e.skew.x=e.skew.y=0):(e.rotation=0,e.skew.x=o,e.skew.y=a),e.scale.x=Math.sqrt(t*t+r*r),e.scale.y=Math.sqrt(i*i+n*n),e.position.x=this.tx,e.position.y=this.ty,e},t.prototype.invert=function(){var e=this.a,t=this.b,r=this.c,i=this.d,n=this.tx,o=e*i-t*r;return this.a=i/o,this.b=-t/o,this.c=-r/o,this.d=e/o,this.tx=(r*this.ty-i*n)/o,this.ty=-(e*this.ty-t*n)/o,this},t.prototype.identity=function(){return this.a=1,this.b=0,this.c=0,this.d=1,this.tx=0,this.ty=0,this},t.prototype.clone=function(){var e=new t;return e.a=this.a,e.b=this.b,e.c=this.c,e.d=this.d,e.tx=this.tx,e.ty=this.ty,e},t.prototype.copyTo=function(e){return e.a=this.a,e.b=this.b,e.c=this.c,e.d=this.d,e.tx=this.tx,e.ty=this.ty,e},t.prototype.copyFrom=function(e){return this.a=e.a,this.b=e.b,this.c=e.c,this.d=e.d,this.tx=e.tx,this.ty=e.ty,this},Object.defineProperty(t,"IDENTITY",{get:function(){return new t},enumerable:!1,configurable:!0}),Object.defineProperty(t,"TEMP_MATRIX",{get:function(){return new t},enumerable:!1,configurable:!0}),t}(),Ut=[1,1,0,-1,-1,-1,0,1,1,1,0,-1,-1,-1,0,1],Xt=[0,1,1,1,0,-1,-1,-1,0,1,1,1,0,-1,-1,-1],Ht=[0,-1,-1,-1,0,1,1,1,0,1,1,1,0,-1,-1,-1],Gt=[1,1,0,-1,-1,-1,0,1,-1,-1,0,1,1,1,0,-1],Wt=[],qt=[],Vt=Math.sign;!function(){for(var e=0;e<16;e++){var t=[];Wt.push(t);for(var r=0;r<16;r++)for(var i=Vt(Ut[e]*Ut[r]+Ht[e]*Xt[r]),n=Vt(Xt[e]*Ut[r]+Gt[e]*Xt[r]),o=Vt(Ut[e]*Ht[r]+Ht[e]*Gt[r]),a=Vt(Xt[e]*Ht[r]+Gt[e]*Gt[r]),s=0;s<16;s++)if(Ut[s]===i&&Xt[s]===n&&Ht[s]===o&&Gt[s]===a){t.push(s);break}}for(e=0;e<16;e++){var l=new Bt;l.set(Ut[e],Xt[e],Ht[e],Gt[e],0,0),qt.push(l)}}();var Yt={E:0,SE:1,S:2,SW:3,W:4,NW:5,N:6,NE:7,MIRROR_VERTICAL:8,MAIN_DIAGONAL:10,MIRROR_HORIZONTAL:12,REVERSE_DIAGONAL:14,uX:function(e){return Ut[e]},uY:function(e){return Xt[e]},vX:function(e){return Ht[e]},vY:function(e){return Gt[e]},inv:function(e){return 8&e?15&e:7&-e},add:function(e,t){return Wt[e][t]},sub:function(e,t){return Wt[e][Yt.inv(t)]},rotate180:function(e){return 4^e},isVertical:function(e){return 2==(3&e)},byDirection:function(e,t){return 2*Math.abs(e)<=Math.abs(t)?0<=t?Yt.S:Yt.N:2*Math.abs(t)<=Math.abs(e)?0this.maxX||this.minY>this.maxY},e.prototype.clear=function(){this.minX=1/0,this.minY=1/0,this.maxX=-1/0,this.maxY=-1/0},e.prototype.getRectangle=function(e){return this.minX>this.maxX||this.minY>this.maxY?Dt.EMPTY:((e=e||new Dt(0,0,1,1)).x=this.minX,e.y=this.minY,e.width=this.maxX-this.minX,e.height=this.maxY-this.minY,e)},e.prototype.addPoint=function(e){this.minX=Math.min(this.minX,e.x),this.maxX=Math.max(this.maxX,e.x),this.minY=Math.min(this.minY,e.y),this.maxY=Math.max(this.maxY,e.y)},e.prototype.addQuad=function(e){var t=this.minX,r=this.minY,i=this.maxX,n=this.maxY,o=e[0],a=e[1];t=oi?e.maxX:i,this.maxY=e.maxY>n?e.maxY:n},e.prototype.addBoundsMask=function(e,t){var r=e.minX>t.minX?e.minX:t.minX,i=e.minY>t.minY?e.minY:t.minY,n=e.maxXt.x?e.minX:t.x,i=e.minY>t.y?e.minY:t.y,n=e.maxXr?this.maxX:r,this.minY=this.minYi?this.maxY:i},e}(),Kt=function(e,t){return(Kt=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])})(e,t)};function Qt(e,t){function r(){this.constructor=e}Kt(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)}var $t=function(t){function n(){var e=t.call(this)||this;return e.tempDisplayObjectParent=null,e.transform=new Zt,e.alpha=1,e.visible=!0,e.renderable=!0,e.parent=null,e.worldAlpha=1,e._lastSortedIndex=0,e._zIndex=0,e.filterArea=null,e.filters=null,e._enabledFilters=null,e._bounds=new Jt,e._localBounds=null,e._boundsID=0,e._boundsRect=null,e._localBoundsRect=null,e._mask=null,e._destroyed=!1,e.isSprite=!1,e.isMask=!1,e}return Qt(n,t),n.mixin=function(e){for(var t=Object.keys(e),r=0;rthis.children.length)throw new Error(e+"addChildAt: The index "+t+" supplied is out of bounds "+this.children.length);return e.parent&&e.parent.removeChild(e),(e.parent=this).sortDirty=!0,e.transform._parentID=-1,this.children.splice(t,0,e),this._boundsID++,this.onChildrenChange(t),e.emit("added",this),this.emit("childAdded",e,this,t),e},e.prototype.swapChildren=function(e,t){if(e!==t){var r=this.getChildIndex(e),i=this.getChildIndex(t);this.children[r]=t,this.children[i]=e,this.onChildrenChange(r=this.children.length)throw new Error("The index "+t+" supplied is out of bounds "+this.children.length);var r=this.getChildIndex(e);pt(this.children,r,1),this.children.splice(t,0,e),this.onChildrenChange(t)},e.prototype.getChildAt=function(e){if(e<0||e>=this.children.length)throw new Error("getChildAt: Index ("+e+") does not exist.");return this.children[e]},e.prototype.removeChild=function(){for(var e=arguments,t=[],r=0;r title : "+e.title+"
tabIndex: "+e.tabIndex},e.prototype.capHitArea=function(e){e.x<0&&(e.width+=e.x,e.x=0),e.y<0&&(e.height+=e.y,e.y=0),e.x+e.width>this.renderer.width&&(e.width=this.renderer.width-e.x),e.y+e.height>this.renderer.height&&(e.height=this.renderer.height-e.y)},e.prototype.addChild=function(e){var t=this.pool.pop();t||((t=document.createElement("button")).style.width="100px",t.style.height="100px",t.style.backgroundColor=this.debug?"rgba(255,255,255,0.5)":"transparent",t.style.position="absolute",t.style.zIndex=2..toString(),t.style.borderStyle="none",-1t.priority){e.connect(r);break}t=(r=t).next}e.previous||e.connect(r)}else e.connect(r);return this._startIfPossible(),this},t.prototype.remove=function(e,t){for(var r=this._head.next;r;)r=r.match(e,t)?r.destroy():r.next;return this._head.next||this._cancelIfNeeded(),this},Object.defineProperty(t.prototype,"count",{get:function(){if(!this._head)return 0;for(var e=0,t=this._head;t=t.next;)e++;return e},enumerable:!1,configurable:!0}),t.prototype.start=function(){this.started||(this.started=!0,this._requestIfNeeded())},t.prototype.stop=function(){this.started&&(this.started=!1,this._cancelIfNeeded())},t.prototype.destroy=function(){if(!this._protected){this.stop();for(var e=this._head.next;e;)e=e.destroy(!0);this._head.destroy(),this._head=null}},t.prototype.update=function(e){var t;if(void 0===e&&(e=performance.now()),e>this.lastTime){if((t=this.elapsedMS=e-this.lastTime)>this._maxElapsedMS&&(t=this._maxElapsedMS),t*=this.speed,this._minElapsedMS){var r=e-this._lastFrame|0;if(r]*(?:\s(width|height)=('|")(\d*(?:\.\d+)?)(?:px)?('|"))[^>]*(?:\s(width|height)=('|")(\d*(?:\.\d+)?)(?:px)?('|"))[^>]*>/i,n}(Ar),Dr=function(f){function p(e,t){var r=this;if(t=t||{},!(e instanceof HTMLVideoElement)){var i=document.createElement("video");i.setAttribute("preload","auto"),i.setAttribute("webkit-playsinline",""),i.setAttribute("playsinline",""),"string"==typeof e&&(e=[e]);var n=e[0].src||e[0];Ar.crossOrigin(i,n,t.crossorigin);for(var o=0;othis.baseTexture.width,a=r+n>this.baseTexture.height;if(o||a){var s=o&&a?"and":"or",l="X: "+t+" + "+i+" = "+(t+i)+" > "+this.baseTexture.width,u="Y: "+r+" + "+n+" = "+(r+n)+" > "+this.baseTexture.height;throw new Error("Texture Error: frame does not fit inside the base Texture dimensions: "+l+" "+s+" "+u)}this.valid=i&&n&&this.baseTexture.valid,this.trim||this.rotate||(this.orig=e),this.valid&&this.updateUvs()},enumerable:!1,configurable:!0}),Object.defineProperty(l.prototype,"rotate",{get:function(){return this._rotate},set:function(e){this._rotate=e,this.valid&&this.updateUvs()},enumerable:!1,configurable:!0}),Object.defineProperty(l.prototype,"width",{get:function(){return this.orig.width},enumerable:!1,configurable:!0}),Object.defineProperty(l.prototype,"height",{get:function(){return this.orig.height},enumerable:!1,configurable:!0}),l.prototype.castToBaseTexture=function(){return this.baseTexture},l}(I);function Hr(e){e.destroy=function(){},e.on=function(){},e.once=function(){},e.emit=function(){}}Xr.EMPTY=new Xr(new Pr),Hr(Xr.EMPTY),Hr(Xr.EMPTY.baseTexture),Xr.WHITE=function(){var e=document.createElement("canvas");e.width=16,e.height=16;var t=e.getContext("2d");return t.fillStyle="white",t.fillRect(0,0,16,16),new Xr(new Pr(new Cr(e)))}(),Hr(Xr.WHITE),Hr(Xr.WHITE.baseTexture);var Gr=function(l){function t(e,t){var r=this,i=null;if(!(e instanceof Nr)){var n=arguments[1],o=arguments[2],a=arguments[3],s=arguments[4];console.warn("Please use RenderTexture.create("+n+", "+o+") instead of the ctor directly."),i=arguments[0],t=null,e=new Nr({width:n,height:o,scaleMode:a,resolution:s})}return(r=l.call(this,e,t)||this).legacyRenderer=i,r.valid=!0,r.filterFrame=null,r.filterPoolKey=null,r.updateUvs(),r}return xr(t,l),Object.defineProperty(t.prototype,"framebuffer",{get:function(){return this.baseTexture.framebuffer},enumerable:!1,configurable:!0}),t.prototype.resize=function(e,t,r){void 0===r&&(r=!0),e=Math.ceil(e),t=Math.ceil(t),this.valid=0=K.ENV.WEBGL2&&(r=e.getContext("webgl2",t)),r)this.webGLVersion=2;else if(this.webGLVersion=1,!(r=e.getContext("webgl",t)||e.getContext("experimental-webgl",t)))throw new Error("This browser does not support WebGL. Try using the canvas renderer");return this.gl=r,this.getExtensions(),this.gl},e.prototype.getExtensions=function(){var e=this.gl;1===this.webGLVersion?Object.assign(this.extensions,{drawBuffers:e.getExtension("WEBGL_draw_buffers"),depthTexture:e.getExtension("WEBGL_depth_texture"),loseContext:e.getExtension("WEBGL_lose_context"),vertexArrayObject:e.getExtension("OES_vertex_array_object")||e.getExtension("MOZ_OES_vertex_array_object")||e.getExtension("WEBKIT_OES_vertex_array_object"),anisotropicFiltering:e.getExtension("EXT_texture_filter_anisotropic"),uint32ElementIndex:e.getExtension("OES_element_index_uint"),floatTexture:e.getExtension("OES_texture_float"),floatTextureLinear:e.getExtension("OES_texture_float_linear"),textureHalfFloat:e.getExtension("OES_texture_half_float"),textureHalfFloatLinear:e.getExtension("OES_texture_half_float_linear")}):2===this.webGLVersion&&Object.assign(this.extensions,{anisotropicFiltering:e.getExtension("EXT_texture_filter_anisotropic"),colorBufferFloat:e.getExtension("EXT_color_buffer_float"),floatTextureLinear:e.getExtension("OES_texture_float_linear")})},e.prototype.handleContextLost=function(e){e.preventDefault()},e.prototype.handleContextRestored=function(){this.renderer.runners.contextChange.emit(this.gl)},e.prototype.destroy=function(){var e=this.renderer.view;e.removeEventListener("webglcontextlost",this.handleContextLost),e.removeEventListener("webglcontextrestored",this.handleContextRestored),this.gl.useProgram(null),this.extensions.loseContext&&this.extensions.loseContext.loseContext()},e.prototype.postrender=function(){this.renderer.renderingToScreen&&this.gl.flush()},e.prototype.validateContext=function(e){e.getContextAttributes().stencil||console.warn("Provided WebGL context does not have a stencil buffer, masks may not render correctly");var t="WebGL2RenderingContext"in window&&e instanceof window.WebGL2RenderingContext||!!e.getExtension("OES_element_index_uint");(this.supports.uint32Indices=t)||console.warn("Provided WebGL context does not support 32 index buffer, complex graphics may not render correctly")},e}(Lr),ci=function(e){this.framebuffer=e,this.stencil=null,this.dirtyId=0,this.dirtyFormat=0,this.dirtySize=0,this.multisample=K.MSAA_QUALITY.NONE,this.msaaBuffer=null,this.blitFramebuffer=null},fi=new Dt,pi=function(r){function e(e){var t=r.call(this,e)||this;return t.managedFramebuffers=[],t.unknownFramebuffer=new jr(10,10),t.msaaSamples=null,t}return xr(e,r),e.prototype.contextChange=function(){var e=this.gl=this.renderer.gl;if(this.CONTEXT_UID=this.renderer.CONTEXT_UID,this.current=this.unknownFramebuffer,this.viewport=new Dt,this.hasMRT=!0,this.writeDepthTexture=!0,this.disposeAll(!0),1===this.renderer.context.webGLVersion){var t=this.renderer.context.extensions.drawBuffers,r=this.renderer.context.extensions.depthTexture;C.PREFER_ENV===K.ENV.WEBGL_LEGACY&&(r=t=null),t?e.drawBuffers=function(e){return t.drawBuffersWEBGL(e)}:(this.hasMRT=!1,e.drawBuffers=function(){}),r||(this.writeDepthTexture=!1)}else this.msaaSamples=e.getInternalformatParameter(e.RENDERBUFFER,e.RGBA8,e.SAMPLES)},e.prototype.bind=function(e,t){var r=this.gl;if(e){var i=e.glFramebuffers[this.CONTEXT_UID]||this.initFramebuffer(e);this.current!==e&&(this.current=e,r.bindFramebuffer(r.FRAMEBUFFER,i.framebuffer)),i.dirtyId!==e.dirtyId&&(i.dirtyId=e.dirtyId,i.dirtyFormat!==e.dirtyFormat?(i.dirtyFormat=e.dirtyFormat,this.updateFramebuffer(e)):i.dirtySize!==e.dirtySize&&(i.dirtySize=e.dirtySize,this.resizeFramebuffer(e)));for(var n=0;n=i.data.byteLength)t.bufferSubData(o,0,i.data);else{var a=i.static?t.STATIC_DRAW:t.DYNAMIC_DRAW;n.byteLength=i.data.byteLength,t.bufferData(o,i.data,a)}}}},e.prototype.checkCompatibility=function(e,t){var r=e.attributes,i=t.attributeData;for(var n in i)if(!r[n])throw new Error('shader and geometry incompatible, geometry missing the "'+n+'" attribute')},e.prototype.getSignature=function(e,t){var r=e.attributes,i=t.attributeData,n=["g",e.id];for(var o in r)i[o]&&n.push(o);return n.join("-")},e.prototype.initGeometryVao=function(e,t){this.checkCompatibility(e,t);var r=this.gl,i=this.CONTEXT_UID,n=this.getSignature(e,t),o=e.glVertexArrayObjects[this.CONTEXT_UID],a=o[n];if(a)return o[t.id]=a;var s=e.buffers,l=e.attributes,u={},h={};for(var c in s)u[c]=0,h[c]=0;for(var c in l)!l[c].size&&t.attributeData[c]?l[c].size=t.attributeData[c].size:l[c].size||console.warn("PIXI Geometry attribute '"+c+"' size cannot be determined (likely the bound shader does not have the attribute)"),u[l[c].buffer]+=l[c].size*mi[l[c].type];for(var c in l){var f=l[c],p=f.size;void 0===f.stride&&(u[f.buffer]===p*mi[f.type]?f.stride=0:f.stride=u[f.buffer]),void 0===f.start&&(f.start=h[f.buffer],h[f.buffer]+=p*mi[f.type])}a=r.createVertexArray(),r.bindVertexArray(a);for(var d=0;d=K.ENV.WEBGL2&&(t=e.getContext("webgl2",{})),t||((t=e.getContext("webgl",{})||e.getContext("experimental-webgl",{}))?t.getExtension("WEBGL_draw_buffers"):t=null),ki=t}return ki}function Si(e,t,r){if("precision"===e.substring(0,9))return r!==K.PRECISION.HIGH&&"precision highp"===e.substring(0,15)?e.replace("precision highp","precision mediump"):e;var i=t;return t===K.PRECISION.HIGH&&r!==K.PRECISION.HIGH&&(i=K.PRECISION.MEDIUM),"precision "+i+" float;\n"+e}var Ei={float:1,vec2:2,vec3:3,vec4:4,int:1,ivec2:2,ivec3:3,ivec4:4,bool:1,bvec2:2,bvec3:3,bvec4:4,mat2:4,mat3:9,mat4:16,sampler2D:1};var Ai=null,Ci={FLOAT:"float",FLOAT_VEC2:"vec2",FLOAT_VEC3:"vec3",FLOAT_VEC4:"vec4",INT:"int",INT_VEC2:"ivec2",INT_VEC3:"ivec3",INT_VEC4:"ivec4",BOOL:"bool",BOOL_VEC2:"bvec2",BOOL_VEC3:"bvec3",BOOL_VEC4:"bvec4",FLOAT_MAT2:"mat2",FLOAT_MAT3:"mat3",FLOAT_MAT4:"mat4",SAMPLER_2D:"sampler2D",INT_SAMPLER_2D:"sampler2D",UNSIGNED_INT_SAMPLER_2D:"sampler2D",SAMPLER_CUBE:"samplerCube",INT_SAMPLER_CUBE:"samplerCube",UNSIGNED_INT_SAMPLER_CUBE:"samplerCube",SAMPLER_2D_ARRAY:"sampler2DArray",INT_SAMPLER_2D_ARRAY:"sampler2DArray",UNSIGNED_INT_SAMPLER_2D_ARRAY:"sampler2DArray"};function Ii(e,t){if(!Ai){var r=Object.keys(Ci);Ai={};for(var i=0;it.name?1:-1});for(a=0;a>=1,r++;this.stateId=e.data}for(r=0;rthis.checkCountMax&&(this.checkCount=0,this.run())))},e.prototype.run=function(){for(var e=this.renderer.texture,t=e.managedTextures,r=!1,i=0;ithis.maxIdle&&(e.destroyTexture(n,!0),r=!(t[i]=null))}if(r){var o=0;for(i=0;ithis.size&&this.flush(),this._vertexCount+=e.vertexData.length/2,this._indexCount+=e.indices.length,this._bufferedTextures[this._bufferSize]=e._texture.baseTexture,this._bufferedElements[this._bufferSize++]=e)},g.prototype.buildTexturesAndDrawCalls=function(){var e=this._bufferedTextures,t=this.MAX_TEXTURES,r=g._textureArrayPool,i=this.renderer.batch,n=this._tempBoundTextures,o=this.renderer.textureGC.count,a=++Pr._globalBatch,s=0,l=r[0],u=0;i.copyBoundTextures(n,t);for(var h=0;h=t&&(i.boundArray(l,n,a,t),this.buildDrawCalls(l,u,h),u=h,l=r[++s],++a),c._batchEnabled=a,c.touched=o,l.elements[l.count++]=c)}0>2,n[1]=(3&i[0])<<4|i[1]>>4,n[2]=(15&i[1])<<2|i[2]>>6,n[3]=63&i[2],r-(e.length-1)){case 2:n[3]=64,n[2]=64;break;case 1:n[3]=64}for(var a=0;a=a.length&&a.push(this._generateOneMoreBuffer(e));var d=a[f];d.uploadDynamic(t,c,p);var m=e._bufferUpdateIDs[f]||0;(h=h||d._updateIDthis.maxSegments&&(r=this.maxSegments),r}},mo=function(){function t(){this.color=16777215,this.alpha=1,this.texture=Xr.WHITE,this.matrix=null,this.visible=!1,this.reset()}return t.prototype.clone=function(){var e=new t;return e.color=this.color,e.alpha=this.alpha,e.texture=this.texture,e.matrix=this.matrix,e.visible=this.visible,e},t.prototype.reset=function(){this.color=16777215,this.alpha=1,this.texture=Xr.WHITE,this.matrix=null,this.visible=!1},t.prototype.destroy=function(){this.texture=null,this.matrix=null},t}(),go=function(e,t){return(go=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])})(e,t)};function vo(e,t){function r(){this.constructor=e}go(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)}var _o={build:function(e){e.points=e.shape.points.slice()},triangulate:function(e,t){var r=e.points,i=e.holes,n=t.points,o=t.indices;if(6<=r.length){for(var a=[],s=0;s>0),v=p/g;if(f+=v,s){a.push(e,t),a.push(r,i);for(var _=1,y=f;_>16)+(65280&t)+((255&t)<<16),r);0>16&255)/255*n,o.tint[1]=(i>>8&255)/255*n,o.tint[2]=(255&i)/255*n,o.tint[3]=n,e.shader.bind(t),e.geometry.bind(r,t),e.state.set(this.state);for(var s=0,l=a.length;s>16)+(65280&n)+((255&n)<<16)}}},t.prototype.calculateVertices=function(){var e=this.transform._worldID;if(this._transformID!==e){this._transformID=e;for(var t=this.transform.worldTransform,r=t.a,i=t.b,n=t.c,o=t.d,a=t.tx,s=t.ty,l=this._geometry.points,u=this.vertexData,h=0,c=0;c=i&&Vo.x=n&&Vo.y>16)+(65280&e)+((255&e)<<16)},enumerable:!1,configurable:!0}),Object.defineProperty(i.prototype,"texture",{get:function(){return this._texture},set:function(e){this._texture!==e&&(this._texture&&this._texture.off("update",this._onTextureUpdate,this),this._texture=e||Xr.EMPTY,this._cachedTint=16777215,this._textureID=-1,this._textureTrimmedID=-1,e&&(e.baseTexture.valid?this._onTextureUpdate():e.once("update",this._onTextureUpdate,this)))},enumerable:!1,configurable:!0}),i}(rr),Jo=function(e,t){return(Jo=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])})(e,t)};(qo=K.TEXT_GRADIENT||(K.TEXT_GRADIENT={}))[qo.LINEAR_VERTICAL=0]="LINEAR_VERTICAL";var Ko={align:"left",breakWords:!(qo[qo.LINEAR_HORIZONTAL=1]="LINEAR_HORIZONTAL"),dropShadow:!1,dropShadowAlpha:1,dropShadowAngle:Math.PI/6,dropShadowBlur:0,dropShadowColor:"black",dropShadowDistance:5,fill:"black",fillGradientType:K.TEXT_GRADIENT.LINEAR_VERTICAL,fillGradientStops:[],fontFamily:"Arial",fontSize:26,fontStyle:"normal",fontVariant:"normal",fontWeight:"normal",letterSpacing:0,lineHeight:0,lineJoin:"miter",miterLimit:10,padding:0,stroke:"black",strokeThickness:0,textBaseline:"alphabetic",trim:!1,whiteSpace:"pre",wordWrap:!1,wordWrapWidth:100,leading:0},Qo=["serif","sans-serif","monospace","cursive","fantasy","system-ui"],$o=function(){function t(e){this.styleID=0,this.reset(),ra(this,e,e)}return t.prototype.clone=function(){var e={};return ra(e,this,Ko),new t(e)},t.prototype.reset=function(){ra(this,Ko,Ko)},Object.defineProperty(t.prototype,"align",{get:function(){return this._align},set:function(e){this._align!==e&&(this._align=e,this.styleID++)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"breakWords",{get:function(){return this._breakWords},set:function(e){this._breakWords!==e&&(this._breakWords=e,this.styleID++)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"dropShadow",{get:function(){return this._dropShadow},set:function(e){this._dropShadow!==e&&(this._dropShadow=e,this.styleID++)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"dropShadowAlpha",{get:function(){return this._dropShadowAlpha},set:function(e){this._dropShadowAlpha!==e&&(this._dropShadowAlpha=e,this.styleID++)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"dropShadowAngle",{get:function(){return this._dropShadowAngle},set:function(e){this._dropShadowAngle!==e&&(this._dropShadowAngle=e,this.styleID++)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"dropShadowBlur",{get:function(){return this._dropShadowBlur},set:function(e){this._dropShadowBlur!==e&&(this._dropShadowBlur=e,this.styleID++)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"dropShadowColor",{get:function(){return this._dropShadowColor},set:function(e){var t=ta(e);this._dropShadowColor!==t&&(this._dropShadowColor=t,this.styleID++)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"dropShadowDistance",{get:function(){return this._dropShadowDistance},set:function(e){this._dropShadowDistance!==e&&(this._dropShadowDistance=e,this.styleID++)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"fill",{get:function(){return this._fill},set:function(e){var t=ta(e);this._fill!==t&&(this._fill=t,this.styleID++)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"fillGradientType",{get:function(){return this._fillGradientType},set:function(e){this._fillGradientType!==e&&(this._fillGradientType=e,this.styleID++)},enumerable:!1,configurable:!0}),Object.defineProperty(t.prototype,"fillGradientStops",{get:function(){return this._fillGradientStops},set:function(e){(function(e,t){if(!Array.isArray(e)||!Array.isArray(t))return!1;if(e.length!==t.length)return!1;for(var r=0;r=i&&Sa.x=n&&Sa.y>16)+(65280&e)+((255&e)<<16),this._colorDirty=!0)},enumerable:!1,configurable:!0}),e.prototype.update=function(){if(this._colorDirty){this._colorDirty=!1;var e=this.texture.baseTexture;at(this._tint,this._alpha,this.uniforms.uColor,e.alphaMode)}this.uvMatrix.update()&&(this.uniforms.uTextureMatrix=this.uvMatrix.mapCoord)},e}(Ui),ja=function(s){function e(e,t,r){var i=s.call(this)||this,n=new Yr(e),o=new Yr(t,!0),a=new Yr(r,!0,!0);return i.addAttribute("aVertexPosition",n,2,!1,K.TYPES.FLOAT).addAttribute("aTextureCoord",o,2,!1,K.TYPES.FLOAT).addIndex(a),i._updateId=-1,i}return Ma(e,s),Object.defineProperty(e.prototype,"vertexDirtyId",{get:function(){return this.buffers[0]._updateID},enumerable:!1,configurable:!0}),e}(ei),Na=function(e,t){return(Na=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])})(e,t)};var Ba=function(){this.info=[],this.common=[],this.page=[],this.char=[],this.kerning=[]},Ua=[function(){function e(){}return e.test=function(e){return"string"==typeof e&&0===e.indexOf("info face=")},e.parse=function(e){var t=e.match(/^[a-z]+\s+.+$/gm),r={info:[],common:[],page:[],char:[],chars:[],kerning:[]};for(var i in t){var n=t[i].match(/^[a-z]+/gm)[0],o=t[i].match(/[a-zA-Z]+=([^\s"']+|"([^"]*)")/gm),a={};for(var s in o){var l=o[s].split("="),u=l[0],h=l[1].replace(/"/gm,""),c=parseFloat(h),f=isNaN(c)?h:c;a[u]=f}r[n].push(a)}var p=new Ba;return r.info.forEach(function(e){return p.info.push({face:e.face,size:parseInt(e.size,10)})}),r.common.forEach(function(e){return p.common.push({lineHeight:parseInt(e.lineHeight,10)})}),r.page.forEach(function(e){return p.page.push({id:parseInt(e.id,10),file:e.file})}),r.char.forEach(function(e){return p.char.push({id:parseInt(e.id,10),page:parseInt(e.page,10),x:parseInt(e.x,10),y:parseInt(e.y,10),width:parseInt(e.width,10),height:parseInt(e.height,10),xoffset:parseInt(e.xoffset,10),yoffset:parseInt(e.yoffset,10),xadvance:parseInt(e.xadvance,10)})}),r.kerning.forEach(function(e){return p.kerning.push({first:parseInt(e.first,10),second:parseInt(e.second,10),amount:parseInt(e.amount,10)})}),p},e}(),function(){function e(){}return e.test=function(e){return e instanceof XMLDocument&&e.getElementsByTagName("page").length&&null!==e.getElementsByTagName("info")[0].getAttribute("face")},e.parse=function(e){for(var t=new Ba,r=e.getElementsByTagName("info"),i=e.getElementsByTagName("common"),n=e.getElementsByTagName("page"),o=e.getElementsByTagName("char"),a=e.getElementsByTagName("kerning"),s=0;sl&&(pt(n,1+p-++m,1+v-p),v=p,p=-1,o.push(d),c=Math.max(c,d),f++,i.x=0,i.y+=t.lineHeight,u=null)}}else o.push(h),c=Math.max(c,h),++f,++m,i.x=0,i.y+=t.lineHeight,u=null}var w=a.charAt(a.length-1);"\r"!==w&&"\n"!==w&&(/(?:\s)/.test(w)&&(h=d),o.push(h),c=Math.max(c,h));var T=[];for(v=0;v<=f;v++){var k=0;"right"===this._align?k=c-o[v]:"center"===this._align&&(k=(c-o[v])/2),T.push(k)}var P=n.length,S={},E=[],A=this._activePagesMeshData;for(v=0;v6*M&&!(B.vertices.length<2*La.BATCHABLE_SIZE)||(B.vertices=new Float32Array(8*M),B.uvs=new Float32Array(8*M),B.indices=new Uint16Array(6*M)),B.mesh.size=6*M}for(v=0;v 0.0) {\n c.rgb /= c.a;\n }\n\n vec4 result;\n\n result.r = (m[0] * c.r);\n result.r += (m[1] * c.g);\n result.r += (m[2] * c.b);\n result.r += (m[3] * c.a);\n result.r += m[4];\n\n result.g = (m[5] * c.r);\n result.g += (m[6] * c.g);\n result.g += (m[7] * c.b);\n result.g += (m[8] * c.a);\n result.g += m[9];\n\n result.b = (m[10] * c.r);\n result.b += (m[11] * c.g);\n result.b += (m[12] * c.b);\n result.b += (m[13] * c.a);\n result.b += m[14];\n\n result.a = (m[15] * c.r);\n result.a += (m[16] * c.g);\n result.a += (m[17] * c.b);\n result.a += (m[18] * c.a);\n result.a += m[19];\n\n vec3 rgb = mix(c.rgb, result.rgb, uAlpha);\n\n // Premultiply alpha again.\n rgb *= result.a;\n\n gl_FragColor = vec4(rgb, result.a);\n}\n",t)||this).alpha=1,e}return function(e,t){function r(){this.constructor=e}Ns(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)}(e,r),e.prototype._loadMatrix=function(e,t){void 0===t&&(t=!1);var r=e;t&&(this._multiply(r,this.uniforms.m,e),r=this._colorMatrix(r)),this.uniforms.m=r},e.prototype._multiply=function(e,t,r){return e[0]=t[0]*r[0]+t[1]*r[5]+t[2]*r[10]+t[3]*r[15],e[1]=t[0]*r[1]+t[1]*r[6]+t[2]*r[11]+t[3]*r[16],e[2]=t[0]*r[2]+t[1]*r[7]+t[2]*r[12]+t[3]*r[17],e[3]=t[0]*r[3]+t[1]*r[8]+t[2]*r[13]+t[3]*r[18],e[4]=t[0]*r[4]+t[1]*r[9]+t[2]*r[14]+t[3]*r[19]+t[4],e[5]=t[5]*r[0]+t[6]*r[5]+t[7]*r[10]+t[8]*r[15],e[6]=t[5]*r[1]+t[6]*r[6]+t[7]*r[11]+t[8]*r[16],e[7]=t[5]*r[2]+t[6]*r[7]+t[7]*r[12]+t[8]*r[17],e[8]=t[5]*r[3]+t[6]*r[8]+t[7]*r[13]+t[8]*r[18],e[9]=t[5]*r[4]+t[6]*r[9]+t[7]*r[14]+t[8]*r[19]+t[9],e[10]=t[10]*r[0]+t[11]*r[5]+t[12]*r[10]+t[13]*r[15],e[11]=t[10]*r[1]+t[11]*r[6]+t[12]*r[11]+t[13]*r[16],e[12]=t[10]*r[2]+t[11]*r[7]+t[12]*r[12]+t[13]*r[17],e[13]=t[10]*r[3]+t[11]*r[8]+t[12]*r[13]+t[13]*r[18],e[14]=t[10]*r[4]+t[11]*r[9]+t[12]*r[14]+t[13]*r[19]+t[14],e[15]=t[15]*r[0]+t[16]*r[5]+t[17]*r[10]+t[18]*r[15],e[16]=t[15]*r[1]+t[16]*r[6]+t[17]*r[11]+t[18]*r[16],e[17]=t[15]*r[2]+t[16]*r[7]+t[17]*r[12]+t[18]*r[17],e[18]=t[15]*r[3]+t[16]*r[8]+t[17]*r[13]+t[18]*r[18],e[19]=t[15]*r[4]+t[16]*r[9]+t[17]*r[14]+t[18]*r[19]+t[19],e},e.prototype._colorMatrix=function(e){var t=new Float32Array(e);return t[4]/=255,t[9]/=255,t[14]/=255,t[19]/=255,t},e.prototype.brightness=function(e,t){var r=[e,0,0,0,0,0,e,0,0,0,0,0,e,0,0,0,0,0,1,0];this._loadMatrix(r,t)},e.prototype.greyscale=function(e,t){var r=[e,e,e,0,0,e,e,e,0,0,e,e,e,0,0,0,0,0,1,0];this._loadMatrix(r,t)},e.prototype.blackAndWhite=function(e){this._loadMatrix([.3,.6,.1,0,0,.3,.6,.1,0,0,.3,.6,.1,0,0,0,0,0,1,0],e)},e.prototype.hue=function(e,t){e=(e||0)/180*Math.PI;var r=Math.cos(e),i=Math.sin(e),n=(0,Math.sqrt)(1/3),o=[r+1/3*(1-r),1/3*(1-r)-n*i,1/3*(1-r)+n*i,0,0,1/3*(1-r)+n*i,r+1/3*(1-r),1/3*(1-r)-n*i,0,0,1/3*(1-r)-n*i,1/3*(1-r)+n*i,r+1/3*(1-r),0,0,0,0,0,1,0];this._loadMatrix(o,t)},e.prototype.contrast=function(e,t){var r=(e||0)+1,i=-.5*(r-1),n=[r,0,0,0,i,0,r,0,0,i,0,0,r,0,i,0,0,0,1,0];this._loadMatrix(n,t)},e.prototype.saturate=function(e,t){void 0===e&&(e=0);var r=2*e/3+1,i=-.5*(r-1),n=[r,i,i,0,0,i,r,i,0,0,i,i,r,0,0,0,0,0,1,0];this._loadMatrix(n,t)},e.prototype.desaturate=function(){this.saturate(-1)},e.prototype.negative=function(e){this._loadMatrix([-1,0,0,1,0,0,-1,0,1,0,0,0,-1,1,0,0,0,0,1,0],e)},e.prototype.sepia=function(e){this._loadMatrix([.393,.7689999,.18899999,0,0,.349,.6859999,.16799999,0,0,.272,.5339999,.13099999,0,0,0,0,0,1,0],e)},e.prototype.technicolor=function(e){this._loadMatrix([1.9125277891456083,-.8545344976951645,-.09155508482755585,0,11.793603434377337,-.3087833385928097,1.7658908555458428,-.10601743074722245,0,-70.35205161461398,-.231103377548616,-.7501899197440212,1.847597816108189,0,30.950940869491138,0,0,0,1,0],e)},e.prototype.polaroid=function(e){this._loadMatrix([1.438,-.062,-.062,0,0,-.122,1.378,-.122,0,0,-.016,-.016,1.483,0,0,0,0,0,1,0],e)},e.prototype.toBGR=function(e){this._loadMatrix([0,0,1,0,0,0,1,0,0,0,1,0,0,0,0,0,0,0,1,0],e)},e.prototype.kodachrome=function(e){this._loadMatrix([1.1285582396593525,-.3967382283601348,-.03992559172921793,0,63.72958762196502,-.16404339962244616,1.0835251566291304,-.05498805115633132,0,24.732407896706203,-.16786010706155763,-.5603416277695248,1.6014850761964943,0,35.62982807460946,0,0,0,1,0],e)},e.prototype.browni=function(e){this._loadMatrix([.5997023498159715,.34553243048391263,-.2708298674538042,0,47.43192855600873,-.037703249837783157,.8609577587992641,.15059552388459913,0,-36.96841498319127,.24113635128153335,-.07441037908422492,.44972182064877153,0,-7.562075277591283,0,0,0,1,0],e)},e.prototype.vintage=function(e){this._loadMatrix([.6279345635605994,.3202183420819367,-.03965408211312453,0,9.651285835294123,.02578397704808868,.6441188644374771,.03259127616149294,0,7.462829176470591,.0466055556782719,-.0851232987247891,.5241648018700465,0,5.159190588235296,0,0,0,1,0],e)},e.prototype.colorTone=function(e,t,r,i,n){var o=((r=r||16770432)>>16&255)/255,a=(r>>8&255)/255,s=(255&r)/255,l=((i=i||3375104)>>16&255)/255,u=(i>>8&255)/255,h=(255&i)/255,c=[.3,.59,.11,0,0,o,a,s,e=e||.2,0,l,u,h,t=t||.15,0,o-l,a-u,s-h,0,0];this._loadMatrix(c,n)},e.prototype.night=function(e,t){var r=[-2*(e=e||.1),-e,0,0,0,-e,0,e,0,0,0,e,2*e,0,0,0,0,0,1,0];this._loadMatrix(r,t)},e.prototype.predator=function(e,t){var r=[11.224130630493164*e,-4.794486999511719*e,-2.8746118545532227*e,0*e,.40342438220977783*e,-3.6330697536468506*e,9.193157196044922*e,-2.951810836791992*e,0*e,-1.316135048866272*e,-3.2184197902679443*e,-4.2375030517578125*e,7.476448059082031*e,0*e,.8044459223747253*e,0,0,0,1,0];this._loadMatrix(r,t)},e.prototype.lsd=function(e){this._loadMatrix([2,-.4,.5,0,0,-.5,2,-.4,0,0,-.4,-.5,3,0,0,0,0,0,1,0],e)},e.prototype.reset=function(){this._loadMatrix([1,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,1,0],!1)},Object.defineProperty(e.prototype,"matrix",{get:function(){return this.uniforms.m},set:function(e){this.uniforms.m=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"alpha",{get:function(){return this.uniforms.uAlpha},set:function(e){this.uniforms.uAlpha=e},enumerable:!1,configurable:!0}),e}(Hi);Bs.prototype.grayscale=Bs.prototype.greyscale;var Us=function(e,t){return(Us=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])})(e,t)};var Xs=function(n){function e(e,t){var r=this,i=new Bt;return e.renderable=!1,(r=n.call(this,"attribute vec2 aVertexPosition;\n\nuniform mat3 projectionMatrix;\nuniform mat3 filterMatrix;\n\nvarying vec2 vTextureCoord;\nvarying vec2 vFilterCoord;\n\nuniform vec4 inputSize;\nuniform vec4 outputFrame;\n\nvec4 filterVertexPosition( void )\n{\n vec2 position = aVertexPosition * max(outputFrame.zw, vec2(0.)) + outputFrame.xy;\n\n return vec4((projectionMatrix * vec3(position, 1.0)).xy, 0.0, 1.0);\n}\n\nvec2 filterTextureCoord( void )\n{\n return aVertexPosition * (outputFrame.zw * inputSize.zw);\n}\n\nvoid main(void)\n{\n\tgl_Position = filterVertexPosition();\n\tvTextureCoord = filterTextureCoord();\n\tvFilterCoord = ( filterMatrix * vec3( vTextureCoord, 1.0) ).xy;\n}\n","varying vec2 vFilterCoord;\nvarying vec2 vTextureCoord;\n\nuniform vec2 scale;\nuniform mat2 rotation;\nuniform sampler2D uSampler;\nuniform sampler2D mapSampler;\n\nuniform highp vec4 inputSize;\nuniform vec4 inputClamp;\n\nvoid main(void)\n{\n vec4 map = texture2D(mapSampler, vFilterCoord);\n\n map -= 0.5;\n map.xy = scale * inputSize.zw * (rotation * map.xy);\n\n gl_FragColor = texture2D(uSampler, clamp(vec2(vTextureCoord.x + map.x, vTextureCoord.y + map.y), inputClamp.xy, inputClamp.zw));\n}\n",{mapSampler:e._texture,filterMatrix:i,scale:{x:1,y:1},rotation:new Float32Array([1,0,0,1])})||this).maskSprite=e,r.maskMatrix=i,null==t&&(t=20),r.scale=new jt(t,t),r}return function(e,t){function r(){this.constructor=e}Us(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)}(e,n),e.prototype.apply=function(e,t,r,i){this.uniforms.filterMatrix=e.calculateSpriteMatrix(this.maskMatrix,this.maskSprite),this.uniforms.scale.x=this.scale.x,this.uniforms.scale.y=this.scale.y;var n=this.maskSprite.worldTransform,o=Math.sqrt(n.a*n.a+n.b*n.b),a=Math.sqrt(n.c*n.c+n.d*n.d);0!==o&&0!==a&&(this.uniforms.rotation[0]=n.a/o,this.uniforms.rotation[1]=n.b/o,this.uniforms.rotation[2]=n.c/a,this.uniforms.rotation[3]=n.d/a),e.applyFilter(this,t,r,i)},Object.defineProperty(e.prototype,"map",{get:function(){return this.uniforms.mapSampler},set:function(e){this.uniforms.mapSampler=e},enumerable:!1,configurable:!0}),e}(Hi),Hs=function(e,t){return(Hs=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])})(e,t)};var Gs=function(e){function t(){return e.call(this,"\nattribute vec2 aVertexPosition;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 v_rgbNW;\nvarying vec2 v_rgbNE;\nvarying vec2 v_rgbSW;\nvarying vec2 v_rgbSE;\nvarying vec2 v_rgbM;\n\nvarying vec2 vFragCoord;\n\nuniform vec4 inputPixel;\nuniform vec4 outputFrame;\n\nvec4 filterVertexPosition( void )\n{\n vec2 position = aVertexPosition * max(outputFrame.zw, vec2(0.)) + outputFrame.xy;\n\n return vec4((projectionMatrix * vec3(position, 1.0)).xy, 0.0, 1.0);\n}\n\nvoid texcoords(vec2 fragCoord, vec2 inverseVP,\n out vec2 v_rgbNW, out vec2 v_rgbNE,\n out vec2 v_rgbSW, out vec2 v_rgbSE,\n out vec2 v_rgbM) {\n v_rgbNW = (fragCoord + vec2(-1.0, -1.0)) * inverseVP;\n v_rgbNE = (fragCoord + vec2(1.0, -1.0)) * inverseVP;\n v_rgbSW = (fragCoord + vec2(-1.0, 1.0)) * inverseVP;\n v_rgbSE = (fragCoord + vec2(1.0, 1.0)) * inverseVP;\n v_rgbM = vec2(fragCoord * inverseVP);\n}\n\nvoid main(void) {\n\n gl_Position = filterVertexPosition();\n\n vFragCoord = aVertexPosition * outputFrame.zw;\n\n texcoords(vFragCoord, inputPixel.zw, v_rgbNW, v_rgbNE, v_rgbSW, v_rgbSE, v_rgbM);\n}\n",'varying vec2 v_rgbNW;\nvarying vec2 v_rgbNE;\nvarying vec2 v_rgbSW;\nvarying vec2 v_rgbSE;\nvarying vec2 v_rgbM;\n\nvarying vec2 vFragCoord;\nuniform sampler2D uSampler;\nuniform highp vec4 inputPixel;\n\n\n/**\n Basic FXAA implementation based on the code on geeks3d.com with the\n modification that the texture2DLod stuff was removed since it\'s\n unsupported by WebGL.\n\n --\n\n From:\n https://github.com/mitsuhiko/webgl-meincraft\n\n Copyright (c) 2011 by Armin Ronacher.\n\n Some rights reserved.\n\n Redistribution and use in source and binary forms, with or without\n modification, are permitted provided that the following conditions are\n met:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n\n * Redistributions in binary form must reproduce the above\n copyright notice, this list of conditions and the following\n disclaimer in the documentation and/or other materials provided\n with the distribution.\n\n * The names of the contributors may not be used to endorse or\n promote products derived from this software without specific\n prior written permission.\n\n THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n#ifndef FXAA_REDUCE_MIN\n#define FXAA_REDUCE_MIN (1.0/ 128.0)\n#endif\n#ifndef FXAA_REDUCE_MUL\n#define FXAA_REDUCE_MUL (1.0 / 8.0)\n#endif\n#ifndef FXAA_SPAN_MAX\n#define FXAA_SPAN_MAX 8.0\n#endif\n\n//optimized version for mobile, where dependent\n//texture reads can be a bottleneck\nvec4 fxaa(sampler2D tex, vec2 fragCoord, vec2 inverseVP,\n vec2 v_rgbNW, vec2 v_rgbNE,\n vec2 v_rgbSW, vec2 v_rgbSE,\n vec2 v_rgbM) {\n vec4 color;\n vec3 rgbNW = texture2D(tex, v_rgbNW).xyz;\n vec3 rgbNE = texture2D(tex, v_rgbNE).xyz;\n vec3 rgbSW = texture2D(tex, v_rgbSW).xyz;\n vec3 rgbSE = texture2D(tex, v_rgbSE).xyz;\n vec4 texColor = texture2D(tex, v_rgbM);\n vec3 rgbM = texColor.xyz;\n vec3 luma = vec3(0.299, 0.587, 0.114);\n float lumaNW = dot(rgbNW, luma);\n float lumaNE = dot(rgbNE, luma);\n float lumaSW = dot(rgbSW, luma);\n float lumaSE = dot(rgbSE, luma);\n float lumaM = dot(rgbM, luma);\n float lumaMin = min(lumaM, min(min(lumaNW, lumaNE), min(lumaSW, lumaSE)));\n float lumaMax = max(lumaM, max(max(lumaNW, lumaNE), max(lumaSW, lumaSE)));\n\n mediump vec2 dir;\n dir.x = -((lumaNW + lumaNE) - (lumaSW + lumaSE));\n dir.y = ((lumaNW + lumaSW) - (lumaNE + lumaSE));\n\n float dirReduce = max((lumaNW + lumaNE + lumaSW + lumaSE) *\n (0.25 * FXAA_REDUCE_MUL), FXAA_REDUCE_MIN);\n\n float rcpDirMin = 1.0 / (min(abs(dir.x), abs(dir.y)) + dirReduce);\n dir = min(vec2(FXAA_SPAN_MAX, FXAA_SPAN_MAX),\n max(vec2(-FXAA_SPAN_MAX, -FXAA_SPAN_MAX),\n dir * rcpDirMin)) * inverseVP;\n\n vec3 rgbA = 0.5 * (\n texture2D(tex, fragCoord * inverseVP + dir * (1.0 / 3.0 - 0.5)).xyz +\n texture2D(tex, fragCoord * inverseVP + dir * (2.0 / 3.0 - 0.5)).xyz);\n vec3 rgbB = rgbA * 0.5 + 0.25 * (\n texture2D(tex, fragCoord * inverseVP + dir * -0.5).xyz +\n texture2D(tex, fragCoord * inverseVP + dir * 0.5).xyz);\n\n float lumaB = dot(rgbB, luma);\n if ((lumaB < lumaMin) || (lumaB > lumaMax))\n color = vec4(rgbA, texColor.a);\n else\n color = vec4(rgbB, texColor.a);\n return color;\n}\n\nvoid main() {\n\n vec4 color;\n\n color = fxaa(uSampler, vFragCoord, inputPixel.zw, v_rgbNW, v_rgbNE, v_rgbSW, v_rgbSE, v_rgbM);\n\n gl_FragColor = color;\n}\n')||this}return function(e,t){function r(){this.constructor=e}Hs(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)}(t,e),t}(Hi),Ws=function(e,t){return(Ws=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])})(e,t)};var qs=function(i){function e(e,t){void 0===e&&(e=.5),void 0===t&&(t=Math.random());var r=i.call(this,_n,"precision highp float;\n\nvarying vec2 vTextureCoord;\nvarying vec4 vColor;\n\nuniform float uNoise;\nuniform float uSeed;\nuniform sampler2D uSampler;\n\nfloat rand(vec2 co)\n{\n return fract(sin(dot(co.xy, vec2(12.9898, 78.233))) * 43758.5453);\n}\n\nvoid main()\n{\n vec4 color = texture2D(uSampler, vTextureCoord);\n float randomValue = rand(gl_FragCoord.xy * uSeed);\n float diff = (randomValue - 0.5) * uNoise;\n\n // Un-premultiply alpha before applying the color matrix. See issue #3539.\n if (color.a > 0.0) {\n color.rgb /= color.a;\n }\n\n color.r += diff;\n color.g += diff;\n color.b += diff;\n\n // Premultiply alpha again.\n color.rgb *= color.a;\n\n gl_FragColor = color;\n}\n",{uNoise:0,uSeed:0})||this;return r.noise=e,r.seed=t,r}return function(e,t){function r(){this.constructor=e}Ws(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)}(e,i),Object.defineProperty(e.prototype,"noise",{get:function(){return this.uniforms.uNoise},set:function(e){this.uniforms.uNoise=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"seed",{get:function(){return this.uniforms.uSeed},set:function(e){this.uniforms.uSeed=e},enumerable:!1,configurable:!0}),e}(Hi),Vs=new Bt;$t.prototype._cacheAsBitmap=!1,$t.prototype._cacheData=null;var Ys=function(){this.textureCacheId=null,this.originalRender=null,this.originalRenderCanvas=null,this.originalCalculateBounds=null,this.originalGetLocalBounds=null,this.originalUpdateTransform=null,this.originalDestroy=null,this.originalMask=null,this.originalFilterArea=null,this.originalContainsPoint=null,this.sprite=null};Object.defineProperties($t.prototype,{cacheAsBitmap:{get:function(){return this._cacheAsBitmap},set:function(e){var t;this._cacheAsBitmap!==e&&((this._cacheAsBitmap=e)?(this._cacheData||(this._cacheData=new Ys),(t=this._cacheData).originalRender=this.render,t.originalRenderCanvas=this.renderCanvas,t.originalUpdateTransform=this.updateTransform,t.originalCalculateBounds=this.calculateBounds,t.originalGetLocalBounds=this.getLocalBounds,t.originalDestroy=this.destroy,t.originalContainsPoint=this.containsPoint,t.originalMask=this._mask,t.originalFilterArea=this.filterArea,this.render=this._renderCached,this.renderCanvas=this._renderCachedCanvas,this.destroy=this._cacheAsBitmapDestroy):((t=this._cacheData).sprite&&this._destroyCachedDisplayObject(),this.render=t.originalRender,this.renderCanvas=t.originalRenderCanvas,this.calculateBounds=t.originalCalculateBounds,this.getLocalBounds=t.originalGetLocalBounds,this.destroy=t.originalDestroy,this.updateTransform=t.originalUpdateTransform,this.containsPoint=t.originalContainsPoint,this._mask=t.originalMask,this.filterArea=t.originalFilterArea))}}}),$t.prototype._renderCached=function(e){!this.visible||this.worldAlpha<=0||!this.renderable||(this._initCachedDisplayObject(e),this._cacheData.sprite.transform._worldID=this.transform._worldID,this._cacheData.sprite.worldAlpha=this.worldAlpha,this._cacheData.sprite._render(e))},$t.prototype._initCachedDisplayObject=function(e){if(!this._cacheData||!this._cacheData.sprite){var t=this.alpha;this.alpha=1,e.batch.flush();var r=this.getLocalBounds(null,!0).clone();if(this.filters){var i=this.filters[0].padding;r.pad(i)}r.ceil(C.RESOLUTION);var n=e.renderTexture.current,o=e.renderTexture.sourceFrame.clone(),a=e.projection.transform,s=Gr.create({width:r.width,height:r.height}),l="cacheAsBitmap_"+gt();this._cacheData.textureCacheId=l,Pr.addToCache(s.baseTexture,l),Xr.addToCache(s,l);var u=this.transform.localTransform.copyTo(Vs).invert().translate(-r.x,-r.y);this.render=this._cacheData.originalRender,e.render(this,s,!0,u,!1),e.projection.transform=a,e.renderTexture.bind(n,o),this.render=this._renderCached,this.updateTransform=this.displayObjectUpdateTransform,this.calculateBounds=this._calculateCachedBounds,this.getLocalBounds=this._getCachedLocalBounds,this._mask=null,this.filterArea=null;var h=new Zo(s);h.transform.worldTransform=this.transform.worldTransform,h.anchor.x=-r.x/r.width,h.anchor.y=-r.y/r.height,h.alpha=t,h._bounds=this._bounds,this._cacheData.sprite=h,this.transform._parentID=-1,this.parent?this.updateTransform():(this.enableTempParent(),this.updateTransform(),this.disableTempParent(null)),this.containsPoint=h.containsPoint.bind(h)}},$t.prototype._renderCachedCanvas=function(e){!this.visible||this.worldAlpha<=0||!this.renderable||(this._initCachedDisplayObjectCanvas(e),this._cacheData.sprite.worldAlpha=this.worldAlpha,this._cacheData.sprite._renderCanvas(e))},$t.prototype._initCachedDisplayObjectCanvas=function(e){if(!this._cacheData||!this._cacheData.sprite){var t=this.getLocalBounds(null,!0),r=this.alpha;this.alpha=1;var i=e.context,n=e._projTransform;t.ceil(C.RESOLUTION);var o=Gr.create({width:t.width,height:t.height}),a="cacheAsBitmap_"+gt();this._cacheData.textureCacheId=a,Pr.addToCache(o.baseTexture,a),Xr.addToCache(o,a);var s=Vs;this.transform.localTransform.copyTo(s),s.invert(),s.tx-=t.x,s.ty-=t.y,this.renderCanvas=this._cacheData.originalRenderCanvas,e.render(this,o,!0,s,!1),e.context=i,e._projTransform=n,this.renderCanvas=this._renderCachedCanvas,this.updateTransform=this.displayObjectUpdateTransform,this.calculateBounds=this._calculateCachedBounds,this.getLocalBounds=this._getCachedLocalBounds,this._mask=null,this.filterArea=null;var l=new Zo(o);l.transform.worldTransform=this.transform.worldTransform,l.anchor.x=-t.x/t.width,l.anchor.y=-t.y/t.height,l.alpha=r,l._bounds=this._bounds,this._cacheData.sprite=l,this.transform._parentID=-1,this.parent?this.updateTransform():(this.parent=e._tempDisplayObjectParent,this.updateTransform(),this.parent=null),this.containsPoint=l.containsPoint.bind(l)}},$t.prototype._calculateCachedBounds=function(){this._bounds.clear(),this._cacheData.sprite.transform._worldID=this.transform._worldID,this._cacheData.sprite._calculateBounds(),this._bounds.updateID=this._boundsID},$t.prototype._getCachedLocalBounds=function(){return this._cacheData.sprite.getLocalBounds(null)},$t.prototype._destroyCachedDisplayObject=function(){this._cacheData.sprite._texture.destroy(!0),this._cacheData.sprite=null,Pr.removeFromCache(this._cacheData.textureCacheId),Xr.removeFromCache(this._cacheData.textureCacheId),this._cacheData.textureCacheId=null},$t.prototype._cacheAsBitmapDestroy=function(e){this.cacheAsBitmap=!1,this.destroy(e)},$t.prototype.name=null,rr.prototype.getChildByName=function(e,t){for(var r=0,i=this.children.length;re?1:this._width/e,r=this._topHeight+this._bottomHeight,i=this._height>r?1:this._height/r;return Math.min(t,i)},Object.defineProperty(e.prototype,"width",{get:function(){return this._width},set:function(e){this._width=e,this._refresh()},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"height",{get:function(){return this._height},set:function(e){this._height=e,this._refresh()},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"leftWidth",{get:function(){return this._leftWidth},set:function(e){this._leftWidth=e,this._refresh()},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"rightWidth",{get:function(){return this._rightWidth},set:function(e){this._rightWidth=e,this._refresh()},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"topHeight",{get:function(){return this._topHeight},set:function(e){this._topHeight=e,this._refresh()},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"bottomHeight",{get:function(){return this._bottomHeight},set:function(e){this._bottomHeight=e,this._refresh()},enumerable:!1,configurable:!0}),e.prototype._refresh=function(){var e=this.texture,t=this.geometry.buffers[1].data;this._origWidth=e.orig.width,this._origHeight=e.orig.height;var r=1/this._origWidth,i=1/this._origHeight;t[0]=t[8]=t[16]=t[24]=0,t[1]=t[3]=t[5]=t[7]=0,t[6]=t[14]=t[22]=t[30]=1,t[25]=t[27]=t[29]=t[31]=1,t[2]=t[10]=t[18]=t[26]=r*this._leftWidth,t[4]=t[12]=t[20]=t[28]=1-r*this._rightWidth,t[9]=t[11]=t[13]=t[15]=i*this._topHeight,t[17]=t[19]=t[21]=t[23]=1-i*this._bottomHeight,this.updateHorizontalVertices(),this.updateVerticalVertices(),this.geometry.buffers[0].update(),this.geometry.buffers[1].update()},e}(il),al=function(e,t){return(al=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])})(e,t)};var sl=function(i){function n(e,t){void 0===t&&(t=!0);var r=i.call(this,e[0]instanceof Xr?e[0]:e[0].texture)||this;return r._textures=null,r._durations=null,r._autoUpdate=t,r._isConnectedToTicker=!1,r.animationSpeed=1,r.loop=!0,r.updateAnchor=!1,r.onComplete=null,r.onFrameChange=null,r.onLoop=null,r._currentTime=0,r._playing=!1,r._previousFrame=null,r.textures=e,r}return function(e,t){function r(){this.constructor=e}al(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)}(n,i),n.prototype.stop=function(){this._playing&&(this._playing=!1,this._autoUpdate&&this._isConnectedToTicker&&(sr.shared.remove(this.update,this),this._isConnectedToTicker=!1))},n.prototype.play=function(){this._playing||(this._playing=!0,this._autoUpdate&&!this._isConnectedToTicker&&(sr.shared.add(this.update,this,K.UPDATE_PRIORITY.HIGH),this._isConnectedToTicker=!0))},n.prototype.gotoAndStop=function(e){this.stop();var t=this.currentFrame;this._currentTime=e,t!==this.currentFrame&&this.updateTexture()},n.prototype.gotoAndPlay=function(e){var t=this.currentFrame;this._currentTime=e,t!==this.currentFrame&&this.updateTexture(),this.play()},n.prototype.update=function(e){var t=this.animationSpeed*e,r=this.currentFrame;if(null!==this._durations){var i=this._currentTime%1*this._durations[this.currentFrame];for(i+=t/60*1e3;i<0;)this._currentTime--,i+=this._durations[this.currentFrame];var n=Math.sign(this.animationSpeed*e);for(this._currentTime=Math.floor(this._currentTime);i>=this._durations[this.currentFrame];)i-=this._durations[this.currentFrame]*n,this._currentTime+=n;this._currentTime+=i/this._durations[this.currentFrame]}else this._currentTime+=t;this._currentTime<0&&!this.loop?(this.gotoAndStop(0),this.onComplete&&this.onComplete()):this._currentTime>=this._textures.length&&!this.loop?(this.gotoAndStop(this._textures.length-1),this.onComplete&&this.onComplete()):r!==this.currentFrame&&(this.loop&&this.onLoop&&(0r&&this.onLoop()),this.updateTexture())},n.prototype.updateTexture=function(){var e=this.currentFrame;this._previousFrame!==e&&(this._previousFrame=e,this._texture=this._textures[e],this._textureID=-1,this._textureTrimmedID=-1,this._cachedTint=16777215,this.uvs=this._texture._uvs.uvsFloat32,this.updateAnchor&&this._anchor.copyFrom(this._texture.defaultAnchor),this.onFrameChange&&this.onFrameChange(this.currentFrame))},n.prototype.destroy=function(e){this.stop(),i.prototype.destroy.call(this,e),this.onComplete=null,this.onFrameChange=null,this.onLoop=null},n.fromFrames=function(e){for(var t=[],r=0;r 0) var gc = undefined");else{if(!ba&&!ca)throw"Unknown runtime environment. Where are we?";e.read=function(e){var t=new XMLHttpRequest;return t.open("GET",e,!1),t.send(null),t.responseText},"undefined"!=typeof arguments&&(e.arguments=arguments),"undefined"!=typeof console?(e.print||(e.print=function(e){console.log(e)}),e.printErr||(e.printErr=function(e){console.log(e)})):e.print||(e.print=function(){}),ca&&(e.load=importScripts),void 0===e.setWindowTitle&&(e.setWindowTitle=function(e){document.title=e})}function ha(e){eval.call(null,e)}for(k in!e.load&&e.read&&(e.load=function(t){ha(e.read(t))}),e.print||(e.print=function(){}),e.printErr||(e.printErr=e.print),e.arguments||(e.arguments=[]),e.thisProgram||(e.thisProgram="./this.program"),e.print=e.print,e.W=e.printErr,e.preRun=[],e.postRun=[],aa)aa.hasOwnProperty(k)&&(e[k]=aa[k]);var n={rb:function(e){ka=e},fb:function(){return ka},ua:function(){return m},ba:function(e){m=e},Ka:function(e){switch(e){case"i1":case"i8":return 1;case"i16":return 2;case"i32":return 4;case"i64":return 8;case"float":return 4;case"double":return 8;default:return"*"===e[e.length-1]?n.J:"i"===e[0]?(assert(0==(e=parseInt(e.substr(1)))%8),e/8):0}},eb:function(e){return Math.max(n.Ka(e),n.J)},ud:16,Qd:function(e,t){return"double"===t||"i64"===t?7&e&&(assert(4==(7&e)),e+=4):assert(0==(3&e)),e},Ed:function(e,t,r){return r||"i64"!=e&&"double"!=e?e?Math.min(t||(e?n.eb(e):0),n.J):Math.min(t,8):8},L:function(t,r,i){return i&&i.length?(i.splice||(i=Array.prototype.slice.call(i)),i.splice(0,0,r),e["dynCall_"+t].apply(null,i)):e["dynCall_"+t].call(null,r)},Z:[],Xa:function(e){for(var t=0;t>>0)+4294967296*+(t>>>0):+(e>>>0)+4294967296*+(0|t)},Ua:8,J:4,vd:0};e.Runtime=n,n.addFunction=n.Xa,n.removeFunction=n.nb;var na=!1,oa,pa,ka,ra,sa;function assert(e,t){e||x("Assertion failed: "+t)}function qa(a){var b=e["_"+a];if(!b)try{b=eval("_"+a)}catch(e){}return assert(b,"Cannot call unknown function "+a+" (perhaps LLVM optimizations or closure removed it?)"),b}function wa(e,t,r){switch("*"===(r=r||"i8").charAt(r.length-1)&&(r="i32"),r){case"i1":case"i8":y[e>>0]=t;break;case"i16":z[e>>1]=t;break;case"i32":C[e>>2]=t;break;case"i64":pa=[t>>>0,(oa=t,1<=+xa(oa)?0>>0:~~+Aa((oa-+(~~oa>>>0))/4294967296)>>>0:0)],C[e>>2]=pa[0],C[e+4>>2]=pa[1];break;case"float":Ba[e>>2]=t;break;case"double":Ca[e>>3]=t;break;default:x("invalid type for setValue: "+r)}}function Da(e,t){switch("*"===(t=t||"i8").charAt(t.length-1)&&(t="i32"),t){case"i1":case"i8":return y[e>>0];case"i16":return z[e>>1];case"i32":case"i64":return C[e>>2];case"float":return Ba[e>>2];case"double":return Ca[e>>3];default:x("invalid type for setValue: "+t)}return null}function D(e,t,r,i){var o,a;a="number"==typeof e?(o=!0,e):(o=!1,e.length);var s,l,u="string"==typeof t?t:null;if(r=4==r?i:[Ea,n.aa,n.Ra,n.R][void 0===r?2:r](Math.max(a,u?1:t.length)),o){for(assert(0==(3&(i=r))),e=r+(-4&a);i>2]=0;for(e=r+a;i>0]=0;return r}if("i8"===u)return e.subarray||e.slice?E.set(e,r):E.set(new Uint8Array(e),r),r;for(i=0;i>0],0!=i||r)&&(o++,!r||o!=r););if(r||(r=o),i="",n<128){for(;0>10,56320|1023&r)))):s+=String.fromCharCode(r)}}function Ka(e,t,r,i){if(!(0>6}else{if(a<=65535){if(i<=r+2)break;t[r++]=224|a>>12}else{if(a<=2097151){if(i<=r+3)break;t[r++]=240|a>>18}else{if(a<=67108863){if(i<=r+4)break;t[r++]=248|a>>24}else{if(i<=r+5)break;t[r++]=252|a>>30,t[r++]=128|a>>24&63}t[r++]=128|a>>18&63}t[r++]=128|a>>12&63}t[r++]=128|a>>6&63}t[r++]=128|63&a}}return t[r]=0,r-n}function La(e){for(var t=0,r=0;r"):o=n;e:for(;c>0];if(!r)return t;t+=String.fromCharCode(r)}},e.stringToAscii=function(e,t){return Ia(e,t,!1)},e.UTF8ArrayToString=Ja,e.UTF8ToString=function(e){return Ja(E,e)},e.stringToUTF8Array=Ka,e.stringToUTF8=function(e,t,r){return Ka(e,E,t,r)},e.lengthBytesUTF8=La,e.UTF16ToString=function(e){for(var t=0,r="";;){var i=z[e+2*t>>1];if(0==i)return r;++t,r+=String.fromCharCode(i)}},e.stringToUTF16=function(e,t,r){if(void 0===r&&(r=2147483647),r<2)return 0;var i=t;r=(r-=2)<2*e.length?r/2:e.length;for(var n=0;n>1]=e.charCodeAt(n),t+=2;return z[t>>1]=0,t-i},e.lengthBytesUTF16=function(e){return 2*e.length},e.UTF32ToString=function(e){for(var t=0,r="";;){var i=C[e+4*t>>2];if(0==i)return r;++t,65536<=i?(i-=65536,r+=String.fromCharCode(55296|i>>10,56320|1023&i)):r+=String.fromCharCode(i)}},e.stringToUTF32=function(e,t,r){if(void 0===r&&(r=2147483647),r<4)return 0;var i=t;r=i+r-4;for(var n=0;n>2]=o,r<(t+=4)+4)break}return C[t>>2]=0,t-i},e.lengthBytesUTF32=function(e){for(var t=0,r=0;r>0]=e[r],r+=1}function ta(e,t){for(var r=0;r>0]=e[r]}function Ia(e,t,r){for(var i=0;i>0]=e.charCodeAt(i);r||(y[t>>0]=0)}e.addOnPreRun=fb,e.addOnInit=function(e){cb.unshift(e)},e.addOnPreMain=function(e){db.unshift(e)},e.addOnExit=function(e){H.unshift(e)},e.addOnPostRun=gb,e.intArrayFromString=hb,e.intArrayToString=function(e){for(var t=[],r=0;r>>16)*i+r*(t>>>16)<<16)|0}),Math.Jd=Math.imul,Math.clz32||(Math.clz32=function(e){e>>>=0;for(var t=0;t<32;t++)if(e&1<<31-t)return t;return 32}),Math.Ad=Math.clz32;var xa=Math.abs,Aa=Math.ceil,za=Math.floor,ya=Math.min,I=0,ib=null,jb=null;function kb(){I++,e.monitorRunDependencies&&e.monitorRunDependencies(I)}function lb(){if(I--,e.monitorRunDependencies&&e.monitorRunDependencies(I),0==I&&(null!==ib&&(clearInterval(ib),ib=null),jb)){var t=jb;jb=null,t()}}e.addRunDependency=kb,e.removeRunDependency=lb,e.preloadedImages={},e.preloadedAudios={},Ta=8,la=Ta+5888,cb.push(),D([124,0,0,0,98,7,0,0,124,0,0,0,111,7,0,0,164,0,0,0,124,7,0,0,16,0,0,0,0,0,0,0,164,0,0,0,157,7,0,0,24,0,0,0,0,0,0,0,164,0,0,0,227,7,0,0,24,0,0,0,0,0,0,0,164,0,0,0,191,7,0,0,56,0,0,0,0,0,0,0,164,0,0,0,5,8,0,0,40,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,40,0,0,0,1,0,0,0,2,0,0,0,3,0,0,0,4,0,0,0,1,0,0,0,1,0,0,0,1,0,0,0,1,0,0,0,0,0,0,0,88,0,0,0,1,0,0,0,5,0,0,0,3,0,0,0,4,0,0,0,1,0,0,0,2,0,0,0,2,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,114,9,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,124,1,0,0,236,1,0,0,236,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,255,255,255,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,5,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,0,0,0,4,0,0,0,239,20,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,255,255,255,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,5,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,5,0,0,0,4,0,0,0,231,16,0,0,0,4,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,10,255,255,255,255,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,37,115,40,37,117,41,58,32,65,115,115,101,114,116,105,111,110,32,102,97,105,108,117,114,101,58,32,34,37,115,34,10,0,109,95,115,105,122,101,32,60,61,32,109,95,99,97,112,97,99,105,116,121,0,46,47,99,114,110,95,100,101,99,111,109,112,46,104,0,109,105,110,95,110,101,119,95,99,97,112,97,99,105,116,121,32,60,32,40,48,120,55,70,70,70,48,48,48,48,85,32,47,32,101,108,101,109,101,110,116,95,115,105,122,101,41,0,110,101,119,95,99,97,112,97,99,105,116,121,32,38,38,32,40,110,101,119,95,99,97,112,97,99,105,116,121,32,62,32,109,95,99,97,112,97,99,105,116,121,41,0,110,117,109,95,99,111,100,101,115,91,99,93,0,115,111,114,116,101,100,95,112,111,115,32,60,32,116,111,116,97,108,95,117,115,101,100,95,115,121,109,115,0,112,67,111,100,101,115,105,122,101,115,91,115,121,109,95,105,110,100,101,120,93,32,61,61,32,99,111,100,101,115,105,122,101,0,116,32,60,32,40,49,85,32,60,60,32,116,97,98,108,101,95,98,105,116,115,41,0,109,95,108,111,111,107,117,112,91,116,93,32,61,61,32,99,85,73,78,84,51,50,95,77,65,88,0,99,114,110,100,95,109,97,108,108,111,99,58,32,115,105,122,101,32,116,111,111,32,98,105,103,0,99,114,110,100,95,109,97,108,108,111,99,58,32,111,117,116,32,111,102,32,109,101,109,111,114,121,0,40,40,117,105,110,116,51,50,41,112,95,110,101,119,32,38,32,40,67,82,78,68,95,77,73,78,95,65,76,76,79,67,95,65,76,73,71,78,77,69,78,84,32,45,32,49,41,41,32,61,61,32,48,0,99,114,110,100,95,114,101,97,108,108,111,99,58,32,98,97,100,32,112,116,114,0,99,114,110,100,95,102,114,101,101,58,32,98,97,100,32,112,116,114,0,102,97,108,115,101,0,40,116,111,116,97,108,95,115,121,109,115,32,62,61,32,49,41,32,38,38,32,40,116,111,116,97,108,95,115,121,109,115,32,60,61,32,112,114,101,102,105,120,95,99,111,100,105,110,103,58,58,99,77,97,120,83,117,112,112,111,114,116,101,100,83,121,109,115,41,0,17,18,19,20,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15,16,48,0,110,117,109,95,98,105,116,115,32,60,61,32,51,50,85,0,109,95,98,105,116,95,99,111,117,110,116,32,60,61,32,99,66,105,116,66,117,102,83,105,122,101,0,116,32,33,61,32,99,85,73,78,84,51,50,95,77,65,88,0,109,111,100,101,108,46,109,95,99,111,100,101,95,115,105,122,101,115,91,115,121,109,93,32,61,61,32,108,101,110,0,0,2,3,1,0,2,3,4,5,6,7,1,40,108,101,110,32,62,61,32,49,41,32,38,38,32,40,108,101,110,32,60,61,32,99,77,97,120,69,120,112,101,99,116,101,100,67,111,100,101,83,105,122,101,41,0,105,32,60,32,109,95,115,105,122,101,0,110,101,120,116,95,108,101,118,101,108,95,111,102,115,32,62,32,99,117,114,95,108,101,118,101,108,95,111,102,115,0,1,2,2,3,3,3,3,4,0,0,0,0,0,0,1,1,0,1,0,1,0,0,1,2,1,2,0,0,0,1,0,2,1,0,2,0,0,1,2,3,110,117,109,32,38,38,32,40,110,117,109,32,61,61,32,126,110,117,109,95,99,104,101,99,107,41,0,83,116,57,101,120,99,101,112,116,105,111,110,0,83,116,57,116,121,112,101,95,105,110,102,111,0,78,49,48,95,95,99,120,120,97,98,105,118,49,49,54,95,95,115,104,105,109,95,116,121,112,101,95,105,110,102,111,69,0,78,49,48,95,95,99,120,120,97,98,105,118,49,49,55,95,95,99,108,97,115,115,95,116,121,112,101,95,105,110,102,111,69,0,78,49,48,95,95,99,120,120,97,98,105,118,49,49,57,95,95,112,111,105,110,116,101,114,95,116,121,112,101,95,105,110,102,111,69,0,78,49,48,95,95,99,120,120,97,98,105,118,49,49,55,95,95,112,98,97,115,101,95,116,121,112,101,95,105,110,102,111,69,0,78,49,48,95,95,99,120,120,97,98,105,118,49,50,48,95,95,115,105,95,99,108,97,115,115,95,116,121,112,101,95,105,110,102,111,69,0,112,116,104,114,101,97,100,95,111,110,99,101,32,102,97,105,108,117,114,101,32,105,110,32,95,95,99,120,97,95,103,101,116,95,103,108,111,98,97,108,115,95,102,97,115,116,40,41,0,116,101,114,109,105,110,97,116,101,95,104,97,110,100,108,101,114,32,117,110,101,120,112,101,99,116,101,100,108,121,32,114,101,116,117,114,110,101,100,0,99,97,110,110,111,116,32,99,114,101,97,116,101,32,112,116,104,114,101,97,100,32,107,101,121,32,102,111,114,32,95,95,99,120,97,95,103,101,116,95,103,108,111,98,97,108,115,40,41,0,99,97,110,110,111,116,32,122,101,114,111,32,111,117,116,32,116,104,114,101,97,100,32,118,97,108,117,101,32,102,111,114,32,95,95,99,120,97,95,103,101,116,95,103,108,111,98,97,108,115,40,41,0,116,101,114,109,105,110,97,116,105,110,103,32,119,105,116,104,32,37,115,32,101,120,99,101,112,116,105,111,110,32,111,102,32,116,121,112,101,32,37,115,58,32,37,115,0,116,101,114,109,105,110,97,116,105,110,103,32,119,105,116,104,32,37,115,32,101,120,99,101,112,116,105,111,110,32,111,102,32,116,121,112,101,32,37,115,0,116,101,114,109,105,110,97,116,105,110,103,32,119,105,116,104,32,37,115,32,102,111,114,101,105,103,110,32,101,120,99,101,112,116,105,111,110,0,116,101,114,109,105,110,97,116,105,110,103,0,117,110,99,97,117,103,104,116,0,84,33,34,25,13,1,2,3,17,75,28,12,16,4,11,29,18,30,39,104,110,111,112,113,98,32,5,6,15,19,20,21,26,8,22,7,40,36,23,24,9,10,14,27,31,37,35,131,130,125,38,42,43,60,61,62,63,67,71,74,77,88,89,90,91,92,93,94,95,96,97,99,100,101,102,103,105,106,107,108,114,115,116,121,122,123,124,0,73,108,108,101,103,97,108,32,98,121,116,101,32,115,101,113,117,101,110,99,101,0,68,111,109,97,105,110,32,101,114,114,111,114,0,82,101,115,117,108,116,32,110,111,116,32,114,101,112,114,101,115,101,110,116,97,98,108,101,0,78,111,116,32,97,32,116,116,121,0,80,101,114,109,105,115,115,105,111,110,32,100,101,110,105,101,100,0,79,112,101,114,97,116,105,111,110,32,110,111,116,32,112,101,114,109,105,116,116,101,100,0,78,111,32,115,117,99,104,32,102,105,108,101,32,111,114,32,100,105,114,101,99,116,111,114,121,0,78,111,32,115,117,99,104,32,112,114,111,99,101,115,115,0,70,105,108,101,32,101,120,105,115,116,115,0,86,97,108,117,101,32,116,111,111,32,108,97,114,103,101,32,102,111,114,32,100,97,116,97,32,116,121,112,101,0,78,111,32,115,112,97,99,101,32,108,101,102,116,32,111,110,32,100,101,118,105,99,101,0,79,117,116,32,111,102,32,109,101,109,111,114,121,0,82,101,115,111,117,114,99,101,32,98,117,115,121,0,73,110,116,101,114,114,117,112,116,101,100,32,115,121,115,116,101,109,32,99,97,108,108,0,82,101,115,111,117,114,99,101,32,116,101,109,112,111,114,97,114,105,108,121,32,117,110,97,118,97,105,108,97,98,108,101,0,73,110,118,97,108,105,100,32,115,101,101,107,0,67,114,111,115,115,45,100,101,118,105,99,101,32,108,105,110,107,0,82,101,97,100,45,111,110,108,121,32,102,105,108,101,32,115,121,115,116,101,109,0,68,105,114,101,99,116,111,114,121,32,110,111,116,32,101,109,112,116,121,0,67,111,110,110,101,99,116,105,111,110,32,114,101,115,101,116,32,98,121,32,112,101,101,114,0,79,112,101,114,97,116,105,111,110,32,116,105,109,101,100,32,111,117,116,0,67,111,110,110,101,99,116,105,111,110,32,114,101,102,117,115,101,100,0,72,111,115,116,32,105,115,32,100,111,119,110,0,72,111,115,116,32,105,115,32,117,110,114,101,97,99,104,97,98,108,101,0,65,100,100,114,101,115,115,32,105,110,32,117,115,101,0,66,114,111,107,101,110,32,112,105,112,101,0,73,47,79,32,101,114,114,111,114,0,78,111,32,115,117,99,104,32,100,101,118,105,99,101,32,111,114,32,97,100,100,114,101,115,115,0,66,108,111,99,107,32,100,101,118,105,99,101,32,114,101,113,117,105,114,101,100,0,78,111,32,115,117,99,104,32,100,101,118,105,99,101,0,78,111,116,32,97,32,100,105,114,101,99,116,111,114,121,0,73,115,32,97,32,100,105,114,101,99,116,111,114,121,0,84,101,120,116,32,102,105,108,101,32,98,117,115,121,0,69,120,101,99,32,102,111,114,109,97,116,32,101,114,114,111,114,0,73,110,118,97,108,105,100,32,97,114,103,117,109,101,110,116,0,65,114,103,117,109,101,110,116,32,108,105,115,116,32,116,111,111,32,108,111,110,103,0,83,121,109,98,111,108,105,99,32,108,105,110,107,32,108,111,111,112,0,70,105,108,101,110,97,109,101,32,116,111,111,32,108,111,110,103,0,84,111,111,32,109,97,110,121,32,111,112,101,110,32,102,105,108,101,115,32,105,110,32,115,121,115,116,101,109,0,78,111,32,102,105,108,101,32,100,101,115,99,114,105,112,116,111,114,115,32,97,118,97,105,108,97,98,108,101,0,66,97,100,32,102,105,108,101,32,100,101,115,99,114,105,112,116,111,114,0,78,111,32,99,104,105,108,100,32,112,114,111,99,101,115,115,0,66,97,100,32,97,100,100,114,101,115,115,0,70,105,108,101,32,116,111,111,32,108,97,114,103,101,0,84,111,111,32,109,97,110,121,32,108,105,110,107,115,0,78,111,32,108,111,99,107,115,32,97,118,97,105,108,97,98,108,101,0,82,101,115,111,117,114,99,101,32,100,101,97,100,108,111,99,107,32,119,111,117,108,100,32,111,99,99,117,114,0,83,116,97,116,101,32,110,111,116,32,114,101,99,111,118,101,114,97,98,108,101,0,80,114,101,118,105,111,117,115,32,111,119,110,101,114,32,100,105,101,100,0,79,112,101,114,97,116,105,111,110,32,99,97,110,99,101,108,101,100,0,70,117,110,99,116,105,111,110,32,110,111,116,32,105,109,112,108,101,109,101,110,116,101,100,0,78,111,32,109,101,115,115,97,103,101,32,111,102,32,100,101,115,105,114,101,100,32,116,121,112,101,0,73,100,101,110,116,105,102,105,101,114,32,114,101,109,111,118,101,100,0,68,101,118,105,99,101,32,110,111,116,32,97,32,115,116,114,101,97,109,0,78,111,32,100,97,116,97,32,97,118,97,105,108,97,98,108,101,0,68,101,118,105,99,101,32,116,105,109,101,111,117,116,0,79,117,116,32,111,102,32,115,116,114,101,97,109,115,32,114,101,115,111,117,114,99,101,115,0,76,105,110,107,32,104,97,115,32,98,101,101,110,32,115,101,118,101,114,101,100,0,80,114,111,116,111,99,111,108,32,101,114,114,111,114,0,66,97,100,32,109,101,115,115,97,103,101,0,70,105,108,101,32,100,101,115,99,114,105,112,116,111,114,32,105,110,32,98,97,100,32,115,116,97,116,101,0,78,111,116,32,97,32,115,111,99,107,101,116,0,68,101,115,116,105,110,97,116,105,111,110,32,97,100,100,114,101,115,115,32,114,101,113,117,105,114,101,100,0,77,101,115,115,97,103,101,32,116,111,111,32,108,97,114,103,101,0,80,114,111,116,111,99,111,108,32,119,114,111,110,103,32,116,121,112,101,32,102,111,114,32,115,111,99,107,101,116,0,80,114,111,116,111,99,111,108,32,110,111,116,32,97,118,97,105,108,97,98,108,101,0,80,114,111,116,111,99,111,108,32,110,111,116,32,115,117,112,112,111,114,116,101,100,0,83,111,99,107,101,116,32,116,121,112,101,32,110,111,116,32,115,117,112,112,111,114,116,101,100,0,78,111,116,32,115,117,112,112,111,114,116,101,100,0,80,114,111,116,111,99,111,108,32,102,97,109,105,108,121,32,110,111,116,32,115,117,112,112,111,114,116,101,100,0,65,100,100,114,101,115,115,32,102,97,109,105,108,121,32,110,111,116,32,115,117,112,112,111,114,116,101,100,32,98,121,32,112,114,111,116,111,99,111,108,0,65,100,100,114,101,115,115,32,110,111,116,32,97,118,97,105,108,97,98,108,101,0,78,101,116,119,111,114,107,32,105,115,32,100,111,119,110,0,78,101,116,119,111,114,107,32,117,110,114,101,97,99,104,97,98,108,101,0,67,111,110,110,101,99,116,105,111,110,32,114,101,115,101,116,32,98,121,32,110,101,116,119,111,114,107,0,67,111,110,110,101,99,116,105,111,110,32,97,98,111,114,116,101,100,0,78,111,32,98,117,102,102,101,114,32,115,112,97,99,101,32,97,118,97,105,108,97,98,108,101,0,83,111,99,107,101,116,32,105,115,32,99,111,110,110,101,99,116,101,100,0,83,111,99,107,101,116,32,110,111,116,32,99,111,110,110,101,99,116,101,100,0,67,97,110,110,111,116,32,115,101,110,100,32,97,102,116,101,114,32,115,111,99,107,101,116,32,115,104,117,116,100,111,119,110,0,79,112,101,114,97,116,105,111,110,32,97,108,114,101,97,100,121,32,105,110,32,112,114,111,103,114,101,115,115,0,79,112,101,114,97,116,105,111,110,32,105,110,32,112,114,111,103,114,101,115,115,0,83,116,97,108,101,32,102,105,108,101,32,104,97,110,100,108,101,0,82,101,109,111,116,101,32,73,47,79,32,101,114,114,111,114,0,81,117,111,116,97,32,101,120,99,101,101,100,101,100,0,78,111,32,109,101,100,105,117,109,32,102,111,117,110,100,0,87,114,111,110,103,32,109,101,100,105,117,109,32,116,121,112,101,0,78,111,32,101,114,114,111,114,32,105,110,102,111,114,109,97,116,105,111,110,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,17,0,10,0,17,17,17,0,0,0,0,5,0,0,0,0,0,0,9,0,0,0,0,11,0,0,0,0,0,0,0,0,17,0,15,10,17,17,17,3,10,7,0,1,19,9,11,11,0,0,9,6,11,0,0,11,0,6,17,0,0,0,17,17,17,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,11,0,0,0,0,0,0,0,0,17,0,10,10,17,17,17,0,10,0,0,2,0,9,11,0,0,0,9,0,11,0,0,11,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,12,0,0,0,0,0,0,0,0,0,0,0,12,0,0,0,0,12,0,0,0,0,9,12,0,0,0,0,0,12,0,0,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,14,0,0,0,0,0,0,0,0,0,0,0,13,0,0,0,4,13,0,0,0,0,9,14,0,0,0,0,0,14,0,0,14,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,16,0,0,0,0,0,0,0,0,0,0,0,15,0,0,0,0,15,0,0,0,0,9,16,0,0,0,0,0,16,0,0,16,0,0,18,0,0,0,18,18,18,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,18,0,0,0,18,18,18,0,0,0,0,0,0,9,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,11,0,0,0,0,0,0,0,0,0,0,0,10,0,0,0,0,10,0,0,0,0,9,11,0,0,0,0,0,11,0,0,11,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,12,0,0,0,0,0,0,0,0,0,0,0,12,0,0,0,0,12,0,0,0,0,9,12,0,0,0,0,0,12,0,0,12,0,0,48,49,50,51,52,53,54,55,56,57,65,66,67,68,69,70,45,43,32,32,32,48,88,48,120,0,40,110,117,108,108,41,0,45,48,88,43,48,88,32,48,88,45,48,120,43,48,120,32,48,120,0,105,110,102,0,73,78,70,0,110,97,110,0,78,65,78,0,46,0],"i8",4,n.Ua);var mb=n.ja(D(12,"i8",2),8);function ob(t){return e.___errno_location&&(C[e.___errno_location()>>2]=t),t}assert(0==mb%8),e._i64Subtract=nb;var J={I:1,F:2,ed:3,bc:4,H:5,Aa:6,vb:7,zc:8,ea:9,Jb:10,va:11,qd:11,Ta:12,da:13,Vb:14,Lc:15,fa:16,wa:17,rd:18,ha:19,ya:20,P:21,q:22,uc:23,Sa:24,Q:25,nd:26,Wb:27,Hc:28,ia:29,bd:30,nc:31,Vc:32,Sb:33,Zc:34,Dc:42,Zb:43,Kb:44,ec:45,fc:46,gc:47,mc:48,od:49,xc:50,dc:51,Pb:35,Ac:37,Bb:52,Eb:53,sd:54,vc:55,Fb:56,Gb:57,Qb:35,Hb:59,Jc:60,yc:61,kd:62,Ic:63,Ec:64,Fc:65,ad:66,Bc:67,yb:68,gd:69,Lb:70,Wc:71,pc:72,Tb:73,Db:74,Qc:76,Cb:77,$c:78,hc:79,ic:80,lc:81,kc:82,jc:83,Kc:38,za:39,qc:36,ga:40,Rc:95,Uc:96,Ob:104,wc:105,zb:97,Yc:91,Oc:88,Gc:92,cd:108,Nb:111,wb:98,Mb:103,tc:101,rc:100,ld:110,Xb:112,Yb:113,ac:115,Ab:114,Rb:89,oc:90,Xc:93,dd:94,xb:99,sc:102,cc:106,Mc:107,md:109,pd:87,Ub:122,hd:116,Pc:95,Cc:123,$b:84,Sc:75,Ib:125,Nc:131,Tc:130,jd:86};function pb(e,t){H.push(function(){n.L("vi",e,[t])}),pb.level=H.length}function tb(){return!!tb.p}e._memset=qb,e._bitshift64Lshr=rb,e._bitshift64Shl=sb;var ub=[],vb={};function wb(e,t){wb.p||(wb.p={}),e in wb.p||(n.L("v",t),wb.p[e]=1)}var xb={0:"Success",1:"Not super-user",2:"No such file or directory",3:"No such process",4:"Interrupted system call",5:"I/O error",6:"No such device or address",7:"Arg list too long",8:"Exec format error",9:"Bad file number",10:"No children",11:"No more processes",12:"Not enough core",13:"Permission denied",14:"Bad address",15:"Block device required",16:"Mount device busy",17:"File exists",18:"Cross-device link",19:"No such device",20:"Not a directory",21:"Is a directory",22:"Invalid argument",23:"Too many open files in system",24:"Too many open files",25:"Not a typewriter",26:"Text file busy",27:"File too large",28:"No space left on device",29:"Illegal seek",30:"Read only file system",31:"Too many links",32:"Broken pipe",33:"Math arg out of domain of func",34:"Math result not representable",35:"File locking deadlock error",36:"File or path name too long",37:"No record locks available",38:"Function not implemented",39:"Directory not empty",40:"Too many symbolic links",42:"No message of desired type",43:"Identifier removed",44:"Channel number out of range",45:"Level 2 not synchronized",46:"Level 3 halted",47:"Level 3 reset",48:"Link number out of range",49:"Protocol driver not attached",50:"No CSI structure available",51:"Level 2 halted",52:"Invalid exchange",53:"Invalid request descriptor",54:"Exchange full",55:"No anode",56:"Invalid request code",57:"Invalid slot",59:"Bad font file fmt",60:"Device not a stream",61:"No data (for no delay io)",62:"Timer expired",63:"Out of streams resources",64:"Machine is not on the network",65:"Package not installed",66:"The object is remote",67:"The link has been severed",68:"Advertise error",69:"Srmount error",70:"Communication error on send",71:"Protocol error",72:"Multihop attempted",73:"Cross mount point (not really error)",74:"Trying to read unreadable message",75:"Value too large for defined data type",76:"Given log. name not unique",77:"f.d. invalid for this operation",78:"Remote address changed",79:"Can access a needed shared lib",80:"Accessing a corrupted shared lib",81:".lib section in a.out corrupted",82:"Attempting to link in too many libs",83:"Attempting to exec a shared library",84:"Illegal byte sequence",86:"Streams pipe error",87:"Too many users",88:"Socket operation on non-socket",89:"Destination address required",90:"Message too long",91:"Protocol wrong type for socket",92:"Protocol not available",93:"Unknown protocol",94:"Socket type not supported",95:"Not supported",96:"Protocol family not supported",97:"Address family not supported by protocol family",98:"Address already in use",99:"Address not available",100:"Network interface is not configured",101:"Network is unreachable",102:"Connection reset by network",103:"Connection aborted",104:"Connection reset by peer",105:"No buffer space available",106:"Socket is already connected",107:"Socket is not connected",108:"Can't send after socket shutdown",109:"Too many references",110:"Connection timed out",111:"Connection refused",112:"Host is down",113:"Host is unreachable",114:"Socket already connected",115:"Connection already in progress",116:"Stale file handle",122:"Quota exceeded",123:"No medium (in tape drive)",125:"Operation canceled",130:"Previous owner died",131:"State not recoverable"};function yb(e,t){for(var r=0,i=e.length-1;0<=i;i--){var n=e[i];"."===n?e.splice(i,1):".."===n?(e.splice(i,1),r++):r&&(e.splice(i,1),r--)}if(t)for(;r--;r)e.unshift("..");return e}function zb(e){var t="/"===e.charAt(0),r="/"===e.substr(-1);return(e=yb(e.split("/").filter(function(e){return!!e}),!t).join("/"))||t||(e="."),e&&r&&(e+="/"),(t?"/":"")+e}function Ab(e){var t=/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/.exec(e).slice(1);return e=t[0],t=t[1],e||t?(t&&(t=t.substr(0,t.length-1)),e+t):"."}function Bb(e){if("/"===e)return"/";var t=e.lastIndexOf("/");return-1===t?e:e.substr(t+1)}function Cb(){return zb(Array.prototype.slice.call(arguments,0).join("/"))}function K(e,t){return zb(e+"/"+t)}function Db(){for(var e="",t=!1,r=arguments.length-1;-1<=r&&!t;r--){if("string"!=typeof(t=0<=r?arguments[r]:"/"))throw new TypeError("Arguments to path.resolve must be strings");if(!t)return"";e=t+"/"+e,t="/"===t.charAt(0)}return(t?"/":"")+(e=yb(e.split("/").filter(function(e){return!!e}),!t).join("/"))||"."}var Eb=[];function Fb(e,t){Eb[e]={input:[],output:[],N:t},Gb(e,Hb)}var Hb={open:function(e){var t=Eb[e.g.rdev];if(!t)throw new L(J.ha);e.tty=t,e.seekable=!1},close:function(e){e.tty.N.flush(e.tty)},flush:function(e){e.tty.N.flush(e.tty)},read:function(e,t,r,i){if(!e.tty||!e.tty.N.La)throw new L(J.Aa);for(var n=0,o=0;oe.e.length&&(e.e=M.cb(e),e.o=e.e.length),!e.e||e.e.subarray){var r=e.e?e.e.buffer.byteLength:0;t<=r||(t=Math.max(t,r*(r<1048576?2:1.125)|0),0!=r&&(t=Math.max(t,256)),r=e.e,e.e=new Uint8Array(t),0t)e.e.length=t;else for(;e.e.length=e.g.o)return 0;if(assert(0<=(e=Math.min(e.g.o-n,i))),8>1)}catch(e){if(!e.code)throw e;throw new L(J[e.code])}return t.mode},B:function(e){for(var t=[];e.parent!==e;)t.push(e.name),e=e.parent;return t.push(e.A.pa.root),t.reverse(),Cb.apply(null,t)},Ha:{0:"r",1:"r+",2:"r+",64:"r",65:"r+",66:"r+",129:"rx+",193:"rx+",514:"w+",577:"w",578:"w+",705:"wx",706:"wx+",1024:"a",1025:"a",1026:"a+",1089:"a",1090:"a+",1153:"ax",1154:"ax+",1217:"ax",1218:"ax+",4096:"rs",4098:"rs+"},$a:function(e){if((e&=-32769)in P.Ha)return P.Ha[e];throw new L(J.q)},k:{D:function(e){var t;e=P.B(e);try{t=fs.lstatSync(e)}catch(e){if(!e.code)throw e;throw new L(J[e.code])}return P.$&&!t.K&&(t.K=4096),P.$&&!t.blocks&&(t.blocks=(t.size+t.K-1)/t.K|0),{dev:t.dev,ino:t.ino,mode:t.mode,nlink:t.nlink,uid:t.uid,gid:t.gid,rdev:t.rdev,size:t.size,atime:t.atime,mtime:t.mtime,ctime:t.ctime,K:t.K,blocks:t.blocks}},u:function(e,t){var r=P.B(e);try{void 0!==t.mode&&(fs.chmodSync(r,t.mode),e.mode=t.mode),void 0!==t.size&&fs.truncateSync(r,t.size)}catch(e){if(!e.code)throw e;throw new L(J[e.code])}},lookup:function(e,t){var r=K(P.B(e),t);r=P.Ja(r);return P.createNode(e,t,r)},T:function(e,t,r,i){e=P.createNode(e,t,r,i),t=P.B(e);try{N(e.mode)?fs.mkdirSync(t,e.mode):fs.writeFileSync(t,"",{mode:e.mode})}catch(e){if(!e.code)throw e;throw new L(J[e.code])}return e},rename:function(e,t,r){e=P.B(e),t=K(P.B(t),r);try{fs.renameSync(e,t)}catch(e){if(!e.code)throw e;throw new L(J[e.code])}},unlink:function(e,t){var r=K(P.B(e),t);try{fs.unlinkSync(r)}catch(e){if(!e.code)throw e;throw new L(J[e.code])}},rmdir:function(e,t){var r=K(P.B(e),t);try{fs.rmdirSync(r)}catch(e){if(!e.code)throw e;throw new L(J[e.code])}},readdir:function(e){e=P.B(e);try{return fs.readdirSync(e)}catch(e){if(!e.code)throw e;throw new L(J[e.code])}},symlink:function(e,t,r){e=K(P.B(e),t);try{fs.symlinkSync(r,e)}catch(e){if(!e.code)throw e;throw new L(J[e.code])}},readlink:function(e){var t=P.B(e);try{return t=fs.readlinkSync(t),t=Ob.relative(Ob.resolve(e.A.pa.root),t)}catch(e){if(!e.code)throw e;throw new L(J[e.code])}}},n:{open:function(e){var t=P.B(e.g);try{32768==(61440&e.g.mode)&&(e.V=fs.openSync(t,P.$a(e.flags)))}catch(e){if(!e.code)throw e;throw new L(J[e.code])}},close:function(e){try{32768==(61440&e.g.mode)&&e.V&&fs.closeSync(e.V)}catch(e){if(!e.code)throw e;throw new L(J[e.code])}},read:function(e,t,r,i,n){if(0===i)return 0;var o,a=new Buffer(i);try{o=fs.readSync(e.V,a,0,i,n)}catch(e){throw new L(J[e.code])}if(0>>0)%Q.length}function Xb(e){var t=Wb(e.parent.id,e.name);e.M=Q[t],Q[t]=e}function Nb(e,t){var r;if(r=(r=Yb(e,"x"))?r:e.k.lookup?0:J.da)throw new L(r,e);for(r=Q[Wb(e.id,t)];r;r=r.M){var i=r.name;if(r.parent.id===e.id&&i===t)return r}return e.k.lookup(e,t)}function Lb(e,t,r,i){return Zb||((Zb=function(e,t,r,i){e||(e=this),this.parent=e,this.A=e.A,this.U=null,this.id=Sb++,this.name=t,this.mode=r,this.k={},this.n={},this.rdev=i}).prototype={},Object.defineProperties(Zb.prototype,{read:{get:function(){return 365==(365&this.mode)},set:function(e){e?this.mode|=365:this.mode&=-366}},write:{get:function(){return 146==(146&this.mode)},set:function(e){e?this.mode|=146:this.mode&=-147}},kb:{get:function(){return N(this.mode)}},jb:{get:function(){return 8192==(61440&this.mode)}}})),Xb(e=new Zb(e,t,r,i)),e}function N(e){return 16384==(61440&e)}var $b={r:0,rs:1052672,"r+":2,w:577,wx:705,xw:705,"w+":578,"wx+":706,"xw+":706,a:1089,ax:1217,xa:1217,"a+":1090,"ax+":1218,"xa+":1218};function Yb(e,t){return Tb?0:(-1===t.indexOf("r")||292&e.mode)&&(-1===t.indexOf("w")||146&e.mode)&&(-1===t.indexOf("x")||73&e.mode)?0:J.da}function ac(e,t){try{return Nb(e,t),J.wa}catch(e){}return Yb(e,"wx")}function bc(){for(var e=0;e<=4096;e++)if(!Rb[e])return e;throw new L(J.Sa)}function cc(e){dc||((dc=function(){}).prototype={},Object.defineProperties(dc.prototype,{object:{get:function(){return this.g},set:function(e){this.g=e}},Ld:{get:function(){return 1!=(2097155&this.flags)}},Md:{get:function(){return 0!=(2097155&this.flags)}},Kd:{get:function(){return 1024&this.flags}}}));var t,r=new dc;for(t in e)r[t]=e[t];return e=r,r=bc(),e.fd=r,Rb[r]=e}var Kb={open:function(e){e.n=Qb[e.g.rdev].n,e.n.open&&e.n.open(e)},G:function(){throw new L(J.ia)}},qc;function Gb(e,t){Qb[e]={n:t}}function ec(e,t){var r,i="/"===t,n=!t;if(i&&Pb)throw new L(J.fa);if(!i&&!n){if(t=(r=S(t,{Ia:!1})).path,(r=r.g).U)throw new L(J.fa);if(!N(r.mode))throw new L(J.ya)}n={type:e,pa:{},Oa:t,lb:[]};var o=e.A(n);(o.A=n).root=o,i?Pb=o:r&&(r.U=n,r.A&&r.A.lb.push(n))}function fc(e,t,r){var i=S(e,{parent:!0}).g;if(!(e=Bb(e))||"."===e||".."===e)throw new L(J.q);var n=ac(i,e);if(n)throw new L(n);if(!i.k.T)throw new L(J.I);return i.k.T(i,e,t,r)}function gc(e,t){return t=4095&(void 0!==t?t:438),fc(e,t|=32768,0)}function V(e,t){return t=1023&(void 0!==t?t:511),fc(e,t|=16384,0)}function hc(e,t,r){return void 0===r&&(r=t,t=438),fc(e,8192|t,r)}function ic(e,t){if(!Db(e))throw new L(J.F);var r=S(t,{parent:!0}).g;if(!r)throw new L(J.F);var i=Bb(t),n=ac(r,i);if(n)throw new L(n);if(!r.k.symlink)throw new L(J.I);return r.k.symlink(r,i,e)}function Vb(e){if(!(e=S(e).g))throw new L(J.F);if(!e.k.readlink)throw new L(J.q);return Db(T(e.parent),e.k.readlink(e))}function jc(e,t){var r;if(!(r="string"==typeof e?S(e,{la:!0}).g:e).k.u)throw new L(J.I);r.k.u(r,{mode:4095&t|-4096&r.mode,timestamp:Date.now()})}function kc(t,r){var i,n,o;if(""===t)throw new L(J.F);if("string"==typeof r){if(void 0===(n=$b[r]))throw Error("Unknown file open mode: "+r)}else n=r;if(i=64&(r=n)?4095&(void 0===i?438:i)|32768:0,"object"==typeof t)o=t;else{t=zb(t);try{o=S(t,{la:!(131072&r)}).g}catch(e){}}if(n=!1,64&r)if(o){if(128&r)throw new L(J.wa)}else o=fc(t,i,0),n=!0;if(!o)throw new L(J.F);if(8192==(61440&o.mode)&&(r&=-513),65536&r&&!N(o.mode))throw new L(J.ya);if(!n&&(i=o?40960==(61440&o.mode)?J.ga:N(o.mode)&&(0!=(2097155&r)||512&r)?J.P:(i=["r","w","rw"][3&r],512&r&&(i+="w"),Yb(o,i)):J.F))throw new L(i);if(512&r){var a;if(!(a="string"==typeof(i=o)?S(i,{la:!0}).g:i).k.u)throw new L(J.I);if(N(a.mode))throw new L(J.P);if(32768!=(61440&a.mode))throw new L(J.q);if(i=Yb(a,"w"))throw new L(i);a.k.u(a,{size:0,timestamp:Date.now()})}r&=-641,(o=cc({g:o,path:T(o),flags:r,seekable:!0,position:0,n:o.n,tb:[],error:!1})).n.open&&o.n.open(o),!e.logReadFiles||1&r||(lc||(lc={}),t in lc||(lc[t]=1,e.printErr("read file: "+t)));try{R.onOpenFile&&(a=0,1!=(2097155&r)&&(a|=1),0!=(2097155&r)&&(a|=2),R.onOpenFile(t,a))}catch(e){console.log("FS.trackingDelegate['onOpenFile']('"+t+"', flags) threw an exception: "+e.message)}return o}function mc(e){e.na&&(e.na=null);try{e.n.close&&e.n.close(e)}catch(e){throw e}finally{Rb[e.fd]=null}}function nc(e,t,r){if(!e.seekable||!e.n.G)throw new L(J.ia);e.position=e.n.G(e,t,r),e.tb=[]}function oc(e,t,r,i,n,o){if(i<0||n<0)throw new L(J.q);if(0==(2097155&e.flags))throw new L(J.ea);if(N(e.g.mode))throw new L(J.P);if(!e.n.write)throw new L(J.q);1024&e.flags&&nc(e,0,2);var a=!0;if(void 0===n)n=e.position,a=!1;else if(!e.seekable)throw new L(J.ia);t=e.n.write(e,t,r,i,n,o),a||(e.position+=t);try{e.path&&R.onWriteToFile&&R.onWriteToFile(e.path)}catch(e){console.log("FS.trackingDelegate['onWriteToFile']('"+path+"') threw an exception: "+e.message)}return t}function pc(){L||((L=function(e,t){this.g=t,this.qb=function(e){for(var t in this.S=e,J)if(J[t]===e){this.code=t;break}},this.qb(e),this.message=xb[e]}).prototype=Error(),L.prototype.constructor=L,[J.F].forEach(function(e){Mb[e]=new L(e),Mb[e].stack=""}))}function rc(e,t){var r=0;return e&&(r|=365),t&&(r|=146),r}function sc(e,t,r,i){return gc(e=K("string"==typeof e?e:T(e),t),rc(r,i))}function tc(e,t,r,i,n,o){if(n=gc(e=t?K("string"==typeof e?e:T(e),t):e,i=rc(i,n)),r){if("string"==typeof r){e=Array(r.length),t=0;for(var a=r.length;t>2]}function xc(){var e;if(e=X(),!(e=Rb[e]))throw new L(J.ea);return e}var yc={};function Ga(e){Ga.p||(r=Qa(r),Ga.p=!0,assert(n.R),Ga.bb=n.R,n.R=function(){x("cannot dynamically allocate, sbrk now has control")});var t=r;return 0==e||Ga.bb(e)?t:4294967295}e._i64Add=zc;var Ac=1;function Cc(e,t){if(Dc=e,Ec=t,!Fc)return 1;if(0==e)Y=function(){setTimeout(Gc,t)},Hc="timeout";else if(1==e)Y=function(){Ic(Gc)},Hc="rAF";else if(2==e){if(!window.setImmediate){var r=[];window.addEventListener("message",function(e){e.source===window&&"__emcc"===e.data&&(e.stopPropagation(),r.shift()())},!0),window.setImmediate=function(e){r.push(e),window.postMessage("__emcc","*")}}Y=function(){window.setImmediate(Gc)},Hc="immediate"}return 0}function Jc(a,t,r,s,i){e.noExitRuntime=!0,assert(!Fc,"emscripten_set_main_loop: there can only be one main loop function at once: call emscripten_cancel_main_loop to cancel the previous one before setting a new one with different parameters."),Fc=a,Kc=s;var l=Lc;if(Gc=function(){if(!na)if(0>r-6&63;r=r-6,e=e+"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[n]}2==r?(e+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[(3&t)<<4],e+="=="):4==r&&(e+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[(15&t)<<2],e+="="),u.src="data:audio/x-"+a.substr(-3)+";base64,"+e,s(u)}},u.src=n,ad(function(){s(u)})}});var r=e.canvas;r&&(r.sa=r.requestPointerLock||r.mozRequestPointerLock||r.webkitRequestPointerLock||r.msRequestPointerLock||function(){},r.Fa=document.exitPointerLock||document.mozExitPointerLock||document.webkitExitPointerLock||document.msExitPointerLock||function(){},r.Fa=r.Fa.bind(document),document.addEventListener("pointerlockchange",t,!1),document.addEventListener("mozpointerlockchange",t,!1),document.addEventListener("webkitpointerlockchange",t,!1),document.addEventListener("mspointerlockchange",t,!1),e.elementPointerLock&&r.addEventListener("click",function(e){!Tc&&r.sa&&(r.sa(),e.preventDefault())},!1))}}function bd(t,r,i,n){if(r&&e.ka&&t==e.canvas)return e.ka;var o,a;if(r){if(a={antialias:!1,alpha:!1},n)for(var s in n)a[s]=n[s];(a=GL.createContext(t,a))&&(o=GL.getContext(a).td),t.style.backgroundColor="black"}else o=t.getContext("2d");return o?(i&&(r||assert("undefined"==typeof GLctx,"cannot set in module if GLctx is used, but we are a non-GL context that would replace it"),e.ka=o,r&&GL.Od(a),e.Td=r,Uc.forEach(function(e){e()}),Vc()),o):null}var cd=!1,dd=void 0,ed=void 0;function fd(t,r,i){function n(){Sc=!1;var t=o.parentNode;(document.webkitFullScreenElement||document.webkitFullscreenElement||document.mozFullScreenElement||document.mozFullscreenElement||document.fullScreenElement||document.fullscreenElement||document.msFullScreenElement||document.msFullscreenElement||document.webkitCurrentFullScreenElement)===t?(o.Da=document.cancelFullScreen||document.mozCancelFullScreen||document.webkitCancelFullScreen||document.msExitFullscreen||document.exitFullscreen||function(){},o.Da=o.Da.bind(document),dd&&o.sa(),Sc=!0,ed&&gd()):(t.parentNode.insertBefore(o,t),t.parentNode.removeChild(t),ed&&hd()),e.onFullScreen&&e.onFullScreen(Sc),id(o)}void 0===(dd=t)&&(dd=!0),void 0===(ed=r)&&(ed=!1),void 0===(jd=i)&&(jd=null);var o=e.canvas;cd||(cd=!0,document.addEventListener("fullscreenchange",n,!1),document.addEventListener("mozfullscreenchange",n,!1),document.addEventListener("webkitfullscreenchange",n,!1),document.addEventListener("MSFullscreenChange",n,!1));var a=document.createElement("div");o.parentNode.insertBefore(a,o),a.appendChild(o),a.p=a.requestFullScreen||a.mozRequestFullScreen||a.msRequestFullscreen||(a.webkitRequestFullScreen?function(){a.webkitRequestFullScreen(Element.ALLOW_KEYBOARD_INPUT)}:null),i?a.p({Ud:i}):a.p()}var kd=0;function ld(e){var t=Date.now();if(0===kd)kd=t+1e3/60;else for(;kd<=t+2;)kd+=1e3/60;t=Math.max(kd-t,0),setTimeout(e,t)}function Ic(e){"undefined"==typeof window?ld(e):(window.requestAnimationFrame||(window.requestAnimationFrame=window.requestAnimationFrame||window.mozRequestAnimationFrame||window.webkitRequestAnimationFrame||window.msRequestAnimationFrame||window.oRequestAnimationFrame||ld),window.requestAnimationFrame(e))}function ad(t){e.noExitRuntime=!0,setTimeout(function(){na||t()},1e4)}function $c(e){return{jpg:"image/jpeg",jpeg:"image/jpeg",png:"image/png",bmp:"image/bmp",ogg:"audio/ogg",wav:"audio/wav",mp3:"audio/mpeg"}[e.substr(e.lastIndexOf(".")+1)]}function md(e,t,r){var i=new XMLHttpRequest;i.open("GET",e,!0),i.responseType="arraybuffer",i.onload=function(){200==i.status||0==i.status&&i.response?t(i.response):r()},i.onerror=r,i.send(null)}function nd(t,r,e){md(t,function(e){assert(e,'Loading data file "'+t+'" failed (no arrayBuffer).'),r(new Uint8Array(e)),lb()},function(){if(!e)throw'Loading data file "'+t+'" failed.';e()}),kb()}var od=[],Wc,Xc,Yc,Zc,jd;function pd(){var t=e.canvas;od.forEach(function(e){e(t.width,t.height)})}function gd(){if("undefined"!=typeof SDL){var e=Sa[SDL.screen+0*n.J>>2];C[SDL.screen+0*n.J>>2]=8388608|e}pd()}function hd(){if("undefined"!=typeof SDL){var e=Sa[SDL.screen+0*n.J>>2];C[SDL.screen+0*n.J>>2]=-8388609&e}pd()}function id(t,r,i){r&&i?(t.ub=r,t.hb=i):(r=t.ub,i=t.hb);var n=r,o=i;if(e.forcedAspectRatio&&0this.length-1||e<0)){var t=e%this.chunkSize;return this.gb(e/this.chunkSize|0)[t]}},a.prototype.pb=function(e){this.gb=e},a.prototype.Ca=function(){var e=new XMLHttpRequest;if(e.open("HEAD",l,!1),e.send(null),!(200<=e.status&&e.status<300||304===e.status))throw Error("Couldn't load "+l+". Status: "+e.status);var t,o=Number(e.getResponseHeader("Content-length")),a=1048576;(t=e.getResponseHeader("Accept-Ranges"))&&"bytes"===t||(a=o);var s=this;s.pb(function(e){var t=e*a,r=(e+1)*a-1;r=Math.min(r,o-1);if(void 0===s.Y[e]){var i=s.Y;if(r=(e=e.g.e).length)return 0;if(assert(0<=(i=Math.min(e.length-n,i))),e.slice)for(var o=0;o>2]=0;case 21520:return r.tty?-J.q:-J.Q;case 21531:if(n=X(),!r.n.ib)throw new L(J.Q);return r.n.ib(r,i,n);default:x("bad ioctl syscall "+i)}}catch(e){return void 0!==vc&&e instanceof L||x(e),-e.S}},___syscall6:function(e,t){wc=t;try{return mc(xc()),0}catch(e){return void 0!==vc&&e instanceof L||x(e),-e.S}},_emscripten_set_main_loop_timing:Cc,__ZSt18uncaught_exceptionv:tb,___setErrNo:ob,_sbrk:Ga,___cxa_begin_catch:function(e){var t;tb.p--,ub.push(e);e:{if(e&&!vb[e])for(t in vb)if(vb[t].wd===e)break e;t=e}return t&&vb[t].Sd++,e},_emscripten_memcpy_big:function(e,t,r){return E.set(E.subarray(t,t+r),e),e},_sysconf:function(e){switch(e){case 30:return 4096;case 85:return F/4096;case 132:case 133:case 12:case 137:case 138:case 15:case 235:case 16:case 17:case 18:case 19:case 20:case 149:case 13:case 10:case 236:case 153:case 9:case 21:case 22:case 159:case 154:case 14:case 77:case 78:case 139:case 80:case 81:case 82:case 68:case 67:case 164:case 11:case 29:case 47:case 48:case 95:case 52:case 51:case 46:return 200809;case 79:return 0;case 27:case 246:case 127:case 128:case 23:case 24:case 160:case 161:case 181:case 182:case 242:case 183:case 184:case 243:case 244:case 245:case 165:case 178:case 179:case 49:case 50:case 168:case 169:case 175:case 170:case 171:case 172:case 97:case 76:case 32:case 173:case 35:return-1;case 176:case 177:case 7:case 155:case 8:case 157:case 125:case 126:case 92:case 93:case 129:case 130:case 131:case 94:case 91:return 1;case 74:case 60:case 69:case 70:case 4:return 1024;case 31:case 42:case 72:return 32;case 87:case 26:case 33:return 2147483647;case 34:case 1:return 47839;case 38:case 36:return 99;case 43:case 37:return 2048;case 0:return 2097152;case 3:return 65536;case 28:return 32768;case 44:return 32767;case 75:return 16384;case 39:return 1e3;case 89:return 700;case 71:return 256;case 40:return 255;case 2:return 100;case 180:return 64;case 25:return 20;case 5:return 16;case 6:return 6;case 73:return 4;case 84:return"object"==typeof navigator&&navigator.hardwareConcurrency||1}return ob(J.q),-1},_pthread_getspecific:function(e){return yc[e]||0},_pthread_self:function(){return 0},_pthread_once:wb,_pthread_key_create:function(e){return 0==e?J.q:(C[e>>2]=Ac,yc[Ac]=0,Ac++,0)},___unlock:function(){},_emscripten_set_main_loop:Jc,_pthread_setspecific:function(e,t){return e in yc?(yc[e]=t,0):J.q},___lock:function(){},_abort:function(){e.abort()},_pthread_cleanup_push:pb,_time:function(e){var t=Date.now()/1e3|0;return e&&(C[e>>2]=t),t},___syscall140:function(e,t){wc=t;try{var r=xc(),i=X(),n=X(),o=X(),a=X();return assert(0===i),nc(r,n,a),C[o>>2]=r.position,r.na&&0===n&&0===a&&(r.na=null),0}catch(e){return void 0!==vc&&e instanceof L||x(e),-e.S}},___syscall146:function(e,t){wc=t;try{var r,i=xc(),n=X();e:{for(var o=X(),a=0,s=0;s>2],C[n+(8*s+4)>>2],void 0);if(l<0){r=-1;break e}a+=l}r=a}return r}catch(e){return void 0!==vc&&e instanceof L||x(e),-e.S}},STACKTOP:m,STACK_MAX:Va,tempDoublePtr:mb,ABORT:na,cttz_i8:qd};var Z=function(e,t,r){"use asm";var i=e.Int8Array;var n=e.Int16Array;var o=e.Int32Array;var a=e.Uint8Array;var s=e.Uint16Array;var l=e.Uint32Array;var u=e.Float32Array;var h=e.Float64Array;var pe=new i(r);var $=new n(r);var de=new o(r);var me=new a(r);var ge=new s(r);var c=new l(r);var f=new u(r);var ee=new h(r);var p=e.byteLength;var ve=t.STACKTOP|0;var d=t.STACK_MAX|0;var te=t.tempDoublePtr|0;var m=t.ABORT|0;var g=t.cttz_i8|0;var v=0;var _=0;var y=0;var b=0;var x=e.NaN,w=e.Infinity;var T=0,k=0,P=0,S=0,E=0.0,A=0,C=0,I=0,O=0.0;var re=0;var M=0;var D=0;var R=0;var z=0;var L=0;var F=0;var j=0;var N=0;var B=0;var U=e.Math.floor;var X=e.Math.abs;var H=e.Math.sqrt;var G=e.Math.pow;var W=e.Math.cos;var q=e.Math.sin;var V=e.Math.tan;var Y=e.Math.acos;var Z=e.Math.asin;var J=e.Math.atan;var K=e.Math.atan2;var Q=e.Math.exp;var ie=e.Math.log;var ne=e.Math.ceil;var _e=e.Math.imul;var oe=e.Math.min;var ae=e.Math.clz32;var se=t.abort;var le=t.assert;var ue=t.invoke_iiii;var he=t.invoke_viiiii;var ce=t.invoke_vi;var fe=t.invoke_ii;var ye=t.invoke_viii;var be=t.invoke_v;var xe=t.invoke_viiiiii;var we=t.invoke_iiiiii;var Te=t.invoke_viiii;var ke=t._pthread_cleanup_pop;var Pe=t.___syscall54;var Se=t.___syscall6;var Ee=t._emscripten_set_main_loop_timing;var Ae=t.__ZSt18uncaught_exceptionv;var Ce=t.___setErrNo;var Ie=t._sbrk;var Oe=t.___cxa_begin_catch;var Me=t._emscripten_memcpy_big;var De=t._sysconf;var Re=t._pthread_getspecific;var ze=t._pthread_self;var Le=t._pthread_once;var Fe=t._pthread_key_create;var je=t.___unlock;var Ne=t._emscripten_set_main_loop;var Be=t._pthread_setspecific;var Ue=t.___lock;var Xe=t._abort;var He=t._pthread_cleanup_push;var Ge=t._time;var We=t.___syscall140;var qe=t.___syscall146;var Ve=0.0;function Ye(e){if(p(e)&16777215||p(e)<=16777215||p(e)>2147483648)return false;pe=new i(e);$=new n(e);de=new o(e);me=new a(e);ge=new s(e);c=new l(e);f=new u(e);ee=new h(e);r=e;return true}function Ze(e){e=e|0;var t=0;t=ve;ve=ve+e|0;ve=ve+15&-16;return t|0}function Je(){return ve|0}function Ke(e){e=e|0;ve=e}function Qe(e,t){e=e|0;t=t|0;ve=e;d=t}function $e(e,t){e=e|0;t=t|0;if(!v){v=e;_=t}}function et(e){e=e|0;pe[te>>0]=pe[e>>0];pe[te+1>>0]=pe[e+1>>0];pe[te+2>>0]=pe[e+2>>0];pe[te+3>>0]=pe[e+3>>0]}function tt(e){e=e|0;pe[te>>0]=pe[e>>0];pe[te+1>>0]=pe[e+1>>0];pe[te+2>>0]=pe[e+2>>0];pe[te+3>>0]=pe[e+3>>0];pe[te+4>>0]=pe[e+4>>0];pe[te+5>>0]=pe[e+5>>0];pe[te+6>>0]=pe[e+6>>0];pe[te+7>>0]=pe[e+7>>0]}function rt(e){e=e|0;re=e}function it(){return re|0}function nt(e,t,r,i,n){e=e|0;t=t|0;r=r|0;i=i|0;n=n|0;var o=0,a=0,s=0,l=0,u=0,h=0,c=0,f=0,p=0,d=0,m=0;m=ve;ve=ve+608|0;f=m+88|0;c=m+72|0;l=m+64|0;s=m+48|0;a=m+24|0;o=m;h=m+96|0;p=m+92|0;u=e+4|0;d=e+8|0;if((de[u>>2]|0)>>>0>(de[d>>2]|0)>>>0){de[o>>2]=1154;de[o+4>>2]=2120;de[o+8>>2]=1133;br(h,1100,o)|0;yr(h,m+16|0)|0}if((2147418112/(i>>>0)|0)>>>0<=t>>>0){de[a>>2]=1154;de[a+4>>2]=2121;de[a+8>>2]=1169;br(h,1100,a)|0;yr(h,m+40|0)|0}a=de[d>>2]|0;if(a>>>0>=t>>>0){d=1;ve=m;return d|0}do{if(r){if(t){o=t+-1|0;if(!(o&t)){o=11;break}else t=o}else t=-1;t=t>>>16|t;t=t>>>8|t;t=t>>>4|t;t=t>>>2|t;t=(t>>>1|t)+1|0;o=10}else o=10}while(0);if((o|0)==10)if(!t){t=0;o=12}else o=11;if((o|0)==11)if(t>>>0<=a>>>0)o=12;if((o|0)==12){de[s>>2]=1154;de[s+4>>2]=2130;de[s+8>>2]=1217;br(h,1100,s)|0;yr(h,l)|0}r=_e(t,i)|0;do{if(!n){o=ot(de[e>>2]|0,r,p,1)|0;if(!o){d=0;ve=m;return d|0}else{de[e>>2]=o;break}}else{a=at(r,p)|0;if(!a){d=0;ve=m;return d|0}Ii[n&0](a,de[e>>2]|0,de[u>>2]|0);o=de[e>>2]|0;do{if(o)if(!(o&7)){Di[de[104>>2]&1](o,0,0,1,de[27]|0)|0;break}else{de[c>>2]=1154;de[c+4>>2]=2499;de[c+8>>2]=1516;br(h,1100,c)|0;yr(h,f)|0;break}}while(0);de[e>>2]=a}}while(0);o=de[p>>2]|0;if(o>>>0>r>>>0)t=(o>>>0)/(i>>>0)|0;de[d>>2]=t;d=1;ve=m;return d|0}function ot(e,t,r,i){e=e|0;t=t|0;r=r|0;i=i|0;var n=0,o=0,a=0,s=0,l=0,u=0;u=ve;ve=ve+592|0;l=u+48|0;o=u+24|0;n=u;s=u+72|0;a=u+68|0;if(e&7){de[n>>2]=1154;de[n+4>>2]=2499;de[n+8>>2]=1494;br(s,1100,n)|0;yr(s,u+16|0)|0;l=0;ve=u;return l|0}if(t>>>0>2147418112){de[o>>2]=1154;de[o+4>>2]=2499;de[o+8>>2]=1387;br(s,1100,o)|0;yr(s,u+40|0)|0;l=0;ve=u;return l|0}de[a>>2]=t;i=Di[de[104>>2]&1](e,t,a,i,de[27]|0)|0;if(r)de[r>>2]=de[a>>2];if(!(i&7)){l=i;ve=u;return l|0}de[l>>2]=1154;de[l+4>>2]=2551;de[l+8>>2]=1440;br(s,1100,l)|0;yr(s,u+64|0)|0;l=i;ve=u;return l|0}function at(e,t){e=e|0;t=t|0;var r=0,i=0,n=0,o=0,a=0,s=0,l=0;l=ve;ve=ve+592|0;a=l+48|0;s=l+24|0;r=l;o=l+72|0;n=l+68|0;i=e+3&-4;i=(i|0)!=0?i:4;if(i>>>0>2147418112){de[r>>2]=1154;de[r+4>>2]=2499;de[r+8>>2]=1387;br(o,1100,r)|0;yr(o,l+16|0)|0;s=0;ve=l;return s|0}de[n>>2]=i;r=Di[de[104>>2]&1](0,i,n,1,de[27]|0)|0;e=de[n>>2]|0;if(t)de[t>>2]=e;if((r|0)==0|e>>>0>>0){de[s>>2]=1154;de[s+4>>2]=2499;de[s+8>>2]=1413;br(o,1100,s)|0;yr(o,l+40|0)|0;s=0;ve=l;return s|0}if(!(r&7)){s=r;ve=l;return s|0}de[a>>2]=1154;de[a+4>>2]=2526;de[a+8>>2]=1440;br(o,1100,a)|0;yr(o,l+64|0)|0;s=r;ve=l;return s|0}function st(e,t,r,i){e=e|0;t=t|0;r=r|0;i=i|0;var n=0,o=0,a=0,s=0,l=0,u=0,h=0,c=0,f=0,p=0,d=0,m=0,g=0,v=0,_=0,y=0,b=0,x=0,w=0,T=0,k=0,P=0,S=0,E=0,A=0,C=0,I=0,O=0,M=0,D=0,R=0,z=0,L=0,F=0,j=0;j=ve;ve=ve+960|0;z=j+232|0;R=j+216|0;D=j+208|0;M=j+192|0;O=j+184|0;I=j+168|0;C=j+160|0;A=j+144|0;P=j+136|0;k=j+120|0;T=j+112|0;w=j+96|0;y=j+88|0;_=j+72|0;v=j+64|0;g=j+48|0;c=j+40|0;p=j+24|0;f=j+16|0;h=j;E=j+440|0;L=j+376|0;F=j+304|0;m=j+236|0;if((t|0)==0|i>>>0>11){e=0;ve=j;return e|0}de[e>>2]=t;n=F;o=n+68|0;do{de[n>>2]=0;n=n+4|0}while((n|0)<(o|0));o=0;do{n=pe[r+o>>0]|0;if(n<<24>>24){S=F+((n&255)<<2)|0;de[S>>2]=(de[S>>2]|0)+1}o=o+1|0}while((o|0)!=(t|0));o=0;u=1;a=0;s=-1;l=0;while(1){n=de[F+(u<<2)>>2]|0;if(!n)de[e+28+(u+-1<<2)>>2]=0;else{S=u+-1|0;de[L+(S<<2)>>2]=o;o=n+o|0;x=16-u|0;de[e+28+(S<<2)>>2]=(o+-1<>2]=l;de[m+(u<<2)>>2]=l;a=a>>>0>u>>>0?a:u;s=s>>>0>>0?s:u;l=n+l|0}u=u+1|0;if((u|0)==17){S=a;break}else o=o<<1}de[e+4>>2]=l;o=e+172|0;do{if(l>>>0>(de[o>>2]|0)>>>0){de[o>>2]=l;if(l){n=l+-1|0;if(n&l)d=14}else{n=-1;d=14}if((d|0)==14){x=n>>>16|n;x=x>>>8|x;x=x>>>4|x;x=x>>>2|x;x=(x>>>1|x)+1|0;de[o>>2]=x>>>0>t>>>0?t:x}a=e+176|0;n=de[a>>2]|0;do{if(n){x=de[n+-4>>2]|0;n=n+-8|0;if(!((x|0)!=0?(x|0)==(~de[n>>2]|0):0)){de[h>>2]=1154;de[h+4>>2]=644;de[h+8>>2]=1863;br(E,1100,h)|0;yr(E,f)|0}if(!(n&7)){Di[de[104>>2]&1](n,0,0,1,de[27]|0)|0;break}else{de[p>>2]=1154;de[p+4>>2]=2499;de[p+8>>2]=1516;br(E,1100,p)|0;yr(E,c)|0;break}}}while(0);o=de[o>>2]|0;o=(o|0)!=0?o:1;n=at((o<<1)+8|0,0)|0;if(!n){de[a>>2]=0;n=0;break}else{de[n+4>>2]=o;de[n>>2]=~o;de[a>>2]=n+8;d=25;break}}else d=25}while(0);e:do{if((d|0)==25){x=e+24|0;pe[x>>0]=s;pe[e+25>>0]=S;o=e+176|0;a=0;do{b=pe[r+a>>0]|0;n=b&255;if(b<<24>>24){if(!(de[F+(n<<2)>>2]|0)){de[g>>2]=1154;de[g+4>>2]=2273;de[g+8>>2]=1261;br(E,1100,g)|0;yr(E,v)|0}b=m+(n<<2)|0;n=de[b>>2]|0;de[b>>2]=n+1;if(n>>>0>=l>>>0){de[_>>2]=1154;de[_+4>>2]=2277;de[_+8>>2]=1274;br(E,1100,_)|0;yr(E,y)|0}$[(de[o>>2]|0)+(n<<1)>>1]=a}a=a+1|0}while((a|0)!=(t|0));n=pe[x>>0]|0;y=(n&255)>>>0>>0?i:0;b=e+8|0;de[b>>2]=y;_=(y|0)!=0;if(_){v=1<>>0>(de[n>>2]|0)>>>0){de[n>>2]=v;a=e+168|0;n=de[a>>2]|0;do{if(n){g=de[n+-4>>2]|0;n=n+-8|0;if(!((g|0)!=0?(g|0)==(~de[n>>2]|0):0)){de[w>>2]=1154;de[w+4>>2]=644;de[w+8>>2]=1863;br(E,1100,w)|0;yr(E,T)|0}if(!(n&7)){Di[de[104>>2]&1](n,0,0,1,de[27]|0)|0;break}else{de[k>>2]=1154;de[k+4>>2]=2499;de[k+8>>2]=1516;br(E,1100,k)|0;yr(E,P)|0;break}}}while(0);n=v<<2;o=at(n+8|0,0)|0;if(!o){de[a>>2]=0;n=0;break e}else{P=o+8|0;de[o+4>>2]=v;de[o>>2]=~v;de[a>>2]=P;o=P;break}}else{o=e+168|0;n=v<<2;a=o;o=de[o>>2]|0}}while(0);Yr(o|0,-1,n|0)|0;d=e+176|0;g=1;do{if(de[F+(g<<2)>>2]|0){t=y-g|0;m=1<>2]|0;if(o>>>0>=16){de[A>>2]=1154;de[A+4>>2]=1953;de[A+8>>2]=1737;br(E,1100,A)|0;yr(E,C)|0}n=de[e+28+(o<<2)>>2]|0;if(!n)p=-1;else p=(n+-1|0)>>>(16-g|0);if(s>>>0<=p>>>0){c=(de[e+96+(o<<2)>>2]|0)-s|0;f=g<<16;do{n=ge[(de[d>>2]|0)+(c+s<<1)>>1]|0;if((me[r+n>>0]|0|0)!=(g|0)){de[I>>2]=1154;de[I+4>>2]=2319;de[I+8>>2]=1303;br(E,1100,I)|0;yr(E,O)|0}h=s<>>0>=v>>>0){de[M>>2]=1154;de[M+4>>2]=2325;de[M+8>>2]=1337;br(E,1100,M)|0;yr(E,D)|0}n=de[a>>2]|0;if((de[n+(l<<2)>>2]|0)!=-1){de[R>>2]=1154;de[R+4>>2]=2327;de[R+8>>2]=1360;br(E,1100,R)|0;yr(E,z)|0;n=de[a>>2]|0}de[n+(l<<2)>>2]=o;u=u+1|0}while(u>>>0>>0);s=s+1|0}while(s>>>0<=p>>>0)}}g=g+1|0}while(y>>>0>=g>>>0);n=pe[x>>0]|0}o=e+96|0;de[o>>2]=(de[o>>2]|0)-(de[L>>2]|0);o=e+100|0;de[o>>2]=(de[o>>2]|0)-(de[L+4>>2]|0);o=e+104|0;de[o>>2]=(de[o>>2]|0)-(de[L+8>>2]|0);o=e+108|0;de[o>>2]=(de[o>>2]|0)-(de[L+12>>2]|0);o=e+112|0;de[o>>2]=(de[o>>2]|0)-(de[L+16>>2]|0);o=e+116|0;de[o>>2]=(de[o>>2]|0)-(de[L+20>>2]|0);o=e+120|0;de[o>>2]=(de[o>>2]|0)-(de[L+24>>2]|0);o=e+124|0;de[o>>2]=(de[o>>2]|0)-(de[L+28>>2]|0);o=e+128|0;de[o>>2]=(de[o>>2]|0)-(de[L+32>>2]|0);o=e+132|0;de[o>>2]=(de[o>>2]|0)-(de[L+36>>2]|0);o=e+136|0;de[o>>2]=(de[o>>2]|0)-(de[L+40>>2]|0);o=e+140|0;de[o>>2]=(de[o>>2]|0)-(de[L+44>>2]|0);o=e+144|0;de[o>>2]=(de[o>>2]|0)-(de[L+48>>2]|0);o=e+148|0;de[o>>2]=(de[o>>2]|0)-(de[L+52>>2]|0);o=e+152|0;de[o>>2]=(de[o>>2]|0)-(de[L+56>>2]|0);o=e+156|0;de[o>>2]=(de[o>>2]|0)-(de[L+60>>2]|0);o=e+16|0;de[o>>2]=0;a=e+20|0;de[a>>2]=n&255;t:do{if(_){while(1){if(!i)break t;n=i+-1|0;if(!(de[F+(i<<2)>>2]|0))i=n;else break}de[o>>2]=de[e+28+(n<<2)>>2];n=y+1|0;de[a>>2]=n;if(n>>>0<=S>>>0){while(1){if(de[F+(n<<2)>>2]|0)break;n=n+1|0;if(n>>>0>S>>>0)break t}de[a>>2]=n}}}while(0);de[e+92>>2]=-1;de[e+160>>2]=1048575;de[e+12>>2]=32-(de[b>>2]|0);n=1}}while(0);e=n;ve=j;return e|0}function lt(e,t,r,i,n){e=e|0;t=t|0;r=r|0;i=i|0;n=n|0;var o=0;if(!e){n=Br(t)|0;if(!r){r=n;return r|0}if(!n)o=0;else o=Hr(n)|0;de[r>>2]=o;r=n;return r|0}if(!t){Ur(e);if(!r){r=0;return r|0}de[r>>2]=0;r=0;return r|0}n=Xr(e,t)|0;o=(n|0)!=0;if(o|i^1)o=o?n:e;else{n=Xr(e,t)|0;o=(n|0)==0?e:n}if(!r){r=n;return r|0}t=Hr(o)|0;de[r>>2]=t;r=n;return r|0}function ut(e,t,r){e=e|0;t=t|0;r=r|0;var i=0;if(!((e|0)!=0&t>>>0>73&(r|0)!=0)){r=0;return r|0}if((de[r>>2]|0)!=40|t>>>0<74){r=0;return r|0}if(((me[e>>0]|0)<<8|(me[e+1>>0]|0)|0)!=18552){r=0;return r|0}if(((me[e+2>>0]|0)<<8|(me[e+3>>0]|0))>>>0<74){r=0;return r|0}if(((me[e+7>>0]|0)<<16|(me[e+6>>0]|0)<<24|(me[e+8>>0]|0)<<8|(me[e+9>>0]|0))>>>0>t>>>0){r=0;return r|0}de[r+4>>2]=(me[e+12>>0]|0)<<8|(me[e+13>>0]|0);de[r+8>>2]=(me[e+14>>0]|0)<<8|(me[e+15>>0]|0);de[r+12>>2]=me[e+16>>0];de[r+16>>2]=me[e+17>>0];t=e+18|0;i=r+32|0;de[i>>2]=me[t>>0];de[i+4>>2]=0;t=pe[t>>0]|0;de[r+20>>2]=t<<24>>24==0|t<<24>>24==9?8:16;de[r+24>>2]=(me[e+26>>0]|0)<<16|(me[e+25>>0]|0)<<24|(me[e+27>>0]|0)<<8|(me[e+28>>0]|0);de[r+28>>2]=(me[e+30>>0]|0)<<16|(me[e+29>>0]|0)<<24|(me[e+31>>0]|0)<<8|(me[e+32>>0]|0);r=1;return r|0}function ht(e){e=e|0;Oe(e|0)|0;Ut()}function ct(e){e=e|0;var t=0,r=0,i=0,n=0,o=0;o=ve;ve=ve+544|0;n=o;i=o+24|0;t=de[e+20>>2]|0;if(t)ft(t);t=e+4|0;r=de[t>>2]|0;if(!r){n=e+16|0;pe[n>>0]=0;ve=o;return}if(!(r&7))Di[de[104>>2]&1](r,0,0,1,de[27]|0)|0;else{de[n>>2]=1154;de[n+4>>2]=2499;de[n+8>>2]=1516;br(i,1100,n)|0;yr(i,o+16|0)|0}de[t>>2]=0;de[e+8>>2]=0;de[e+12>>2]=0;n=e+16|0;pe[n>>0]=0;ve=o;return}function ft(e){e=e|0;var t=0,r=0,i=0,n=0,o=0,a=0,s=0,l=0,u=0,h=0,c=0,f=0,p=0,d=0;p=ve;ve=ve+640|0;f=p+112|0;c=p+96|0;h=p+88|0;u=p+72|0;l=p+64|0;s=p+48|0;i=p+40|0;o=p+24|0;n=p+16|0;r=p;a=p+120|0;if(!e){ve=p;return}t=de[e+168>>2]|0;do{if(t){d=de[t+-4>>2]|0;t=t+-8|0;if(!((d|0)!=0?(d|0)==(~de[t>>2]|0):0)){de[r>>2]=1154;de[r+4>>2]=644;de[r+8>>2]=1863;br(a,1100,r)|0;yr(a,n)|0}if(!(t&7)){Di[de[104>>2]&1](t,0,0,1,de[27]|0)|0;break}else{de[o>>2]=1154;de[o+4>>2]=2499;de[o+8>>2]=1516;br(a,1100,o)|0;yr(a,i)|0;break}}}while(0);t=de[e+176>>2]|0;do{if(t){d=de[t+-4>>2]|0;t=t+-8|0;if(!((d|0)!=0?(d|0)==(~de[t>>2]|0):0)){de[s>>2]=1154;de[s+4>>2]=644;de[s+8>>2]=1863;br(a,1100,s)|0;yr(a,l)|0}if(!(t&7)){Di[de[104>>2]&1](t,0,0,1,de[27]|0)|0;break}else{de[u>>2]=1154;de[u+4>>2]=2499;de[u+8>>2]=1516;br(a,1100,u)|0;yr(a,h)|0;break}}}while(0);if(!(e&7)){Di[de[104>>2]&1](e,0,0,1,de[27]|0)|0;ve=p;return}else{de[c>>2]=1154;de[c+4>>2]=2499;de[c+8>>2]=1516;br(a,1100,c)|0;yr(a,f)|0;ve=p;return}}function pt(e){e=e|0;var t=0,r=0,i=0,n=0,o=0,a=0,s=0,l=0,u=0,h=0;h=ve;ve=ve+560|0;a=h+40|0;s=h+24|0;t=h;o=h+48|0;n=e+8|0;r=de[n>>2]|0;if((r+-1|0)>>>0>=8192){de[t>>2]=1154;de[t+4>>2]=2997;de[t+8>>2]=1541;br(o,1100,t)|0;yr(o,h+16|0)|0}de[e>>2]=r;i=e+20|0;t=de[i>>2]|0;if(!t){t=at(180,0)|0;if(!t)t=0;else{u=t+164|0;de[u>>2]=0;de[u+4>>2]=0;de[u+8>>2]=0;de[u+12>>2]=0}de[i>>2]=t;u=t;l=de[e>>2]|0}else{u=t;l=r}if(!(de[n>>2]|0)){de[s>>2]=1154;de[s+4>>2]=903;de[s+8>>2]=1781;br(o,1100,s)|0;yr(o,a)|0;o=de[e>>2]|0}else o=l;n=de[e+4>>2]|0;if(o>>>0>16){r=o;t=0}else{e=0;u=st(u,l,n,e)|0;ve=h;return u|0}while(1){i=t+1|0;if(r>>>0>3){r=r>>>1;t=i}else{r=i;break}}e=t+2+((r|0)!=32&1<>>0>>0&1)|0;e=e>>>0<11?e&255:11;u=st(u,l,n,e)|0;ve=h;return u|0}function dt(e,t){e=e|0;t=t|0;var r=0,i=0,n=0,o=0,a=0,s=0,l=0,u=0,h=0,c=0,f=0,p=0,d=0,m=0,g=0,v=0,_=0,y=0,b=0,x=0,w=0,T=0,k=0,P=0,S=0,E=0,A=0,C=0,I=0,O=0,M=0,D=0,R=0,z=0;z=ve;ve=ve+800|0;I=z+256|0;C=z+240|0;A=z+232|0;E=z+216|0;S=z+208|0;P=z+192|0;k=z+184|0;T=z+168|0;w=z+160|0;x=z+144|0;b=z+136|0;y=z+120|0;_=z+112|0;v=z+96|0;g=z+88|0;m=z+72|0;c=z+64|0;h=z+48|0;s=z+40|0;l=z+24|0;o=z+16|0;n=z;D=z+288|0;R=z+264|0;O=mt(e,14)|0;if(!O){de[t>>2]=0;r=t+4|0;i=de[r>>2]|0;if(i){if(!(i&7))Di[de[104>>2]&1](i,0,0,1,de[27]|0)|0;else{de[n>>2]=1154;de[n+4>>2]=2499;de[n+8>>2]=1516;br(D,1100,n)|0;yr(D,o)|0}de[r>>2]=0;de[t+8>>2]=0;de[t+12>>2]=0}pe[t+16>>0]=0;r=t+20|0;i=de[r>>2]|0;if(!i){t=1;ve=z;return t|0}ft(i);de[r>>2]=0;t=1;ve=z;return t|0}p=t+4|0;d=t+8|0;r=de[d>>2]|0;if((r|0)!=(O|0)){if(r>>>0<=O>>>0){do{if((de[t+12>>2]|0)>>>0>>0){if(nt(p,O,(r+1|0)==(O|0),1,0)|0){r=de[d>>2]|0;break}pe[t+16>>0]=1;t=0;ve=z;return t|0}}while(0);Yr((de[p>>2]|0)+r|0,0,O-r|0)|0}de[d>>2]=O}Yr(de[p>>2]|0,0,O|0)|0;f=e+20|0;r=de[f>>2]|0;if((r|0)<5){o=e+4|0;a=e+8|0;n=e+16|0;do{i=de[o>>2]|0;if((i|0)==(de[a>>2]|0))i=0;else{de[o>>2]=i+1;i=me[i>>0]|0}r=r+8|0;de[f>>2]=r;if((r|0)>=33){de[l>>2]=1154;de[l+4>>2]=3199;de[l+8>>2]=1650;br(D,1100,l)|0;yr(D,s)|0;r=de[f>>2]|0}i=i<<32-r|de[n>>2];de[n>>2]=i}while((r|0)<5)}else{i=e+16|0;n=i;i=de[i>>2]|0}u=i>>>27;de[n>>2]=i<<5;de[f>>2]=r+-5;if((u+-1|0)>>>0>20){t=0;ve=z;return t|0}de[R+20>>2]=0;de[R>>2]=0;de[R+4>>2]=0;de[R+8>>2]=0;de[R+12>>2]=0;pe[R+16>>0]=0;r=R+4|0;i=R+8|0;e:do{if(nt(r,21,0,1,0)|0){s=de[i>>2]|0;l=de[r>>2]|0;Yr(l+s|0,0,21-s|0)|0;de[i>>2]=21;if(u){n=e+4|0;o=e+8|0;a=e+16|0;s=0;do{r=de[f>>2]|0;if((r|0)<3)do{i=de[n>>2]|0;if((i|0)==(de[o>>2]|0))i=0;else{de[n>>2]=i+1;i=me[i>>0]|0}r=r+8|0;de[f>>2]=r;if((r|0)>=33){de[h>>2]=1154;de[h+4>>2]=3199;de[h+8>>2]=1650;br(D,1100,h)|0;yr(D,c)|0;r=de[f>>2]|0}i=i<<32-r|de[a>>2];de[a>>2]=i}while((r|0)<3);else i=de[a>>2]|0;de[a>>2]=i<<3;de[f>>2]=r+-3;pe[l+(me[1611+s>>0]|0)>>0]=i>>>29;s=s+1|0}while((s|0)!=(u|0))}if(pt(R)|0){s=e+4|0;l=e+8|0;u=e+16|0;i=0;t:while(1){a=O-i|0;r=gt(e,R)|0;r:do{if(r>>>0<17){if((de[d>>2]|0)>>>0<=i>>>0){de[m>>2]=1154;de[m+4>>2]=903;de[m+8>>2]=1781;br(D,1100,m)|0;yr(D,g)|0}pe[(de[p>>2]|0)+i>>0]=r;r=i+1|0}else switch(r|0){case 17:{r=de[f>>2]|0;if((r|0)<3)do{n=de[s>>2]|0;if((n|0)==(de[l>>2]|0))n=0;else{de[s>>2]=n+1;n=me[n>>0]|0}r=r+8|0;de[f>>2]=r;if((r|0)>=33){de[v>>2]=1154;de[v+4>>2]=3199;de[v+8>>2]=1650;br(D,1100,v)|0;yr(D,_)|0;r=de[f>>2]|0}n=n<<32-r|de[u>>2];de[u>>2]=n}while((r|0)<3);else n=de[u>>2]|0;de[u>>2]=n<<3;de[f>>2]=r+-3;r=(n>>>29)+3|0;if(r>>>0>a>>>0){r=0;break e}r=r+i|0;break r}case 18:{r=de[f>>2]|0;if((r|0)<7)do{n=de[s>>2]|0;if((n|0)==(de[l>>2]|0))n=0;else{de[s>>2]=n+1;n=me[n>>0]|0}r=r+8|0;de[f>>2]=r;if((r|0)>=33){de[y>>2]=1154;de[y+4>>2]=3199;de[y+8>>2]=1650;br(D,1100,y)|0;yr(D,b)|0;r=de[f>>2]|0}n=n<<32-r|de[u>>2];de[u>>2]=n}while((r|0)<7);else n=de[u>>2]|0;de[u>>2]=n<<7;de[f>>2]=r+-7;r=(n>>>25)+11|0;if(r>>>0>a>>>0){r=0;break e}r=r+i|0;break r}default:{if((r+-19|0)>>>0>=2){M=90;break t}o=de[f>>2]|0;if((r|0)==19){if((o|0)<2){n=o;while(1){r=de[s>>2]|0;if((r|0)==(de[l>>2]|0))o=0;else{de[s>>2]=r+1;o=me[r>>0]|0}r=n+8|0;de[f>>2]=r;if((r|0)>=33){de[x>>2]=1154;de[x+4>>2]=3199;de[x+8>>2]=1650;br(D,1100,x)|0;yr(D,w)|0;r=de[f>>2]|0}n=o<<32-r|de[u>>2];de[u>>2]=n;if((r|0)<2)n=r;else break}}else{n=de[u>>2]|0;r=o}de[u>>2]=n<<2;de[f>>2]=r+-2;o=(n>>>30)+3|0}else{if((o|0)<6){n=o;while(1){r=de[s>>2]|0;if((r|0)==(de[l>>2]|0))o=0;else{de[s>>2]=r+1;o=me[r>>0]|0}r=n+8|0;de[f>>2]=r;if((r|0)>=33){de[T>>2]=1154;de[T+4>>2]=3199;de[T+8>>2]=1650;br(D,1100,T)|0;yr(D,k)|0;r=de[f>>2]|0}n=o<<32-r|de[u>>2];de[u>>2]=n;if((r|0)<6)n=r;else break}}else{n=de[u>>2]|0;r=o}de[u>>2]=n<<6;de[f>>2]=r+-6;o=(n>>>26)+7|0}if((i|0)==0|o>>>0>a>>>0){r=0;break e}r=i+-1|0;if((de[d>>2]|0)>>>0<=r>>>0){de[P>>2]=1154;de[P+4>>2]=903;de[P+8>>2]=1781;br(D,1100,P)|0;yr(D,S)|0}n=pe[(de[p>>2]|0)+r>>0]|0;if(!(n<<24>>24)){r=0;break e}r=o+i|0;if(i>>>0>=r>>>0){r=i;break r}do{if((de[d>>2]|0)>>>0<=i>>>0){de[E>>2]=1154;de[E+4>>2]=903;de[E+8>>2]=1781;br(D,1100,E)|0;yr(D,A)|0}pe[(de[p>>2]|0)+i>>0]=n;i=i+1|0}while((i|0)!=(r|0))}}}while(0);if(O>>>0>r>>>0)i=r;else break}if((M|0)==90){de[C>>2]=1154;de[C+4>>2]=3140;de[C+8>>2]=1632;br(D,1100,C)|0;yr(D,I)|0;r=0;break}if((O|0)==(r|0))r=pt(t)|0;else r=0}else r=0}else{pe[R+16>>0]=1;r=0}}while(0);ct(R);t=r;ve=z;return t|0}function mt(e,t){e=e|0;t=t|0;var r=0,i=0,n=0,o=0,a=0,s=0,l=0,u=0,h=0;h=ve;ve=ve+544|0;s=h+16|0;a=h;o=h+24|0;if(!t){u=0;ve=h;return u|0}if(t>>>0<=16){u=vt(e,t)|0;ve=h;return u|0}l=vt(e,t+-16|0)|0;u=e+20|0;t=de[u>>2]|0;if((t|0)<16){i=e+4|0;n=e+8|0;r=e+16|0;do{e=de[i>>2]|0;if((e|0)==(de[n>>2]|0))e=0;else{de[i>>2]=e+1;e=me[e>>0]|0}t=t+8|0;de[u>>2]=t;if((t|0)>=33){de[a>>2]=1154;de[a+4>>2]=3199;de[a+8>>2]=1650;br(o,1100,a)|0;yr(o,s)|0;t=de[u>>2]|0}e=e<<32-t|de[r>>2];de[r>>2]=e}while((t|0)<16)}else{e=e+16|0;r=e;e=de[e>>2]|0}de[r>>2]=e<<16;de[u>>2]=t+-16;u=e>>>16|l<<16;ve=h;return u|0}function gt(e,t){e=e|0;t=t|0;var r=0,i=0,n=0,o=0,a=0,s=0,l=0,u=0,h=0,c=0,f=0,p=0,d=0,m=0,g=0,v=0,_=0,y=0;y=ve;ve=ve+608|0;m=y+88|0;d=y+72|0;f=y+64|0;c=y+48|0;h=y+40|0;p=y+24|0;u=y+16|0;l=y;v=y+96|0;g=de[t+20>>2]|0;_=e+20|0;s=de[_>>2]|0;do{if((s|0)<24){a=e+4|0;i=de[a>>2]|0;n=de[e+8>>2]|0;r=i>>>0>>0;if((s|0)>=16){if(r){de[a>>2]=i+1;r=me[i>>0]|0}else r=0;de[_>>2]=s+8;a=e+16|0;o=r<<24-s|de[a>>2];de[a>>2]=o;break}if(r){o=(me[i>>0]|0)<<8;r=i+1|0}else{o=0;r=i}if(r>>>0>>0){i=me[r>>0]|0;r=r+1|0}else i=0;de[a>>2]=r;de[_>>2]=s+16;a=e+16|0;o=(i|o)<<16-s|de[a>>2];de[a>>2]=o}else{o=e+16|0;a=o;o=de[o>>2]|0}}while(0);n=(o>>>16)+1|0;do{if(n>>>0<=(de[g+16>>2]|0)>>>0){i=de[(de[g+168>>2]|0)+(o>>>(32-(de[g+8>>2]|0)|0)<<2)>>2]|0;if((i|0)==-1){de[l>>2]=1154;de[l+4>>2]=3244;de[l+8>>2]=1677;br(v,1100,l)|0;yr(v,u)|0}r=i&65535;i=i>>>16;if((de[t+8>>2]|0)>>>0<=r>>>0){de[p>>2]=1154;de[p+4>>2]=902;de[p+8>>2]=1781;br(v,1100,p)|0;yr(v,h)|0}if((me[(de[t+4>>2]|0)+r>>0]|0|0)!=(i|0)){de[c>>2]=1154;de[c+4>>2]=3248;de[c+8>>2]=1694;br(v,1100,c)|0;yr(v,f)|0}}else{i=de[g+20>>2]|0;while(1){r=i+-1|0;if(n>>>0>(de[g+28+(r<<2)>>2]|0)>>>0)i=i+1|0;else break}r=(o>>>(32-i|0))+(de[g+96+(r<<2)>>2]|0)|0;if(r>>>0<(de[t>>2]|0)>>>0){r=ge[(de[g+176>>2]|0)+(r<<1)>>1]|0;break}de[d>>2]=1154;de[d+4>>2]=3266;de[d+8>>2]=1632;br(v,1100,d)|0;yr(v,m)|0;_=0;ve=y;return _|0}}while(0);de[a>>2]=de[a>>2]<>2]=(de[_>>2]|0)-i;_=r;ve=y;return _|0}function vt(e,t){e=e|0;t=t|0;var r=0,i=0,n=0,o=0,a=0,s=0,l=0,u=0,h=0;h=ve;ve=ve+560|0;s=h+40|0;l=h+24|0;r=h;a=h+48|0;if(t>>>0>=33){de[r>>2]=1154;de[r+4>>2]=3190;de[r+8>>2]=1634;br(a,1100,r)|0;yr(a,h+16|0)|0}u=e+20|0;r=de[u>>2]|0;if((r|0)>=(t|0)){o=e+16|0;a=o;o=de[o>>2]|0;s=r;l=32-t|0;l=o>>>l;o=o<>2]=o;t=s-t|0;de[u>>2]=t;ve=h;return l|0}n=e+4|0;o=e+8|0;i=e+16|0;do{e=de[n>>2]|0;if((e|0)==(de[o>>2]|0))e=0;else{de[n>>2]=e+1;e=me[e>>0]|0}r=r+8|0;de[u>>2]=r;if((r|0)>=33){de[l>>2]=1154;de[l+4>>2]=3199;de[l+8>>2]=1650;br(a,1100,l)|0;yr(a,s)|0;r=de[u>>2]|0}e=e<<32-r|de[i>>2];de[i>>2]=e}while((r|0)<(t|0));l=32-t|0;l=e>>>l;s=e<>2]=s;t=r-t|0;de[u>>2]=t;ve=h;return l|0}function _t(e,t){e=e|0;t=t|0;var r=0,i=0,n=0,o=0,a=0,s=0,l=0,u=0,h=0,c=0,f=0,p=0,d=0,m=0,g=0;d=ve;ve=ve+544|0;f=d+16|0;c=d;h=d+24|0;if((e|0)==0|t>>>0<62){p=0;ve=d;return p|0}u=at(300,0)|0;if(!u){p=0;ve=d;return p|0}de[u>>2]=519686845;r=u+4|0;de[r>>2]=0;i=u+8|0;de[i>>2]=0;l=u+88|0;n=u+136|0;o=u+160|0;a=l;s=a+44|0;do{de[a>>2]=0;a=a+4|0}while((a|0)<(s|0));pe[l+44>>0]=0;m=u+184|0;a=u+208|0;s=u+232|0;g=u+252|0;de[g>>2]=0;de[g+4>>2]=0;de[g+8>>2]=0;pe[g+12>>0]=0;g=u+268|0;de[g>>2]=0;de[g+4>>2]=0;de[g+8>>2]=0;pe[g+12>>0]=0;g=u+284|0;de[g>>2]=0;de[g+4>>2]=0;de[g+8>>2]=0;pe[g+12>>0]=0;de[n>>2]=0;de[n+4>>2]=0;de[n+8>>2]=0;de[n+12>>2]=0;de[n+16>>2]=0;pe[n+20>>0]=0;de[o>>2]=0;de[o+4>>2]=0;de[o+8>>2]=0;de[o+12>>2]=0;de[o+16>>2]=0;pe[o+20>>0]=0;de[m>>2]=0;de[m+4>>2]=0;de[m+8>>2]=0;de[m+12>>2]=0;de[m+16>>2]=0;pe[m+20>>0]=0;de[a>>2]=0;de[a+4>>2]=0;de[a+8>>2]=0;de[a+12>>2]=0;de[a+16>>2]=0;pe[a+20>>0]=0;de[s>>2]=0;de[s+4>>2]=0;de[s+8>>2]=0;de[s+12>>2]=0;pe[s+16>>0]=0;do{if(((t>>>0>=74?((me[e>>0]|0)<<8|(me[e+1>>0]|0)|0)==18552:0)?((me[e+2>>0]|0)<<8|(me[e+3>>0]|0))>>>0>=74:0)?((me[e+7>>0]|0)<<16|(me[e+6>>0]|0)<<24|(me[e+8>>0]|0)<<8|(me[e+9>>0]|0))>>>0<=t>>>0:0){de[l>>2]=e;de[r>>2]=e;de[i>>2]=t;if(Et(u)|0){r=de[l>>2]|0;if((me[r+39>>0]|0)<<8|(me[r+40>>0]|0)){if(!(At(u)|0))break;if(!(Ct(u)|0))break;r=de[l>>2]|0}if(!((me[r+55>>0]|0)<<8|(me[r+56>>0]|0))){g=u;ve=d;return g|0}if(It(u)|0?Ot(u)|0:0){g=u;ve=d;return g|0}}}else p=7}while(0);if((p|0)==7)de[l>>2]=0;Lt(u);if(!(u&7)){Di[de[104>>2]&1](u,0,0,1,de[27]|0)|0;g=0;ve=d;return g|0}else{de[c>>2]=1154;de[c+4>>2]=2499;de[c+8>>2]=1516;br(h,1100,c)|0;yr(h,f)|0;g=0;ve=d;return g|0}return 0}function yt(e,t,r,i,n){e=e|0;t=t|0;r=r|0;i=i|0;n=n|0;var o=0,a=0,s=0,l=0,u=0,h=0;h=ve;ve=ve+544|0;u=h;l=h+24|0;o=de[e+88>>2]|0;s=(me[o+70+(n<<2)+1>>0]|0)<<16|(me[o+70+(n<<2)>>0]|0)<<24|(me[o+70+(n<<2)+2>>0]|0)<<8|(me[o+70+(n<<2)+3>>0]|0);a=n+1|0;if(a>>>0<(me[o+16>>0]|0)>>>0)o=(me[o+70+(a<<2)+1>>0]|0)<<16|(me[o+70+(a<<2)>>0]|0)<<24|(me[o+70+(a<<2)+2>>0]|0)<<8|(me[o+70+(a<<2)+3>>0]|0);else o=de[e+8>>2]|0;if(o>>>0>s>>>0){l=e+4|0;l=de[l>>2]|0;l=l+s|0;u=o-s|0;u=bt(e,l,u,t,r,i,n)|0;ve=h;return u|0}de[u>>2]=1154;de[u+4>>2]=3704;de[u+8>>2]=1792;br(l,1100,u)|0;yr(l,h+16|0)|0;l=e+4|0;l=de[l>>2]|0;l=l+s|0;u=o-s|0;u=bt(e,l,u,t,r,i,n)|0;ve=h;return u|0}function bt(e,t,r,i,n,o,a){e=e|0;t=t|0;r=r|0;i=i|0;n=n|0;o=o|0;a=a|0;var s=0,l=0,u=0,h=0;h=de[e+88>>2]|0;l=((me[h+12>>0]|0)<<8|(me[h+13>>0]|0))>>>a;u=((me[h+14>>0]|0)<<8|(me[h+15>>0]|0))>>>a;l=l>>>0>1?(l+3|0)>>>2:1;u=u>>>0>1?(u+3|0)>>>2:1;h=h+18|0;a=pe[h>>0]|0;a=_e(a<<24>>24==0|a<<24>>24==9?8:16,l)|0;if(o)if((o&3|0)==0&a>>>0<=o>>>0)a=o;else{e=0;return e|0}if((_e(a,u)|0)>>>0>n>>>0){e=0;return e|0}o=(l+1|0)>>>1;s=(u+1|0)>>>1;if(!r){e=0;return e|0}de[e+92>>2]=t;de[e+96>>2]=t;de[e+104>>2]=r;de[e+100>>2]=t+r;de[e+108>>2]=0;de[e+112>>2]=0;switch(me[h>>0]|0|0){case 0:{Mt(e,i,n,a,l,u,o,s)|0;e=1;return e|0}case 4:case 6:case 5:case 3:case 2:{Dt(e,i,n,a,l,u,o,s)|0;e=1;return e|0}case 9:{Rt(e,i,n,a,l,u,o,s)|0;e=1;return e|0}case 8:case 7:{zt(e,i,n,a,l,u,o,s)|0;e=1;return e|0}default:{e=0;return e|0}}return 0}function xt(e,t){e=e|0;t=t|0;var r=0,i=0;i=ve;ve=ve+48|0;r=i;de[r>>2]=40;ut(e,t,r)|0;ve=i;return de[r+4>>2]|0}function wt(e,t){e=e|0;t=t|0;var r=0,i=0;i=ve;ve=ve+48|0;r=i;de[r>>2]=40;ut(e,t,r)|0;ve=i;return de[r+8>>2]|0}function Tt(e,t){e=e|0;t=t|0;var r=0,i=0;i=ve;ve=ve+48|0;r=i;de[r>>2]=40;ut(e,t,r)|0;ve=i;return de[r+12>>2]|0}function kt(e,t){e=e|0;t=t|0;var r=0,i=0;i=ve;ve=ve+48|0;r=i;de[r>>2]=40;ut(e,t,r)|0;ve=i;return de[r+32>>2]|0}function Pt(e,t,r){e=e|0;t=t|0;r=r|0;var i=0,n=0,o=0,a=0,s=0,l=0,u=0;l=ve;ve=ve+576|0;a=l+56|0;o=l+40|0;n=l+64|0;u=l;de[u>>2]=40;ut(e,t,u)|0;i=(((de[u+4>>2]|0)>>>r)+3|0)>>>2;t=(((de[u+8>>2]|0)>>>r)+3|0)>>>2;r=u+32|0;e=de[r+4>>2]|0;do{switch(de[r>>2]|0){case 0:{if(!e)e=8;else s=13;break}case 1:{if(!e)s=12;else s=13;break}case 2:{if(!e)s=12;else s=13;break}case 3:{if(!e)s=12;else s=13;break}case 4:{if(!e)s=12;else s=13;break}case 5:{if(!e)s=12;else s=13;break}case 6:{if(!e)s=12;else s=13;break}case 7:{if(!e)s=12;else s=13;break}case 8:{if(!e)s=12;else s=13;break}case 9:{if(!e)e=8;else s=13;break}default:s=13}}while(0);if((s|0)==12)e=16;else if((s|0)==13){de[o>>2]=1154;de[o+4>>2]=2663;de[o+8>>2]=1535;br(n,1100,o)|0;yr(n,a)|0;e=0}u=_e(_e(t,i)|0,e)|0;ve=l;return u|0}function St(e,t,r,i,n){e=e|0;t=t|0;r=r|0;i=i|0;n=n|0;var o=0,a=0,s=0,l=0,u=0,h=0,c=0,f=0,p=0,d=0,m=0;d=ve;ve=ve+608|0;f=d+80|0;p=d+64|0;s=d+56|0;a=d+40|0;h=d+88|0;m=d;c=d+84|0;de[m>>2]=40;ut(e,t,m)|0;l=(((de[m+4>>2]|0)>>>n)+3|0)>>>2;m=m+32|0;o=de[m+4>>2]|0;do{switch(de[m>>2]|0){case 0:{if(!o)o=8;else u=13;break}case 1:{if(!o)u=12;else u=13;break}case 2:{if(!o)u=12;else u=13;break}case 3:{if(!o)u=12;else u=13;break}case 4:{if(!o)u=12;else u=13;break}case 5:{if(!o)u=12;else u=13;break}case 6:{if(!o)u=12;else u=13;break}case 7:{if(!o)u=12;else u=13;break}case 8:{if(!o)u=12;else u=13;break}case 9:{if(!o)o=8;else u=13;break}default:u=13}}while(0);if((u|0)==12)o=16;else if((u|0)==13){de[a>>2]=1154;de[a+4>>2]=2663;de[a+8>>2]=1535;br(h,1100,a)|0;yr(h,s)|0;o=0}s=_e(o,l)|0;a=_t(e,t)|0;de[c>>2]=r;o=(a|0)==0;if(!(n>>>0>15|(i>>>0<8|o))?(de[a>>2]|0)==519686845:0)yt(a,c,i,s,n)|0;if(o){ve=d;return}if((de[a>>2]|0)!=519686845){ve=d;return}Lt(a);if(!(a&7)){Di[de[104>>2]&1](a,0,0,1,de[27]|0)|0;ve=d;return}else{de[p>>2]=1154;de[p+4>>2]=2499;de[p+8>>2]=1516;br(h,1100,p)|0;yr(h,f)|0;ve=d;return}}function Et(e){e=e|0;var t=0,r=0,i=0,n=0,o=0,a=0;a=e+92|0;i=de[e+4>>2]|0;o=e+88|0;n=de[o>>2]|0;t=(me[n+68>>0]|0)<<8|(me[n+67>>0]|0)<<16|(me[n+69>>0]|0);r=i+t|0;n=(me[n+65>>0]|0)<<8|(me[n+66>>0]|0);if(!n){e=0;return e|0}de[a>>2]=r;de[e+96>>2]=r;de[e+104>>2]=n;de[e+100>>2]=i+(n+t);de[e+108>>2]=0;de[e+112>>2]=0;if(!(dt(a,e+116|0)|0)){e=0;return e|0}t=de[o>>2]|0;do{if(!((me[t+39>>0]|0)<<8|(me[t+40>>0]|0))){if(!((me[t+55>>0]|0)<<8|(me[t+56>>0]|0))){e=0;return e|0}}else{if(!(dt(a,e+140|0)|0)){e=0;return e|0}if(dt(a,e+188|0)|0){t=de[o>>2]|0;break}else{e=0;return e|0}}}while(0);if((me[t+55>>0]|0)<<8|(me[t+56>>0]|0)){if(!(dt(a,e+164|0)|0)){e=0;return e|0}if(!(dt(a,e+212|0)|0)){e=0;return e|0}}e=1;return e|0}function At(e){e=e|0;var t=0,r=0,i=0,n=0,o=0,a=0,s=0,l=0,u=0,h=0,c=0,f=0,p=0,d=0;d=ve;ve=ve+592|0;l=d+16|0;s=d;a=d+72|0;p=d+24|0;i=e+88|0;t=de[i>>2]|0;f=(me[t+39>>0]|0)<<8|(me[t+40>>0]|0);h=e+236|0;o=e+240|0;r=de[o>>2]|0;if((r|0)!=(f|0)){if(r>>>0<=f>>>0){do{if((de[e+244>>2]|0)>>>0>>0){if(nt(h,f,(r+1|0)==(f|0),4,0)|0){t=de[o>>2]|0;break}pe[e+248>>0]=1;p=0;ve=d;return p|0}else t=r}while(0);Yr((de[h>>2]|0)+(t<<2)|0,0,f-t<<2|0)|0;t=de[i>>2]|0}de[o>>2]=f}u=e+92|0;r=de[e+4>>2]|0;i=(me[t+34>>0]|0)<<8|(me[t+33>>0]|0)<<16|(me[t+35>>0]|0);n=r+i|0;t=(me[t+37>>0]|0)<<8|(me[t+36>>0]|0)<<16|(me[t+38>>0]|0);if(!t){p=0;ve=d;return p|0}de[u>>2]=n;de[e+96>>2]=n;de[e+104>>2]=t;de[e+100>>2]=r+(t+i);de[e+108>>2]=0;de[e+112>>2]=0;de[p+20>>2]=0;de[p>>2]=0;de[p+4>>2]=0;de[p+8>>2]=0;de[p+12>>2]=0;pe[p+16>>0]=0;e=p+24|0;de[p+44>>2]=0;de[e>>2]=0;de[e+4>>2]=0;de[e+8>>2]=0;de[e+12>>2]=0;pe[e+16>>0]=0;if(dt(u,p)|0?(c=p+24|0,dt(u,c)|0):0){if(!(de[o>>2]|0)){de[s>>2]=1154;de[s+4>>2]=903;de[s+8>>2]=1781;br(a,1100,s)|0;yr(a,l)|0}if(!f)t=1;else{i=0;n=0;o=0;t=0;a=0;e=0;s=0;r=de[h>>2]|0;while(1){i=(gt(u,p)|0)+i&31;n=(gt(u,c)|0)+n&63;o=(gt(u,p)|0)+o&31;t=(gt(u,p)|0)+t|0;a=(gt(u,c)|0)+a&63;e=(gt(u,p)|0)+e&31;de[r>>2]=n<<5|i<<11|o|t<<27|a<<21|e<<16;s=s+1|0;if((s|0)==(f|0)){t=1;break}else{t=t&31;r=r+4|0}}}}else t=0;ct(p+24|0);ct(p);p=t;ve=d;return p|0}function Ct(e){e=e|0;var t=0,r=0,i=0,n=0,o=0,a=0,s=0,l=0,u=0,h=0,c=0,f=0,p=0,d=0,m=0,g=0,v=0,_=0,y=0,b=0,x=0,w=0,T=0,k=0,P=0,S=0,E=0;P=ve;ve=ve+1024|0;s=P+16|0;a=P;o=P+504|0;k=P+480|0;w=P+284|0;T=P+88|0;x=P+24|0;n=de[e+88>>2]|0;b=(me[n+47>>0]|0)<<8|(me[n+48>>0]|0);y=e+92|0;t=de[e+4>>2]|0;r=(me[n+42>>0]|0)<<8|(me[n+41>>0]|0)<<16|(me[n+43>>0]|0);i=t+r|0;n=(me[n+45>>0]|0)<<8|(me[n+44>>0]|0)<<16|(me[n+46>>0]|0);if(!n){k=0;ve=P;return k|0}de[y>>2]=i;de[e+96>>2]=i;de[e+104>>2]=n;de[e+100>>2]=t+(n+r);de[e+108>>2]=0;de[e+112>>2]=0;de[k+20>>2]=0;de[k>>2]=0;de[k+4>>2]=0;de[k+8>>2]=0;de[k+12>>2]=0;pe[k+16>>0]=0;if(dt(y,k)|0){r=0;i=-3;n=-3;while(1){de[w+(r<<2)>>2]=i;de[T+(r<<2)>>2]=n;t=(i|0)>2;r=r+1|0;if((r|0)==49)break;else{i=t?-3:i+1|0;n=(t&1)+n|0}}t=x;r=t+64|0;do{de[t>>2]=0;t=t+4|0}while((t|0)<(r|0));_=e+252|0;r=e+256|0;t=de[r>>2]|0;e:do{if((t|0)==(b|0))l=13;else{if(t>>>0<=b>>>0){do{if((de[e+260>>2]|0)>>>0>>0)if(nt(_,b,(t+1|0)==(b|0),4,0)|0){t=de[r>>2]|0;break}else{pe[e+264>>0]=1;t=0;break e}}while(0);Yr((de[_>>2]|0)+(t<<2)|0,0,b-t<<2|0)|0}de[r>>2]=b;l=13}}while(0);do{if((l|0)==13){if(!b){de[a>>2]=1154;de[a+4>>2]=903;de[a+8>>2]=1781;br(o,1100,a)|0;yr(o,s)|0;t=1;break}i=x+4|0;n=x+8|0;e=x+12|0;o=x+16|0;a=x+20|0;s=x+24|0;l=x+28|0;u=x+32|0;h=x+36|0;c=x+40|0;f=x+44|0;p=x+48|0;d=x+52|0;m=x+56|0;g=x+60|0;v=0;r=de[_>>2]|0;while(1){t=0;do{S=gt(y,k)|0;_=t<<1;E=x+(_<<2)|0;de[E>>2]=(de[E>>2]|0)+(de[w+(S<<2)>>2]|0)&3;_=x+((_|1)<<2)|0;de[_>>2]=(de[_>>2]|0)+(de[T+(S<<2)>>2]|0)&3;t=t+1|0}while((t|0)!=8);de[r>>2]=(me[1725+(de[i>>2]|0)>>0]|0)<<2|(me[1725+(de[x>>2]|0)>>0]|0)|(me[1725+(de[n>>2]|0)>>0]|0)<<4|(me[1725+(de[e>>2]|0)>>0]|0)<<6|(me[1725+(de[o>>2]|0)>>0]|0)<<8|(me[1725+(de[a>>2]|0)>>0]|0)<<10|(me[1725+(de[s>>2]|0)>>0]|0)<<12|(me[1725+(de[l>>2]|0)>>0]|0)<<14|(me[1725+(de[u>>2]|0)>>0]|0)<<16|(me[1725+(de[h>>2]|0)>>0]|0)<<18|(me[1725+(de[c>>2]|0)>>0]|0)<<20|(me[1725+(de[f>>2]|0)>>0]|0)<<22|(me[1725+(de[p>>2]|0)>>0]|0)<<24|(me[1725+(de[d>>2]|0)>>0]|0)<<26|(me[1725+(de[m>>2]|0)>>0]|0)<<28|(me[1725+(de[g>>2]|0)>>0]|0)<<30;v=v+1|0;if((v|0)==(b|0)){t=1;break}else r=r+4|0}}}while(0)}else t=0;ct(k);E=t;ve=P;return E|0}function It(e){e=e|0;var t=0,r=0,i=0,n=0,o=0,a=0,s=0,l=0,u=0,h=0,c=0,f=0;f=ve;ve=ve+560|0;l=f+16|0;s=f;a=f+48|0;c=f+24|0;n=de[e+88>>2]|0;h=(me[n+55>>0]|0)<<8|(me[n+56>>0]|0);u=e+92|0;t=de[e+4>>2]|0;r=(me[n+50>>0]|0)<<8|(me[n+49>>0]|0)<<16|(me[n+51>>0]|0);i=t+r|0;n=(me[n+53>>0]|0)<<8|(me[n+52>>0]|0)<<16|(me[n+54>>0]|0);if(!n){c=0;ve=f;return c|0}de[u>>2]=i;de[e+96>>2]=i;de[e+104>>2]=n;de[e+100>>2]=t+(n+r);de[e+108>>2]=0;de[e+112>>2]=0;de[c+20>>2]=0;de[c>>2]=0;de[c+4>>2]=0;de[c+8>>2]=0;de[c+12>>2]=0;pe[c+16>>0]=0;e:do{if(dt(u,c)|0){o=e+268|0;r=e+272|0;t=de[r>>2]|0;if((t|0)!=(h|0)){if(t>>>0<=h>>>0){do{if((de[e+276>>2]|0)>>>0>>0)if(nt(o,h,(t+1|0)==(h|0),2,0)|0){t=de[r>>2]|0;break}else{pe[e+280>>0]=1;t=0;break e}}while(0);Yr((de[o>>2]|0)+(t<<1)|0,0,h-t<<1|0)|0}de[r>>2]=h}if(!h){de[s>>2]=1154;de[s+4>>2]=903;de[s+8>>2]=1781;br(a,1100,s)|0;yr(a,l)|0;t=1;break}r=0;i=0;n=0;t=de[o>>2]|0;while(1){l=gt(u,c)|0;r=l+r&255;i=(gt(u,c)|0)+i&255;$[t>>1]=i<<8|r;n=n+1|0;if((n|0)==(h|0)){t=1;break}else t=t+2|0}}else t=0}while(0);ct(c);c=t;ve=f;return c|0}function Ot(e){e=e|0;var t=0,r=0,i=0,n=0,o=0,a=0,s=0,l=0,u=0,h=0,c=0,f=0,p=0,d=0,m=0,g=0,v=0,_=0,y=0,b=0,x=0,w=0,T=0,k=0,P=0,S=0,E=0;P=ve;ve=ve+2432|0;s=P+16|0;a=P;o=P+1912|0;k=P+1888|0;w=P+988|0;T=P+88|0;x=P+24|0;n=de[e+88>>2]|0;b=(me[n+63>>0]|0)<<8|(me[n+64>>0]|0);y=e+92|0;t=de[e+4>>2]|0;r=(me[n+58>>0]|0)<<8|(me[n+57>>0]|0)<<16|(me[n+59>>0]|0);i=t+r|0;n=(me[n+61>>0]|0)<<8|(me[n+60>>0]|0)<<16|(me[n+62>>0]|0);if(!n){k=0;ve=P;return k|0}de[y>>2]=i;de[e+96>>2]=i;de[e+104>>2]=n;de[e+100>>2]=t+(n+r);de[e+108>>2]=0;de[e+112>>2]=0;de[k+20>>2]=0;de[k>>2]=0;de[k+4>>2]=0;de[k+8>>2]=0;de[k+12>>2]=0;pe[k+16>>0]=0;if(dt(y,k)|0){r=0;i=-7;n=-7;while(1){de[w+(r<<2)>>2]=i;de[T+(r<<2)>>2]=n;t=(i|0)>6;r=r+1|0;if((r|0)==225)break;else{i=t?-7:i+1|0;n=(t&1)+n|0}}t=x;r=t+64|0;do{de[t>>2]=0;t=t+4|0}while((t|0)<(r|0));_=e+284|0;r=b*3|0;i=e+288|0;t=de[i>>2]|0;e:do{if((t|0)==(r|0))l=13;else{if(t>>>0<=r>>>0){do{if((de[e+292>>2]|0)>>>0>>0)if(nt(_,r,(t+1|0)==(r|0),2,0)|0){t=de[i>>2]|0;break}else{pe[e+296>>0]=1;t=0;break e}}while(0);Yr((de[_>>2]|0)+(t<<1)|0,0,r-t<<1|0)|0}de[i>>2]=r;l=13}}while(0);do{if((l|0)==13){if(!b){de[a>>2]=1154;de[a+4>>2]=903;de[a+8>>2]=1781;br(o,1100,a)|0;yr(o,s)|0;t=1;break}i=x+4|0;n=x+8|0;e=x+12|0;o=x+16|0;a=x+20|0;s=x+24|0;l=x+28|0;u=x+32|0;h=x+36|0;c=x+40|0;f=x+44|0;p=x+48|0;d=x+52|0;m=x+56|0;g=x+60|0;v=0;r=de[_>>2]|0;while(1){t=0;do{S=gt(y,k)|0;_=t<<1;E=x+(_<<2)|0;de[E>>2]=(de[E>>2]|0)+(de[w+(S<<2)>>2]|0)&7;_=x+((_|1)<<2)|0;de[_>>2]=(de[_>>2]|0)+(de[T+(S<<2)>>2]|0)&7;t=t+1|0}while((t|0)!=8);S=me[1729+(de[a>>2]|0)>>0]|0;$[r>>1]=(me[1729+(de[i>>2]|0)>>0]|0)<<3|(me[1729+(de[x>>2]|0)>>0]|0)|(me[1729+(de[n>>2]|0)>>0]|0)<<6|(me[1729+(de[e>>2]|0)>>0]|0)<<9|(me[1729+(de[o>>2]|0)>>0]|0)<<12|S<<15;E=me[1729+(de[c>>2]|0)>>0]|0;$[r+2>>1]=(me[1729+(de[s>>2]|0)>>0]|0)<<2|S>>>1|(me[1729+(de[l>>2]|0)>>0]|0)<<5|(me[1729+(de[u>>2]|0)>>0]|0)<<8|(me[1729+(de[h>>2]|0)>>0]|0)<<11|E<<14;$[r+4>>1]=(me[1729+(de[f>>2]|0)>>0]|0)<<1|E>>>2|(me[1729+(de[p>>2]|0)>>0]|0)<<4|(me[1729+(de[d>>2]|0)>>0]|0)<<7|(me[1729+(de[m>>2]|0)>>0]|0)<<10|(me[1729+(de[g>>2]|0)>>0]|0)<<13;v=v+1|0;if((v|0)==(b|0)){t=1;break}else r=r+6|0}}}while(0)}else t=0;ct(k);E=t;ve=P;return E|0}function Mt(e,t,r,i,n,o,a,s){e=e|0;t=t|0;r=r|0;i=i|0;n=n|0;o=o|0;a=a|0;s=s|0;var l=0,u=0,h=0,c=0,f=0,p=0,d=0,m=0,g=0,v=0,_=0,y=0,b=0,x=0,w=0,T=0,k=0,P=0,S=0,E=0,A=0,C=0,I=0,O=0,M=0,D=0,R=0,z=0,L=0,F=0,j=0,N=0,B=0,U=0,X=0,H=0,G=0,W=0,q=0,V=0,Y=0,Z=0,J=0,K=0,Q=0,$=0,ee=0,te=0,re=0,ie=0,ne=0,oe=0,ae=0,se=0,le=0,ue=0,he=0,ce=0,fe=0;he=ve;ve=ve+720|0;ue=he+184|0;se=he+168|0;ae=he+160|0;oe=he+144|0;ne=he+136|0;ie=he+120|0;re=he+112|0;ee=he+96|0;$=he+88|0;Q=he+72|0;K=he+64|0;J=he+48|0;Z=he+40|0;le=he+24|0;te=he+16|0;Y=he;q=he+208|0;V=he+192|0;N=e+240|0;B=de[N>>2]|0;H=e+256|0;G=de[H>>2]|0;r=pe[(de[e+88>>2]|0)+17>>0]|0;W=i>>>2;if(!(r<<24>>24)){ve=he;return 1}U=(s|0)==0;X=s+-1|0;M=(o&1|0)!=0;D=i<<1;R=e+92|0;z=e+116|0;L=e+140|0;F=e+236|0;j=a+-1|0;O=(n&1|0)!=0;I=e+188|0;P=e+252|0;S=W+1|0;E=W+2|0;A=W+3|0;C=j<<4;T=r&255;r=0;o=0;n=1;k=0;do{if(!U){x=de[t+(k<<2)>>2]|0;w=0;while(1){_=w&1;l=(_|0)==0;v=(_<<5^32)+-16|0;_=(_<<1^2)+-1|0;b=l?a:-1;u=l?0:j;e=(w|0)==(X|0);y=M&e;if((u|0)!=(b|0)){g=M&e^1;m=l?x:x+C|0;while(1){if((n|0)==1)n=gt(R,z)|0|512;d=n&7;n=n>>>3;l=me[1823+d>>0]|0;e=0;do{f=(gt(R,L)|0)+o|0;p=f-B|0;o=p>>31;o=o&f|p&~o;if((de[N>>2]|0)>>>0<=o>>>0){de[Y>>2]=1154;de[Y+4>>2]=903;de[Y+8>>2]=1781;br(q,1100,Y)|0;yr(q,te)|0}de[V+(e<<2)>>2]=de[(de[F>>2]|0)+(o<<2)>>2];e=e+1|0}while(e>>>0>>0);p=O&(u|0)==(j|0);if(y|p){f=0;do{h=_e(f,i)|0;e=m+h|0;l=(f|0)==0|g;c=f<<1;fe=(gt(R,I)|0)+r|0;ce=fe-G|0;r=ce>>31;r=r&fe|ce&~r;do{if(p){if(!l){ce=(gt(R,I)|0)+r|0;fe=ce-G|0;r=fe>>31;r=r&ce|fe&~r;break}de[e>>2]=de[V+((me[1831+(d<<2)+c>>0]|0)<<2)>>2];if((de[H>>2]|0)>>>0<=r>>>0){de[oe>>2]=1154;de[oe+4>>2]=903;de[oe+8>>2]=1781;br(q,1100,oe)|0;yr(q,ae)|0}de[m+(h+4)>>2]=de[(de[P>>2]|0)+(r<<2)>>2];ce=(gt(R,I)|0)+r|0;fe=ce-G|0;r=fe>>31;r=r&ce|fe&~r}else{if(!l){ce=(gt(R,I)|0)+r|0;fe=ce-G|0;r=fe>>31;r=r&ce|fe&~r;break}de[e>>2]=de[V+((me[1831+(d<<2)+c>>0]|0)<<2)>>2];if((de[H>>2]|0)>>>0<=r>>>0){de[ie>>2]=1154;de[ie+4>>2]=903;de[ie+8>>2]=1781;br(q,1100,ie)|0;yr(q,ne)|0}de[m+(h+4)>>2]=de[(de[P>>2]|0)+(r<<2)>>2];ce=(gt(R,I)|0)+r|0;fe=ce-G|0;r=fe>>31;r=r&ce|fe&~r;de[m+(h+8)>>2]=de[V+((me[(c|1)+(1831+(d<<2))>>0]|0)<<2)>>2];if((de[H>>2]|0)>>>0<=r>>>0){de[se>>2]=1154;de[se+4>>2]=903;de[se+8>>2]=1781;br(q,1100,se)|0;yr(q,ue)|0}de[m+(h+12)>>2]=de[(de[P>>2]|0)+(r<<2)>>2]}}while(0);f=f+1|0}while((f|0)!=2)}else{de[m>>2]=de[V+((me[1831+(d<<2)>>0]|0)<<2)>>2];ce=(gt(R,I)|0)+r|0;fe=ce-G|0;r=fe>>31;r=r&ce|fe&~r;if((de[H>>2]|0)>>>0<=r>>>0){de[le>>2]=1154;de[le+4>>2]=903;de[le+8>>2]=1781;br(q,1100,le)|0;yr(q,Z)|0}de[m+4>>2]=de[(de[P>>2]|0)+(r<<2)>>2];de[m+8>>2]=de[V+((me[1831+(d<<2)+1>>0]|0)<<2)>>2];ce=(gt(R,I)|0)+r|0;fe=ce-G|0;r=fe>>31;r=r&ce|fe&~r;if((de[H>>2]|0)>>>0<=r>>>0){de[J>>2]=1154;de[J+4>>2]=903;de[J+8>>2]=1781;br(q,1100,J)|0;yr(q,K)|0}de[m+12>>2]=de[(de[P>>2]|0)+(r<<2)>>2];de[m+(W<<2)>>2]=de[V+((me[1831+(d<<2)+2>>0]|0)<<2)>>2];ce=(gt(R,I)|0)+r|0;fe=ce-G|0;r=fe>>31;r=r&ce|fe&~r;if((de[H>>2]|0)>>>0<=r>>>0){de[Q>>2]=1154;de[Q+4>>2]=903;de[Q+8>>2]=1781;br(q,1100,Q)|0;yr(q,$)|0}de[m+(S<<2)>>2]=de[(de[P>>2]|0)+(r<<2)>>2];de[m+(E<<2)>>2]=de[V+((me[1831+(d<<2)+3>>0]|0)<<2)>>2];ce=(gt(R,I)|0)+r|0;fe=ce-G|0;r=fe>>31;r=r&ce|fe&~r;if((de[H>>2]|0)>>>0<=r>>>0){de[ee>>2]=1154;de[ee+4>>2]=903;de[ee+8>>2]=1781;br(q,1100,ee)|0;yr(q,re)|0}de[m+(A<<2)>>2]=de[(de[P>>2]|0)+(r<<2)>>2]}u=u+_|0;if((u|0)==(b|0))break;else m=m+v|0}}w=w+1|0;if((w|0)==(s|0))break;else x=x+D|0}}k=k+1|0}while((k|0)!=(T|0));ve=he;return 1}function Dt(e,t,r,i,n,o,a,s){e=e|0;t=t|0;r=r|0;i=i|0;n=n|0;o=o|0;a=a|0;s=s|0;var l=0,u=0,h=0,c=0,f=0,p=0,d=0,m=0,g=0,v=0,_=0,y=0,b=0,x=0,w=0,T=0,k=0,P=0,S=0,E=0,A=0,C=0,I=0,O=0,M=0,D=0,R=0,z=0,L=0,F=0,j=0,N=0,B=0,U=0,X=0,H=0,G=0,W=0,q=0,V=0,Y=0,Z=0,J=0,K=0,Q=0,$=0,ee=0,te=0,re=0,ie=0,ne=0,oe=0,ae=0,se=0,le=0,ue=0,he=0,ce=0,fe=0;ce=ve;ve=ve+640|0;le=ce+88|0;se=ce+72|0;ae=ce+64|0;oe=ce+48|0;ne=ce+40|0;he=ce+24|0;ue=ce+16|0;ie=ce;te=ce+128|0;re=ce+112|0;ee=ce+96|0;N=e+240|0;B=de[N>>2]|0;H=e+256|0;K=de[H>>2]|0;Q=e+272|0;$=de[Q>>2]|0;r=de[e+88>>2]|0;U=(me[r+63>>0]|0)<<8|(me[r+64>>0]|0);r=pe[r+17>>0]|0;if(!(r<<24>>24)){ve=ce;return 1}X=(s|0)==0;G=s+-1|0;W=i<<1;q=e+92|0;V=e+116|0;Y=a+-1|0;Z=e+212|0;J=e+188|0;j=(n&1|0)==0;F=(o&1|0)==0;O=e+288|0;M=e+284|0;D=e+252|0;R=e+140|0;z=e+236|0;L=e+164|0;C=e+268|0;I=Y<<5;E=r&255;r=0;n=0;o=0;e=0;l=1;A=0;do{if(!X){P=de[t+(A<<2)>>2]|0;S=0;while(1){T=S&1;u=(T|0)==0;w=(T<<6^64)+-32|0;T=(T<<1^2)+-1|0;k=u?a:-1;h=u?0:Y;if((h|0)!=(k|0)){x=F|(S|0)!=(G|0);b=u?P:P+I|0;while(1){if((l|0)==1)l=gt(q,V)|0|512;y=l&7;l=l>>>3;c=me[1823+y>>0]|0;u=0;do{v=(gt(q,L)|0)+n|0;_=v-$|0;n=_>>31;n=n&v|_&~n;if((de[Q>>2]|0)>>>0<=n>>>0){de[ie>>2]=1154;de[ie+4>>2]=903;de[ie+8>>2]=1781;br(te,1100,ie)|0;yr(te,ue)|0}de[ee+(u<<2)>>2]=ge[(de[C>>2]|0)+(n<<1)>>1];u=u+1|0}while(u>>>0>>0);u=0;do{v=(gt(q,R)|0)+e|0;_=v-B|0;e=_>>31;e=e&v|_&~e;if((de[N>>2]|0)>>>0<=e>>>0){de[he>>2]=1154;de[he+4>>2]=903;de[he+8>>2]=1781;br(te,1100,he)|0;yr(te,ne)|0}de[re+(u<<2)>>2]=de[(de[z>>2]|0)+(e<<2)>>2];u=u+1|0}while(u>>>0>>0);_=j|(h|0)!=(Y|0);g=0;v=b;while(1){m=x|(g|0)==0;d=g<<1;f=0;p=v;while(1){c=(gt(q,Z)|0)+r|0;u=c-U|0;r=u>>31;r=r&c|u&~r;u=(gt(q,J)|0)+o|0;c=u-K|0;o=c>>31;o=o&u|c&~o;if((_|(f|0)==0)&m){u=me[f+d+(1831+(y<<2))>>0]|0;c=r*3|0;if((de[O>>2]|0)>>>0<=c>>>0){de[oe>>2]=1154;de[oe+4>>2]=903;de[oe+8>>2]=1781;br(te,1100,oe)|0;yr(te,ae)|0}fe=de[M>>2]|0;de[p>>2]=(ge[fe+(c<<1)>>1]|0)<<16|de[ee+(u<<2)>>2];de[p+4>>2]=(ge[fe+(c+2<<1)>>1]|0)<<16|(ge[fe+(c+1<<1)>>1]|0);de[p+8>>2]=de[re+(u<<2)>>2];if((de[H>>2]|0)>>>0<=o>>>0){de[se>>2]=1154;de[se+4>>2]=903;de[se+8>>2]=1781;br(te,1100,se)|0;yr(te,le)|0}de[p+12>>2]=de[(de[D>>2]|0)+(o<<2)>>2]}f=f+1|0;if((f|0)==2)break;else p=p+16|0}g=g+1|0;if((g|0)==2)break;else v=v+i|0}h=h+T|0;if((h|0)==(k|0))break;else b=b+w|0}}S=S+1|0;if((S|0)==(s|0))break;else P=P+W|0}}A=A+1|0}while((A|0)!=(E|0));ve=ce;return 1}function Rt(e,t,r,i,n,o,a,s){e=e|0;t=t|0;r=r|0;i=i|0;n=n|0;o=o|0;a=a|0;s=s|0;var l=0,u=0,h=0,c=0,f=0,p=0,d=0,m=0,g=0,v=0,_=0,y=0,b=0,x=0,w=0,T=0,k=0,P=0,S=0,E=0,A=0,C=0,I=0,O=0,M=0,D=0,R=0,z=0,L=0,F=0,j=0,N=0,B=0,U=0,X=0,H=0,G=0,W=0,q=0,V=0,Y=0,Z=0,J=0,K=0;K=ve;ve=ve+608|0;Y=K+64|0;V=K+48|0;q=K+40|0;J=K+24|0;Z=K+16|0;W=K;G=K+88|0;H=K+72|0;D=e+272|0;R=de[D>>2]|0;r=de[e+88>>2]|0;z=(me[r+63>>0]|0)<<8|(me[r+64>>0]|0);r=pe[r+17>>0]|0;if(!(r<<24>>24)){ve=K;return 1}L=(s|0)==0;F=s+-1|0;j=i<<1;N=e+92|0;B=e+116|0;U=a+-1|0;X=e+212|0;M=(o&1|0)==0;C=e+288|0;I=e+284|0;O=e+164|0;E=e+268|0;A=U<<4;S=r&255;P=(n&1|0)!=0;r=0;o=0;e=1;k=0;do{if(!L){w=de[t+(k<<2)>>2]|0;T=0;while(1){b=T&1;n=(b|0)==0;y=(b<<5^32)+-16|0;b=(b<<1^2)+-1|0;x=n?a:-1;l=n?0:U;if((l|0)!=(x|0)){_=M|(T|0)!=(F|0);v=n?w:w+A|0;while(1){if((e|0)==1)e=gt(N,B)|0|512;g=e&7;e=e>>>3;u=me[1823+g>>0]|0;n=0;do{d=(gt(N,O)|0)+o|0;m=d-R|0;o=m>>31;o=o&d|m&~o;if((de[D>>2]|0)>>>0<=o>>>0){de[W>>2]=1154;de[W+4>>2]=903;de[W+8>>2]=1781;br(G,1100,W)|0;yr(G,Z)|0}de[H+(n<<2)>>2]=ge[(de[E>>2]|0)+(o<<1)>>1];n=n+1|0}while(n>>>0>>0);m=(l|0)==(U|0)&P;p=0;d=v;while(1){f=_|(p|0)==0;c=p<<1;n=(gt(N,X)|0)+r|0;h=n-z|0;u=h>>31;u=u&n|h&~u;if(f){r=me[1831+(g<<2)+c>>0]|0;n=u*3|0;if((de[C>>2]|0)>>>0<=n>>>0){de[J>>2]=1154;de[J+4>>2]=903;de[J+8>>2]=1781;br(G,1100,J)|0;yr(G,q)|0}h=de[I>>2]|0;de[d>>2]=(ge[h+(n<<1)>>1]|0)<<16|de[H+(r<<2)>>2];de[d+4>>2]=(ge[h+(n+2<<1)>>1]|0)<<16|(ge[h+(n+1<<1)>>1]|0)}h=d+8|0;n=(gt(N,X)|0)+u|0;u=n-z|0;r=u>>31;r=r&n|u&~r;if(!(m|f^1)){n=me[(c|1)+(1831+(g<<2))>>0]|0;u=r*3|0;if((de[C>>2]|0)>>>0<=u>>>0){de[V>>2]=1154;de[V+4>>2]=903;de[V+8>>2]=1781;br(G,1100,V)|0;yr(G,Y)|0}f=de[I>>2]|0;de[h>>2]=(ge[f+(u<<1)>>1]|0)<<16|de[H+(n<<2)>>2];de[d+12>>2]=(ge[f+(u+2<<1)>>1]|0)<<16|(ge[f+(u+1<<1)>>1]|0)}p=p+1|0;if((p|0)==2)break;else d=d+i|0}l=l+b|0;if((l|0)==(x|0))break;else v=v+y|0}}T=T+1|0;if((T|0)==(s|0))break;else w=w+j|0}}k=k+1|0}while((k|0)!=(S|0));ve=K;return 1}function zt(e,t,r,i,n,o,a,s){e=e|0;t=t|0;r=r|0;i=i|0;n=n|0;o=o|0;a=a|0;s=s|0;var l=0,u=0,h=0,c=0,f=0,p=0,d=0,m=0,g=0,v=0,_=0,y=0,b=0,x=0,w=0,T=0,k=0,P=0,S=0,E=0,A=0,C=0,I=0,O=0,M=0,D=0,R=0,z=0,L=0,F=0,j=0,N=0,B=0,U=0,X=0,H=0,G=0,W=0,q=0,V=0,Y=0,Z=0,J=0,K=0,Q=0,$=0,ee=0,te=0,re=0,ie=0,ne=0,oe=0,ae=0;ae=ve;ve=ve+640|0;ie=ae+88|0;re=ae+72|0;te=ae+64|0;ee=ae+48|0;$=ae+40|0;oe=ae+24|0;ne=ae+16|0;Q=ae;K=ae+128|0;Z=ae+112|0;J=ae+96|0;N=e+272|0;B=de[N>>2]|0;r=de[e+88>>2]|0;U=(me[r+63>>0]|0)<<8|(me[r+64>>0]|0);r=pe[r+17>>0]|0;if(!(r<<24>>24)){ve=ae;return 1}X=(s|0)==0;H=s+-1|0;G=i<<1;W=e+92|0;q=e+116|0;V=a+-1|0;Y=e+212|0;j=(n&1|0)==0;F=(o&1|0)==0;R=e+288|0;z=e+284|0;L=e+164|0;M=e+268|0;D=V<<5;I=r&255;r=0;n=0;o=0;e=0;l=1;O=0;do{if(!X){A=de[t+(O<<2)>>2]|0;C=0;while(1){S=C&1;u=(S|0)==0;P=(S<<6^64)+-32|0;S=(S<<1^2)+-1|0;E=u?a:-1;h=u?0:V;if((h|0)!=(E|0)){k=F|(C|0)!=(H|0);T=u?A:A+D|0;while(1){if((l|0)==1)l=gt(W,q)|0|512;w=l&7;l=l>>>3;c=me[1823+w>>0]|0;u=0;do{b=(gt(W,L)|0)+e|0;x=b-B|0;e=x>>31;e=e&b|x&~e;if((de[N>>2]|0)>>>0<=e>>>0){de[Q>>2]=1154;de[Q+4>>2]=903;de[Q+8>>2]=1781;br(K,1100,Q)|0;yr(K,ne)|0}de[Z+(u<<2)>>2]=ge[(de[M>>2]|0)+(e<<1)>>1];u=u+1|0}while(u>>>0>>0);u=0;do{b=(gt(W,L)|0)+n|0;x=b-B|0;n=x>>31;n=n&b|x&~n;if((de[N>>2]|0)>>>0<=n>>>0){de[oe>>2]=1154;de[oe+4>>2]=903;de[oe+8>>2]=1781;br(K,1100,oe)|0;yr(K,$)|0}de[J+(u<<2)>>2]=ge[(de[M>>2]|0)+(n<<1)>>1];u=u+1|0}while(u>>>0>>0);x=j|(h|0)!=(V|0);y=0;b=T;while(1){_=k|(y|0)==0;v=y<<1;m=0;g=b;while(1){d=(gt(W,Y)|0)+o|0;p=d-U|0;o=p>>31;o=o&d|p&~o;p=(gt(W,Y)|0)+r|0;d=p-U|0;r=d>>31;r=r&p|d&~r;if((x|(m|0)==0)&_){p=me[m+v+(1831+(w<<2))>>0]|0;d=o*3|0;u=de[R>>2]|0;if(u>>>0<=d>>>0){de[ee>>2]=1154;de[ee+4>>2]=903;de[ee+8>>2]=1781;br(K,1100,ee)|0;yr(K,te)|0;u=de[R>>2]|0}c=de[z>>2]|0;f=r*3|0;if(u>>>0>f>>>0)u=c;else{de[re>>2]=1154;de[re+4>>2]=903;de[re+8>>2]=1781;br(K,1100,re)|0;yr(K,ie)|0;u=de[z>>2]|0}de[g>>2]=(ge[c+(d<<1)>>1]|0)<<16|de[Z+(p<<2)>>2];de[g+4>>2]=(ge[c+(d+2<<1)>>1]|0)<<16|(ge[c+(d+1<<1)>>1]|0);de[g+8>>2]=(ge[u+(f<<1)>>1]|0)<<16|de[J+(p<<2)>>2];de[g+12>>2]=(ge[u+(f+2<<1)>>1]|0)<<16|(ge[u+(f+1<<1)>>1]|0)}m=m+1|0;if((m|0)==2)break;else g=g+16|0}y=y+1|0;if((y|0)==2)break;else b=b+i|0}h=h+S|0;if((h|0)==(E|0))break;else T=T+P|0}}C=C+1|0;if((C|0)==(s|0))break;else A=A+G|0}}O=O+1|0}while((O|0)!=(I|0));ve=ae;return 1}function Lt(e){e=e|0;var t=0,r=0,i=0,n=0,o=0,a=0,s=0,l=0,u=0,h=0,c=0,f=0;f=ve;ve=ve+608|0;c=f+88|0;h=f+72|0;l=f+64|0;s=f+48|0;o=f+40|0;a=f+24|0;n=f+16|0;i=f;u=f+96|0;de[e>>2]=0;t=e+284|0;r=de[t>>2]|0;if(r){if(!(r&7))Di[de[104>>2]&1](r,0,0,1,de[27]|0)|0;else{de[i>>2]=1154;de[i+4>>2]=2499;de[i+8>>2]=1516;br(u,1100,i)|0;yr(u,n)|0}de[t>>2]=0;de[e+288>>2]=0;de[e+292>>2]=0}pe[e+296>>0]=0;t=e+268|0;r=de[t>>2]|0;if(r){if(!(r&7))Di[de[104>>2]&1](r,0,0,1,de[27]|0)|0;else{de[a>>2]=1154;de[a+4>>2]=2499;de[a+8>>2]=1516;br(u,1100,a)|0;yr(u,o)|0}de[t>>2]=0;de[e+272>>2]=0;de[e+276>>2]=0}pe[e+280>>0]=0;t=e+252|0;r=de[t>>2]|0;if(r){if(!(r&7))Di[de[104>>2]&1](r,0,0,1,de[27]|0)|0;else{de[s>>2]=1154;de[s+4>>2]=2499;de[s+8>>2]=1516;br(u,1100,s)|0;yr(u,l)|0}de[t>>2]=0;de[e+256>>2]=0;de[e+260>>2]=0}pe[e+264>>0]=0;t=e+236|0;r=de[t>>2]|0;if(!r){c=e+248|0;pe[c>>0]=0;c=e+212|0;ct(c);c=e+188|0;ct(c);c=e+164|0;ct(c);c=e+140|0;ct(c);c=e+116|0;ct(c);ve=f;return}if(!(r&7))Di[de[104>>2]&1](r,0,0,1,de[27]|0)|0;else{de[h>>2]=1154;de[h+4>>2]=2499;de[h+8>>2]=1516;br(u,1100,h)|0;yr(u,c)|0}de[t>>2]=0;de[e+240>>2]=0;de[e+244>>2]=0;c=e+248|0;pe[c>>0]=0;c=e+212|0;ct(c);c=e+188|0;ct(c);c=e+164|0;ct(c);c=e+140|0;ct(c);c=e+116|0;ct(c);ve=f;return}function Ft(e,t){e=e|0;t=t|0;var r=0;r=ve;ve=ve+16|0;de[r>>2]=t;t=de[63]|0;xr(t,e,r)|0;vr(10,t)|0;Xe()}function jt(){var e=0,t=0;e=ve;ve=ve+16|0;if(!(Le(200,2)|0)){t=Re(de[49]|0)|0;ve=e;return t|0}else Ft(2090,e);return 0}function Nt(e){e=e|0;Ur(e);return}function Bt(e){e=e|0;var t=0;t=ve;ve=ve+16|0;Oi[e&3]();Ft(2139,t)}function Ut(){var e=0,t=0;e=jt()|0;if(((e|0)!=0?(t=de[e>>2]|0,(t|0)!=0):0)?(e=t+48|0,(de[e>>2]&-256|0)==1126902528?(de[e+4>>2]|0)==1129074247:0):0)Bt(de[t+12>>2]|0);t=de[28]|0;de[28]=t+0;Bt(t)}function Xt(e){e=e|0;return}function Ht(e){e=e|0;return}function Gt(e){e=e|0;return}function Wt(e){e=e|0;return}function qt(e){e=e|0;Nt(e);return}function Vt(e){e=e|0;Nt(e);return}function Yt(e,t,r){e=e|0;t=t|0;r=r|0;var i=0,n=0,o=0,a=0;a=ve;ve=ve+64|0;o=a;if((e|0)!=(t|0))if((t|0)!=0?(n=Qt(t,24,40,0)|0,(n|0)!=0):0){t=o;i=t+56|0;do{de[t>>2]=0;t=t+4|0}while((t|0)<(i|0));de[o>>2]=n;de[o+8>>2]=e;de[o+12>>2]=-1;de[o+48>>2]=1;Ri[de[(de[n>>2]|0)+28>>2]&3](n,o,de[r>>2]|0,1);if((de[o+24>>2]|0)==1){de[r>>2]=de[o+16>>2];t=1}else t=0}else t=0;else t=1;ve=a;return t|0}function Zt(e,t,r,i){e=e|0;t=t|0;r=r|0;i=i|0;var n=0;e=t+16|0;n=de[e>>2]|0;do{if(n){if((n|0)!=(r|0)){i=t+36|0;de[i>>2]=(de[i>>2]|0)+1;de[t+24>>2]=2;pe[t+54>>0]=1;break}e=t+24|0;if((de[e>>2]|0)==2)de[e>>2]=i}else{de[e>>2]=r;de[t+24>>2]=i;de[t+36>>2]=1}}while(0);return}function Jt(e,t,r,i){e=e|0;t=t|0;r=r|0;i=i|0;if((e|0)==(de[t+8>>2]|0))Zt(0,t,r,i);return}function Kt(e,t,r,i){e=e|0;t=t|0;r=r|0;i=i|0;if((e|0)==(de[t+8>>2]|0))Zt(0,t,r,i);else{e=de[e+8>>2]|0;Ri[de[(de[e>>2]|0)+28>>2]&3](e,t,r,i)}return}function Qt(e,t,r,i){e=e|0;t=t|0;r=r|0;i=i|0;var n=0,o=0,a=0,s=0,l=0,u=0,h=0,c=0,f=0,p=0;p=ve;ve=ve+64|0;f=p;c=de[e>>2]|0;h=e+(de[c+-8>>2]|0)|0;c=de[c+-4>>2]|0;de[f>>2]=r;de[f+4>>2]=e;de[f+8>>2]=t;de[f+12>>2]=i;i=f+16|0;e=f+20|0;t=f+24|0;n=f+28|0;o=f+32|0;a=f+40|0;s=(c|0)==(r|0);l=i;u=l+36|0;do{de[l>>2]=0;l=l+4|0}while((l|0)<(u|0));$[i+36>>1]=0;pe[i+38>>0]=0;e:do{if(s){de[f+48>>2]=1;Mi[de[(de[r>>2]|0)+20>>2]&3](r,f,h,h,1,0);i=(de[t>>2]|0)==1?h:0}else{Ei[de[(de[c>>2]|0)+24>>2]&3](c,f,h,1,0);switch(de[f+36>>2]|0){case 0:{i=(de[a>>2]|0)==1&(de[n>>2]|0)==1&(de[o>>2]|0)==1?de[e>>2]|0:0;break e}case 1:break;default:{i=0;break e}}if((de[t>>2]|0)!=1?!((de[a>>2]|0)==0&(de[n>>2]|0)==1&(de[o>>2]|0)==1):0){i=0;break}i=de[i>>2]|0}}while(0);ve=p;return i|0}function $t(e,t,r,i,n){e=e|0;t=t|0;r=r|0;i=i|0;n=n|0;pe[t+53>>0]=1;do{if((de[t+4>>2]|0)==(i|0)){pe[t+52>>0]=1;i=t+16|0;e=de[i>>2]|0;if(!e){de[i>>2]=r;de[t+24>>2]=n;de[t+36>>2]=1;if(!((n|0)==1?(de[t+48>>2]|0)==1:0))break;pe[t+54>>0]=1;break}if((e|0)!=(r|0)){n=t+36|0;de[n>>2]=(de[n>>2]|0)+1;pe[t+54>>0]=1;break}e=t+24|0;i=de[e>>2]|0;if((i|0)==2){de[e>>2]=n;i=n}if((i|0)==1?(de[t+48>>2]|0)==1:0)pe[t+54>>0]=1}}while(0);return}function er(e,t,r,i,n){e=e|0;t=t|0;r=r|0;i=i|0;n=n|0;var o=0,a=0,s=0,l=0;e:do{if((e|0)==(de[t+8>>2]|0)){if((de[t+4>>2]|0)==(r|0)?(o=t+28|0,(de[o>>2]|0)!=1):0)de[o>>2]=i}else{if((e|0)!=(de[t>>2]|0)){s=de[e+8>>2]|0;Ei[de[(de[s>>2]|0)+24>>2]&3](s,t,r,i,n);break}if((de[t+16>>2]|0)!=(r|0)?(a=t+20|0,(de[a>>2]|0)!=(r|0)):0){de[t+32>>2]=i;i=t+44|0;if((de[i>>2]|0)==4)break;o=t+52|0;pe[o>>0]=0;l=t+53|0;pe[l>>0]=0;e=de[e+8>>2]|0;Mi[de[(de[e>>2]|0)+20>>2]&3](e,t,r,r,1,n);if(pe[l>>0]|0){if(!(pe[o>>0]|0)){o=1;s=13}}else{o=0;s=13}do{if((s|0)==13){de[a>>2]=r;l=t+40|0;de[l>>2]=(de[l>>2]|0)+1;if((de[t+36>>2]|0)==1?(de[t+24>>2]|0)==2:0){pe[t+54>>0]=1;if(o)break}else s=16;if((s|0)==16?o:0)break;de[i>>2]=4;break e}}while(0);de[i>>2]=3;break}if((i|0)==1)de[t+32>>2]=1}}while(0);return}function tr(e,t,r,i,n){e=e|0;t=t|0;r=r|0;i=i|0;n=n|0;var o=0,a=0;do{if((e|0)==(de[t+8>>2]|0)){if((de[t+4>>2]|0)==(r|0)?(a=t+28|0,(de[a>>2]|0)!=1):0)de[a>>2]=i}else if((e|0)==(de[t>>2]|0)){if((de[t+16>>2]|0)!=(r|0)?(o=t+20|0,(de[o>>2]|0)!=(r|0)):0){de[t+32>>2]=i;de[o>>2]=r;n=t+40|0;de[n>>2]=(de[n>>2]|0)+1;if((de[t+36>>2]|0)==1?(de[t+24>>2]|0)==2:0)pe[t+54>>0]=1;de[t+44>>2]=4;break}if((i|0)==1)de[t+32>>2]=1}}while(0);return}function rr(e,t,r,i,n,o){e=e|0;t=t|0;r=r|0;i=i|0;n=n|0;o=o|0;if((e|0)==(de[t+8>>2]|0))$t(0,t,r,i,n);else{e=de[e+8>>2]|0;Mi[de[(de[e>>2]|0)+20>>2]&3](e,t,r,i,n,o)}return}function ir(e,t,r,i,n,o){e=e|0;t=t|0;r=r|0;i=i|0;n=n|0;o=o|0;if((e|0)==(de[t+8>>2]|0))$t(0,t,r,i,n);return}function nr(e,t,r){e=e|0;t=t|0;r=r|0;var i=0,n=0;n=ve;ve=ve+16|0;i=n;de[i>>2]=de[r>>2];e=Si[de[(de[e>>2]|0)+16>>2]&7](e,t,i)|0;if(e)de[r>>2]=de[i>>2];ve=n;return e&1|0}function or(e){e=e|0;if(!e)e=0;else e=(Qt(e,24,72,0)|0)!=0;return e&1|0}function ar(){var e=0,t=0,r=0,i=0,n=0,o=0,a=0,s=0;n=ve;ve=ve+48|0;a=n+32|0;r=n+24|0;s=n+16|0;o=n;n=n+36|0;e=jt()|0;if((e|0)!=0?(i=de[e>>2]|0,(i|0)!=0):0){e=i+48|0;t=de[e>>2]|0;e=de[e+4>>2]|0;if(!((t&-256|0)==1126902528&(e|0)==1129074247)){de[r>>2]=de[51];Ft(2368,r)}if((t|0)==1126902529&(e|0)==1129074247)e=de[i+44>>2]|0;else e=i+80|0;de[n>>2]=e;i=de[i>>2]|0;e=de[i+4>>2]|0;if(Si[de[(de[8>>2]|0)+16>>2]&7](8,i,n)|0){s=de[n>>2]|0;n=de[51]|0;s=Ci[de[(de[s>>2]|0)+8>>2]&1](s)|0;de[o>>2]=n;de[o+4>>2]=e;de[o+8>>2]=s;Ft(2282,o)}else{de[s>>2]=de[51];de[s+4>>2]=e;Ft(2327,s)}}Ft(2406,a)}function sr(){var e=0;e=ve;ve=ve+16|0;if(!(Fe(196,6)|0)){ve=e;return}else Ft(2179,e)}function lr(e){e=e|0;var t=0;t=ve;ve=ve+16|0;Ur(e);if(!(Be(de[49]|0,0)|0)){ve=t;return}else Ft(2229,t)}function ur(e){e=e|0;var t=0,r=0;t=0;while(1){if((me[2427+t>>0]|0)==(e|0)){r=2;break}t=t+1|0;if((t|0)==87){t=87;e=2515;r=5;break}}if((r|0)==2)if(!t)e=2515;else{e=2515;r=5}if((r|0)==5)while(1){r=e;while(1){e=r+1|0;if(!(pe[r>>0]|0))break;else r=e}t=t+-1|0;if(!t)break;else r=5}return e|0}function hr(){var e=0;if(!(de[52]|0))e=264;else{e=(ze()|0)+60|0;e=de[e>>2]|0}return e|0}function cr(e){e=e|0;var t=0;if(e>>>0>4294963200){t=hr()|0;de[t>>2]=0-e;e=-1}return e|0}function fr(e,t){e=+e;t=t|0;var r=0,i=0,n=0;ee[te>>3]=e;r=de[te>>2]|0;i=de[te+4>>2]|0;n=Zr(r|0,i|0,52)|0;n=n&2047;switch(n|0){case 0:{if(e!=0.0){e=+fr(e*18446744073709552.0e3,t);r=(de[t>>2]|0)+-64|0}else r=0;de[t>>2]=r;break}case 2047:break;default:{de[t>>2]=n+-1022;de[te>>2]=r;de[te+4>>2]=i&-2146435073|1071644672;e=+ee[te>>3]}}return+e}function pr(e,t){e=+e;t=t|0;return+ +fr(e,t)}function dr(e,t,r){e=e|0;t=t|0;r=r|0;do{if(e){if(t>>>0<128){pe[e>>0]=t;e=1;break}if(t>>>0<2048){pe[e>>0]=t>>>6|192;pe[e+1>>0]=t&63|128;e=2;break}if(t>>>0<55296|(t&-8192|0)==57344){pe[e>>0]=t>>>12|224;pe[e+1>>0]=t>>>6&63|128;pe[e+2>>0]=t&63|128;e=3;break}if((t+-65536|0)>>>0<1048576){pe[e>>0]=t>>>18|240;pe[e+1>>0]=t>>>12&63|128;pe[e+2>>0]=t>>>6&63|128;pe[e+3>>0]=t&63|128;e=4;break}else{e=hr()|0;de[e>>2]=84;e=-1;break}}else e=1}while(0);return e|0}function mr(e,t){e=e|0;t=t|0;if(!e)e=0;else e=dr(e,t,0)|0;return e|0}function gr(e){e=e|0;var t=0,r=0;do{if(e){if((de[e+76>>2]|0)<=-1){t=Dr(e)|0;break}r=(kr(e)|0)==0;t=Dr(e)|0;if(!r)Pr(e)}else{if(!(de[65]|0))t=0;else t=gr(de[65]|0)|0;Ue(236);e=de[58]|0;if(e)do{if((de[e+76>>2]|0)>-1)r=kr(e)|0;else r=0;if((de[e+20>>2]|0)>>>0>(de[e+28>>2]|0)>>>0)t=Dr(e)|0|t;if(r)Pr(e);e=de[e+56>>2]|0}while((e|0)!=0);je(236)}}while(0);return t|0}function vr(e,t){e=e|0;t=t|0;var r=0,i=0,n=0,o=0,a=0;if((de[t+76>>2]|0)>=0?(kr(t)|0)!=0:0){if((pe[t+75>>0]|0)!=(e|0)?(i=t+20|0,n=de[i>>2]|0,n>>>0<(de[t+16>>2]|0)>>>0):0){de[i>>2]=n+1;pe[n>>0]=e;r=e&255}else r=Sr(t,e)|0;Pr(t)}else a=3;do{if((a|0)==3){if((pe[t+75>>0]|0)!=(e|0)?(o=t+20|0,r=de[o>>2]|0,r>>>0<(de[t+16>>2]|0)>>>0):0){de[o>>2]=r+1;pe[r>>0]=e;r=e&255;break}r=Sr(t,e)|0}}while(0);return r|0}function _r(e,t,r){e=e|0;t=t|0;r=r|0;var i=0,n=0,o=0,a=0;i=r+16|0;n=de[i>>2]|0;if(!n)if(!(Or(r)|0)){n=de[i>>2]|0;o=4}else i=0;else o=4;e:do{if((o|0)==4){a=r+20|0;o=de[a>>2]|0;if((n-o|0)>>>0>>0){i=Si[de[r+36>>2]&7](r,e,t)|0;break}t:do{if((pe[r+75>>0]|0)>-1){i=t;while(1){if(!i){n=o;i=0;break t}n=i+-1|0;if((pe[e+n>>0]|0)==10)break;else i=n}if((Si[de[r+36>>2]&7](r,e,i)|0)>>>0>>0)break e;t=t-i|0;e=e+i|0;n=de[a>>2]|0}else{n=o;i=0}}while(0);Qr(n|0,e|0,t|0)|0;de[a>>2]=(de[a>>2]|0)+t;i=i+t|0}}while(0);return i|0}function yr(e,t){e=e|0;t=t|0;var r=0,i=0;r=ve;ve=ve+16|0;i=r;de[i>>2]=t;t=xr(de[64]|0,e,i)|0;ve=r;return t|0}function br(e,t,r){e=e|0;t=t|0;r=r|0;var i=0,n=0;i=ve;ve=ve+16|0;n=i;de[n>>2]=r;r=Tr(e,t,n)|0;ve=i;return r|0}function xr(e,t,r){e=e|0;t=t|0;r=r|0;var i=0,n=0,o=0,a=0,s=0,l=0,u=0,h=0,c=0,f=0,p=0,d=0,m=0;m=ve;ve=ve+224|0;c=m+120|0;d=m+80|0;p=m;f=m+136|0;i=d;n=i+40|0;do{de[i>>2]=0;i=i+4|0}while((i|0)<(n|0));de[c>>2]=de[r>>2];if((Rr(0,t,c,p,d)|0)<0)r=-1;else{if((de[e+76>>2]|0)>-1)u=kr(e)|0;else u=0;r=de[e>>2]|0;h=r&32;if((pe[e+74>>0]|0)<1)de[e>>2]=r&-33;r=e+48|0;if(!(de[r>>2]|0)){n=e+44|0;o=de[n>>2]|0;de[n>>2]=f;a=e+28|0;de[a>>2]=f;s=e+20|0;de[s>>2]=f;de[r>>2]=80;l=e+16|0;de[l>>2]=f+80;i=Rr(e,t,c,p,d)|0;if(o){Si[de[e+36>>2]&7](e,0,0)|0;i=(de[s>>2]|0)==0?-1:i;de[n>>2]=o;de[r>>2]=0;de[l>>2]=0;de[a>>2]=0;de[s>>2]=0}}else i=Rr(e,t,c,p,d)|0;r=de[e>>2]|0;de[e>>2]=r|h;if(u)Pr(e);r=(r&32|0)==0?i:-1}ve=m;return r|0}function wr(e,t,r,i){e=e|0;t=t|0;r=r|0;i=i|0;var n=0,o=0,a=0,s=0,l=0,u=0,h=0;h=ve;ve=ve+128|0;n=h+112|0;u=h;o=u;a=268;s=o+112|0;do{de[o>>2]=de[a>>2];o=o+4|0;a=a+4|0}while((o|0)<(s|0));if((t+-1|0)>>>0>2147483646)if(!t){t=1;l=4}else{t=hr()|0;de[t>>2]=75;t=-1}else{n=e;l=4}if((l|0)==4){l=-2-n|0;l=t>>>0>l>>>0?l:t;de[u+48>>2]=l;e=u+20|0;de[e>>2]=n;de[u+44>>2]=n;t=n+l|0;n=u+16|0;de[n>>2]=t;de[u+28>>2]=t;t=xr(u,r,i)|0;if(l){r=de[e>>2]|0;pe[r+(((r|0)==(de[n>>2]|0))<<31>>31)>>0]=0}}ve=h;return t|0}function Tr(e,t,r){e=e|0;t=t|0;r=r|0;return wr(e,2147483647,t,r)|0}function kr(e){e=e|0;return 0}function Pr(e){e=e|0;return}function Sr(e,t){e=e|0;t=t|0;var r=0,i=0,n=0,o=0,a=0,s=0,l=0;l=ve;ve=ve+16|0;s=l;a=t&255;pe[s>>0]=a;i=e+16|0;n=de[i>>2]|0;if(!n)if(!(Or(e)|0)){n=de[i>>2]|0;o=4}else r=-1;else o=4;do{if((o|0)==4){i=e+20|0;o=de[i>>2]|0;if(o>>>0>>0?(r=t&255,(r|0)!=(pe[e+75>>0]|0)):0){de[i>>2]=o+1;pe[o>>0]=a;break}if((Si[de[e+36>>2]&7](e,s,1)|0)==1)r=me[s>>0]|0;else r=-1}}while(0);ve=l;return r|0}function Er(e){e=e|0;var t=0,r=0;t=ve;ve=ve+16|0;r=t;de[r>>2]=de[e+60>>2];e=cr(Se(6,r|0)|0)|0;ve=t;return e|0}function Ar(e,t,r){e=e|0;t=t|0;r=r|0;var i=0,n=0,o=0;n=ve;ve=ve+32|0;o=n;i=n+20|0;de[o>>2]=de[e+60>>2];de[o+4>>2]=0;de[o+8>>2]=t;de[o+12>>2]=i;de[o+16>>2]=r;if((cr(We(140,o|0)|0)|0)<0){de[i>>2]=-1;e=-1}else e=de[i>>2]|0;ve=n;return e|0}function Cr(e,t,r){e=e|0;t=t|0;r=r|0;var i=0,n=0,o=0,a=0,s=0,l=0,u=0,h=0,c=0,f=0,p=0,d=0;d=ve;ve=ve+48|0;c=d+16|0;h=d;i=d+32|0;f=e+28|0;n=de[f>>2]|0;de[i>>2]=n;p=e+20|0;n=(de[p>>2]|0)-n|0;de[i+4>>2]=n;de[i+8>>2]=t;de[i+12>>2]=r;l=e+60|0;u=e+44|0;t=2;n=n+r|0;while(1){if(!(de[52]|0)){de[c>>2]=de[l>>2];de[c+4>>2]=i;de[c+8>>2]=t;a=cr(qe(146,c|0)|0)|0}else{He(7,e|0);de[h>>2]=de[l>>2];de[h+4>>2]=i;de[h+8>>2]=t;a=cr(qe(146,h|0)|0)|0;ke(0)}if((n|0)==(a|0)){n=6;break}if((a|0)<0){n=8;break}n=n-a|0;o=de[i+4>>2]|0;if(a>>>0<=o>>>0)if((t|0)==2){de[f>>2]=(de[f>>2]|0)+a;s=o;t=2}else s=o;else{s=de[u>>2]|0;de[f>>2]=s;de[p>>2]=s;s=de[i+12>>2]|0;a=a-o|0;i=i+8|0;t=t+-1|0}de[i>>2]=(de[i>>2]|0)+a;de[i+4>>2]=s-a}if((n|0)==6){c=de[u>>2]|0;de[e+16>>2]=c+(de[e+48>>2]|0);e=c;de[f>>2]=e;de[p>>2]=e}else if((n|0)==8){de[e+16>>2]=0;de[f>>2]=0;de[p>>2]=0;de[e>>2]=de[e>>2]|32;if((t|0)==2)r=0;else r=r-(de[i+4>>2]|0)|0}ve=d;return r|0}function Ir(e,t,r){e=e|0;t=t|0;r=r|0;var i=0,n=0;n=ve;ve=ve+80|0;i=n;de[e+36>>2]=3;if((de[e>>2]&64|0)==0?(de[i>>2]=de[e+60>>2],de[i+4>>2]=21505,de[i+8>>2]=n+12,(Pe(54,i|0)|0)!=0):0)pe[e+75>>0]=-1;i=Cr(e,t,r)|0;ve=n;return i|0}function Or(e){e=e|0;var t=0,r=0;t=e+74|0;r=pe[t>>0]|0;pe[t>>0]=r+255|r;t=de[e>>2]|0;if(!(t&8)){de[e+8>>2]=0;de[e+4>>2]=0;t=de[e+44>>2]|0;de[e+28>>2]=t;de[e+20>>2]=t;de[e+16>>2]=t+(de[e+48>>2]|0);t=0}else{de[e>>2]=t|32;t=-1}return t|0}function Mr(e,t,r){e=e|0;t=t|0;r=r|0;var i=0,n=0,o=0,a=0;o=t&255;i=(r|0)!=0;e:do{if(i&(e&3|0)!=0){n=t&255;while(1){if((pe[e>>0]|0)==n<<24>>24){a=6;break e}e=e+1|0;r=r+-1|0;i=(r|0)!=0;if(!(i&(e&3|0)!=0)){a=5;break}}}else a=5}while(0);if((a|0)==5)if(i)a=6;else r=0;e:do{if((a|0)==6){n=t&255;if((pe[e>>0]|0)!=n<<24>>24){i=_e(o,16843009)|0;t:do{if(r>>>0>3)while(1){o=de[e>>2]^i;if((o&-2139062144^-2139062144)&o+-16843009)break;e=e+4|0;r=r+-4|0;if(r>>>0<=3){a=11;break t}}else a=11}while(0);if((a|0)==11)if(!r){r=0;break}while(1){if((pe[e>>0]|0)==n<<24>>24)break e;e=e+1|0;r=r+-1|0;if(!r){r=0;break}}}}}while(0);return((r|0)!=0?e:0)|0}function Dr(e){e=e|0;var t=0,r=0,i=0,n=0,o=0,a=0;t=e+20|0;o=e+28|0;if((de[t>>2]|0)>>>0>(de[o>>2]|0)>>>0?(Si[de[e+36>>2]&7](e,0,0)|0,(de[t>>2]|0)==0):0)t=-1;else{a=e+4|0;r=de[a>>2]|0;i=e+8|0;n=de[i>>2]|0;if(r>>>0>>0)Si[de[e+40>>2]&7](e,r-n|0,1)|0;de[e+16>>2]=0;de[o>>2]=0;de[t>>2]=0;de[i>>2]=0;de[a>>2]=0;t=0}return t|0}function Rr(e,t,r,i,n){e=e|0;t=t|0;r=r|0;i=i|0;n=n|0;var o=0,a=0,s=0,l=0,u=0.0,h=0,c=0,f=0,p=0,d=0.0,m=0,g=0,v=0,_=0,y=0,b=0,x=0,w=0,T=0,k=0,P=0,S=0,E=0,A=0,C=0,I=0,O=0,M=0,D=0,R=0,z=0,L=0,F=0,j=0,N=0,B=0,U=0,X=0,H=0,G=0,W=0,q=0,V=0,Y=0,Z=0,J=0,K=0,Q=0;Q=ve;ve=ve+624|0;V=Q+24|0;Z=Q+16|0;Y=Q+588|0;X=Q+576|0;q=Q;N=Q+536|0;K=Q+8|0;J=Q+528|0;I=(e|0)!=0;O=N+40|0;j=O;N=N+39|0;B=K+4|0;U=X+12|0;X=X+11|0;H=Y;G=U;W=G-H|0;M=-2-H|0;D=G+2|0;R=V+288|0;z=Y+9|0;L=z;F=Y+8|0;o=0;m=t;a=0;t=0;e:while(1){do{if((o|0)>-1)if((a|0)>(2147483647-o|0)){o=hr()|0;de[o>>2]=75;o=-1;break}else{o=a+o|0;break}}while(0);a=pe[m>>0]|0;if(!(a<<24>>24)){C=245;break}else s=m;t:while(1){switch(a<<24>>24){case 37:{a=s;C=9;break t}case 0:{a=s;break t}default:{}}A=s+1|0;a=pe[A>>0]|0;s=A}t:do{if((C|0)==9)while(1){C=0;if((pe[a+1>>0]|0)!=37)break t;s=s+1|0;a=a+2|0;if((pe[a>>0]|0)==37)C=9;else break}}while(0);v=s-m|0;if(I?(de[e>>2]&32|0)==0:0)_r(m,v,e)|0;if((s|0)!=(m|0)){m=a;a=v;continue}h=a+1|0;s=pe[h>>0]|0;l=(s<<24>>24)+-48|0;if(l>>>0<10){A=(pe[a+2>>0]|0)==36;h=A?a+3|0:h;s=pe[h>>0]|0;p=A?l:-1;t=A?1:t}else p=-1;a=s<<24>>24;t:do{if((a&-32|0)==32){l=0;while(1){if(!(1<>24)+-32|l;h=h+1|0;s=pe[h>>0]|0;a=s<<24>>24;if((a&-32|0)!=32){c=l;a=h;break}}}else{c=0;a=h}}while(0);do{if(s<<24>>24==42){l=a+1|0;s=(pe[l>>0]|0)+-48|0;if(s>>>0<10?(pe[a+2>>0]|0)==36:0){de[n+(s<<2)>>2]=10;t=1;a=a+3|0;s=de[i+((pe[l>>0]|0)+-48<<3)>>2]|0}else{if(t){o=-1;break e}if(!I){g=c;a=l;t=0;A=0;break}t=(de[r>>2]|0)+(4-1)&~(4-1);s=de[t>>2]|0;de[r>>2]=t+4;t=0;a=l}if((s|0)<0){g=c|8192;A=0-s|0}else{g=c;A=s}}else{l=(s<<24>>24)+-48|0;if(l>>>0<10){s=0;do{s=(s*10|0)+l|0;a=a+1|0;l=(pe[a>>0]|0)+-48|0}while(l>>>0<10);if((s|0)<0){o=-1;break e}else{g=c;A=s}}else{g=c;A=0}}}while(0);t:do{if((pe[a>>0]|0)==46){l=a+1|0;s=pe[l>>0]|0;if(s<<24>>24!=42){h=(s<<24>>24)+-48|0;if(h>>>0<10){a=l;s=0}else{a=l;h=0;break}while(1){s=(s*10|0)+h|0;a=a+1|0;h=(pe[a>>0]|0)+-48|0;if(h>>>0>=10){h=s;break t}}}l=a+2|0;s=(pe[l>>0]|0)+-48|0;if(s>>>0<10?(pe[a+3>>0]|0)==36:0){de[n+(s<<2)>>2]=10;a=a+4|0;h=de[i+((pe[l>>0]|0)+-48<<3)>>2]|0;break}if(t){o=-1;break e}if(I){a=(de[r>>2]|0)+(4-1)&~(4-1);h=de[a>>2]|0;de[r>>2]=a+4;a=l}else{a=l;h=0}}else h=-1}while(0);f=0;while(1){s=(pe[a>>0]|0)+-65|0;if(s>>>0>57){o=-1;break e}l=a+1|0;s=pe[5359+(f*58|0)+s>>0]|0;c=s&255;if((c+-1|0)>>>0<8){a=l;f=c}else{E=l;break}}if(!(s<<24>>24)){o=-1;break}l=(p|0)>-1;do{if(s<<24>>24==19)if(l){o=-1;break e}else C=52;else{if(l){de[n+(p<<2)>>2]=c;P=i+(p<<3)|0;S=de[P+4>>2]|0;C=q;de[C>>2]=de[P>>2];de[C+4>>2]=S;C=52;break}if(!I){o=0;break e}Fr(q,c,r)}}while(0);if((C|0)==52?(C=0,!I):0){m=E;a=v;continue}p=pe[a>>0]|0;p=(f|0)!=0&(p&15|0)==3?p&-33:p;l=g&-65537;S=(g&8192|0)==0?g:l;t:do{switch(p|0){case 110:switch(f|0){case 0:{de[de[q>>2]>>2]=o;m=E;a=v;continue e}case 1:{de[de[q>>2]>>2]=o;m=E;a=v;continue e}case 2:{m=de[q>>2]|0;de[m>>2]=o;de[m+4>>2]=((o|0)<0)<<31>>31;m=E;a=v;continue e}case 3:{$[de[q>>2]>>1]=o;m=E;a=v;continue e}case 4:{pe[de[q>>2]>>0]=o;m=E;a=v;continue e}case 6:{de[de[q>>2]>>2]=o;m=E;a=v;continue e}case 7:{m=de[q>>2]|0;de[m>>2]=o;de[m+4>>2]=((o|0)<0)<<31>>31;m=E;a=v;continue e}default:{m=E;a=v;continue e}}case 112:{f=S|8;h=h>>>0>8?h:8;p=120;C=64;break}case 88:case 120:{f=S;C=64;break}case 111:{l=q;s=de[l>>2]|0;l=de[l+4>>2]|0;if((s|0)==0&(l|0)==0)a=O;else{a=O;do{a=a+-1|0;pe[a>>0]=s&7|48;s=Zr(s|0,l|0,3)|0;l=re}while(!((s|0)==0&(l|0)==0))}if(!(S&8)){s=S;f=0;c=5839;C=77}else{f=j-a+1|0;s=S;h=(h|0)<(f|0)?f:h;f=0;c=5839;C=77}break}case 105:case 100:{s=q;a=de[s>>2]|0;s=de[s+4>>2]|0;if((s|0)<0){a=Vr(0,0,a|0,s|0)|0;s=re;l=q;de[l>>2]=a;de[l+4>>2]=s;l=1;c=5839;C=76;break t}if(!(S&2048)){c=S&1;l=c;c=(c|0)==0?5839:5841;C=76}else{l=1;c=5840;C=76}break}case 117:{s=q;a=de[s>>2]|0;s=de[s+4>>2]|0;l=0;c=5839;C=76;break}case 99:{pe[N>>0]=de[q>>2];m=N;s=1;f=0;p=5839;a=O;break}case 109:{a=hr()|0;a=ur(de[a>>2]|0)|0;C=82;break}case 115:{a=de[q>>2]|0;a=(a|0)!=0?a:5849;C=82;break}case 67:{de[K>>2]=de[q>>2];de[B>>2]=0;de[q>>2]=K;h=-1;C=86;break}case 83:{if(!h){Nr(e,32,A,0,S);a=0;C=98}else C=86;break}case 65:case 71:case 70:case 69:case 97:case 103:case 102:case 101:{u=+ee[q>>3];de[Z>>2]=0;ee[te>>3]=u;if((de[te+4>>2]|0)>=0)if(!(S&2048)){P=S&1;k=P;P=(P|0)==0?5857:5862}else{k=1;P=5859}else{u=-u;k=1;P=5856}ee[te>>3]=u;T=de[te+4>>2]&2146435072;do{if(T>>>0<2146435072|(T|0)==2146435072&0<0){d=+pr(u,Z)*2.0;s=d!=0.0;if(s)de[Z>>2]=(de[Z>>2]|0)+-1;x=p|32;if((x|0)==97){m=p&32;v=(m|0)==0?P:P+9|0;g=k|2;a=12-h|0;do{if(!(h>>>0>11|(a|0)==0)){u=8.0;do{a=a+-1|0;u=u*16.0}while((a|0)!=0);if((pe[v>>0]|0)==45){u=-(u+(-d-u));break}else{u=d+u-u;break}}else u=d}while(0);s=de[Z>>2]|0;a=(s|0)<0?0-s|0:s;a=jr(a,((a|0)<0)<<31>>31,U)|0;if((a|0)==(U|0)){pe[X>>0]=48;a=X}pe[a+-1>>0]=(s>>31&2)+43;f=a+-2|0;pe[f>>0]=p+15;c=(h|0)<1;l=(S&8|0)==0;s=Y;while(1){P=~~u;a=s+1|0;pe[s>>0]=me[5823+P>>0]|m;u=(u-+(P|0))*16.0;do{if((a-H|0)==1){if(l&(c&u==0.0))break;pe[a>>0]=46;a=s+2|0}}while(0);if(!(u!=0.0))break;else s=a}h=(h|0)!=0&(M+a|0)<(h|0)?D+h-f|0:W-f+a|0;l=h+g|0;Nr(e,32,A,l,S);if(!(de[e>>2]&32))_r(v,g,e)|0;Nr(e,48,A,l,S^65536);a=a-H|0;if(!(de[e>>2]&32))_r(Y,a,e)|0;s=G-f|0;Nr(e,48,h-(a+s)|0,0,0);if(!(de[e>>2]&32))_r(f,s,e)|0;Nr(e,32,A,l,S^8192);a=(l|0)<(A|0)?A:l;break}a=(h|0)<0?6:h;if(s){s=(de[Z>>2]|0)+-28|0;de[Z>>2]=s;u=d*268435456.0}else{u=d;s=de[Z>>2]|0}T=(s|0)<0?V:R;w=T;s=T;do{b=~~u>>>0;de[s>>2]=b;s=s+4|0;u=(u-+(b>>>0))*1.0e9}while(u!=0.0);l=s;s=de[Z>>2]|0;if((s|0)>0){c=T;while(1){f=(s|0)>29?29:s;h=l+-4|0;do{if(h>>>0>>0)h=c;else{s=0;do{b=Jr(de[h>>2]|0,0,f|0)|0;b=Kr(b|0,re|0,s|0,0)|0;s=re;y=ai(b|0,s|0,1e9,0)|0;de[h>>2]=y;s=oi(b|0,s|0,1e9,0)|0;h=h+-4|0}while(h>>>0>=c>>>0);if(!s){h=c;break}h=c+-4|0;de[h>>2]=s}}while(0);while(1){if(l>>>0<=h>>>0)break;s=l+-4|0;if(!(de[s>>2]|0))l=s;else break}s=(de[Z>>2]|0)-f|0;de[Z>>2]=s;if((s|0)>0)c=h;else break}}else h=T;if((s|0)<0){v=((a+25|0)/9|0)+1|0;_=(x|0)==102;m=h;while(1){g=0-s|0;g=(g|0)>9?9:g;do{if(m>>>0>>0){s=(1<>>g;h=0;f=m;do{b=de[f>>2]|0;de[f>>2]=(b>>>g)+h;h=_e(b&s,c)|0;f=f+4|0}while(f>>>0>>0);s=(de[m>>2]|0)==0?m+4|0:m;if(!h){h=s;break}de[l>>2]=h;h=s;l=l+4|0}else h=(de[m>>2]|0)==0?m+4|0:m}while(0);s=_?T:h;l=(l-s>>2|0)>(v|0)?s+(v<<2)|0:l;s=(de[Z>>2]|0)+g|0;de[Z>>2]=s;if((s|0)>=0){m=h;break}else m=h}}else m=h;do{if(m>>>0>>0){s=(w-m>>2)*9|0;c=de[m>>2]|0;if(c>>>0<10)break;else h=10;do{h=h*10|0;s=s+1|0}while(c>>>0>=h>>>0)}else s=0}while(0);y=(x|0)==103;b=(a|0)!=0;h=a-((x|0)!=102?s:0)+((b&y)<<31>>31)|0;if((h|0)<(((l-w>>2)*9|0)+-9|0)){f=h+9216|0;_=(f|0)/9|0;h=T+(_+-1023<<2)|0;f=((f|0)%9|0)+1|0;if((f|0)<9){c=10;do{c=c*10|0;f=f+1|0}while((f|0)!=9)}else c=10;g=de[h>>2]|0;v=(g>>>0)%(c>>>0)|0;if((v|0)==0?(T+(_+-1022<<2)|0)==(l|0):0)c=m;else C=163;do{if((C|0)==163){C=0;d=(((g>>>0)/(c>>>0)|0)&1|0)==0?9007199254740992.0:9007199254740994.0;f=(c|0)/2|0;do{if(v>>>0>>0)u=.5;else{if((v|0)==(f|0)?(T+(_+-1022<<2)|0)==(l|0):0){u=1.0;break}u=1.5}}while(0);do{if(k){if((pe[P>>0]|0)!=45)break;d=-d;u=-u}}while(0);f=g-v|0;de[h>>2]=f;if(!(d+u!=d)){c=m;break}x=f+c|0;de[h>>2]=x;if(x>>>0>999999999){s=m;while(1){c=h+-4|0;de[h>>2]=0;if(c>>>0>>0){s=s+-4|0;de[s>>2]=0}x=(de[c>>2]|0)+1|0;de[c>>2]=x;if(x>>>0>999999999)h=c;else{m=s;h=c;break}}}s=(w-m>>2)*9|0;f=de[m>>2]|0;if(f>>>0<10){c=m;break}else c=10;do{c=c*10|0;s=s+1|0}while(f>>>0>=c>>>0);c=m}}while(0);x=h+4|0;m=c;l=l>>>0>x>>>0?x:l}v=0-s|0;while(1){if(l>>>0<=m>>>0){_=0;x=l;break}h=l+-4|0;if(!(de[h>>2]|0))l=h;else{_=1;x=l;break}}do{if(y){a=(b&1^1)+a|0;if((a|0)>(s|0)&(s|0)>-5){p=p+-1|0;a=a+-1-s|0}else{p=p+-2|0;a=a+-1|0}l=S&8;if(l)break;do{if(_){l=de[x+-4>>2]|0;if(!l){h=9;break}if(!((l>>>0)%10|0)){c=10;h=0}else{h=0;break}do{c=c*10|0;h=h+1|0}while(((l>>>0)%(c>>>0)|0|0)==0)}else h=9}while(0);l=((x-w>>2)*9|0)+-9|0;if((p|32|0)==102){l=l-h|0;l=(l|0)<0?0:l;a=(a|0)<(l|0)?a:l;l=0;break}else{l=l+s-h|0;l=(l|0)<0?0:l;a=(a|0)<(l|0)?a:l;l=0;break}}else l=S&8}while(0);g=a|l;c=(g|0)!=0&1;f=(p|32|0)==102;if(f){s=(s|0)>0?s:0;p=0}else{h=(s|0)<0?v:s;h=jr(h,((h|0)<0)<<31>>31,U)|0;if((G-h|0)<2)do{h=h+-1|0;pe[h>>0]=48}while((G-h|0)<2);pe[h+-1>>0]=(s>>31&2)+43;w=h+-2|0;pe[w>>0]=p;s=G-w|0;p=w}v=k+1+a+c+s|0;Nr(e,32,A,v,S);if(!(de[e>>2]&32))_r(P,k,e)|0;Nr(e,48,A,v,S^65536);do{if(f){h=m>>>0>T>>>0?T:m;s=h;do{l=jr(de[s>>2]|0,0,z)|0;do{if((s|0)==(h|0)){if((l|0)!=(z|0))break;pe[F>>0]=48;l=F}else{if(l>>>0<=Y>>>0)break;do{l=l+-1|0;pe[l>>0]=48}while(l>>>0>Y>>>0)}}while(0);if(!(de[e>>2]&32))_r(l,L-l|0,e)|0;s=s+4|0}while(s>>>0<=T>>>0);do{if(g){if(de[e>>2]&32)break;_r(5891,1,e)|0}}while(0);if((a|0)>0&s>>>0>>0){l=s;while(1){s=jr(de[l>>2]|0,0,z)|0;if(s>>>0>Y>>>0)do{s=s+-1|0;pe[s>>0]=48}while(s>>>0>Y>>>0);if(!(de[e>>2]&32))_r(s,(a|0)>9?9:a,e)|0;l=l+4|0;s=a+-9|0;if(!((a|0)>9&l>>>0>>0)){a=s;break}else a=s}}Nr(e,48,a+9|0,9,0)}else{f=_?x:m+4|0;if((a|0)>-1){c=(l|0)==0;h=m;do{s=jr(de[h>>2]|0,0,z)|0;if((s|0)==(z|0)){pe[F>>0]=48;s=F}do{if((h|0)==(m|0)){l=s+1|0;if(!(de[e>>2]&32))_r(s,1,e)|0;if(c&(a|0)<1){s=l;break}if(de[e>>2]&32){s=l;break}_r(5891,1,e)|0;s=l}else{if(s>>>0<=Y>>>0)break;do{s=s+-1|0;pe[s>>0]=48}while(s>>>0>Y>>>0)}}while(0);l=L-s|0;if(!(de[e>>2]&32))_r(s,(a|0)>(l|0)?l:a,e)|0;a=a-l|0;h=h+4|0}while(h>>>0>>0&(a|0)>-1)}Nr(e,48,a+18|0,18,0);if(de[e>>2]&32)break;_r(p,G-p|0,e)|0}}while(0);Nr(e,32,A,v,S^8192);a=(v|0)<(A|0)?A:v}else{f=(p&32|0)!=0;c=u!=u|0.0!=0.0;s=c?0:k;h=s+3|0;Nr(e,32,A,h,l);a=de[e>>2]|0;if(!(a&32)){_r(P,s,e)|0;a=de[e>>2]|0}if(!(a&32))_r(c?f?5883:5887:f?5875:5879,3,e)|0;Nr(e,32,A,h,S^8192);a=(h|0)<(A|0)?A:h}}while(0);m=E;continue e}default:{l=S;s=h;f=0;p=5839;a=O}}}while(0);t:do{if((C|0)==64){l=q;s=de[l>>2]|0;l=de[l+4>>2]|0;c=p&32;if(!((s|0)==0&(l|0)==0)){a=O;do{a=a+-1|0;pe[a>>0]=me[5823+(s&15)>>0]|c;s=Zr(s|0,l|0,4)|0;l=re}while(!((s|0)==0&(l|0)==0));C=q;if((f&8|0)==0|(de[C>>2]|0)==0&(de[C+4>>2]|0)==0){s=f;f=0;c=5839;C=77}else{s=f;f=2;c=5839+(p>>4)|0;C=77}}else{a=O;s=f;f=0;c=5839;C=77}}else if((C|0)==76){a=jr(a,s,O)|0;s=S;f=l;C=77}else if((C|0)==82){C=0;S=Mr(a,0,h)|0;P=(S|0)==0;m=a;s=P?h:S-a|0;f=0;p=5839;a=P?a+h|0:S}else if((C|0)==86){C=0;s=0;a=0;c=de[q>>2]|0;while(1){l=de[c>>2]|0;if(!l)break;a=mr(J,l)|0;if((a|0)<0|a>>>0>(h-s|0)>>>0)break;s=a+s|0;if(h>>>0>s>>>0)c=c+4|0;else break}if((a|0)<0){o=-1;break e}Nr(e,32,A,s,S);if(!s){a=0;C=98}else{l=0;h=de[q>>2]|0;while(1){a=de[h>>2]|0;if(!a){a=s;C=98;break t}a=mr(J,a)|0;l=a+l|0;if((l|0)>(s|0)){a=s;C=98;break t}if(!(de[e>>2]&32))_r(J,a,e)|0;if(l>>>0>=s>>>0){a=s;C=98;break}else h=h+4|0}}}}while(0);if((C|0)==98){C=0;Nr(e,32,A,a,S^8192);m=E;a=(A|0)>(a|0)?A:a;continue}if((C|0)==77){C=0;l=(h|0)>-1?s&-65537:s;s=q;s=(de[s>>2]|0)!=0|(de[s+4>>2]|0)!=0;if((h|0)!=0|s){s=(s&1^1)+(j-a)|0;m=a;s=(h|0)>(s|0)?h:s;p=c;a=O}else{m=O;s=0;p=c;a=O}}c=a-m|0;s=(s|0)<(c|0)?c:s;h=f+s|0;a=(A|0)<(h|0)?h:A;Nr(e,32,a,h,l);if(!(de[e>>2]&32))_r(p,f,e)|0;Nr(e,48,a,h,l^65536);Nr(e,48,s,c,0);if(!(de[e>>2]&32))_r(m,c,e)|0;Nr(e,32,a,h,l^8192);m=E}e:do{if((C|0)==245)if(!e)if(t){o=1;while(1){t=de[n+(o<<2)>>2]|0;if(!t)break;Fr(i+(o<<3)|0,t,r);o=o+1|0;if((o|0)>=10){o=1;break e}}if((o|0)<10)while(1){if(de[n+(o<<2)>>2]|0){o=-1;break e}o=o+1|0;if((o|0)>=10){o=1;break}}else o=1}else o=0}while(0);ve=Q;return o|0}function zr(e){e=e|0;if(!(de[e+68>>2]|0))Pr(e);return}function Lr(e,t,r){e=e|0;t=t|0;r=r|0;var i=0,n=0;i=e+20|0;n=de[i>>2]|0;e=(de[e+16>>2]|0)-n|0;e=e>>>0>r>>>0?r:e;Qr(n|0,t|0,e|0)|0;de[i>>2]=(de[i>>2]|0)+e;return r|0}function Fr(e,t,r){e=e|0;t=t|0;r=r|0;var i=0,n=0,o=0.0;e:do{if(t>>>0<=20)do{switch(t|0){case 9:{i=(de[r>>2]|0)+(4-1)&~(4-1);t=de[i>>2]|0;de[r>>2]=i+4;de[e>>2]=t;break e}case 10:{i=(de[r>>2]|0)+(4-1)&~(4-1);t=de[i>>2]|0;de[r>>2]=i+4;i=e;de[i>>2]=t;de[i+4>>2]=((t|0)<0)<<31>>31;break e}case 11:{i=(de[r>>2]|0)+(4-1)&~(4-1);t=de[i>>2]|0;de[r>>2]=i+4;i=e;de[i>>2]=t;de[i+4>>2]=0;break e}case 12:{i=(de[r>>2]|0)+(8-1)&~(8-1);t=i;n=de[t>>2]|0;t=de[t+4>>2]|0;de[r>>2]=i+8;i=e;de[i>>2]=n;de[i+4>>2]=t;break e}case 13:{n=(de[r>>2]|0)+(4-1)&~(4-1);i=de[n>>2]|0;de[r>>2]=n+4;i=(i&65535)<<16>>16;n=e;de[n>>2]=i;de[n+4>>2]=((i|0)<0)<<31>>31;break e}case 14:{n=(de[r>>2]|0)+(4-1)&~(4-1);i=de[n>>2]|0;de[r>>2]=n+4;n=e;de[n>>2]=i&65535;de[n+4>>2]=0;break e}case 15:{n=(de[r>>2]|0)+(4-1)&~(4-1);i=de[n>>2]|0;de[r>>2]=n+4;i=(i&255)<<24>>24;n=e;de[n>>2]=i;de[n+4>>2]=((i|0)<0)<<31>>31;break e}case 16:{n=(de[r>>2]|0)+(4-1)&~(4-1);i=de[n>>2]|0;de[r>>2]=n+4;n=e;de[n>>2]=i&255;de[n+4>>2]=0;break e}case 17:{n=(de[r>>2]|0)+(8-1)&~(8-1);o=+ee[n>>3];de[r>>2]=n+8;ee[e>>3]=o;break e}case 18:{n=(de[r>>2]|0)+(8-1)&~(8-1);o=+ee[n>>3];de[r>>2]=n+8;ee[e>>3]=o;break e}default:break e}}while(0)}while(0);return}function jr(e,t,r){e=e|0;t=t|0;r=r|0;var i=0;if(t>>>0>0|(t|0)==0&e>>>0>4294967295)while(1){i=ai(e|0,t|0,10,0)|0;r=r+-1|0;pe[r>>0]=i|48;i=oi(e|0,t|0,10,0)|0;if(t>>>0>9|(t|0)==9&e>>>0>4294967295){e=i;t=re}else{e=i;break}}if(e)while(1){r=r+-1|0;pe[r>>0]=(e>>>0)%10|0|48;if(e>>>0<10)break;else e=(e>>>0)/10|0}return r|0}function Nr(e,t,r,i,n){e=e|0;t=t|0;r=r|0;i=i|0;n=n|0;var o=0,a=0,s=0;s=ve;ve=ve+256|0;a=s;do{if((r|0)>(i|0)&(n&73728|0)==0){n=r-i|0;Yr(a|0,t|0,(n>>>0>256?256:n)|0)|0;t=de[e>>2]|0;o=(t&32|0)==0;if(n>>>0>255){i=r-i|0;do{if(o){_r(a,256,e)|0;t=de[e>>2]|0}n=n+-256|0;o=(t&32|0)==0}while(n>>>0>255);if(o)n=i&255;else break}else if(!o)break;_r(a,n,e)|0}}while(0);ve=s;return}function Br(e){e=e|0;var t=0,r=0,i=0,n=0,o=0,a=0,s=0,l=0,u=0,h=0,c=0,f=0,p=0,d=0,m=0,g=0,v=0,_=0,y=0,b=0,x=0,w=0,T=0,k=0,P=0,S=0,E=0,A=0,C=0,I=0,O=0,M=0,D=0,R=0,z=0,L=0,F=0;do{if(e>>>0<245){p=e>>>0<11?16:e+11&-8;e=p>>>3;s=de[151]|0;r=s>>>e;if(r&3){e=(r&1^1)+e|0;i=e<<1;r=644+(i<<2)|0;i=644+(i+2<<2)|0;n=de[i>>2]|0;o=n+8|0;a=de[o>>2]|0;do{if((r|0)!=(a|0)){if(a>>>0<(de[155]|0)>>>0)Xe();t=a+12|0;if((de[t>>2]|0)==(n|0)){de[t>>2]=r;de[i>>2]=a;break}else Xe()}else de[151]=s&~(1<>2]=F|3;F=n+(F|4)|0;de[F>>2]=de[F>>2]|1;F=o;return F|0}a=de[153]|0;if(p>>>0>a>>>0){if(r){i=2<>>12&16;i=i>>>l;n=i>>>5&8;i=i>>>n;o=i>>>2&4;i=i>>>o;r=i>>>1&2;i=i>>>r;e=i>>>1&1;e=(n|l|o|r|e)+(i>>>e)|0;i=e<<1;r=644+(i<<2)|0;i=644+(i+2<<2)|0;o=de[i>>2]|0;l=o+8|0;n=de[l>>2]|0;do{if((r|0)!=(n|0)){if(n>>>0<(de[155]|0)>>>0)Xe();t=n+12|0;if((de[t>>2]|0)==(o|0)){de[t>>2]=r;de[i>>2]=n;u=de[153]|0;break}else Xe()}else{de[151]=s&~(1<>2]=p|3;s=o+p|0;de[o+(p|4)>>2]=a|1;de[o+F>>2]=a;if(u){n=de[156]|0;r=u>>>3;t=r<<1;i=644+(t<<2)|0;e=de[151]|0;r=1<>2]|0;if(t>>>0<(de[155]|0)>>>0)Xe();else{h=e;c=t}}else{de[151]=e|r;h=644+(t+2<<2)|0;c=i}de[h>>2]=n;de[c+12>>2]=n;de[n+8>>2]=c;de[n+12>>2]=i}de[153]=a;de[156]=s;F=l;return F|0}e=de[152]|0;if(e){r=(e&0-e)+-1|0;L=r>>>12&16;r=r>>>L;z=r>>>5&8;r=r>>>z;F=r>>>2&4;r=r>>>F;e=r>>>1&2;r=r>>>e;i=r>>>1&1;i=de[908+((z|L|F|e|i)+(r>>>i)<<2)>>2]|0;r=(de[i+4>>2]&-8)-p|0;e=i;while(1){t=de[e+16>>2]|0;if(!t){t=de[e+20>>2]|0;if(!t){l=r;break}}e=(de[t+4>>2]&-8)-p|0;F=e>>>0>>0;r=F?e:r;e=t;i=F?t:i}o=de[155]|0;if(i>>>0>>0)Xe();s=i+p|0;if(i>>>0>=s>>>0)Xe();a=de[i+24>>2]|0;r=de[i+12>>2]|0;do{if((r|0)==(i|0)){e=i+20|0;t=de[e>>2]|0;if(!t){e=i+16|0;t=de[e>>2]|0;if(!t){f=0;break}}while(1){r=t+20|0;n=de[r>>2]|0;if(n){t=n;e=r;continue}r=t+16|0;n=de[r>>2]|0;if(!n)break;else{t=n;e=r}}if(e>>>0>>0)Xe();else{de[e>>2]=0;f=t;break}}else{n=de[i+8>>2]|0;if(n>>>0>>0)Xe();t=n+12|0;if((de[t>>2]|0)!=(i|0))Xe();e=r+8|0;if((de[e>>2]|0)==(i|0)){de[t>>2]=r;de[e>>2]=n;f=r;break}else Xe()}}while(0);do{if(a){t=de[i+28>>2]|0;e=908+(t<<2)|0;if((i|0)==(de[e>>2]|0)){de[e>>2]=f;if(!f){de[152]=de[152]&~(1<>>0<(de[155]|0)>>>0)Xe();t=a+16|0;if((de[t>>2]|0)==(i|0))de[t>>2]=f;else de[a+20>>2]=f;if(!f)break}e=de[155]|0;if(f>>>0>>0)Xe();de[f+24>>2]=a;t=de[i+16>>2]|0;do{if(t)if(t>>>0>>0)Xe();else{de[f+16>>2]=t;de[t+24>>2]=f;break}}while(0);t=de[i+20>>2]|0;if(t)if(t>>>0<(de[155]|0)>>>0)Xe();else{de[f+20>>2]=t;de[t+24>>2]=f;break}}}while(0);if(l>>>0<16){F=l+p|0;de[i+4>>2]=F|3;F=i+(F+4)|0;de[F>>2]=de[F>>2]|1}else{de[i+4>>2]=p|3;de[i+(p|4)>>2]=l|1;de[i+(l+p)>>2]=l;t=de[153]|0;if(t){o=de[156]|0;r=t>>>3;t=r<<1;n=644+(t<<2)|0;e=de[151]|0;r=1<>2]|0;if(e>>>0<(de[155]|0)>>>0)Xe();else{d=t;m=e}}else{de[151]=e|r;d=644+(t+2<<2)|0;m=n}de[d>>2]=o;de[m+12>>2]=o;de[o+8>>2]=m;de[o+12>>2]=n}de[153]=l;de[156]=s}F=i+8|0;return F|0}else m=p}else m=p}else if(e>>>0<=4294967231){e=e+11|0;c=e&-8;h=de[152]|0;if(h){r=0-c|0;e=e>>>8;if(e)if(c>>>0>16777215)u=31;else{m=(e+1048320|0)>>>16&8;b=e<>>16&4;b=b<>>16&2;u=14-(d|m|u)+(b<>>15)|0;u=c>>>(u+7|0)&1|u<<1}else u=0;e=de[908+(u<<2)>>2]|0;e:do{if(!e){n=0;e=0;b=86}else{a=r;n=0;s=c<<((u|0)==31?0:25-(u>>>1)|0);l=e;e=0;while(1){o=de[l+4>>2]&-8;r=o-c|0;if(r>>>0>>0)if((o|0)==(c|0)){o=l;e=l;b=90;break e}else e=l;else r=a;b=de[l+20>>2]|0;l=de[l+16+(s>>>31<<2)>>2]|0;n=(b|0)==0|(b|0)==(l|0)?n:b;if(!l){b=86;break}else{a=r;s=s<<1}}}}while(0);if((b|0)==86){if((n|0)==0&(e|0)==0){e=2<>>12&16;e=e>>>f;h=e>>>5&8;e=e>>>h;d=e>>>2&4;e=e>>>d;m=e>>>1&2;e=e>>>m;n=e>>>1&1;n=de[908+((h|f|d|m|n)+(e>>>n)<<2)>>2]|0;e=0}if(!n){s=r;l=e}else{o=n;b=90}}if((b|0)==90)while(1){b=0;m=(de[o+4>>2]&-8)-c|0;n=m>>>0>>0;r=n?m:r;e=n?o:e;n=de[o+16>>2]|0;if(n){o=n;b=90;continue}o=de[o+20>>2]|0;if(!o){s=r;l=e;break}else b=90}if((l|0)!=0?s>>>0<((de[153]|0)-c|0)>>>0:0){n=de[155]|0;if(l>>>0>>0)Xe();a=l+c|0;if(l>>>0>=a>>>0)Xe();o=de[l+24>>2]|0;r=de[l+12>>2]|0;do{if((r|0)==(l|0)){e=l+20|0;t=de[e>>2]|0;if(!t){e=l+16|0;t=de[e>>2]|0;if(!t){p=0;break}}while(1){r=t+20|0;i=de[r>>2]|0;if(i){t=i;e=r;continue}r=t+16|0;i=de[r>>2]|0;if(!i)break;else{t=i;e=r}}if(e>>>0>>0)Xe();else{de[e>>2]=0;p=t;break}}else{i=de[l+8>>2]|0;if(i>>>0>>0)Xe();t=i+12|0;if((de[t>>2]|0)!=(l|0))Xe();e=r+8|0;if((de[e>>2]|0)==(l|0)){de[t>>2]=r;de[e>>2]=i;p=r;break}else Xe()}}while(0);do{if(o){t=de[l+28>>2]|0;e=908+(t<<2)|0;if((l|0)==(de[e>>2]|0)){de[e>>2]=p;if(!p){de[152]=de[152]&~(1<>>0<(de[155]|0)>>>0)Xe();t=o+16|0;if((de[t>>2]|0)==(l|0))de[t>>2]=p;else de[o+20>>2]=p;if(!p)break}e=de[155]|0;if(p>>>0>>0)Xe();de[p+24>>2]=o;t=de[l+16>>2]|0;do{if(t)if(t>>>0>>0)Xe();else{de[p+16>>2]=t;de[t+24>>2]=p;break}}while(0);t=de[l+20>>2]|0;if(t)if(t>>>0<(de[155]|0)>>>0)Xe();else{de[p+20>>2]=t;de[t+24>>2]=p;break}}}while(0);e:do{if(s>>>0>=16){de[l+4>>2]=c|3;de[l+(c|4)>>2]=s|1;de[l+(s+c)>>2]=s;t=s>>>3;if(s>>>0<256){e=t<<1;i=644+(e<<2)|0;r=de[151]|0;t=1<>2]|0;if(e>>>0<(de[155]|0)>>>0)Xe();else{v=t;_=e}}else{de[151]=r|t;v=644+(e+2<<2)|0;_=i}de[v>>2]=a;de[_+12>>2]=a;de[l+(c+8)>>2]=_;de[l+(c+12)>>2]=i;break}t=s>>>8;if(t)if(s>>>0>16777215)i=31;else{L=(t+1048320|0)>>>16&8;F=t<>>16&4;F=F<>>16&2;i=14-(z|L|i)+(F<>>15)|0;i=s>>>(i+7|0)&1|i<<1}else i=0;t=908+(i<<2)|0;de[l+(c+28)>>2]=i;de[l+(c+20)>>2]=0;de[l+(c+16)>>2]=0;e=de[152]|0;r=1<>2]=a;de[l+(c+24)>>2]=t;de[l+(c+12)>>2]=a;de[l+(c+8)>>2]=a;break}t=de[t>>2]|0;t:do{if((de[t+4>>2]&-8|0)!=(s|0)){i=s<<((i|0)==31?0:25-(i>>>1)|0);while(1){e=t+16+(i>>>31<<2)|0;r=de[e>>2]|0;if(!r)break;if((de[r+4>>2]&-8|0)==(s|0)){T=r;break t}else{i=i<<1;t=r}}if(e>>>0<(de[155]|0)>>>0)Xe();else{de[e>>2]=a;de[l+(c+24)>>2]=t;de[l+(c+12)>>2]=a;de[l+(c+8)>>2]=a;break e}}else T=t}while(0);t=T+8|0;e=de[t>>2]|0;F=de[155]|0;if(e>>>0>=F>>>0&T>>>0>=F>>>0){de[e+12>>2]=a;de[t>>2]=a;de[l+(c+8)>>2]=e;de[l+(c+12)>>2]=T;de[l+(c+24)>>2]=0;break}else Xe()}else{F=s+c|0;de[l+4>>2]=F|3;F=l+(F+4)|0;de[F>>2]=de[F>>2]|1}}while(0);F=l+8|0;return F|0}else m=c}else m=c}else m=-1}while(0);r=de[153]|0;if(r>>>0>=m>>>0){t=r-m|0;e=de[156]|0;if(t>>>0>15){de[156]=e+m;de[153]=t;de[e+(m+4)>>2]=t|1;de[e+r>>2]=t;de[e+4>>2]=m|3}else{de[153]=0;de[156]=0;de[e+4>>2]=r|3;F=e+(r+4)|0;de[F>>2]=de[F>>2]|1}F=e+8|0;return F|0}e=de[154]|0;if(e>>>0>m>>>0){L=e-m|0;de[154]=L;F=de[157]|0;de[157]=F+m;de[F+(m+4)>>2]=L|1;de[F+4>>2]=m|3;F=F+8|0;return F|0}do{if(!(de[269]|0)){e=De(30)|0;if(!(e+-1&e)){de[271]=e;de[270]=e;de[272]=-1;de[273]=-1;de[274]=0;de[262]=0;T=(Ge(0)|0)&-16^1431655768;de[269]=T;break}else Xe()}}while(0);l=m+48|0;s=de[271]|0;u=m+47|0;a=s+u|0;s=0-s|0;h=a&s;if(h>>>0<=m>>>0){F=0;return F|0}e=de[261]|0;if((e|0)!=0?(_=de[259]|0,T=_+h|0,T>>>0<=_>>>0|T>>>0>e>>>0):0){F=0;return F|0}e:do{if(!(de[262]&4)){e=de[157]|0;t:do{if(e){n=1052;while(1){r=de[n>>2]|0;if(r>>>0<=e>>>0?(g=n+4|0,(r+(de[g>>2]|0)|0)>>>0>e>>>0):0){o=n;e=g;break}n=de[n+8>>2]|0;if(!n){b=174;break t}}r=a-(de[154]|0)&s;if(r>>>0<2147483647){n=Ie(r|0)|0;T=(n|0)==((de[o>>2]|0)+(de[e>>2]|0)|0);e=T?r:0;if(T){if((n|0)!=(-1|0)){x=n;d=e;b=194;break e}}else b=184}else e=0}else b=174}while(0);do{if((b|0)==174){o=Ie(0)|0;if((o|0)!=(-1|0)){e=o;r=de[270]|0;n=r+-1|0;if(!(n&e))r=h;else r=h-e+(n+e&0-r)|0;e=de[259]|0;n=e+r|0;if(r>>>0>m>>>0&r>>>0<2147483647){T=de[261]|0;if((T|0)!=0?n>>>0<=e>>>0|n>>>0>T>>>0:0){e=0;break}n=Ie(r|0)|0;T=(n|0)==(o|0);e=T?r:0;if(T){x=o;d=e;b=194;break e}else b=184}else e=0}else e=0}}while(0);t:do{if((b|0)==184){o=0-r|0;do{if(l>>>0>r>>>0&(r>>>0<2147483647&(n|0)!=(-1|0))?(y=de[271]|0,y=u-r+y&0-y,y>>>0<2147483647):0)if((Ie(y|0)|0)==(-1|0)){Ie(o|0)|0;break t}else{r=y+r|0;break}}while(0);if((n|0)!=(-1|0)){x=n;d=r;b=194;break e}}}while(0);de[262]=de[262]|4;b=191}else{e=0;b=191}}while(0);if((((b|0)==191?h>>>0<2147483647:0)?(x=Ie(h|0)|0,w=Ie(0)|0,x>>>0>>0&((x|0)!=(-1|0)&(w|0)!=(-1|0))):0)?(k=w-x|0,P=k>>>0>(m+40|0)>>>0,P):0){d=P?k:e;b=194}if((b|0)==194){e=(de[259]|0)+d|0;de[259]=e;if(e>>>0>(de[260]|0)>>>0)de[260]=e;a=de[157]|0;e:do{if(a){o=1052;do{e=de[o>>2]|0;r=o+4|0;n=de[r>>2]|0;if((x|0)==(e+n|0)){S=e;E=r;A=n;C=o;b=204;break}o=de[o+8>>2]|0}while((o|0)!=0);if(((b|0)==204?(de[C+12>>2]&8|0)==0:0)?a>>>0>>0&a>>>0>=S>>>0:0){de[E>>2]=A+d;F=(de[154]|0)+d|0;L=a+8|0;L=(L&7|0)==0?0:0-L&7;z=F-L|0;de[157]=a+L;de[154]=z;de[a+(L+4)>>2]=z|1;de[a+(F+4)>>2]=40;de[158]=de[273];break}e=de[155]|0;if(x>>>0>>0){de[155]=x;e=x}r=x+d|0;o=1052;while(1){if((de[o>>2]|0)==(r|0)){n=o;r=o;b=212;break}o=de[o+8>>2]|0;if(!o){r=1052;break}}if((b|0)==212)if(!(de[r+12>>2]&8)){de[n>>2]=x;f=r+4|0;de[f>>2]=(de[f>>2]|0)+d;f=x+8|0;f=(f&7|0)==0?0:0-f&7;u=x+(d+8)|0;u=(u&7|0)==0?0:0-u&7;t=x+(u+d)|0;c=f+m|0;p=x+c|0;h=t-(x+f)-m|0;de[x+(f+4)>>2]=m|3;t:do{if((t|0)!=(a|0)){if((t|0)==(de[156]|0)){F=(de[153]|0)+h|0;de[153]=F;de[156]=p;de[x+(c+4)>>2]=F|1;de[x+(F+c)>>2]=F;break}s=d+4|0;r=de[x+(s+u)>>2]|0;if((r&3|0)==1){l=r&-8;o=r>>>3;r:do{if(r>>>0>=256){a=de[x+((u|24)+d)>>2]|0;i=de[x+(d+12+u)>>2]|0;do{if((i|0)==(t|0)){n=u|16;i=x+(s+n)|0;r=de[i>>2]|0;if(!r){i=x+(n+d)|0;r=de[i>>2]|0;if(!r){R=0;break}}while(1){n=r+20|0;o=de[n>>2]|0;if(o){r=o;i=n;continue}n=r+16|0;o=de[n>>2]|0;if(!o)break;else{r=o;i=n}}if(i>>>0>>0)Xe();else{de[i>>2]=0;R=r;break}}else{n=de[x+((u|8)+d)>>2]|0;if(n>>>0>>0)Xe();e=n+12|0;if((de[e>>2]|0)!=(t|0))Xe();r=i+8|0;if((de[r>>2]|0)==(t|0)){de[e>>2]=i;de[r>>2]=n;R=i;break}else Xe()}}while(0);if(!a)break;e=de[x+(d+28+u)>>2]|0;r=908+(e<<2)|0;do{if((t|0)!=(de[r>>2]|0)){if(a>>>0<(de[155]|0)>>>0)Xe();e=a+16|0;if((de[e>>2]|0)==(t|0))de[e>>2]=R;else de[a+20>>2]=R;if(!R)break r}else{de[r>>2]=R;if(R)break;de[152]=de[152]&~(1<>>0>>0)Xe();de[R+24>>2]=a;t=u|16;e=de[x+(t+d)>>2]|0;do{if(e)if(e>>>0>>0)Xe();else{de[R+16>>2]=e;de[e+24>>2]=R;break}}while(0);t=de[x+(s+t)>>2]|0;if(!t)break;if(t>>>0<(de[155]|0)>>>0)Xe();else{de[R+20>>2]=t;de[t+24>>2]=R;break}}else{i=de[x+((u|8)+d)>>2]|0;n=de[x+(d+12+u)>>2]|0;r=644+(o<<1<<2)|0;do{if((i|0)!=(r|0)){if(i>>>0>>0)Xe();if((de[i+12>>2]|0)==(t|0))break;Xe()}}while(0);if((n|0)==(i|0)){de[151]=de[151]&~(1<>>0>>0)Xe();e=n+8|0;if((de[e>>2]|0)==(t|0)){I=e;break}Xe()}}while(0);de[i+12>>2]=n;de[I>>2]=i}}while(0);t=x+((l|u)+d)|0;n=l+h|0}else n=h;t=t+4|0;de[t>>2]=de[t>>2]&-2;de[x+(c+4)>>2]=n|1;de[x+(n+c)>>2]=n;t=n>>>3;if(n>>>0<256){e=t<<1;i=644+(e<<2)|0;r=de[151]|0;t=1<>2]|0;if(e>>>0>=(de[155]|0)>>>0){z=t;L=e;break}Xe()}}while(0);de[z>>2]=p;de[L+12>>2]=p;de[x+(c+8)>>2]=L;de[x+(c+12)>>2]=i;break}t=n>>>8;do{if(!t)i=0;else{if(n>>>0>16777215){i=31;break}z=(t+1048320|0)>>>16&8;L=t<>>16&4;L=L<>>16&2;i=14-(R|z|i)+(L<>>15)|0;i=n>>>(i+7|0)&1|i<<1}}while(0);t=908+(i<<2)|0;de[x+(c+28)>>2]=i;de[x+(c+20)>>2]=0;de[x+(c+16)>>2]=0;e=de[152]|0;r=1<>2]=p;de[x+(c+24)>>2]=t;de[x+(c+12)>>2]=p;de[x+(c+8)>>2]=p;break}t=de[t>>2]|0;r:do{if((de[t+4>>2]&-8|0)!=(n|0)){i=n<<((i|0)==31?0:25-(i>>>1)|0);while(1){e=t+16+(i>>>31<<2)|0;r=de[e>>2]|0;if(!r)break;if((de[r+4>>2]&-8|0)==(n|0)){F=r;break r}else{i=i<<1;t=r}}if(e>>>0<(de[155]|0)>>>0)Xe();else{de[e>>2]=p;de[x+(c+24)>>2]=t;de[x+(c+12)>>2]=p;de[x+(c+8)>>2]=p;break t}}else F=t}while(0);t=F+8|0;e=de[t>>2]|0;L=de[155]|0;if(e>>>0>=L>>>0&F>>>0>=L>>>0){de[e+12>>2]=p;de[t>>2]=p;de[x+(c+8)>>2]=e;de[x+(c+12)>>2]=F;de[x+(c+24)>>2]=0;break}else Xe()}else{F=(de[154]|0)+h|0;de[154]=F;de[157]=p;de[x+(c+4)>>2]=F|1}}while(0);F=x+(f|8)|0;return F|0}else r=1052;while(1){e=de[r>>2]|0;if(e>>>0<=a>>>0?(t=de[r+4>>2]|0,i=e+t|0,i>>>0>a>>>0):0)break;r=de[r+8>>2]|0}n=e+(t+-39)|0;e=e+(t+-47+((n&7|0)==0?0:0-n&7))|0;n=a+16|0;e=e>>>0>>0?a:e;t=e+8|0;r=x+8|0;r=(r&7|0)==0?0:0-r&7;F=d+-40-r|0;de[157]=x+r;de[154]=F;de[x+(r+4)>>2]=F|1;de[x+(d+-36)>>2]=40;de[158]=de[273];r=e+4|0;de[r>>2]=27;de[t>>2]=de[263];de[t+4>>2]=de[264];de[t+8>>2]=de[265];de[t+12>>2]=de[266];de[263]=x;de[264]=d;de[266]=0;de[265]=t;t=e+28|0;de[t>>2]=7;if((e+32|0)>>>0>>0)do{F=t;t=t+4|0;de[t>>2]=7}while((F+8|0)>>>0>>0);if((e|0)!=(a|0)){o=e-a|0;de[r>>2]=de[r>>2]&-2;de[a+4>>2]=o|1;de[e>>2]=o;t=o>>>3;if(o>>>0<256){e=t<<1;i=644+(e<<2)|0;r=de[151]|0;t=1<>2]|0;if(e>>>0<(de[155]|0)>>>0)Xe();else{O=t;M=e}}else{de[151]=r|t;O=644+(e+2<<2)|0;M=i}de[O>>2]=a;de[M+12>>2]=a;de[a+8>>2]=M;de[a+12>>2]=i;break}t=o>>>8;if(t)if(o>>>0>16777215)i=31;else{L=(t+1048320|0)>>>16&8;F=t<>>16&4;F=F<>>16&2;i=14-(z|L|i)+(F<>>15)|0;i=o>>>(i+7|0)&1|i<<1}else i=0;r=908+(i<<2)|0;de[a+28>>2]=i;de[a+20>>2]=0;de[n>>2]=0;t=de[152]|0;e=1<>2]=a;de[a+24>>2]=r;de[a+12>>2]=a;de[a+8>>2]=a;break}t=de[r>>2]|0;t:do{if((de[t+4>>2]&-8|0)!=(o|0)){i=o<<((i|0)==31?0:25-(i>>>1)|0);while(1){e=t+16+(i>>>31<<2)|0;r=de[e>>2]|0;if(!r)break;if((de[r+4>>2]&-8|0)==(o|0)){D=r;break t}else{i=i<<1;t=r}}if(e>>>0<(de[155]|0)>>>0)Xe();else{de[e>>2]=a;de[a+24>>2]=t;de[a+12>>2]=a;de[a+8>>2]=a;break e}}else D=t}while(0);t=D+8|0;e=de[t>>2]|0;F=de[155]|0;if(e>>>0>=F>>>0&D>>>0>=F>>>0){de[e+12>>2]=a;de[t>>2]=a;de[a+8>>2]=e;de[a+12>>2]=D;de[a+24>>2]=0;break}else Xe()}}else{F=de[155]|0;if((F|0)==0|x>>>0>>0)de[155]=x;de[263]=x;de[264]=d;de[266]=0;de[160]=de[269];de[159]=-1;t=0;do{F=t<<1;L=644+(F<<2)|0;de[644+(F+3<<2)>>2]=L;de[644+(F+2<<2)>>2]=L;t=t+1|0}while((t|0)!=32);F=x+8|0;F=(F&7|0)==0?0:0-F&7;L=d+-40-F|0;de[157]=x+F;de[154]=L;de[x+(F+4)>>2]=L|1;de[x+(d+-36)>>2]=40;de[158]=de[273]}}while(0);t=de[154]|0;if(t>>>0>m>>>0){L=t-m|0;de[154]=L;F=de[157]|0;de[157]=F+m;de[F+(m+4)>>2]=L|1;de[F+4>>2]=m|3;F=F+8|0;return F|0}}F=hr()|0;de[F>>2]=12;F=0;return F|0}function Ur(e){e=e|0;var t=0,r=0,i=0,n=0,o=0,a=0,s=0,l=0,u=0,h=0,c=0,f=0,p=0,d=0,m=0,g=0,v=0,_=0,y=0;if(!e)return;t=e+-8|0;s=de[155]|0;if(t>>>0>>0)Xe();r=de[e+-4>>2]|0;i=r&3;if((i|0)==1)Xe();p=r&-8;m=e+(p+-8)|0;do{if(!(r&1)){t=de[t>>2]|0;if(!i)return;l=-8-t|0;h=e+l|0;c=t+p|0;if(h>>>0>>0)Xe();if((h|0)==(de[156]|0)){t=e+(p+-4)|0;r=de[t>>2]|0;if((r&3|0)!=3){y=h;o=c;break}de[153]=c;de[t>>2]=r&-2;de[e+(l+4)>>2]=c|1;de[m>>2]=c;return}n=t>>>3;if(t>>>0<256){i=de[e+(l+8)>>2]|0;r=de[e+(l+12)>>2]|0;t=644+(n<<1<<2)|0;if((i|0)!=(t|0)){if(i>>>0>>0)Xe();if((de[i+12>>2]|0)!=(h|0))Xe()}if((r|0)==(i|0)){de[151]=de[151]&~(1<>>0>>0)Xe();t=r+8|0;if((de[t>>2]|0)==(h|0))a=t;else Xe()}else a=r+8|0;de[i+12>>2]=r;de[a>>2]=i;y=h;o=c;break}a=de[e+(l+24)>>2]|0;i=de[e+(l+12)>>2]|0;do{if((i|0)==(h|0)){r=e+(l+20)|0;t=de[r>>2]|0;if(!t){r=e+(l+16)|0;t=de[r>>2]|0;if(!t){u=0;break}}while(1){i=t+20|0;n=de[i>>2]|0;if(n){t=n;r=i;continue}i=t+16|0;n=de[i>>2]|0;if(!n)break;else{t=n;r=i}}if(r>>>0>>0)Xe();else{de[r>>2]=0;u=t;break}}else{n=de[e+(l+8)>>2]|0;if(n>>>0>>0)Xe();t=n+12|0;if((de[t>>2]|0)!=(h|0))Xe();r=i+8|0;if((de[r>>2]|0)==(h|0)){de[t>>2]=i;de[r>>2]=n;u=i;break}else Xe()}}while(0);if(a){t=de[e+(l+28)>>2]|0;r=908+(t<<2)|0;if((h|0)==(de[r>>2]|0)){de[r>>2]=u;if(!u){de[152]=de[152]&~(1<>>0<(de[155]|0)>>>0)Xe();t=a+16|0;if((de[t>>2]|0)==(h|0))de[t>>2]=u;else de[a+20>>2]=u;if(!u){y=h;o=c;break}}r=de[155]|0;if(u>>>0>>0)Xe();de[u+24>>2]=a;t=de[e+(l+16)>>2]|0;do{if(t)if(t>>>0>>0)Xe();else{de[u+16>>2]=t;de[t+24>>2]=u;break}}while(0);t=de[e+(l+20)>>2]|0;if(t)if(t>>>0<(de[155]|0)>>>0)Xe();else{de[u+20>>2]=t;de[t+24>>2]=u;y=h;o=c;break}else{y=h;o=c}}else{y=h;o=c}}else{y=t;o=p}}while(0);if(y>>>0>=m>>>0)Xe();t=e+(p+-4)|0;r=de[t>>2]|0;if(!(r&1))Xe();if(!(r&2)){if((m|0)==(de[157]|0)){_=(de[154]|0)+o|0;de[154]=_;de[157]=y;de[y+4>>2]=_|1;if((y|0)!=(de[156]|0))return;de[156]=0;de[153]=0;return}if((m|0)==(de[156]|0)){_=(de[153]|0)+o|0;de[153]=_;de[156]=y;de[y+4>>2]=_|1;de[y+_>>2]=_;return}o=(r&-8)+o|0;n=r>>>3;do{if(r>>>0>=256){a=de[e+(p+16)>>2]|0;t=de[e+(p|4)>>2]|0;do{if((t|0)==(m|0)){r=e+(p+12)|0;t=de[r>>2]|0;if(!t){r=e+(p+8)|0;t=de[r>>2]|0;if(!t){d=0;break}}while(1){i=t+20|0;n=de[i>>2]|0;if(n){t=n;r=i;continue}i=t+16|0;n=de[i>>2]|0;if(!n)break;else{t=n;r=i}}if(r>>>0<(de[155]|0)>>>0)Xe();else{de[r>>2]=0;d=t;break}}else{r=de[e+p>>2]|0;if(r>>>0<(de[155]|0)>>>0)Xe();i=r+12|0;if((de[i>>2]|0)!=(m|0))Xe();n=t+8|0;if((de[n>>2]|0)==(m|0)){de[i>>2]=t;de[n>>2]=r;d=t;break}else Xe()}}while(0);if(a){t=de[e+(p+20)>>2]|0;r=908+(t<<2)|0;if((m|0)==(de[r>>2]|0)){de[r>>2]=d;if(!d){de[152]=de[152]&~(1<>>0<(de[155]|0)>>>0)Xe();t=a+16|0;if((de[t>>2]|0)==(m|0))de[t>>2]=d;else de[a+20>>2]=d;if(!d)break}r=de[155]|0;if(d>>>0>>0)Xe();de[d+24>>2]=a;t=de[e+(p+8)>>2]|0;do{if(t)if(t>>>0>>0)Xe();else{de[d+16>>2]=t;de[t+24>>2]=d;break}}while(0);t=de[e+(p+12)>>2]|0;if(t)if(t>>>0<(de[155]|0)>>>0)Xe();else{de[d+20>>2]=t;de[t+24>>2]=d;break}}}else{i=de[e+p>>2]|0;r=de[e+(p|4)>>2]|0;t=644+(n<<1<<2)|0;if((i|0)!=(t|0)){if(i>>>0<(de[155]|0)>>>0)Xe();if((de[i+12>>2]|0)!=(m|0))Xe()}if((r|0)==(i|0)){de[151]=de[151]&~(1<>>0<(de[155]|0)>>>0)Xe();t=r+8|0;if((de[t>>2]|0)==(m|0))f=t;else Xe()}else f=r+8|0;de[i+12>>2]=r;de[f>>2]=i}}while(0);de[y+4>>2]=o|1;de[y+o>>2]=o;if((y|0)==(de[156]|0)){de[153]=o;return}}else{de[t>>2]=r&-2;de[y+4>>2]=o|1;de[y+o>>2]=o}t=o>>>3;if(o>>>0<256){r=t<<1;n=644+(r<<2)|0;i=de[151]|0;t=1<>2]|0;if(r>>>0<(de[155]|0)>>>0)Xe();else{g=t;v=r}}else{de[151]=i|t;g=644+(r+2<<2)|0;v=n}de[g>>2]=y;de[v+12>>2]=y;de[y+8>>2]=v;de[y+12>>2]=n;return}t=o>>>8;if(t)if(o>>>0>16777215)n=31;else{g=(t+1048320|0)>>>16&8;v=t<>>16&4;v=v<>>16&2;n=14-(m|g|n)+(v<>>15)|0;n=o>>>(n+7|0)&1|n<<1}else n=0;t=908+(n<<2)|0;de[y+28>>2]=n;de[y+20>>2]=0;de[y+16>>2]=0;r=de[152]|0;i=1<>2]|0;t:do{if((de[t+4>>2]&-8|0)!=(o|0)){n=o<<((n|0)==31?0:25-(n>>>1)|0);while(1){r=t+16+(n>>>31<<2)|0;i=de[r>>2]|0;if(!i)break;if((de[i+4>>2]&-8|0)==(o|0)){_=i;break t}else{n=n<<1;t=i}}if(r>>>0<(de[155]|0)>>>0)Xe();else{de[r>>2]=y;de[y+24>>2]=t;de[y+12>>2]=y;de[y+8>>2]=y;break e}}else _=t}while(0);t=_+8|0;r=de[t>>2]|0;v=de[155]|0;if(r>>>0>=v>>>0&_>>>0>=v>>>0){de[r+12>>2]=y;de[t>>2]=y;de[y+8>>2]=r;de[y+12>>2]=_;de[y+24>>2]=0;break}else Xe()}else{de[152]=r|i;de[t>>2]=y;de[y+24>>2]=t;de[y+12>>2]=y;de[y+8>>2]=y}}while(0);y=(de[159]|0)+-1|0;de[159]=y;if(!y)t=1060;else return;while(1){t=de[t>>2]|0;if(!t)break;else t=t+8|0}de[159]=-1;return}function Xr(e,t){e=e|0;t=t|0;var r=0,i=0;if(!e){e=Br(t)|0;return e|0}if(t>>>0>4294967231){e=hr()|0;de[e>>2]=12;e=0;return e|0}r=Gr(e+-8|0,t>>>0<11?16:t+11&-8)|0;if(r){e=r+8|0;return e|0}r=Br(t)|0;if(!r){e=0;return e|0}i=de[e+-4>>2]|0;i=(i&-8)-((i&3|0)==0?8:4)|0;Qr(r|0,e|0,(i>>>0>>0?i:t)|0)|0;Ur(e);e=r;return e|0}function Hr(e){e=e|0;var t=0;if(!e){t=0;return t|0}e=de[e+-4>>2]|0;t=e&3;if((t|0)==1){t=0;return t|0}t=(e&-8)-((t|0)==0?8:4)|0;return t|0}function Gr(e,t){e=e|0;t=t|0;var r=0,i=0,n=0,o=0,a=0,s=0,l=0,u=0,h=0,c=0,f=0,p=0,d=0;p=e+4|0;d=de[p>>2]|0;l=d&-8;h=e+l|0;s=de[155]|0;r=d&3;if(!((r|0)!=1&e>>>0>=s>>>0&e>>>0>>0))Xe();i=e+(l|4)|0;n=de[i>>2]|0;if(!(n&1))Xe();if(!r){if(t>>>0<256){e=0;return e|0}if(l>>>0>=(t+4|0)>>>0?(l-t|0)>>>0<=de[271]<<1>>>0:0)return e|0;e=0;return e|0}if(l>>>0>=t>>>0){r=l-t|0;if(r>>>0<=15)return e|0;de[p>>2]=d&1|t|2;de[e+(t+4)>>2]=r|3;de[i>>2]=de[i>>2]|1;Wr(e+t|0,r);return e|0}if((h|0)==(de[157]|0)){r=(de[154]|0)+l|0;if(r>>>0<=t>>>0){e=0;return e|0}f=r-t|0;de[p>>2]=d&1|t|2;de[e+(t+4)>>2]=f|1;de[157]=e+t;de[154]=f;return e|0}if((h|0)==(de[156]|0)){i=(de[153]|0)+l|0;if(i>>>0>>0){e=0;return e|0}r=i-t|0;if(r>>>0>15){de[p>>2]=d&1|t|2;de[e+(t+4)>>2]=r|1;de[e+i>>2]=r;i=e+(i+4)|0;de[i>>2]=de[i>>2]&-2;i=e+t|0}else{de[p>>2]=d&1|i|2;i=e+(i+4)|0;de[i>>2]=de[i>>2]|1;i=0;r=0}de[153]=r;de[156]=i;return e|0}if(n&2){e=0;return e|0}c=(n&-8)+l|0;if(c>>>0>>0){e=0;return e|0}f=c-t|0;o=n>>>3;do{if(n>>>0>=256){a=de[e+(l+24)>>2]|0;o=de[e+(l+12)>>2]|0;do{if((o|0)==(h|0)){i=e+(l+20)|0;r=de[i>>2]|0;if(!r){i=e+(l+16)|0;r=de[i>>2]|0;if(!r){u=0;break}}while(1){n=r+20|0;o=de[n>>2]|0;if(o){r=o;i=n;continue}n=r+16|0;o=de[n>>2]|0;if(!o)break;else{r=o;i=n}}if(i>>>0>>0)Xe();else{de[i>>2]=0;u=r;break}}else{n=de[e+(l+8)>>2]|0;if(n>>>0>>0)Xe();r=n+12|0;if((de[r>>2]|0)!=(h|0))Xe();i=o+8|0;if((de[i>>2]|0)==(h|0)){de[r>>2]=o;de[i>>2]=n;u=o;break}else Xe()}}while(0);if(a){r=de[e+(l+28)>>2]|0;i=908+(r<<2)|0;if((h|0)==(de[i>>2]|0)){de[i>>2]=u;if(!u){de[152]=de[152]&~(1<>>0<(de[155]|0)>>>0)Xe();r=a+16|0;if((de[r>>2]|0)==(h|0))de[r>>2]=u;else de[a+20>>2]=u;if(!u)break}i=de[155]|0;if(u>>>0>>0)Xe();de[u+24>>2]=a;r=de[e+(l+16)>>2]|0;do{if(r)if(r>>>0>>0)Xe();else{de[u+16>>2]=r;de[r+24>>2]=u;break}}while(0);r=de[e+(l+20)>>2]|0;if(r)if(r>>>0<(de[155]|0)>>>0)Xe();else{de[u+20>>2]=r;de[r+24>>2]=u;break}}}else{n=de[e+(l+8)>>2]|0;i=de[e+(l+12)>>2]|0;r=644+(o<<1<<2)|0;if((n|0)!=(r|0)){if(n>>>0>>0)Xe();if((de[n+12>>2]|0)!=(h|0))Xe()}if((i|0)==(n|0)){de[151]=de[151]&~(1<>>0>>0)Xe();r=i+8|0;if((de[r>>2]|0)==(h|0))a=r;else Xe()}else a=i+8|0;de[n+12>>2]=i;de[a>>2]=n}}while(0);if(f>>>0<16){de[p>>2]=c|d&1|2;t=e+(c|4)|0;de[t>>2]=de[t>>2]|1;return e|0}else{de[p>>2]=d&1|t|2;de[e+(t+4)>>2]=f|3;d=e+(c|4)|0;de[d>>2]=de[d>>2]|1;Wr(e+t|0,f);return e|0}return 0}function Wr(e,t){e=e|0;t=t|0;var r=0,i=0,n=0,o=0,a=0,s=0,l=0,u=0,h=0,c=0,f=0,p=0,d=0,m=0,g=0,v=0,_=0;m=e+t|0;r=de[e+4>>2]|0;do{if(!(r&1)){u=de[e>>2]|0;if(!(r&3))return;f=e+(0-u)|0;c=u+t|0;l=de[155]|0;if(f>>>0>>0)Xe();if((f|0)==(de[156]|0)){i=e+(t+4)|0;r=de[i>>2]|0;if((r&3|0)!=3){_=f;a=c;break}de[153]=c;de[i>>2]=r&-2;de[e+(4-u)>>2]=c|1;de[m>>2]=c;return}o=u>>>3;if(u>>>0<256){n=de[e+(8-u)>>2]|0;i=de[e+(12-u)>>2]|0;r=644+(o<<1<<2)|0;if((n|0)!=(r|0)){if(n>>>0>>0)Xe();if((de[n+12>>2]|0)!=(f|0))Xe()}if((i|0)==(n|0)){de[151]=de[151]&~(1<>>0>>0)Xe();r=i+8|0;if((de[r>>2]|0)==(f|0))s=r;else Xe()}else s=i+8|0;de[n+12>>2]=i;de[s>>2]=n;_=f;a=c;break}s=de[e+(24-u)>>2]|0;n=de[e+(12-u)>>2]|0;do{if((n|0)==(f|0)){n=16-u|0;i=e+(n+4)|0;r=de[i>>2]|0;if(!r){i=e+n|0;r=de[i>>2]|0;if(!r){h=0;break}}while(1){n=r+20|0;o=de[n>>2]|0;if(o){r=o;i=n;continue}n=r+16|0;o=de[n>>2]|0;if(!o)break;else{r=o;i=n}}if(i>>>0>>0)Xe();else{de[i>>2]=0;h=r;break}}else{o=de[e+(8-u)>>2]|0;if(o>>>0>>0)Xe();r=o+12|0;if((de[r>>2]|0)!=(f|0))Xe();i=n+8|0;if((de[i>>2]|0)==(f|0)){de[r>>2]=n;de[i>>2]=o;h=n;break}else Xe()}}while(0);if(s){r=de[e+(28-u)>>2]|0;i=908+(r<<2)|0;if((f|0)==(de[i>>2]|0)){de[i>>2]=h;if(!h){de[152]=de[152]&~(1<>>0<(de[155]|0)>>>0)Xe();r=s+16|0;if((de[r>>2]|0)==(f|0))de[r>>2]=h;else de[s+20>>2]=h;if(!h){_=f;a=c;break}}n=de[155]|0;if(h>>>0>>0)Xe();de[h+24>>2]=s;r=16-u|0;i=de[e+r>>2]|0;do{if(i)if(i>>>0>>0)Xe();else{de[h+16>>2]=i;de[i+24>>2]=h;break}}while(0);r=de[e+(r+4)>>2]|0;if(r)if(r>>>0<(de[155]|0)>>>0)Xe();else{de[h+20>>2]=r;de[r+24>>2]=h;_=f;a=c;break}else{_=f;a=c}}else{_=f;a=c}}else{_=e;a=t}}while(0);l=de[155]|0;if(m>>>0>>0)Xe();r=e+(t+4)|0;i=de[r>>2]|0;if(!(i&2)){if((m|0)==(de[157]|0)){v=(de[154]|0)+a|0;de[154]=v;de[157]=_;de[_+4>>2]=v|1;if((_|0)!=(de[156]|0))return;de[156]=0;de[153]=0;return}if((m|0)==(de[156]|0)){v=(de[153]|0)+a|0;de[153]=v;de[156]=_;de[_+4>>2]=v|1;de[_+v>>2]=v;return}a=(i&-8)+a|0;o=i>>>3;do{if(i>>>0>=256){s=de[e+(t+24)>>2]|0;n=de[e+(t+12)>>2]|0;do{if((n|0)==(m|0)){i=e+(t+20)|0;r=de[i>>2]|0;if(!r){i=e+(t+16)|0;r=de[i>>2]|0;if(!r){d=0;break}}while(1){n=r+20|0;o=de[n>>2]|0;if(o){r=o;i=n;continue}n=r+16|0;o=de[n>>2]|0;if(!o)break;else{r=o;i=n}}if(i>>>0>>0)Xe();else{de[i>>2]=0;d=r;break}}else{o=de[e+(t+8)>>2]|0;if(o>>>0>>0)Xe();r=o+12|0;if((de[r>>2]|0)!=(m|0))Xe();i=n+8|0;if((de[i>>2]|0)==(m|0)){de[r>>2]=n;de[i>>2]=o;d=n;break}else Xe()}}while(0);if(s){r=de[e+(t+28)>>2]|0;i=908+(r<<2)|0;if((m|0)==(de[i>>2]|0)){de[i>>2]=d;if(!d){de[152]=de[152]&~(1<>>0<(de[155]|0)>>>0)Xe();r=s+16|0;if((de[r>>2]|0)==(m|0))de[r>>2]=d;else de[s+20>>2]=d;if(!d)break}i=de[155]|0;if(d>>>0>>0)Xe();de[d+24>>2]=s;r=de[e+(t+16)>>2]|0;do{if(r)if(r>>>0>>0)Xe();else{de[d+16>>2]=r;de[r+24>>2]=d;break}}while(0);r=de[e+(t+20)>>2]|0;if(r)if(r>>>0<(de[155]|0)>>>0)Xe();else{de[d+20>>2]=r;de[r+24>>2]=d;break}}}else{n=de[e+(t+8)>>2]|0;i=de[e+(t+12)>>2]|0;r=644+(o<<1<<2)|0;if((n|0)!=(r|0)){if(n>>>0>>0)Xe();if((de[n+12>>2]|0)!=(m|0))Xe()}if((i|0)==(n|0)){de[151]=de[151]&~(1<>>0>>0)Xe();r=i+8|0;if((de[r>>2]|0)==(m|0))p=r;else Xe()}else p=i+8|0;de[n+12>>2]=i;de[p>>2]=n}}while(0);de[_+4>>2]=a|1;de[_+a>>2]=a;if((_|0)==(de[156]|0)){de[153]=a;return}}else{de[r>>2]=i&-2;de[_+4>>2]=a|1;de[_+a>>2]=a}r=a>>>3;if(a>>>0<256){i=r<<1;o=644+(i<<2)|0;n=de[151]|0;r=1<>2]|0;if(i>>>0<(de[155]|0)>>>0)Xe();else{g=r;v=i}}else{de[151]=n|r;g=644+(i+2<<2)|0;v=o}de[g>>2]=_;de[v+12>>2]=_;de[_+8>>2]=v;de[_+12>>2]=o;return}r=a>>>8;if(r)if(a>>>0>16777215)o=31;else{g=(r+1048320|0)>>>16&8;v=r<>>16&4;v=v<>>16&2;o=14-(m|g|o)+(v<>>15)|0;o=a>>>(o+7|0)&1|o<<1}else o=0;r=908+(o<<2)|0;de[_+28>>2]=o;de[_+20>>2]=0;de[_+16>>2]=0;i=de[152]|0;n=1<>2]=_;de[_+24>>2]=r;de[_+12>>2]=_;de[_+8>>2]=_;return}r=de[r>>2]|0;e:do{if((de[r+4>>2]&-8|0)!=(a|0)){o=a<<((o|0)==31?0:25-(o>>>1)|0);while(1){i=r+16+(o>>>31<<2)|0;n=de[i>>2]|0;if(!n)break;if((de[n+4>>2]&-8|0)==(a|0)){r=n;break e}else{o=o<<1;r=n}}if(i>>>0<(de[155]|0)>>>0)Xe();de[i>>2]=_;de[_+24>>2]=r;de[_+12>>2]=_;de[_+8>>2]=_;return}}while(0);i=r+8|0;n=de[i>>2]|0;v=de[155]|0;if(!(n>>>0>=v>>>0&r>>>0>=v>>>0))Xe();de[n+12>>2]=_;de[i>>2]=_;de[_+8>>2]=n;de[_+12>>2]=r;de[_+24>>2]=0;return}function qr(){}function Vr(e,t,r,i){e=e|0;t=t|0;r=r|0;i=i|0;i=t-i-(r>>>0>e>>>0|0)>>>0;return(re=i,e-r>>>0|0)|0}function Yr(e,t,r){e=e|0;t=t|0;r=r|0;var i=0,n=0,o=0,a=0;i=e+r|0;if((r|0)>=20){t=t&255;o=e&3;a=t|t<<8|t<<16|t<<24;n=i&~3;if(o){o=e+4-o|0;while((e|0)<(o|0)){pe[e>>0]=t;e=e+1|0}}while((e|0)<(n|0)){de[e>>2]=a;e=e+4|0}}while((e|0)<(i|0)){pe[e>>0]=t;e=e+1|0}return e-r|0}function Zr(e,t,r){e=e|0;t=t|0;r=r|0;if((r|0)<32){re=t>>>r;return e>>>r|(t&(1<>>r-32|0}function Jr(e,t,r){e=e|0;t=t|0;r=r|0;if((r|0)<32){re=t<>>32-r;return e<>>0;return(re=t+i+(r>>>0>>0|0)>>>0,r|0)|0}function Qr(e,t,r){e=e|0;t=t|0;r=r|0;var i=0;if((r|0)>=4096)return Me(e|0,t|0,r|0)|0;i=e|0;if((e&3)==(t&3)){while(e&3){if(!r)return i|0;pe[e>>0]=pe[t>>0]|0;e=e+1|0;t=t+1|0;r=r-1|0}while((r|0)>=4){de[e>>2]=de[t>>2];e=e+4|0;t=t+4|0;r=r-4|0}}while((r|0)>0){pe[e>>0]=pe[t>>0]|0;e=e+1|0;t=t+1|0;r=r-1|0}return i|0}function $r(e,t,r){e=e|0;t=t|0;r=r|0;if((r|0)<32){re=t>>r;return e>>>r|(t&(1<>r-32|0}function ei(e){e=e|0;var t=0;t=pe[g+(e&255)>>0]|0;if((t|0)<8)return t|0;t=pe[g+(e>>8&255)>>0]|0;if((t|0)<8)return t+8|0;t=pe[g+(e>>16&255)>>0]|0;if((t|0)<8)return t+16|0;return(pe[g+(e>>>24)>>0]|0)+24|0}function ti(e,t){e=e|0;t=t|0;var r=0,i=0,n=0,o=0;o=e&65535;n=t&65535;r=_e(n,o)|0;i=e>>>16;e=(r>>>16)+(_e(n,i)|0)|0;n=t>>>16;t=_e(n,o)|0;return(re=(e>>>16)+(_e(n,i)|0)+(((e&65535)+t|0)>>>16)|0,e+t<<16|r&65535|0)|0}function ri(e,t,r,i){e=e|0;t=t|0;r=r|0;i=i|0;var n=0,o=0,a=0,s=0,l=0,u=0;u=t>>31|((t|0)<0?-1:0)<<1;l=((t|0)<0?-1:0)>>31|((t|0)<0?-1:0)<<1;o=i>>31|((i|0)<0?-1:0)<<1;n=((i|0)<0?-1:0)>>31|((i|0)<0?-1:0)<<1;s=Vr(u^e,l^t,u,l)|0;a=re;e=o^u;t=n^l;return Vr((si(s,a,Vr(o^r,n^i,o,n)|0,re,0)|0)^e,re^t,e,t)|0}function ii(e,t,r,i){e=e|0;t=t|0;r=r|0;i=i|0;var n=0,o=0,a=0,s=0,l=0,u=0;n=ve;ve=ve+16|0;s=n|0;a=t>>31|((t|0)<0?-1:0)<<1;o=((t|0)<0?-1:0)>>31|((t|0)<0?-1:0)<<1;u=i>>31|((i|0)<0?-1:0)<<1;l=((i|0)<0?-1:0)>>31|((i|0)<0?-1:0)<<1;e=Vr(a^e,o^t,a,o)|0;t=re;si(e,t,Vr(u^r,l^i,u,l)|0,re,s)|0;i=Vr(de[s>>2]^a,de[s+4>>2]^o,a,o)|0;r=re;ve=n;return(re=r,i)|0}function ni(e,t,r,i){e=e|0;t=t|0;r=r|0;i=i|0;var n=0,o=0;n=e;o=r;r=ti(n,o)|0;e=re;return(re=(_e(t,o)|0)+(_e(i,n)|0)+e|e&0,r|0|0)|0}function oi(e,t,r,i){e=e|0;t=t|0;r=r|0;i=i|0;return si(e,t,r,i,0)|0}function ai(e,t,r,i){e=e|0;t=t|0;r=r|0;i=i|0;var n=0,o=0;o=ve;ve=ve+16|0;n=o|0;si(e,t,r,i,n)|0;ve=o;return(re=de[n+4>>2]|0,de[n>>2]|0)|0}function si(e,t,r,i,n){e=e|0;t=t|0;r=r|0;i=i|0;n=n|0;var o=0,a=0,s=0,l=0,u=0,h=0,c=0,f=0,p=0,d=0;h=e;l=t;u=l;a=r;f=i;s=f;if(!u){o=(n|0)!=0;if(!s){if(o){de[n>>2]=(h>>>0)%(a>>>0);de[n+4>>2]=0}f=0;n=(h>>>0)/(a>>>0)>>>0;return(re=f,n)|0}else{if(!o){f=0;n=0;return(re=f,n)|0}de[n>>2]=e|0;de[n+4>>2]=t&0;f=0;n=0;return(re=f,n)|0}}o=(s|0)==0;do{if(a){if(!o){o=(ae(s|0)|0)-(ae(u|0)|0)|0;if(o>>>0<=31){c=o+1|0;s=31-o|0;t=o-31>>31;a=c;e=h>>>(c>>>0)&t|u<>>(c>>>0)&t;o=0;s=h<>2]=e|0;de[n+4>>2]=l|t&0;f=0;n=0;return(re=f,n)|0}o=a-1|0;if(o&a){s=(ae(a|0)|0)+33-(ae(u|0)|0)|0;d=64-s|0;c=32-s|0;l=c>>31;p=s-32|0;t=p>>31;a=s;e=c-1>>31&u>>>(p>>>0)|(u<>>(s>>>0))&t;t=t&u>>>(s>>>0);o=h<>>(p>>>0))&l|h<>31;break}if(n){de[n>>2]=o&h;de[n+4>>2]=0}if((a|0)==1){p=l|t&0;d=e|0|0;return(re=p,d)|0}else{d=ei(a|0)|0;p=u>>>(d>>>0)|0;d=u<<32-d|h>>>(d>>>0)|0;return(re=p,d)|0}}else{if(o){if(n){de[n>>2]=(u>>>0)%(a>>>0);de[n+4>>2]=0}p=0;d=(u>>>0)/(a>>>0)>>>0;return(re=p,d)|0}if(!h){if(n){de[n>>2]=0;de[n+4>>2]=(u>>>0)%(s>>>0)}p=0;d=(u>>>0)/(s>>>0)>>>0;return(re=p,d)|0}o=s-1|0;if(!(o&s)){if(n){de[n>>2]=e|0;de[n+4>>2]=o&u|t&0}p=0;d=u>>>((ei(s|0)|0)>>>0);return(re=p,d)|0}o=(ae(s|0)|0)-(ae(u|0)|0)|0;if(o>>>0<=30){t=o+1|0;s=31-o|0;a=t;e=u<>>(t>>>0);t=u>>>(t>>>0);o=0;s=h<>2]=e|0;de[n+4>>2]=l|t&0;p=0;d=0;return(re=p,d)|0}}while(0);if(!a){u=s;l=0;s=0}else{c=r|0|0;h=f|i&0;u=Kr(c|0,h|0,-1,-1)|0;r=re;l=s;s=0;do{i=l;l=o>>>31|l<<1;o=s|o<<1;i=e<<1|i>>>31|0;f=e>>>31|t<<1|0;Vr(u,r,i,f)|0;d=re;p=d>>31|((d|0)<0?-1:0)<<1;s=p&1;e=Vr(i,f,p&c,(((d|0)<0?-1:0)>>31|((d|0)<0?-1:0)<<1)&h)|0;t=re;a=a-1|0}while((a|0)!=0);u=l;l=0}a=0;if(n){de[n>>2]=e;de[n+4>>2]=t}p=(o|0)>>>31|(u|a)<<1|(a<<1|o>>>31)&0|l;d=(o<<1|0>>>31)&-2|s;return(re=p,d)|0}function li(e,t,r,i){e=e|0;t=t|0;r=r|0;i=i|0;return Si[e&7](t|0,r|0,i|0)|0}function ui(e,t,r,i,n,o){e=e|0;t=t|0;r=r|0;i=i|0;n=n|0;o=o|0;Ei[e&3](t|0,r|0,i|0,n|0,o|0)}function hi(e,t){e=e|0;t=t|0;Ai[e&7](t|0)}function ci(e,t){e=e|0;t=t|0;return Ci[e&1](t|0)|0}function fi(e,t,r,i){e=e|0;t=t|0;r=r|0;i=i|0;Ii[e&0](t|0,r|0,i|0)}function pi(e){e=e|0;Oi[e&3]()}function di(e,t,r,i,n,o,a){e=e|0;t=t|0;r=r|0;i=i|0;n=n|0;o=o|0;a=a|0;Mi[e&3](t|0,r|0,i|0,n|0,o|0,a|0)}function mi(e,t,r,i,n,o){e=e|0;t=t|0;r=r|0;i=i|0;n=n|0;o=o|0;return Di[e&1](t|0,r|0,i|0,n|0,o|0)|0}function gi(e,t,r,i,n){e=e|0;t=t|0;r=r|0;i=i|0;n=n|0;Ri[e&3](t|0,r|0,i|0,n|0)}function vi(e,t,r){e=e|0;t=t|0;r=r|0;se(0);return 0}function _i(e,t,r,i,n){e=e|0;t=t|0;r=r|0;i=i|0;n=n|0;se(1)}function yi(e){e=e|0;se(2)}function bi(e){e=e|0;se(3);return 0}function xi(e,t,r){e=e|0;t=t|0;r=r|0;se(4)}function wi(){se(5)}function Ti(e,t,r,i,n,o){e=e|0;t=t|0;r=r|0;i=i|0;n=n|0;o=o|0;se(6)}function ki(e,t,r,i,n){e=e|0;t=t|0;r=r|0;i=i|0;n=n|0;se(7);return 0}function Pi(e,t,r,i){e=e|0;t=t|0;r=r|0;i=i|0;se(8)}var Si=[vi,Yt,Lr,Cr,Ar,Ir,vi,vi];var Ei=[_i,tr,er,_i];var Ai=[yi,Ht,qt,Gt,Wt,Vt,lr,zr];var Ci=[bi,Er];var Ii=[xi];var Oi=[wi,ar,sr,wi];var Mi=[Ti,ir,rr,Ti];var Di=[ki,lt];var Ri=[Pi,Jt,Kt,Pi];return{___cxa_can_catch:nr,_crn_get_levels:Tt,_crn_get_uncompressed_size:Pt,_crn_decompress:St,_i64Add:Kr,_crn_get_width:xt,___cxa_is_pointer_type:or,_i64Subtract:Vr,_memset:Yr,_malloc:Br,_free:Ur,_memcpy:Qr,_bitshift64Lshr:Zr,_fflush:gr,_bitshift64Shl:Jr,_crn_get_height:wt,___errno_location:hr,_crn_get_dxt_format:kt,runPostSets:qr,_emscripten_replace_memory:Ye,stackAlloc:Ze,stackSave:Je,stackRestore:Ke,establishStackSpace:Qe,setThrew:$e,setTempRet0:rt,getTempRet0:it,dynCall_iiii:li,dynCall_viiiii:ui,dynCall_vi:hi,dynCall_ii:ci,dynCall_viii:fi,dynCall_v:pi,dynCall_viiiiii:di,dynCall_iiiiii:mi,dynCall_viiii:gi}}(e.Ya,e.Za,buffer);e.___cxa_can_catch=Z.___cxa_can_catch,e._crn_get_levels=Z._crn_get_levels,e.runPostSets=Z.runPostSets,e._crn_get_uncompressed_size=Z._crn_get_uncompressed_size,e._crn_decompress=Z._crn_decompress;var zc=e._i64Add=Z._i64Add;e._crn_get_height=Z._crn_get_height,e.___cxa_is_pointer_type=Z.___cxa_is_pointer_type;var nb=e._i64Subtract=Z._i64Subtract,qb=e._memset=Z._memset,Ea=e._malloc=Z._malloc,Bc=e._memcpy=Z._memcpy,Xa=e._emscripten_replace_memory=Z._emscripten_replace_memory;e._crn_get_dxt_format=Z._crn_get_dxt_format;var rb=e._bitshift64Lshr=Z._bitshift64Lshr,Na=e._free=Z._free;e._fflush=Z._fflush,e._crn_get_width=Z._crn_get_width,e.___errno_location=Z.___errno_location;var sb=e._bitshift64Shl=Z._bitshift64Shl;function ia(e){this.name="ExitStatus",this.message="Program terminated with exit("+e+")",this.status=e}e.dynCall_iiii=Z.dynCall_iiii,e.dynCall_viiiii=Z.dynCall_viiiii,e.dynCall_vi=Z.dynCall_vi,e.dynCall_ii=Z.dynCall_ii,e.dynCall_viii=Z.dynCall_viii,e.dynCall_v=Z.dynCall_v,e.dynCall_viiiiii=Z.dynCall_viiiiii,e.dynCall_iiiiii=Z.dynCall_iiiiii,e.dynCall_viiii=Z.dynCall_viiii,n.aa=Z.stackAlloc,n.ua=Z.stackSave,n.ba=Z.stackRestore,n.Cd=Z.establishStackSpace,n.rb=Z.setTempRet0,n.fb=Z.getTempRet0,ia.prototype=Error(),ia.prototype.constructor=ia;var rd=null,jb=function t(){e.calledRun||td(),e.calledRun||(jb=t)};function td(t){function r(){if(!e.calledRun&&(e.calledRun=!0,!na)){if(Ha||(Ha=!0,ab(cb)),ab(db),e.onRuntimeInitialized&&e.onRuntimeInitialized(),e._main&&vd&&e.callMain(t),e.postRun)for("function"==typeof e.postRun&&(e.postRun=[e.postRun]);e.postRun.length;)gb(e.postRun.shift());ab(eb)}}if(t=t||e.arguments,null===rd&&(rd=Date.now()),!(0>8&255,e>>16&255,e>>24&255)}!function(s){s.loadFromArrayBuffer=function(e,t,r){return new i(t).loadFromArrayBuffer(e,r)};var i=function(l){function e(e,t,r,i,n,o,a){var s=l.call(this)||this;return s.complete=!1,s.isCompressedImage=!0,s.preserveSource=!0,s.onload=null,s.baseTexture=null,s.init(e,t,r,i,n,o,a),s}return __extends(e,l),e.prototype.init=function(e,t,r,i,n,o,a){void 0===i&&(i=-1),void 0===n&&(n=-1),this.src=e,this.resize(i,n),this._width=i,this._height=n,this.data=t,this.type=r,this.levels=o,this.internalFormat=a;var s=this.complete;return this.complete=!!t,!s&&this.complete&&this.onload&&this.onload({target:this}),this.update(),this},e.prototype.dispose=function(){this.data=null},e.prototype.bind=function(e){void 0!==e.alphaMode?e.alphaMode=PIXI.ALPHA_MODES.NO_PREMULTIPLIED_ALPHA:e.premultiplyAlpha=!1,l.prototype.bind.call(this,e)},e.prototype.upload=function(e,t,r){var i=e.state.gl;if(r.compressed=!1,e.texture.initCompressed(),null===this.data)throw"Trying to create a second (or more) webgl texture from the same CompressedImage : "+this.src;for(var n=this.levels,o=this.width,a=this.height,s=0,l=0;l>=1)<1&&(o=1),(a>>=1)<1&&(a=1),s+=u}return this._internalLoader.free(),this.preserveSource||(this.data=null),!0},e.prototype.style=function(e,t,r){var i=e.state.gl,n=this.levels;return t.scaleMode===PIXI.SCALE_MODES.LINEAR?1>2)*(t+3>>2)*8;case 33778:case 33779:case 35987:case 34798:return(e+3>>2)*(t+3>>2)*16;default:return 0}},h.type="DDS",h}(e.AbstractInternalLoader);e.DDSLoader=l}(pixi_compressed_textures||(pixi_compressed_textures={})),function(e){var t,c=((t={})[0]=35841,t[1]=35843,t[2]=35840,t[3]=35842,t[6]=36196,t[7]=33776,t[9]=33778,t[5]=33779,t),r=function(t){function h(e){return t.call(this,e)||this}return __extends(h,t),h.prototype.load=function(e){if(!h.test(e))throw"Invalid magic number in PVR header";var t=new Int32Array(e,0,13),r=t[2],i=c[r]||-1,n=t[7],o=t[6],a=t[11],s=t[12]+52,l=new Uint8Array(e,s),u=this._image;return this._format=i,u.init(u.src,l,"PVR",n,o,a,i),u},h.test=function(e){return 55727696===new Int32Array(e,0,1)[0]},h.prototype.levelBufferSize=function(e,t,r){switch(void 0===r&&(r=0),this._format){case 33776:case 36196:return(e+3>>2)*(t+3>>2)*8;case 33778:case 33779:return(e+3>>2)*(t+3>>2)*16;case 35840:case 35842:return Math.floor((Math.max(e,8)*Math.max(t,8)*4+7)/8);case 35841:case 35843:return Math.floor((Math.max(e,16)*Math.max(t,8)*2+7)/8);default:return 0}},h.type="PVR",h}(e.AbstractInternalLoader);e.PVRTCLoader=r}(pixi_compressed_textures||(pixi_compressed_textures={})),function(l){var e,t,r=0,i=2,n=3,o=8,a=9,s=10,u=11,c=((e={})[3]=!0,e[9]=!0,e[10]=!0,e[11]=!0,e),h=((t={})[u]=-1,t[r]=36196,t[i]=33776,t[n]=33779,t[o]=35840,t[a]=35842,t[s]=37808,t),f=Object.keys(h).reduce(function(e,t){return e[h[+t]]=+t,e},{}),p=function(r){function h(e){var t=r.call(this,e)||this;return t.type="BASIS",t._file=void 0,t}return __extends(h,r),h.test=function(e){var t=1262195===new Uint32Array(e,0,1)[0]&&!!h.BASIS_BINDING,r=h.RGB_FORMAT&&h.RGBA_FORMAT;return!t&&r&&console.warn("[BASIS LOADER] Is Supported, but transcoder not binded or file is not BASIS file!"),r&&t},h.bindTranscoder=function(e,i){if(!e||!i)throw"Invalid state! undef fileCtr or ext invalid!";var t=Object.keys(i).reduce(function(e,t){var r=i[t];return r?Object.assign(e,r.__proto__):e},{}),r=void 0,n=void 0;for(var o in t){var a=t[o];if(void 0!==f[a]){var s=f[a];c[s]?n={native:a,name:o,basis:s}:r={native:a,name:o,basis:s}}}h.RGB_FORMAT=r||n,h.RGBA_FORMAT=n||r,h.BASIS_BINDING=e,console.log("[BASISLoader] Supported formats:","\nRGB:"+h.RGB_FORMAT.name+"\nRGBA:"+h.RGBA_FORMAT.name),l.RegisterCompressedLoader(h),l.RegisterCompressedExtensions("basis")},h.prototype.load=function(e){if(!h.test(e))throw"BASIS Transcoder not binded or transcoding not supported =(!";return this._loadAsync(e),this._image},h.prototype._loadAsync=function(e){var t=performance.now(),r=new h.BASIS_BINDING(new Uint8Array(e)),i=r.getImageWidth(0,0),n=r.getImageHeight(0,0),o=r.getHasAlpha(),a=this._image;if(!r.startTranscoding())throw"Transcoding error!";var s=o?h.RGBA_FORMAT:h.RGB_FORMAT;console.log("Grats! BASIS will be transcoded to:",s);var l=new Uint8Array(r.getImageTranscodedSizeInBytes(0,0,s.basis));if(!r.transcodeImage(l,0,0,s.basis,!1,!1))throw"Transcoding error!";console.log("[BASISLoader] Totla transcoding time:",performance.now()-t),this._format=s.native,this._file=r;var u=s.name.replace("COMPRESSED_","");return Promise.resolve(a.init(a.src,l,"BASIS|"+u,i,n,1,s.native))},h.prototype.levelBufferSize=function(e,t,r){return this._file?this._file.getImageTranscodedSizeInBytes(0,r,f[this._format]):void 0},h.BASIS_BINDING=void 0,h}(l.AbstractInternalLoader);l.BASISLoader=p}(pixi_compressed_textures||(pixi_compressed_textures={})),function(i){var p=window.CRN_Module;var d=[33776,33778,33779],e=function(t){function e(e){return t.call(this,e)||this}return __extends(e,t),e.prototype.load=function(e){var t=e.byteLength,r=new Uint8Array(e),i=p._malloc(t);!function(e,t,r,i){for(var n=r/4,o=i%4,a=new Uint32Array(e.buffer,0,(i-o)/4),s=new Uint32Array(t.buffer),l=0;li.count)){var e=new a;return i.workers.push(e),e.init(t,r).then(function(){r=e.binary,o()})}};return o().then(function(){return i})},e.prototype.transcode=function(t,r){if(!this.workers||!this.workers.length)throw"[TranscoderWorkerPool] Pool empty, populate before!";var n=this.workers,o=void 0,a=0,s=function(e){for(var t=0,r=n;t 0.0) {\n c.rgb /= c.a;\n\n vec3 rgb = pow(c.rgb, vec3(1. / gamma));\n rgb = mix(vec3(.5), mix(vec3(dot(vec3(.2125, .7154, .0721), rgb)), rgb, saturation), contrast);\n rgb.r *= red;\n rgb.g *= green;\n rgb.b *= blue;\n c.rgb = rgb * brightness;\n\n c.rgb *= c.a;\n }\n\n gl_FragColor = c * alpha;\n}\n"),Object.assign(this,{gamma:1,saturation:1,contrast:1,brightness:1,red:1,green:1,blue:1,alpha:1},e)}return t&&(e.__proto__=t),((e.prototype=Object.create(t&&t.prototype)).constructor=e).prototype.apply=function(e,t,r,i){this.uniforms.gamma=Math.max(this.gamma,1e-4),this.uniforms.saturation=this.saturation,this.uniforms.contrast=this.contrast,this.uniforms.brightness=this.brightness,this.uniforms.red=this.red,this.uniforms.green=this.green,this.uniforms.blue=this.blue,this.uniforms.alpha=this.alpha,e.applyFilter(this,t,r,i)},e}(n.Filter),d=function(i){function e(e,t,r){void 0===e&&(e=4),void 0===t&&(t=3),void 0===r&&(r=!1),i.call(this,"attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n vTextureCoord = aTextureCoord;\n}",r?"\nvarying vec2 vTextureCoord;\nuniform sampler2D uSampler;\n\nuniform vec2 uOffset;\nuniform vec4 filterClamp;\n\nvoid main(void)\n{\n vec4 color = vec4(0.0);\n\n // Sample top left pixel\n color += texture2D(uSampler, clamp(vec2(vTextureCoord.x - uOffset.x, vTextureCoord.y + uOffset.y), filterClamp.xy, filterClamp.zw));\n\n // Sample top right pixel\n color += texture2D(uSampler, clamp(vec2(vTextureCoord.x + uOffset.x, vTextureCoord.y + uOffset.y), filterClamp.xy, filterClamp.zw));\n\n // Sample bottom right pixel\n color += texture2D(uSampler, clamp(vec2(vTextureCoord.x + uOffset.x, vTextureCoord.y - uOffset.y), filterClamp.xy, filterClamp.zw));\n\n // Sample bottom left pixel\n color += texture2D(uSampler, clamp(vec2(vTextureCoord.x - uOffset.x, vTextureCoord.y - uOffset.y), filterClamp.xy, filterClamp.zw));\n\n // Average\n color *= 0.25;\n\n gl_FragColor = color;\n}\n":"\nvarying vec2 vTextureCoord;\nuniform sampler2D uSampler;\n\nuniform vec2 uOffset;\n\nvoid main(void)\n{\n vec4 color = vec4(0.0);\n\n // Sample top left pixel\n color += texture2D(uSampler, vec2(vTextureCoord.x - uOffset.x, vTextureCoord.y + uOffset.y));\n\n // Sample top right pixel\n color += texture2D(uSampler, vec2(vTextureCoord.x + uOffset.x, vTextureCoord.y + uOffset.y));\n\n // Sample bottom right pixel\n color += texture2D(uSampler, vec2(vTextureCoord.x + uOffset.x, vTextureCoord.y - uOffset.y));\n\n // Sample bottom left pixel\n color += texture2D(uSampler, vec2(vTextureCoord.x - uOffset.x, vTextureCoord.y - uOffset.y));\n\n // Average\n color *= 0.25;\n\n gl_FragColor = color;\n}"),this.uniforms.uOffset=new Float32Array(2),this._pixelSize=new f.Point,this.pixelSize=1,this._clamp=r,this._kernels=null,Array.isArray(e)?this.kernels=e:(this._blur=e,this.quality=t)}i&&(e.__proto__=i);var t={kernels:{configurable:!0},clamp:{configurable:!0},pixelSize:{configurable:!0},quality:{configurable:!0},blur:{configurable:!0}};return((e.prototype=Object.create(i&&i.prototype)).constructor=e).prototype.apply=function(e,t,r,i){var n,o=this.pixelSize.x/t._frame.width,a=this.pixelSize.y/t._frame.height;if(1===this._quality||0===this._blur)n=this._kernels[0]+.5,this.uniforms.uOffset[0]=n*o,this.uniforms.uOffset[1]=n*a,e.applyFilter(this,t,r,i);else{for(var s,l=e.getFilterTexture(),u=t,h=l,c=this._quality-1,f=0;f threshold) {\n gl_FragColor = color;\n } else {\n gl_FragColor = vec4(0.0, 0.0, 0.0, 0.0);\n }\n}\n"),this.threshold=e}t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e;var r={threshold:{configurable:!0}};return r.threshold.get=function(){return this.uniforms.threshold},r.threshold.set=function(e){this.uniforms.threshold=e},Object.defineProperties(e.prototype,r),e}(n.Filter),i=function(a){function e(e){a.call(this,c,"uniform sampler2D uSampler;\nvarying vec2 vTextureCoord;\n\nuniform sampler2D bloomTexture;\nuniform float bloomScale;\nuniform float brightness;\n\nvoid main() {\n vec4 color = texture2D(uSampler, vTextureCoord);\n color.rgb *= brightness;\n vec4 bloomColor = vec4(texture2D(bloomTexture, vTextureCoord).rgb, 0.0);\n bloomColor.rgb *= bloomScale;\n gl_FragColor = color + bloomColor;\n}\n"),"number"==typeof e&&(e={threshold:e}),e=Object.assign({threshold:.5,bloomScale:1,brightness:1,kernels:null,blur:8,quality:4,pixelSize:1,resolution:p.settings.RESOLUTION},e),this.bloomScale=e.bloomScale,this.brightness=e.brightness;var t=e.kernels,r=e.blur,i=e.quality,n=e.pixelSize,o=e.resolution;this._extractFilter=new m(e.threshold),this._extractFilter.resolution=o,this._blurFilter=t?new d(t):new d(r,i),this.pixelSize=n,this.resolution=o}a&&(e.__proto__=a);var t={resolution:{configurable:!0},threshold:{configurable:!0},kernels:{configurable:!0},blur:{configurable:!0},quality:{configurable:!0},pixelSize:{configurable:!0}};return((e.prototype=Object.create(a&&a.prototype)).constructor=e).prototype.apply=function(e,t,r,i,n){var o=e.getFilterTexture();this._extractFilter.apply(e,t,o,!0,n);var a=e.getFilterTexture();this._blurFilter.apply(e,o,a,!0,n),this.uniforms.bloomScale=this.bloomScale,this.uniforms.brightness=this.brightness,this.uniforms.bloomTexture=a,e.applyFilter(this,t,r,i),e.returnFilterTexture(a),e.returnFilterTexture(o)},t.resolution.get=function(){return this._resolution},t.resolution.set=function(e){this._resolution=e,this._extractFilter&&(this._extractFilter.resolution=e),this._blurFilter&&(this._blurFilter.resolution=e)},t.threshold.get=function(){return this._extractFilter.threshold},t.threshold.set=function(e){this._extractFilter.threshold=e},t.kernels.get=function(){return this._blurFilter.kernels},t.kernels.set=function(e){this._blurFilter.kernels=e},t.blur.get=function(){return this._blurFilter.blur},t.blur.set=function(e){this._blurFilter.blur=e},t.quality.get=function(){return this._blurFilter.quality},t.quality.set=function(e){this._blurFilter.quality=e},t.pixelSize.get=function(){return this._blurFilter.pixelSize},t.pixelSize.set=function(e){this._blurFilter.pixelSize=e},Object.defineProperties(e.prototype,t),e}(n.Filter),o=function(t){function e(e){void 0===e&&(e=8),t.call(this,"attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n vTextureCoord = aTextureCoord;\n}","varying vec2 vTextureCoord;\n\nuniform vec4 filterArea;\nuniform float pixelSize;\nuniform sampler2D uSampler;\n\nvec2 mapCoord( vec2 coord )\n{\n coord *= filterArea.xy;\n coord += filterArea.zw;\n\n return coord;\n}\n\nvec2 unmapCoord( vec2 coord )\n{\n coord -= filterArea.zw;\n coord /= filterArea.xy;\n\n return coord;\n}\n\nvec2 pixelate(vec2 coord, vec2 size)\n{\n return floor( coord / size ) * size;\n}\n\nvec2 getMod(vec2 coord, vec2 size)\n{\n return mod( coord , size) / size;\n}\n\nfloat character(float n, vec2 p)\n{\n p = floor(p*vec2(4.0, -4.0) + 2.5);\n\n if (clamp(p.x, 0.0, 4.0) == p.x)\n {\n if (clamp(p.y, 0.0, 4.0) == p.y)\n {\n if (int(mod(n/exp2(p.x + 5.0*p.y), 2.0)) == 1) return 1.0;\n }\n }\n return 0.0;\n}\n\nvoid main()\n{\n vec2 coord = mapCoord(vTextureCoord);\n\n // get the rounded color..\n vec2 pixCoord = pixelate(coord, vec2(pixelSize));\n pixCoord = unmapCoord(pixCoord);\n\n vec4 color = texture2D(uSampler, pixCoord);\n\n // determine the character to use\n float gray = (color.r + color.g + color.b) / 3.0;\n\n float n = 65536.0; // .\n if (gray > 0.2) n = 65600.0; // :\n if (gray > 0.3) n = 332772.0; // *\n if (gray > 0.4) n = 15255086.0; // o\n if (gray > 0.5) n = 23385164.0; // &\n if (gray > 0.6) n = 15252014.0; // 8\n if (gray > 0.7) n = 13199452.0; // @\n if (gray > 0.8) n = 11512810.0; // #\n\n // get the mod..\n vec2 modd = getMod(coord, vec2(pixelSize));\n\n gl_FragColor = color * character( n, vec2(-1.0) + modd * 2.0);\n\n}\n"),this.size=e}t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e;var r={size:{configurable:!0}};return r.size.get=function(){return this.uniforms.pixelSize},r.size.set=function(e){this.uniforms.pixelSize=e},Object.defineProperties(e.prototype,r),e}(n.Filter),a=function(t){function e(e){void 0===e&&(e={}),t.call(this,"attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n vTextureCoord = aTextureCoord;\n}","precision mediump float;\n\nvarying vec2 vTextureCoord;\nuniform sampler2D uSampler;\nuniform vec4 filterArea;\n\nuniform float transformX;\nuniform float transformY;\nuniform vec3 lightColor;\nuniform float lightAlpha;\nuniform vec3 shadowColor;\nuniform float shadowAlpha;\n\nvoid main(void) {\n vec2 transform = vec2(1.0 / filterArea) * vec2(transformX, transformY);\n vec4 color = texture2D(uSampler, vTextureCoord);\n float light = texture2D(uSampler, vTextureCoord - transform).a;\n float shadow = texture2D(uSampler, vTextureCoord + transform).a;\n\n color.rgb = mix(color.rgb, lightColor, clamp((color.a - light) * lightAlpha, 0.0, 1.0));\n color.rgb = mix(color.rgb, shadowColor, clamp((color.a - shadow) * shadowAlpha, 0.0, 1.0));\n gl_FragColor = vec4(color.rgb * color.a, color.a);\n}\n"),this.uniforms.lightColor=new Float32Array(3),this.uniforms.shadowColor=new Float32Array(3),e=Object.assign({rotation:45,thickness:2,lightColor:16777215,lightAlpha:.7,shadowColor:0,shadowAlpha:.7},e),this.rotation=e.rotation,this.thickness=e.thickness,this.lightColor=e.lightColor,this.lightAlpha=e.lightAlpha,this.shadowColor=e.shadowColor,this.shadowAlpha=e.shadowAlpha}t&&(e.__proto__=t);var r={rotation:{configurable:!0},thickness:{configurable:!0},lightColor:{configurable:!0},lightAlpha:{configurable:!0},shadowColor:{configurable:!0},shadowAlpha:{configurable:!0}};return((e.prototype=Object.create(t&&t.prototype)).constructor=e).prototype._updateTransform=function(){this.uniforms.transformX=this._thickness*Math.cos(this._angle),this.uniforms.transformY=this._thickness*Math.sin(this._angle)},r.rotation.get=function(){return this._angle/f.DEG_TO_RAD},r.rotation.set=function(e){this._angle=e*f.DEG_TO_RAD,this._updateTransform()},r.thickness.get=function(){return this._thickness},r.thickness.set=function(e){this._thickness=e,this._updateTransform()},r.lightColor.get=function(){return l.rgb2hex(this.uniforms.lightColor)},r.lightColor.set=function(e){l.hex2rgb(e,this.uniforms.lightColor)},r.lightAlpha.get=function(){return this.uniforms.lightAlpha},r.lightAlpha.set=function(e){this.uniforms.lightAlpha=e},r.shadowColor.get=function(){return l.rgb2hex(this.uniforms.shadowColor)},r.shadowColor.set=function(e){l.hex2rgb(e,this.uniforms.shadowColor)},r.shadowAlpha.get=function(){return this.uniforms.shadowAlpha},r.shadowAlpha.set=function(e){this.uniforms.shadowAlpha=e},Object.defineProperties(e.prototype,r),e}(n.Filter),g=function(a){function e(e,t,r,i){var n,o;void 0===e&&(e=2),void 0===t&&(t=4),void 0===r&&(r=p.settings.RESOLUTION),void 0===i&&(i=5),a.call(this),"number"==typeof e?o=n=e:e instanceof f.Point?(n=e.x,o=e.y):Array.isArray(e)&&(n=e[0],o=e[1]),this.blurXFilter=new h.BlurFilterPass(!0,n,t,r,i),this.blurYFilter=new h.BlurFilterPass(!1,o,t,r,i),this.blurYFilter.blendMode=s.BLEND_MODES.SCREEN,this.defaultFilter=new u.AlphaFilter}a&&(e.__proto__=a);var t={blur:{configurable:!0},blurX:{configurable:!0},blurY:{configurable:!0}};return((e.prototype=Object.create(a&&a.prototype)).constructor=e).prototype.apply=function(e,t,r){var i=e.getFilterTexture(!0);this.defaultFilter.apply(e,t,r),this.blurXFilter.apply(e,t,i),this.blurYFilter.apply(e,i,r),e.returnFilterTexture(i)},t.blur.get=function(){return this.blurXFilter.blur},t.blur.set=function(e){this.blurXFilter.blur=this.blurYFilter.blur=e},t.blurX.get=function(){return this.blurXFilter.blur},t.blurX.set=function(e){this.blurXFilter.blur=e},t.blurY.get=function(){return this.blurYFilter.blur},t.blurY.set=function(e){this.blurYFilter.blur=e},Object.defineProperties(e.prototype,t),e}(n.Filter),v=function(i){function e(e,t,r){i.call(this,"attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n vTextureCoord = aTextureCoord;\n}","uniform float radius;\nuniform float strength;\nuniform vec2 center;\nuniform sampler2D uSampler;\nvarying vec2 vTextureCoord;\n\nuniform vec4 filterArea;\nuniform vec4 filterClamp;\nuniform vec2 dimensions;\n\nvoid main()\n{\n vec2 coord = vTextureCoord * filterArea.xy;\n coord -= center * dimensions.xy;\n float distance = length(coord);\n if (distance < radius) {\n float percent = distance / radius;\n if (strength > 0.0) {\n coord *= mix(1.0, smoothstep(0.0, radius / distance, percent), strength * 0.75);\n } else {\n coord *= mix(1.0, pow(percent, 1.0 + strength * 0.75) * radius / distance, 1.0 - percent);\n }\n }\n coord += center * dimensions.xy;\n coord /= filterArea.xy;\n vec2 clampedCoord = clamp(coord, filterClamp.xy, filterClamp.zw);\n vec4 color = texture2D(uSampler, clampedCoord);\n if (coord != clampedCoord) {\n color *= max(0.0, 1.0 - length(coord - clampedCoord));\n }\n\n gl_FragColor = color;\n}\n"),this.uniforms.dimensions=new Float32Array(2),this.center=e||[.5,.5],this.radius="number"==typeof t?t:100,this.strength="number"==typeof r?r:1}i&&(e.__proto__=i);var t={radius:{configurable:!0},strength:{configurable:!0},center:{configurable:!0}};return((e.prototype=Object.create(i&&i.prototype)).constructor=e).prototype.apply=function(e,t,r,i){this.uniforms.dimensions[0]=t.filterFrame.width,this.uniforms.dimensions[1]=t.filterFrame.height,e.applyFilter(this,t,r,i)},t.radius.get=function(){return this.uniforms.radius},t.radius.set=function(e){this.uniforms.radius=e},t.strength.get=function(){return this.uniforms.strength},t.strength.set=function(e){this.uniforms.strength=e},t.center.get=function(){return this.uniforms.center},t.center.set=function(e){this.uniforms.center=e},Object.defineProperties(e.prototype,t),e}(n.Filter),_=function(i){function e(e,t,r){void 0===t&&(t=!1),void 0===r&&(r=1),i.call(this,"attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n vTextureCoord = aTextureCoord;\n}","varying vec2 vTextureCoord;\nuniform sampler2D uSampler;\nuniform sampler2D colorMap;\nuniform float _mix;\nuniform float _size;\nuniform float _sliceSize;\nuniform float _slicePixelSize;\nuniform float _sliceInnerSize;\nvoid main() {\n vec4 color = texture2D(uSampler, vTextureCoord.xy);\n\n vec4 adjusted;\n if (color.a > 0.0) {\n color.rgb /= color.a;\n float innerWidth = _size - 1.0;\n float zSlice0 = min(floor(color.b * innerWidth), innerWidth);\n float zSlice1 = min(zSlice0 + 1.0, innerWidth);\n float xOffset = _slicePixelSize * 0.5 + color.r * _sliceInnerSize;\n float s0 = xOffset + (zSlice0 * _sliceSize);\n float s1 = xOffset + (zSlice1 * _sliceSize);\n float yOffset = _sliceSize * 0.5 + color.g * (1.0 - _sliceSize);\n vec4 slice0Color = texture2D(colorMap, vec2(s0,yOffset));\n vec4 slice1Color = texture2D(colorMap, vec2(s1,yOffset));\n float zOffset = fract(color.b * innerWidth);\n adjusted = mix(slice0Color, slice1Color, zOffset);\n\n color.rgb *= color.a;\n }\n gl_FragColor = vec4(mix(color, adjusted, _mix).rgb, color.a);\n\n}"),this._size=0,this._sliceSize=0,this._slicePixelSize=0,this._sliceInnerSize=0,this._scaleMode=null,this._nearest=!1,this.nearest=t,this.mix=r,this.colorMap=e}i&&(e.__proto__=i);var t={colorSize:{configurable:!0},colorMap:{configurable:!0},nearest:{configurable:!0}};return((e.prototype=Object.create(i&&i.prototype)).constructor=e).prototype.apply=function(e,t,r,i){this.uniforms._mix=this.mix,e.applyFilter(this,t,r,i)},t.colorSize.get=function(){return this._size},t.colorMap.get=function(){return this._colorMap},t.colorMap.set=function(e){e instanceof n.Texture||(e=n.Texture.from(e)),e&&e.baseTexture&&(e.baseTexture.scaleMode=this._scaleMode,e.baseTexture.mipmap=!1,this._size=e.height,this._sliceSize=1/this._size,this._slicePixelSize=this._sliceSize/this._size,this._sliceInnerSize=this._slicePixelSize*(this._size-1),this.uniforms._size=this._size,this.uniforms._sliceSize=this._sliceSize,this.uniforms._slicePixelSize=this._slicePixelSize,this.uniforms._sliceInnerSize=this._sliceInnerSize,this.uniforms.colorMap=e),this._colorMap=e},t.nearest.get=function(){return this._nearest},t.nearest.set=function(e){this._nearest=e,this._scaleMode=e?s.SCALE_MODES.NEAREST:s.SCALE_MODES.LINEAR;var t=this._colorMap;t&&t.baseTexture&&(t.baseTexture._glTextures={},t.baseTexture.scaleMode=this._scaleMode,t.baseTexture.mipmap=!1,t._updateID++,t.baseTexture.emit("update",t.baseTexture))},e.prototype.updateColorMap=function(){var e=this._colorMap;e&&e.baseTexture&&(e._updateID++,e.baseTexture.emit("update",e.baseTexture),this.colorMap=e)},e.prototype.destroy=function(e){this._colorMap&&this._colorMap.destroy(e),i.prototype.destroy.call(this)},Object.defineProperties(e.prototype,t),e}(n.Filter),y=function(i){function e(e,t,r){void 0===e&&(e=16711680),void 0===t&&(t=0),void 0===r&&(r=.4),i.call(this,"attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n vTextureCoord = aTextureCoord;\n}","varying vec2 vTextureCoord;\nuniform sampler2D uSampler;\nuniform vec3 originalColor;\nuniform vec3 newColor;\nuniform float epsilon;\nvoid main(void) {\n vec4 currentColor = texture2D(uSampler, vTextureCoord);\n vec3 colorDiff = originalColor - (currentColor.rgb / max(currentColor.a, 0.0000000001));\n float colorDistance = length(colorDiff);\n float doReplace = step(colorDistance, epsilon);\n gl_FragColor = vec4(mix(currentColor.rgb, (newColor + colorDiff) * currentColor.a, doReplace), currentColor.a);\n}\n"),this.uniforms.originalColor=new Float32Array(3),this.uniforms.newColor=new Float32Array(3),this.originalColor=e,this.newColor=t,this.epsilon=r}i&&(e.__proto__=i),(e.prototype=Object.create(i&&i.prototype)).constructor=e;var t={originalColor:{configurable:!0},newColor:{configurable:!0},epsilon:{configurable:!0}};return t.originalColor.set=function(e){var t=this.uniforms.originalColor;"number"==typeof e?(l.hex2rgb(e,t),this._originalColor=e):(t[0]=e[0],t[1]=e[1],t[2]=e[2],this._originalColor=l.rgb2hex(t))},t.originalColor.get=function(){return this._originalColor},t.newColor.set=function(e){var t=this.uniforms.newColor;"number"==typeof e?(l.hex2rgb(e,t),this._newColor=e):(t[0]=e[0],t[1]=e[1],t[2]=e[2],this._newColor=l.rgb2hex(t))},t.newColor.get=function(){return this._newColor},t.epsilon.set=function(e){this.uniforms.epsilon=e},t.epsilon.get=function(){return this.uniforms.epsilon},Object.defineProperties(e.prototype,t),e}(n.Filter),b=function(i){function e(e,t,r){void 0===t&&(t=200),void 0===r&&(r=200),i.call(this,"attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n vTextureCoord = aTextureCoord;\n}","precision mediump float;\n\nvarying mediump vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\nuniform vec2 texelSize;\nuniform float matrix[9];\n\nvoid main(void)\n{\n vec4 c11 = texture2D(uSampler, vTextureCoord - texelSize); // top left\n vec4 c12 = texture2D(uSampler, vec2(vTextureCoord.x, vTextureCoord.y - texelSize.y)); // top center\n vec4 c13 = texture2D(uSampler, vec2(vTextureCoord.x + texelSize.x, vTextureCoord.y - texelSize.y)); // top right\n\n vec4 c21 = texture2D(uSampler, vec2(vTextureCoord.x - texelSize.x, vTextureCoord.y)); // mid left\n vec4 c22 = texture2D(uSampler, vTextureCoord); // mid center\n vec4 c23 = texture2D(uSampler, vec2(vTextureCoord.x + texelSize.x, vTextureCoord.y)); // mid right\n\n vec4 c31 = texture2D(uSampler, vec2(vTextureCoord.x - texelSize.x, vTextureCoord.y + texelSize.y)); // bottom left\n vec4 c32 = texture2D(uSampler, vec2(vTextureCoord.x, vTextureCoord.y + texelSize.y)); // bottom center\n vec4 c33 = texture2D(uSampler, vTextureCoord + texelSize); // bottom right\n\n gl_FragColor =\n c11 * matrix[0] + c12 * matrix[1] + c13 * matrix[2] +\n c21 * matrix[3] + c22 * matrix[4] + c23 * matrix[5] +\n c31 * matrix[6] + c32 * matrix[7] + c33 * matrix[8];\n\n gl_FragColor.a = c22.a;\n}\n"),this.uniforms.texelSize=new Float32Array(2),this.uniforms.matrix=new Float32Array(9),void 0!==e&&(this.matrix=e),this.width=t,this.height=r}i&&(e.__proto__=i),(e.prototype=Object.create(i&&i.prototype)).constructor=e;var t={matrix:{configurable:!0},width:{configurable:!0},height:{configurable:!0}};return t.matrix.get=function(){return this.uniforms.matrix},t.matrix.set=function(e){var r=this;e.forEach(function(e,t){return r.uniforms.matrix[t]=e})},t.width.get=function(){return 1/this.uniforms.texelSize[0]},t.width.set=function(e){this.uniforms.texelSize[0]=1/e},t.height.get=function(){return 1/this.uniforms.texelSize[1]},t.height.set=function(e){this.uniforms.texelSize[1]=1/e},Object.defineProperties(e.prototype,t),e}(n.Filter),x=function(e){function t(){e.call(this,"attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n vTextureCoord = aTextureCoord;\n}","precision mediump float;\n\nvarying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\n\nvoid main(void)\n{\n float lum = length(texture2D(uSampler, vTextureCoord.xy).rgb);\n\n gl_FragColor = vec4(1.0, 1.0, 1.0, 1.0);\n\n if (lum < 1.00)\n {\n if (mod(gl_FragCoord.x + gl_FragCoord.y, 10.0) == 0.0)\n {\n gl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);\n }\n }\n\n if (lum < 0.75)\n {\n if (mod(gl_FragCoord.x - gl_FragCoord.y, 10.0) == 0.0)\n {\n gl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);\n }\n }\n\n if (lum < 0.50)\n {\n if (mod(gl_FragCoord.x + gl_FragCoord.y - 5.0, 10.0) == 0.0)\n {\n gl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);\n }\n }\n\n if (lum < 0.3)\n {\n if (mod(gl_FragCoord.x - gl_FragCoord.y - 5.0, 10.0) == 0.0)\n {\n gl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);\n }\n }\n}\n")}return e&&(t.__proto__=e),(t.prototype=Object.create(e&&e.prototype)).constructor=t}(n.Filter),w=function(t){function e(e){t.call(this,"attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n vTextureCoord = aTextureCoord;\n}","varying vec2 vTextureCoord;\nuniform sampler2D uSampler;\n\nuniform vec4 filterArea;\nuniform vec2 dimensions;\n\nconst float SQRT_2 = 1.414213;\n\nconst float light = 1.0;\n\nuniform float curvature;\nuniform float lineWidth;\nuniform float lineContrast;\nuniform bool verticalLine;\nuniform float noise;\nuniform float noiseSize;\n\nuniform float vignetting;\nuniform float vignettingAlpha;\nuniform float vignettingBlur;\n\nuniform float seed;\nuniform float time;\n\nfloat rand(vec2 co) {\n return fract(sin(dot(co.xy, vec2(12.9898, 78.233))) * 43758.5453);\n}\n\nvoid main(void)\n{\n vec2 pixelCoord = vTextureCoord.xy * filterArea.xy;\n vec2 coord = pixelCoord / dimensions;\n\n vec2 dir = vec2(coord - vec2(0.5, 0.5));\n\n float _c = curvature > 0. ? curvature : 1.;\n float k = curvature > 0. ?(length(dir * dir) * 0.25 * _c * _c + 0.935 * _c) : 1.;\n vec2 uv = dir * k;\n\n gl_FragColor = texture2D(uSampler, vTextureCoord);\n vec3 rgb = gl_FragColor.rgb;\n\n\n if (noise > 0.0 && noiseSize > 0.0)\n {\n pixelCoord.x = floor(pixelCoord.x / noiseSize);\n pixelCoord.y = floor(pixelCoord.y / noiseSize);\n float _noise = rand(pixelCoord * noiseSize * seed) - 0.5;\n rgb += _noise * noise;\n }\n\n if (lineWidth > 0.0) {\n float v = (verticalLine ? uv.x * dimensions.x : uv.y * dimensions.y) * min(1.0, 2.0 / lineWidth ) / _c;\n float j = 1. + cos(v * 1.2 - time) * 0.5 * lineContrast;\n rgb *= j;\n float segment = verticalLine ? mod((dir.x + .5) * dimensions.x, 4.) : mod((dir.y + .5) * dimensions.y, 4.);\n rgb *= 0.99 + ceil(segment) * 0.015;\n }\n\n if (vignetting > 0.0)\n {\n float outter = SQRT_2 - vignetting * SQRT_2;\n float darker = clamp((outter - length(dir) * SQRT_2) / ( 0.00001 + vignettingBlur * SQRT_2), 0.0, 1.0);\n rgb *= darker + (1.0 - darker) * (1.0 - vignettingAlpha);\n }\n\n gl_FragColor.rgb = rgb;\n}\n"),this.uniforms.dimensions=new Float32Array(2),this.time=0,this.seed=0,Object.assign(this,{curvature:1,lineWidth:1,lineContrast:.25,verticalLine:!1,noise:0,noiseSize:1,seed:0,vignetting:.3,vignettingAlpha:1,vignettingBlur:.3,time:0},e)}t&&(e.__proto__=t);var r={curvature:{configurable:!0},lineWidth:{configurable:!0},lineContrast:{configurable:!0},verticalLine:{configurable:!0},noise:{configurable:!0},noiseSize:{configurable:!0},vignetting:{configurable:!0},vignettingAlpha:{configurable:!0},vignettingBlur:{configurable:!0}};return((e.prototype=Object.create(t&&t.prototype)).constructor=e).prototype.apply=function(e,t,r,i){this.uniforms.dimensions[0]=t.filterFrame.width,this.uniforms.dimensions[1]=t.filterFrame.height,this.uniforms.seed=this.seed,this.uniforms.time=this.time,e.applyFilter(this,t,r,i)},r.curvature.set=function(e){this.uniforms.curvature=e},r.curvature.get=function(){return this.uniforms.curvature},r.lineWidth.set=function(e){this.uniforms.lineWidth=e},r.lineWidth.get=function(){return this.uniforms.lineWidth},r.lineContrast.set=function(e){this.uniforms.lineContrast=e},r.lineContrast.get=function(){return this.uniforms.lineContrast},r.verticalLine.set=function(e){this.uniforms.verticalLine=e},r.verticalLine.get=function(){return this.uniforms.verticalLine},r.noise.set=function(e){this.uniforms.noise=e},r.noise.get=function(){return this.uniforms.noise},r.noiseSize.set=function(e){this.uniforms.noiseSize=e},r.noiseSize.get=function(){return this.uniforms.noiseSize},r.vignetting.set=function(e){this.uniforms.vignetting=e},r.vignetting.get=function(){return this.uniforms.vignetting},r.vignettingAlpha.set=function(e){this.uniforms.vignettingAlpha=e},r.vignettingAlpha.get=function(){return this.uniforms.vignettingAlpha},r.vignettingBlur.set=function(e){this.uniforms.vignettingBlur=e},r.vignettingBlur.get=function(){return this.uniforms.vignettingBlur},Object.defineProperties(e.prototype,r),e}(n.Filter),T=function(r){function e(e,t){void 0===e&&(e=1),void 0===t&&(t=5),r.call(this,"attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n vTextureCoord = aTextureCoord;\n}","precision mediump float;\n\nvarying vec2 vTextureCoord;\nvarying vec4 vColor;\n\nuniform vec4 filterArea;\nuniform sampler2D uSampler;\n\nuniform float angle;\nuniform float scale;\n\nfloat pattern()\n{\n float s = sin(angle), c = cos(angle);\n vec2 tex = vTextureCoord * filterArea.xy;\n vec2 point = vec2(\n c * tex.x - s * tex.y,\n s * tex.x + c * tex.y\n ) * scale;\n return (sin(point.x) * sin(point.y)) * 4.0;\n}\n\nvoid main()\n{\n vec4 color = texture2D(uSampler, vTextureCoord);\n float average = (color.r + color.g + color.b) / 3.0;\n gl_FragColor = vec4(vec3(average * 10.0 - 5.0 + pattern()), color.a);\n}\n"),this.scale=e,this.angle=t}r&&(e.__proto__=r),(e.prototype=Object.create(r&&r.prototype)).constructor=e;var t={scale:{configurable:!0},angle:{configurable:!0}};return t.scale.get=function(){return this.uniforms.scale},t.scale.set=function(e){this.uniforms.scale=e},t.angle.get=function(){return this.uniforms.angle},t.angle.set=function(e){this.uniforms.angle=e},Object.defineProperties(e.prototype,t),e}(n.Filter),k=function(c){function e(e){e&&e.constructor!==Object&&(console.warn("DropShadowFilter now uses options instead of (rotation, distance, blur, color, alpha)"),e={rotation:e},void 0!==arguments[1]&&(e.distance=arguments[1]),void 0!==arguments[2]&&(e.blur=arguments[2]),void 0!==arguments[3]&&(e.color=arguments[3]),void 0!==arguments[4]&&(e.alpha=arguments[4])),e=Object.assign({rotation:45,distance:5,color:0,alpha:.5,shadowOnly:!1,kernels:null,blur:2,quality:3,pixelSize:1,resolution:p.settings.RESOLUTION},e),c.call(this);var t=e.kernels,r=e.blur,i=e.quality,n=e.pixelSize,o=e.resolution;this._tintFilter=new c("attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n vTextureCoord = aTextureCoord;\n}","varying vec2 vTextureCoord;\nuniform sampler2D uSampler;\nuniform float alpha;\nuniform vec3 color;\n\nuniform vec2 shift;\nuniform vec4 inputSize;\n\nvoid main(void){\n vec4 sample = texture2D(uSampler, vTextureCoord - shift * inputSize.zw);\n\n // Un-premultiply alpha before applying the color\n if (sample.a > 0.0) {\n sample.rgb /= sample.a;\n }\n\n // Premultiply alpha again\n sample.rgb = color.rgb * sample.a;\n\n // alpha user alpha\n sample *= alpha;\n\n gl_FragColor = sample;\n}"),this._tintFilter.uniforms.color=new Float32Array(4),this._tintFilter.uniforms.shift=new f.Point,this._tintFilter.resolution=o,this._blurFilter=t?new d(t):new d(r,i),this.pixelSize=n,this.resolution=o;var a=e.shadowOnly,s=e.rotation,l=e.distance,u=e.alpha,h=e.color;this.shadowOnly=a,this.rotation=s,this.distance=l,this.alpha=u,this.color=h,this._updatePadding()}c&&(e.__proto__=c);var t={resolution:{configurable:!0},distance:{configurable:!0},rotation:{configurable:!0},alpha:{configurable:!0},color:{configurable:!0},kernels:{configurable:!0},blur:{configurable:!0},quality:{configurable:!0},pixelSize:{configurable:!0}};return((e.prototype=Object.create(c&&c.prototype)).constructor=e).prototype.apply=function(e,t,r,i){var n=e.getFilterTexture();this._tintFilter.apply(e,t,n,!0),this._blurFilter.apply(e,n,r,i),!0!==this.shadowOnly&&e.applyFilter(this,t,r,!1),e.returnFilterTexture(n)},e.prototype._updatePadding=function(){this.padding=this.distance+2*this.blur},e.prototype._updateShift=function(){this._tintFilter.uniforms.shift.set(this.distance*Math.cos(this.angle),this.distance*Math.sin(this.angle))},t.resolution.get=function(){return this._resolution},t.resolution.set=function(e){this._resolution=e,this._tintFilter&&(this._tintFilter.resolution=e),this._blurFilter&&(this._blurFilter.resolution=e)},t.distance.get=function(){return this._distance},t.distance.set=function(e){this._distance=e,this._updatePadding(),this._updateShift()},t.rotation.get=function(){return this.angle/f.DEG_TO_RAD},t.rotation.set=function(e){this.angle=e*f.DEG_TO_RAD,this._updateShift()},t.alpha.get=function(){return this._tintFilter.uniforms.alpha},t.alpha.set=function(e){this._tintFilter.uniforms.alpha=e},t.color.get=function(){return l.rgb2hex(this._tintFilter.uniforms.color)},t.color.set=function(e){l.hex2rgb(e,this._tintFilter.uniforms.color)},t.kernels.get=function(){return this._blurFilter.kernels},t.kernels.set=function(e){this._blurFilter.kernels=e},t.blur.get=function(){return this._blurFilter.blur},t.blur.set=function(e){this._blurFilter.blur=e,this._updatePadding()},t.quality.get=function(){return this._blurFilter.quality},t.quality.set=function(e){this._blurFilter.quality=e},t.pixelSize.get=function(){return this._blurFilter.pixelSize},t.pixelSize.set=function(e){this._blurFilter.pixelSize=e},Object.defineProperties(e.prototype,t),e}(n.Filter),P=function(t){function e(e){void 0===e&&(e=5),t.call(this,"attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n vTextureCoord = aTextureCoord;\n}","precision mediump float;\n\nvarying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\nuniform float strength;\nuniform vec4 filterArea;\n\n\nvoid main(void)\n{\n\tvec2 onePixel = vec2(1.0 / filterArea);\n\n\tvec4 color;\n\n\tcolor.rgb = vec3(0.5);\n\n\tcolor -= texture2D(uSampler, vTextureCoord - onePixel) * strength;\n\tcolor += texture2D(uSampler, vTextureCoord + onePixel) * strength;\n\n\tcolor.rgb = vec3((color.r + color.g + color.b) / 3.0);\n\n\tfloat alpha = texture2D(uSampler, vTextureCoord).a;\n\n\tgl_FragColor = vec4(color.rgb * alpha, alpha);\n}\n"),this.strength=e}t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e;var r={strength:{configurable:!0}};return r.strength.get=function(){return this.uniforms.strength},r.strength.set=function(e){this.uniforms.strength=e},Object.defineProperties(e.prototype,r),e}(n.Filter),S=function(t){function e(e){void 0===e&&(e={}),t.call(this,"attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n vTextureCoord = aTextureCoord;\n}","// precision highp float;\n\nvarying vec2 vTextureCoord;\nuniform sampler2D uSampler;\n\nuniform vec4 filterArea;\nuniform vec4 filterClamp;\nuniform vec2 dimensions;\nuniform float aspect;\n\nuniform sampler2D displacementMap;\nuniform float offset;\nuniform float sinDir;\nuniform float cosDir;\nuniform int fillMode;\n\nuniform float seed;\nuniform vec2 red;\nuniform vec2 green;\nuniform vec2 blue;\n\nconst int TRANSPARENT = 0;\nconst int ORIGINAL = 1;\nconst int LOOP = 2;\nconst int CLAMP = 3;\nconst int MIRROR = 4;\n\nvoid main(void)\n{\n vec2 coord = (vTextureCoord * filterArea.xy) / dimensions;\n\n if (coord.x > 1.0 || coord.y > 1.0) {\n return;\n }\n\n float cx = coord.x - 0.5;\n float cy = (coord.y - 0.5) * aspect;\n float ny = (-sinDir * cx + cosDir * cy) / aspect + 0.5;\n\n // displacementMap: repeat\n // ny = ny > 1.0 ? ny - 1.0 : (ny < 0.0 ? 1.0 + ny : ny);\n\n // displacementMap: mirror\n ny = ny > 1.0 ? 2.0 - ny : (ny < 0.0 ? -ny : ny);\n\n vec4 dc = texture2D(displacementMap, vec2(0.5, ny));\n\n float displacement = (dc.r - dc.g) * (offset / filterArea.x);\n\n coord = vTextureCoord + vec2(cosDir * displacement, sinDir * displacement * aspect);\n\n if (fillMode == CLAMP) {\n coord = clamp(coord, filterClamp.xy, filterClamp.zw);\n } else {\n if( coord.x > filterClamp.z ) {\n if (fillMode == TRANSPARENT) {\n discard;\n } else if (fillMode == LOOP) {\n coord.x -= filterClamp.z;\n } else if (fillMode == MIRROR) {\n coord.x = filterClamp.z * 2.0 - coord.x;\n }\n } else if( coord.x < filterClamp.x ) {\n if (fillMode == TRANSPARENT) {\n discard;\n } else if (fillMode == LOOP) {\n coord.x += filterClamp.z;\n } else if (fillMode == MIRROR) {\n coord.x *= -filterClamp.z;\n }\n }\n\n if( coord.y > filterClamp.w ) {\n if (fillMode == TRANSPARENT) {\n discard;\n } else if (fillMode == LOOP) {\n coord.y -= filterClamp.w;\n } else if (fillMode == MIRROR) {\n coord.y = filterClamp.w * 2.0 - coord.y;\n }\n } else if( coord.y < filterClamp.y ) {\n if (fillMode == TRANSPARENT) {\n discard;\n } else if (fillMode == LOOP) {\n coord.y += filterClamp.w;\n } else if (fillMode == MIRROR) {\n coord.y *= -filterClamp.w;\n }\n }\n }\n\n gl_FragColor.r = texture2D(uSampler, coord + red * (1.0 - seed * 0.4) / filterArea.xy).r;\n gl_FragColor.g = texture2D(uSampler, coord + green * (1.0 - seed * 0.3) / filterArea.xy).g;\n gl_FragColor.b = texture2D(uSampler, coord + blue * (1.0 - seed * 0.2) / filterArea.xy).b;\n gl_FragColor.a = texture2D(uSampler, coord).a;\n}\n"),this.uniforms.dimensions=new Float32Array(2),e=Object.assign({slices:5,offset:100,direction:0,fillMode:0,average:!1,seed:0,red:[0,0],green:[0,0],blue:[0,0],minSize:8,sampleSize:512},e),this.direction=e.direction,this.red=e.red,this.green=e.green,this.blue=e.blue,this.offset=e.offset,this.fillMode=e.fillMode,this.average=e.average,this.seed=e.seed,this.minSize=e.minSize,this.sampleSize=e.sampleSize,this._canvas=document.createElement("canvas"),this._canvas.width=4,this._canvas.height=this.sampleSize,this.texture=n.Texture.from(this._canvas,{scaleMode:s.SCALE_MODES.NEAREST}),this._slices=0,this.slices=e.slices}t&&(e.__proto__=t);var r={sizes:{configurable:!0},offsets:{configurable:!0},slices:{configurable:!0},direction:{configurable:!0},red:{configurable:!0},green:{configurable:!0},blue:{configurable:!0}};return((e.prototype=Object.create(t&&t.prototype)).constructor=e).prototype.apply=function(e,t,r,i){var n=t.filterFrame.width,o=t.filterFrame.height;this.uniforms.dimensions[0]=n,this.uniforms.dimensions[1]=o,this.uniforms.aspect=o/n,this.uniforms.seed=this.seed,this.uniforms.offset=this.offset,this.uniforms.fillMode=this.fillMode,e.applyFilter(this,t,r,i)},e.prototype._randomizeSizes=function(){var e=this._sizes,t=this._slices-1,r=this.sampleSize,i=Math.min(this.minSize/r,.9/this._slices);if(this.average){for(var n=this._slices,o=1,a=0;a>0,i=e[t];e[t]=e[r],e[r]=i}},e.prototype._randomizeOffsets=function(){for(var e=0;e>0,t,1+a>>0),n+=a}r.baseTexture.update(),this.uniforms.displacementMap=r},r.sizes.set=function(e){for(var t=Math.min(this._slices,e.length),r=0;rthis._maxColors)throw"Length of replacements ("+i+") exceeds the maximum colors length ("+this._maxColors+")";t[3*i]=-1;for(var n=0;n 0.5) then: 1 - 2 * (1 - dst) * (1 - src)\n return vec3((dst.x <= 0.5) ? (2.0 * src.x * dst.x) : (1.0 - 2.0 * (1.0 - dst.x) * (1.0 - src.x)),\n (dst.y <= 0.5) ? (2.0 * src.y * dst.y) : (1.0 - 2.0 * (1.0 - dst.y) * (1.0 - src.y)),\n (dst.z <= 0.5) ? (2.0 * src.z * dst.z) : (1.0 - 2.0 * (1.0 - dst.z) * (1.0 - src.z)));\n}\n\n\nvoid main()\n{\n gl_FragColor = texture2D(uSampler, vTextureCoord);\n vec3 color = gl_FragColor.rgb;\n\n if (sepia > 0.0)\n {\n float gray = (color.x + color.y + color.z) / 3.0;\n vec3 grayscale = vec3(gray);\n\n color = Overlay(SEPIA_RGB, grayscale);\n\n color = grayscale + sepia * (color - grayscale);\n }\n\n vec2 coord = vTextureCoord * filterArea.xy / dimensions.xy;\n\n if (vignetting > 0.0)\n {\n float outter = SQRT_2 - vignetting * SQRT_2;\n vec2 dir = vec2(vec2(0.5, 0.5) - coord);\n dir.y *= dimensions.y / dimensions.x;\n float darker = clamp((outter - length(dir) * SQRT_2) / ( 0.00001 + vignettingBlur * SQRT_2), 0.0, 1.0);\n color.rgb *= darker + (1.0 - darker) * (1.0 - vignettingAlpha);\n }\n\n if (scratchDensity > seed && scratch != 0.0)\n {\n float phase = seed * 256.0;\n float s = mod(floor(phase), 2.0);\n float dist = 1.0 / scratchDensity;\n float d = distance(coord, vec2(seed * dist, abs(s - seed * dist)));\n if (d < seed * 0.6 + 0.4)\n {\n highp float period = scratchDensity * 10.0;\n\n float xx = coord.x * period + phase;\n float aa = abs(mod(xx, 0.5) * 4.0);\n float bb = mod(floor(xx / 0.5), 2.0);\n float yy = (1.0 - bb) * aa + bb * (2.0 - aa);\n\n float kk = 2.0 * period;\n float dw = scratchWidth / dimensions.x * (0.75 + seed);\n float dh = dw * kk;\n\n float tine = (yy - (2.0 - dh));\n\n if (tine > 0.0) {\n float _sign = sign(scratch);\n\n tine = s * tine / period + scratch + 0.1;\n tine = clamp(tine + 1.0, 0.5 + _sign * 0.5, 1.5 + _sign * 0.5);\n\n color.rgb *= tine;\n }\n }\n }\n\n if (noise > 0.0 && noiseSize > 0.0)\n {\n vec2 pixelCoord = vTextureCoord.xy * filterArea.xy;\n pixelCoord.x = floor(pixelCoord.x / noiseSize);\n pixelCoord.y = floor(pixelCoord.y / noiseSize);\n // vec2 d = pixelCoord * noiseSize * vec2(1024.0 + seed * 512.0, 1024.0 - seed * 512.0);\n // float _noise = snoise(d) * 0.5;\n float _noise = rand(pixelCoord * noiseSize * seed) - 0.5;\n color += _noise * noise;\n }\n\n gl_FragColor.rgb = color;\n}\n"),this.uniforms.dimensions=new Float32Array(2),"number"==typeof e?(this.seed=e,e=null):this.seed=t,Object.assign(this,{sepia:.3,noise:.3,noiseSize:1,scratch:.5,scratchDensity:.3,scratchWidth:1,vignetting:.3,vignettingAlpha:1,vignettingBlur:.3},e)}r&&(e.__proto__=r);var t={sepia:{configurable:!0},noise:{configurable:!0},noiseSize:{configurable:!0},scratch:{configurable:!0},scratchDensity:{configurable:!0},scratchWidth:{configurable:!0},vignetting:{configurable:!0},vignettingAlpha:{configurable:!0},vignettingBlur:{configurable:!0}};return((e.prototype=Object.create(r&&r.prototype)).constructor=e).prototype.apply=function(e,t,r,i){this.uniforms.dimensions[0]=t.filterFrame.width,this.uniforms.dimensions[1]=t.filterFrame.height,this.uniforms.seed=this.seed,e.applyFilter(this,t,r,i)},t.sepia.set=function(e){this.uniforms.sepia=e},t.sepia.get=function(){return this.uniforms.sepia},t.noise.set=function(e){this.uniforms.noise=e},t.noise.get=function(){return this.uniforms.noise},t.noiseSize.set=function(e){this.uniforms.noiseSize=e},t.noiseSize.get=function(){return this.uniforms.noiseSize},t.scratch.set=function(e){this.uniforms.scratch=e},t.scratch.get=function(){return this.uniforms.scratch},t.scratchDensity.set=function(e){this.uniforms.scratchDensity=e},t.scratchDensity.get=function(){return this.uniforms.scratchDensity},t.scratchWidth.set=function(e){this.uniforms.scratchWidth=e},t.scratchWidth.get=function(){return this.uniforms.scratchWidth},t.vignetting.set=function(e){this.uniforms.vignetting=e},t.vignetting.get=function(){return this.uniforms.vignetting},t.vignettingAlpha.set=function(e){this.uniforms.vignettingAlpha=e},t.vignettingAlpha.get=function(){return this.uniforms.vignettingAlpha},t.vignettingBlur.set=function(e){this.uniforms.vignettingBlur=e},t.vignettingBlur.get=function(){return this.uniforms.vignettingBlur},Object.defineProperties(e.prototype,t),e}(n.Filter),M=function(o){function a(e,t,r){void 0===e&&(e=1),void 0===t&&(t=0),void 0===r&&(r=.1);var i=Math.max(r*a.MAX_SAMPLES,a.MIN_SAMPLES),n=(2*Math.PI/i).toFixed(7);o.call(this,"attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n vTextureCoord = aTextureCoord;\n}","varying vec2 vTextureCoord;\nuniform sampler2D uSampler;\n\nuniform vec2 thickness;\nuniform vec4 outlineColor;\nuniform vec4 filterClamp;\n\nconst float DOUBLE_PI = 3.14159265358979323846264 * 2.;\n\nvoid main(void) {\n vec4 ownColor = texture2D(uSampler, vTextureCoord);\n vec4 curColor;\n float maxAlpha = 0.;\n vec2 displaced;\n for (float angle = 0.; angle <= DOUBLE_PI; angle += ${angleStep}) {\n displaced.x = vTextureCoord.x + thickness.x * cos(angle);\n displaced.y = vTextureCoord.y + thickness.y * sin(angle);\n curColor = texture2D(uSampler, clamp(displaced, filterClamp.xy, filterClamp.zw));\n maxAlpha = max(maxAlpha, curColor.a);\n }\n float resultAlpha = max(maxAlpha, ownColor.a);\n gl_FragColor = vec4((ownColor.rgb + outlineColor.rgb * (1. - ownColor.a)) * resultAlpha, resultAlpha);\n}\n".replace(/\$\{angleStep\}/,n)),this.uniforms.thickness=new Float32Array([0,0]),this.thickness=e,this.uniforms.outlineColor=new Float32Array([0,0,0,1]),this.color=t,this.quality=r}o&&(a.__proto__=o);var e={color:{configurable:!0}};return((a.prototype=Object.create(o&&o.prototype)).constructor=a).prototype.apply=function(e,t,r,i){this.uniforms.thickness[0]=this.thickness/t._frame.width,this.uniforms.thickness[1]=this.thickness/t._frame.height,e.applyFilter(this,t,r,i)},e.color.get=function(){return l.rgb2hex(this.uniforms.outlineColor)},e.color.set=function(e){l.hex2rgb(e,this.uniforms.outlineColor)},Object.defineProperties(a.prototype,e),a}(n.Filter);M.MIN_SAMPLES=1,M.MAX_SAMPLES=100;var D=function(t){function e(e){void 0===e&&(e=10),t.call(this,"attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n vTextureCoord = aTextureCoord;\n}","precision mediump float;\n\nvarying vec2 vTextureCoord;\n\nuniform vec2 size;\nuniform sampler2D uSampler;\n\nuniform vec4 filterArea;\n\nvec2 mapCoord( vec2 coord )\n{\n coord *= filterArea.xy;\n coord += filterArea.zw;\n\n return coord;\n}\n\nvec2 unmapCoord( vec2 coord )\n{\n coord -= filterArea.zw;\n coord /= filterArea.xy;\n\n return coord;\n}\n\nvec2 pixelate(vec2 coord, vec2 size)\n{\n\treturn floor( coord / size ) * size;\n}\n\nvoid main(void)\n{\n vec2 coord = mapCoord(vTextureCoord);\n\n coord = pixelate(coord, size);\n\n coord = unmapCoord(coord);\n\n gl_FragColor = texture2D(uSampler, coord);\n}\n"),this.size=e}t&&(e.__proto__=t),(e.prototype=Object.create(t&&t.prototype)).constructor=e;var r={size:{configurable:!0}};return r.size.get=function(){return this.uniforms.size},r.size.set=function(e){"number"==typeof e&&(e=[e,e]),this.uniforms.size=e},Object.defineProperties(e.prototype,r),e}(n.Filter),R=function(n){function e(e,t,r,i){void 0===e&&(e=0),void 0===t&&(t=[0,0]),void 0===r&&(r=5),void 0===i&&(i=-1),n.call(this,"attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n vTextureCoord = aTextureCoord;\n}","varying vec2 vTextureCoord;\nuniform sampler2D uSampler;\nuniform vec4 filterArea;\n\nuniform float uRadian;\nuniform vec2 uCenter;\nuniform float uRadius;\nuniform int uKernelSize;\n\nconst int MAX_KERNEL_SIZE = 2048;\n\nvoid main(void)\n{\n vec4 color = texture2D(uSampler, vTextureCoord);\n\n if (uKernelSize == 0)\n {\n gl_FragColor = color;\n return;\n }\n\n float aspect = filterArea.y / filterArea.x;\n vec2 center = uCenter.xy / filterArea.xy;\n float gradient = uRadius / filterArea.x * 0.3;\n float radius = uRadius / filterArea.x - gradient * 0.5;\n int k = uKernelSize - 1;\n\n vec2 coord = vTextureCoord;\n vec2 dir = vec2(center - coord);\n float dist = length(vec2(dir.x, dir.y * aspect));\n\n float radianStep = uRadian;\n if (radius >= 0.0 && dist > radius) {\n float delta = dist - radius;\n float gap = gradient;\n float scale = 1.0 - abs(delta / gap);\n if (scale <= 0.0) {\n gl_FragColor = color;\n return;\n }\n radianStep *= scale;\n }\n radianStep /= float(k);\n\n float s = sin(radianStep);\n float c = cos(radianStep);\n mat2 rotationMatrix = mat2(vec2(c, -s), vec2(s, c));\n\n for(int i = 0; i < MAX_KERNEL_SIZE - 1; i++) {\n if (i == k) {\n break;\n }\n\n coord -= center;\n coord.y *= aspect;\n coord = rotationMatrix * coord;\n coord.y /= aspect;\n coord += center;\n\n vec4 sample = texture2D(uSampler, coord);\n\n // switch to pre-multiplied alpha to correctly blur transparent images\n // sample.rgb *= sample.a;\n\n color += sample;\n }\n\n gl_FragColor = color / float(uKernelSize);\n}\n"),this._angle=0,this.angle=e,this.center=t,this.kernelSize=r,this.radius=i}n&&(e.__proto__=n);var t={angle:{configurable:!0},center:{configurable:!0},radius:{configurable:!0}};return((e.prototype=Object.create(n&&n.prototype)).constructor=e).prototype.apply=function(e,t,r,i){this.uniforms.uKernelSize=0!==this._angle?this.kernelSize:0,e.applyFilter(this,t,r,i)},t.angle.set=function(e){this._angle=e,this.uniforms.uRadian=e*Math.PI/180},t.angle.get=function(){return this._angle},t.center.get=function(){return this.uniforms.uCenter},t.center.set=function(e){this.uniforms.uCenter=e},t.radius.get=function(){return this.uniforms.uRadius},t.radius.set=function(e){(e<0||e===1/0)&&(e=-1),this.uniforms.uRadius=e},Object.defineProperties(e.prototype,t),e}(n.Filter),z=function(t){function e(e){t.call(this,"attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n vTextureCoord = aTextureCoord;\n}","varying vec2 vTextureCoord;\nuniform sampler2D uSampler;\n\nuniform vec4 filterArea;\nuniform vec4 filterClamp;\nuniform vec2 dimensions;\n\nuniform bool mirror;\nuniform float boundary;\nuniform vec2 amplitude;\nuniform vec2 waveLength;\nuniform vec2 alpha;\nuniform float time;\n\nfloat rand(vec2 co) {\n return fract(sin(dot(co.xy, vec2(12.9898, 78.233))) * 43758.5453);\n}\n\nvoid main(void)\n{\n vec2 pixelCoord = vTextureCoord.xy * filterArea.xy;\n vec2 coord = pixelCoord / dimensions;\n\n if (coord.y < boundary) {\n gl_FragColor = texture2D(uSampler, vTextureCoord);\n return;\n }\n\n float k = (coord.y - boundary) / (1. - boundary + 0.0001);\n float areaY = boundary * dimensions.y / filterArea.y;\n float v = areaY + areaY - vTextureCoord.y;\n float y = mirror ? v : vTextureCoord.y;\n\n float _amplitude = ((amplitude.y - amplitude.x) * k + amplitude.x ) / filterArea.x;\n float _waveLength = ((waveLength.y - waveLength.x) * k + waveLength.x) / filterArea.y;\n float _alpha = (alpha.y - alpha.x) * k + alpha.x;\n\n float x = vTextureCoord.x + cos(v * 6.28 / _waveLength - time) * _amplitude;\n x = clamp(x, filterClamp.x, filterClamp.z);\n\n vec4 color = texture2D(uSampler, vec2(x, y));\n\n gl_FragColor = color * _alpha;\n}\n"),this.uniforms.amplitude=new Float32Array(2),this.uniforms.waveLength=new Float32Array(2),this.uniforms.alpha=new Float32Array(2),this.uniforms.dimensions=new Float32Array(2),Object.assign(this,{mirror:!0,boundary:.5,amplitude:[0,20],waveLength:[30,100],alpha:[1,1],time:0},e)}t&&(e.__proto__=t);var r={mirror:{configurable:!0},boundary:{configurable:!0},amplitude:{configurable:!0},waveLength:{configurable:!0},alpha:{configurable:!0}};return((e.prototype=Object.create(t&&t.prototype)).constructor=e).prototype.apply=function(e,t,r,i){this.uniforms.dimensions[0]=t.filterFrame.width,this.uniforms.dimensions[1]=t.filterFrame.height,this.uniforms.time=this.time,e.applyFilter(this,t,r,i)},r.mirror.set=function(e){this.uniforms.mirror=e},r.mirror.get=function(){return this.uniforms.mirror},r.boundary.set=function(e){this.uniforms.boundary=e},r.boundary.get=function(){return this.uniforms.boundary},r.amplitude.set=function(e){this.uniforms.amplitude[0]=e[0],this.uniforms.amplitude[1]=e[1]},r.amplitude.get=function(){return this.uniforms.amplitude},r.waveLength.set=function(e){this.uniforms.waveLength[0]=e[0],this.uniforms.waveLength[1]=e[1]},r.waveLength.get=function(){return this.uniforms.waveLength},r.alpha.set=function(e){this.uniforms.alpha[0]=e[0],this.uniforms.alpha[1]=e[1]},r.alpha.get=function(){return this.uniforms.alpha},Object.defineProperties(e.prototype,r),e}(n.Filter),L=function(i){function e(e,t,r){void 0===e&&(e=[-10,0]),void 0===t&&(t=[0,10]),void 0===r&&(r=[0,0]),i.call(this,"attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n vTextureCoord = aTextureCoord;\n}","precision mediump float;\n\nvarying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\nuniform vec4 filterArea;\nuniform vec2 red;\nuniform vec2 green;\nuniform vec2 blue;\n\nvoid main(void)\n{\n gl_FragColor.r = texture2D(uSampler, vTextureCoord + red/filterArea.xy).r;\n gl_FragColor.g = texture2D(uSampler, vTextureCoord + green/filterArea.xy).g;\n gl_FragColor.b = texture2D(uSampler, vTextureCoord + blue/filterArea.xy).b;\n gl_FragColor.a = texture2D(uSampler, vTextureCoord).a;\n}\n"),this.red=e,this.green=t,this.blue=r}i&&(e.__proto__=i),(e.prototype=Object.create(i&&i.prototype)).constructor=e;var t={red:{configurable:!0},green:{configurable:!0},blue:{configurable:!0}};return t.red.get=function(){return this.uniforms.red},t.red.set=function(e){this.uniforms.red=e},t.green.get=function(){return this.uniforms.green},t.green.set=function(e){this.uniforms.green=e},t.blue.get=function(){return this.uniforms.blue},t.blue.set=function(e){this.uniforms.blue=e},Object.defineProperties(e.prototype,t),e}(n.Filter),F=function(i){function e(e,t,r){void 0===e&&(e=[0,0]),void 0===t&&(t={}),void 0===r&&(r=0),i.call(this,"attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n vTextureCoord = aTextureCoord;\n}","varying vec2 vTextureCoord;\nuniform sampler2D uSampler;\nuniform vec4 filterArea;\nuniform vec4 filterClamp;\n\nuniform vec2 center;\n\nuniform float amplitude;\nuniform float wavelength;\n// uniform float power;\nuniform float brightness;\nuniform float speed;\nuniform float radius;\n\nuniform float time;\n\nconst float PI = 3.14159;\n\nvoid main()\n{\n float halfWavelength = wavelength * 0.5 / filterArea.x;\n float maxRadius = radius / filterArea.x;\n float currentRadius = time * speed / filterArea.x;\n\n float fade = 1.0;\n\n if (maxRadius > 0.0) {\n if (currentRadius > maxRadius) {\n gl_FragColor = texture2D(uSampler, vTextureCoord);\n return;\n }\n fade = 1.0 - pow(currentRadius / maxRadius, 2.0);\n }\n\n vec2 dir = vec2(vTextureCoord - center / filterArea.xy);\n dir.y *= filterArea.y / filterArea.x;\n float dist = length(dir);\n\n if (dist <= 0.0 || dist < currentRadius - halfWavelength || dist > currentRadius + halfWavelength) {\n gl_FragColor = texture2D(uSampler, vTextureCoord);\n return;\n }\n\n vec2 diffUV = normalize(dir);\n\n float diff = (dist - currentRadius) / halfWavelength;\n\n float p = 1.0 - pow(abs(diff), 2.0);\n\n // float powDiff = diff * pow(p, 2.0) * ( amplitude * fade );\n float powDiff = 1.25 * sin(diff * PI) * p * ( amplitude * fade );\n\n vec2 offset = diffUV * powDiff / filterArea.xy;\n\n // Do clamp :\n vec2 coord = vTextureCoord + offset;\n vec2 clampedCoord = clamp(coord, filterClamp.xy, filterClamp.zw);\n vec4 color = texture2D(uSampler, clampedCoord);\n if (coord != clampedCoord) {\n color *= max(0.0, 1.0 - length(coord - clampedCoord));\n }\n\n // No clamp :\n // gl_FragColor = texture2D(uSampler, vTextureCoord + offset);\n\n color.rgb *= 1.0 + (brightness - 1.0) * p * fade;\n\n gl_FragColor = color;\n}\n"),this.center=e,Array.isArray(t)&&(console.warn("Deprecated Warning: ShockwaveFilter params Array has been changed to options Object."),t={}),t=Object.assign({amplitude:30,wavelength:160,brightness:1,speed:500,radius:-1},t),this.amplitude=t.amplitude,this.wavelength=t.wavelength,this.brightness=t.brightness,this.speed=t.speed,this.radius=t.radius,this.time=r}i&&(e.__proto__=i);var t={center:{configurable:!0},amplitude:{configurable:!0},wavelength:{configurable:!0},brightness:{configurable:!0},speed:{configurable:!0},radius:{configurable:!0}};return((e.prototype=Object.create(i&&i.prototype)).constructor=e).prototype.apply=function(e,t,r,i){this.uniforms.time=this.time,e.applyFilter(this,t,r,i)},t.center.get=function(){return this.uniforms.center},t.center.set=function(e){this.uniforms.center=e},t.amplitude.get=function(){return this.uniforms.amplitude},t.amplitude.set=function(e){this.uniforms.amplitude=e},t.wavelength.get=function(){return this.uniforms.wavelength},t.wavelength.set=function(e){this.uniforms.wavelength=e},t.brightness.get=function(){return this.uniforms.brightness},t.brightness.set=function(e){this.uniforms.brightness=e},t.speed.get=function(){return this.uniforms.speed},t.speed.set=function(e){this.uniforms.speed=e},t.radius.get=function(){return this.uniforms.radius},t.radius.set=function(e){this.uniforms.radius=e},Object.defineProperties(e.prototype,t),e}(n.Filter),j=function(i){function e(e,t,r){void 0===t&&(t=0),void 0===r&&(r=1),i.call(this,"attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n vTextureCoord = aTextureCoord;\n}","varying vec2 vTextureCoord;\nuniform sampler2D uSampler;\nuniform sampler2D uLightmap;\nuniform vec4 filterArea;\nuniform vec2 dimensions;\nuniform vec4 ambientColor;\nvoid main() {\n vec4 diffuseColor = texture2D(uSampler, vTextureCoord);\n vec2 lightCoord = (vTextureCoord * filterArea.xy) / dimensions;\n vec4 light = texture2D(uLightmap, lightCoord);\n vec3 ambient = ambientColor.rgb * ambientColor.a;\n vec3 intensity = ambient + light.rgb;\n vec3 finalColor = diffuseColor.rgb * intensity;\n gl_FragColor = vec4(finalColor, diffuseColor.a);\n}\n"),this.uniforms.dimensions=new Float32Array(2),this.uniforms.ambientColor=new Float32Array([0,0,0,r]),this.texture=e,this.color=t}i&&(e.__proto__=i);var t={texture:{configurable:!0},color:{configurable:!0},alpha:{configurable:!0}};return((e.prototype=Object.create(i&&i.prototype)).constructor=e).prototype.apply=function(e,t,r,i){this.uniforms.dimensions[0]=t.filterFrame.width,this.uniforms.dimensions[1]=t.filterFrame.height,e.applyFilter(this,t,r,i)},t.texture.get=function(){return this.uniforms.uLightmap},t.texture.set=function(e){this.uniforms.uLightmap=e},t.color.set=function(e){var t=this.uniforms.ambientColor;"number"==typeof e?(l.hex2rgb(e,t),this._color=e):(t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=e[3],this._color=l.rgb2hex(t))},t.color.get=function(){return this._color},t.alpha.get=function(){return this.uniforms.ambientColor[3]},t.alpha.set=function(e){this.uniforms.ambientColor[3]=e},Object.defineProperties(e.prototype,t),e}(n.Filter),N=function(n){function e(e,t,r,i){void 0===e&&(e=100),void 0===t&&(t=600),void 0===r&&(r=null),void 0===i&&(i=null),n.call(this,"attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n vTextureCoord = aTextureCoord;\n}","varying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\nuniform float blur;\nuniform float gradientBlur;\nuniform vec2 start;\nuniform vec2 end;\nuniform vec2 delta;\nuniform vec2 texSize;\n\nfloat random(vec3 scale, float seed)\n{\n return fract(sin(dot(gl_FragCoord.xyz + seed, scale)) * 43758.5453 + seed);\n}\n\nvoid main(void)\n{\n vec4 color = vec4(0.0);\n float total = 0.0;\n\n float offset = random(vec3(12.9898, 78.233, 151.7182), 0.0);\n vec2 normal = normalize(vec2(start.y - end.y, end.x - start.x));\n float radius = smoothstep(0.0, 1.0, abs(dot(vTextureCoord * texSize - start, normal)) / gradientBlur) * blur;\n\n for (float t = -30.0; t <= 30.0; t++)\n {\n float percent = (t + offset - 0.5) / 30.0;\n float weight = 1.0 - abs(percent);\n vec4 sample = texture2D(uSampler, vTextureCoord + delta / texSize * percent * radius);\n sample.rgb *= sample.a;\n color += sample * weight;\n total += weight;\n }\n\n color /= total;\n color.rgb /= color.a + 0.00001;\n\n gl_FragColor = color;\n}\n"),this.uniforms.blur=e,this.uniforms.gradientBlur=t,this.uniforms.start=r||new f.Point(0,window.innerHeight/2),this.uniforms.end=i||new f.Point(600,window.innerHeight/2),this.uniforms.delta=new f.Point(30,30),this.uniforms.texSize=new f.Point(window.innerWidth,window.innerHeight),this.updateDelta()}n&&(e.__proto__=n);var t={blur:{configurable:!0},gradientBlur:{configurable:!0},start:{configurable:!0},end:{configurable:!0}};return((e.prototype=Object.create(n&&n.prototype)).constructor=e).prototype.updateDelta=function(){this.uniforms.delta.x=0,this.uniforms.delta.y=0},t.blur.get=function(){return this.uniforms.blur},t.blur.set=function(e){this.uniforms.blur=e},t.gradientBlur.get=function(){return this.uniforms.gradientBlur},t.gradientBlur.set=function(e){this.uniforms.gradientBlur=e},t.start.get=function(){return this.uniforms.start},t.start.set=function(e){this.uniforms.start=e,this.updateDelta()},t.end.get=function(){return this.uniforms.end},t.end.set=function(e){this.uniforms.end=e,this.updateDelta()},Object.defineProperties(e.prototype,t),e}(n.Filter),B=function(e){function t(){e.apply(this,arguments)}return e&&(t.__proto__=e),((t.prototype=Object.create(e&&e.prototype)).constructor=t).prototype.updateDelta=function(){var e=this.uniforms.end.x-this.uniforms.start.x,t=this.uniforms.end.y-this.uniforms.start.y,r=Math.sqrt(e*e+t*t);this.uniforms.delta.x=e/r,this.uniforms.delta.y=t/r},t}(N),U=function(e){function t(){e.apply(this,arguments)}return e&&(t.__proto__=e),((t.prototype=Object.create(e&&e.prototype)).constructor=t).prototype.updateDelta=function(){var e=this.uniforms.end.x-this.uniforms.start.x,t=this.uniforms.end.y-this.uniforms.start.y,r=Math.sqrt(e*e+t*t);this.uniforms.delta.x=-t/r,this.uniforms.delta.y=e/r},t}(N),X=function(n){function e(e,t,r,i){void 0===e&&(e=100),void 0===t&&(t=600),void 0===r&&(r=null),void 0===i&&(i=null),n.call(this),this.tiltShiftXFilter=new B(e,t,r,i),this.tiltShiftYFilter=new U(e,t,r,i)}n&&(e.__proto__=n);var t={blur:{configurable:!0},gradientBlur:{configurable:!0},start:{configurable:!0},end:{configurable:!0}};return((e.prototype=Object.create(n&&n.prototype)).constructor=e).prototype.apply=function(e,t,r){var i=e.getFilterTexture();this.tiltShiftXFilter.apply(e,t,i),this.tiltShiftYFilter.apply(e,i,r),e.returnFilterTexture(i)},t.blur.get=function(){return this.tiltShiftXFilter.blur},t.blur.set=function(e){this.tiltShiftXFilter.blur=this.tiltShiftYFilter.blur=e},t.gradientBlur.get=function(){return this.tiltShiftXFilter.gradientBlur},t.gradientBlur.set=function(e){this.tiltShiftXFilter.gradientBlur=this.tiltShiftYFilter.gradientBlur=e},t.start.get=function(){return this.tiltShiftXFilter.start},t.start.set=function(e){this.tiltShiftXFilter.start=this.tiltShiftYFilter.start=e},t.end.get=function(){return this.tiltShiftXFilter.end},t.end.set=function(e){this.tiltShiftXFilter.end=this.tiltShiftYFilter.end=e},Object.defineProperties(e.prototype,t),e}(n.Filter),H=function(i){function e(e,t,r){void 0===e&&(e=200),void 0===t&&(t=4),void 0===r&&(r=20),i.call(this,"attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n vTextureCoord = aTextureCoord;\n}","varying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\nuniform float radius;\nuniform float angle;\nuniform vec2 offset;\nuniform vec4 filterArea;\n\nvec2 mapCoord( vec2 coord )\n{\n coord *= filterArea.xy;\n coord += filterArea.zw;\n\n return coord;\n}\n\nvec2 unmapCoord( vec2 coord )\n{\n coord -= filterArea.zw;\n coord /= filterArea.xy;\n\n return coord;\n}\n\nvec2 twist(vec2 coord)\n{\n coord -= offset;\n\n float dist = length(coord);\n\n if (dist < radius)\n {\n float ratioDist = (radius - dist) / radius;\n float angleMod = ratioDist * ratioDist * angle;\n float s = sin(angleMod);\n float c = cos(angleMod);\n coord = vec2(coord.x * c - coord.y * s, coord.x * s + coord.y * c);\n }\n\n coord += offset;\n\n return coord;\n}\n\nvoid main(void)\n{\n\n vec2 coord = mapCoord(vTextureCoord);\n\n coord = twist(coord);\n\n coord = unmapCoord(coord);\n\n gl_FragColor = texture2D(uSampler, coord );\n\n}\n"),this.radius=e,this.angle=t,this.padding=r}i&&(e.__proto__=i),(e.prototype=Object.create(i&&i.prototype)).constructor=e;var t={offset:{configurable:!0},radius:{configurable:!0},angle:{configurable:!0}};return t.offset.get=function(){return this.uniforms.offset},t.offset.set=function(e){this.uniforms.offset=e},t.radius.get=function(){return this.uniforms.radius},t.radius.set=function(e){this.uniforms.radius=e},t.angle.get=function(){return this.uniforms.angle},t.angle.set=function(e){this.uniforms.angle=e},Object.defineProperties(e.prototype,t),e}(n.Filter),G=function(n){function e(e,t,r,i){void 0===e&&(e=.1),void 0===t&&(t=[0,0]),void 0===r&&(r=0),void 0===i&&(i=-1),n.call(this,"attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n vTextureCoord = aTextureCoord;\n}","varying vec2 vTextureCoord;\nuniform sampler2D uSampler;\nuniform vec4 filterArea;\n\nuniform vec2 uCenter;\nuniform float uStrength;\nuniform float uInnerRadius;\nuniform float uRadius;\n\nconst float MAX_KERNEL_SIZE = 32.0;\n\n// author: http://byteblacksmith.com/improvements-to-the-canonical-one-liner-glsl-rand-for-opengl-es-2-0/\nhighp float rand(vec2 co, float seed) {\n const highp float a = 12.9898, b = 78.233, c = 43758.5453;\n highp float dt = dot(co + seed, vec2(a, b)), sn = mod(dt, 3.14159);\n return fract(sin(sn) * c + seed);\n}\n\nvoid main() {\n\n float minGradient = uInnerRadius * 0.3;\n float innerRadius = (uInnerRadius + minGradient * 0.5) / filterArea.x;\n\n float gradient = uRadius * 0.3;\n float radius = (uRadius - gradient * 0.5) / filterArea.x;\n\n float countLimit = MAX_KERNEL_SIZE;\n\n vec2 dir = vec2(uCenter.xy / filterArea.xy - vTextureCoord);\n float dist = length(vec2(dir.x, dir.y * filterArea.y / filterArea.x));\n\n float strength = uStrength;\n\n float delta = 0.0;\n float gap;\n if (dist < innerRadius) {\n delta = innerRadius - dist;\n gap = minGradient;\n } else if (radius >= 0.0 && dist > radius) { // radius < 0 means it's infinity\n delta = dist - radius;\n gap = gradient;\n }\n\n if (delta > 0.0) {\n float normalCount = gap / filterArea.x;\n delta = (normalCount - delta) / normalCount;\n countLimit *= delta;\n strength *= delta;\n if (countLimit < 1.0)\n {\n gl_FragColor = texture2D(uSampler, vTextureCoord);\n return;\n }\n }\n\n // randomize the lookup values to hide the fixed number of samples\n float offset = rand(vTextureCoord, 0.0);\n\n float total = 0.0;\n vec4 color = vec4(0.0);\n\n dir *= strength;\n\n for (float t = 0.0; t < MAX_KERNEL_SIZE; t++) {\n float percent = (t + offset) / MAX_KERNEL_SIZE;\n float weight = 4.0 * (percent - percent * percent);\n vec2 p = vTextureCoord + dir * percent;\n vec4 sample = texture2D(uSampler, p);\n\n // switch to pre-multiplied alpha to correctly blur transparent images\n // sample.rgb *= sample.a;\n\n color += sample * weight;\n total += weight;\n\n if (t > countLimit){\n break;\n }\n }\n\n color /= total;\n // switch back from pre-multiplied alpha\n // color.rgb /= color.a + 0.00001;\n\n gl_FragColor = color;\n}\n"),this.center=t,this.strength=e,this.innerRadius=r,this.radius=i}n&&(e.__proto__=n),(e.prototype=Object.create(n&&n.prototype)).constructor=e;var t={center:{configurable:!0},strength:{configurable:!0},innerRadius:{configurable:!0},radius:{configurable:!0}};return t.center.get=function(){return this.uniforms.uCenter},t.center.set=function(e){this.uniforms.uCenter=e},t.strength.get=function(){return this.uniforms.uStrength},t.strength.set=function(e){this.uniforms.uStrength=e},t.innerRadius.get=function(){return this.uniforms.uInnerRadius},t.innerRadius.set=function(e){this.uniforms.uInnerRadius=e},t.radius.get=function(){return this.uniforms.uRadius},t.radius.set=function(e){(e<0||e===1/0)&&(e=-1),this.uniforms.uRadius=e},Object.defineProperties(e.prototype,t),e}(n.Filter);return e.AdjustmentFilter=t,e.AdvancedBloomFilter=i,e.AsciiFilter=o,e.BevelFilter=a,e.BloomFilter=g,e.BulgePinchFilter=v,e.CRTFilter=w,e.ColorMapFilter=_,e.ColorReplaceFilter=y,e.ConvolutionFilter=b,e.CrossHatchFilter=x,e.DotFilter=T,e.DropShadowFilter=k,e.EmbossFilter=P,e.GlitchFilter=S,e.GlowFilter=E,e.GodrayFilter=A,e.KawaseBlurFilter=d,e.MotionBlurFilter=C,e.MultiColorReplaceFilter=I,e.OldFilmFilter=O,e.OutlineFilter=M,e.PixelateFilter=D,e.RGBSplitFilter=L,e.RadialBlurFilter=R,e.ReflectionFilter=z,e.ShockwaveFilter=F,e.SimpleLightmapFilter=j,e.TiltShiftAxisFilter=N,e.TiltShiftFilter=X,e.TiltShiftXFilter=B,e.TiltShiftYFilter=U,e.TwistFilter=H,e.ZoomBlurFilter=G,e}({},PIXI,PIXI,PIXI,PIXI.utils,PIXI,PIXI.filters,PIXI.filters),pixi_projection,pixi_projection;Object.assign(PIXI.filters,__filters),this.PIXI=this.PIXI||{},function(p,v){"use strict";var t,f,d=function(){function f(e,t,r){this.value=e,this.time=t,this.next=null,this.isStepped=!1,this.ease=r?"function"==typeof r?r:p.ParticleUtils.generateEase(r):null}return f.createList=function(e){if("list"in e){var t=e.list,r=void 0,i=void 0,n=t[0],o=n.value,a=n.time;if(i=r=new f("string"==typeof o?p.ParticleUtils.hexToRGB(o):o,a,e.ease),2a.time;)n=a,a=e[++o];l=(l-n.time)/(a.time-n.time);var u=f.hexToRGB(n.value),h=f.hexToRGB(a.value),c={r:(h.r-u.r)*l+u.r,g:(h.g-u.g)*l+u.g,b:(h.b-u.b)*l+u.b};i.next=new d(c,s/t),i=i.next}return r};var i=function(e,t){return(i=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])})(e,t)};function n(e,t){function r(){this.constructor=e}i(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)}var o=function(){function e(e){void 0===e&&(e=!1),this.current=null,this.next=null,this.isColor=!!e,this.interpolate=null,this.ease=null}return e.prototype.reset=function(e){this.current=e,this.next=e.next,this.next&&1<=this.next.time?this.interpolate=this.isColor?a:r:e.isStepped?this.interpolate=this.isColor?c:u:this.interpolate=this.isColor?l:s,this.ease=this.current.ease},e}();function r(e){return this.ease&&(e=this.ease(e)),(this.next.value-this.current.value)*e+this.current.value}function a(e){this.ease&&(e=this.ease(e));var t=this.current.value,r=this.next.value,i=(r.r-t.r)*e+t.r,n=(r.g-t.g)*e+t.g,o=(r.b-t.b)*e+t.b;return p.ParticleUtils.combineRGBComponents(i,n,o)}function s(e){for(this.ease&&(e=this.ease(e));e>this.next.time;)this.current=this.next,this.next=this.next.next;return e=(e-this.current.time)/(this.next.time-this.current.time),(this.next.value-this.current.value)*e+this.current.value}function l(e){for(this.ease&&(e=this.ease(e));e>this.next.time;)this.current=this.next,this.next=this.next.next;e=(e-this.current.time)/(this.next.time-this.current.time);var t=this.current.value,r=this.next.value,i=(r.r-t.r)*e+t.r,n=(r.g-t.g)*e+t.g,o=(r.b-t.b)*e+t.b;return p.ParticleUtils.combineRGBComponents(i,n,o)}function u(e){for(this.ease&&(e=this.ease(e));this.next&&e>this.next.time;)this.current=this.next,this.next=this.next.next;return this.current.value}function c(e){for(this.ease&&(e=this.ease(e));this.next&&e>this.next.time;)this.current=this.next,this.next=this.next.next;var t=this.current.value;return p.ParticleUtils.combineRGBComponents(t.r,t.g,t.b)}var m,g=function(r){function i(e){var t=r.call(this)||this;return t.emitter=e,t.anchor.x=t.anchor.y=.5,t.velocity=new v.Point,t.rotationSpeed=0,t.rotationAcceleration=0,t.maxLife=0,t.age=0,t.ease=null,t.extraData=null,t.alphaList=new o,t.speedList=new o,t.speedMultiplier=1,t.acceleration=new v.Point,t.maxSpeed=NaN,t.scaleList=new o,t.scaleMultiplier=1,t.colorList=new o(!0),t._doAlpha=!1,t._doScale=!1,t._doSpeed=!1,t._doAcceleration=!1,t._doColor=!1,t._doNormalMovement=!1,t._oneOverLife=0,t.next=null,t.prev=null,t.init=t.init,t.Particle_init=i.prototype.init,t.update=t.update,t.Particle_update=i.prototype.update,t.Sprite_destroy=r.prototype.destroy,t.Particle_destroy=i.prototype.destroy,t.applyArt=t.applyArt,t.kill=t.kill,t}return n(i,r),i.prototype.init=function(){this.age=0,this.velocity.x=this.speedList.current.value*this.speedMultiplier,this.velocity.y=0,p.ParticleUtils.rotatePoint(this.rotation,this.velocity),this.noRotation?this.rotation=0:this.rotation*=p.ParticleUtils.DEG_TO_RADS,this.rotationSpeed*=p.ParticleUtils.DEG_TO_RADS,this.rotationAcceleration*=p.ParticleUtils.DEG_TO_RADS,this.alpha=this.alphaList.current.value,this.scale.x=this.scale.y=this.scaleList.current.value,this._doAlpha=!!this.alphaList.current.next,this._doSpeed=!!this.speedList.current.next,this._doScale=!!this.scaleList.current.next,this._doColor=!!this.colorList.current.next,this._doAcceleration=0!==this.acceleration.x||0!==this.acceleration.y,this._doNormalMovement=this._doSpeed||0!==this.speedList.current.value||this._doAcceleration,this._oneOverLife=1/this.maxLife;var e=this.colorList.current.value;this.tint=p.ParticleUtils.combineRGBComponents(e.r,e.g,e.b),this.visible=!0},i.prototype.applyArt=function(e){this.texture=e||v.Texture.EMPTY},i.prototype.update=function(e){if(this.age+=e,this.age>=this.maxLife||this.age<0)return this.kill(),-1;var t=this.age*this._oneOverLife;if(this.ease&&(t=4==this.ease.length?this.ease(t,0,1,1):this.ease(t)),this._doAlpha&&(this.alpha=this.alphaList.interpolate(t)),this._doScale){var r=this.scaleList.interpolate(t)*this.scaleMultiplier;this.scale.x=this.scale.y=r}if(this._doNormalMovement){var i=void 0,n=void 0;if(this._doSpeed){var o=this.speedList.interpolate(t)*this.speedMultiplier;p.ParticleUtils.normalize(this.velocity),p.ParticleUtils.scaleBy(this.velocity,o),i=this.velocity.x*e,n=this.velocity.y*e}else if(this._doAcceleration){var a=this.velocity.x,s=this.velocity.y;if(this.velocity.x+=this.acceleration.x*e,this.velocity.y+=this.acceleration.y*e,this.maxSpeed){var l=p.ParticleUtils.length(this.velocity);l>this.maxSpeed&&p.ParticleUtils.scaleBy(this.velocity,this.maxSpeed/l)}i=(a+this.velocity.x)/2*e,n=(s+this.velocity.y)/2*e}else i=this.velocity.x*e,n=this.velocity.y*e;this.position.x+=i,this.position.y+=n}if(this._doColor&&(this.tint=this.colorList.interpolate(t)),0!==this.rotationAcceleration){var u=this.rotationSpeed+this.rotationAcceleration*e;this.rotation+=(this.rotationSpeed+u)/2*e,this.rotationSpeed=u}else 0!==this.rotationSpeed?this.rotation+=this.rotationSpeed*e:this.acceleration&&!this.noRotation&&(this.rotation=Math.atan2(this.velocity.y,this.velocity.x));return t},i.prototype.kill=function(){this.emitter.recycle(this)},i.prototype.destroy=function(){this.parent&&this.parent.removeChild(this),this.Sprite_destroy(),this.emitter=this.velocity=this.colorList=this.scaleList=this.alphaList=this.speedList=this.ease=this.next=this.prev=null},i.parseArt=function(e){var t;for(t=e.length;0<=t;--t)"string"==typeof e[t]&&(e[t]=h(e[t]));if(p.ParticleUtils.verbose)for(t=e.length-1;0=this.maxParticles)this._spawnTimer+=this._frequency;else{var l=void 0;if(l=this.minLifetime==this.maxLifetime?this.minLifetime:Math.random()*(this.maxLifetime-this.minLifetime)+this.minLifetime,-this._spawnTimer=this.spawnChance)){var p=void 0;if(this._poolFirst?(p=this._poolFirst,this._poolFirst=this._poolFirst.next,p.next=null):p=new this.particleConstructor(this),1=this.particleImages.length)&&(this._currentImageIndex=0)):p.applyArt(this.particleImages[Math.floor(Math.random()*this.particleImages.length)]):p.applyArt(this.particleImages[0]),p.alphaList.reset(this.startAlpha),1!=this.minimumSpeedMultiplier&&(p.speedMultiplier=Math.random()*(1-this.minimumSpeedMultiplier)+this.minimumSpeedMultiplier),p.speedList.reset(this.startSpeed),p.acceleration.x=this.acceleration.x,p.acceleration.y=this.acceleration.y,p.maxSpeed=this.maxSpeed,1!=this.minimumScaleMultiplier&&(p.scaleMultiplier=Math.random()*(1-this.minimumScaleMultiplier)+this.minimumScaleMultiplier),p.scaleList.reset(this.startScale),p.colorList.reset(this.startColor),this.minRotationSpeed==this.maxRotationSpeed?p.rotationSpeed=this.minRotationSpeed:p.rotationSpeed=Math.random()*(this.maxRotationSpeed-this.minRotationSpeed)+this.minRotationSpeed,p.rotationAcceleration=this.rotationAcceleration,p.noRotation=this.noRotation,p.maxLife=l,p.blendMode=this.particleBlendMode,p.ease=this.customEase,p.extraData=this.extraData,this.applyAdditionalProperties(p),this._spawnFunc(p,u,h,t),p.init(),p.update(-this._spawnTimer),p.parent){var d=this._parent.children;if(d[0]==p)d.shift();else if(d[d.length-1]==p)d.pop();else{var m=d.indexOf(p);d.splice(m,1)}this.addAtBack?d.unshift(p):d.push(p)}else this.addAtBack?this._parent.addChildAt(p,0):this._parent.addChild(p);this._activeParticlesLast?((this._activeParticlesLast.next=p).prev=this._activeParticlesLast,this._activeParticlesLast=p):this._activeParticlesLast=this._activeParticlesFirst=p,++this.particleCount}}this._spawnTimer+=this._frequency}}if(this._posChanged&&(this._prevEmitterPos.x=a,this._prevEmitterPos.y=s,this._prevPosIsValid=!0,this._posChanged=!1),!this._emit&&!this._activeParticlesFirst){if(this._completeCallback){var g=this._completeCallback;this._completeCallback=null,g()}this._destroyWhenComplete&&this.destroy()}}},e.prototype.applyAdditionalProperties=function(e){},e.prototype._spawnPoint=function(e,t,r){this.minStartRotation==this.maxStartRotation?e.rotation=this.minStartRotation+this.rotation:e.rotation=Math.random()*(this.maxStartRotation-this.minStartRotation)+this.minStartRotation+this.rotation,e.position.x=t,e.position.y=r},e.prototype._spawnRect=function(e,t,r){this.minStartRotation==this.maxStartRotation?e.rotation=this.minStartRotation+this.rotation:e.rotation=Math.random()*(this.maxStartRotation-this.minStartRotation)+this.minStartRotation+this.rotation,b.x=Math.random()*this.spawnRect.width+this.spawnRect.x,b.y=Math.random()*this.spawnRect.height+this.spawnRect.y,0!==this.rotation&&p.ParticleUtils.rotatePoint(this.rotation,b),e.position.x=t+b.x,e.position.y=r+b.y},e.prototype._spawnCircle=function(e,t,r){this.minStartRotation==this.maxStartRotation?e.rotation=this.minStartRotation+this.rotation:e.rotation=Math.random()*(this.maxStartRotation-this.minStartRotation)+this.minStartRotation+this.rotation,b.x=Math.random()*this.spawnCircle.radius,b.y=0,p.ParticleUtils.rotatePoint(360*Math.random(),b),b.x+=this.spawnCircle.x,b.y+=this.spawnCircle.y,0!==this.rotation&&p.ParticleUtils.rotatePoint(this.rotation,b),e.position.x=t+b.x,e.position.y=r+b.y},e.prototype._spawnRing=function(e,t,r){var i=this.spawnCircle;this.minStartRotation==this.maxStartRotation?e.rotation=this.minStartRotation+this.rotation:e.rotation=Math.random()*(this.maxStartRotation-this.minStartRotation)+this.minStartRotation+this.rotation,i.minRadius!==i.radius?b.x=Math.random()*(i.radius-i.minRadius)+i.minRadius:b.x=i.radius,b.y=0;var n=360*Math.random();e.rotation+=n,p.ParticleUtils.rotatePoint(n,b),b.x+=this.spawnCircle.x,b.y+=this.spawnCircle.y,0!==this.rotation&&p.ParticleUtils.rotatePoint(this.rotation,b),e.position.x=t+b.x,e.position.y=r+b.y},e.prototype._spawnPolygonalChain=function(e,t,r){this.minStartRotation==this.maxStartRotation?e.rotation=this.minStartRotation+this.rotation:e.rotation=Math.random()*(this.maxStartRotation-this.minStartRotation)+this.minStartRotation+this.rotation,this.spawnPolygonalChain.getRandomPoint(b),0!==this.rotation&&p.ParticleUtils.rotatePoint(this.rotation,b),e.position.x=t+b.x,e.position.y=r+b.y},e.prototype._spawnBurst=function(e,t,r,i){0===this.particleSpacing?e.rotation=360*Math.random():e.rotation=this.angleStart+this.particleSpacing*i+this.rotation,e.position.x=t,e.position.y=r},e.prototype.cleanup=function(){var e,t;for(e=this._activeParticlesFirst;e;e=t)t=e.next,this.recycle(e),e.parent&&e.parent.removeChild(e);this._activeParticlesFirst=this._activeParticlesLast=null,this.particleCount=0},e.prototype.destroy=function(){var e;this.autoUpdate=!1,this.cleanup();for(var t=this._poolFirst;t;t=e)e=t.next,t.destroy();this._poolFirst=this._parent=this.particleImages=this.spawnPos=this.ownerPos=this.startColor=this.startScale=this.startAlpha=this.startSpeed=this.customEase=this._completeCallback=null},e}(),w=new v.Point,T=["pow","sqrt","abs","floor","round","ceil","E","PI","sin","cos","tan","asin","acos","atan","atan2","log"],k=new RegExp(["[01234567890\\.\\*\\-\\+\\/\\(\\)x ,]"].concat(T).join("|"),"g"),P=function(r){function e(e){var t=r.call(this,e)||this;return t.path=null,t.initialRotation=0,t.initialPosition=new v.Point,t.movement=0,t}return n(e,r),e.prototype.init=function(){this.initialRotation=this.rotation,this.Particle_init(),this.path=this.extraData.path,this._doNormalMovement=!this.path,this.movement=0,this.initialPosition.x=this.position.x,this.initialPosition.y=this.position.y},e.prototype.update=function(e){var t=this.Particle_update(e);if(0<=t&&this.path){var r=this.speedList.interpolate(t)*this.speedMultiplier;this.movement+=r*e,w.x=this.movement,w.y=this.path(this.movement),p.ParticleUtils.rotatePoint(this.initialRotation,w),this.position.x=this.initialPosition.x+w.x,this.position.y=this.initialPosition.y+w.y}return t},e.prototype.destroy=function(){this.Particle_destroy(),this.path=this.initialPosition=null},e.parseArt=function(e){return g.parseArt(e)},e.parseData=function(e){var t={};if(e&&e.path)try{t.path=function(e){for(var t=e.match(k),r=t.length-1;0<=r;--r)0<=T.indexOf(t[r])&&(t[r]="Math."+t[r]);return e=t.join(""),new Function("x","return "+e+";")}(e.path)}catch(e){p.ParticleUtils.verbose&&console.error("PathParticle: error in parsing path expression"),t.path=null}else p.ParticleUtils.verbose&&console.error("PathParticle requires a path string in extraData!"),t.path=null;return t},e}(g),S=function(r){function e(e){var t=r.call(this,e)||this;return t.textures=null,t.duration=0,t.framerate=0,t.elapsed=0,t.loop=!1,t}return n(e,r),e.prototype.init=function(){this.Particle_init(),this.elapsed=0,this.framerate<0&&(this.duration=this.maxLife,this.framerate=this.textures.length/this.duration)},e.prototype.applyArt=function(e){this.textures=e.textures,this.framerate=e.framerate,this.duration=e.duration,this.loop=e.loop},e.prototype.update=function(e){var t=this.Particle_update(e);if(0<=t){this.elapsed+=e,this.elapsed>this.duration&&(this.loop?this.elapsed=this.elapsed%this.duration:this.elapsed=this.duration-1e-6);var r=this.elapsed*this.framerate+1e-7|0;this.texture=this.textures[r]||v.Texture.EMPTY}return t},e.prototype.destroy=function(){this.Particle_destroy(),this.textures=null},e.parseArt=function(e){for(var t,r,i,n,o,a=[],s=0;st[s]&&(i=t[s]),ot[s+1]&&(n=t[s+1]),af[u]){l=c[s];c[s]=c[u],c[u]=l;var h=f[s];f[s]=f[u],f[u]=h}if(t[0]=c[0].x,t[1]=c[0].y,t[2]=c[1].x,t[3]=c[1].y,t[4]=c[2].x,t[5]=c[2].y,t[6]=c[3].x,t[7]=c[3].y,(c[3].x-c[2].x)*(c[1].y-c[2].y)-(c[1].x-c[2].x)*(c[3].y-c[2].y)<0)return t[4]=c[3].x,void(t[5]=c[3].y)}},e}();e.Surface=t}(pixi_projection||(pixi_projection={})),function(e){var k=new PIXI.Matrix,n=new PIXI.Rectangle,P=new PIXI.Point,t=function(t){function e(){var e=t.call(this)||this;return e.distortion=new PIXI.Point,e}return __extends(e,t),e.prototype.clear=function(){this.distortion.set(0,0)},e.prototype.apply=function(e,t){t=t||new PIXI.Point;var r=this.distortion,i=e.x*e.y;return t.x=e.x+r.x*i,t.y=e.y+r.y*i,t},e.prototype.applyInverse=function(e,t){t=t||new PIXI.Point;var r=e.x,i=e.y,n=this.distortion.x,o=this.distortion.y;if(0==n)t.x=r,t.y=i/(1+o*r);else if(0==o)t.y=i,t.x=r/(1+n*i);else{var a=.5*(i*n-r*o+1)/o,s=a*a+r/o;if(s<=1e-5)return void t.set(NaN,NaN);t.x=0 vFrame.z ||\n pixels.y < vFrame.y || pixels.y > vFrame.w) {\n uv.x = vTrans1.x * surface2.x + vTrans1.y * surface2.y + vTrans1.z;\n uv.y = vTrans2.x * surface2.x + vTrans2.y * surface2.y + vTrans2.z;\n pixels = uv * vSamplerSize;\n \n// if (pixels.x < vFrame.x || pixels.x > vFrame.z ||\n// pixels.y < vFrame.y || pixels.y > vFrame.w) {\n// discard;\n// }\n}\n\nvec4 edge;\nedge.xy = clamp(pixels - vFrame.xy + 0.5, vec2(0.0, 0.0), vec2(1.0, 1.0));\nedge.zw = clamp(vFrame.zw - pixels + 0.5, vec2(0.0, 0.0), vec2(1.0, 1.0));\n\nfloat alpha = 1.0; //edge.x * edge.y * edge.z * edge.w;\nvec4 rColor = vColor * alpha;\n\nfloat textureId = floor(vTextureId+0.5);\nvec2 vTextureCoord = uv;\nvec4 color;\n%forloop%\ngl_FragColor = vec4(0.0, 1.0, 0.0, 1.0);\n//gl_FragColor = color * rColor;\n}",geometryClass:s,vertexSize:16},e),i=t.vertex,n=t.fragment,o=t.vertexSize,a=t.geometryClass;return function(r){function e(e){var t=r.call(this,e)||this;return t.defUniforms={translationMatrix:new PIXI.Matrix,distortion:new Float32Array([0,0])},t.size=1e3,t.forceMaxTextures=1,t.shaderGenerator=new PIXI.BatchShaderGenerator(i,n),t.geometryClass=a,t.vertexSize=o,t}return __extends(e,r),e.prototype.getUniforms=function(e){var t=e.proj;return null!==t.surface?t.uniforms:null!==t._activeProjection?t._activeProjection.uniforms:this.defUniforms},e.prototype.packInterleavedGeometry=function(e,t,r,i,n){for(var o=t.uint32View,a=t.float32View,s=i/this.vertexSize,l=e.indices,u=e.vertexData,h=e._texture._frame,c=e.aTrans,f=e._texture.baseTexture,p=f._batchLocation,d=f.realWidth,m=f.realHeight,g=f.resolution,v=Math.min(e.worldAlpha,1),_=v<1&&e._texture.baseTexture.alphaMode?b(e._tintRGB,v):e._tintRGB+(255*v<<24),y=0;y=o.TRANSFORM_STEP.PROJ?(i||this.displayObjectUpdateTransform(),this.proj.affine?this.transform.worldTransform.applyInverse(e,r):this.proj.world.applyInverse(e,r)):(this.parent?r=this.parent.worldTransform.applyInverse(e,r):r.copyFrom(e),n===o.TRANSFORM_STEP.NONE?r:this.transform.localTransform.applyInverse(r,r))},Object.defineProperty(e.prototype,"worldTransform",{get:function(){return this.proj.affine?this.transform.worldTransform:this.proj.world},enumerable:!0,configurable:!0}),e}(PIXI.Container);o.Container2d=e,o.container2dToLocal=e.prototype.toLocal}(pixi_projection||(pixi_projection={})),function(e){var l,t,v=PIXI.Point,r=[1,0,0,0,1,0,0,0,1];(t=l=e.AFFINE||(e.AFFINE={}))[t.NONE=0]="NONE",t[t.FREE=1]="FREE",t[t.AXIS_X=2]="AXIS_X",t[t.AXIS_Y=3]="AXIS_Y",t[t.POINT=4]="POINT",t[t.AXIS_XR=5]="AXIS_XR";var i=function(){function e(e){this.floatArray=null,this.mat3=new Float64Array(e||r)}return Object.defineProperty(e.prototype,"a",{get:function(){return this.mat3[0]/this.mat3[8]},set:function(e){this.mat3[0]=e*this.mat3[8]},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"b",{get:function(){return this.mat3[1]/this.mat3[8]},set:function(e){this.mat3[1]=e*this.mat3[8]},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"c",{get:function(){return this.mat3[3]/this.mat3[8]},set:function(e){this.mat3[3]=e*this.mat3[8]},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"d",{get:function(){return this.mat3[4]/this.mat3[8]},set:function(e){this.mat3[4]=e*this.mat3[8]},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"tx",{get:function(){return this.mat3[6]/this.mat3[8]},set:function(e){this.mat3[6]=e*this.mat3[8]},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"ty",{get:function(){return this.mat3[7]/this.mat3[8]},set:function(e){this.mat3[7]=e*this.mat3[8]},enumerable:!0,configurable:!0}),e.prototype.set=function(e,t,r,i,n,o){var a=this.mat3;return a[0]=e,a[1]=t,a[2]=0,a[3]=r,a[4]=i,a[5]=0,a[6]=n,a[7]=o,a[8]=1,this},e.prototype.toArray=function(e,t){this.floatArray||(this.floatArray=new Float32Array(9));var r=t||this.floatArray,i=this.mat3;return e?(r[0]=i[0],r[1]=i[1],r[2]=i[2],r[3]=i[3],r[4]=i[4],r[5]=i[5],r[6]=i[6],r[7]=i[7]):(r[0]=i[0],r[1]=i[3],r[2]=i[6],r[3]=i[1],r[4]=i[4],r[5]=i[7],r[6]=i[2],r[7]=i[5]),r[8]=i[8],r},e.prototype.apply=function(e,t){t=t||new PIXI.Point;var r=this.mat3,i=e.x,n=e.y,o=1/(r[2]*i+r[5]*n+r[8]);return t.x=o*(r[0]*i+r[3]*n+r[6]),t.y=o*(r[1]*i+r[4]*n+r[7]),t},e.prototype.translate=function(e,t){var r=this.mat3;return r[0]+=e*r[2],r[1]+=t*r[2],r[3]+=e*r[5],r[4]+=t*r[5],r[6]+=e*r[8],r[7]+=t*r[8],this},e.prototype.scale=function(e,t){var r=this.mat3;return r[0]*=e,r[1]*=t,r[3]*=e,r[4]*=t,r[6]*=e,r[7]*=t,this},e.prototype.scaleAndTranslate=function(e,t,r,i){var n=this.mat3;n[0]=e*n[0]+r*n[2],n[1]=t*n[1]+i*n[2],n[3]=e*n[3]+r*n[5],n[4]=t*n[4]+i*n[5],n[6]=e*n[6]+r*n[8],n[7]=t*n[7]+i*n[8]},e.prototype.applyInverse=function(e,t){t=t||new v;var r=this.mat3,i=e.x,n=e.y,o=r[0],a=r[3],s=r[6],l=r[1],u=r[4],h=r[7],c=r[2],f=r[5],p=r[8],d=(p*u-h*f)*i+(-p*a+s*f)*n+(h*a-s*u),m=(-p*l+h*c)*i+(p*o-s*c)*n+(-h*o+s*l),g=(f*l-u*c)*i+(-f*o+a*c)*n+(u*o-a*l);return t.x=d/g,t.y=m/g,t},e.prototype.invert=function(){var e=this.mat3,t=e[0],r=e[1],i=e[2],n=e[3],o=e[4],a=e[5],s=e[6],l=e[7],u=e[8],h=u*o-a*l,c=-u*n+a*s,f=l*n-o*s,p=t*h+r*c+i*f;return p&&(p=1/p,e[0]=h*p,e[1]=(-u*r+i*l)*p,e[2]=(a*r-i*o)*p,e[3]=c*p,e[4]=(u*t-i*s)*p,e[5]=(-a*t+i*n)*p,e[6]=f*p,e[7]=(-l*t+r*s)*p,e[8]=(o*t-r*n)*p),this},e.prototype.identity=function(){var e=this.mat3;return e[0]=1,e[1]=0,e[2]=0,e[3]=0,e[4]=1,e[5]=0,e[6]=0,e[7]=0,e[8]=1,this},e.prototype.clone=function(){return new e(this.mat3)},e.prototype.copyTo2dOr3d=function(e){var t=this.mat3,r=e.mat3;return r[0]=t[0],r[1]=t[1],r[2]=t[2],r[3]=t[3],r[4]=t[4],r[5]=t[5],r[6]=t[6],r[7]=t[7],r[8]=t[8],e},e.prototype.copyTo=function(e,t,r){var i=this.mat3,n=1/i[8],o=i[6]*n,a=i[7]*n;if(e.a=(i[0]-i[2]*o)*n,e.b=(i[1]-i[2]*a)*n,e.c=(i[3]-i[5]*o)*n,e.d=(i[4]-i[5]*a)*n,e.tx=o,e.ty=a,2<=t){var s=e.a*e.d-e.b*e.c;r||(s=Math.abs(s)),t===l.POINT?(s=0>0,0!==f._cycle&&f._cycle===f._totalTime/a&&m<=e&&f._cycle--,f._time=f._totalTime-f._cycle*a,f._yoyo&&0!=(1&f._cycle)&&(f._time=v-f._time,(c=f._yoyoEase||f.vars.yoyoEase)&&(f._yoyoEase||(!0!==c||f._initted?f._yoyoEase=c=!0===c?f._ease:c instanceof Ease?c:Ease.map[c]:(c=f.vars.ease,f._yoyoEase=c=c?c instanceof Ease?c:"function"==typeof c?new Ease(c,f.vars.easeParams):Ease.map[c]||y.defaultEase:y.defaultEase)),f.ratio=c?1-c.getRatio((v-f._time)/v):0)),f._time>v?f._time=v:f._time<0&&(f._time=0)),f._easeType&&!c?(s=f._time/v,(1===(l=f._easeType)||3===l&&.5<=s)&&(s=1-s),3===l&&(s*=2),1===(u=f._easePower)?s*=s:2===u?s*=s*s:3===u?s*=s*s*s:4===u&&(s*=s*s*s*s),f.ratio=1===l?1-s:2===l?s:f._time/v<.5?s/2:1-s/2):c||(f.ratio=f._ease.getRatio(f._time/v))),d!==f._time||r||g!==f._cycle){if(!f._initted){if(f._init(),!f._initted||f._gc)return;if(!r&&f._firstPT&&(!1!==f.vars.lazy&&f._duration||f.vars.lazy&&!f._duration))return f._time=d,f._totalTime=m,f._rawPrevTime=_,f._cycle=g,x.lazyTweens.push(f),void(f._lazy=[e,t]);!f._time||i||c?i&&this._ease._calcEnd&&!c&&(f.ratio=f._ease.getRatio(0===f._time?0:1)):f.ratio=f._ease.getRatio(f._time/v)}for(!1!==f._lazy&&(f._lazy=!1),f._active||!f._paused&&f._time!==d&&0<=e&&(f._active=!0),0===m&&(2===f._initted&&0e._startTime;l._timeline;)u&&l._timeline.smoothChildTiming?l.totalTime(l._totalTime,!0):l._gc&&l._enabled(!0,!1),l=l._timeline;return h},r.remove=function(e){if(e instanceof c){this._remove(e,!1);var t=e._timeline=e.vars.useFrames?c._rootFramesTimeline:c._rootTimeline;return e._startTime=(e._paused?e._pauseTime:t._time)-(e._reversed?e.totalDuration()-e._totalTime:e._totalTime)/e._timeScale,this}if(e instanceof Array||e&&e.push&&p(e)){for(var r=e.length;-1<--r;)this.remove(e[r]);return this}return"string"==typeof e?this.removeLabel(e):this.kill(null,e)},r._remove=function(e,t){return f.prototype._remove.call(this,e,t),this._last?this._time>this.duration()&&(this._time=this._duration,this._totalTime=this._totalDuration):this._time=this._totalTime=this._duration=this._totalDuration=0,this},r.append=function(e,t){return this.add(e,this._parseTimeOrLabel(null,t,!0,e))},r.insert=r.insertMultiple=function(e,t,r,i){return this.add(e,t||0,r,i)},r.appendMultiple=function(e,t,r,i){return this.add(e,this._parseTimeOrLabel(null,t,!0,e),r,i)},r.addLabel=function(e,t){return this._labels[e]=this._parseTimeOrLabel(t),this},r.addPause=function(e,t,r,i){var n=d.delayedCall(0,o,r,i||this);return n.vars.onComplete=n.vars.onReverseComplete=t,n.data="isPause",this._hasPause=!0,this.add(n,e)},r.removeLabel=function(e){return delete this._labels[e],this},r.getLabelTime=function(e){return null!=this._labels[e]?this._labels[e]:-1},r._parseTimeOrLabel=function(e,t,r,i){var n,o;if(i instanceof c&&i.timeline===this)this.remove(i);else if(i&&(i instanceof Array||i.push&&p(i)))for(o=i.length;-1<--o;)i[o]instanceof c&&i[o].timeline===this&&this.remove(i[o]);if(n="number"!=typeof e||t?99999999999=e&&!l;)i._duration||"isPause"===i.data&&0c._time;)l.render(l._reversed?l.totalDuration()-(e-l._startTime)*l._timeScale:(e-l._startTime)*l._timeScale,t,r),l=l._prev;l=null,c.pause(),c._pauseTime=h}i._reversed?i.render((i._dirty?i.totalDuration():i._totalDuration)-(e-i._startTime)*i._timeScale,t,r):i.render((e-i._startTime)*i._timeScale,t,r)}i=o}c._onUpdate&&(t||(v.length&&_(),c._callback("onUpdate"))),a&&(c._gc||d!==c._startTime&&m===c._timeScale||(0===c._time||p>=c.totalDuration())&&(n&&(v.length&&_(),c._timeline.autoRemoveChildren&&c._enabled(!1,!1),c._active=!1),!t&&c.vars[a]&&c._callback(a)))}},r._hasPausedChild=function(){for(var e=this._first;e;){if(e._paused||e instanceof m&&e._hasPausedChild())return!0;e=e._next}return!1},r.getChildren=function(e,t,r,i){i=i||-9999999999;for(var n=[],o=this._first,a=0;o;)o._startTime=r&&(n._startTime+=e),n=n._next;if(t)for(i in o)o[i]>=r&&(o[i]+=e);return this._uncache(!0)},r._kill=function(e,t){if(!e&&!t)return this._enabled(!1,!1);for(var r=t?this.getTweensOf(t):this.getChildren(!0,!0,!1),i=r.length,n=!1;-1<--i;)r[i]._kill(e,t)&&(n=!0);return n},r.clear=function(e){var t=this.getChildren(!1,!0,!0),r=t.length;for(this._time=this._totalTime=0;-1<--r;)t[r]._enabled(!1,!1);return!1!==e&&(this._labels={}),this._uncache(!0)},r.invalidate=function(){for(var e=this._first;e;)e.invalidate(),e=e._next;return c.prototype.invalidate.call(this)},r._enabled=function(e,t){if(e===this._gc)for(var r=this._first;r;)r._enabled(e,!0),r=r._next;return f.prototype._enabled.call(this,e,t)},r.totalTime=function(e,t,r){this._forcingPlayhead=!0;var i=c.prototype.totalTime.apply(this,arguments);return this._forcingPlayhead=!1,i},r.duration=function(e){return arguments.length?(0!==this.duration()&&0!==e&&this.timeScale(this._duration/e),this):(this._dirty&&this.totalDuration(),this._duration)},r.totalDuration=function(e){if(arguments.length)return e&&this.totalDuration()?this.timeScale(this._totalDuration/e):this;if(this._dirty){for(var t,r,i=0,n=this,o=n._last,a=999999999999;o;)t=o._prev,o._dirty&&o.totalDuration(),o._startTime>a&&n._sortChildren&&!o._paused&&!n._calculatingDuration?(n._calculatingDuration=1,n.add(o,o._startTime-o._delay),n._calculatingDuration=0):a=o._startTime,o._startTime<0&&!o._paused&&(i-=o._startTime,n._timeline.smoothChildTiming&&(n._startTime+=o._startTime/n._timeScale,n._time-=o._startTime,n._totalTime-=o._startTime,n._rawPrevTime-=o._startTime),n.shiftChildren(-o._startTime,!1,-9999999999),a=0),i<(r=o._startTime+o._totalDuration/o._timeScale)&&(i=r),o=t;n._duration=n._totalDuration=i,n._dirty=!1}return this._totalDuration},r.paused=function(e){if(!1===e&&this._paused)for(var t=this._first;t;)t._startTime===this._time&&"isPause"===t.data&&(t._rawPrevTime=0),t=t._next;return c.prototype.paused.apply(this,arguments)},r.usesFrames=function(){for(var e=this._timeline;e._timeline;)e=e._timeline;return e===c._rootFramesTimeline},r.rawTime=function(e){return e&&(this._paused||this._repeat&&0>0,f._cycle&&f._cycle===f._totalTime/l&&g<=e&&f._cycle--,f._time=f._totalTime-f._cycle*l,f._yoyo&&1&f._cycle&&(f._time=m-f._time),f._time>m?e=(f._time=m)+1e-4:f._time<0?f._time=e=0:e=f._time));if(f._hasPause&&!f._forcingPlayhead&&!t){if(p<(e=f._time)||f._repeat&&x!==f._cycle)for(i=f._first;i&&i._startTime<=e&&!u;)i._duration||"isPause"!==i.data||i.ratio||0===i._startTime&&0===f._rawPrevTime||(u=i),i=i._next;else for(i=f._last;i&&i._startTime>=e&&!u;)i._duration||"isPause"===i.data&&0f._time;)u.render(u._reversed?u.totalDuration()-(e-u._startTime)*u._timeScale:(e-u._startTime)*u._timeScale,t,r),u=u._prev;u=null,f.pause(),f._pauseTime=c}i._reversed?i.render((i._dirty?i.totalDuration():i._totalDuration)-(e-i._startTime)*i._timeScale,t,r):i.render((e-i._startTime)*i._timeScale,t,r)}i=o}f._onUpdate&&(t||(C.length&&I(),f._callback("onUpdate"))),a&&(f._locked||f._gc||v!==f._startTime&&_===f._timeScale||(0===f._time||d>=f.totalDuration())&&(n&&(C.length&&I(),f._timeline.autoRemoveChildren&&f._enabled(!1,!1),f._active=!1),!t&&f.vars[a]&&f._callback(a)))}else g!==f._totalTime&&f._onUpdate&&(t||f._callback("onUpdate"))},n.getActive=function(e,t,r){var i,n,o=[],a=this.getChildren(e||null==e,t||null==e,!!r),s=0,l=a.length;for(i=0;ie)return r[t].name;return null},n.getLabelBefore=function(e){null==e&&(e=this._time);for(var t=this.getLabelsArray(),r=t.length;-1<--r;)if(t[r].time>0||6)-1,c=[],f=[];for(r in e)d(e[r],a,t);for(n=a.length,i=0;i>0]=f,s[o]=u,l=0,f=[]);return{length:u,lengths:s,segments:c}}(this._beziers,this._timeRes);this._length=f.length,this._lengths=f.lengths,this._segments=f.segments,this._l1=this._li=this._s1=this._si=0,this._l2=this._lengths[0],this._curSeg=this._segments[0],this._s2=this._curSeg[0],this._prec=1/this._curSeg.length}if(c=this._autoRotate)for(this._initialRotations=[],c[0]instanceof Array||(this._autoRotate=c=[c]),o=c.length;-1<--o;){for(a=0;a<3;a++)i=c[o][a],this._func[i]="function"==typeof e[i]&&e[i.indexOf("set")||"function"!=typeof e["get"+i.substr(3)]?i:"get"+i.substr(3)];i=c[o][2],this._initialRotations[o]=(this._func[i]?this._func[i].call(this._target):this._target[i])||0,this._overwriteProps.push(i)}return this._startRatio=r.vars.runBackwards?1:0,!0},set:function(e){var t,r,i,n,o,a,s,l,u,h,c,f=this._segCount,p=this._func,d=this._target,m=e!==this._startRatio;if(this._timeRes){if(u=this._lengths,h=this._curSeg,c=e*this._length,i=this._li,c>this._l2&&i=c;);0===i&&cthis._s2&&i=c;);0===i&&c>0)*(1/f))*f;for(r=1-a,i=this._props.length;-1<--i;)n=this._props[i],s=(a*a*(o=this._beziers[n][t]).da+3*r*(a*o.ca+r*o.ba))*a+o.a,this._mod[n]&&(s=this._mod[n](s,d)),p[n]?d[n](s):d[n]=s;if(this._autoRotate){var g,v,_,y,b,x,w,T=this._autoRotate;for(i=T.length;-1<--i;)n=T[i][2],x=T[i][3]||0,w=!0===T[i][4]?1:k,o=this._beziers[T[i][0]],g=this._beziers[T[i][1]],o&&g&&(o=o[t],g=g[t],v=o.a+(o.b-o.a)*a,v+=((y=o.b+(o.c-o.b)*a)-v)*a,y+=(o.c+(o.d-o.c)*a-y)*a,_=g.a+(g.b-g.a)*a,_+=((b=g.b+(g.c-g.b)*a)-_)*a,b+=(g.c+(g.d-g.c)*a-b)*a,s=m?Math.atan2(b-_,y-v)*w+x:this._initialRotations[i],this._mod[n]&&(s=this._mod[n](s,d)),p[n]?d[n](s):d[n]=s)}}}),e=g.prototype,g.bezierThrough=p,g.cubicToQuadratic=P,g._autoCSS=!0,g.quadraticToCubic=function(e,t,r){return new _(e,(2*t+e)/3,(2*t+r)/3,r)},g._cssRegister=function(){var e=r.CSSPlugin;if(e){var t=e._internals,p=t._parseToProxy,d=t._setPluginRatio,m=t.CSSPropTween;t._registerComplexSpecialProp("bezier",{parser:function(e,t,r,i,n,o){t instanceof Array&&(t={values:t}),o=new g;var a,s,l,u=t.values,h=u.length-1,c=[],f={};if(h<0)return n;for(a=0;a<=h;a++)l=p(e,u[a],i,n,o,h!==a),c[a]=l.end;for(s in t)f[s]=t[s];return f.values=c,(n=new m(e,"bezier",0,0,l.pt,2)).data=l,n.plugin=o,n.setRatio=d,0===f.autoRotate&&(f.autoRotate=!0),!f.autoRotate||f.autoRotate instanceof Array||(a=!0===f.autoRotate?0:Number(f.autoRotate),f.autoRotate=null!=l.end.left?[["left","top","rotation",a,!1]]:null!=l.end.x&&[["x","y","rotation",a,!1]]),f.autoRotate&&(i._transform||i._enableTransforms(!1),l.autoRotate=i._target._gsTransform,l.proxy.rotation=l.autoRotate.rotation||0,i._overwriteProps.push("rotation")),o._onInitTween(l.proxy,f,i._tween),n}})}},e._mod=function(e){for(var t,r=this._overwriteProps,i=r.length;-1<--i;)(t=e[r[i]])&&"function"==typeof t&&(this._mod[r[i]]=t)},e._kill=function(e){var t,r,i=this._props;for(t in this._beziers)if(t in e)for(delete this._beziers[t],delete this._func[t],r=i.length;-1<--r;)i[r]===t&&i.splice(r,1);if(i=this._autoRotate)for(r=i.length;-1<--r;)e[i[r][2]]&&i.splice(r,1);return this._super._kill.call(this,e)},_gsScope._gsDefine("plugins.CSSPlugin",["plugins.TweenPlugin","TweenLite"],function(o,B){var d,k,P,m,U=function(){o.call(this,"css"),this._overwriteProps.length=0,this.setRatio=U.prototype.setRatio},u=_gsScope._gsDefine.globals,g={},e=U.prototype=new o("css");(e.constructor=U).version="2.1.3",U.API=2,U.defaultTransformPerspective=0,U.defaultSkewType="compensated",U.defaultSmoothOrigin=!0,e="px",U.suffixMap={top:e,right:e,bottom:e,left:e,width:e,height:e,fontSize:e,padding:e,margin:e,perspective:e,lineHeight:""};var E,v,_,F,y,S,A,C,t,r,I=/(?:\-|\.|\b)(\d|\.|e\-)+/g,O=/(?:\d|\-\d|\.\d|\-\.\d|\+=\d|\-=\d|\+=.\d|\-=\.\d)+/g,b=/(?:\+=|\-=|\-|\b)[\d\-\.]+[a-zA-Z0-9]*(?:%|\b)/gi,n=/(?:\+=|\-=|\-|\b)[\d\-\.]+[a-zA-Z0-9]*(?:%|\b),?/gi,h=/(?![+-]?\d*\.?\d+|[+-]|e[+-]\d+)[^0-9]/g,M=/(?:\d|\-|\+|=|#|\.)*/g,D=/opacity *= *([^)]*)/i,x=/opacity:([^;]*)/i,a=/alpha\(opacity *=.+?\)/i,w=/^(rgb|hsl)/,s=/([A-Z])/g,l=/-([a-z])/gi,T=/(^(?:url\(\"|url\())|(?:(\"\))$|\)$)/gi,c=function(e,t){return t.toUpperCase()},p=/(?:Left|Right|Width)/i,f=/(M11|M12|M21|M22)=[\d\-\.e]+/gi,R=/progid\:DXImageTransform\.Microsoft\.Matrix\(.+?\)/i,z=/,(?=[^\)]*(?:\(|$))/gi,L=/[\s,\(]/i,j=Math.PI/180,X=180/Math.PI,N={},i={style:{}},H=_gsScope.document||{createElement:function(){return i}},G=function(e,t){var r=H.createElementNS?H.createElementNS(t||"http://www.w3.org/1999/xhtml",e):H.createElement(e);return r.style?r:H.createElement(e)},W=G("div"),q=G("img"),V=U._internals={_specialProps:g},Y=(_gsScope.navigator||{}).userAgent||"",Z=(t=Y.indexOf("Android"),r=G("a"),_=-1!==Y.indexOf("Safari")&&-1===Y.indexOf("Chrome")&&(-1===t||3>16,e>>8&255,255&e];else{if(","===e.charAt(e.length-1)&&(e=e.substr(0,e.length-1)),me[e])r=me[e];else if("#"===e.charAt(0))4===e.length&&(e="#"+(i=e.charAt(1))+i+(n=e.charAt(2))+n+(o=e.charAt(3))+o),r=[(e=parseInt(e.substr(1),16))>>16,e>>8&255,255&e];else if("hsl"===e.substr(0,3))if(r=f=e.match(I),t){if(-1!==e.indexOf("="))return e.match(O)}else a=Number(r[0])%360/360,s=Number(r[1])/100,i=2*(l=Number(r[2])/100)-(n=l<=.5?l*(s+1):l+s-l*s),3i--)for(;++ii--)for(;++i>0];return i.parse(e,a,n,o)}},we=(V._setPluginRatio=function(e){this.plugin.setRatio(e);for(var t,r,i,n,o,a=this.data,s=a.proxy,l=a.firstMPT;l;)t=s[l.v],l.r?t=l.r(t):t<1e-6&&-1e-6s.length?l.length:s.length,a=0;ao.pr;)a=a._next;(o._prev=a?a._prev:l)?o._prev._next=o:s=o,(o._next=a)?a._prev=o:l=o,o=u}this._firstPT=s}return!0},e.parse=function(e,t,r,i){var n,o,a,s,l,u,h,c,f,p,d=e.style;for(n in t){if(u=t[n],o=g[n],"function"!=typeof u||o&&o.allowFunc||(u=u(C,A)),o)r=o.parse(e,u,n,this,r,i,t);else{if("--"===n.substr(0,2)){this._tween._propLookup[n]=this._addTween.call(this._tween,e.style,"setProperty",re(e).getPropertyValue(n)+"",u+"",n,!1,n);continue}l=ie(e,n,P)+"",f="string"==typeof u,"color"===n||"fill"===n||"stroke"===n||-1!==n.indexOf("Color")||f&&w.test(u)?(f||(u=(3<(u=ve(u)).length?"rgba(":"rgb(")+u.join(",")+")"),r=Pe(d,n,l,u,!0,"transparent",r,0,i)):f&&L.test(u)?r=Pe(d,n,l,u,!0,null,r,0,i):(h=(a=parseFloat(l))||0===a?l.substr((a+"").length):"",""!==l&&"auto"!==l||(h="width"===n||"height"===n?(a=he(e,n,P),"px"):"left"===n||"top"===n?(a=oe(e,n,P),"px"):(a="opacity"!==n?0:1,"")),""===(c=(p=f&&"="===u.charAt(1))?(s=parseInt(u.charAt(0)+"1",10),u=u.substr(2),s*=parseFloat(u),u.replace(M,"")):(s=parseFloat(u),f?u.replace(M,""):""))&&(c=n in k?k[n]:h),u=s||0===s?(p?s+a:s)+c:t[n],h!==c&&(""===c&&"lineHeight"!==n||(s||0===s)&&a&&(a=ne(e,n,a,h),"%"===c?(a/=ne(e,n,100,"%")/100,!0!==t.strictUnits&&(l=a+"%")):"em"===c||"rem"===c||"vw"===c||"vh"===c?a/=ne(e,n,1,c):"px"!==c&&(s=ne(e,n,s,c),c="px"),p&&(s||0===s)&&(u=s+a+c))),p&&(s+=a),!a&&0!==a||!s&&0!==s?void 0!==d[n]&&(u||u+""!="NaN"&&null!=u)?(r=new Te(d,n,s||a||0,0,r,-1,n,!1,0,l,u)).xs0="none"!==u||"display"!==n&&-1===n.indexOf("Style")?u:l:K("invalid "+n+" tween value: "+t[n]):(r=new Te(d,n,a,s-a,r,0,n,!1!==E&&("px"===c||"zIndex"===n),0,l,u)).xs0=c)}i&&r&&!r.plugin&&(r.plugin=i)}return r},e.setRatio=function(e){var t,r,i,n=this._firstPT;if(1!==e||this._tween._time!==this._tween._duration&&0!==this._tween._time)if(e||this._tween._time!==this._tween._duration&&0!==this._tween._time||-1e-6===this._tween._rawPrevTime)for(;n;){if(t=n.c*e+n.s,n.r?t=n.r(t):t<1e-6&&-1e-6this._p3?this._calcEnd?1===e?0:1-(e=(e-this._p3)/this._p1)*e:t+(e-t)*(e=(e-this._p3)/this._p1)*e*e*e:this._calcEnd?1:t},d.ease=new d(.7,.7),m.config=d.config=function(e,t,r){return new d(e,t,r)},(m=(r=l("easing.SteppedEase",function(e,t){e=e||1,this._p1=1/e,this._p2=e+(t?0:1),this._p3=t?1:0},!0)).prototype=new g).constructor=r,m.getRatio=function(e){return e<0?e=0:1<=e&&(e=.999999999),((this._p2*e|0)+this._p3)*this._p1},m.config=r.config=function(e,t){return new r(e,t)},(m=(i=l("easing.ExpoScaleEase",function(e,t,r){this._p1=Math.log(t/e),this._p2=t-e,this._p3=e,this._ease=r},!0)).prototype=new g).constructor=i,m.getRatio=function(e){return this._ease&&(e=this._ease.getRatio(e)),(this._p3*Math.exp(this._p1*e)-this._p3)/this._p2},m.config=i.config=function(e,t,r){return new i(e,t,r)},(m=(t=l("easing.RoughEase",function(e){for(var t,r,i,n,o,a,s=(e=e||{}).taper||"none",l=[],u=0,h=0|(e.points||20),c=h,f=!1!==e.randomize,p=!0===e.clamp,d=e.template instanceof g?e.template:null,m="number"==typeof e.strength?.4*e.strength:.4;-1<--c;)t=f?Math.random():1/h*c,r=d?d.getRatio(t):t,i="none"===s?m:"out"===s?(n=1-t)*n*m:"in"===s?t*t*m:t<.5?(n=2*t)*n*.5*m:(n=2*(1-t))*n*.5*m,f?r+=Math.random()*i-.5*i:c%2?r+=.5*i:r-=.5*i,p&&(1t.t){for(;t.next&&e>=t.t;)t=t.next;t=t.prev}else for(;t.prev&&e<=t.t;)t=t.prev;return(this._prev=t).v+(e-t.t)/t.gap*t.c},m.config=function(e){return new t(e)},t.ease=new t,c("Bounce",u("BounceOut",function(e){return e<1/2.75?7.5625*e*e:e<2/2.75?7.5625*(e-=1.5/2.75)*e+.75:e<2.5/2.75?7.5625*(e-=2.25/2.75)*e+.9375:7.5625*(e-=2.625/2.75)*e+.984375}),u("BounceIn",function(e){return(e=1-e)<1/2.75?1-7.5625*e*e:e<2/2.75?1-(7.5625*(e-=1.5/2.75)*e+.75):e<2.5/2.75?1-(7.5625*(e-=2.25/2.75)*e+.9375):1-(7.5625*(e-=2.625/2.75)*e+.984375)}),u("BounceInOut",function(e){var t=e<.5;return(e=t?1-2*e:2*e-1)<1/2.75?e*=7.5625*e:e=e<2/2.75?7.5625*(e-=1.5/2.75)*e+.75:e<2.5/2.75?7.5625*(e-=2.25/2.75)*e+.9375:7.5625*(e-=2.625/2.75)*e+.984375,t?.5*(1-e):.5*e+.5})),c("Circ",u("CircOut",function(e){return Math.sqrt(1-(e-=1)*e)}),u("CircIn",function(e){return-(Math.sqrt(1-e*e)-1)}),u("CircInOut",function(e){return(e*=2)<1?-.5*(Math.sqrt(1-e*e)-1):.5*(Math.sqrt(1-(e-=2)*e)+1)})),c("Elastic",(e=function(e,t,r){var i=l("easing."+e,function(e,t){this._p1=1<=e?e:1,this._p2=(t||r)/(e<1?e:1),this._p3=this._p2/a*(Math.asin(1/this._p1)||0),this._p2=a/this._p2},!0),n=i.prototype=new g;return n.constructor=i,n.getRatio=t,n.config=function(e,t){return new i(e,t)},i})("ElasticOut",function(e){return this._p1*Math.pow(2,-10*e)*Math.sin((e-this._p3)*this._p2)+1},.3),e("ElasticIn",function(e){return-this._p1*Math.pow(2,10*(e-=1))*Math.sin((e-this._p3)*this._p2)},.3),e("ElasticInOut",function(e){return(e*=2)<1?this._p1*Math.pow(2,10*(e-=1))*Math.sin((e-this._p3)*this._p2)*-.5:this._p1*Math.pow(2,-10*(e-=1))*Math.sin((e-this._p3)*this._p2)*.5+1},.45)),c("Expo",u("ExpoOut",function(e){return 1-Math.pow(2,-10*e)}),u("ExpoIn",function(e){return Math.pow(2,10*(e-1))-.001}),u("ExpoInOut",function(e){return(e*=2)<1?.5*Math.pow(2,10*(e-1)):.5*(2-Math.pow(2,-10*(e-1)))})),c("Sine",u("SineOut",function(e){return Math.sin(e*s)}),u("SineIn",function(e){return 1-Math.cos(e*s)}),u("SineInOut",function(e){return-.5*(Math.cos(Math.PI*e)-1)})),l("easing.EaseLookup",{find:function(e){return g.map[e]}},!0),h(n.SlowMo,"SlowMo","ease,"),h(t,"RoughEase","ease,"),h(r,"SteppedEase","ease,"),p},!0)}),_gsScope._gsDefine&&_gsScope._gsQueue.pop()(),function(f,p){"use strict";var d={},i=f.document,m=f.GreenSockGlobals=f.GreenSockGlobals||f,e=m[p];if(e)return"undefined"!=typeof module&&module.exports&&(module.exports=e);var t,r,n,g,v,o,a,_=function(e){var t,r=e.split("."),i=m;for(t=0;t=r&&ethis._duration?this._duration:e,t)):this._time},n.totalTime=function(e,t,r){if(v||g.wake(),!arguments.length)return this._totalTime;if(this._timeline){if(e<0&&!r&&(e+=this.totalDuration()),this._timeline.smoothChildTiming){this._dirty&&this.totalDuration();var i=this._totalDuration,n=this._timeline;if(io;)n=n._prev;return n?(e._next=n._next,n._next=e):(e._next=this._first,this._first=e),e._next?e._next._prev=e:this._last=e,e._prev=n,this._recent=e,this._timeline&&this._uncache(!0),this},n._remove=function(e,t){return e.timeline===this&&(t||e._enabled(!1,!0),e._prev?e._prev._next=e._next:this._first===e&&(this._first=e._next),e._next?e._next._prev=e._prev:this._last===e&&(this._last=e._prev),e._next=e._prev=e.timeline=null,e===this._recent&&(this._recent=this._last),this._timeline&&this._uncache(!0)),this},n.render=function(e,t,r){var i,n=this._first;for(this._totalTime=this._time=this._rawPrevTime=e;n;)i=n._next,(n._active||e>=n._startTime&&!n._paused&&!n._gc)&&(n._reversed?n.render((n._dirty?n.totalDuration():n._totalDuration)-(e-n._startTime)*n._timeScale,t,r):n.render((e-n._startTime)*n._timeScale,t,r)),n=i},n.rawTime=function(){return v||g.wake(),this._totalTime};var z=k("TweenLite",function(e,t,r){if(M.call(this,t,r),this.render=z.prototype.render,null==e)throw"Cannot tween a null target.";this.target=e="string"!=typeof e?e:z.selector(e)||e;var i,n,o,a=e.jquery||e.length&&e!==f&&e[0]&&(e[0]===f||e[0].nodeType&&e[0].style&&!e.nodeType),s=this.vars.overwrite;if(this._overwrite=s=null==s?J[z.defaultOverwrite]:"number"==typeof s?s>>0:J[s],(a||e instanceof Array||e.push&&x(e))&&"number"!=typeof e[0])for(this._targets=o=l(e),this._propLookup=[],this._siblings=[],i=0;i=$){for(r in $=g.frame+(parseInt(z.autoSleep,10)||120),V){for(e=(t=V[r].tweens).length;-1<--e;)t[e]._gc&&t.splice(e,1);0===t.length&&delete V[r]}if((!(r=Q._first)||r._paused)&&z.autoSleep&&!K._first&&1===g._listeners.tick.length){for(;r&&r._paused;)r=r._next;r||g.sleep()}}},g.addEventListener("tick",M._updateRoot);var te=function(e,t,r){var i,n,o=e._gsTweenID;if(V[o||(e._gsTweenID=o="t"+Y++)]||(V[o]={target:e,tweens:[]}),t&&((i=V[o].tweens)[n=i.length]=t,r))for(;-1<--n;)i[n]===t&&i.splice(n,1);return V[o].tweens},re=function(e,t,r,i){var n,o,a=e.vars.onOverwrite;return a&&(n=a(e,t,r,i)),(a=z.onOverwrite)&&(o=a(e,t,r,i)),!1!==n&&!1!==o},ie=function(e,t,r,i,n){var o,a,s,l;if(1===i||4<=i){for(l=n.length,o=0;oh&&((p||!s._initted)&&h-s._startTime<=2e-8||(c[f++]=s)));for(o=f;-1<--o;)if(l=(s=c[o])._firstPT,2===i&&s._kill(r,e,t)&&(a=!0),2!==i||!s._firstPT&&s._initted&&l){if(2!==i&&!re(s,t))continue;s._enabled(!1,!1)&&(a=!0)}return a},ne=function(e,t,r){for(var i=e._timeline,n=i._timeScale,o=e._startTime;i._timeline;){if(o+=i._startTime,n*=i._timeScale,i._paused)return-100;i=i._timeline}return t<(o/=n)?o-t:r&&o===t||!e._initted&&o-t<2e-8?y:(o+=e.totalDuration()/e._timeScale/n)>t+y?0:o-t-y};n._init=function(){var e,t,r,i,n,o,a=this.vars,s=this._overwrittenProps,l=this._duration,u=!!a.immediateRender,h=a.ease,c=this._startAt;if(a.startAt){for(i in c&&(c.render(-1,!0),c.kill()),n={},a.startAt)n[i]=a.startAt[i];if(n.data="isStart",n.overwrite=!1,n.immediateRender=!0,n.lazy=u&&!1!==a.lazy,n.startAt=n.delay=null,n.onUpdate=a.onUpdate,n.onUpdateParams=a.onUpdateParams,n.onUpdateScope=a.onUpdateScope||a.callbackScope||this,this._startAt=z.to(this.target||{},0,n),u)if(0s.pr;)i=i._next;(s._prev=i?i._prev:o)?s._prev._next=s:n=s,(s._next=i)?i._prev=s:o=s,s=a}s=t._firstPT=n}for(;s;)s.pg&&"function"==typeof s.t[e]&&s.t[e]()&&(r=!0),s=s._next;return r},oe.activate=function(e){for(var t=e.length;-1<--t;)e[t].API===oe.API&&(q[(new e[t])._propName]=e[t]);return!0},s.plugin=function(e){if(!(e&&e.propName&&e.init&&e.API))throw"illegal plugin definition.";var t,r=e.propName,i=e.priority||0,n=e.overwriteProps,o={init:"_onInitTween",set:"setRatio",kill:"_kill",round:"_mod",mod:"_mod",initAll:"_onInitAllProps"},a=k("plugins."+r.charAt(0).toUpperCase()+r.substr(1)+"Plugin",function(){oe.call(this,r,i),this._overwriteProps=n||[]},!0===e.global),s=a.prototype=new oe(r);for(t in(s.constructor=a).API=e.API,o)"function"==typeof e[t]&&(s[o[t]]=e[t]);return a.version=e.version,oe.activate([a]),a},t=f._gsQueue){for(r=0;r>0,f._cycle&&f._cycle===f._totalTime/l&&g<=e&&f._cycle--,f._time=f._totalTime-f._cycle*l,f._yoyo&&1&f._cycle&&(f._time=m-f._time),f._time>m?e=(f._time=m)+1e-4:f._time<0?f._time=e=0:e=f._time));if(f._hasPause&&!f._forcingPlayhead&&!t){if(p<(e=f._time)||f._repeat&&x!==f._cycle)for(i=f._first;i&&i._startTime<=e&&!u;)i._duration||"isPause"!==i.data||i.ratio||0===i._startTime&&0===f._rawPrevTime||(u=i),i=i._next;else for(i=f._last;i&&i._startTime>=e&&!u;)i._duration||"isPause"===i.data&&0f._time;)u.render(u._reversed?u.totalDuration()-(e-u._startTime)*u._timeScale:(e-u._startTime)*u._timeScale,t,r),u=u._prev;u=null,f.pause(),f._pauseTime=c}i._reversed?i.render((i._dirty?i.totalDuration():i._totalDuration)-(e-i._startTime)*i._timeScale,t,r):i.render((e-i._startTime)*i._timeScale,t,r)}i=o}f._onUpdate&&(t||(C.length&&I(),f._callback("onUpdate"))),a&&(f._locked||f._gc||v!==f._startTime&&_===f._timeScale||(0===f._time||d>=f.totalDuration())&&(n&&(C.length&&I(),f._timeline.autoRemoveChildren&&f._enabled(!1,!1),f._active=!1),!t&&f.vars[a]&&f._callback(a)))}else g!==f._totalTime&&f._onUpdate&&(t||f._callback("onUpdate"))},n.getActive=function(e,t,r){var i,n,o=[],a=this.getChildren(e||null==e,t||null==e,!!r),s=0,l=a.length;for(i=0;ie)return r[t].name;return null},n.getLabelBefore=function(e){null==e&&(e=this._time);for(var t=this.getLabelsArray(),r=t.length;-1<--r;)if(t[r].timee._startTime;l._timeline;)u&&l._timeline.smoothChildTiming?l.totalTime(l._totalTime,!0):l._gc&&l._enabled(!0,!1),l=l._timeline;return h},r.remove=function(e){if(e instanceof c){this._remove(e,!1);var t=e._timeline=e.vars.useFrames?c._rootFramesTimeline:c._rootTimeline;return e._startTime=(e._paused?e._pauseTime:t._time)-(e._reversed?e.totalDuration()-e._totalTime:e._totalTime)/e._timeScale,this}if(e instanceof Array||e&&e.push&&p(e)){for(var r=e.length;-1<--r;)this.remove(e[r]);return this}return"string"==typeof e?this.removeLabel(e):this.kill(null,e)},r._remove=function(e,t){return f.prototype._remove.call(this,e,t),this._last?this._time>this.duration()&&(this._time=this._duration,this._totalTime=this._totalDuration):this._time=this._totalTime=this._duration=this._totalDuration=0,this},r.append=function(e,t){return this.add(e,this._parseTimeOrLabel(null,t,!0,e))},r.insert=r.insertMultiple=function(e,t,r,i){return this.add(e,t||0,r,i)},r.appendMultiple=function(e,t,r,i){return this.add(e,this._parseTimeOrLabel(null,t,!0,e),r,i)},r.addLabel=function(e,t){return this._labels[e]=this._parseTimeOrLabel(t),this},r.addPause=function(e,t,r,i){var n=d.delayedCall(0,o,r,i||this);return n.vars.onComplete=n.vars.onReverseComplete=t,n.data="isPause",this._hasPause=!0,this.add(n,e)},r.removeLabel=function(e){return delete this._labels[e],this},r.getLabelTime=function(e){return null!=this._labels[e]?this._labels[e]:-1},r._parseTimeOrLabel=function(e,t,r,i){var n,o;if(i instanceof c&&i.timeline===this)this.remove(i);else if(i&&(i instanceof Array||i.push&&p(i)))for(o=i.length;-1<--o;)i[o]instanceof c&&i[o].timeline===this&&this.remove(i[o]);if(n="number"!=typeof e||t?99999999999=e&&!l;)i._duration||"isPause"===i.data&&0c._time;)l.render(l._reversed?l.totalDuration()-(e-l._startTime)*l._timeScale:(e-l._startTime)*l._timeScale,t,r),l=l._prev;l=null,c.pause(),c._pauseTime=h}i._reversed?i.render((i._dirty?i.totalDuration():i._totalDuration)-(e-i._startTime)*i._timeScale,t,r):i.render((e-i._startTime)*i._timeScale,t,r)}i=o}c._onUpdate&&(t||(v.length&&_(),c._callback("onUpdate"))),a&&(c._gc||d!==c._startTime&&m===c._timeScale||(0===c._time||p>=c.totalDuration())&&(n&&(v.length&&_(),c._timeline.autoRemoveChildren&&c._enabled(!1,!1),c._active=!1),!t&&c.vars[a]&&c._callback(a)))}},r._hasPausedChild=function(){for(var e=this._first;e;){if(e._paused||e instanceof m&&e._hasPausedChild())return!0;e=e._next}return!1},r.getChildren=function(e,t,r,i){i=i||-9999999999;for(var n=[],o=this._first,a=0;o;)o._startTime=r&&(n._startTime+=e),n=n._next;if(t)for(i in o)o[i]>=r&&(o[i]+=e);return this._uncache(!0)},r._kill=function(e,t){if(!e&&!t)return this._enabled(!1,!1);for(var r=t?this.getTweensOf(t):this.getChildren(!0,!0,!1),i=r.length,n=!1;-1<--i;)r[i]._kill(e,t)&&(n=!0);return n},r.clear=function(e){var t=this.getChildren(!1,!0,!0),r=t.length;for(this._time=this._totalTime=0;-1<--r;)t[r]._enabled(!1,!1);return!1!==e&&(this._labels={}),this._uncache(!0)},r.invalidate=function(){for(var e=this._first;e;)e.invalidate(),e=e._next;return c.prototype.invalidate.call(this)},r._enabled=function(e,t){if(e===this._gc)for(var r=this._first;r;)r._enabled(e,!0),r=r._next;return f.prototype._enabled.call(this,e,t)},r.totalTime=function(e,t,r){this._forcingPlayhead=!0;var i=c.prototype.totalTime.apply(this,arguments);return this._forcingPlayhead=!1,i},r.duration=function(e){return arguments.length?(0!==this.duration()&&0!==e&&this.timeScale(this._duration/e),this):(this._dirty&&this.totalDuration(),this._duration)},r.totalDuration=function(e){if(arguments.length)return e&&this.totalDuration()?this.timeScale(this._totalDuration/e):this;if(this._dirty){for(var t,r,i=0,n=this,o=n._last,a=999999999999;o;)t=o._prev,o._dirty&&o.totalDuration(),o._startTime>a&&n._sortChildren&&!o._paused&&!n._calculatingDuration?(n._calculatingDuration=1,n.add(o,o._startTime-o._delay),n._calculatingDuration=0):a=o._startTime,o._startTime<0&&!o._paused&&(i-=o._startTime,n._timeline.smoothChildTiming&&(n._startTime+=o._startTime/n._timeScale,n._time-=o._startTime,n._totalTime-=o._startTime,n._rawPrevTime-=o._startTime),n.shiftChildren(-o._startTime,!1,-9999999999),a=0),i<(r=o._startTime+o._totalDuration/o._timeScale)&&(i=r),o=t;n._duration=n._totalDuration=i,n._dirty=!1}return this._totalDuration},r.paused=function(e){if(!1===e&&this._paused)for(var t=this._first;t;)t._startTime===this._time&&"isPause"===t.data&&(t._rawPrevTime=0),t=t._next;return c.prototype.paused.apply(this,arguments)},r.usesFrames=function(){for(var e=this._timeline;e._timeline;)e=e._timeline;return e===c._rootFramesTimeline},r.rawTime=function(e){return e&&(this._paused||this._repeat&&0+~]|"+L+")"+L+"*"),G=new RegExp("="+L+"*([^\\]'\"]*?)"+L+"*\\]","g"),W=new RegExp(N),q=new RegExp("^"+F+"$"),V={ID:new RegExp("^#("+F+")"),CLASS:new RegExp("^\\.("+F+")"),TAG:new RegExp("^("+F+"|[*])"),ATTR:new RegExp("^"+j),PSEUDO:new RegExp("^"+N),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+L+"*(even|odd|(([+-]|)(\\d*)n|)"+L+"*(?:([+-]|)"+L+"*(\\d+)|))"+L+"*\\)|)","i"),bool:new RegExp("^(?:"+z+")$","i"),needsContext:new RegExp("^"+L+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+L+"*((?:-\\d)?\\d*)"+L+"*\\)|)(?=[^-]|$)","i")},Y=/^(?:input|select|textarea|button)$/i,Z=/^h\d$/i,J=/^[^{]+\{\s*\[native \w/,K=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,Q=/[+~]/,$=new RegExp("\\\\([\\da-f]{1,6}"+L+"?|("+L+")|.)","ig"),ee=function(e,t,r){var i="0x"+t-65536;return i!=i||r?t:i<0?String.fromCharCode(65536+i):String.fromCharCode(i>>10|55296,1023&i|56320)},te=/([\0-\x1f\x7f]|^-?\d)|^-$|[^\0-\x1f\x7f-\uFFFF\w-]/g,re=function(e,t){return t?"\0"===e?"�":e.slice(0,-1)+"\\"+e.charCodeAt(e.length-1).toString(16)+" ":"\\"+e},ie=function(){w()},ne=_e(function(e){return!0===e.disabled&&("form"in e||"label"in e)},{dir:"parentNode",next:"legend"});try{M.apply(t=D.call(_.childNodes),_.childNodes),t[_.childNodes.length].nodeType}catch(e){M={apply:t.length?function(e,t){O.apply(e,D.call(t))}:function(e,t){for(var r=e.length,i=0;e[r++]=t[i++];);e.length=r-1}}}function oe(e,t,r,i){var n,o,a,s,l,u,h,c=t&&t.ownerDocument,f=t?t.nodeType:9;if(r=r||[],"string"!=typeof e||!e||1!==f&&9!==f&&11!==f)return r;if(!i&&((t?t.ownerDocument||t:_)!==T&&w(t),t=t||T,k)){if(11!==f&&(l=K.exec(e)))if(n=l[1]){if(9===f){if(!(a=t.getElementById(n)))return r;if(a.id===n)return r.push(a),r}else if(c&&(a=c.getElementById(n))&&v(t,a)&&a.id===n)return r.push(a),r}else{if(l[2])return M.apply(r,t.getElementsByTagName(e)),r;if((n=l[3])&&p.getElementsByClassName&&t.getElementsByClassName)return M.apply(r,t.getElementsByClassName(n)),r}if(p.qsa&&!E[e+" "]&&(!g||!g.test(e))){if(1!==f)c=t,h=e;else if("object"!==t.nodeName.toLowerCase()){for((s=t.getAttribute("id"))?s=s.replace(te,re):t.setAttribute("id",s=P),o=(u=d(e)).length;o--;)u[o]="#"+s+" "+ve(u[o]);h=u.join(","),c=Q.test(e)&&me(t.parentNode)||t}if(h)try{return M.apply(r,c.querySelectorAll(h)),r}catch(e){}finally{s===P&&t.removeAttribute("id")}}}return m(e.replace(U,"$1"),t,r,i)}function ae(){var i=[];return function e(t,r){return i.push(t+" ")>b.cacheLength&&delete e[i.shift()],e[t+" "]=r}}function se(e){return e[P]=!0,e}function le(e){var t=T.createElement("fieldset");try{return!!e(t)}catch(e){return!1}finally{t.parentNode&&t.parentNode.removeChild(t),t=null}}function ue(e,t){for(var r=e.split("|"),i=r.length;i--;)b.attrHandle[r[i]]=t}function he(e,t){var r=t&&e,i=r&&1===e.nodeType&&1===t.nodeType&&e.sourceIndex-t.sourceIndex;if(i)return i;if(r)for(;r=r.nextSibling;)if(r===t)return-1;return e?1:-1}function ce(t){return function(e){return"input"===e.nodeName.toLowerCase()&&e.type===t}}function fe(r){return function(e){var t=e.nodeName.toLowerCase();return("input"===t||"button"===t)&&e.type===r}}function pe(t){return function(e){return"form"in e?e.parentNode&&!1===e.disabled?"label"in e?"label"in e.parentNode?e.parentNode.disabled===t:e.disabled===t:e.isDisabled===t||e.isDisabled!==!t&&ne(e)===t:e.disabled===t:"label"in e&&e.disabled===t}}function de(a){return se(function(o){return o=+o,se(function(e,t){for(var r,i=a([],e.length,o),n=i.length;n--;)e[r=i[n]]&&(e[r]=!(t[r]=e[r]))})})}function me(e){return e&&void 0!==e.getElementsByTagName&&e}for(e in p=oe.support={},n=oe.isXML=function(e){var t=e&&(e.ownerDocument||e).documentElement;return!!t&&"HTML"!==t.nodeName},w=oe.setDocument=function(e){var t,r,i=e?e.ownerDocument||e:_;return i!==T&&9===i.nodeType&&i.documentElement&&(a=(T=i).documentElement,k=!n(T),_!==T&&(r=T.defaultView)&&r.top!==r&&(r.addEventListener?r.addEventListener("unload",ie,!1):r.attachEvent&&r.attachEvent("onunload",ie)),p.attributes=le(function(e){return e.className="i",!e.getAttribute("className")}),p.getElementsByTagName=le(function(e){return e.appendChild(T.createComment("")),!e.getElementsByTagName("*").length}),p.getElementsByClassName=J.test(T.getElementsByClassName),p.getById=le(function(e){return a.appendChild(e).id=P,!T.getElementsByName||!T.getElementsByName(P).length}),p.getById?(b.filter.ID=function(e){var t=e.replace($,ee);return function(e){return e.getAttribute("id")===t}},b.find.ID=function(e,t){if(void 0!==t.getElementById&&k){var r=t.getElementById(e);return r?[r]:[]}}):(b.filter.ID=function(e){var r=e.replace($,ee);return function(e){var t=void 0!==e.getAttributeNode&&e.getAttributeNode("id");return t&&t.value===r}},b.find.ID=function(e,t){if(void 0!==t.getElementById&&k){var r,i,n,o=t.getElementById(e);if(o){if((r=o.getAttributeNode("id"))&&r.value===e)return[o];for(n=t.getElementsByName(e),i=0;o=n[i++];)if((r=o.getAttributeNode("id"))&&r.value===e)return[o]}return[]}}),b.find.TAG=p.getElementsByTagName?function(e,t){return void 0!==t.getElementsByTagName?t.getElementsByTagName(e):p.qsa?t.querySelectorAll(e):void 0}:function(e,t){var r,i=[],n=0,o=t.getElementsByTagName(e);if("*"!==e)return o;for(;r=o[n++];)1===r.nodeType&&i.push(r);return i},b.find.CLASS=p.getElementsByClassName&&function(e,t){if(void 0!==t.getElementsByClassName&&k)return t.getElementsByClassName(e)},s=[],g=[],(p.qsa=J.test(T.querySelectorAll))&&(le(function(e){a.appendChild(e).innerHTML="",e.querySelectorAll("[msallowcapture^='']").length&&g.push("[*^$]="+L+"*(?:''|\"\")"),e.querySelectorAll("[selected]").length||g.push("\\["+L+"*(?:value|"+z+")"),e.querySelectorAll("[id~="+P+"-]").length||g.push("~="),e.querySelectorAll(":checked").length||g.push(":checked"),e.querySelectorAll("a#"+P+"+*").length||g.push(".#.+[+~]")}),le(function(e){e.innerHTML="";var t=T.createElement("input");t.setAttribute("type","hidden"),e.appendChild(t).setAttribute("name","D"),e.querySelectorAll("[name=d]").length&&g.push("name"+L+"*[*^$|!~]?="),2!==e.querySelectorAll(":enabled").length&&g.push(":enabled",":disabled"),a.appendChild(e).disabled=!0,2!==e.querySelectorAll(":disabled").length&&g.push(":enabled",":disabled"),e.querySelectorAll("*,:x"),g.push(",.*:")})),(p.matchesSelector=J.test(h=a.matches||a.webkitMatchesSelector||a.mozMatchesSelector||a.oMatchesSelector||a.msMatchesSelector))&&le(function(e){p.disconnectedMatch=h.call(e,"*"),h.call(e,"[s!='']:x"),s.push("!=",N)}),g=g.length&&new RegExp(g.join("|")),s=s.length&&new RegExp(s.join("|")),t=J.test(a.compareDocumentPosition),v=t||J.test(a.contains)?function(e,t){var r=9===e.nodeType?e.documentElement:e,i=t&&t.parentNode;return e===i||!(!i||1!==i.nodeType||!(r.contains?r.contains(i):e.compareDocumentPosition&&16&e.compareDocumentPosition(i)))}:function(e,t){if(t)for(;t=t.parentNode;)if(t===e)return!0;return!1},A=t?function(e,t){if(e===t)return u=!0,0;var r=!e.compareDocumentPosition-!t.compareDocumentPosition;return r||(1&(r=(e.ownerDocument||e)===(t.ownerDocument||t)?e.compareDocumentPosition(t):1)||!p.sortDetached&&t.compareDocumentPosition(e)===r?e===T||e.ownerDocument===_&&v(_,e)?-1:t===T||t.ownerDocument===_&&v(_,t)?1:l?R(l,e)-R(l,t):0:4&r?-1:1)}:function(e,t){if(e===t)return u=!0,0;var r,i=0,n=e.parentNode,o=t.parentNode,a=[e],s=[t];if(!n||!o)return e===T?-1:t===T?1:n?-1:o?1:l?R(l,e)-R(l,t):0;if(n===o)return he(e,t);for(r=e;r=r.parentNode;)a.unshift(r);for(r=t;r=r.parentNode;)s.unshift(r);for(;a[i]===s[i];)i++;return i?he(a[i],s[i]):a[i]===_?-1:s[i]===_?1:0}),T},oe.matches=function(e,t){return oe(e,null,null,t)},oe.matchesSelector=function(e,t){if((e.ownerDocument||e)!==T&&w(e),t=t.replace(G,"='$1']"),p.matchesSelector&&k&&!E[t+" "]&&(!s||!s.test(t))&&(!g||!g.test(t)))try{var r=h.call(e,t);if(r||p.disconnectedMatch||e.document&&11!==e.document.nodeType)return r}catch(e){}return 0":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(e){return e[1]=e[1].replace($,ee),e[3]=(e[3]||e[4]||e[5]||"").replace($,ee),"~="===e[2]&&(e[3]=" "+e[3]+" "),e.slice(0,4)},CHILD:function(e){return e[1]=e[1].toLowerCase(),"nth"===e[1].slice(0,3)?(e[3]||oe.error(e[0]),e[4]=+(e[4]?e[5]+(e[6]||1):2*("even"===e[3]||"odd"===e[3])),e[5]=+(e[7]+e[8]||"odd"===e[3])):e[3]&&oe.error(e[0]),e},PSEUDO:function(e){var t,r=!e[6]&&e[2];return V.CHILD.test(e[0])?null:(e[3]?e[2]=e[4]||e[5]||"":r&&W.test(r)&&(t=d(r,!0))&&(t=r.indexOf(")",r.length-t)-r.length)&&(e[0]=e[0].slice(0,t),e[2]=r.slice(0,t)),e.slice(0,3))}},filter:{TAG:function(e){var t=e.replace($,ee).toLowerCase();return"*"===e?function(){return!0}:function(e){return e.nodeName&&e.nodeName.toLowerCase()===t}},CLASS:function(e){var t=f[e+" "];return t||(t=new RegExp("(^|"+L+")"+e+"("+L+"|$)"))&&f(e,function(e){return t.test("string"==typeof e.className&&e.className||void 0!==e.getAttribute&&e.getAttribute("class")||"")})},ATTR:function(r,i,n){return function(e){var t=oe.attr(e,r);return null==t?"!="===i:!i||(t+="","="===i?t===n:"!="===i?t!==n:"^="===i?n&&0===t.indexOf(n):"*="===i?n&&-1:\x20\t\r\n\f]*)[\x20\t\r\n\f]*\/?>(?:<\/\1>|)$/i;function C(e,r,i){return _(r)?P.grep(e,function(e,t){return!!r.call(e,t,e)!==i}):r.nodeType?P.grep(e,function(e){return e===r!==i}):"string"!=typeof r?P.grep(e,function(e){return-1)[^>]*|#([\w-]+))$/;(P.fn.init=function(e,t,r){var i,n;if(!e)return this;if(r=r||I,"string"!=typeof e)return e.nodeType?(this[0]=e,this.length=1,this):_(e)?void 0!==r.ready?r.ready(e):e(P):P.makeArray(e,this);if(!(i="<"===e[0]&&">"===e[e.length-1]&&3<=e.length?[null,e,null]:O.exec(e))||!i[1]&&t)return!t||t.jquery?(t||r).find(e):this.constructor(t).find(e);if(i[1]){if(t=t instanceof P?t[0]:t,P.merge(this,P.parseHTML(i[1],t&&t.nodeType?t.ownerDocument||t:k,!0)),A.test(i[1])&&P.isPlainObject(t))for(i in t)_(this[i])?this[i](t[i]):this.attr(i,t[i]);return this}return(n=k.getElementById(i[2]))&&(this[0]=n,this.length=1),this}).prototype=P.fn,I=P(k);var M=/^(?:parents|prev(?:Until|All))/,D={children:!0,contents:!0,next:!0,prev:!0};function R(e,t){for(;(e=e[t])&&1!==e.nodeType;);return e}P.fn.extend({has:function(e){var t=P(e,this),r=t.length;return this.filter(function(){for(var e=0;e\x20\t\r\n\f]+)/i,he=/^$|^module$|\/(?:java|ecma)script/i,ce={option:[1,""],thead:[1,"","
"],col:[2,"","
"],tr:[2,"","
"],td:[3,"","
"],_default:[0,"",""]};function fe(e,t){var r;return r=void 0!==e.getElementsByTagName?e.getElementsByTagName(t||"*"):void 0!==e.querySelectorAll?e.querySelectorAll(t||"*"):[],void 0===t||t&&E(e,t)?P.merge([e],r):r}function pe(e,t){for(var r=0,i=e.length;rx",v.noCloneChecked=!!de.cloneNode(!0).lastChild.defaultValue;var _e=k.documentElement,ye=/^key/,be=/^(?:mouse|pointer|contextmenu|drag|drop)|click/,xe=/^([^.]*)(?:\.(.+)|)/;function we(){return!0}function Te(){return!1}function ke(){try{return k.activeElement}catch(e){}}function Pe(e,t,r,i,n,o){var a,s;if("object"==typeof t){for(s in"string"!=typeof r&&(i=i||r,r=void 0),t)Pe(e,s,r,i,t[s],o);return e}if(null==i&&null==n?(n=r,i=r=void 0):null==n&&("string"==typeof r?(n=i,i=void 0):(n=i,i=r,r=void 0)),!1===n)n=Te;else if(!n)return e;return 1===o&&(a=n,(n=function(e){return P().off(e),a.apply(this,arguments)}).guid=a.guid||(a.guid=P.guid++)),e.each(function(){P.event.add(this,t,n,i,r)})}P.event={global:{},add:function(t,e,r,i,n){var o,a,s,l,u,h,c,f,p,d,m,g=Z.get(t);if(g)for(r.handler&&(r=(o=r).handler,n=o.selector),n&&P.find.matchesSelector(_e,n),r.guid||(r.guid=P.guid++),(l=g.events)||(l=g.events={}),(a=g.handle)||(a=g.handle=function(e){return void 0!==P&&P.event.triggered!==e.type?P.event.dispatch.apply(t,arguments):void 0}),u=(e=(e||"").match(z)||[""]).length;u--;)p=m=(s=xe.exec(e[u])||[])[1],d=(s[2]||"").split(".").sort(),p&&(c=P.event.special[p]||{},p=(n?c.delegateType:c.bindType)||p,c=P.event.special[p]||{},h=P.extend({type:p,origType:m,data:i,handler:r,guid:r.guid,selector:n,needsContext:n&&P.expr.match.needsContext.test(n),namespace:d.join(".")},o),(f=l[p])||((f=l[p]=[]).delegateCount=0,c.setup&&!1!==c.setup.call(t,i,d,a)||t.addEventListener&&t.addEventListener(p,a)),c.add&&(c.add.call(t,h),h.handler.guid||(h.handler.guid=r.guid)),n?f.splice(f.delegateCount++,0,h):f.push(h),P.event.global[p]=!0)},remove:function(e,t,r,i,n){var o,a,s,l,u,h,c,f,p,d,m,g=Z.hasData(e)&&Z.get(e);if(g&&(l=g.events)){for(u=(t=(t||"").match(z)||[""]).length;u--;)if(p=m=(s=xe.exec(t[u])||[])[1],d=(s[2]||"").split(".").sort(),p){for(c=P.event.special[p]||{},f=l[p=(i?c.delegateType:c.bindType)||p]||[],s=s[2]&&new RegExp("(^|\\.)"+d.join("\\.(?:.*\\.|)")+"(\\.|$)"),a=o=f.length;o--;)h=f[o],!n&&m!==h.origType||r&&r.guid!==h.guid||s&&!s.test(h.namespace)||i&&i!==h.selector&&("**"!==i||!h.selector)||(f.splice(o,1),h.selector&&f.delegateCount--,c.remove&&c.remove.call(e,h));a&&!f.length&&(c.teardown&&!1!==c.teardown.call(e,d,g.handle)||P.removeEvent(e,p,g.handle),delete l[p])}else for(p in l)P.event.remove(e,p+t[u],r,i,!0);P.isEmptyObject(l)&&Z.remove(e,"handle events")}},dispatch:function(e){var t,r,i,n,o,a,s=P.event.fix(e),l=new Array(arguments.length),u=(Z.get(this,"events")||{})[s.type]||[],h=P.event.special[s.type]||{};for(l[0]=s,t=1;t\x20\t\r\n\f]*)[^>]*)\/>/gi,Ee=/\s*$/g;function Ie(e,t){return E(e,"table")&&E(11!==t.nodeType?t:t.firstChild,"tr")&&P(e).children("tbody")[0]||e}function Oe(e){return e.type=(null!==e.getAttribute("type"))+"/"+e.type,e}function Me(e){return"true/"===(e.type||"").slice(0,5)?e.type=e.type.slice(5):e.removeAttribute("type"),e}function De(e,t){var r,i,n,o,a,s,l,u;if(1===t.nodeType){if(Z.hasData(e)&&(o=Z.access(e),a=Z.set(t,o),u=o.events))for(n in delete a.handle,a.events={},u)for(r=0,i=u[n].length;r")},clone:function(e,t,r){var i,n,o,a,s,l,u,h=e.cloneNode(!0),c=P.contains(e.ownerDocument,e);if(!(v.noCloneChecked||1!==e.nodeType&&11!==e.nodeType||P.isXMLDoc(e)))for(a=fe(h),i=0,n=(o=fe(e)).length;i").prop({charset:r.scriptCharset,src:r.url}).on("load error",n=function(e){i.remove(),n=null,e&&t("error"===e.type?404:200,e.type)}),k.head.appendChild(i[0])},abort:function(){n&&n()}}});var Xt,Ht=[],Gt=/(=)\?(?=&|$)|\?\?/;P.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var e=Ht.pop()||P.expando+"_"+bt++;return this[e]=!0,e}}),P.ajaxPrefilter("json jsonp",function(e,t,r){var i,n,o,a=!1!==e.jsonp&&(Gt.test(e.url)?"url":"string"==typeof e.data&&0===(e.contentType||"").indexOf("application/x-www-form-urlencoded")&&Gt.test(e.data)&&"data");if(a||"jsonp"===e.dataTypes[0])return i=e.jsonpCallback=_(e.jsonpCallback)?e.jsonpCallback():e.jsonpCallback,a?e[a]=e[a].replace(Gt,"$1"+i):!1!==e.jsonp&&(e.url+=(xt.test(e.url)?"&":"?")+e.jsonp+"="+i),e.converters["script json"]=function(){return o||P.error(i+" was not called"),o[0]},e.dataTypes[0]="json",n=T[i],T[i]=function(){o=arguments},r.always(function(){void 0===n?P(T).removeProp(i):T[i]=n,e[i]&&(e.jsonpCallback=t.jsonpCallback,Ht.push(i)),o&&_(n)&&n(o[0]),o=n=void 0}),"script"}),v.createHTMLDocument=((Xt=k.implementation.createHTMLDocument("").body).innerHTML="
",2===Xt.childNodes.length),P.parseHTML=function(e,t,r){return"string"!=typeof e?[]:("boolean"==typeof t&&(r=t,t=!1),t||(v.createHTMLDocument?((i=(t=k.implementation.createHTMLDocument("")).createElement("base")).href=k.location.href,t.head.appendChild(i)):t=k),o=!r&&[],(n=A.exec(e))?[t.createElement(n[1])]:(n=ve([e],t,o),o&&o.length&&P(o).remove(),P.merge([],n.childNodes)));var i,n,o},P.fn.load=function(e,t,r){var i,n,o,a=this,s=e.indexOf(" ");return-1").append(P.parseHTML(e)).find(i):e)}).always(r&&function(e,t){a.each(function(){r.apply(this,o||[e.responseText,t,e])})}),this},P.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(e,t){P.fn[t]=function(e){return this.on(t,e)}}),P.expr.pseudos.animated=function(t){return P.grep(P.timers,function(e){return t===e.elem}).length},P.offset={setOffset:function(e,t,r){var i,n,o,a,s,l,u=P.css(e,"position"),h=P(e),c={};"static"===u&&(e.style.position="relative"),s=h.offset(),o=P.css(e,"top"),l=P.css(e,"left"),n=("absolute"===u||"fixed"===u)&&-1<(o+l).indexOf("auto")?(a=(i=h.position()).top,i.left):(a=parseFloat(o)||0,parseFloat(l)||0),_(t)&&(t=t.call(e,r,P.extend({},s))),null!=t.top&&(c.top=t.top-s.top+a),null!=t.left&&(c.left=t.left-s.left+n),"using"in t?t.using.call(e,c):h.css(c)}},P.fn.extend({offset:function(t){if(arguments.length)return void 0===t?this:this.each(function(e){P.offset.setOffset(this,t,e)});var e,r,i=this[0];return i?i.getClientRects().length?(e=i.getBoundingClientRect(),r=i.ownerDocument.defaultView,{top:e.top+r.pageYOffset,left:e.left+r.pageXOffset}):{top:0,left:0}:void 0},position:function(){if(this[0]){var e,t,r,i=this[0],n={top:0,left:0};if("fixed"===P.css(i,"position"))t=i.getBoundingClientRect();else{for(t=this.offset(),r=i.ownerDocument,e=i.offsetParent||r.documentElement;e&&(e===r.body||e===r.documentElement)&&"static"===P.css(e,"position");)e=e.parentNode;e&&e!==i&&1===e.nodeType&&((n=P(e).offset()).top+=P.css(e,"borderTopWidth",!0),n.left+=P.css(e,"borderLeftWidth",!0))}return{top:t.top-n.top-P.css(i,"marginTop",!0),left:t.left-n.left-P.css(i,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){for(var e=this.offsetParent;e&&"static"===P.css(e,"position");)e=e.offsetParent;return e||_e})}}),P.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(t,n){var o="pageYOffset"===n;P.fn[t]=function(e){return X(this,function(e,t,r){var i;if(y(e)?i=e:9===e.nodeType&&(i=e.defaultView),void 0===r)return i?i[n]:e[t];i?i.scrollTo(o?i.pageXOffset:r,o?r:i.pageYOffset):e[t]=r},t,e,arguments.length)}}),P.each(["top","left"],function(e,r){P.cssHooks[r]=Be(v.pixelPosition,function(e,t){if(t)return t=Ne(e,r),Le.test(t)?P(e).position()[r]+"px":t})}),P.each({Height:"height",Width:"width"},function(a,s){P.each({padding:"inner"+a,content:s,"":"outer"+a},function(i,o){P.fn[o]=function(e,t){var r=arguments.length&&(i||"boolean"!=typeof e),n=i||(!0===e||!0===t?"margin":"border");return X(this,function(e,t,r){var i;return y(e)?0===o.indexOf("outer")?e["inner"+a]:e.document.documentElement["client"+a]:9===e.nodeType?(i=e.documentElement,Math.max(e.body["scroll"+a],i["scroll"+a],e.body["offset"+a],i["offset"+a],i["client"+a])):void 0===r?P.css(e,t,n):P.style(e,t,r,n)},s,r?e:void 0,r)}})}),P.each("blur focus focusin focusout resize scroll click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup contextmenu".split(" "),function(e,r){P.fn[r]=function(e,t){return 0>>0,i=(r*=i)>>>0,i+=4294967296*(r-=i)}return 2.3283064365386963e-10*(i>>>0)}}();t.next=function(){var e=2091639*t.s0+2.3283064365386963e-10*t.c;return t.s0=t.s1,t.s1=t.s2,t.s2=e-(t.c=0|e)},t.c=1,t.s0=r(" "),t.s1=r(" "),t.s2=r(" "),t.s0-=r(e),t.s0<0&&(t.s0+=1),t.s1-=r(e),t.s1<0&&(t.s1+=1),t.s2-=r(e),t.s2<0&&(t.s2+=1),r=null}function a(e,t){return t.c=e.c,t.s0=e.s0,t.s1=e.s1,t.s2=e.s2,t}function i(e,t){var r=new o(e),i=t&&t.state,n=r.next;return n.int32=function(){return 4294967296*r.next()|0},n.double=function(){return n()+11102230246251565e-32*(2097152*n()|0)},n.quick=n,i&&("object"==typeof i&&a(i,r),n.state=function(){return a(r,{})}),n}t&&t.exports?t.exports=i:r&&r.amd?r(function(){return i}):this.alea=i}(0,"object"==typeof t&&t,"function"==typeof define&&define)},{}],16:[function(e,t,r){!function(e,t,r){function o(e){var n=this,t="";n.next=function(){var e=n.b,t=n.c,r=n.d,i=n.a;return e=e<<25^e>>>7^t,t=t-r|0,r=r<<24^r>>>8^i,i=i-e|0,n.b=e=e<<20^e>>>12^t,n.c=t=t-r|0,n.d=r<<16^t>>>16^i,n.a=i-e|0},n.a=0,n.b=0,n.c=-1640531527,n.d=1367130551,e===Math.floor(e)?(n.a=e/4294967296|0,n.b=0|e):t+=e;for(var r=0;r>>0)/4294967296};return n.double=function(){do{var e=((r.next()>>>11)+(r.next()>>>0)/4294967296)/(1<<21)}while(0===e);return e},n.int32=r.next,n.quick=n,i&&("object"==typeof i&&a(i,r),n.state=function(){return a(r,{})}),n}t&&t.exports?t.exports=i:r&&r.amd?r(function(){return i}):this.tychei=i}(0,"object"==typeof t&&t,"function"==typeof define&&define)},{}],17:[function(e,t,r){!function(e,t,r){function o(e){var t=this,r="";t.x=0,t.y=0,t.z=0,t.w=0,t.next=function(){var e=t.x^t.x<<11;return t.x=t.y,t.y=t.z,t.z=t.w,t.w^=t.w>>>19^e^e>>>8},e===(0|e)?t.x=e:r+=e;for(var i=0;i>>0)/4294967296};return n.double=function(){do{var e=((r.next()>>>11)+(r.next()>>>0)/4294967296)/(1<<21)}while(0===e);return e},n.int32=r.next,n.quick=n,i&&("object"==typeof i&&a(i,r),n.state=function(){return a(r,{})}),n}t&&t.exports?t.exports=i:r&&r.amd?r(function(){return i}):this.xor128=i}(0,"object"==typeof t&&t,"function"==typeof define&&define)},{}],18:[function(e,t,r){!function(e,t,r){function o(e){var o=this;o.next=function(){var e,t,r=o.w,i=o.X,n=o.i;return o.w=r=r+1640531527|0,t=i[n+34&127],e=i[n=n+1&127],t^=t<<13,e^=e<<17,t^=t>>>15,e^=e>>>12,t=i[n]=t^e,o.i=n,t+(r^r>>>16)|0},function(e,t){var r,i,n,o,a,s=[],l=128;for(t===(0|t)?(i=t,t=null):(t+="\0",i=0,l=Math.max(l,t.length)),n=0,o=-32;o>>15,i^=i<<4,i^=i>>>13,0<=o&&(a=a+1640531527|0,n=0==(r=s[127&o]^=i+a)?n+1:0);for(128<=n&&(s[127&(t&&t.length||0)]=-1),n=127,o=512;0>>15,r^=r>>>12,s[n]=i^r;e.w=a,e.X=s,e.i=n}(o,e)}function a(e,t){return t.i=e.i,t.w=e.w,t.X=e.X.slice(),t}function i(e,t){null==e&&(e=+new Date);var r=new o(e),i=t&&t.state,n=function(){return(r.next()>>>0)/4294967296};return n.double=function(){do{var e=((r.next()>>>11)+(r.next()>>>0)/4294967296)/(1<<21)}while(0===e);return e},n.int32=r.next,n.quick=n,i&&(i.X&&a(i,r),n.state=function(){return a(r,{})}),n}t&&t.exports?t.exports=i:r&&r.amd?r(function(){return i}):this.xor4096=i}(0,"object"==typeof t&&t,"function"==typeof define&&define)},{}],19:[function(e,t,r){!function(e,t,r){function o(e){var n=this;n.next=function(){var e,t,r=n.x,i=n.i;return e=r[i],t=(e^=e>>>7)^e<<24,t^=(e=r[i+1&7])^e>>>10,t^=(e=r[i+3&7])^e>>>3,t^=(e=r[i+4&7])^e<<7,e=r[i+7&7],t^=(e^=e<<13)^e<<9,r[i]=t,n.i=i+1&7,t},function(e,t){var r,i=[];if(t===(0|t))i[0]=t;else for(t=""+t,r=0;r>>0)/4294967296};return n.double=function(){do{var e=((r.next()>>>11)+(r.next()>>>0)/4294967296)/(1<<21)}while(0===e);return e},n.int32=r.next,n.quick=n,i&&(i.x&&a(i,r),n.state=function(){return a(r,{})}),n}t&&t.exports?t.exports=i:r&&r.amd?r(function(){return i}):this.xorshift7=i}(0,"object"==typeof t&&t,"function"==typeof define&&define)},{}],20:[function(e,t,r){!function(e,t,r){function o(e){var t=this,r="";t.next=function(){var e=t.x^t.x>>>2;return t.x=t.y,t.y=t.z,t.z=t.w,t.w=t.v,(t.d=t.d+362437|0)+(t.v=t.v^t.v<<4^e^e<<1)|0},t.x=0,t.y=0,t.z=0,t.w=0,e===((t.v=0)|e)?t.x=e:r+=e;for(var i=0;i>>4),t.next()}function a(e,t){return t.x=e.x,t.y=e.y,t.z=e.z,t.w=e.w,t.v=e.v,t.d=e.d,t}function i(e,t){var r=new o(e),i=t&&t.state,n=function(){return(r.next()>>>0)/4294967296};return n.double=function(){do{var e=((r.next()>>>11)+(r.next()>>>0)/4294967296)/(1<<21)}while(0===e);return e},n.int32=r.next,n.quick=n,i&&("object"==typeof i&&a(i,r),n.state=function(){return a(r,{})}),n}t&&t.exports?t.exports=i:r&&r.amd?r(function(){return i}):this.xorwow=i}(0,"object"==typeof t&&t,"function"==typeof define&&define)},{}],21:[function(t,r,e){!function(s,l){var u,h=this,c=256,f=6,p="random",d=l.pow(c,f),m=l.pow(2,52),g=2*m,v=c-1;function e(e,t,r){var i=[],n=b(function e(t,r){var i,n=[],o=typeof t;if(r&&"object"==o)for(i in t)try{n.push(e(t[i],r-1))}catch(e){}return n.length?n:"string"==o?t:t+"\0"}((t=1==t?{entropy:!0}:t||{}).entropy?[e,x(s)]:null==e?function(){try{var e;return u&&(e=u.randomBytes)?e=e(c):(e=new Uint8Array(c),(h.crypto||h.msCrypto).getRandomValues(e)),x(e)}catch(e){var t=h.navigator,r=t&&t.plugins;return[+new Date,h,r,h.screen,x(s)]}}():e,3),i),o=new _(i),a=function(){for(var e=o.g(f),t=d,r=0;e>>=1;return(e+r)/t};return a.int32=function(){return 0|o.g(4)},a.quick=function(){return o.g(4)/4294967296},a.double=a,b(x(o.S),s),(t.pass||r||function(e,t,r,i){return i&&(i.S&&y(i,o),e.state=function(){return y(o,{})}),r?(l[p]=e,t):e})(a,n,"global"in t?t.global:this==l,t.state)}function _(e){var t,r=e.length,a=this,i=0,n=a.i=a.j=0,o=a.S=[];for(r||(e=[r++]);iMath.PI?c-r:r}function g(e){return e-c*Math.floor(e/c)}t.exports={UP:o,DOWN:a,LEFT:s,RIGHT:0,NORTH:l,SOUTH:u,WEST:h,EAST:0,PI_2:c,PI_QUARTER:f,PI_HALF:p,toDegrees:function(e){return e*i},toRadians:function(e){return e*n},isAngleBetween:function(e,t,r){if(((r-t)%c+c)%c>=Math.PI){var i=t;t=r,r=i}return t<=r?t<=e&&e<=r:t<=e||e<=r},differenceAnglesSign:d,differenceAngles:m,shortestAngle:function(e,t){return m(t,e)*d(t,e)+e},normalize:g,angleTwoPoints:function(){return 4===arguments.length?Math.atan2(arguments[3]-arguments[1],arguments[2]-arguments[0]):Math.atan2(arguments[1].y-arguments[0].y,arguments[1].x-arguments[0].x)},distanceTwoPoints:function(){return 2===arguments.length?Math.sqrt(Math.pow(arguments[1].x-arguments[0].x,2)+Math.pow(arguments[1].y-arguments[0].y,2)):Math.sqrt(Math.pow(arguments[2]-arguments[0],2)+Math.pow(arguments[3]-arguments[1],2))},distanceTwoPointsSquared:function(){return 2===arguments.length?Math.pow(arguments[1].x-arguments[0].x,2)+Math.pow(arguments[1].y-arguments[0].y,2):Math.pow(arguments[2]-arguments[0],2)+Math.pow(arguments[3]-arguments[1],2)},closestAngle:function(e){var t=m(e,s),r=m(e,0),i=m(e,o),n=m(e,a);return t<=r&&t<=i&&t<=n?s:r<=i&&r<=n?0:i<=n?o:a},equals:function(e,t,r){return r?m(e,t)>16)+e*(r>>16)<<16|i*(t>>8&255)+e*(r>>8&255)<<8|i*(255&t)+e*(255&r)},random:function(e,t){function r(){return s.range(e,t)}var i=s.pick([{r:1,g:1,b:1},{r:1,g:1,b:0},{r:1,g:0,b:1},{r:0,g:1,b:1},{r:1,g:0,b:0},{r:0,g:1,b:0},{r:0,g:0,b:1}]);return e=e||0,t=t||255,this.rgbToHex(i.r?r():0,i.g?r():0,i.b?r():0)},randomHSL:function(e,t,r,i,n,o){var a={h:s.range(e,t),s:s.range(r,i,!0),l:s.range(n,o,!0)};return this.hslToHex(a)},randomGoldenRatioHSL:function(e,t,r){for(var i=s.get(1,!0),n=[],o=0;o=this.time?(this.parent.x=t.end,this.toX=null,this.parent.emit("bounce-x-end",this.parent)):this.parent.x=this.ease(t.time,t.start,t.delta,this.time),this.parent.dirty=!0}if(this.toY){var r=this.toY;r.time+=e,this.parent.emit("moved",{viewport:this.parent,type:"bounce-y"}),r.time>=this.time?(this.parent.y=r.end,this.toY=null,this.parent.emit("bounce-y-end",this.parent)):this.parent.y=this.ease(r.time,r.start,r.delta,this.time),this.parent.dirty=!0}}}},{key:"calcUnderflowX",value:function(){var e=void 0;switch(this.underflowX){case-1:e=0;break;case 1:e=this.parent.screenWidth-this.parent.screenWorldWidth;break;default:e=(this.parent.screenWidth-this.parent.screenWorldWidth)/2}return e}},{key:"calcUnderflowY",value:function(){var e=void 0;switch(this.underflowY){case-1:e=0;break;case 1:e=this.parent.screenHeight-this.parent.screenWorldHeight;break;default:e=(this.parent.screenHeight-this.parent.screenWorldHeight)/2}return e}},{key:"bounce",value:function(){if(!this.paused){var e=void 0,t=this.parent.plugins.decelerate;t&&(t.x||t.y)&&(t.x&&t.percentChangeX===t.friction||t.y&&t.percentChangeY===t.friction)&&(((e=this.parent.OOB()).left&&this.left||e.right&&this.right)&&(t.percentChangeX=this.friction),(e.top&&this.top||e.bottom&&this.bottom)&&(t.percentChangeY=this.friction));var r=this.parent.plugins.drag||{},i=this.parent.plugins.pinch||{};if(t=t||{},!(r.active||i.active||this.toX&&this.toY||t.x&&t.y)){var n=(e=e||this.parent.OOB()).cornerPoint;if(!this.toX&&!t.x){var o=null;e.left&&this.left?o=this.parent.screenWorldWidththis.maxWidth&&(this.parent.fitWidth(this.maxWidth),e=this.parent.worldScreenWidth,t=this.parent.worldScreenHeight,this.parent.emit("zoomed",{viewport:this.parent,type:"clamp-zoom"})),this.minHeight&&tthis.maxHeight&&(this.parent.fitHeight(this.maxHeight),this.parent.emit("zoomed",{viewport:this.parent,type:"clamp-zoom"}))}}}]),i}()},{"./plugin":9}],3:[function(e,t,r){"use strict";var n=function(){function i(e,t){for(var r=0;r(!0===this.right?this.parent.worldWidth:this.right)&&(this.parent.x=-(!0===this.right?this.parent.worldWidth:this.right)*this.parent.scale.x+this.parent.screenWidth,t=!(e.x=0));t&&this.parent.emit("moved",{viewport:this.parent,type:"clamp-x"})}if(null!==this.top||null!==this.bottom){var r=void 0;if(this.parent.screenWorldHeight(!0===this.bottom?this.parent.worldHeight:this.bottom)&&(this.parent.y=-(!0===this.bottom?this.parent.worldHeight:this.bottom)*this.parent.scale.y+this.parent.screenHeight,r=!(e.y=0));r&&this.parent.emit("moved",{viewport:this.parent,type:"clamp-y"})}}}}]),i}()},{"./plugin":9,"./utils":12}],4:[function(e,t,r){"use strict";var n=function(){function i(e,t){for(var r=0;r=e-100){var s=e-a.time;this.x=(this.parent.x-a.x)/s,this.y=(this.parent.y-a.y)/s,this.percentChangeX=this.percentChangeY=this.friction;break}}}catch(e){r=!0,i=e}finally{try{!t&&o.return&&o.return()}finally{if(r)throw i}}}}},{key:"activate",value:function(e){void 0!==(e=e||{}).x&&(this.x=e.x,this.percentChangeX=this.friction),void 0!==e.y&&(this.y=e.y,this.percentChangeY=this.friction)}},{key:"update",value:function(e){if(!this.paused){var t=void 0;this.x&&(this.parent.x+=this.x*e,this.x*=this.percentChangeX,Math.abs(this.x)this.parent.worldWidth&&(this.parent.x=-this.parent.worldWidth*this.parent.scale.x+this.parent.screenWidth,e.x=0);if("x"!==this.clampWheel)if(this.parent.screenWorldHeightthis.parent.worldHeight&&(this.parent.y=-this.parent.worldHeight*this.parent.scale.y+this.parent.screenHeight,e.y=0)}},{key:"active",get:function(){return this.moved}}]),i}()},{"./plugin":9,"./utils":12}],6:[function(e,t,r){"use strict";var i=function(){function i(e,t){for(var r=0;rthis.radius))return;var i=Math.atan2(this.target.y-e.y,this.target.x-e.x);t=this.target.x-Math.cos(i)*this.radius,r=this.target.y-Math.sin(i)*this.radius}if(this.speed){var n=t-e.x,o=r-e.y;if(n||o){var a=Math.atan2(r-e.y,t-e.x),s=Math.cos(a)*this.speed,l=Math.sin(a)*this.speed,u=Math.abs(s)>Math.abs(n)?t:e.x+s,h=Math.abs(l)>Math.abs(o)?r:e.y+l;this.parent.moveCenter(u,h),this.parent.emit("moved",{viewport:this.parent,type:"follow"})}}else this.parent.moveCenter(t,r),this.parent.emit("moved",{viewport:this.parent,type:"follow"})}}}]),n}()},{"./plugin":9}],7:[function(e,t,r){"use strict";var n=function(){function i(e,t){for(var r=0;r=this.radiusSquared){var n=Math.atan2(i.y-r,i.x-t);this.linear?(this.horizontal=Math.round(Math.cos(n))*this.speed*this.reverse*.06,this.vertical=Math.round(Math.sin(n))*this.speed*this.reverse*.06):(this.horizontal=Math.cos(n)*this.speed*this.reverse*.06,this.vertical=Math.sin(n)*this.speed*this.reverse*.06)}else this.horizontal&&this.decelerateHorizontal(),this.vertical&&this.decelerateVertical(),this.horizontal=this.vertical=0}else o.exists(this.left)&&tthis.right?this.horizontal=-1*this.reverse*this.speed*.06:(this.decelerateHorizontal(),this.horizontal=0),o.exists(this.top)&&rthis.bottom?this.vertical=-1*this.reverse*this.speed*.06:(this.decelerateVertical(),this.vertical=0)}}},{key:"decelerateHorizontal",value:function(){var e=this.parent.plugins.decelerate;this.horizontal&&e&&!this.noDecelerate&&e.activate({x:this.horizontal*this.speed*this.reverse/(1e3/60)})}},{key:"decelerateVertical",value:function(){var e=this.parent.plugins.decelerate;this.vertical&&e&&!this.noDecelerate&&e.activate({y:this.vertical*this.speed*this.reverse/(1e3/60)})}},{key:"up",value:function(){this.horizontal&&this.decelerateHorizontal(),this.vertical&&this.decelerateVertical(),this.horizontal=this.vertical=null}},{key:"update",value:function(){if(!this.paused&&(this.horizontal||this.vertical)){var e=this.parent.center;this.horizontal&&(e.x+=this.horizontal*this.speed),this.vertical&&(e.y+=this.vertical*this.speed),this.parent.moveCenter(e),this.parent.emit("moved",{viewport:this.parent,type:"mouse-edges"})}}}]),i}()},{"./plugin":9,"./utils":12}],8:[function(e,t,r){"use strict";var n=function(){function i(e,t){for(var r=0;r=this.time)this.parent.scale.set(this.x_scale,this.y_scale),this.removeOnComplete&&this.parent.removePlugin("snap-zoom"),this.parent.emit("snap-zoom-end",this.parent),this.snapping=null;else{var i=this.snapping;this.parent.scale.x=this.ease(i.time,i.startX,i.deltaX,this.time),this.parent.scale.y=this.ease(i.time,i.startY,i.deltaY,this.time)}var n=this.parent.plugins["clamp-zoom"];n&&n.clamp(),this.noMove||(this.center?this.parent.moveCenter(this.center):this.parent.moveCenter(t))}}else this.parent.scale.x===this.x_scale&&this.parent.scale.y===this.y_scale||this.createSnapping()}}},{key:"resume",value:function(){this.snapping=null,function e(t,r,i){null===t&&(t=Function.prototype);var n=Object.getOwnPropertyDescriptor(t,r);if(void 0===n){var o=Object.getPrototypeOf(t);return null===o?void 0:e(o,r,i)}if("value"in n)return n.value;var a=n.get;return void 0!==a?a.call(i):void 0}(i.prototype.__proto__||Object.getPrototypeOf(i.prototype),"resume",this).call(this)}}]),i}()},{"./plugin":9,"./utils":12}],11:[function(e,t,r){"use strict";var i=function(){function i(e,t){for(var r=0;rthis.time)r=!0,i=this.startX+this.deltaX,n=this.startY+this.deltaY;else{var o=this.ease(t.time,0,1,this.time);i=this.startX+this.deltaX*o,n=this.startY+this.deltaY*o}this.topLeft?this.parent.moveCorner(i,n):this.parent.moveCenter(i,n),this.parent.emit("moved",{viewport:this.parent,type:"snap"}),r&&(this.removeOnComplete&&this.parent.removePlugin("snap"),this.parent.emit("snap-end",this.parent),this.snapping=null)}else{var a=this.topLeft?this.parent.corner:this.parent.center;a.x===this.x&&a.y===this.y||this.snapStart()}}}]),o}()},{"./plugin":9,"./utils":12}],12:[function(e,t,r){"use strict";var i=e("penner");function n(e){return null!=e}t.exports={exists:n,defaults:function(e,t){return null!=e?e:t},ease:function(e,t){return n(e)?"function"==typeof e?e:"string"==typeof e?i[e]:void 0:i[t]}}},{penner:15}],13:[function(e,t,r){"use strict";var i=function(){function i(e,t){for(var r=0;r=this.threshold}},{key:"move",value:function(e){if(!this.pause){var t=!0,r=!1,i=void 0;try{for(var n,o=this.pluginsList[Symbol.iterator]();!(t=(n=o.next()).done);t=!0){n.value.move(e)}}catch(e){r=!0,i=e}finally{try{!t&&o.return&&o.return()}finally{if(r)throw i}}if(this.clickedAvailable){var a=e.data.global.x-this.last.x,s=e.data.global.y-this.last.y;(this.checkThreshold(a)||this.checkThreshold(s))&&(this.clickedAvailable=!1)}}}},{key:"up",value:function(e){if(!this.pause){if(e.data.originalEvent instanceof MouseEvent&&0==e.data.originalEvent.button&&(this.leftDown=!1),"mouse"!==e.data.pointerType)for(var t=0;tthis._worldWidth,e.top=this.top<0,e.bottom=this.bottom>this._worldHeight,e.cornerPoint={x:this._worldWidth*this.scale.x-this._screenWidth,y:this._worldHeight*this.scale.y-this._screenHeight},e}},{key:"countDownPointers",value:function(){return(this.leftDown?1:0)+this.touches.length}},{key:"getTouchPointers",value:function(){var e=[],t=this.trackedPointers;for(var r in t){var i=t[r];-1!==this.touches.indexOf(i.pointerId)&&e.push(i)}return e}},{key:"getPointers",value:function(){var e=[],t=this.trackedPointers;for(var r in t)e.push(t[r]);return e}},{key:"_reset",value:function(){this.plugins.bounce&&(this.plugins.bounce.reset(),this.plugins.bounce.bounce()),this.plugins.decelerate&&this.plugins.decelerate.reset(),this.plugins.snap&&this.plugins.snap.reset(),this.plugins.clamp&&this.plugins.clamp.update(),this.plugins["clamp-zoom"]&&this.plugins["clamp-zoom"].clamp(),this.dirty=!0}},{key:"removePlugin",value:function(e){this.plugins[e]&&(this.plugins[e]=null,this.emit(e+"-remove"),this.pluginsSort())}},{key:"pausePlugin",value:function(e){this.plugins[e]&&this.plugins[e].pause()}},{key:"resumePlugin",value:function(e){this.plugins[e]&&this.plugins[e].resume()}},{key:"pluginsSort",value:function(){var e=!0,t=!(this.pluginsList=[]),r=void 0;try{for(var i,n=g[Symbol.iterator]();!(e=(i=n.next()).done);e=!0){var o=i.value;this.plugins[o]&&this.pluginsList.push(this.plugins[o])}}catch(e){t=!0,r=e}finally{try{!e&&n.return&&n.return()}finally{if(t)throw r}}}},{key:"drag",value:function(e){return this.plugins.drag=new o(this,e),this.pluginsSort(),this}},{key:"clamp",value:function(e){return this.plugins.clamp=new s(this,e),this.pluginsSort(),this}},{key:"decelerate",value:function(e){return this.plugins.decelerate=new u(this,e),this.pluginsSort(),this}},{key:"bounce",value:function(e){return this.plugins.bounce=new h(this,e),this.pluginsSort(),this}},{key:"pinch",value:function(e){return this.plugins.pinch=new a(this,e),this.pluginsSort(),this}},{key:"snap",value:function(e,t,r){return this.plugins.snap=new c(this,e,t,r),this.pluginsSort(),this}},{key:"follow",value:function(e,t){return this.plugins.follow=new p(this,e,t),this.pluginsSort(),this}},{key:"wheel",value:function(e){return this.plugins.wheel=new d(this,e),this.pluginsSort(),this}},{key:"clampZoom",value:function(e){return this.plugins["clamp-zoom"]=new l(this,e),this.pluginsSort(),this}},{key:"mouseEdges",value:function(e){return this.plugins["mouse-edges"]=new m(this,e),this.pluginsSort(),this}},{key:"screenWidth",get:function(){return this._screenWidth},set:function(e){this._screenWidth=e}},{key:"screenHeight",get:function(){return this._screenHeight},set:function(e){this._screenHeight=e}},{key:"worldWidth",get:function(){return this._worldWidth?this._worldWidth:this.width},set:function(e){this._worldWidth=e,this.resizePlugins()}},{key:"worldHeight",get:function(){return this._worldHeight?this._worldHeight:this.height},set:function(e){this._worldHeight=e,this.resizePlugins()}},{key:"worldScreenWidth",get:function(){return this._screenWidth/this.scale.x}},{key:"worldScreenHeight",get:function(){return this._screenHeight/this.scale.y}},{key:"screenWorldWidth",get:function(){return this._worldWidth*this.scale.x}},{key:"screenWorldHeight",get:function(){return this._worldHeight*this.scale.y}},{key:"center",get:function(){return{x:this.worldScreenWidth/2-this.x/this.scale.x,y:this.worldScreenHeight/2-this.y/this.scale.y}},set:function(e){this.moveCenter(e)}},{key:"corner",get:function(){return{x:-this.x/this.scale.x,y:-this.y/this.scale.y}},set:function(e){this.moveCorner(e)}},{key:"right",get:function(){return-this.x/this.scale.x+this.worldScreenWidth},set:function(e){this.x=-e*this.scale.x+this.screenWidth,this._reset()}},{key:"left",get:function(){return-this.x/this.scale.x},set:function(e){this.x=-e*this.scale.x,this._reset()}},{key:"top",get:function(){return-this.y/this.scale.y},set:function(e){this.y=-e*this.scale.y,this._reset()}},{key:"bottom",get:function(){return-this.y/this.scale.y+this.worldScreenHeight},set:function(e){this.y=-e*this.scale.y+this.screenHeight,this._reset()}},{key:"dirty",get:function(){return this._dirty},set:function(e){this._dirty=e}},{key:"forceHitArea",get:function(){return this._forceHitArea},set:function(e){e?(this._forceHitArea=e,this.hitArea=e):(this._forceHitArea=!1,this.hitArea=new PIXI.Rectangle(0,0,this.worldWidth,this.worldHeight))}},{key:"pause",get:function(){return this._pause},set:function(e){(this._pause=e)&&(this.touches=[],this.leftDown=!1)}}]),r}();PIXI.extras.Viewport=v,t.exports=v},{"./bounce":1,"./clamp":3,"./clamp-zoom":2,"./decelerate":4,"./drag":5,"./follow":6,"./mouse-edges":7,"./pinch":8,"./snap":11,"./snap-zoom":10,"./utils":12,"./wheel":14}],14:[function(e,t,r){"use strict";var n=function(){function i(e,t){for(var r=0;rt&&(r[i]=this.hyphenate(r[i]).join("­"));return r.join("")},t.prototype.hyphenate=function(e){var t,r,i,n,o,a,s,l,u,h=[],c=[],f=e.toLowerCase(),p=Math.max,d=this.trie,m=[""];if(this.exceptions.hasOwnProperty(f))return e.match(this.exceptions[f]).slice(1);if(-1!==e.indexOf("­"))return[e];for(t=(e="_"+e+"_").toLowerCase().split(""),r=e.split(""),s=t.length,i=0;ithis.leftMin&&i@~]/g,"\\$&").replace(/\n/g,"A")}},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getCommonAncestor=function(e){for(var t=(1 /g,">").split(/\s+(?=(?:(?:[^"]*"){2})*[^"]*$)/);if(i.length<2)return c("",e,"",t);var n=[i.pop()];for(;1/g,"> ").trim()};var i=r(3),u=(i=i)&&i.__esModule?i:{default:i},h=r(0);function c(r,i,n,o){if(r.length&&(r+=" "),n.length&&(n=" "+n),/\[*\]/.test(i)){var e=i.replace(/=.*$/,"]"),a=""+r+e+n;if(f(document.querySelectorAll(a),o))i=e;else for(var s=document.querySelectorAll(""+r+e),l=0,t=s.length;l/.test(i)&&(e=i.replace(/>/,""),a=""+r+e+n,f(document.querySelectorAll(a),o)&&(i=e)),/:nth-child/.test(i)&&(e=i.replace(/nth-child/g,"nth-of-type"),a=""+r+e+n,f(document.querySelectorAll(a),o)&&(i=e)),/\.\S+\.\S+/.test(i)){for(var u=i.trim().split(".").slice(1).map(function(e){return"."+e}).sort(function(e,t){return e.length-t.length});u.length;){var h=i.replace(u.shift(),"").trim();if(!(a=(""+r+h+n).trim()).length||">"===a.charAt(0)||">"===a.charAt(a.length-1))break;f(document.querySelectorAll(a),o)&&(i=h)}if((u=i&&i.match(/\./g))&&2)(\S)/g,"$1 $2").trim()).split(" ").reverse().map(function(e,t){var r,i,n,o=0===t,t=e.split(":"),e=m(t,2),a=e[0],t=e[1],s=null,l=null;switch(!0){case/>/.test(a):l=function(t){return function(e){return e(t.parent)&&t.parent}};break;case/^\./.test(a):var u=a.substr(1).split(".");s=function(e){var t=e.attribs.class;return t&&u.every(function(e){return-1 "+l+":nth-child("+(a+1)+")",i.unshift(u)):console.warn("\n Element couldn't be matched through strict ignore pattern!\n ",h,r,l)}}(o,l,a,s)}l=l.parentNode,u=s.length}l===i&&(t=m(o,l,a),s.unshift(t));return s.join(" ")};var f=r(0),c={attribute:function(e){return-1<["style","data-reactid","data-react-checksum"].indexOf(e)}};function p(e,t,r,i,n){n=4\s*\(/gm,"{anonymous}()@"):"Unknown Stack Trace",t=n.console&&(n.console.warn||n.console.log);return t&&t.call(n.console,i,e),r.apply(this,arguments)}}var s="function"!=typeof Object.assign?function(e){if(e===h||null===e)throw new TypeError("Cannot convert undefined or null to object");for(var t=Object(e),r=1;rt[r]}):i.sort():i}function d(e,t){for(var r,i=t[0].toUpperCase()+t.slice(1),n=0;nc(a.y)?a.x:a.y,i.scale=s?function(e,t){return O(t[0],t[1],A)/O(e[0],e[1],A)}(s.pointers,t):1,i.rotation=s?function(e,t){return he(t[1],t[0],A)+he(e[1],e[0],A)}(s.pointers,t):0,i.maxPointers=!o.prevInput||i.pointers.length>o.prevInput.maxPointers?i.pointers.length:o.prevInput.maxPointers,function(e,t){var r,i,n,o=e.lastInterval||t,a=t.timeStamp-o.timeStamp;{var s,l;t.eventType!=v&&(rec(a.y)?a.x:a.y,s=ue(s,l),e.lastInterval=t):(r=o.velocity,i=o.velocityX,n=o.velocityY,s=o.direction)}t.velocity=r,t.velocityX=i,t.velocityY=n,t.direction=s}(o,i),n.element);V(i.srcEvent.target,l)&&(l=i.srcEvent.target),i.target=l,e.emit("hammer.input",r),e.recognize(r),e.session.prevInput=r}function ae(e){for(var t=[],r=0;r=c(t)?e<0?b:x:t<0?T:w}function O(e,t,r){var i=t[(r=r||ne)[0]]-e[r[0]],t=t[r[1]]-e[r[1]];return Math.sqrt(i*i+t*t)}function he(e,t,r){var i=t[(r=r||ne)[0]]-e[r[0]],t=t[r[1]]-e[r[1]];return 180*Math.atan2(t,i)/Math.PI}k.prototype={handler:function(){},init:function(){this.evEl&&t(this.element,this.evEl,this.domHandler),this.evTarget&&t(this.target,this.evTarget,this.domHandler),this.evWin&&t(Z(this.element),this.evWin,this.domHandler)},destroy:function(){this.evEl&&i(this.element,this.evEl,this.domHandler),this.evTarget&&i(this.target,this.evTarget,this.domHandler),this.evWin&&i(Z(this.element),this.evWin,this.domHandler)}};var ce={mousedown:_,mousemove:2,mouseup:g};function P(){this.evEl="mousedown",this.evWin="mousemove mouseup",this.pressed=!1,k.apply(this,arguments)}e(P,k,{handler:function(e){var t=ce[e.type];t&_&&0===e.button&&(this.pressed=!0),2&t&&1!==e.which&&(t=g),this.pressed&&(t&g&&(this.pressed=!1),this.callback(this.manager,t,{pointers:[e],changedPointers:[e],pointerType:te,srcEvent:e}))}});var fe={pointerdown:_,pointermove:2,pointerup:g,pointercancel:v,pointerout:v},pe={2:m,3:"pen",4:te,5:"kinect"},de="pointerdown",me="pointermove pointerup pointercancel";function _e(){this.evEl=de,this.evWin=me,k.apply(this,arguments),this.store=this.manager.session.pointerEvents=[]}n.MSPointerEvent&&!n.PointerEvent&&(de="MSPointerDown",me="MSPointerMove MSPointerUp MSPointerCancel"),e(_e,k,{handler:function(e){var t=this.store,r=!1,i=e.type.toLowerCase().replace("ms",""),i=fe[i],n=pe[e.pointerType]||e.pointerType,o=n==m,a=f(t,e.pointerId,"pointerId");i&_&&(0===e.button||o)?a<0&&(t.push(e),a=t.length-1):i&(g|v)&&(r=!0),a<0||(t[a]=e,this.callback(this.manager,i,{pointers:t,changedPointers:[e],pointerType:n,srcEvent:e}),r&&t.splice(a,1))}});var ge={touchstart:_,touchmove:2,touchend:g,touchcancel:v};function ve(){this.evTarget="touchstart",this.evWin="touchstart touchmove touchend touchcancel",this.started=!1,k.apply(this,arguments)}e(ve,k,{handler:function(e){var t,r=ge[e.type];r===_&&(this.started=!0),this.started&&(t=function(e,t){var r=p(e.touches),e=p(e.changedTouches);t&(g|v)&&(r=K(r.concat(e),"identifier",!0));return[r,e]}.call(this,e,r),r&(g|v)&&t[0].length-t[1].length==0&&(this.started=!1),this.callback(this.manager,r,{pointers:t[0],changedPointers:t[1],pointerType:m,srcEvent:e}))}});var ye={touchstart:_,touchmove:2,touchend:g,touchcancel:v};function be(){this.evTarget="touchstart touchmove touchend touchcancel",this.targetIds={},k.apply(this,arguments)}e(be,k,{handler:function(e){var t=ye[e.type],r=function(e,t){var r=p(e.touches),i=this.targetIds;if(t&(2|_)&&1===r.length)return i[r[0].identifier]=!0,[r,r];var n,o,a=p(e.changedTouches),s=[],l=this.target;if(o=r.filter(function(e){return V(e.target,l)}),t===_)for(n=0;nt.threshold&&n&t.direction},attrTest:function(e){return D.prototype.attrTest.call(this,e)&&(2&this.state||!(2&this.state)&&this.directionTest(e))},emit:function(e){this.pX=e.deltaX,this.pY=e.deltaY;var t=Ie(e.direction);t&&(e.additionalEvent=this.options.event+t),this._super.emit.call(this,e)}}),e(Fe,D,{defaults:{event:"pinch",threshold:0,pointers:2},getTouchAction:function(){return[R]},attrTest:function(e){return this._super.attrTest.call(this,e)&&(Math.abs(e.scale-1)>this.options.threshold||2&this.state)},emit:function(e){var t;1!==e.scale&&(t=e.scale<1?"in":"out",e.additionalEvent=this.options.event+t),this._super.emit.call(this,e)}}),e(Ne,I,{defaults:{event:"press",pointers:1,time:251,threshold:9},getTouchAction:function(){return["auto"]},process:function(e){var t=this.options,r=e.pointers.length===t.pointers,i=e.distancet.time;if(this._input=e,!i||!r||e.eventType&(g|v)&&!n)this.reset();else if(e.eventType&_)this.reset(),this._timer=U(function(){this.state=8,this.tryEmit()},t.time,this);else if(e.eventType&g)return 8;return 32},reset:function(){clearTimeout(this._timer)},emit:function(e){8===this.state&&(e&&e.eventType&g?this.manager.emit(this.options.event+"up",e):(this._input.timeStamp=j(),this.manager.emit(this.options.event,this._input)))}}),e(ze,D,{defaults:{event:"rotate",threshold:0,pointers:2},getTouchAction:function(){return[R]},attrTest:function(e){return this._super.attrTest.call(this,e)&&(Math.abs(e.rotation)>this.options.threshold||2&this.state)}}),e(Be,D,{defaults:{event:"swipe",threshold:10,velocity:.3,direction:E|S,pointers:1},getTouchAction:function(){return Le.prototype.getTouchAction.call(this)},attrTest:function(e){var t,r=this.options.direction;return r&(E|S)?t=e.overallVelocity:r&E?t=e.overallVelocityX:r&S&&(t=e.overallVelocityY),this._super.attrTest.call(this,e)&&r&e.offsetDirection&&e.distance>this.options.threshold&&e.maxPointers==this.options.pointers&&c(t)>this.options.velocity&&e.eventType&g},emit:function(e){var t=Ie(e.offsetDirection);t&&this.manager.emit(this.options.event+t,e),this.manager.emit(this.options.event,e)}}),e(je,I,{defaults:{event:"tap",pointers:1,taps:1,interval:300,time:250,threshold:9,posThreshold:10},getTouchAction:function(){return[Pe]},process:function(e){var t=this.options,r=e.pointers.length===t.pointers,i=e.distance=i.next.y&&i.next.y!==i.y){var s=i.x+(o-i.y)*(i.next.x-i.x)/(i.next.y-i.y);if(s<=n&&a=i.x&&i.x>=h&&n!==i.x&&be(or.x||i.x===r.x&&function(e,t){return xe(e.prev,e,t.prev)<0&&xe(t.next,e,e.next)<0}(r,i)))&&(r=i,f=l)),i=i.next,i!==u;);return r}(e,t);return r?(_e(e=ke(r,e),e.next),_e(r,r.next)):t}(l[n],r);return r}(e,t,h,r)),e.length>80*r){for(var f=i=e[0],p=n=e[1],d=r;d=g&&b&&b.z<=v;){if(y.x>=p&&y.x<=m&&y.y>=d&&y.y<=_&&y!==n&&y!==a&&be(s,h,l,c,u,f,y.x,y.y)&&0<=xe(y.prev,y,y.next))return;if(y=y.prevZ,b.x>=p&&b.x<=m&&b.y>=d&&b.y<=_&&b!==n&&b!==a&&be(s,h,l,c,u,f,b.x,b.y)&&0<=xe(b.prev,b,b.next))return;b=b.nextZ}for(;y&&y.z>=g;){if(y.x>=p&&y.x<=m&&y.y>=d&&y.y<=_&&y!==n&&y!==a&&be(s,h,l,c,u,f,y.x,y.y)&&0<=xe(y.prev,y,y.next))return;y=y.prevZ}for(;b&&b.z<=v;){if(b.x>=p&&b.x<=m&&b.y>=d&&b.y<=_&&b!==n&&b!==a&&be(s,h,l,c,u,f,b.x,b.y)&&0<=xe(b.prev,b,b.next))return;b=b.nextZ}return 1}(e,i,n,o):function(e){var t=e.prev,r=e,e=e.next;if(0<=xe(t,r,e))return;var i=t.x,n=r.x,o=e.x,a=t.y,s=r.y,l=e.y,u=i=u&&p.x<=c&&p.y>=h&&p.y<=f&&be(i,a,n,s,o,l,p.x,p.y)&&0<=xe(p.prev,p,p.next))return;p=p.next}return 1}(e))t.push(T.i/r|0),t.push(e.i/r|0),t.push(w.i/r|0),Pe(e),e=w.next,E=w.next;else if((e=w)===E){a?1===a?ge(e=function(e,t,r){var i=e;do{var n=i.prev,o=i.next.next}while(!Te(n,o)&&we(n,i,i.next,o)&&Ae(n,o)&&Ae(o,n)&&(t.push(n.i/r|0),t.push(i.i/r|0),t.push(o.i/r|0),Pe(i),Pe(i.next),i=e=o),i=i.next,i!==e);return _e(i)}(_e(e),t,r),t,r,i,n,o,2):2===a&&function(e,t,r,i,n,o){var a=e;do{for(var s,l=a.next.next;l!==a.prev;){if(a.i!==l.i&&function(e,t){return e.next.i!==t.i&&e.prev.i!==t.i&&!function(e,t){var r=e;do{if(r.i!==e.i&&r.next.i!==e.i&&r.i!==t.i&&r.next.i!==t.i&&we(r,r.next,e,t))return 1}while(r=r.next,r!==e);return}(e,t)&&(Ae(e,t)&&Ae(t,e)&&function(e,t){var r=e,i=!1,n=(e.x+t.x)/2,o=(e.y+t.y)/2;for(;r.y>o!=r.next.y>o&&r.next.y!==r.y&&n<(r.next.x-r.x)*(o-r.y)/(r.next.y-r.y)+r.x&&(i=!i),r=r.next,r!==e;);return i}(e,t)&&(xe(e.prev,e,t.prev)||xe(e,t.prev,t))||Te(e,t)&&0=Math.min(e.x,r.x)&&t.y<=Math.max(e.y,r.y)&&t.y>=Math.min(e.y,r.y)}function Se(e){return 0= 0x80 (not a basic code point)","invalid-input":"Invalid input"},p=g-1,y=Math.floor,b=String.fromCharCode;function x(e){throw RangeError(f[e])}function d(e,t){for(var r=e.length,i=[];r--;)i[r]=t(e[r]);return i}function m(e,t){var r=e.split("@"),i="",r=(1>>10&1023|55296),e=56320|1023&e),t+=b(e)}).join("")}function E(e,t){return e+22+75*(e<26)-((0!=t)<<5)}function S(e,t,r){var i=0;for(e=r?y(e/l):e>>1,e+=y(e/t);p*v>>1y((_-h)/o))&&x("overflow"),h+=s*o,!(s<(s=a<=f?1:f+v<=a?v:a-f));a+=g)o>y(_/(s=g-s))&&x("overflow"),o*=s;f=S(h-n,t=l.length+1,0==n),y(h/t)>_-c&&x("overflow"),c+=y(h/t),h%=t,l.splice(h++,0,c)}return w(l)}function k(e){for(var t,r,i,n,o,a,s,l,u,h,c=[],f=(e=T(e)).length,p=128,d=72,m=t=0;my((_-t)/(l=r+1))&&x("overflow"),t+=(n-p)*l,p=n,m=0;m_&&x("overflow"),s==p){for(o=t,a=g;!(o<(u=a<=d?1:d+v<=a?v:a-d));a+=g)c.push(b(E(u+(h=o-u)%(u=g-u),0))),o=y(h/u);c.push(b(E(o,0))),d=S(t,l,r==i),t=0,++r}++t,++p}return c.join("")}if(o={version:"1.3.2",ucs2:{decode:T,encode:w},decode:A,encode:k,toASCII:function(e){return m(e,function(e){return h.test(e)?"xn--"+k(e):e})},toUnicode:function(e){return m(e,function(e){return u.test(e)?A(e.slice(4).toLowerCase()):e})}},i&&t)if(e.exports==i)t.exports=o;else for(a in o)o.hasOwnProperty(a)&&(i[a]=o[a]);else r.punycode=o}),Ie=function(e){return"string"==typeof e},De=function(e){return"object"==typeof e&&null!==e},Le=function(e){return null===e},Fe=function(e){return null==e};function Ne(e,t,r,i){t=t||"&",r=r||"=";var n={};if("string"==typeof e&&0!==e.length){var o=/\+/g,t=(e=e.split(t),1e3),a=(i&&"number"==typeof i.maxKeys&&(t=i.maxKeys),e.length);0",'"',"`"," ","\r","\n","\t"]),Ve=["'"].concat(r),Ke=["%","/","?",";","#"].concat(Ve),Je=["/","?","#"],Ze=/^[+a-z0-9A-Z_-]{0,63}$/,Qe=/^([+a-z0-9A-Z_-]{0,63})(.*)$/,$e={javascript:!0,"javascript:":!0},et={javascript:!0,"javascript:":!0},tt={http:!0,https:!0,ftp:!0,gopher:!0,file:!0,"http:":!0,"https:":!0,"ftp:":!0,"gopher:":!0,"file:":!0};function rt(e,t,r){var i;return e&&De(e)&&e instanceof He?e:((i=new He).parse(e,t,r),i)}He.prototype.parse=function(e,t,r){if(!Ie(e))throw new TypeError("Parameter 'url' must be a string, not "+typeof e);var i=e.indexOf("?"),i=-1!==i&&i]*?)$/i.test(e)},hasProtocol:function(e){return/^[^/:]+:\//.test(this.toPosix(e))},getProtocol:function(e){ot(e),e=this.toPosix(e);var t="",r=/^file:\/\/\//.exec(e),i=/^[^/:]+:\/\//.exec(e),n=/^[^/:]+:\//.exec(e);return(r||i||n)&&(r=(null==r?void 0:r[0])||(null==i?void 0:i[0])||(null==n?void 0:n[0]),e=e.slice((t=r).length)),t},toAbsolute:function(e,t,r){return this.isDataUrl(e)?e:(t=at(this.toPosix(null!=t?t:R.ADAPTER.getBaseUrl())),r=at(this.toPosix(null!=r?r:this.rootname(t))),ot(e),(e=this.toPosix(e)).startsWith("/")?lt.join(r,e.slice(1)):this.isAbsolute(e)?e:this.join(t,e))},normalize:function(e){var t,r,i;return ot(e=this.toPosix(e)),0===e.length?".":(t="",r=e.startsWith("/"),this.hasProtocol(e)&&(t=this.rootname(e),e=e.slice(t.length)),i=e.endsWith("/"),0<(e=function(e,t){for(var r,i="",n=0,o=-1,a=0,s=0;s<=e.length;++s){if(s>16&255)/255,t[1]=(e>>8&255)/255,t[2]=(255&e)/255,t}function dt(e){e=e.toString(16);return"#"+("000000".substring(0,6-e.length)+e)}function mt(e){return"string"==typeof e&&"#"===(e=ft[e.toLowerCase()]||e)[0]&&(e=e.slice(1)),parseInt(e,16)}var _t=function(){for(var e=[],t=[],r=0;r<32;r++)t[e[r]=r]=r;e[$.BLEND_MODES.NORMAL_NPM]=$.BLEND_MODES.NORMAL,e[$.BLEND_MODES.ADD_NPM]=$.BLEND_MODES.ADD,e[$.BLEND_MODES.SCREEN_NPM]=$.BLEND_MODES.SCREEN,t[$.BLEND_MODES.NORMAL]=$.BLEND_MODES.NORMAL_NPM,t[$.BLEND_MODES.ADD]=$.BLEND_MODES.ADD_NPM,t[$.BLEND_MODES.SCREEN]=$.BLEND_MODES.SCREEN_NPM;var i=[];return i.push(t),i.push(e),i}();function gt(e,t){return _t[t?1:0][e]}function vt(e,t,r,i){return r=r||new Float32Array(4),i||void 0===i?(r[0]=e[0]*t,r[1]=e[1]*t,r[2]=e[2]*t):(r[0]=e[0],r[1]=e[1],r[2]=e[2]),r[3]=t,r}function yt(e,t){return 1===t?(255*t<<24)+e:0===t?0:(255*t<<24)+(((e>>16&255)*t+.5|0)<<16)+(((e>>8&255)*t+.5|0)<<8)+((255&e)*t+.5|0)}function bt(e,t,r,i){return(r=r||new Float32Array(4))[0]=(e>>16&255)/255,r[1]=(e>>8&255)/255,r[2]=(255&e)/255,!i&&void 0!==i||(r[0]*=t,r[1]*=t,r[2]*=t),r[3]=t,r}function xt(e,t){var r=6*e;if((t=(t=void 0===t?null:t)||new Uint16Array(r)).length!==r)throw new Error("Out buffer length is incorrect, got "+t.length+" and expected "+r);for(var i=0,n=0;i>>1)|e>>>2)|e>>>4)|e>>>8)|e>>>16)+1}function St(e){return!(e&e-1||!e)}function At(e){var t=(65535>>=t)?1:0)<<3;return(t|=r)|(r=(15<(e>>>=r)?1:0)<<2)|(r=(3<(e>>>=r)?1:0)<<1)|(e>>>=r)>>1}function kt(e,t,r){var i=e.length;if(!(i<=t||0===r)){for(var n=i-(r=i=this.x&&e=this.y&&t=i||Math.max(a.y,d.y,s.y,l.y)<=n||Math.min(a.y,d.y,s.y,l.y)>=o)&&(h=(t=u*(d.y-a.y))*r+(d=u*(a.x-d.x))*n,c=t*i+d*n,f=t*r+d*o,p=t*i+d*o,!(Math.max(h,c,f,p)<=t*a.x+d*a.y||Math.min(h,c,f,p)>=t*l.x+d*l.y)&&(f=(h=u*(a.y-s.y))*r+(c=u*(s.x-a.x))*n,p=h*i+c*n,t=h*r+c*o,d=h*i+c*o,!(Math.max(f,p,t,d)<=h*a.x+c*a.y||Math.min(f,p,t,d)>=h*l.x+c*l.y))))))):(u=(this.xe.right?e:this).right<=u)&&(this.ye.bottom?e:this).bottom)},Kt.prototype.pad=function(e,t){return void 0===e&&(e=0),void 0===t&&(t=e),this.x-=e,this.y-=t,this.width+=2*e,this.height+=2*t,this},Kt.prototype.fit=function(e){var t=Math.max(this.x,e.x),r=Math.min(this.x+this.width,e.x+e.width),i=Math.max(this.y,e.y),e=Math.min(this.y+this.height,e.y+e.height);return this.x=t,this.width=Math.max(r-t,0),this.y=i,this.height=Math.max(e-i,0),this},Kt.prototype.ceil=function(e,t){void 0===e&&(e=1),void 0===t&&(t=.001);var r=Math.ceil((this.x+this.width-t)*e)/e,i=Math.ceil((this.y+this.height-t)*e)/e;return this.x=Math.floor((this.x+t)*e)/e,this.y=Math.floor((this.y+t)*e)/e,this.width=r-this.x,this.height=i-this.y,this},Kt.prototype.enlarge=function(e){var t=Math.min(this.x,e.x),r=Math.max(this.x+this.width,e.x+e.width),i=Math.min(this.y,e.y),e=Math.max(this.y+this.height,e.y+e.height);return this.x=t,this.width=r-t,this.y=i,this.height=e-i,this},Kt.prototype.toString=function(){return"[@pixi/math:Rectangle x="+this.x+" y="+this.y+" width="+this.width+" height="+this.height+"]"},Kt);function Kt(e,t,r,i){void 0===e&&(e=0),void 0===t&&(t=0),void 0===r&&(r=0),void 0===i&&(i=0),this.x=Number(e),this.y=Number(t),this.width=Number(r),this.height=Number(i),this.type=$.SHAPES.RECT}Zt.prototype.clone=function(){return new Zt(this.x,this.y,this.radius)},Zt.prototype.contains=function(e,t){var r;return!(this.radius<=0)&&(r=this.radius*this.radius,e=this.x-e,t=this.y-t,(e*=e)+(t*=t)<=r)},Zt.prototype.getBounds=function(){return new w(this.x-this.radius,this.y-this.radius,2*this.radius,2*this.radius)},Zt.prototype.toString=function(){return"[@pixi/math:Circle x="+this.x+" y="+this.y+" radius="+this.radius+"]"};var Jt=Zt;function Zt(e,t,r){void 0===t&&(t=0),void 0===r&&(r=0),this.x=e=void 0===e?0:e,this.y=t,this.radius=r,this.type=$.SHAPES.CIRC}$t.prototype.clone=function(){return new $t(this.x,this.y,this.width,this.height)},$t.prototype.contains=function(e,t){return!(this.width<=0||this.height<=0)&&(e=(e-this.x)/this.width,t=(t-this.y)/this.height,(e*=e)+(t*=t)<=1)},$t.prototype.getBounds=function(){return new w(this.x-this.width,this.y-this.height,this.width,this.height)},$t.prototype.toString=function(){return"[@pixi/math:Ellipse x="+this.x+" y="+this.y+" width="+this.width+" height="+this.height+"]"};var Qt=$t;function $t(e,t,r,i){void 0===t&&(t=0),void 0===r&&(r=0),void 0===i&&(i=0),this.x=e=void 0===e?0:e,this.y=t,this.width=r,this.height=i,this.type=$.SHAPES.ELIP}tr.prototype.clone=function(){var e=new tr(this.points.slice());return e.closeStroke=this.closeStroke,e},tr.prototype.contains=function(e,t){for(var r=!1,i=this.points.length/2,n=0,o=i-1;n=this.x&&e<=this.x+this.width&&t>=this.y&&t<=this.y+this.height){var r=Math.max(0,Math.min(this.radius,Math.min(this.width,this.height)/2));if(t>=this.y+r&&t<=this.y+this.height-r||e>=this.x+r&&e<=this.x+this.width-r)return!0;var i=e-(this.x+r),n=t-(this.y+r),o=r*r;if(i*i+n*n<=o)return!0;if((i=e-(this.x+this.width-r))*i+n*n<=o)return!0;if(i*i+(n=t-(this.y+this.height-r))*n<=o)return!0;if((i=e-(this.x+r))*i+n*n<=o)return!0}return!1},ir.prototype.toString=function(){return"[@pixi/math:RoundedRectangle x="+this.x+" y="+this.y+"width="+this.width+" height="+this.height+" radius="+this.radius+"]"};var rr=ir;function ir(e,t,r,i,n){void 0===t&&(t=0),void 0===r&&(r=0),void 0===i&&(i=0),void 0===n&&(n=20),this.x=e=void 0===e?0:e,this.y=t,this.width=r,this.height=i,this.radius=n,this.type=$.SHAPES.RREC}or.prototype.clone=function(e,t){return new or(e=void 0===e?this.cb:e,t=void 0===t?this.scope:t,this._x,this._y)},or.prototype.set=function(e,t){return void 0===e&&(e=0),void 0===t&&(t=e),this._x===e&&this._y===t||(this._x=e,this._y=t,this.cb.call(this.scope)),this},or.prototype.copyFrom=function(e){return this._x===e.x&&this._y===e.y||(this._x=e.x,this._y=e.y,this.cb.call(this.scope)),this},or.prototype.copyTo=function(e){return e.set(this._x,this._y),e},or.prototype.equals=function(e){return e.x===this._x&&e.y===this._y},or.prototype.toString=function(){return"[@pixi/math:ObservablePoint x=0 y=0 scope="+this.scope+"]"},Object.defineProperty(or.prototype,"x",{get:function(){return this._x},set:function(e){this._x!==e&&(this._x=e,this.cb.call(this.scope))},enumerable:!1,configurable:!0}),Object.defineProperty(or.prototype,"y",{get:function(){return this._y},set:function(e){this._y!==e&&(this._y=e,this.cb.call(this.scope))},enumerable:!1,configurable:!0});var nr=or;function or(e,t,r,i){void 0===i&&(i=0),this._x=r=void 0===r?0:r,this._y=i,this.cb=e,this.scope=t}sr.prototype.fromArray=function(e){this.a=e[0],this.b=e[1],this.c=e[3],this.d=e[4],this.tx=e[2],this.ty=e[5]},sr.prototype.set=function(e,t,r,i,n,o){return this.a=e,this.b=t,this.c=r,this.d=i,this.tx=n,this.ty=o,this},sr.prototype.toArray=function(e,t){this.array||(this.array=new Float32Array(9));t=t||this.array;return e?(t[0]=this.a,t[1]=this.b,t[2]=0,t[3]=this.c,t[4]=this.d,t[5]=0,t[6]=this.tx,t[7]=this.ty):(t[0]=this.a,t[1]=this.c,t[2]=this.tx,t[3]=this.b,t[4]=this.d,t[5]=this.ty,t[6]=0,t[7]=0),t[8]=1,t},sr.prototype.apply=function(e,t){t=t||new ee;var r=e.x,e=e.y;return t.x=this.a*r+this.c*e+this.tx,t.y=this.b*r+this.d*e+this.ty,t},sr.prototype.applyInverse=function(e,t){t=t||new ee;var r=1/(this.a*this.d+this.c*-this.b),i=e.x,e=e.y;return t.x=this.d*r*i+-this.c*r*e+(this.ty*this.c-this.tx*this.d)*r,t.y=this.a*r*e+-this.b*r*i+(-this.ty*this.a+this.tx*this.b)*r,t},sr.prototype.translate=function(e,t){return this.tx+=e,this.ty+=t,this},sr.prototype.scale=function(e,t){return this.a*=e,this.d*=t,this.c*=e,this.b*=t,this.tx*=e,this.ty*=t,this},sr.prototype.rotate=function(e){var t=Math.cos(e),e=Math.sin(e),r=this.a,i=this.c,n=this.tx;return this.a=r*t-this.b*e,this.b=r*e+this.b*t,this.c=i*t-this.d*e,this.d=i*e+this.d*t,this.tx=n*t-this.ty*e,this.ty=n*e+this.ty*t,this},sr.prototype.append=function(e){var t=this.a,r=this.b,i=this.c,n=this.d;return this.a=e.a*t+e.b*i,this.b=e.a*r+e.b*n,this.c=e.c*t+e.d*i,this.d=e.c*r+e.d*n,this.tx=e.tx*t+e.ty*i+this.tx,this.ty=e.tx*r+e.ty*n+this.ty,this},sr.prototype.setTransform=function(e,t,r,i,n,o,a,s,l){return this.a=Math.cos(a+l)*n,this.b=Math.sin(a+l)*n,this.c=-Math.sin(a-s)*o,this.d=Math.cos(a-s)*o,this.tx=e-(r*this.a+i*this.c),this.ty=t-(r*this.b+i*this.d),this},sr.prototype.prepend=function(e){var t,r,i=this.tx;return 1===e.a&&0===e.b&&0===e.c&&1===e.d||(t=this.a,r=this.c,this.a=t*e.a+this.b*e.c,this.b=t*e.b+this.b*e.d,this.c=r*e.a+this.d*e.c,this.d=r*e.b+this.d*e.d),this.tx=i*e.a+this.ty*e.c+e.tx,this.ty=i*e.b+this.ty*e.d+e.ty,this},sr.prototype.decompose=function(e){var t=this.a,r=this.b,i=this.c,n=this.d,o=e.pivot,a=-Math.atan2(-i,n),s=Math.atan2(r,t),l=Math.abs(a+s);return l<1e-5||Math.abs(Ht-l)<1e-5?(e.rotation=s,e.skew.x=e.skew.y=0):(e.rotation=0,e.skew.x=a,e.skew.y=s),e.scale.x=Math.sqrt(t*t+r*r),e.scale.y=Math.sqrt(i*i+n*n),e.position.x=this.tx+(o.x*t+o.y*i),e.position.y=this.ty+(o.x*r+o.y*n),e},sr.prototype.invert=function(){var e=this.a,t=this.b,r=this.c,i=this.d,n=this.tx,o=e*i-t*r;return this.a=i/o,this.b=-t/o,this.c=-r/o,this.d=e/o,this.tx=(r*this.ty-i*n)/o,this.ty=-(e*this.ty-t*n)/o,this},sr.prototype.identity=function(){return this.a=1,this.b=0,this.c=0,this.d=1,this.tx=0,this.ty=0,this},sr.prototype.clone=function(){var e=new sr;return e.a=this.a,e.b=this.b,e.c=this.c,e.d=this.d,e.tx=this.tx,e.ty=this.ty,e},sr.prototype.copyTo=function(e){return e.a=this.a,e.b=this.b,e.c=this.c,e.d=this.d,e.tx=this.tx,e.ty=this.ty,e},sr.prototype.copyFrom=function(e){return this.a=e.a,this.b=e.b,this.c=e.c,this.d=e.d,this.tx=e.tx,this.ty=e.ty,this},sr.prototype.toString=function(){return"[@pixi/math:Matrix a="+this.a+" b="+this.b+" c="+this.c+" d="+this.d+" tx="+this.tx+" ty="+this.ty+"]"},Object.defineProperty(sr,"IDENTITY",{get:function(){return new sr},enumerable:!1,configurable:!0}),Object.defineProperty(sr,"TEMP_MATRIX",{get:function(){return new sr},enumerable:!1,configurable:!0});var ar=sr;function sr(e,t,r,i,n,o){void 0===e&&(e=1),void 0===t&&(t=0),void 0===r&&(r=0),void 0===i&&(i=1),void 0===n&&(n=0),void 0===o&&(o=0),this.array=null,this.a=e,this.b=t,this.c=r,this.d=i,this.tx=n,this.ty=o}var lr=[1,1,0,-1,-1,-1,0,1,1,1,0,-1,-1,-1,0,1],ur=[0,1,1,1,0,-1,-1,-1,0,1,1,1,0,-1,-1,-1],hr=[0,-1,-1,-1,0,1,1,1,0,1,1,1,0,-1,-1,-1],cr=[1,1,0,-1,-1,-1,0,1,-1,-1,0,1,1,1,0,-1],fr=[],pr=[],dr=Math.sign;for(var mr=0;mr<16;mr++){var _r=[];fr.push(_r);for(var gr=0;gr<16;gr++)for(var vr=dr(lr[mr]*lr[gr]+hr[mr]*ur[gr]),yr=dr(ur[mr]*lr[gr]+cr[mr]*ur[gr]),br=dr(lr[mr]*hr[gr]+hr[mr]*cr[gr]),xr=dr(ur[mr]*hr[gr]+cr[mr]*cr[gr]),Tr=0;Tr<16;Tr++)if(lr[Tr]===vr&&ur[Tr]===yr&&hr[Tr]===br&&cr[Tr]===xr){_r.push(Tr);break}}for(mr=0;mr<16;mr++){var wr=new ar;wr.set(lr[mr],ur[mr],hr[mr],cr[mr],0,0),pr.push(wr)}var Er={E:0,SE:1,S:2,SW:3,W:4,NW:5,N:6,NE:7,MIRROR_VERTICAL:8,MAIN_DIAGONAL:10,MIRROR_HORIZONTAL:12,REVERSE_DIAGONAL:14,uX:function(e){return lr[e]},uY:function(e){return ur[e]},vX:function(e){return hr[e]},vY:function(e){return cr[e]},inv:function(e){return 8&e?15&e:7&-e},add:function(e,t){return fr[e][t]},sub:function(e,t){return fr[e][Er.inv(t)]},rotate180:function(e){return 4^e},isVertical:function(e){return 2==(3&e)},byDirection:function(e,t){return 2*Math.abs(e)<=Math.abs(t)?0<=t?Er.S:Er.N:2*Math.abs(t)<=Math.abs(e)?0this.maxX||this.minY>this.maxY},Or.prototype.clear=function(){this.minX=1/0,this.minY=1/0,this.maxX=-1/0,this.maxY=-1/0},Or.prototype.getRectangle=function(e){return this.minX>this.maxX||this.minY>this.maxY?w.EMPTY:((e=e||new w(0,0,1,1)).x=this.minX,e.y=this.minY,e.width=this.maxX-this.minX,e.height=this.maxY-this.minY,e)},Or.prototype.addPoint=function(e){this.minX=Math.min(this.minX,e.x),this.maxX=Math.max(this.maxX,e.x),this.minY=Math.min(this.minY,e.y),this.maxY=Math.max(this.maxY,e.y)},Or.prototype.addPointMatrix=function(e,t){var r=e.a,i=e.b,n=e.c,o=e.d,a=e.tx,e=e.ty,r=r*t.x+n*t.y+a,n=i*t.x+o*t.y+e;this.minX=Math.min(this.minX,r),this.maxX=Math.max(this.maxX,r),this.minY=Math.min(this.minY,n),this.maxY=Math.max(this.maxY,n)},Or.prototype.addQuad=function(e){var t=this.minX,r=this.minY,i=this.maxX,n=this.maxY,o=e[0],a=e[1],t=oi?e.maxX:i,this.maxY=e.maxY>n?e.maxY:n},Or.prototype.addBoundsMask=function(e,t){var r,i,n,o=(e.minX>t.minX?e:t).minX,a=(e.minY>t.minY?e:t).minY,s=(e.maxXt.x?e.minX:t.x,a=e.minY>t.y?e.minY:t.y,s=e.maxXr?this.maxX:r,this.minY=this.minYi?this.maxY:i};var kr=Or;function Or(){this.minX=1/0,this.minY=1/0,this.maxX=-1/0,this.maxY=-1/0,this.rect=null,this.updateID=-1}var Pr=function(e,t){return(Pr=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])})(e,t)};function Rr(e,t){function r(){this.constructor=e}Pr(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)}Rr(l,Cr=re),l.mixin=function(e){for(var t=Object.keys(e),r=0;rthis.children.length)throw new Error(e+"addChildAt: The index "+t+" supplied is out of bounds "+this.children.length);return e.parent&&e.parent.removeChild(e),(e.parent=this).sortDirty=!0,e.transform._parentID=-1,this.children.splice(t,0,e),this._boundsID++,this.onChildrenChange(t),e.emit("added",this),this.emit("childAdded",e,this,t),e},u.prototype.swapChildren=function(e,t){var r,i;e!==t&&(r=this.getChildIndex(e),i=this.getChildIndex(t),this.children[r]=t,this.children[i]=e,this.onChildrenChange(r=this.children.length)throw new Error("The index "+t+" supplied is out of bounds "+this.children.length);var r=this.getChildIndex(e);kt(this.children,r,1),this.children.splice(t,0,e),this.onChildrenChange(t)},u.prototype.getChildAt=function(e){if(e<0||e>=this.children.length)throw new Error("getChildAt: Index ("+e+") does not exist.");return this.children[e]},u.prototype.removeChild=function(){for(var e=arguments,t=[],r=0;rt.priority){e.connect(r);break}t=(r=t).next}e.previous||e.connect(r)}else e.connect(r);return this._startIfPossible(),this},h.prototype.remove=function(e,t){for(var r=this._head.next;r;)r=r.match(e,t)?r.destroy():r.next;return this._head.next||this._cancelIfNeeded(),this},Object.defineProperty(h.prototype,"count",{get:function(){if(!this._head)return 0;for(var e=0,t=this._head;t=t.next;)e++;return e},enumerable:!1,configurable:!0}),h.prototype.start=function(){this.started||(this.started=!0,this._requestIfNeeded())},h.prototype.stop=function(){this.started&&(this.started=!1,this._cancelIfNeeded())},h.prototype.destroy=function(){if(!this._protected){this.stop();for(var e=this._head.next;e;)e=e.destroy(!0);this._head.destroy(),this._head=null}},h.prototype.update=function(e){var t;if((e=void 0===e?performance.now():e)>this.lastTime){if((t=this.elapsedMS=e-this.lastTime)>this._maxElapsedMS&&(t=this._maxElapsedMS),t*=this.speed,this._minElapsedMS){var r=e-this._lastFrame|0;if(r)?\s*()]*-->)?\s*\]*(?:\s(width|height)=('|")(\d*(?:\.\d+)?)(?:px)?('|"))[^>]*(?:\s(width|height)=('|")(\d*(?:\.\d+)?)(?:px)?('|"))[^>]*>/i;var yi,d=bi;function bi(e,t){var r=this;return t=t||{},(r=yi.call(this,R.ADAPTER.createCanvas())||this)._width=0,r._height=0,r.svg=e,r.scale=t.scale||1,r._overrideWidth=t.width,r._overrideHeight=t.height,r._resolve=null,r._crossorigin=t.crossorigin,r._load=null,!1!==t.autoLoad&&r.load(),r}c(wi,xi=hi),wi.prototype.update=function(e){var t;this.destroyed||(t=Wr.shared.elapsedMS*this.source.playbackRate,this._msToNextUpdate=Math.floor(this._msToNextUpdate-t),(!this._updateFPS||this._msToNextUpdate<=0)&&(xi.prototype.update.call(this),this._msToNextUpdate=this._updateFPS?Math.floor(1e3/this._updateFPS):0))},wi.prototype.load=function(){var t,r=this;return this._load||(((t=this.source).readyState===t.HAVE_ENOUGH_DATA||t.readyState===t.HAVE_FUTURE_DATA)&&t.width&&t.height&&(t.complete=!0),t.addEventListener("play",this._onPlayStart.bind(this)),t.addEventListener("pause",this._onPlayStop.bind(this)),this._isSourceReady()?this._onCanPlay():(t.addEventListener("canplay",this._onCanPlay),t.addEventListener("canplaythrough",this._onCanPlay),t.addEventListener("error",this._onError,!0)),this._load=new Promise(function(e){r.valid?e(r):(r._resolve=e,t.load())})),this._load},wi.prototype._onError=function(e){this.source.removeEventListener("error",this._onError,!0),this.onError.emit(e)},wi.prototype._isSourcePlaying=function(){var e=this.source;return 0this.baseTexture.width,a=r+n>this.baseTexture.height;if(o||a)throw t="X: "+t+" + "+i+" = "+(t+i)+" > "+this.baseTexture.width,r="Y: "+r+" + "+n+" = "+(r+n)+" > "+this.baseTexture.height,new Error("Texture Error: frame does not fit inside the base Texture dimensions: "+t+" "+(o&&a?"and":"or")+" "+r);this.valid=i&&n&&this.baseTexture.valid,this.trim||this.rotate||(this.orig=e),this.valid&&this.updateUvs()},enumerable:!1,configurable:!0}),Object.defineProperty(m.prototype,"rotate",{get:function(){return this._rotate},set:function(e){this._rotate=e,this.valid&&this.updateUvs()},enumerable:!1,configurable:!0}),Object.defineProperty(m.prototype,"width",{get:function(){return this.orig.width},enumerable:!1,configurable:!0}),Object.defineProperty(m.prototype,"height",{get:function(){return this.orig.height},enumerable:!1,configurable:!0}),m.prototype.castToBaseTexture=function(){return this.baseTexture},Object.defineProperty(m,"EMPTY",{get:function(){return m._EMPTY||(Bi(m._EMPTY=new m(new C)),Bi(m._EMPTY.baseTexture)),m._EMPTY},enumerable:!1,configurable:!0}),Object.defineProperty(m,"WHITE",{get:function(){var e,t;return m._WHITE||(t=(e=R.ADAPTER.createCanvas(16,16)).getContext("2d"),e.width=16,e.height=16,t.fillStyle="white",t.fillRect(0,0,16,16),Bi(m._WHITE=new m(C.from(e))),Bi(m._WHITE.baseTexture)),m._WHITE},enumerable:!1,configurable:!0});var ji,te=m;function m(e,t,r,i,n,o){var a=ji.call(this)||this;if(a.noFrame=!1,t||(a.noFrame=!0,t=new w(0,0,1,1)),e instanceof m&&(e=e.baseTexture),a.baseTexture=e,a._frame=t,a.trim=i,a.valid=!1,a._uvs=zi,a.uvMatrix=null,a.orig=r||t,a._rotate=Number(n||0),!0===n)a._rotate=2;else if(a._rotate%2!=0)throw new Error("attempt to use diamond-shaped UVs. If you are sure, set rotation manually");return a.defaultAnchor=o?new ee(o.x,o.y):new ee(0,0),a._updateID=0,a.textureCacheIds=[],e.valid?a.noFrame?e.valid&&a.onBaseTextureUpdated(e):a.frame=t:e.once("loaded",a.onBaseTextureUpdated,a),a.noFrame&&e.on("update",a.onBaseTextureUpdated,a),a}c(Xi,Ui=te),Object.defineProperty(Xi.prototype,"framebuffer",{get:function(){return this.baseTexture.framebuffer},enumerable:!1,configurable:!0}),Object.defineProperty(Xi.prototype,"multisample",{get:function(){return this.framebuffer.multisample},set:function(e){this.framebuffer.multisample=e},enumerable:!1,configurable:!0}),Xi.prototype.resize=function(e,t,r){void 0===r&&(r=!0);var i=this.baseTexture.resolution,e=Math.round(e*i)/i,t=Math.round(t*i)/i;this.valid=0>>0,1=$.ENV.WEBGL2?e.getContext("webgl2",t):r)this.webGLVersion=2;else if(this.webGLVersion=1,!(r=e.getContext("webgl",t)||e.getContext("experimental-webgl",t)))throw new Error("This browser does not support WebGL. Try using the canvas renderer");return this.gl=r,this.getExtensions(),this.gl},Sn.prototype.getExtensions=function(){var e=this.gl,t={anisotropicFiltering:e.getExtension("EXT_texture_filter_anisotropic"),floatTextureLinear:e.getExtension("OES_texture_float_linear"),s3tc:e.getExtension("WEBGL_compressed_texture_s3tc"),s3tc_sRGB:e.getExtension("WEBGL_compressed_texture_s3tc_srgb"),etc:e.getExtension("WEBGL_compressed_texture_etc"),etc1:e.getExtension("WEBGL_compressed_texture_etc1"),pvrtc:e.getExtension("WEBGL_compressed_texture_pvrtc")||e.getExtension("WEBKIT_WEBGL_compressed_texture_pvrtc"),atc:e.getExtension("WEBGL_compressed_texture_atc"),astc:e.getExtension("WEBGL_compressed_texture_astc")};1===this.webGLVersion?Object.assign(this.extensions,t,{drawBuffers:e.getExtension("WEBGL_draw_buffers"),depthTexture:e.getExtension("WEBGL_depth_texture"),loseContext:e.getExtension("WEBGL_lose_context"),vertexArrayObject:e.getExtension("OES_vertex_array_object")||e.getExtension("MOZ_OES_vertex_array_object")||e.getExtension("WEBKIT_OES_vertex_array_object"),uint32ElementIndex:e.getExtension("OES_element_index_uint"),floatTexture:e.getExtension("OES_texture_float"),floatTextureLinear:e.getExtension("OES_texture_float_linear"),textureHalfFloat:e.getExtension("OES_texture_half_float"),textureHalfFloatLinear:e.getExtension("OES_texture_half_float_linear")}):2===this.webGLVersion&&Object.assign(this.extensions,t,{colorBufferFloat:e.getExtension("EXT_color_buffer_float")})},Sn.prototype.handleContextLost=function(e){e.preventDefault()},Sn.prototype.handleContextRestored=function(){this.renderer.runners.contextChange.emit(this.gl)},Sn.prototype.destroy=function(){var e=this.renderer.view;this.renderer=null,e.removeEventListener("webglcontextlost",this.handleContextLost),e.removeEventListener("webglcontextrestored",this.handleContextRestored),this.gl.useProgram(null),this.extensions.loseContext&&this.extensions.loseContext.loseContext()},Sn.prototype.postrender=function(){this.renderer.renderingToScreen&&this.gl.flush()},Sn.prototype.validateContext=function(e){var t=e.getContextAttributes(),r="WebGL2RenderingContext"in globalThis&&e instanceof globalThis.WebGL2RenderingContext,t=(r&&(this.webGLVersion=2),t&&!t.stencil&&console.warn("Provided WebGL context does not have a stencil buffer, masks may not render correctly"),r||!!e.getExtension("OES_element_index_uint"));(this.supports.uint32Indices=t)||console.warn("Provided WebGL context does not support 32 index buffer, complex graphics may not render correctly")},Sn);function Sn(e){this.renderer=e,this.webGLVersion=1,this.extensions={},this.supports={uint32Indices:!1},this.handleContextLost=this.handleContextLost.bind(this),this.handleContextRestored=this.handleContextRestored.bind(this),e.view.addEventListener("webglcontextlost",this.handleContextLost,!1),e.view.addEventListener("webglcontextrestored",this.handleContextRestored,!1)}var An=function(e){this.framebuffer=e,this.stencil=null,this.dirtyId=-1,this.dirtyFormat=-1,this.dirtySize=-1,this.multisample=$.MSAA_QUALITY.NONE,this.msaaBuffer=null,this.blitFramebuffer=null,this.mipLevel=0},kn=new w,On=(Pn.prototype.contextChange=function(){var t,e,r=this.gl=this.renderer.gl;this.CONTEXT_UID=this.renderer.CONTEXT_UID,this.current=this.unknownFramebuffer,this.viewport=new w,this.hasMRT=!0,this.writeDepthTexture=!0,this.disposeAll(!0),1===this.renderer.context.webGLVersion?(t=this.renderer.context.extensions.drawBuffers,e=this.renderer.context.extensions.depthTexture,R.PREFER_ENV===$.ENV.WEBGL_LEGACY&&(e=t=null),t?r.drawBuffers=function(e){return t.drawBuffersWEBGL(e)}:(this.hasMRT=!1,r.drawBuffers=function(){}),e||(this.writeDepthTexture=!1)):this.msaaSamples=r.getInternalformatParameter(r.RENDERBUFFER,r.RGBA8,r.SAMPLES)},Pn.prototype.bind=function(e,t,r){void 0===r&&(r=0);var i=this.gl;if(e){var n=e.glFramebuffers[this.CONTEXT_UID]||this.initFramebuffer(e);this.current!==e&&(this.current=e,i.bindFramebuffer(i.FRAMEBUFFER,n.framebuffer)),n.mipLevel!==r&&(e.dirtyId++,e.dirtyFormat++,n.mipLevel=r),n.dirtyId!==e.dirtyId&&(n.dirtyId=e.dirtyId,n.dirtyFormat!==e.dirtyFormat?(n.dirtyFormat=e.dirtyFormat,n.dirtySize=e.dirtySize,this.updateFramebuffer(e,r)):n.dirtySize!==e.dirtySize&&(n.dirtySize=e.dirtySize,this.resizeFramebuffer(e)));for(var o,a,s=0;s>r,a=t.height>>r,n=o/t.width,this.setViewport(t.x*n,t.y*n,o,a)):(o=e.width>>r,a=e.height>>r,this.setViewport(0,0,o,a))}else this.current&&(this.current=null,i.bindFramebuffer(i.FRAMEBUFFER,null)),t?this.setViewport(t.x,t.y,t.width,t.height):this.setViewport(0,0,this.renderer.width,this.renderer.height)},Pn.prototype.setViewport=function(e,t,r,i){var n=this.viewport;e=Math.round(e),t=Math.round(t),r=Math.round(r),i=Math.round(i),n.width===r&&n.height===i&&n.x===e&&n.y===t||(n.x=e,n.y=t,n.width=r,n.height=i,this.gl.viewport(e,t,r,i))},Object.defineProperty(Pn.prototype,"size",{get:function(){return this.current?{x:0,y:0,width:this.current.width,height:this.current.height}:{x:0,y:0,width:this.renderer.width,height:this.renderer.height}},enumerable:!1,configurable:!0}),Pn.prototype.clear=function(e,t,r,i,n){void 0===n&&(n=$.BUFFER_BITS.COLOR|$.BUFFER_BITS.DEPTH);var o=this.gl;o.clearColor(e,t,r,i),o.clear(n)},Pn.prototype.initFramebuffer=function(e){var t=this.gl,t=new An(t.createFramebuffer());return t.multisample=this.detectSamples(e.multisample),e.glFramebuffers[this.CONTEXT_UID]=t,this.managedFramebuffers.push(e),e.disposeRunner.add(this),t},Pn.prototype.resizeFramebuffer=function(e){var t=this.gl,r=e.glFramebuffers[this.CONTEXT_UID],i=(r.msaaBuffer&&(t.bindRenderbuffer(t.RENDERBUFFER,r.msaaBuffer),t.renderbufferStorageMultisample(t.RENDERBUFFER,r.multisample,t.RGBA8,e.width,e.height)),r.stencil&&(t.bindRenderbuffer(t.RENDERBUFFER,r.stencil),r.msaaBuffer?t.renderbufferStorageMultisample(t.RENDERBUFFER,r.multisample,t.DEPTH24_STENCIL8,e.width,e.height):t.renderbufferStorage(t.RENDERBUFFER,t.DEPTH_STENCIL,e.width,e.height)),e.colorTextures),n=i.length;t.drawBuffers||(n=Math.min(n,1));for(var o=0;o=$.ENV.WEBGL2?e.getContext("webgl2",{}):t)||((t=e.getContext("webgl",{})||e.getContext("experimental-webgl",{}))?t.getExtension("WEBGL_draw_buffers"):t=null),Un=t),Un}function Xn(e,t,r){return"precision"!==e.substring(0,9)?"precision "+(t===$.PRECISION.HIGH&&r!==$.PRECISION.HIGH?$.PRECISION.MEDIUM:t)+" float;\n"+e:r!==$.PRECISION.HIGH&&"precision highp"===e.substring(0,15)?e.replace("precision highp","precision mediump"):e}var Hn={float:1,vec2:2,vec3:3,vec4:4,int:1,ivec2:2,ivec3:3,ivec4:4,uint:1,uvec2:2,uvec3:3,uvec4:4,bool:1,bvec2:2,bvec3:3,bvec4:4,mat2:4,mat3:9,mat4:16,sampler2D:1};function Yn(e){return Hn[e]}var Wn=null,qn={FLOAT:"float",FLOAT_VEC2:"vec2",FLOAT_VEC3:"vec3",FLOAT_VEC4:"vec4",INT:"int",INT_VEC2:"ivec2",INT_VEC3:"ivec3",INT_VEC4:"ivec4",UNSIGNED_INT:"uint",UNSIGNED_INT_VEC2:"uvec2",UNSIGNED_INT_VEC3:"uvec3",UNSIGNED_INT_VEC4:"uvec4",BOOL:"bool",BOOL_VEC2:"bvec2",BOOL_VEC3:"bvec3",BOOL_VEC4:"bvec4",FLOAT_MAT2:"mat2",FLOAT_MAT3:"mat3",FLOAT_MAT4:"mat4",SAMPLER_2D:"sampler2D",INT_SAMPLER_2D:"sampler2D",UNSIGNED_INT_SAMPLER_2D:"sampler2D",SAMPLER_CUBE:"samplerCube",INT_SAMPLER_CUBE:"samplerCube",UNSIGNED_INT_SAMPLER_CUBE:"samplerCube",SAMPLER_2D_ARRAY:"sampler2DArray",INT_SAMPLER_2D_ARRAY:"sampler2DArray",UNSIGNED_INT_SAMPLER_2D_ARRAY:"sampler2DArray"};function Vn(e,t){if(!Wn){var r=Object.keys(qn);Wn={};for(var i=0;i>=1,r++;this.stateId=e.data}for(r=0;rthis.checkCountMax&&(this.checkCount=0,this.run())))},Qo.prototype.run=function(){for(var e=this.renderer.texture,t=e.managedTextures,r=!1,i=0;ithis.maxIdle&&(e.destroyTexture(n,!0),r=!(t[i]=null))}if(r){for(var o=0,i=0;i=e.data.byteLength?r.bufferSubData(e.type,0,e.data):(t=e.static?r.STATIC_DRAW:r.DYNAMIC_DRAW,i.byteLength=e.data.byteLength,r.bufferData(e.type,e.data,t)))},ua.prototype.dispose=function(e,t){var r,i;this.managedBuffers[e.id]&&(delete this.managedBuffers[e.id],r=e._glBuffers[this.CONTEXT_UID],i=this.gl,e.disposeRunner.remove(this),r&&(t||i.deleteBuffer(r.buffer),delete e._glBuffers[this.CONTEXT_UID]))},ua.prototype.disposeAll=function(e){for(var t=Object.keys(this.managedBuffers),r=0;r=$.MSAA_QUALITY.HIGH?this.multisample=$.MSAA_QUALITY.HIGH:e>=$.MSAA_QUALITY.MEDIUM?this.multisample=$.MSAA_QUALITY.MEDIUM:e>=$.MSAA_QUALITY.LOW?this.multisample=$.MSAA_QUALITY.LOW:this.multisample=$.MSAA_QUALITY.NONE},fa.prototype.addSystem=function(e,t){var r,i=new e(this);if(this[t])throw new Error('Whoops! The name "'+t+'" is already in use');for(r in this[t]=i,this.runners)this.runners[r].add(i);return this},fa.prototype.render=function(e,t){var r,i,n,o;t&&(o=t instanceof Gi?(Mt("6.0.0","Renderer#render arguments changed, use options instead."),r=t,i=arguments[2],n=arguments[3],arguments[4]):(r=t.renderTexture,i=t.clear,n=t.transform,t.skipUpdateTransform)),this.renderingToScreen=!r,this.runners.prerender.emit(),this.emit("prerender"),this.projection.transform=n,this.context.isLost||(r||(this._lastObjectRendered=e),o||(t=e.enableTempParent(),e.updateTransform(),e.disableTempParent(t)),this.renderTexture.bind(r),this.batch.currentRenderer.start(),(void 0!==i?i:this.clearBeforeRender)&&this.renderTexture.clear(),e.render(this),this.batch.currentRenderer.flush(),r&&r.baseTexture.update(),this.runners.postrender.emit(),this.projection.transform=null,this.emit("postrender"))},fa.prototype.generateTexture=function(e,t,r,i){e=ha.prototype.generateTexture.call(this,e,t=void 0===t?{}:t,r,i);return this.framebuffer.blit(),e},fa.prototype.resize=function(e,t){ha.prototype.resize.call(this,e,t),this.runners.resize.emit(this.screen.height,this.screen.width)},fa.prototype.reset=function(){return this.runners.reset.emit(),this},fa.prototype.clear=function(){this.renderTexture.bind(),this.renderTexture.clear()},fa.prototype.destroy=function(e){for(var t in this.runners.destroy.emit(),this.runners)this.runners[t].destroy();ha.prototype.destroy.call(this,e),this.gl=null},Object.defineProperty(fa.prototype,"extract",{get:function(){return Mt("6.0.0","Renderer#extract has been deprecated, please use Renderer#plugins.extract instead."),this.plugins.extract},enumerable:!1,configurable:!0}),fa.registerPlugin=function(e,t){Mt("6.5.0","Renderer.registerPlugin() has been deprecated, please use extensions.add() instead."),Ur.add({name:e,type:$.ExtensionType.RendererPlugin,ref:t})},fa.__plugins={};var ha,ca=fa;function fa(e){var t=ha.call(this,$.RENDERER_TYPE.WEBGL,e)||this;return e=t.options,t.gl=null,t.CONTEXT_UID=0,t.runners={destroy:new Gr("destroy"),contextChange:new Gr("contextChange"),reset:new Gr("reset"),update:new Gr("update"),postrender:new Gr("postrender"),prerender:new Gr("prerender"),resize:new Gr("resize")},t.runners.contextChange.add(t),t.globalUniforms=new cn({projectionMatrix:new ar},!0),t.addSystem(vo,"mask").addSystem(En,"context").addSystem(Ko,"state").addSystem(qo,"shader").addSystem(ea,"texture").addSystem(la,"buffer").addSystem(Cn,"geometry").addSystem(On,"framebuffer").addSystem(Eo,"scissor").addSystem(ko,"stencil").addSystem(Po,"projection").addSystem(Zo,"textureGC").addSystem(gn,"filter").addSystem(Io,"renderTexture").addSystem(xn,"batch"),t.initPlugins(fa.__plugins),t.multisample=void 0,e.context?t.context.initFromContext(e.context):t.context.initFromOptions({alpha:!!t.useContextAlpha,antialias:e.antialias,premultipliedAlpha:t.useContextAlpha&&"notMultiplied"!==t.useContextAlpha,stencil:!0,preserveDrawingBuffer:e.preserveDrawingBuffer,powerPreference:t.options.powerPreference}),t.renderingToScreen=!0,ht(2===t.context.webGLVersion?"WebGL 2":"WebGL 1"),t.resize(t.options.width,t.options.height),t}function pa(e){return ca.create(e)}Ur.handleByMap($.ExtensionType.RendererPlugin,ca.__plugins);var da="attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n vTextureCoord = aTextureCoord;\n}",ma="attribute vec2 aVertexPosition;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 vTextureCoord;\n\nuniform vec4 inputSize;\nuniform vec4 outputFrame;\n\nvec4 filterVertexPosition( void )\n{\n vec2 position = aVertexPosition * max(outputFrame.zw, vec2(0.)) + outputFrame.xy;\n\n return vec4((projectionMatrix * vec3(position, 1.0)).xy, 0.0, 1.0);\n}\n\nvec2 filterTextureCoord( void )\n{\n return aVertexPosition * (outputFrame.zw * inputSize.zw);\n}\n\nvoid main(void)\n{\n gl_Position = filterVertexPosition();\n vTextureCoord = filterTextureCoord();\n}\n",_a=(ga.prototype.destroy=function(){this.renderer=null},ga);function ga(e){Mt("6.1.0","System class is deprecated, implemement ISystem interface instead."),this.renderer=e}var va=function(){this.texArray=null,this.blend=0,this.type=$.DRAW_MODES.TRIANGLES,this.start=0,this.size=0,this.data=null},ya=(ba.prototype.clear=function(){for(var e=0;ethis.size&&this.flush(),this._vertexCount+=e.vertexData.length/2,this._indexCount+=e.indices.length,this._bufferedTextures[this._bufferSize]=e._texture.baseTexture,this._bufferedElements[this._bufferSize++]=e)},Sa.prototype.buildTexturesAndDrawCalls=function(){var e=this._bufferedTextures,t=this.MAX_TEXTURES,r=Sa._textureArrayPool,i=this.renderer.batch,n=this._tempBoundTextures,o=this.renderer.textureGC.count,a=++C._globalBatch,s=0,l=r[0],u=0;i.copyBoundTextures(n,t);for(var h=0;h=t&&(i.boundArray(l,n,a,t),this.buildDrawCalls(l,u,h),u=h,l=r[++s],++a),c._batchEnabled=a,c.touched=o,l.elements[l.count++]=c)}0 title : "+e.title+"
tabIndex: "+e.tabIndex},za.prototype.capHitArea=function(e){e.x<0&&(e.width+=e.x,e.x=0),e.y<0&&(e.height+=e.y,e.y=0);var t=this.renderer,r=t.width,t=t.height;e.x+e.width>r&&(e.width=r-e.x),e.y+e.height>t&&(e.height=t-e.y)},za.prototype.addChild=function(e){var t=this.pool.pop();t||((t=document.createElement("button")).style.width="100px",t.style.height="100px",t.style.backgroundColor=this.debug?"rgba(255,255,255,0.5)":"transparent",t.style.position="absolute",t.style.zIndex=2..toString(),t.style.borderStyle="none",-1>2,n[1]=(3&i[0])<<4|i[1]>>4,n[2]=(15&i[1])<<2|i[2]>>6,n[3]=63&i[2],r-(e.length-1)){case 2:n[3]=64,n[2]=64;break;case 1:n[3]=64}for(o=0;os[0]&&t[1]>1||1)+i-1&~(i-1))*(f=(h=h>>1||1)+n-1&~(n-1))*ws[t];return s};var Rs,Cs=Ms;function Ms(e,t){var r=Rs.call(this,e,t)||this;return r.format=t.format,r.levels=t.levels||1,r._width=t.width,r._height=t.height,r._extension=Ms._formatToExtension(r.format),(t.levelBuffers||r.buffer)&&(r._levelBuffers=t.levelBuffers||Ms._createLevelBuffers(e instanceof Uint8Array?e:r.buffer.uint8View,r.format,r.levels,4,4,r.width,r.height)),r}Is.use=function(r,i){var e=r.data;if(r.type===$.LoaderResource.TYPE.JSON&&e&&e.cacheID&&e.textures){for(var t,n,o=e.textures,a=void 0,s=void 0,l=0,u=o.length;l>>=1,m>>>=1;for(var g=148,_=0;_>1||1)+4-1&-4)*(x=(y=y>>1||1)+4-1&-4)*_}return 0!==o?{uncompressed:d.map(function(e){var t=e[0].levelBuffer,r=!1;return o===$.TYPES.FLOAT?t=new Float32Array(e[0].levelBuffer.buffer,e[0].levelBuffer.byteOffset,e[0].levelBuffer.byteLength/4):o===$.TYPES.UNSIGNED_INT?(r=!0,t=new Uint32Array(e[0].levelBuffer.buffer,e[0].levelBuffer.byteOffset,e[0].levelBuffer.byteLength/4)):o===$.TYPES.INT&&(r=!0,t=new Int32Array(e[0].levelBuffer.buffer,e[0].levelBuffer.byteOffset,e[0].levelBuffer.byteLength/4)),{resource:new ti(t,{width:e[0].levelWidth,height:e[0].levelHeight}),type:o,format:r?function(e){switch(e){case $.FORMATS.RGBA:return $.FORMATS.RGBA_INTEGER;case $.FORMATS.RGB:return $.FORMATS.RGB_INTEGER;case $.FORMATS.RG:return $.FORMATS.RG_INTEGER;case $.FORMATS.RED:return $.FORMATS.RED_INTEGER;default:return e}}(a):a}}),kvData:r}:{compressed:d.map(function(e){return new Cs(null,{format:s,width:l,height:u,levels:f,levelBuffers:e})}),kvData:r}}$.LoaderResource.setExtensionXhrType("dds",$.LoaderResource.XHR_RESPONSE_TYPE.BUFFER);cl.use=function(e,t){if("dds"===e.extension&&e.data)try{Object.assign(e,Ds(e.name||e.url,qs(e.data),e.metadata))}catch(e){return void t(e)}t()},cl.extension=$.ExtensionType.Loader;var v=cl;function cl(){}$.LoaderResource.setExtensionXhrType("ktx",$.LoaderResource.XHR_RESPONSE_TYPE.BUFFER);pl.use=function(e,t){if("ktx"===e.extension&&e.data)try{var i,n=e.name||e.url,r=hl(n,e.data,this.loadKeyValueData),o=r.compressed,a=r.uncompressed,s=r.kvData;if(o){var l=Ds(n,o,e.metadata);if(s&&l.textures)for(var u in l.textures)l.textures[u].baseTexture.ktxKeyValueData=s;Object.assign(e,l)}else a&&(i={},a.forEach(function(e,t){var e=new te(new C(e.resource,{mipmap:$.MIPMAP_MODES.OFF,alphaMode:$.ALPHA_MODES.NO_PREMULTIPLIED_ALPHA,type:e.type,format:e.format})),r=n+"-"+(t+1);s&&(e.baseTexture.ktxKeyValueData=s),C.addToCache(e.baseTexture,r),te.addToCache(e,r),0===t&&(i[n]=e,C.addToCache(e.baseTexture,n),te.addToCache(e,n)),i[r]=e}),Object.assign(e,{textures:i}))}catch(e){return void t(e)}t()},pl.extension=$.ExtensionType.Loader,pl.loadKeyValueData=!1;var fl=pl;function pl(){}var dl=function(e,t){return(dl=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])})(e,t)};function ml(e,t){function r(){this.constructor=e}dl(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)}ml(vl,_l=zr),vl.prototype.setProperties=function(e){e&&(this._properties[0]="vertices"in e||"scale"in e?!!e.vertices||!!e.scale:this._properties[0],this._properties[1]="position"in e?!!e.position:this._properties[1],this._properties[2]="rotation"in e?!!e.rotation:this._properties[2],this._properties[3]="uvs"in e?!!e.uvs:this._properties[3],this._properties[4]="tint"in e||"alpha"in e?!!e.tint||!!e.alpha:this._properties[4])},vl.prototype.updateTransform=function(){this.displayObjectUpdateTransform()},Object.defineProperty(vl.prototype,"tint",{get:function(){return this._tint},set:function(e){pt(this._tint=e,this.tintRgb)},enumerable:!1,configurable:!0}),vl.prototype.render=function(e){var t=this;this.visible&&!(this.worldAlpha<=0)&&this.children.length&&this.renderable&&(this.baseTexture||(this.baseTexture=this.children[0]._texture.baseTexture,this.baseTexture.valid||this.baseTexture.once("update",function(){return t.onChildrenChange(0)})),e.batch.setObjectRenderer(e.plugins.particle),e.plugins.particle.render(this))},vl.prototype.onChildrenChange=function(e){for(var t=Math.floor(e/this._batchSize);this._bufferUpdateIDs.length=a.length&&a.push(this._generateOneMoreBuffer(e)),a[f]),m=(d.uploadDynamic(t,c,p),e._bufferUpdateIDs[f]||0);(h=h||d._updateIDthis.maxSegments&&(e=this.maxSegments),e):t}},Sl=(Al.prototype.clone=function(){var e=new Al;return e.color=this.color,e.alpha=this.alpha,e.texture=this.texture,e.matrix=this.matrix,e.visible=this.visible,e},Al.prototype.reset=function(){this.color=16777215,this.alpha=1,this.texture=te.WHITE,this.matrix=null,this.visible=!1},Al.prototype.destroy=function(){this.texture=null,this.matrix=null},Al);function Al(){this.color=16777215,this.alpha=1,this.texture=te.WHITE,this.matrix=null,this.visible=!1,this.reset()}var kl=function(e,t){return(kl=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])})(e,t)};function Ol(e,t){function r(){this.constructor=e}kl(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)}function Pl(e,t){void 0===t&&(t=!1);var r=e.length;if(!(r<6)){for(var i=0,n=0,o=e[r-2],a=e[r-1];n>0),m=c/d;if(f+=m,s){a.push(e,t),a.push(r,i);for(var _=1,g=f;_>16)+(65280&t)+((255&t)<<16),r);e.length=Math.max(e.length,n+i);for(var a=0;a>16&255)/255*n,o.tint[1]=(i>>8&255)/255*n,o.tint[2]=(255&i)/255*n,o.tint[3]=n,e.shader.bind(t),e.geometry.bind(r,t),e.state.set(this.state);for(var s=0,l=a.length;s>16)+(65280&i)+((255&i)<<16)}}},b.prototype.calculateVertices=function(){var e=this.transform._worldID;if(this._transformID!==e){this._transformID=e;for(var e=this.transform.worldTransform,t=e.a,r=e.b,i=e.c,n=e.d,o=e.tx,a=e.ty,s=this._geometry.points,l=this.vertexData,u=0,h=0;h=r&&fu.x=r&&fu.y>16)+(65280&e)+((255&e)<<16)},enumerable:!1,configurable:!0}),Object.defineProperty(_u.prototype,"texture",{get:function(){return this._texture},set:function(e){this._texture!==e&&(this._texture&&this._texture.off("update",this._onTextureUpdate,this),this._texture=e||te.EMPTY,this._cachedTint=16777215,this._textureID=-1,this._textureTrimmedID=-1,e&&(e.baseTexture.valid?this._onTextureUpdate():e.once("update",this._onTextureUpdate,this)))},enumerable:!1,configurable:!0}),_u);function mu(){this.constructor=cu}function _u(e){var t=hu.call(this)||this;return t._anchor=new nr(t._onAnchorUpdate,t,e?e.defaultAnchor.x:0,e?e.defaultAnchor.y:0),t._texture=null,t._width=0,t._height=0,t._tint=null,t._tintRGB=null,t.tint=16777215,t.blendMode=$.BLEND_MODES.NORMAL,t._cachedTint=16777215,t.uvs=null,t.texture=e||te.EMPTY,t.vertexData=new Float32Array(8),t.vertexTrimmedData=null,t._transformID=-1,t._textureID=-1,t._transformTrimmedID=-1,t._textureTrimmedID=-1,t.indices=pu,t.pluginName="batch",t.isSprite=!0,t._roundPixels=R.ROUND_PIXELS,t}var gu=function(e,t){return(gu=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])})(e,t)};$.TEXT_GRADIENT=void 0,(Ll=$.TEXT_GRADIENT||($.TEXT_GRADIENT={}))[Ll.LINEAR_VERTICAL=0]="LINEAR_VERTICAL";var vu={align:"left",breakWords:!(Ll[Ll.LINEAR_HORIZONTAL=1]="LINEAR_HORIZONTAL"),dropShadow:!1,dropShadowAlpha:1,dropShadowAngle:Math.PI/6,dropShadowBlur:0,dropShadowColor:"black",dropShadowDistance:5,fill:"black",fillGradientType:$.TEXT_GRADIENT.LINEAR_VERTICAL,fillGradientStops:[],fontFamily:"Arial",fontSize:26,fontStyle:"normal",fontVariant:"normal",fontWeight:"normal",letterSpacing:0,lineHeight:0,lineJoin:"miter",miterLimit:10,padding:0,stroke:"black",strokeThickness:0,textBaseline:"alphabetic",trim:!1,whiteSpace:"pre",wordWrap:!1,wordWrapWidth:100,leading:0},yu=["serif","sans-serif","monospace","cursive","fantasy","system-ui"],bu=(x.prototype.clone=function(){var e={};return wu(e,this,vu),new x(e)},x.prototype.reset=function(){wu(this,vu,vu)},Object.defineProperty(x.prototype,"align",{get:function(){return this._align},set:function(e){this._align!==e&&(this._align=e,this.styleID++)},enumerable:!1,configurable:!0}),Object.defineProperty(x.prototype,"breakWords",{get:function(){return this._breakWords},set:function(e){this._breakWords!==e&&(this._breakWords=e,this.styleID++)},enumerable:!1,configurable:!0}),Object.defineProperty(x.prototype,"dropShadow",{get:function(){return this._dropShadow},set:function(e){this._dropShadow!==e&&(this._dropShadow=e,this.styleID++)},enumerable:!1,configurable:!0}),Object.defineProperty(x.prototype,"dropShadowAlpha",{get:function(){return this._dropShadowAlpha},set:function(e){this._dropShadowAlpha!==e&&(this._dropShadowAlpha=e,this.styleID++)},enumerable:!1,configurable:!0}),Object.defineProperty(x.prototype,"dropShadowAngle",{get:function(){return this._dropShadowAngle},set:function(e){this._dropShadowAngle!==e&&(this._dropShadowAngle=e,this.styleID++)},enumerable:!1,configurable:!0}),Object.defineProperty(x.prototype,"dropShadowBlur",{get:function(){return this._dropShadowBlur},set:function(e){this._dropShadowBlur!==e&&(this._dropShadowBlur=e,this.styleID++)},enumerable:!1,configurable:!0}),Object.defineProperty(x.prototype,"dropShadowColor",{get:function(){return this._dropShadowColor},set:function(e){e=Tu(e);this._dropShadowColor!==e&&(this._dropShadowColor=e,this.styleID++)},enumerable:!1,configurable:!0}),Object.defineProperty(x.prototype,"dropShadowDistance",{get:function(){return this._dropShadowDistance},set:function(e){this._dropShadowDistance!==e&&(this._dropShadowDistance=e,this.styleID++)},enumerable:!1,configurable:!0}),Object.defineProperty(x.prototype,"fill",{get:function(){return this._fill},set:function(e){e=Tu(e);this._fill!==e&&(this._fill=e,this.styleID++)},enumerable:!1,configurable:!0}),Object.defineProperty(x.prototype,"fillGradientType",{get:function(){return this._fillGradientType},set:function(e){this._fillGradientType!==e&&(this._fillGradientType=e,this.styleID++)},enumerable:!1,configurable:!0}),Object.defineProperty(x.prototype,"fillGradientStops",{get:function(){return this._fillGradientStops},set:function(e){!function(e,t){if(!Array.isArray(e)||!Array.isArray(t))return;if(e.length!==t.length)return;for(var r=0;r=r&&nh.x=r&&nh.y>16)+(65280&e)+((255&e)<<16),this._colorDirty=!0)},enumerable:!1,configurable:!0}),wh.prototype.update=function(){var e;this._colorDirty&&(this._colorDirty=!1,e=this.texture.baseTexture,bt(this._tint,this._alpha,this.uniforms.uColor,e.alphaMode)),this.uvMatrix.update()&&(this.uniforms.uTextureMatrix=this.uvMatrix.mapCoord)};var xh,Th=wh;function wh(e,t){var r=this,i={uSampler:e,alpha:1,uTextureMatrix:ar.IDENTITY,uColor:new Float32Array([1,1,1,1])};return(t=Object.assign({tint:16777215,alpha:1,pluginName:"batch"},t)).uniforms&&Object.assign(i,t.uniforms),(r=xh.call(this,t.program||io.from("attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\nuniform mat3 translationMatrix;\nuniform mat3 uTextureMatrix;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n vTextureCoord = (uTextureMatrix * vec3(aTextureCoord, 1.0)).xy;\n}\n","varying vec2 vTextureCoord;\nuniform vec4 uColor;\n\nuniform sampler2D uSampler;\n\nvoid main(void)\n{\n gl_FragColor = texture2D(uSampler, vTextureCoord) * uColor;\n}\n"),i)||this)._colorDirty=!1,r.uvMatrix=new fo(e),r.batchable=void 0===t.program,r.pluginName=t.pluginName,r.tint=t.tint,r.alpha=t.alpha,r}ph(Ah,Eh=tn),Object.defineProperty(Ah.prototype,"vertexDirtyId",{get:function(){return this.buffers[0]._updateID},enumerable:!1,configurable:!0});var Eh,Sh=Ah;function Ah(e,t,r){var i=Eh.call(this)||this,e=new Ki(e),t=new Ki(t,!0),r=new Ki(r,!0,!0);return i.addAttribute("aVertexPosition",e,2,!1,$.TYPES.FLOAT).addAttribute("aTextureCoord",t,2,!1,$.TYPES.FLOAT).addIndex(r),i._updateId=-1,i}var kh=function(e,t){return(kh=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])})(e,t)};var Oh=function(){this.info=[],this.common=[],this.page=[],this.char=[],this.kerning=[],this.distanceField=[]},Ph=(Rh.test=function(e){return"string"==typeof e&&0===e.indexOf("info face=")},Rh.parse=function(e){var t,r=e.match(/^[a-z]+\s+.+$/gm),i={info:[],common:[],page:[],char:[],chars:[],kerning:[],kernings:[],distanceField:[]};for(t in r){var n,o=r[t].match(/^[a-z]+/gm)[0],a=r[t].match(/[a-zA-Z]+=([^\s"']+|"([^"]*)")/gm),s={};for(n in a){var l=a[n].split("="),u=l[0],l=l[1].replace(/"/gm,""),h=parseFloat(l),l=isNaN(h)?l:h;s[u]=l}i[o].push(s)}var c=new Oh;return i.info.forEach(function(e){return c.info.push({face:e.face,size:parseInt(e.size,10)})}),i.common.forEach(function(e){return c.common.push({lineHeight:parseInt(e.lineHeight,10)})}),i.page.forEach(function(e){return c.page.push({id:parseInt(e.id,10),file:e.file})}),i.char.forEach(function(e){return c.char.push({id:parseInt(e.id,10),page:parseInt(e.page,10),x:parseInt(e.x,10),y:parseInt(e.y,10),width:parseInt(e.width,10),height:parseInt(e.height,10),xoffset:parseInt(e.xoffset,10),yoffset:parseInt(e.yoffset,10),xadvance:parseInt(e.xadvance,10)})}),i.kerning.forEach(function(e){return c.kerning.push({first:parseInt(e.first,10),second:parseInt(e.second,10),amount:parseInt(e.amount,10)})}),i.distanceField.forEach(function(e){return c.distanceField.push({distanceRange:parseInt(e.distanceRange,10),fieldType:e.fieldType})}),c},Rh);function Rh(){}Mh.test=function(e){return e instanceof XMLDocument&&e.getElementsByTagName("page").length&&null!==e.getElementsByTagName("info")[0].getAttribute("face")},Mh.parse=function(e){for(var t=new Oh,r=e.getElementsByTagName("info"),i=e.getElementsByTagName("common"),n=e.getElementsByTagName("page"),o=e.getElementsByTagName("char"),a=e.getElementsByTagName("kerning"),s=e.getElementsByTagName("distanceField"),l=0;l")&&(e=(new globalThis.DOMParser).parseFromString(e,"text/xml"),Ch.test(e))},Dh.parse=function(e){e=(new globalThis.DOMParser).parseFromString(e,"text/xml");return Ch.parse(e)};var Ih=Dh;function Dh(){}var Lh=[Ph,Ch,Ih];function Fh(e){for(var t=0;tF&&(kt(i,1+c-++z,1+d-c),d=c,c=-1,n.push(f),o.push(06*E)||I.vertices.length<2*yh.BATCHABLE_SIZE)I.vertices=new Float32Array(8*E),I.uvs=new Float32Array(8*E),I.indices=new Uint16Array(6*E);else for(var Y=I.total,W=I.vertices,q=4*Y*2;q>16&255)/255,0,0,0,0,0,(e>>8&255)/255,0,0,0,0,0,(255&e)/255,0,0,0,0,0,1,0],t)},E.prototype.greyscale=function(e,t){this._loadMatrix([e,e,e,0,0,e,e,e,0,0,e,e,e,0,0,0,0,0,1,0],t)},E.prototype.blackAndWhite=function(e){this._loadMatrix([.3,.6,.1,0,0,.3,.6,.1,0,0,.3,.6,.1,0,0,0,0,0,1,0],e)},E.prototype.hue=function(e,t){e=(e||0)/180*Math.PI;var r=Math.cos(e),e=Math.sin(e),i=(0,Math.sqrt)(1/3);this._loadMatrix([r+1/3*(1-r),1/3*(1-r)-i*e,1/3*(1-r)+i*e,0,0,1/3*(1-r)+i*e,r+1/3*(1-r),1/3*(1-r)-i*e,0,0,1/3*(1-r)-i*e,1/3*(1-r)+i*e,r+1/3*(1-r),0,0,0,0,0,1,0],t)},E.prototype.contrast=function(e,t){var e=(e||0)+1,r=-.5*(e-1);this._loadMatrix([e,0,0,0,r,0,e,0,0,r,0,0,e,0,r,0,0,0,1,0],t)},E.prototype.saturate=function(e,t){var e=2*(e=void 0===e?0:e)/3+1,r=-.5*(e-1);this._loadMatrix([e,r,r,0,0,r,e,r,0,0,r,r,e,0,0,0,0,0,1,0],t)},E.prototype.desaturate=function(){this.saturate(-1)},E.prototype.negative=function(e){this._loadMatrix([-1,0,0,1,0,0,-1,0,1,0,0,0,-1,1,0,0,0,0,1,0],e)},E.prototype.sepia=function(e){this._loadMatrix([.393,.7689999,.18899999,0,0,.349,.6859999,.16799999,0,0,.272,.5339999,.13099999,0,0,0,0,0,1,0],e)},E.prototype.technicolor=function(e){this._loadMatrix([1.9125277891456083,-.8545344976951645,-.09155508482755585,0,11.793603434377337,-.3087833385928097,1.7658908555458428,-.10601743074722245,0,-70.35205161461398,-.231103377548616,-.7501899197440212,1.847597816108189,0,30.950940869491138,0,0,0,1,0],e)},E.prototype.polaroid=function(e){this._loadMatrix([1.438,-.062,-.062,0,0,-.122,1.378,-.122,0,0,-.016,-.016,1.483,0,0,0,0,0,1,0],e)},E.prototype.toBGR=function(e){this._loadMatrix([0,0,1,0,0,0,1,0,0,0,1,0,0,0,0,0,0,0,1,0],e)},E.prototype.kodachrome=function(e){this._loadMatrix([1.1285582396593525,-.3967382283601348,-.03992559172921793,0,63.72958762196502,-.16404339962244616,1.0835251566291304,-.05498805115633132,0,24.732407896706203,-.16786010706155763,-.5603416277695248,1.6014850761964943,0,35.62982807460946,0,0,0,1,0],e)},E.prototype.browni=function(e){this._loadMatrix([.5997023498159715,.34553243048391263,-.2708298674538042,0,47.43192855600873,-.037703249837783157,.8609577587992641,.15059552388459913,0,-36.96841498319127,.24113635128153335,-.07441037908422492,.44972182064877153,0,-7.562075277591283,0,0,0,1,0],e)},E.prototype.vintage=function(e){this._loadMatrix([.6279345635605994,.3202183420819367,-.03965408211312453,0,9.651285835294123,.02578397704808868,.6441188644374771,.03259127616149294,0,7.462829176470591,.0466055556782719,-.0851232987247891,.5241648018700465,0,5.159190588235296,0,0,0,1,0],e)},E.prototype.colorTone=function(e,t,r,i,n){var o=((r=r||16770432)>>16&255)/255,a=(r>>8&255)/255,r=(255&r)/255,s=((i=i||3375104)>>16&255)/255,l=(i>>8&255)/255,i=(255&i)/255;this._loadMatrix([.3,.59,.11,0,0,o,a,r,e=e||.2,0,s,l,i,t=t||.15,0,o-s,a-l,r-i,0,0],n)},E.prototype.night=function(e,t){this._loadMatrix([-2*(e=e||.1),-e,0,0,0,-e,0,e,0,0,0,e,2*e,0,0,0,0,0,1,0],t)},E.prototype.predator=function(e,t){this._loadMatrix([11.224130630493164*e,-4.794486999511719*e,-2.8746118545532227*e,0*e,.40342438220977783*e,-3.6330697536468506*e,9.193157196044922*e,-2.951810836791992*e,0*e,-1.316135048866272*e,-3.2184197902679443*e,-4.2375030517578125*e,7.476448059082031*e,0*e,.8044459223747253*e,0,0,0,1,0],t)},E.prototype.lsd=function(e){this._loadMatrix([2,-.4,.5,0,0,-.5,2,-.4,0,0,-.4,-.5,3,0,0,0,0,0,1,0],e)},E.prototype.reset=function(){this._loadMatrix([1,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,1,0],!1)},Object.defineProperty(E.prototype,"matrix",{get:function(){return this.uniforms.m},set:function(e){this.uniforms.m=e},enumerable:!1,configurable:!0}),Object.defineProperty(E.prototype,"alpha",{get:function(){return this.uniforms.uAlpha},set:function(e){this.uniforms.uAlpha=e},enumerable:!1,configurable:!0});var _c,gc,vc=E;function yc(){this.constructor=gc}function E(){var e=this,t={m:new Float32Array([1,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,1,0]),uAlpha:1};return(e=_c.call(this,ma,"varying vec2 vTextureCoord;\nuniform sampler2D uSampler;\nuniform float m[20];\nuniform float uAlpha;\n\nvoid main(void)\n{\n vec4 c = texture2D(uSampler, vTextureCoord);\n\n if (uAlpha == 0.0) {\n gl_FragColor = c;\n return;\n }\n\n // Un-premultiply alpha before applying the color matrix. See issue #3539.\n if (c.a > 0.0) {\n c.rgb /= c.a;\n }\n\n vec4 result;\n\n result.r = (m[0] * c.r);\n result.r += (m[1] * c.g);\n result.r += (m[2] * c.b);\n result.r += (m[3] * c.a);\n result.r += m[4];\n\n result.g = (m[5] * c.r);\n result.g += (m[6] * c.g);\n result.g += (m[7] * c.b);\n result.g += (m[8] * c.a);\n result.g += m[9];\n\n result.b = (m[10] * c.r);\n result.b += (m[11] * c.g);\n result.b += (m[12] * c.b);\n result.b += (m[13] * c.a);\n result.b += m[14];\n\n result.a = (m[15] * c.r);\n result.a += (m[16] * c.g);\n result.a += (m[17] * c.b);\n result.a += (m[18] * c.a);\n result.a += m[19];\n\n vec3 rgb = mix(c.rgb, result.rgb, uAlpha);\n\n // Premultiply alpha again.\n rgb *= result.a;\n\n gl_FragColor = vec4(rgb, result.a);\n}\n",t)||this).alpha=1,e}vc.prototype.grayscale=vc.prototype.greyscale;var bc=function(e,t){return(bc=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])})(e,t)};bc(Tc=Sc,wc=xc=Q),Tc.prototype=null===wc?Object.create(wc):(Ec.prototype=wc.prototype,new Ec),Sc.prototype.apply=function(e,t,r,i){this.uniforms.filterMatrix=e.calculateSpriteMatrix(this.maskMatrix,this.maskSprite),this.uniforms.scale.x=this.scale.x,this.uniforms.scale.y=this.scale.y;var n=this.maskSprite.worldTransform,o=Math.sqrt(n.a*n.a+n.b*n.b),a=Math.sqrt(n.c*n.c+n.d*n.d);0!==o&&0!==a&&(this.uniforms.rotation[0]=n.a/o,this.uniforms.rotation[1]=n.b/o,this.uniforms.rotation[2]=n.c/a,this.uniforms.rotation[3]=n.d/a),e.applyFilter(this,t,r,i)},Object.defineProperty(Sc.prototype,"map",{get:function(){return this.uniforms.mapSampler},set:function(e){this.uniforms.mapSampler=e},enumerable:!1,configurable:!0});var xc,Tc,wc=Sc;function Ec(){this.constructor=Tc}function Sc(e,t){var r=this,i=new ar;return e.renderable=!1,(r=xc.call(this,"attribute vec2 aVertexPosition;\n\nuniform mat3 projectionMatrix;\nuniform mat3 filterMatrix;\n\nvarying vec2 vTextureCoord;\nvarying vec2 vFilterCoord;\n\nuniform vec4 inputSize;\nuniform vec4 outputFrame;\n\nvec4 filterVertexPosition( void )\n{\n vec2 position = aVertexPosition * max(outputFrame.zw, vec2(0.)) + outputFrame.xy;\n\n return vec4((projectionMatrix * vec3(position, 1.0)).xy, 0.0, 1.0);\n}\n\nvec2 filterTextureCoord( void )\n{\n return aVertexPosition * (outputFrame.zw * inputSize.zw);\n}\n\nvoid main(void)\n{\n\tgl_Position = filterVertexPosition();\n\tvTextureCoord = filterTextureCoord();\n\tvFilterCoord = ( filterMatrix * vec3( vTextureCoord, 1.0) ).xy;\n}\n","varying vec2 vFilterCoord;\nvarying vec2 vTextureCoord;\n\nuniform vec2 scale;\nuniform mat2 rotation;\nuniform sampler2D uSampler;\nuniform sampler2D mapSampler;\n\nuniform highp vec4 inputSize;\nuniform vec4 inputClamp;\n\nvoid main(void)\n{\n vec4 map = texture2D(mapSampler, vFilterCoord);\n\n map -= 0.5;\n map.xy = scale * inputSize.zw * (rotation * map.xy);\n\n gl_FragColor = texture2D(uSampler, clamp(vec2(vTextureCoord.x + map.x, vTextureCoord.y + map.y), inputClamp.xy, inputClamp.zw));\n}\n",{mapSampler:e._texture,filterMatrix:i,scale:{x:1,y:1},rotation:new Float32Array([1,0,0,1])})||this).maskSprite=e,r.maskMatrix=i,r.scale=new ee(t=null==t?20:t,t),r}var Ac=function(e,t){return(Ac=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])})(e,t)};Ac(Oc=Cc,Pc=kc=Q),Oc.prototype=null===Pc?Object.create(Pc):(Rc.prototype=Pc.prototype,new Rc);var kc,Oc,Pc=Cc;function Rc(){this.constructor=Oc}function Cc(){return kc.call(this,"\nattribute vec2 aVertexPosition;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 v_rgbNW;\nvarying vec2 v_rgbNE;\nvarying vec2 v_rgbSW;\nvarying vec2 v_rgbSE;\nvarying vec2 v_rgbM;\n\nvarying vec2 vFragCoord;\n\nuniform vec4 inputSize;\nuniform vec4 outputFrame;\n\nvec4 filterVertexPosition( void )\n{\n vec2 position = aVertexPosition * max(outputFrame.zw, vec2(0.)) + outputFrame.xy;\n\n return vec4((projectionMatrix * vec3(position, 1.0)).xy, 0.0, 1.0);\n}\n\nvoid texcoords(vec2 fragCoord, vec2 inverseVP,\n out vec2 v_rgbNW, out vec2 v_rgbNE,\n out vec2 v_rgbSW, out vec2 v_rgbSE,\n out vec2 v_rgbM) {\n v_rgbNW = (fragCoord + vec2(-1.0, -1.0)) * inverseVP;\n v_rgbNE = (fragCoord + vec2(1.0, -1.0)) * inverseVP;\n v_rgbSW = (fragCoord + vec2(-1.0, 1.0)) * inverseVP;\n v_rgbSE = (fragCoord + vec2(1.0, 1.0)) * inverseVP;\n v_rgbM = vec2(fragCoord * inverseVP);\n}\n\nvoid main(void) {\n\n gl_Position = filterVertexPosition();\n\n vFragCoord = aVertexPosition * outputFrame.zw;\n\n texcoords(vFragCoord, inputSize.zw, v_rgbNW, v_rgbNE, v_rgbSW, v_rgbSE, v_rgbM);\n}\n",'varying vec2 v_rgbNW;\nvarying vec2 v_rgbNE;\nvarying vec2 v_rgbSW;\nvarying vec2 v_rgbSE;\nvarying vec2 v_rgbM;\n\nvarying vec2 vFragCoord;\nuniform sampler2D uSampler;\nuniform highp vec4 inputSize;\n\n\n/**\n Basic FXAA implementation based on the code on geeks3d.com with the\n modification that the texture2DLod stuff was removed since it\'s\n unsupported by WebGL.\n\n --\n\n From:\n https://github.com/mitsuhiko/webgl-meincraft\n\n Copyright (c) 2011 by Armin Ronacher.\n\n Some rights reserved.\n\n Redistribution and use in source and binary forms, with or without\n modification, are permitted provided that the following conditions are\n met:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n\n * Redistributions in binary form must reproduce the above\n copyright notice, this list of conditions and the following\n disclaimer in the documentation and/or other materials provided\n with the distribution.\n\n * The names of the contributors may not be used to endorse or\n promote products derived from this software without specific\n prior written permission.\n\n THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n#ifndef FXAA_REDUCE_MIN\n#define FXAA_REDUCE_MIN (1.0/ 128.0)\n#endif\n#ifndef FXAA_REDUCE_MUL\n#define FXAA_REDUCE_MUL (1.0 / 8.0)\n#endif\n#ifndef FXAA_SPAN_MAX\n#define FXAA_SPAN_MAX 8.0\n#endif\n\n//optimized version for mobile, where dependent\n//texture reads can be a bottleneck\nvec4 fxaa(sampler2D tex, vec2 fragCoord, vec2 inverseVP,\n vec2 v_rgbNW, vec2 v_rgbNE,\n vec2 v_rgbSW, vec2 v_rgbSE,\n vec2 v_rgbM) {\n vec4 color;\n vec3 rgbNW = texture2D(tex, v_rgbNW).xyz;\n vec3 rgbNE = texture2D(tex, v_rgbNE).xyz;\n vec3 rgbSW = texture2D(tex, v_rgbSW).xyz;\n vec3 rgbSE = texture2D(tex, v_rgbSE).xyz;\n vec4 texColor = texture2D(tex, v_rgbM);\n vec3 rgbM = texColor.xyz;\n vec3 luma = vec3(0.299, 0.587, 0.114);\n float lumaNW = dot(rgbNW, luma);\n float lumaNE = dot(rgbNE, luma);\n float lumaSW = dot(rgbSW, luma);\n float lumaSE = dot(rgbSE, luma);\n float lumaM = dot(rgbM, luma);\n float lumaMin = min(lumaM, min(min(lumaNW, lumaNE), min(lumaSW, lumaSE)));\n float lumaMax = max(lumaM, max(max(lumaNW, lumaNE), max(lumaSW, lumaSE)));\n\n mediump vec2 dir;\n dir.x = -((lumaNW + lumaNE) - (lumaSW + lumaSE));\n dir.y = ((lumaNW + lumaSW) - (lumaNE + lumaSE));\n\n float dirReduce = max((lumaNW + lumaNE + lumaSW + lumaSE) *\n (0.25 * FXAA_REDUCE_MUL), FXAA_REDUCE_MIN);\n\n float rcpDirMin = 1.0 / (min(abs(dir.x), abs(dir.y)) + dirReduce);\n dir = min(vec2(FXAA_SPAN_MAX, FXAA_SPAN_MAX),\n max(vec2(-FXAA_SPAN_MAX, -FXAA_SPAN_MAX),\n dir * rcpDirMin)) * inverseVP;\n\n vec3 rgbA = 0.5 * (\n texture2D(tex, fragCoord * inverseVP + dir * (1.0 / 3.0 - 0.5)).xyz +\n texture2D(tex, fragCoord * inverseVP + dir * (2.0 / 3.0 - 0.5)).xyz);\n vec3 rgbB = rgbA * 0.5 + 0.25 * (\n texture2D(tex, fragCoord * inverseVP + dir * -0.5).xyz +\n texture2D(tex, fragCoord * inverseVP + dir * 0.5).xyz);\n\n float lumaB = dot(rgbB, luma);\n if ((lumaB < lumaMin) || (lumaB > lumaMax))\n color = vec4(rgbA, texColor.a);\n else\n color = vec4(rgbB, texColor.a);\n return color;\n}\n\nvoid main() {\n\n vec4 color;\n\n color = fxaa(uSampler, vFragCoord, inputSize.zw, v_rgbNW, v_rgbNE, v_rgbSW, v_rgbSE, v_rgbM);\n\n gl_FragColor = color;\n}\n')||this}var Mc=function(e,t){return(Mc=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])})(e,t)};Mc(Dc=Nc,Lc=Ic=Q),Dc.prototype=null===Lc?Object.create(Lc):(Fc.prototype=Lc.prototype,new Fc),Object.defineProperty(Nc.prototype,"noise",{get:function(){return this.uniforms.uNoise},set:function(e){this.uniforms.uNoise=e},enumerable:!1,configurable:!0}),Object.defineProperty(Nc.prototype,"seed",{get:function(){return this.uniforms.uSeed},set:function(e){this.uniforms.uSeed=e},enumerable:!1,configurable:!0});var Ic,Dc,Lc=Nc;function Fc(){this.constructor=Dc}function Nc(e,t){void 0===e&&(e=.5),void 0===t&&(t=Math.random());var r=Ic.call(this,ma,"precision highp float;\n\nvarying vec2 vTextureCoord;\nvarying vec4 vColor;\n\nuniform float uNoise;\nuniform float uSeed;\nuniform sampler2D uSampler;\n\nfloat rand(vec2 co)\n{\n return fract(sin(dot(co.xy, vec2(12.9898, 78.233))) * 43758.5453);\n}\n\nvoid main()\n{\n vec4 color = texture2D(uSampler, vTextureCoord);\n float randomValue = rand(gl_FragCoord.xy * uSeed);\n float diff = (randomValue - 0.5) * uNoise;\n\n // Un-premultiply alpha before applying the color matrix. See issue #3539.\n if (color.a > 0.0) {\n color.rgb /= color.a;\n }\n\n color.r += diff;\n color.g += diff;\n color.b += diff;\n\n // Premultiply alpha again.\n color.rgb *= color.a;\n\n gl_FragColor = color;\n}\n",{uNoise:0,uSeed:0})||this;return r.noise=e,r.seed=t,r}(A={NORMAL:0,0:"NORMAL",ADD:1,1:"ADD",MULTIPLY:2,2:"MULTIPLY",SCREEN:3,3:"SCREEN",OVERLAY:4,4:"OVERLAY",DARKEN:5,5:"DARKEN",LIGHTEN:6,6:"LIGHTEN",COLOR_DODGE:7,7:"COLOR_DODGE",COLOR_BURN:8,8:"COLOR_BURN",HARD_LIGHT:9,9:"HARD_LIGHT",SOFT_LIGHT:10,10:"SOFT_LIGHT",DIFFERENCE:11,11:"DIFFERENCE",EXCLUSION:12,12:"EXCLUSION",HUE:13,13:"HUE",SATURATION:14,14:"SATURATION",COLOR:15,15:"COLOR",LUMINOSITY:16,16:"LUMINOSITY",NORMAL_NPM:17,17:"NORMAL_NPM",ADD_NPM:18,18:"ADD_NPM",SCREEN_NPM:19,19:"SCREEN_NPM",NONE:20,20:"NONE",SRC_OVER:0})[0]="SRC_OVER",A[A.SRC_IN=21]="SRC_IN",A[A.SRC_OUT=22]="SRC_OUT",A[A.SRC_ATOP=23]="SRC_ATOP",A[A.DST_OVER=24]="DST_OVER",A[A.DST_IN=25]="DST_IN",A[A.DST_OUT=26]="DST_OUT",A[A.DST_ATOP=27]="DST_ATOP",A[A.ERASE=26]="ERASE",A[A.SUBTRACT=28]="SUBTRACT",A[A.XOR=29]="XOR",(A={NPM:0,0:"NPM",UNPACK:1,1:"UNPACK",PMA:2,2:"PMA",NO_PREMULTIPLIED_ALPHA:0})[0]="NO_PREMULTIPLIED_ALPHA",A[A.PREMULTIPLY_ON_UPLOAD=1]="PREMULTIPLY_ON_UPLOAD",A[A.PREMULTIPLY_ALPHA=2]="PREMULTIPLY_ALPHA",A[A.PREMULTIPLIED_ALPHA=2]="PREMULTIPLIED_ALPHA",(A={NO:0,0:"NO",YES:1,1:"YES",AUTO:2,2:"AUTO",BLEND:0})[0]="BLEND",A[A.CLEAR=1]="CLEAR",A[A.BLIT=2]="BLIT",(A=k=k||{})[A.NONE=0]="NONE",A[A.LOW=2]="LOW",A[A.MEDIUM=4]="MEDIUM",A[A.HIGH=8]="HIGH";var zc,Bc,jc,Uc,Gc,Xc,Hc=new ar,Yc=(r.prototype._cacheAsBitmap=!1,r.prototype._cacheData=null,r.prototype._cacheAsBitmapResolution=null,r.prototype._cacheAsBitmapMultisample=k.NONE,function(){this.textureCacheId=null,this.originalRender=null,this.originalRenderCanvas=null,this.originalCalculateBounds=null,this.originalGetLocalBounds=null,this.originalUpdateTransform=null,this.originalDestroy=null,this.originalMask=null,this.originalFilterArea=null,this.originalContainsPoint=null,this.sprite=null}),A=(Object.defineProperties(r.prototype,{cacheAsBitmapResolution:{get:function(){return this._cacheAsBitmapResolution},set:function(e){e!==this._cacheAsBitmapResolution&&(this._cacheAsBitmapResolution=e,this.cacheAsBitmap&&(this.cacheAsBitmap=!1,this.cacheAsBitmap=!0))}},cacheAsBitmapMultisample:{get:function(){return this._cacheAsBitmapMultisample},set:function(e){e!==this._cacheAsBitmapMultisample&&(this._cacheAsBitmapMultisample=e,this.cacheAsBitmap&&(this.cacheAsBitmap=!1,this.cacheAsBitmap=!0))}},cacheAsBitmap:{get:function(){return this._cacheAsBitmap},set:function(e){var t;this._cacheAsBitmap!==e&&((this._cacheAsBitmap=e)?(this._cacheData||(this._cacheData=new Yc),(t=this._cacheData).originalRender=this.render,t.originalRenderCanvas=this.renderCanvas,t.originalUpdateTransform=this.updateTransform,t.originalCalculateBounds=this.calculateBounds,t.originalGetLocalBounds=this.getLocalBounds,t.originalDestroy=this.destroy,t.originalContainsPoint=this.containsPoint,t.originalMask=this._mask,t.originalFilterArea=this.filterArea,this.render=this._renderCached,this.renderCanvas=this._renderCachedCanvas,this.destroy=this._cacheAsBitmapDestroy):((t=this._cacheData).sprite&&this._destroyCachedDisplayObject(),this.render=t.originalRender,this.renderCanvas=t.originalRenderCanvas,this.calculateBounds=t.originalCalculateBounds,this.getLocalBounds=t.originalGetLocalBounds,this.destroy=t.originalDestroy,this.updateTransform=t.originalUpdateTransform,this.containsPoint=t.originalContainsPoint,this._mask=t.originalMask,this.filterArea=t.originalFilterArea))}}}),r.prototype._renderCached=function(e){!this.visible||this.worldAlpha<=0||!this.renderable||(this._initCachedDisplayObject(e),this._cacheData.sprite.transform._worldID=this.transform._worldID,this._cacheData.sprite.worldAlpha=this.worldAlpha,this._cacheData.sprite._render(e))},r.prototype._initCachedDisplayObject=function(e){var t,r,i,n,o,a,s,l;this._cacheData&&this._cacheData.sprite||(t=this.alpha,this.alpha=1,e.batch.flush(),r=this.getLocalBounds(null,!0).clone(),this.filters&&this.filters.length&&(i=this.filters[0].padding,r.pad(i)),r.ceil(R.RESOLUTION),i=e.renderTexture.current,n=e.renderTexture.sourceFrame.clone(),o=e.renderTexture.destinationFrame.clone(),a=e.projection.transform,s=Gi.create({width:r.width,height:r.height,resolution:this.cacheAsBitmapResolution||e.resolution,multisample:null!=(s=this.cacheAsBitmapMultisample)?s:e.multisample}),l="cacheAsBitmap_"+ ++Pt,this._cacheData.textureCacheId=l,C.addToCache(s.baseTexture,l),te.addToCache(s,l),l=this.transform.localTransform.copyTo(Hc).invert().translate(-r.x,-r.y),this.render=this._cacheData.originalRender,e.render(this,{renderTexture:s,clear:!0,transform:l,skipUpdateTransform:!1}),e.framebuffer.blit(),e.projection.transform=a,e.renderTexture.bind(i,n,o),this.render=this._renderCached,this.updateTransform=this.displayObjectUpdateTransform,this.calculateBounds=this._calculateCachedBounds,this.getLocalBounds=this._getCachedLocalBounds,this._mask=null,this.filterArea=null,this.alpha=t,(l=new du(s)).transform.worldTransform=this.transform.worldTransform,l.anchor.x=-(r.x/r.width),l.anchor.y=-(r.y/r.height),l.alpha=t,l._bounds=this._bounds,this._cacheData.sprite=l,this.transform._parentID=-1,this.parent?this.updateTransform():(this.enableTempParent(),this.updateTransform(),this.disableTempParent(null)),this.containsPoint=l.containsPoint.bind(l))},r.prototype._renderCachedCanvas=function(e){!this.visible||this.worldAlpha<=0||!this.renderable||(this._initCachedDisplayObjectCanvas(e),this._cacheData.sprite.worldAlpha=this.worldAlpha,this._cacheData.sprite._renderCanvas(e))},r.prototype._initCachedDisplayObjectCanvas=function(e){var t,r,i,n,o,a;this._cacheData&&this._cacheData.sprite||(t=this.getLocalBounds(null,!0),r=this.alpha,this.alpha=1,i=e.context,n=e._projTransform,t.ceil(R.RESOLUTION),o=Gi.create({width:t.width,height:t.height}),a="cacheAsBitmap_"+ ++Pt,this._cacheData.textureCacheId=a,C.addToCache(o.baseTexture,a),te.addToCache(o,a),this.transform.localTransform.copyTo(a=Hc),a.invert(),a.tx-=t.x,a.ty-=t.y,this.renderCanvas=this._cacheData.originalRenderCanvas,e.render(this,{renderTexture:o,clear:!0,transform:a,skipUpdateTransform:!1}),e.context=i,e._projTransform=n,this.renderCanvas=this._renderCachedCanvas,this.updateTransform=this.displayObjectUpdateTransform,this.calculateBounds=this._calculateCachedBounds,this.getLocalBounds=this._getCachedLocalBounds,this._mask=null,this.filterArea=null,this.alpha=r,(a=new du(o)).transform.worldTransform=this.transform.worldTransform,a.anchor.x=-(t.x/t.width),a.anchor.y=-(t.y/t.height),a.alpha=r,a._bounds=this._bounds,this._cacheData.sprite=a,this.transform._parentID=-1,this.parent?this.updateTransform():(this.parent=e._tempDisplayObjectParent,this.updateTransform(),this.parent=null),this.containsPoint=a.containsPoint.bind(a))},r.prototype._calculateCachedBounds=function(){this._bounds.clear(),this._cacheData.sprite.transform._worldID=this.transform._worldID,this._cacheData.sprite._calculateBounds(),this._bounds.updateID=this._boundsID},r.prototype._getCachedLocalBounds=function(){return this._cacheData.sprite.getLocalBounds(null)},r.prototype._destroyCachedDisplayObject=function(){this._cacheData.sprite._texture.destroy(!0),this._cacheData.sprite=null,C.removeFromCache(this._cacheData.textureCacheId),te.removeFromCache(this._cacheData.textureCacheId),this._cacheData.textureCacheId=null},r.prototype._cacheAsBitmapDestroy=function(e){this.cacheAsBitmap=!1,this.destroy(e)},r.prototype.name=null,zr.prototype.getChildByName=function(e,t){for(var r=0,i=this.children.length;r= 0x80 (not a basic code point)","invalid-input":"Invalid input"},p=g-1,y=Math.floor,b=String.fromCharCode;function x(e){throw RangeError(f[e])}function d(e,t){for(var r=e.length,i=[];r--;)i[r]=t(e[r]);return i}function m(e,t){var r=e.split("@"),i="",r=(1>>10&1023|55296),e=56320|1023&e),t+=b(e)}).join("")}function E(e,t){return e+22+75*(e<26)-((0!=t)<<5)}function S(e,t,r){var i=0;for(e=r?y(e/l):e>>1,e+=y(e/t);p*v>>1y((_-h)/o))&&x("overflow"),h+=s*o,!(s<(s=a<=f?1:f+v<=a?v:a-f));a+=g)o>y(_/(s=g-s))&&x("overflow"),o*=s;f=S(h-n,t=l.length+1,0==n),y(h/t)>_-c&&x("overflow"),c+=y(h/t),h%=t,l.splice(h++,0,c)}return w(l)}function k(e){for(var t,r,i,n,o,a,s,l,u,h,c=[],f=(e=T(e)).length,p=128,d=72,m=t=0;my((_-t)/(l=r+1))&&x("overflow"),t+=(n-p)*l,p=n,m=0;m_&&x("overflow"),s==p){for(o=t,a=g;!(o<(u=a<=d?1:d+v<=a?v:a-d));a+=g)c.push(b(E(u+(h=o-u)%(u=g-u),0))),o=y(h/u);c.push(b(E(o,0))),d=S(t,l,r==i),t=0,++r}++t,++p}return c.join("")}if(o={version:"1.3.2",ucs2:{decode:T,encode:w},decode:A,encode:k,toASCII:function(e){return m(e,function(e){return h.test(e)?"xn--"+k(e):e})},toUnicode:function(e){return m(e,function(e){return u.test(e)?A(e.slice(4).toLowerCase()):e})}},i&&t)if(e.exports==i)t.exports=o;else for(a in o)o.hasOwnProperty(a)&&(i[a]=o[a]);else r.punycode=o});function p0(e,t,r,i){t=t||"&",r=r||"=";var n={};if("string"==typeof e&&0!==e.length){var o=/\+/g,t=(e=e.split(t),1e3),a=(i&&"number"==typeof i.maxKeys&&(t=i.maxKeys),e.length);0e?1:this._width/e,t=this._topHeight+this._bottomHeight,t=this._height>t?1:this._height/t;return Math.min(e,t)},Object.defineProperty(B0.prototype,"width",{get:function(){return this._width},set:function(e){this._width=e,this._refresh()},enumerable:!1,configurable:!0}),Object.defineProperty(B0.prototype,"height",{get:function(){return this._height},set:function(e){this._height=e,this._refresh()},enumerable:!1,configurable:!0}),Object.defineProperty(B0.prototype,"leftWidth",{get:function(){return this._leftWidth},set:function(e){this._leftWidth=e,this._refresh()},enumerable:!1,configurable:!0}),Object.defineProperty(B0.prototype,"rightWidth",{get:function(){return this._rightWidth},set:function(e){this._rightWidth=e,this._refresh()},enumerable:!1,configurable:!0}),Object.defineProperty(B0.prototype,"topHeight",{get:function(){return this._topHeight},set:function(e){this._topHeight=e,this._refresh()},enumerable:!1,configurable:!0}),Object.defineProperty(B0.prototype,"bottomHeight",{get:function(){return this._bottomHeight},set:function(e){this._bottomHeight=e,this._refresh()},enumerable:!1,configurable:!0}),B0.prototype._refresh=function(){var e=this.texture,t=this.geometry.buffers[1].data,e=(this._origWidth=e.orig.width,this._origHeight=e.orig.height,1/this._origWidth),r=1/this._origHeight;t[0]=t[8]=t[16]=t[24]=0,t[1]=t[3]=t[5]=t[7]=0,t[6]=t[14]=t[22]=t[30]=1,t[25]=t[27]=t[29]=t[31]=1,t[2]=t[10]=t[18]=t[26]=e*this._leftWidth,t[4]=t[12]=t[20]=t[28]=1-e*this._rightWidth,t[9]=t[11]=t[13]=t[15]=r*this._topHeight,t[17]=t[19]=t[21]=t[23]=1-r*this._bottomHeight,this.updateHorizontalVertices(),this.updateVerticalVertices(),this.geometry.buffers[0].update(),this.geometry.buffers[1].update()};var z0,i0=B0;function B0(e,t,r,i,n){void 0===t&&(t=10),void 0===r&&(r=10),void 0===i&&(i=10),void 0===n&&(n=10);var o=z0.call(this,te.WHITE,4,4)||this;return o._origWidth=e.orig.width,o._origHeight=e.orig.height,o._width=o._origWidth,o._height=o._origHeight,o._leftWidth=t,o._rightWidth=i,o._topHeight=r,o._bottomHeight=n,o.texture=e,o}var j0=function(e,t){return(j0=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])})(e,t)};j0(G0=H0,n0=U0=du),G0.prototype=null===n0?Object.create(n0):(X0.prototype=n0.prototype,new X0),H0.prototype.stop=function(){this._playing&&(this._playing=!1,this._autoUpdate&&this._isConnectedToTicker&&(Wr.shared.remove(this.update,this),this._isConnectedToTicker=!1))},H0.prototype.play=function(){this._playing||(this._playing=!0,this._autoUpdate&&!this._isConnectedToTicker&&(Wr.shared.add(this.update,this,$.UPDATE_PRIORITY.HIGH),this._isConnectedToTicker=!0))},H0.prototype.gotoAndStop=function(e){this.stop();var t=this.currentFrame;this._currentTime=e,t!==this.currentFrame&&this.updateTexture()},H0.prototype.gotoAndPlay=function(e){var t=this.currentFrame;this._currentTime=e,t!==this.currentFrame&&this.updateTexture(),this.play()},H0.prototype.update=function(e){if(this._playing){var t=this.animationSpeed*e,r=this.currentFrame;if(null!==this._durations){var i=this._currentTime%1*this._durations[this.currentFrame];for(i+=t/60*1e3;i<0;)this._currentTime--,i+=this._durations[this.currentFrame];var n=Math.sign(this.animationSpeed*e);for(this._currentTime=Math.floor(this._currentTime);i>=this._durations[this.currentFrame];)i-=this._durations[this.currentFrame]*n,this._currentTime+=n;this._currentTime+=i/this._durations[this.currentFrame]}else this._currentTime+=t;this._currentTime<0&&!this.loop?(this.gotoAndStop(0),this.onComplete&&this.onComplete()):this._currentTime>=this._textures.length&&!this.loop?(this.gotoAndStop(this._textures.length-1),this.onComplete&&this.onComplete()):r!==this.currentFrame&&(this.loop&&this.onLoop&&(0r)&&this.onLoop(),this.updateTexture())}},H0.prototype.updateTexture=function(){var e=this.currentFrame;this._previousFrame!==e&&(this._previousFrame=e,this._texture=this._textures[e],this._textureID=-1,this._textureTrimmedID=-1,this._cachedTint=16777215,this.uvs=this._texture._uvs.uvsFloat32,this.updateAnchor&&this._anchor.copyFrom(this._texture.defaultAnchor),this.onFrameChange&&this.onFrameChange(this.currentFrame))},H0.prototype.destroy=function(e){this.stop(),U0.prototype.destroy.call(this,e),this.onComplete=null,this.onFrameChange=null,this.onLoop=null},H0.fromFrames=function(e){for(var t=[],r=0;r 0) var gc = undefined");else{if(!ba&&!ca)throw"Unknown runtime environment. Where are we?";e.read=function(e){var t=new XMLHttpRequest;return t.open("GET",e,!1),t.send(null),t.responseText},"undefined"!=typeof arguments&&(e.arguments=arguments),"undefined"!=typeof console?(e.print||(e.print=function(e){console.log(e)}),e.printErr||(e.printErr=function(e){console.log(e)})):e.print||(e.print=function(){}),ca&&(e.load=importScripts),void 0===e.setWindowTitle&&(e.setWindowTitle=function(e){document.title=e})}function ha(e){eval.call(null,e)}for(k in!e.load&&e.read&&(e.load=function(t){ha(e.read(t))}),e.print||(e.print=function(){}),e.printErr||(e.printErr=e.print),e.arguments||(e.arguments=[]),e.thisProgram||(e.thisProgram="./this.program"),e.print=e.print,e.W=e.printErr,e.preRun=[],e.postRun=[],aa)aa.hasOwnProperty(k)&&(e[k]=aa[k]);var n={rb:function(e){ka=e},fb:function(){return ka},ua:function(){return m},ba:function(e){m=e},Ka:function(e){switch(e){case"i1":case"i8":return 1;case"i16":return 2;case"i32":return 4;case"i64":return 8;case"float":return 4;case"double":return 8;default:return"*"===e[e.length-1]?n.J:"i"===e[0]?(assert(0==(e=parseInt(e.substr(1)))%8),e/8):0}},eb:function(e){return Math.max(n.Ka(e),n.J)},ud:16,Qd:function(e,t){return"double"===t||"i64"===t?7&e&&(assert(4==(7&e)),e+=4):assert(0==(3&e)),e},Ed:function(e,t,r){return r||"i64"!=e&&"double"!=e?e?Math.min(t||(e?n.eb(e):0),n.J):Math.min(t,8):8},L:function(t,r,i){return i&&i.length?((i=i.splice?i:Array.prototype.slice.call(i)).splice(0,0,r),e["dynCall_"+t].apply(null,i)):e["dynCall_"+t].call(null,r)},Z:[],Xa:function(e){for(var t=0;t>>0)+4294967296*(t>>>0):(e>>>0)+4294967296*(0|t)},Ua:8,J:4,vd:0},na=(e.Runtime=n,n.addFunction=n.Xa,n.removeFunction=n.nb,!1),oa,pa,ka,ra,sa;function assert(e,t){e||x("Assertion failed: "+t)}function qa(a){var b=e["_"+a];if(!b)try{b=eval("_"+a)}catch(c){}return assert(b,"Cannot call unknown function "+a+" (perhaps LLVM optimizations or closure removed it?)"),b}function wa(e,t,r){switch(r="*"===(r=r||"i8").charAt(r.length-1)?"i32":r){case"i1":case"i8":y[e>>0]=t;break;case"i16":z[e>>1]=t;break;case"i32":C[e>>2]=t;break;case"i64":pa=[t>>>0,1<=+xa(oa=t)?0>>0:~~+Aa((oa-(~~oa>>>0))/4294967296)>>>0:0],C[e>>2]=pa[0],C[e+4>>2]=pa[1];break;case"float":Ba[e>>2]=t;break;case"double":Ca[e>>3]=t;break;default:x("invalid type for setValue: "+r)}}function Da(e,t){switch(t="*"===(t=t||"i8").charAt(t.length-1)?"i32":t){case"i1":case"i8":return y[e>>0];case"i16":return z[e>>1];case"i32":case"i64":return C[e>>2];case"float":return Ba[e>>2];case"double":return Ca[e>>3];default:x("invalid type for setValue: "+t)}return null}function D(e,t,r,i){var o,a,s,l="number"==typeof e?(o=!0,e):(o=!1,e.length),u="string"==typeof t?t:null;if(r=4==r?i:[Ea,n.aa,n.Ra,n.R][void 0===r?2:r](Math.max(l,u?1:t.length)),o){for(assert(0==(3&(i=r))),e=r+(-4&l);i>2]=0;for(e=r+l;i>0]=0}else if("i8"===u)e.subarray||e.slice?E.set(e,r):E.set(new Uint8Array(e),r);else{i=0;for(;i>0],0!=i||r)&&(o++,!r||o!=r););if(r=r||o,i="",n<128){for(;0>10,56320|1023&r)))):s+=String.fromCharCode(r)}}function Ka(e,t,r,i){if(!(0>6}else{if(a<=65535){if(i<=r+2)break;t[r++]=224|a>>12}else{if(a<=2097151){if(i<=r+3)break;t[r++]=240|a>>18}else{if(a<=67108863){if(i<=r+4)break;t[r++]=248|a>>24}else{if(i<=r+5)break;t[r++]=252|a>>30,t[r++]=128|a>>24&63}t[r++]=128|a>>18&63}t[r++]=128|a>>12&63}t[r++]=128|a>>6&63}t[r++]=128|63&a}}return t[r]=0,r-n}function La(e){for(var t=0,r=0;r"):o=n;e:for(;c>0];if(!r)return t;t+=String.fromCharCode(r)}},e.stringToAscii=function(e,t){return Ia(e,t,!1)},e.UTF8ArrayToString=Ja,e.UTF8ToString=function(e){return Ja(E,e)},e.stringToUTF8Array=Ka,e.stringToUTF8=function(e,t,r){return Ka(e,E,t,r)},e.lengthBytesUTF8=La,e.UTF16ToString=function(e){for(var t=0,r="";;){var i=z[e+2*t>>1];if(0==i)return r;++t,r+=String.fromCharCode(i)}},e.stringToUTF16=function(e,t,r){if((r=void 0===r?2147483647:r)<2)return 0;var i=t;r=(r-=2)<2*e.length?r/2:e.length;for(var n=0;n>1]=e.charCodeAt(n),t+=2;return z[t>>1]=0,t-i},e.lengthBytesUTF16=function(e){return 2*e.length},e.UTF32ToString=function(e){for(var t=0,r="";;){var i=C[e+4*t>>2];if(0==i)return r;++t,65536<=i?(i-=65536,r+=String.fromCharCode(55296|i>>10,56320|1023&i)):r+=String.fromCharCode(i)}},e.stringToUTF32=function(e,t,r){if((r=void 0===r?2147483647:r)<4)return 0;var i=t;r=i+r-4;for(var n=0;n>2]=o,r<(t+=4)+4)break}return C[t>>2]=0,t-i},e.lengthBytesUTF32=function(e){for(var t=0,r=0;r>0]=e[r],r+=1}function ta(e,t){for(var r=0;r>0]=e[r]}function Ia(e,t,r){for(var i=0;i>0]=e.charCodeAt(i);r||(y[t>>0]=0)}e.addOnPreRun=fb,e.addOnInit=function(e){cb.unshift(e)},e.addOnPreMain=function(e){db.unshift(e)},e.addOnExit=function(e){H.unshift(e)},e.addOnPostRun=gb,e.intArrayFromString=hb,e.intArrayToString=function(e){for(var t=[],r=0;r>>16)*i+r*(t>>>16)<<16)|0}),Math.Jd=Math.imul,Math.clz32||(Math.clz32=function(e){e>>>=0;for(var t=0;t<32;t++)if(e&1<<31-t)return t;return 32}),Math.Ad=Math.clz32;var xa=Math.abs,Aa=Math.ceil,za=Math.floor,ya=Math.min,I=0,ib=null,jb=null;function kb(){I++,e.monitorRunDependencies&&e.monitorRunDependencies(I)}function lb(){var t;I--,e.monitorRunDependencies&&e.monitorRunDependencies(I),0==I&&(null!==ib&&(clearInterval(ib),ib=null),jb)&&(t=jb,jb=null,t())}e.addRunDependency=kb,e.removeRunDependency=lb,e.preloadedImages={},e.preloadedAudios={},Ta=8,la=Ta+5888,cb.push(),D([124,0,0,0,98,7,0,0,124,0,0,0,111,7,0,0,164,0,0,0,124,7,0,0,16,0,0,0,0,0,0,0,164,0,0,0,157,7,0,0,24,0,0,0,0,0,0,0,164,0,0,0,227,7,0,0,24,0,0,0,0,0,0,0,164,0,0,0,191,7,0,0,56,0,0,0,0,0,0,0,164,0,0,0,5,8,0,0,40,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,40,0,0,0,1,0,0,0,2,0,0,0,3,0,0,0,4,0,0,0,1,0,0,0,1,0,0,0,1,0,0,0,1,0,0,0,0,0,0,0,88,0,0,0,1,0,0,0,5,0,0,0,3,0,0,0,4,0,0,0,1,0,0,0,2,0,0,0,2,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,114,9,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,124,1,0,0,236,1,0,0,236,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,255,255,255,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,5,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,0,0,0,4,0,0,0,239,20,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,255,255,255,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,5,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,5,0,0,0,4,0,0,0,231,16,0,0,0,4,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,10,255,255,255,255,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,37,115,40,37,117,41,58,32,65,115,115,101,114,116,105,111,110,32,102,97,105,108,117,114,101,58,32,34,37,115,34,10,0,109,95,115,105,122,101,32,60,61,32,109,95,99,97,112,97,99,105,116,121,0,46,47,99,114,110,95,100,101,99,111,109,112,46,104,0,109,105,110,95,110,101,119,95,99,97,112,97,99,105,116,121,32,60,32,40,48,120,55,70,70,70,48,48,48,48,85,32,47,32,101,108,101,109,101,110,116,95,115,105,122,101,41,0,110,101,119,95,99,97,112,97,99,105,116,121,32,38,38,32,40,110,101,119,95,99,97,112,97,99,105,116,121,32,62,32,109,95,99,97,112,97,99,105,116,121,41,0,110,117,109,95,99,111,100,101,115,91,99,93,0,115,111,114,116,101,100,95,112,111,115,32,60,32,116,111,116,97,108,95,117,115,101,100,95,115,121,109,115,0,112,67,111,100,101,115,105,122,101,115,91,115,121,109,95,105,110,100,101,120,93,32,61,61,32,99,111,100,101,115,105,122,101,0,116,32,60,32,40,49,85,32,60,60,32,116,97,98,108,101,95,98,105,116,115,41,0,109,95,108,111,111,107,117,112,91,116,93,32,61,61,32,99,85,73,78,84,51,50,95,77,65,88,0,99,114,110,100,95,109,97,108,108,111,99,58,32,115,105,122,101,32,116,111,111,32,98,105,103,0,99,114,110,100,95,109,97,108,108,111,99,58,32,111,117,116,32,111,102,32,109,101,109,111,114,121,0,40,40,117,105,110,116,51,50,41,112,95,110,101,119,32,38,32,40,67,82,78,68,95,77,73,78,95,65,76,76,79,67,95,65,76,73,71,78,77,69,78,84,32,45,32,49,41,41,32,61,61,32,48,0,99,114,110,100,95,114,101,97,108,108,111,99,58,32,98,97,100,32,112,116,114,0,99,114,110,100,95,102,114,101,101,58,32,98,97,100,32,112,116,114,0,102,97,108,115,101,0,40,116,111,116,97,108,95,115,121,109,115,32,62,61,32,49,41,32,38,38,32,40,116,111,116,97,108,95,115,121,109,115,32,60,61,32,112,114,101,102,105,120,95,99,111,100,105,110,103,58,58,99,77,97,120,83,117,112,112,111,114,116,101,100,83,121,109,115,41,0,17,18,19,20,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15,16,48,0,110,117,109,95,98,105,116,115,32,60,61,32,51,50,85,0,109,95,98,105,116,95,99,111,117,110,116,32,60,61,32,99,66,105,116,66,117,102,83,105,122,101,0,116,32,33,61,32,99,85,73,78,84,51,50,95,77,65,88,0,109,111,100,101,108,46,109,95,99,111,100,101,95,115,105,122,101,115,91,115,121,109,93,32,61,61,32,108,101,110,0,0,2,3,1,0,2,3,4,5,6,7,1,40,108,101,110,32,62,61,32,49,41,32,38,38,32,40,108,101,110,32,60,61,32,99,77,97,120,69,120,112,101,99,116,101,100,67,111,100,101,83,105,122,101,41,0,105,32,60,32,109,95,115,105,122,101,0,110,101,120,116,95,108,101,118,101,108,95,111,102,115,32,62,32,99,117,114,95,108,101,118,101,108,95,111,102,115,0,1,2,2,3,3,3,3,4,0,0,0,0,0,0,1,1,0,1,0,1,0,0,1,2,1,2,0,0,0,1,0,2,1,0,2,0,0,1,2,3,110,117,109,32,38,38,32,40,110,117,109,32,61,61,32,126,110,117,109,95,99,104,101,99,107,41,0,83,116,57,101,120,99,101,112,116,105,111,110,0,83,116,57,116,121,112,101,95,105,110,102,111,0,78,49,48,95,95,99,120,120,97,98,105,118,49,49,54,95,95,115,104,105,109,95,116,121,112,101,95,105,110,102,111,69,0,78,49,48,95,95,99,120,120,97,98,105,118,49,49,55,95,95,99,108,97,115,115,95,116,121,112,101,95,105,110,102,111,69,0,78,49,48,95,95,99,120,120,97,98,105,118,49,49,57,95,95,112,111,105,110,116,101,114,95,116,121,112,101,95,105,110,102,111,69,0,78,49,48,95,95,99,120,120,97,98,105,118,49,49,55,95,95,112,98,97,115,101,95,116,121,112,101,95,105,110,102,111,69,0,78,49,48,95,95,99,120,120,97,98,105,118,49,50,48,95,95,115,105,95,99,108,97,115,115,95,116,121,112,101,95,105,110,102,111,69,0,112,116,104,114,101,97,100,95,111,110,99,101,32,102,97,105,108,117,114,101,32,105,110,32,95,95,99,120,97,95,103,101,116,95,103,108,111,98,97,108,115,95,102,97,115,116,40,41,0,116,101,114,109,105,110,97,116,101,95,104,97,110,100,108,101,114,32,117,110,101,120,112,101,99,116,101,100,108,121,32,114,101,116,117,114,110,101,100,0,99,97,110,110,111,116,32,99,114,101,97,116,101,32,112,116,104,114,101,97,100,32,107,101,121,32,102,111,114,32,95,95,99,120,97,95,103,101,116,95,103,108,111,98,97,108,115,40,41,0,99,97,110,110,111,116,32,122,101,114,111,32,111,117,116,32,116,104,114,101,97,100,32,118,97,108,117,101,32,102,111,114,32,95,95,99,120,97,95,103,101,116,95,103,108,111,98,97,108,115,40,41,0,116,101,114,109,105,110,97,116,105,110,103,32,119,105,116,104,32,37,115,32,101,120,99,101,112,116,105,111,110,32,111,102,32,116,121,112,101,32,37,115,58,32,37,115,0,116,101,114,109,105,110,97,116,105,110,103,32,119,105,116,104,32,37,115,32,101,120,99,101,112,116,105,111,110,32,111,102,32,116,121,112,101,32,37,115,0,116,101,114,109,105,110,97,116,105,110,103,32,119,105,116,104,32,37,115,32,102,111,114,101,105,103,110,32,101,120,99,101,112,116,105,111,110,0,116,101,114,109,105,110,97,116,105,110,103,0,117,110,99,97,117,103,104,116,0,84,33,34,25,13,1,2,3,17,75,28,12,16,4,11,29,18,30,39,104,110,111,112,113,98,32,5,6,15,19,20,21,26,8,22,7,40,36,23,24,9,10,14,27,31,37,35,131,130,125,38,42,43,60,61,62,63,67,71,74,77,88,89,90,91,92,93,94,95,96,97,99,100,101,102,103,105,106,107,108,114,115,116,121,122,123,124,0,73,108,108,101,103,97,108,32,98,121,116,101,32,115,101,113,117,101,110,99,101,0,68,111,109,97,105,110,32,101,114,114,111,114,0,82,101,115,117,108,116,32,110,111,116,32,114,101,112,114,101,115,101,110,116,97,98,108,101,0,78,111,116,32,97,32,116,116,121,0,80,101,114,109,105,115,115,105,111,110,32,100,101,110,105,101,100,0,79,112,101,114,97,116,105,111,110,32,110,111,116,32,112,101,114,109,105,116,116,101,100,0,78,111,32,115,117,99,104,32,102,105,108,101,32,111,114,32,100,105,114,101,99,116,111,114,121,0,78,111,32,115,117,99,104,32,112,114,111,99,101,115,115,0,70,105,108,101,32,101,120,105,115,116,115,0,86,97,108,117,101,32,116,111,111,32,108,97,114,103,101,32,102,111,114,32,100,97,116,97,32,116,121,112,101,0,78,111,32,115,112,97,99,101,32,108,101,102,116,32,111,110,32,100,101,118,105,99,101,0,79,117,116,32,111,102,32,109,101,109,111,114,121,0,82,101,115,111,117,114,99,101,32,98,117,115,121,0,73,110,116,101,114,114,117,112,116,101,100,32,115,121,115,116,101,109,32,99,97,108,108,0,82,101,115,111,117,114,99,101,32,116,101,109,112,111,114,97,114,105,108,121,32,117,110,97,118,97,105,108,97,98,108,101,0,73,110,118,97,108,105,100,32,115,101,101,107,0,67,114,111,115,115,45,100,101,118,105,99,101,32,108,105,110,107,0,82,101,97,100,45,111,110,108,121,32,102,105,108,101,32,115,121,115,116,101,109,0,68,105,114,101,99,116,111,114,121,32,110,111,116,32,101,109,112,116,121,0,67,111,110,110,101,99,116,105,111,110,32,114,101,115,101,116,32,98,121,32,112,101,101,114,0,79,112,101,114,97,116,105,111,110,32,116,105,109,101,100,32,111,117,116,0,67,111,110,110,101,99,116,105,111,110,32,114,101,102,117,115,101,100,0,72,111,115,116,32,105,115,32,100,111,119,110,0,72,111,115,116,32,105,115,32,117,110,114,101,97,99,104,97,98,108,101,0,65,100,100,114,101,115,115,32,105,110,32,117,115,101,0,66,114,111,107,101,110,32,112,105,112,101,0,73,47,79,32,101,114,114,111,114,0,78,111,32,115,117,99,104,32,100,101,118,105,99,101,32,111,114,32,97,100,100,114,101,115,115,0,66,108,111,99,107,32,100,101,118,105,99,101,32,114,101,113,117,105,114,101,100,0,78,111,32,115,117,99,104,32,100,101,118,105,99,101,0,78,111,116,32,97,32,100,105,114,101,99,116,111,114,121,0,73,115,32,97,32,100,105,114,101,99,116,111,114,121,0,84,101,120,116,32,102,105,108,101,32,98,117,115,121,0,69,120,101,99,32,102,111,114,109,97,116,32,101,114,114,111,114,0,73,110,118,97,108,105,100,32,97,114,103,117,109,101,110,116,0,65,114,103,117,109,101,110,116,32,108,105,115,116,32,116,111,111,32,108,111,110,103,0,83,121,109,98,111,108,105,99,32,108,105,110,107,32,108,111,111,112,0,70,105,108,101,110,97,109,101,32,116,111,111,32,108,111,110,103,0,84,111,111,32,109,97,110,121,32,111,112,101,110,32,102,105,108,101,115,32,105,110,32,115,121,115,116,101,109,0,78,111,32,102,105,108,101,32,100,101,115,99,114,105,112,116,111,114,115,32,97,118,97,105,108,97,98,108,101,0,66,97,100,32,102,105,108,101,32,100,101,115,99,114,105,112,116,111,114,0,78,111,32,99,104,105,108,100,32,112,114,111,99,101,115,115,0,66,97,100,32,97,100,100,114,101,115,115,0,70,105,108,101,32,116,111,111,32,108,97,114,103,101,0,84,111,111,32,109,97,110,121,32,108,105,110,107,115,0,78,111,32,108,111,99,107,115,32,97,118,97,105,108,97,98,108,101,0,82,101,115,111,117,114,99,101,32,100,101,97,100,108,111,99,107,32,119,111,117,108,100,32,111,99,99,117,114,0,83,116,97,116,101,32,110,111,116,32,114,101,99,111,118,101,114,97,98,108,101,0,80,114,101,118,105,111,117,115,32,111,119,110,101,114,32,100,105,101,100,0,79,112,101,114,97,116,105,111,110,32,99,97,110,99,101,108,101,100,0,70,117,110,99,116,105,111,110,32,110,111,116,32,105,109,112,108,101,109,101,110,116,101,100,0,78,111,32,109,101,115,115,97,103,101,32,111,102,32,100,101,115,105,114,101,100,32,116,121,112,101,0,73,100,101,110,116,105,102,105,101,114,32,114,101,109,111,118,101,100,0,68,101,118,105,99,101,32,110,111,116,32,97,32,115,116,114,101,97,109,0,78,111,32,100,97,116,97,32,97,118,97,105,108,97,98,108,101,0,68,101,118,105,99,101,32,116,105,109,101,111,117,116,0,79,117,116,32,111,102,32,115,116,114,101,97,109,115,32,114,101,115,111,117,114,99,101,115,0,76,105,110,107,32,104,97,115,32,98,101,101,110,32,115,101,118,101,114,101,100,0,80,114,111,116,111,99,111,108,32,101,114,114,111,114,0,66,97,100,32,109,101,115,115,97,103,101,0,70,105,108,101,32,100,101,115,99,114,105,112,116,111,114,32,105,110,32,98,97,100,32,115,116,97,116,101,0,78,111,116,32,97,32,115,111,99,107,101,116,0,68,101,115,116,105,110,97,116,105,111,110,32,97,100,100,114,101,115,115,32,114,101,113,117,105,114,101,100,0,77,101,115,115,97,103,101,32,116,111,111,32,108,97,114,103,101,0,80,114,111,116,111,99,111,108,32,119,114,111,110,103,32,116,121,112,101,32,102,111,114,32,115,111,99,107,101,116,0,80,114,111,116,111,99,111,108,32,110,111,116,32,97,118,97,105,108,97,98,108,101,0,80,114,111,116,111,99,111,108,32,110,111,116,32,115,117,112,112,111,114,116,101,100,0,83,111,99,107,101,116,32,116,121,112,101,32,110,111,116,32,115,117,112,112,111,114,116,101,100,0,78,111,116,32,115,117,112,112,111,114,116,101,100,0,80,114,111,116,111,99,111,108,32,102,97,109,105,108,121,32,110,111,116,32,115,117,112,112,111,114,116,101,100,0,65,100,100,114,101,115,115,32,102,97,109,105,108,121,32,110,111,116,32,115,117,112,112,111,114,116,101,100,32,98,121,32,112,114,111,116,111,99,111,108,0,65,100,100,114,101,115,115,32,110,111,116,32,97,118,97,105,108,97,98,108,101,0,78,101,116,119,111,114,107,32,105,115,32,100,111,119,110,0,78,101,116,119,111,114,107,32,117,110,114,101,97,99,104,97,98,108,101,0,67,111,110,110,101,99,116,105,111,110,32,114,101,115,101,116,32,98,121,32,110,101,116,119,111,114,107,0,67,111,110,110,101,99,116,105,111,110,32,97,98,111,114,116,101,100,0,78,111,32,98,117,102,102,101,114,32,115,112,97,99,101,32,97,118,97,105,108,97,98,108,101,0,83,111,99,107,101,116,32,105,115,32,99,111,110,110,101,99,116,101,100,0,83,111,99,107,101,116,32,110,111,116,32,99,111,110,110,101,99,116,101,100,0,67,97,110,110,111,116,32,115,101,110,100,32,97,102,116,101,114,32,115,111,99,107,101,116,32,115,104,117,116,100,111,119,110,0,79,112,101,114,97,116,105,111,110,32,97,108,114,101,97,100,121,32,105,110,32,112,114,111,103,114,101,115,115,0,79,112,101,114,97,116,105,111,110,32,105,110,32,112,114,111,103,114,101,115,115,0,83,116,97,108,101,32,102,105,108,101,32,104,97,110,100,108,101,0,82,101,109,111,116,101,32,73,47,79,32,101,114,114,111,114,0,81,117,111,116,97,32,101,120,99,101,101,100,101,100,0,78,111,32,109,101,100,105,117,109,32,102,111,117,110,100,0,87,114,111,110,103,32,109,101,100,105,117,109,32,116,121,112,101,0,78,111,32,101,114,114,111,114,32,105,110,102,111,114,109,97,116,105,111,110,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,17,0,10,0,17,17,17,0,0,0,0,5,0,0,0,0,0,0,9,0,0,0,0,11,0,0,0,0,0,0,0,0,17,0,15,10,17,17,17,3,10,7,0,1,19,9,11,11,0,0,9,6,11,0,0,11,0,6,17,0,0,0,17,17,17,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,11,0,0,0,0,0,0,0,0,17,0,10,10,17,17,17,0,10,0,0,2,0,9,11,0,0,0,9,0,11,0,0,11,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,12,0,0,0,0,0,0,0,0,0,0,0,12,0,0,0,0,12,0,0,0,0,9,12,0,0,0,0,0,12,0,0,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,14,0,0,0,0,0,0,0,0,0,0,0,13,0,0,0,4,13,0,0,0,0,9,14,0,0,0,0,0,14,0,0,14,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,16,0,0,0,0,0,0,0,0,0,0,0,15,0,0,0,0,15,0,0,0,0,9,16,0,0,0,0,0,16,0,0,16,0,0,18,0,0,0,18,18,18,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,18,0,0,0,18,18,18,0,0,0,0,0,0,9,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,11,0,0,0,0,0,0,0,0,0,0,0,10,0,0,0,0,10,0,0,0,0,9,11,0,0,0,0,0,11,0,0,11,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,12,0,0,0,0,0,0,0,0,0,0,0,12,0,0,0,0,12,0,0,0,0,9,12,0,0,0,0,0,12,0,0,12,0,0,48,49,50,51,52,53,54,55,56,57,65,66,67,68,69,70,45,43,32,32,32,48,88,48,120,0,40,110,117,108,108,41,0,45,48,88,43,48,88,32,48,88,45,48,120,43,48,120,32,48,120,0,105,110,102,0,73,78,70,0,110,97,110,0,78,65,78,0,46,0],"i8",4,n.Ua);var mb=n.ja(D(12,"i8",2),8);function ob(t){return e.___errno_location&&(C[e.___errno_location()>>2]=t),t}assert(0==mb%8),e._i64Subtract=nb;var J={I:1,F:2,ed:3,bc:4,H:5,Aa:6,vb:7,zc:8,ea:9,Jb:10,va:11,qd:11,Ta:12,da:13,Vb:14,Lc:15,fa:16,wa:17,rd:18,ha:19,ya:20,P:21,q:22,uc:23,Sa:24,Q:25,nd:26,Wb:27,Hc:28,ia:29,bd:30,nc:31,Vc:32,Sb:33,Zc:34,Dc:42,Zb:43,Kb:44,ec:45,fc:46,gc:47,mc:48,od:49,xc:50,dc:51,Pb:35,Ac:37,Bb:52,Eb:53,sd:54,vc:55,Fb:56,Gb:57,Qb:35,Hb:59,Jc:60,yc:61,kd:62,Ic:63,Ec:64,Fc:65,ad:66,Bc:67,yb:68,gd:69,Lb:70,Wc:71,pc:72,Tb:73,Db:74,Qc:76,Cb:77,$c:78,hc:79,ic:80,lc:81,kc:82,jc:83,Kc:38,za:39,qc:36,ga:40,Rc:95,Uc:96,Ob:104,wc:105,zb:97,Yc:91,Oc:88,Gc:92,cd:108,Nb:111,wb:98,Mb:103,tc:101,rc:100,ld:110,Xb:112,Yb:113,ac:115,Ab:114,Rb:89,oc:90,Xc:93,dd:94,xb:99,sc:102,cc:106,Mc:107,md:109,pd:87,Ub:122,hd:116,Pc:95,Cc:123,$b:84,Sc:75,Ib:125,Nc:131,Tc:130,jd:86};function pb(e,t){H.push(function(){n.L("vi",e,[t])}),pb.level=H.length}function tb(){return!!tb.p}e._memset=qb,e._bitshift64Lshr=rb,e._bitshift64Shl=sb;var ub=[],vb={};function wb(e,t){wb.p||(wb.p={}),e in wb.p||(n.L("v",t),wb.p[e]=1)}var xb={0:"Success",1:"Not super-user",2:"No such file or directory",3:"No such process",4:"Interrupted system call",5:"I/O error",6:"No such device or address",7:"Arg list too long",8:"Exec format error",9:"Bad file number",10:"No children",11:"No more processes",12:"Not enough core",13:"Permission denied",14:"Bad address",15:"Block device required",16:"Mount device busy",17:"File exists",18:"Cross-device link",19:"No such device",20:"Not a directory",21:"Is a directory",22:"Invalid argument",23:"Too many open files in system",24:"Too many open files",25:"Not a typewriter",26:"Text file busy",27:"File too large",28:"No space left on device",29:"Illegal seek",30:"Read only file system",31:"Too many links",32:"Broken pipe",33:"Math arg out of domain of func",34:"Math result not representable",35:"File locking deadlock error",36:"File or path name too long",37:"No record locks available",38:"Function not implemented",39:"Directory not empty",40:"Too many symbolic links",42:"No message of desired type",43:"Identifier removed",44:"Channel number out of range",45:"Level 2 not synchronized",46:"Level 3 halted",47:"Level 3 reset",48:"Link number out of range",49:"Protocol driver not attached",50:"No CSI structure available",51:"Level 2 halted",52:"Invalid exchange",53:"Invalid request descriptor",54:"Exchange full",55:"No anode",56:"Invalid request code",57:"Invalid slot",59:"Bad font file fmt",60:"Device not a stream",61:"No data (for no delay io)",62:"Timer expired",63:"Out of streams resources",64:"Machine is not on the network",65:"Package not installed",66:"The object is remote",67:"The link has been severed",68:"Advertise error",69:"Srmount error",70:"Communication error on send",71:"Protocol error",72:"Multihop attempted",73:"Cross mount point (not really error)",74:"Trying to read unreadable message",75:"Value too large for defined data type",76:"Given log. name not unique",77:"f.d. invalid for this operation",78:"Remote address changed",79:"Can access a needed shared lib",80:"Accessing a corrupted shared lib",81:".lib section in a.out corrupted",82:"Attempting to link in too many libs",83:"Attempting to exec a shared library",84:"Illegal byte sequence",86:"Streams pipe error",87:"Too many users",88:"Socket operation on non-socket",89:"Destination address required",90:"Message too long",91:"Protocol wrong type for socket",92:"Protocol not available",93:"Unknown protocol",94:"Socket type not supported",95:"Not supported",96:"Protocol family not supported",97:"Address family not supported by protocol family",98:"Address already in use",99:"Address not available",100:"Network interface is not configured",101:"Network is unreachable",102:"Connection reset by network",103:"Connection aborted",104:"Connection reset by peer",105:"No buffer space available",106:"Socket is already connected",107:"Socket is not connected",108:"Can't send after socket shutdown",109:"Too many references",110:"Connection timed out",111:"Connection refused",112:"Host is down",113:"Host is unreachable",114:"Socket already connected",115:"Connection already in progress",116:"Stale file handle",122:"Quota exceeded",123:"No medium (in tape drive)",125:"Operation canceled",130:"Previous owner died",131:"State not recoverable"};function yb(e,t){for(var r=0,i=e.length-1;0<=i;i--){var n=e[i];"."===n?e.splice(i,1):".."===n?(e.splice(i,1),r++):r&&(e.splice(i,1),r--)}if(t)for(;r--;)e.unshift("..");return e}function zb(e){var t="/"===e.charAt(0),r="/"===e.substr(-1);return(e=(e=yb(e.split("/").filter(function(e){return!!e}),!t).join("/"))||t?e:".")&&r&&(e+="/"),(t?"/":"")+e}function Ab(e){var t=/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/.exec(e).slice(1);return e=t[0],t=t[1],e||t?e+(t=t&&t.substr(0,t.length-1)):"."}function Bb(e){var t;return"/"===e?"/":-1===(t=e.lastIndexOf("/"))?e:e.substr(t+1)}function Cb(){return zb(Array.prototype.slice.call(arguments,0).join("/"))}function K(e,t){return zb(e+"/"+t)}function Db(){for(var e="",t=!1,r=arguments.length-1;-1<=r&&!t;r--){if("string"!=typeof(t=0<=r?arguments[r]:"/"))throw new TypeError("Arguments to path.resolve must be strings");if(!t)return"";e=t+"/"+e,t="/"===t.charAt(0)}return(t?"/":"")+(e=yb(e.split("/").filter(function(e){return!!e}),!t).join("/"))||"."}var Eb=[];function Fb(e,t){Eb[e]={input:[],output:[],N:t},Gb(e,Hb)}var Hb={open:function(e){var t=Eb[e.g.rdev];if(!t)throw new L(J.ha);e.tty=t,e.seekable=!1},close:function(e){e.tty.N.flush(e.tty)},flush:function(e){e.tty.N.flush(e.tty)},read:function(e,t,r,i){if(!e.tty||!e.tty.N.La)throw new L(J.Aa);for(var n,o=0,a=0;ae.e.length&&(e.e=M.cb(e),e.o=e.e.length),!e.e||e.e.subarray){var r=e.e?e.e.buffer.byteLength:0;t<=r||(t=Math.max(t,r*(r<1048576?2:1.125)|0),0!=r&&(t=Math.max(t,256)),r=e.e,e.e=new Uint8Array(t),0t)e.e.length=t;else for(;e.e.length=e.g.o)return 0;if(assert(0<=(e=Math.min(e.g.o-n,i))),8>1)}catch(e){if(e.code)throw new L(J[e.code]);throw e}return t.mode},B:function(e){for(var t=[];e.parent!==e;)t.push(e.name),e=e.parent;return t.push(e.A.pa.root),t.reverse(),Cb.apply(null,t)},Ha:{0:"r",1:"r+",2:"r+",64:"r",65:"r+",66:"r+",129:"rx+",193:"rx+",514:"w+",577:"w",578:"w+",705:"wx",706:"wx+",1024:"a",1025:"a",1026:"a+",1089:"a",1090:"a+",1153:"ax",1154:"ax+",1217:"ax",1218:"ax+",4096:"rs",4098:"rs+"},$a:function(e){if((e&=-32769)in P.Ha)return P.Ha[e];throw new L(J.q)},k:{D:function(e){var t;e=P.B(e);try{t=fs.lstatSync(e)}catch(e){if(e.code)throw new L(J[e.code]);throw e}return P.$&&!t.K&&(t.K=4096),P.$&&!t.blocks&&(t.blocks=(t.size+t.K-1)/t.K|0),{dev:t.dev,ino:t.ino,mode:t.mode,nlink:t.nlink,uid:t.uid,gid:t.gid,rdev:t.rdev,size:t.size,atime:t.atime,mtime:t.mtime,ctime:t.ctime,K:t.K,blocks:t.blocks}},u:function(e,t){var r=P.B(e);try{void 0!==t.mode&&(fs.chmodSync(r,t.mode),e.mode=t.mode),void 0!==t.size&&fs.truncateSync(r,t.size)}catch(e){if(e.code)throw new L(J[e.code]);throw e}},lookup:function(e,t){var r=K(P.B(e),t),r=P.Ja(r);return P.createNode(e,t,r)},T:function(e,t,r,i){e=P.createNode(e,t,r,i),t=P.B(e);try{N(e.mode)?fs.mkdirSync(t,e.mode):fs.writeFileSync(t,"",{mode:e.mode})}catch(e){if(e.code)throw new L(J[e.code]);throw e}return e},rename:function(e,t,r){e=P.B(e),t=K(P.B(t),r);try{fs.renameSync(e,t)}catch(e){if(e.code)throw new L(J[e.code]);throw e}},unlink:function(e,t){e=K(P.B(e),t);try{fs.unlinkSync(e)}catch(e){if(e.code)throw new L(J[e.code]);throw e}},rmdir:function(e,t){e=K(P.B(e),t);try{fs.rmdirSync(e)}catch(e){if(e.code)throw new L(J[e.code]);throw e}},readdir:function(e){e=P.B(e);try{return fs.readdirSync(e)}catch(e){if(e.code)throw new L(J[e.code]);throw e}},symlink:function(e,t,r){e=K(P.B(e),t);try{fs.symlinkSync(r,e)}catch(e){if(e.code)throw new L(J[e.code]);throw e}},readlink:function(e){var t=P.B(e);try{return t=fs.readlinkSync(t),Ob.relative(Ob.resolve(e.A.pa.root),t)}catch(e){if(e.code)throw new L(J[e.code]);throw e}}},n:{open:function(e){var t=P.B(e.g);try{32768==(61440&e.g.mode)&&(e.V=fs.openSync(t,P.$a(e.flags)))}catch(e){if(e.code)throw new L(J[e.code]);throw e}},close:function(e){try{32768==(61440&e.g.mode)&&e.V&&fs.closeSync(e.V)}catch(e){if(e.code)throw new L(J[e.code]);throw e}},read:function(e,t,r,i,n){if(0===i)return 0;var o,a=new Buffer(i);try{o=fs.readSync(e.V,a,0,i,n)}catch(e){throw new L(J[e.code])}if(0>>0)%Q.length}function Xb(e){var t=Wb(e.parent.id,e.name);e.M=Q[t],Q[t]=e}function Nb(e,t){var r;if(r=(r=Yb(e,"x"))?r:e.k.lookup?0:J.da)throw new L(r,e);for(r=Q[Wb(e.id,t)];r;r=r.M){var i=r.name;if(r.parent.id===e.id&&i===t)return r}return e.k.lookup(e,t)}function Lb(e,t,r,i){return Zb||((Zb=function(e,t,r,i){this.parent=e=e||this,this.A=e.A,this.U=null,this.id=Sb++,this.name=t,this.mode=r,this.k={},this.n={},this.rdev=i}).prototype={},Object.defineProperties(Zb.prototype,{read:{get:function(){return 365==(365&this.mode)},set:function(e){e?this.mode|=365:this.mode&=-366}},write:{get:function(){return 146==(146&this.mode)},set:function(e){e?this.mode|=146:this.mode&=-147}},kb:{get:function(){return N(this.mode)}},jb:{get:function(){return 8192==(61440&this.mode)}}})),Xb(e=new Zb(e,t,r,i)),e}function N(e){return 16384==(61440&e)}var $b={r:0,rs:1052672,"r+":2,w:577,wx:705,xw:705,"w+":578,"wx+":706,"xw+":706,a:1089,ax:1217,xa:1217,"a+":1090,"ax+":1218,"xa+":1218};function Yb(e,t){return Tb||(-1===t.indexOf("r")||292&e.mode)&&(-1===t.indexOf("w")||146&e.mode)&&(-1===t.indexOf("x")||73&e.mode)?0:J.da}function ac(e,t){try{return Nb(e,t),J.wa}catch(e){}return Yb(e,"wx")}function bc(){for(var e=0;e<=4096;e++)if(!Rb[e])return e;throw new L(J.Sa)}function cc(e){dc||((dc=function(){}).prototype={},Object.defineProperties(dc.prototype,{object:{get:function(){return this.g},set:function(e){this.g=e}},Ld:{get:function(){return 1!=(2097155&this.flags)}},Md:{get:function(){return 0!=(2097155&this.flags)}},Kd:{get:function(){return 1024&this.flags}}}));var t,r=new dc;for(t in e)r[t]=e[t];return e=r,r=bc(),e.fd=r,Rb[r]=e}var Kb={open:function(e){e.n=Qb[e.g.rdev].n,e.n.open&&e.n.open(e)},G:function(){throw new L(J.ia)}},qc;function Gb(e,t){Qb[e]={n:t}}function ec(e,t){var r,i="/"===t,n=!t;if(i&&Pb)throw new L(J.fa);if(!i&&!n){if(t=(r=S(t,{Ia:!1})).path,(r=r.g).U)throw new L(J.fa);if(!N(r.mode))throw new L(J.ya)}n={type:e,pa:{},Oa:t,lb:[]},t=e.A(n);(t.A=n).root=t,i?Pb=t:r&&(r.U=n,r.A&&r.A.lb.push(n))}function fc(e,t,r){var i=S(e,{parent:!0}).g;if(!(e=Bb(e))||"."===e||".."===e)throw new L(J.q);var n=ac(i,e);if(n)throw new L(n);if(i.k.T)return i.k.T(i,e,t,r);throw new L(J.I)}function gc(e,t){return t=4095&(void 0!==t?t:438),fc(e,t|=32768,0)}function V(e,t){return t=1023&(void 0!==t?t:511),fc(e,t|=16384,0)}function hc(e,t,r){return void 0===r&&(r=t,t=438),fc(e,8192|t,r)}function ic(e,t){if(!Db(e))throw new L(J.F);var r=S(t,{parent:!0}).g;if(!r)throw new L(J.F);var t=Bb(t),i=ac(r,t);if(i)throw new L(i);if(r.k.symlink)return r.k.symlink(r,t,e);throw new L(J.I)}function Vb(e){if(!(e=S(e).g))throw new L(J.F);if(e.k.readlink)return Db(T(e.parent),e.k.readlink(e));throw new L(J.q)}function jc(e,t){e="string"==typeof e?S(e,{la:!0}).g:e;if(!e.k.u)throw new L(J.I);e.k.u(e,{mode:4095&t|-4096&e.mode,timestamp:Date.now()})}function kc(t,r){var i,n;if(""===t)throw new L(J.F);if("string"==typeof r){if(void 0===(i=$b[r]))throw Error("Unknown file open mode: "+r)}else i=r;if(o=64&(r=i)?4095&(void 0===o?438:o)|32768:0,"object"==typeof t)n=t;else{t=zb(t);try{n=S(t,{la:!(131072&r)}).g}catch(e){}}if(i=!1,64&r)if(n){if(128&r)throw new L(J.wa)}else n=fc(t,o,0),i=!0;if(!n)throw new L(J.F);if(8192==(61440&n.mode)&&(r&=-513),65536&r&&!N(n.mode))throw new L(J.ya);if(!i&&(o=n?40960==(61440&n.mode)?J.ga:N(n.mode)&&(0!=(2097155&r)||512&r)?J.P:(o=["r","w","rw"][3&r],512&r&&(o+="w"),Yb(n,o)):J.F))throw new L(o);if(512&r){var o,a="string"==typeof(o=n)?S(o,{la:!0}).g:o;if(!a.k.u)throw new L(J.I);if(N(a.mode))throw new L(J.P);if(32768!=(61440&a.mode))throw new L(J.q);if(o=Yb(a,"w"))throw new L(o);a.k.u(a,{size:0,timestamp:Date.now()})}r&=-641,(n=cc({g:n,path:T(n),flags:r,seekable:!0,position:0,n:n.n,tb:[],error:!1})).n.open&&n.n.open(n),!e.logReadFiles||1&r||(t in(lc=lc||{})||(lc[t]=1,e.printErr("read file: "+t)));try{R.onOpenFile&&(a=0,1!=(2097155&r)&&(a|=1),0!=(2097155&r)&&(a|=2),R.onOpenFile(t,a))}catch(e){console.log("FS.trackingDelegate['onOpenFile']('"+t+"', flags) threw an exception: "+e.message)}return n}function mc(e){e.na&&(e.na=null);try{e.n.close&&e.n.close(e)}catch(e){throw e}finally{Rb[e.fd]=null}}function nc(e,t,r){if(!e.seekable||!e.n.G)throw new L(J.ia);e.position=e.n.G(e,t,r),e.tb=[]}function oc(e,t,r,i,n,o){if(i<0||n<0)throw new L(J.q);if(0==(2097155&e.flags))throw new L(J.ea);if(N(e.g.mode))throw new L(J.P);if(!e.n.write)throw new L(J.q);1024&e.flags&&nc(e,0,2);var a=!0;if(void 0===n)n=e.position,a=!1;else if(!e.seekable)throw new L(J.ia);t=e.n.write(e,t,r,i,n,o),a||(e.position+=t);try{e.path&&R.onWriteToFile&&R.onWriteToFile(e.path)}catch(e){console.log("FS.trackingDelegate['onWriteToFile']('"+path+"') threw an exception: "+e.message)}return t}function pc(){L||((L=function(e,t){this.g=t,this.qb=function(e){for(var t in this.S=e,J)if(J[t]===e){this.code=t;break}},this.qb(e),this.message=xb[e]}).prototype=Error(),L.prototype.constructor=L,[J.F].forEach(function(e){Mb[e]=new L(e),Mb[e].stack=""}))}function rc(e,t){var r=0;return e&&(r|=365),t&&(r|=146),r}function sc(e,t,r,i){return gc(e=K("string"==typeof e?e:T(e),t),rc(r,i))}function tc(e,t,r,i,n,o){if(n=gc(e=t?K("string"==typeof e?e:T(e),t):e,i=rc(i,n)),r){if("string"==typeof r){e=Array(r.length),t=0;for(var a=r.length;t>2]}function xc(){var e=X();if(e=Rb[e])return e;throw new L(J.ea)}var yc={};function Ga(e){Ga.p||(r=Qa(r),Ga.p=!0,assert(n.R),Ga.bb=n.R,n.R=function(){x("cannot dynamically allocate, sbrk now has control")});var t=r;return 0==e||Ga.bb(e)?t:4294967295}e._i64Add=zc;var Ac=1;function Cc(e,t){var r;return Dc=e,Ec=t,Fc?(0==e?(Y=function(){setTimeout(Gc,t)},Hc="timeout"):1==e?(Y=function(){Ic(Gc)},Hc="rAF"):2==e&&(window.setImmediate||(r=[],window.addEventListener("message",function(e){e.source===window&&"__emcc"===e.data&&(e.stopPropagation(),r.shift()())},!0),window.setImmediate=function(e){r.push(e),window.postMessage("__emcc","*")}),Y=function(){window.setImmediate(Gc)},Hc="immediate"),0):1}function Jc(a,t,r,s,i){e.noExitRuntime=!0,assert(!Fc,"emscripten_set_main_loop: there can only be one main loop function at once: call emscripten_cancel_main_loop to cancel the previous one before setting a new one with different parameters."),Fc=a,Kc=s;var l=Lc;if(Gc=function(){var t,r,i,o;na||(0>r-6&63,r=r-6,e=e+"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[n];2==r?e=e+"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[(3&t)<<4]+"==":4==r&&(e=e+"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[(15&t)<<2]+"="),u.src="data:audio/x-"+a.substr(-3)+";base64,"+e,s(u)}},u.src=n,ad(function(){s(u)})}});var r=e.canvas;r&&(r.sa=r.requestPointerLock||r.mozRequestPointerLock||r.webkitRequestPointerLock||r.msRequestPointerLock||function(){},r.Fa=document.exitPointerLock||document.mozExitPointerLock||document.webkitExitPointerLock||document.msExitPointerLock||function(){},r.Fa=r.Fa.bind(document),document.addEventListener("pointerlockchange",t,!1),document.addEventListener("mozpointerlockchange",t,!1),document.addEventListener("webkitpointerlockchange",t,!1),document.addEventListener("mspointerlockchange",t,!1),e.elementPointerLock&&r.addEventListener("click",function(e){!Tc&&r.sa&&(r.sa(),e.preventDefault())},!1))}}function bd(t,r,i,n){if(r&&e.ka&&t==e.canvas)return e.ka;var o,a;if(r){if(a={antialias:!1,alpha:!1},n)for(var s in n)a[s]=n[s];(a=GL.createContext(t,a))&&(o=GL.getContext(a).td),t.style.backgroundColor="black"}else o=t.getContext("2d");return o?(i&&(r||assert("undefined"==typeof GLctx,"cannot set in module if GLctx is used, but we are a non-GL context that would replace it"),e.ka=o,r&&GL.Od(a),e.Td=r,Uc.forEach(function(e){e()}),Vc()),o):null}var cd=!1,dd=void 0,ed=void 0;function fd(t,r,i){function n(){Sc=!1;var t=o.parentNode;(document.webkitFullScreenElement||document.webkitFullscreenElement||document.mozFullScreenElement||document.mozFullscreenElement||document.fullScreenElement||document.fullscreenElement||document.msFullScreenElement||document.msFullscreenElement||document.webkitCurrentFullScreenElement)===t?(o.Da=document.cancelFullScreen||document.mozCancelFullScreen||document.webkitCancelFullScreen||document.msExitFullscreen||document.exitFullscreen||function(){},o.Da=o.Da.bind(document),dd&&o.sa(),Sc=!0,ed&&gd()):(t.parentNode.insertBefore(o,t),t.parentNode.removeChild(t),ed&&hd()),e.onFullScreen&&e.onFullScreen(Sc),id(o)}void 0===(dd=t)&&(dd=!0),void 0===(ed=r)&&(ed=!1),void 0===(jd=i)&&(jd=null);var o=e.canvas,a=(cd||(cd=!0,document.addEventListener("fullscreenchange",n,!1),document.addEventListener("mozfullscreenchange",n,!1),document.addEventListener("webkitfullscreenchange",n,!1),document.addEventListener("MSFullscreenChange",n,!1)),document.createElement("div"));o.parentNode.insertBefore(a,o),a.appendChild(o),a.p=a.requestFullScreen||a.mozRequestFullScreen||a.msRequestFullscreen||(a.webkitRequestFullScreen?function(){a.webkitRequestFullScreen(Element.ALLOW_KEYBOARD_INPUT)}:null),i?a.p({Ud:i}):a.p()}var kd=0;function ld(e){var t=Date.now();if(0===kd)kd=t+1e3/60;else for(;kd<=t+2;)kd+=1e3/60;t=Math.max(kd-t,0),setTimeout(e,t)}function Ic(e){"undefined"==typeof window?ld(e):(window.requestAnimationFrame||(window.requestAnimationFrame=window.requestAnimationFrame||window.mozRequestAnimationFrame||window.webkitRequestAnimationFrame||window.msRequestAnimationFrame||window.oRequestAnimationFrame||ld),window.requestAnimationFrame(e))}function ad(t){e.noExitRuntime=!0,setTimeout(function(){na||t()},1e4)}function $c(e){return{jpg:"image/jpeg",jpeg:"image/jpeg",png:"image/png",bmp:"image/bmp",ogg:"audio/ogg",wav:"audio/wav",mp3:"audio/mpeg"}[e.substr(e.lastIndexOf(".")+1)]}function md(e,t,r){var i=new XMLHttpRequest;i.open("GET",e,!0),i.responseType="arraybuffer",i.onload=function(){200==i.status||0==i.status&&i.response?t(i.response):r()},i.onerror=r,i.send(null)}function nd(t,r,e){md(t,function(e){assert(e,'Loading data file "'+t+'" failed (no arrayBuffer).'),r(new Uint8Array(e)),lb()},function(){if(!e)throw'Loading data file "'+t+'" failed.';e()}),kb()}var od=[],Wc,Xc,Yc,Zc,jd,fs,Ob;function pd(){var t=e.canvas;od.forEach(function(e){e(t.width,t.height)})}function gd(){var e;"undefined"!=typeof SDL&&(e=Sa[SDL.screen+0*n.J>>2],C[SDL.screen+0*n.J>>2]=8388608|e),pd()}function hd(){var e;"undefined"!=typeof SDL&&(e=Sa[SDL.screen+0*n.J>>2],C[SDL.screen+0*n.J>>2]=-8388609&e),pd()}function id(t,r,i){r&&i?(t.ub=r,t.hb=i):(r=t.ub,i=t.hb);var n,o=r,a=i;e.forcedAspectRatio&&0this.length-1||e<0))return t=e%this.chunkSize,this.gb(e/this.chunkSize|0)[t]},a.prototype.pb=function(e){this.gb=e},a.prototype.Ca=function(){var e=new XMLHttpRequest;if(e.open("HEAD",l,!1),e.send(null),!(200<=e.status&&e.status<300||304===e.status))throw Error("Couldn't load "+l+". Status: "+e.status);var o=Number(e.getResponseHeader("Content-length")),a=1048576,s=((e=e.getResponseHeader("Accept-Ranges"))&&"bytes"===e||(a=o),this);s.pb(function(e){var t=e*a,r=(e+1)*a-1,r=Math.min(r,o-1);if(void 0===s.Y[e]){var i=s.Y;if(r=(e=e.g.e).length)return 0;if(assert(0<=(i=Math.min(e.length-n,i))),e.slice)for(var o=0;o>2]=0):-J.Q;case 21520:return i.tty?-J.q:-J.Q;case 21531:if(r=X(),i.n.ib)return i.n.ib(i,n,r);throw new L(J.Q);default:x("bad ioctl syscall "+n)}}catch(e){return void 0!==vc&&e instanceof L||x(e),-e.S}},___syscall6:function(e,t){wc=t;try{return mc(xc()),0}catch(e){return void 0!==vc&&e instanceof L||x(e),-e.S}},_emscripten_set_main_loop_timing:Cc,__ZSt18uncaught_exceptionv:tb,___setErrNo:ob,_sbrk:Ga,___cxa_begin_catch:function(e){tb.p--,ub.push(e);e:{if(e&&!vb[e])for(var t in vb)if(vb[t].wd===e)break e;t=e}return t&&vb[t].Sd++,e},_emscripten_memcpy_big:function(e,t,r){return E.set(E.subarray(t,t+r),e),e},_sysconf:function(e){switch(e){case 30:return 4096;case 85:return F/4096;case 132:case 133:case 12:case 137:case 138:case 15:case 235:case 16:case 17:case 18:case 19:case 20:case 149:case 13:case 10:case 236:case 153:case 9:case 21:case 22:case 159:case 154:case 14:case 77:case 78:case 139:case 80:case 81:case 82:case 68:case 67:case 164:case 11:case 29:case 47:case 48:case 95:case 52:case 51:case 46:return 200809;case 79:return 0;case 27:case 246:case 127:case 128:case 23:case 24:case 160:case 161:case 181:case 182:case 242:case 183:case 184:case 243:case 244:case 245:case 165:case 178:case 179:case 49:case 50:case 168:case 169:case 175:case 170:case 171:case 172:case 97:case 76:case 32:case 173:case 35:return-1;case 176:case 177:case 7:case 155:case 8:case 157:case 125:case 126:case 92:case 93:case 129:case 130:case 131:case 94:case 91:return 1;case 74:case 60:case 69:case 70:case 4:return 1024;case 31:case 42:case 72:return 32;case 87:case 26:case 33:return 2147483647;case 34:case 1:return 47839;case 38:case 36:return 99;case 43:case 37:return 2048;case 0:return 2097152;case 3:return 65536;case 28:return 32768;case 44:return 32767;case 75:return 16384;case 39:return 1e3;case 89:return 700;case 71:return 256;case 40:return 255;case 2:return 100;case 180:return 64;case 25:return 20;case 5:return 16;case 6:return 6;case 73:return 4;case 84:return"object"==typeof navigator&&navigator.hardwareConcurrency||1}return ob(J.q),-1},_pthread_getspecific:function(e){return yc[e]||0},_pthread_self:function(){return 0},_pthread_once:wb,_pthread_key_create:function(e){return 0==e?J.q:(C[e>>2]=Ac,yc[Ac]=0,Ac++,0)},___unlock:function(){},_emscripten_set_main_loop:Jc,_pthread_setspecific:function(e,t){return e in yc?(yc[e]=t,0):J.q},___lock:function(){},_abort:function(){e.abort()},_pthread_cleanup_push:pb,_time:function(e){var t=Date.now()/1e3|0;return e&&(C[e>>2]=t),t},___syscall140:function(e,t){wc=t;try{var r=xc(),i=X(),n=X(),o=X(),a=X();return assert(0===i),nc(r,n,a),C[o>>2]=r.position,r.na&&0===n&&0===a&&(r.na=null),0}catch(e){return void 0!==vc&&e instanceof L||x(e),-e.S}},___syscall146:function(e,t){wc=t;try{var r,i=xc(),n=X();e:{for(var o=X(),a=0,s=0;s>2],C[n+(8*s+4)>>2],void 0);if(l<0){r=-1;break e}a+=l}r=a}return r}catch(e){return void 0!==vc&&e instanceof L||x(e),-e.S}},STACKTOP:m,STACK_MAX:Va,tempDoublePtr:mb,ABORT:na,cttz_i8:qd},function(e,t,r){"use asm";var i=e.Int8Array;var n=e.Int16Array;var o=e.Int32Array;var s=e.Uint8Array;var u=e.Uint16Array;var h=e.Uint32Array;var c=e.Float32Array;var f=e.Float64Array;var pe=new i(r);var $=new n(r);var de=new o(r);var me=new s(r);var _e=new u(r);var p=new h(r);var d=new c(r);var ee=new f(r);var y=e.byteLength;var ge=t.STACKTOP|0;var x=t.STACK_MAX|0;var te=t.tempDoublePtr|0;var T=t.ABORT|0;var w=t.cttz_i8|0;var E=0;var S=0;var A=0;var k=0;var O=e.NaN,P=e.Infinity;var R=0,C=0,M=0,I=0,D=0.0,L=0,H=0,Y=0,W=0.0;var re=0;var q=0;var V=0;var K=0;var J=0;var Z=0;var Q=0;var le=0;var ue=0;var he=0;var ce=e.Math.floor;var fe=e.Math.abs;var Te=e.Math.sqrt;var we=e.Math.pow;var Ee=e.Math.cos;var Se=e.Math.sin;var Ae=e.Math.tan;var ke=e.Math.acos;var Oe=e.Math.asin;var Pe=e.Math.atan;var Re=e.Math.atan2;var Ce=e.Math.exp;var Me=e.Math.log;var Ie=e.Math.ceil;var ve=e.Math.imul;var De=e.Math.min;var m=e.Math.clz32;var a=t.abort;var Le=t.assert;var Fe=t.invoke_iiii;var Ne=t.invoke_viiiii;var ze=t.invoke_vi;var Be=t.invoke_ii;var je=t.invoke_viii;var Ue=t.invoke_v;var Ge=t.invoke_viiiiii;var Xe=t.invoke_iiiiii;var He=t.invoke_viiii;var Ye=t._pthread_cleanup_pop;var We=t.___syscall54;var qe=t.___syscall6;var Ve=t._emscripten_set_main_loop_timing;var Ke=t.__ZSt18uncaught_exceptionv;var Je=t.___setErrNo;var z=t._sbrk;var Ze=t.___cxa_begin_catch;var Qe=t._emscripten_memcpy_big;var $e=t._sysconf;var et=t._pthread_getspecific;var tt=t._pthread_self;var rt=t._pthread_once;var it=t._pthread_key_create;var nt=t.___unlock;var ot=t._emscripten_set_main_loop;var at=t._pthread_setspecific;var st=t.___lock;var B=t._abort;var lt=t._pthread_cleanup_push;var ut=t._time;var ht=t.___syscall140;var ct=t.___syscall146;var ft=0.0;function pt(e){if(y(e)&16777215||y(e)<=16777215||y(e)>2147483648)return false;pe=new i(e);$=new n(e);de=new o(e);me=new s(e);_e=new u(e);p=new h(e);d=new c(e);ee=new f(e);r=e;return true}function dt(e){e=e|0;var t=0;t=ge;ge=ge+e|0;ge=ge+15&-16;return t|0}function mt(){return ge|0}function _t(e){e=e|0;ge=e}function gt(e,t){e=e|0;t=t|0;ge=e;x=t}function vt(e,t){e=e|0;t=t|0;if(!E){E=e;S=t}}function yt(e){e=e|0;pe[te>>0]=pe[e>>0];pe[te+1>>0]=pe[e+1>>0];pe[te+2>>0]=pe[e+2>>0];pe[te+3>>0]=pe[e+3>>0]}function bt(e){e=e|0;pe[te>>0]=pe[e>>0];pe[te+1>>0]=pe[e+1>>0];pe[te+2>>0]=pe[e+2>>0];pe[te+3>>0]=pe[e+3>>0];pe[te+4>>0]=pe[e+4>>0];pe[te+5>>0]=pe[e+5>>0];pe[te+6>>0]=pe[e+6>>0];pe[te+7>>0]=pe[e+7>>0]}function xt(e){e=e|0;re=e}function Tt(){return re|0}function F(e,t,r,i,n){e=e|0;t=t|0;r=r|0;i=i|0;n=n|0;var o=0,a=0,s=0,l=0,u=0,h=0,c=0,f=0,p=0,d=0,m=0;m=ge;ge=ge+608|0;f=m+88|0;c=m+72|0;l=m+64|0;s=m+48|0;a=m+24|0;o=m;h=m+96|0;p=m+92|0;u=e+4|0;d=e+8|0;if((de[u>>2]|0)>>>0>(de[d>>2]|0)>>>0){de[o>>2]=1154;de[o+4>>2]=2120;de[o+8>>2]=1133;xe(h,1100,o)|0;be(h,m+16|0)|0}if((2147418112/(i>>>0)|0)>>>0<=t>>>0){de[a>>2]=1154;de[a+4>>2]=2121;de[a+8>>2]=1169;xe(h,1100,a)|0;be(h,m+40|0)|0}a=de[d>>2]|0;if(a>>>0>=t>>>0){d=1;ge=m;return d|0}do{if(r){if(t){o=t+-1|0;if(!(o&t)){o=11;break}else t=o}else t=-1;t=t>>>16|t;t=t>>>8|t;t=t>>>4|t;t=t>>>2|t;t=(t>>>1|t)+1|0;o=10}else o=10}while(0);if((o|0)==10)if(!t){t=0;o=12}else o=11;if((o|0)==11)if(t>>>0<=a>>>0)o=12;if((o|0)==12){de[s>>2]=1154;de[s+4>>2]=2130;de[s+8>>2]=1217;xe(h,1100,s)|0;be(h,l)|0}r=ve(t,i)|0;do{if(!n){o=wt(de[e>>2]|0,r,p,1)|0;if(!o){d=0;ge=m;return d|0}else{de[e>>2]=o;break}}else{a=j(r,p)|0;if(!a){d=0;ge=m;return d|0}Ci[n&0](a,de[e>>2]|0,de[u>>2]|0);o=de[e>>2]|0;do{if(o)if(!(o&7)){X[de[104>>2]&1](o,0,0,1,de[27]|0)|0;break}else{de[c>>2]=1154;de[c+4>>2]=2499;de[c+8>>2]=1516;xe(h,1100,c)|0;be(h,f)|0;break}}while(0);de[e>>2]=a}}while(0);o=de[p>>2]|0;if(o>>>0>r>>>0)t=(o>>>0)/(i>>>0)|0;de[d>>2]=t;d=1;ge=m;return d|0}function wt(e,t,r,i){e=e|0;t=t|0;r=r|0;i=i|0;var n=0,o=0,a=0,s=0,l=0,u=0;u=ge;ge=ge+592|0;l=u+48|0;o=u+24|0;n=u;s=u+72|0;a=u+68|0;if(e&7){de[n>>2]=1154;de[n+4>>2]=2499;de[n+8>>2]=1494;xe(s,1100,n)|0;be(s,u+16|0)|0;l=0;ge=u;return l|0}if(t>>>0>2147418112){de[o>>2]=1154;de[o+4>>2]=2499;de[o+8>>2]=1387;xe(s,1100,o)|0;be(s,u+40|0)|0;l=0;ge=u;return l|0}de[a>>2]=t;i=X[de[104>>2]&1](e,t,a,i,de[27]|0)|0;if(r)de[r>>2]=de[a>>2];if(!(i&7)){l=i;ge=u;return l|0}de[l>>2]=1154;de[l+4>>2]=2551;de[l+8>>2]=1440;xe(s,1100,l)|0;be(s,u+64|0)|0;l=i;ge=u;return l|0}function j(e,t){e=e|0;t=t|0;var r=0,i=0,n=0,o=0,a=0,s=0,l=0;l=ge;ge=ge+592|0;a=l+48|0;s=l+24|0;r=l;o=l+72|0;n=l+68|0;i=e+3&-4;i=(i|0)!=0?i:4;if(i>>>0>2147418112){de[r>>2]=1154;de[r+4>>2]=2499;de[r+8>>2]=1387;xe(o,1100,r)|0;be(o,l+16|0)|0;s=0;ge=l;return s|0}de[n>>2]=i;r=X[de[104>>2]&1](0,i,n,1,de[27]|0)|0;e=de[n>>2]|0;if(t)de[t>>2]=e;if((r|0)==0|e>>>0
>>0){de[s>>2]=1154;de[s+4>>2]=2499;de[s+8>>2]=1413;xe(o,1100,s)|0;be(o,l+40|0)|0;s=0;ge=l;return s|0}if(!(r&7)){s=r;ge=l;return s|0}de[a>>2]=1154;de[a+4>>2]=2526;de[a+8>>2]=1440;xe(o,1100,a)|0;be(o,l+64|0)|0;s=r;ge=l;return s|0}function Et(e,t,r,i){e=e|0;t=t|0;r=r|0;i=i|0;var n=0,o=0,a=0,s=0,l=0,u=0,h=0,c=0,f=0,p=0,d=0,m=0,_=0,g=0,v=0,y=0,b=0,x=0,T=0,w=0,E=0,S=0,A=0,k=0,O=0,P=0,R=0,F=0,C=0,N=0,M=0,z=0,I=0,D=0,L=0;L=ge;ge=ge+960|0;z=L+232|0;M=L+216|0;N=L+208|0;C=L+192|0;F=L+184|0;R=L+168|0;P=L+160|0;O=L+144|0;S=L+136|0;E=L+120|0;w=L+112|0;T=L+96|0;y=L+88|0;v=L+72|0;g=L+64|0;_=L+48|0;c=L+40|0;p=L+24|0;f=L+16|0;h=L;k=L+440|0;I=L+376|0;D=L+304|0;m=L+236|0;if((t|0)==0|i>>>0>11){e=0;ge=L;return e|0}de[e>>2]=t;n=D;o=n+68|0;do{de[n>>2]=0;n=n+4|0}while((n|0)<(o|0));o=0;do{n=pe[r+o>>0]|0;if(n<<24>>24){A=D+((n&255)<<2)|0;de[A>>2]=(de[A>>2]|0)+1}o=o+1|0}while((o|0)!=(t|0));o=0;u=1;a=0;s=-1;l=0;while(1){n=de[D+(u<<2)>>2]|0;if(!n)de[e+28+(u+-1<<2)>>2]=0;else{A=u+-1|0;de[I+(A<<2)>>2]=o;o=n+o|0;x=16-u|0;de[e+28+(A<<2)>>2]=(o+-1<>2]=l;de[m+(u<<2)>>2]=l;a=a>>>0>u>>>0?a:u;s=s>>>0>>0?s:u;l=n+l|0}u=u+1|0;if((u|0)==17){A=a;break}else o=o<<1}de[e+4>>2]=l;o=e+172|0;do{if(l>>>0>(de[o>>2]|0)>>>0){de[o>>2]=l;if(l){n=l+-1|0;if(n&l)d=14}else{n=-1;d=14}if((d|0)==14){x=n>>>16|n;x=x>>>8|x;x=x>>>4|x;x=x>>>2|x;x=(x>>>1|x)+1|0;de[o>>2]=x>>>0>t>>>0?t:x}a=e+176|0;n=de[a>>2]|0;do{if(n){x=de[n+-4>>2]|0;n=n+-8|0;if(!((x|0)!=0?(x|0)==(~de[n>>2]|0):0)){de[h>>2]=1154;de[h+4>>2]=644;de[h+8>>2]=1863;xe(k,1100,h)|0;be(k,f)|0}if(!(n&7)){X[de[104>>2]&1](n,0,0,1,de[27]|0)|0;break}else{de[p>>2]=1154;de[p+4>>2]=2499;de[p+8>>2]=1516;xe(k,1100,p)|0;be(k,c)|0;break}}}while(0);o=de[o>>2]|0;o=(o|0)!=0?o:1;n=j((o<<1)+8|0,0)|0;if(!n){de[a>>2]=0;n=0;break}else{de[n+4>>2]=o;de[n>>2]=~o;de[a>>2]=n+8;d=25;break}}else d=25}while(0);e:do{if((d|0)==25){x=e+24|0;pe[x>>0]=s;pe[e+25>>0]=A;o=e+176|0;a=0;do{b=pe[r+a>>0]|0;n=b&255;if(b<<24>>24){if(!(de[D+(n<<2)>>2]|0)){de[_>>2]=1154;de[_+4>>2]=2273;de[_+8>>2]=1261;xe(k,1100,_)|0;be(k,g)|0}b=m+(n<<2)|0;n=de[b>>2]|0;de[b>>2]=n+1;if(n>>>0>=l>>>0){de[v>>2]=1154;de[v+4>>2]=2277;de[v+8>>2]=1274;xe(k,1100,v)|0;be(k,y)|0}$[(de[o>>2]|0)+(n<<1)>>1]=a}a=a+1|0}while((a|0)!=(t|0));n=pe[x>>0]|0;y=(n&255)>>>0>>0?i:0;b=e+8|0;de[b>>2]=y;v=(y|0)!=0;if(v){g=1<>>0>(de[n>>2]|0)>>>0){de[n>>2]=g;a=e+168|0;n=de[a>>2]|0;do{if(n){_=de[n+-4>>2]|0;n=n+-8|0;if(!((_|0)!=0?(_|0)==(~de[n>>2]|0):0)){de[T>>2]=1154;de[T+4>>2]=644;de[T+8>>2]=1863;xe(k,1100,T)|0;be(k,w)|0}if(!(n&7)){X[de[104>>2]&1](n,0,0,1,de[27]|0)|0;break}else{de[E>>2]=1154;de[E+4>>2]=2499;de[E+8>>2]=1516;xe(k,1100,E)|0;be(k,S)|0;break}}}while(0);n=g<<2;o=j(n+8|0,0)|0;if(!o){de[a>>2]=0;n=0;break e}else{S=o+8|0;de[o+4>>2]=g;de[o>>2]=~g;de[a>>2]=S;o=S;break}}else{o=e+168|0;n=g<<2;a=o;o=de[o>>2]|0}}while(0);G(o|0,-1,n|0)|0;d=e+176|0;_=1;do{if(de[D+(_<<2)>>2]|0){t=y-_|0;m=1<>2]|0;if(o>>>0>=16){de[O>>2]=1154;de[O+4>>2]=1953;de[O+8>>2]=1737;xe(k,1100,O)|0;be(k,P)|0}n=de[e+28+(o<<2)>>2]|0;if(!n)p=-1;else p=(n+-1|0)>>>(16-_|0);if(s>>>0<=p>>>0){c=(de[e+96+(o<<2)>>2]|0)-s|0;f=_<<16;do{n=_e[(de[d>>2]|0)+(c+s<<1)>>1]|0;if((me[r+n>>0]|0|0)!=(_|0)){de[R>>2]=1154;de[R+4>>2]=2319;de[R+8>>2]=1303;xe(k,1100,R)|0;be(k,F)|0}h=s<>>0>=g>>>0){de[C>>2]=1154;de[C+4>>2]=2325;de[C+8>>2]=1337;xe(k,1100,C)|0;be(k,N)|0}n=de[a>>2]|0;if((de[n+(l<<2)>>2]|0)!=-1){de[M>>2]=1154;de[M+4>>2]=2327;de[M+8>>2]=1360;xe(k,1100,M)|0;be(k,z)|0;n=de[a>>2]|0}de[n+(l<<2)>>2]=o;u=u+1|0}while(u>>>0>>0);s=s+1|0}while(s>>>0<=p>>>0)}}_=_+1|0}while(y>>>0>=_>>>0);n=pe[x>>0]|0}o=e+96|0;de[o>>2]=(de[o>>2]|0)-(de[I>>2]|0);o=e+100|0;de[o>>2]=(de[o>>2]|0)-(de[I+4>>2]|0);o=e+104|0;de[o>>2]=(de[o>>2]|0)-(de[I+8>>2]|0);o=e+108|0;de[o>>2]=(de[o>>2]|0)-(de[I+12>>2]|0);o=e+112|0;de[o>>2]=(de[o>>2]|0)-(de[I+16>>2]|0);o=e+116|0;de[o>>2]=(de[o>>2]|0)-(de[I+20>>2]|0);o=e+120|0;de[o>>2]=(de[o>>2]|0)-(de[I+24>>2]|0);o=e+124|0;de[o>>2]=(de[o>>2]|0)-(de[I+28>>2]|0);o=e+128|0;de[o>>2]=(de[o>>2]|0)-(de[I+32>>2]|0);o=e+132|0;de[o>>2]=(de[o>>2]|0)-(de[I+36>>2]|0);o=e+136|0;de[o>>2]=(de[o>>2]|0)-(de[I+40>>2]|0);o=e+140|0;de[o>>2]=(de[o>>2]|0)-(de[I+44>>2]|0);o=e+144|0;de[o>>2]=(de[o>>2]|0)-(de[I+48>>2]|0);o=e+148|0;de[o>>2]=(de[o>>2]|0)-(de[I+52>>2]|0);o=e+152|0;de[o>>2]=(de[o>>2]|0)-(de[I+56>>2]|0);o=e+156|0;de[o>>2]=(de[o>>2]|0)-(de[I+60>>2]|0);o=e+16|0;de[o>>2]=0;a=e+20|0;de[a>>2]=n&255;t:do{if(v){while(1){if(!i)break t;n=i+-1|0;if(!(de[D+(i<<2)>>2]|0))i=n;else break}de[o>>2]=de[e+28+(n<<2)>>2];n=y+1|0;de[a>>2]=n;if(n>>>0<=A>>>0){while(1){if(de[D+(n<<2)>>2]|0)break;n=n+1|0;if(n>>>0>A>>>0)break t}de[a>>2]=n}}}while(0);de[e+92>>2]=-1;de[e+160>>2]=1048575;de[e+12>>2]=32-(de[b>>2]|0);n=1}}while(0);e=n;ge=L;return e|0}function St(e,t,r,i,n){e=e|0;t=t|0;r=r|0;i=i|0;n=n|0;var o=0;if(!e){n=Yr(t)|0;if(!r){r=n;return r|0}if(!n)o=0;else o=qr(n)|0;de[r>>2]=o;r=n;return r|0}if(!t){b(e);if(!r){r=0;return r|0}de[r>>2]=0;r=0;return r|0}n=Wr(e,t)|0;o=(n|0)!=0;if(o|i^1)o=o?n:e;else{n=Wr(e,t)|0;o=(n|0)==0?e:n}if(!r){r=n;return r|0}t=qr(o)|0;de[r>>2]=t;r=n;return r|0}function _(e,t,r){e=e|0;t=t|0;r=r|0;var i=0;if(!((e|0)!=0&t>>>0>73&(r|0)!=0)){r=0;return r|0}if((de[r>>2]|0)!=40|t>>>0<74){r=0;return r|0}if(((me[e>>0]|0)<<8|(me[e+1>>0]|0)|0)!=18552){r=0;return r|0}if(((me[e+2>>0]|0)<<8|(me[e+3>>0]|0))>>>0<74){r=0;return r|0}if(((me[e+7>>0]|0)<<16|(me[e+6>>0]|0)<<24|(me[e+8>>0]|0)<<8|(me[e+9>>0]|0))>>>0>t>>>0){r=0;return r|0}de[r+4>>2]=(me[e+12>>0]|0)<<8|(me[e+13>>0]|0);de[r+8>>2]=(me[e+14>>0]|0)<<8|(me[e+15>>0]|0);de[r+12>>2]=me[e+16>>0];de[r+16>>2]=me[e+17>>0];t=e+18|0;i=r+32|0;de[i>>2]=me[t>>0];de[i+4>>2]=0;t=pe[t>>0]|0;de[r+20>>2]=t<<24>>24==0|t<<24>>24==9?8:16;de[r+24>>2]=(me[e+26>>0]|0)<<16|(me[e+25>>0]|0)<<24|(me[e+27>>0]|0)<<8|(me[e+28>>0]|0);de[r+28>>2]=(me[e+30>>0]|0)<<16|(me[e+29>>0]|0)<<24|(me[e+31>>0]|0)<<8|(me[e+32>>0]|0);r=1;return r|0}function At(e){e=e|0;Ze(e|0)|0;$t()}function N(e){e=e|0;var t=0,r=0,i=0,n=0,o=0;o=ge;ge=ge+544|0;n=o;i=o+24|0;t=de[e+20>>2]|0;if(t)kt(t);t=e+4|0;r=de[t>>2]|0;if(!r){n=e+16|0;pe[n>>0]=0;ge=o;return}if(!(r&7))X[de[104>>2]&1](r,0,0,1,de[27]|0)|0;else{de[n>>2]=1154;de[n+4>>2]=2499;de[n+8>>2]=1516;xe(i,1100,n)|0;be(i,o+16|0)|0}de[t>>2]=0;de[e+8>>2]=0;de[e+12>>2]=0;n=e+16|0;pe[n>>0]=0;ge=o}function kt(e){e=e|0;var t=0,r=0,i=0,n=0,o=0,a=0,s=0,l=0,u=0,h=0,c=0,f=0,p=0,d=0;p=ge;ge=ge+640|0;f=p+112|0;c=p+96|0;h=p+88|0;u=p+72|0;l=p+64|0;s=p+48|0;i=p+40|0;o=p+24|0;n=p+16|0;r=p;a=p+120|0;if(!e){ge=p;return}t=de[e+168>>2]|0;do{if(t){d=de[t+-4>>2]|0;t=t+-8|0;if(!((d|0)!=0?(d|0)==(~de[t>>2]|0):0)){de[r>>2]=1154;de[r+4>>2]=644;de[r+8>>2]=1863;xe(a,1100,r)|0;be(a,n)|0}if(!(t&7)){X[de[104>>2]&1](t,0,0,1,de[27]|0)|0;break}else{de[o>>2]=1154;de[o+4>>2]=2499;de[o+8>>2]=1516;xe(a,1100,o)|0;be(a,i)|0;break}}}while(0);t=de[e+176>>2]|0;do{if(t){d=de[t+-4>>2]|0;t=t+-8|0;if(!((d|0)!=0?(d|0)==(~de[t>>2]|0):0)){de[s>>2]=1154;de[s+4>>2]=644;de[s+8>>2]=1863;xe(a,1100,s)|0;be(a,l)|0}if(!(t&7)){X[de[104>>2]&1](t,0,0,1,de[27]|0)|0;break}else{de[u>>2]=1154;de[u+4>>2]=2499;de[u+8>>2]=1516;xe(a,1100,u)|0;be(a,h)|0;break}}}while(0);if(!(e&7)){X[de[104>>2]&1](e,0,0,1,de[27]|0)|0;ge=p}else{de[c>>2]=1154;de[c+4>>2]=2499;de[c+8>>2]=1516;xe(a,1100,c)|0;be(a,f)|0;ge=p}}function Ot(e){e=e|0;var t=0,r=0,i=0,n=0,o=0,a=0,s=0,l=0,u=0,h=0;h=ge;ge=ge+560|0;a=h+40|0;s=h+24|0;t=h;o=h+48|0;n=e+8|0;r=de[n>>2]|0;if((r+-1|0)>>>0>=8192){de[t>>2]=1154;de[t+4>>2]=2997;de[t+8>>2]=1541;xe(o,1100,t)|0;be(o,h+16|0)|0}de[e>>2]=r;i=e+20|0;t=de[i>>2]|0;if(!t){t=j(180,0)|0;if(!t)t=0;else{u=t+164|0;de[u>>2]=0;de[u+4>>2]=0;de[u+8>>2]=0;de[u+12>>2]=0}de[i>>2]=t;u=t;l=de[e>>2]|0}else{u=t;l=r}if(!(de[n>>2]|0)){de[s>>2]=1154;de[s+4>>2]=903;de[s+8>>2]=1781;xe(o,1100,s)|0;be(o,a)|0;o=de[e>>2]|0}else o=l;n=de[e+4>>2]|0;if(o>>>0>16){r=o;t=0}else{e=0;u=Et(u,l,n,e)|0;ge=h;return u|0}while(1){i=t+1|0;if(r>>>0>3){r=r>>>1;t=i}else{r=i;break}}e=t+2+((r|0)!=32&1<>>0>>0&1)|0;e=e>>>0<11?e&255:11;u=Et(u,l,n,e)|0;ge=h;return u|0}function U(e,t){e=e|0;t=t|0;var r=0,i=0,n=0,o=0,a=0,s=0,l=0,u=0,h=0,c=0,f=0,p=0,d=0,m=0,_=0,g=0,v=0,y=0,b=0,x=0,T=0,w=0,E=0,S=0,A=0,k=0,O=0,P=0,R=0,C=0,M=0,I=0,D=0,L=0;L=ge;ge=ge+800|0;R=L+256|0;P=L+240|0;O=L+232|0;k=L+216|0;A=L+208|0;S=L+192|0;E=L+184|0;w=L+168|0;T=L+160|0;x=L+144|0;b=L+136|0;y=L+120|0;v=L+112|0;g=L+96|0;_=L+88|0;m=L+72|0;c=L+64|0;h=L+48|0;s=L+40|0;l=L+24|0;o=L+16|0;n=L;I=L+288|0;D=L+264|0;C=Pt(e,14)|0;if(!C){de[t>>2]=0;r=t+4|0;i=de[r>>2]|0;if(i){if(!(i&7))X[de[104>>2]&1](i,0,0,1,de[27]|0)|0;else{de[n>>2]=1154;de[n+4>>2]=2499;de[n+8>>2]=1516;xe(I,1100,n)|0;be(I,o)|0}de[r>>2]=0;de[t+8>>2]=0;de[t+12>>2]=0}pe[t+16>>0]=0;r=t+20|0;i=de[r>>2]|0;if(!i){t=1;ge=L;return t|0}kt(i);de[r>>2]=0;t=1;ge=L;return t|0}p=t+4|0;d=t+8|0;r=de[d>>2]|0;if((r|0)!=(C|0)){if(r>>>0<=C>>>0){do{if((de[t+12>>2]|0)>>>0>>0){if(F(p,C,(r+1|0)==(C|0),1,0)|0){r=de[d>>2]|0;break}pe[t+16>>0]=1;t=0;ge=L;return t|0}}while(0);G((de[p>>2]|0)+r|0,0,C-r|0)|0}de[d>>2]=C}G(de[p>>2]|0,0,C|0)|0;f=e+20|0;r=de[f>>2]|0;if((r|0)<5){o=e+4|0;a=e+8|0;n=e+16|0;do{i=de[o>>2]|0;if((i|0)==(de[a>>2]|0))i=0;else{de[o>>2]=i+1;i=me[i>>0]|0}r=r+8|0;de[f>>2]=r;if((r|0)>=33){de[l>>2]=1154;de[l+4>>2]=3199;de[l+8>>2]=1650;xe(I,1100,l)|0;be(I,s)|0;r=de[f>>2]|0}i=i<<32-r|de[n>>2];de[n>>2]=i}while((r|0)<5)}else{i=e+16|0;n=i;i=de[i>>2]|0}u=i>>>27;de[n>>2]=i<<5;de[f>>2]=r+-5;if((u+-1|0)>>>0>20){t=0;ge=L;return t|0}de[D+20>>2]=0;de[D>>2]=0;de[D+4>>2]=0;de[D+8>>2]=0;de[D+12>>2]=0;pe[D+16>>0]=0;r=D+4|0;i=D+8|0;e:do{if(F(r,21,0,1,0)|0){s=de[i>>2]|0;l=de[r>>2]|0;G(l+s|0,0,21-s|0)|0;de[i>>2]=21;if(u){n=e+4|0;o=e+8|0;a=e+16|0;s=0;do{r=de[f>>2]|0;if((r|0)<3)do{i=de[n>>2]|0;if((i|0)==(de[o>>2]|0))i=0;else{de[n>>2]=i+1;i=me[i>>0]|0}r=r+8|0;de[f>>2]=r;if((r|0)>=33){de[h>>2]=1154;de[h+4>>2]=3199;de[h+8>>2]=1650;xe(I,1100,h)|0;be(I,c)|0;r=de[f>>2]|0}i=i<<32-r|de[a>>2];de[a>>2]=i}while((r|0)<3);else i=de[a>>2]|0;de[a>>2]=i<<3;de[f>>2]=r+-3;pe[l+(me[1611+s>>0]|0)>>0]=i>>>29;s=s+1|0}while((s|0)!=(u|0))}if(Ot(D)|0){s=e+4|0;l=e+8|0;u=e+16|0;i=0;t:while(1){a=C-i|0;r=ye(e,D)|0;r:do{if(r>>>0<17){if((de[d>>2]|0)>>>0<=i>>>0){de[m>>2]=1154;de[m+4>>2]=903;de[m+8>>2]=1781;xe(I,1100,m)|0;be(I,_)|0}pe[(de[p>>2]|0)+i>>0]=r;r=i+1|0}else switch(r|0){case 17:{r=de[f>>2]|0;if((r|0)<3)do{n=de[s>>2]|0;if((n|0)==(de[l>>2]|0))n=0;else{de[s>>2]=n+1;n=me[n>>0]|0}r=r+8|0;de[f>>2]=r;if((r|0)>=33){de[g>>2]=1154;de[g+4>>2]=3199;de[g+8>>2]=1650;xe(I,1100,g)|0;be(I,v)|0;r=de[f>>2]|0}n=n<<32-r|de[u>>2];de[u>>2]=n}while((r|0)<3);else n=de[u>>2]|0;de[u>>2]=n<<3;de[f>>2]=r+-3;r=(n>>>29)+3|0;if(r>>>0>a>>>0){r=0;break e}r=r+i|0;break r}case 18:{r=de[f>>2]|0;if((r|0)<7)do{n=de[s>>2]|0;if((n|0)==(de[l>>2]|0))n=0;else{de[s>>2]=n+1;n=me[n>>0]|0}r=r+8|0;de[f>>2]=r;if((r|0)>=33){de[y>>2]=1154;de[y+4>>2]=3199;de[y+8>>2]=1650;xe(I,1100,y)|0;be(I,b)|0;r=de[f>>2]|0}n=n<<32-r|de[u>>2];de[u>>2]=n}while((r|0)<7);else n=de[u>>2]|0;de[u>>2]=n<<7;de[f>>2]=r+-7;r=(n>>>25)+11|0;if(r>>>0>a>>>0){r=0;break e}r=r+i|0;break r}default:{if((r+-19|0)>>>0>=2){M=90;break t}o=de[f>>2]|0;if((r|0)==19){if((o|0)<2){n=o;while(1){r=de[s>>2]|0;if((r|0)==(de[l>>2]|0))o=0;else{de[s>>2]=r+1;o=me[r>>0]|0}r=n+8|0;de[f>>2]=r;if((r|0)>=33){de[x>>2]=1154;de[x+4>>2]=3199;de[x+8>>2]=1650;xe(I,1100,x)|0;be(I,T)|0;r=de[f>>2]|0}n=o<<32-r|de[u>>2];de[u>>2]=n;if((r|0)<2)n=r;else break}}else{n=de[u>>2]|0;r=o}de[u>>2]=n<<2;de[f>>2]=r+-2;o=(n>>>30)+3|0}else{if((o|0)<6){n=o;while(1){r=de[s>>2]|0;if((r|0)==(de[l>>2]|0))o=0;else{de[s>>2]=r+1;o=me[r>>0]|0}r=n+8|0;de[f>>2]=r;if((r|0)>=33){de[w>>2]=1154;de[w+4>>2]=3199;de[w+8>>2]=1650;xe(I,1100,w)|0;be(I,E)|0;r=de[f>>2]|0}n=o<<32-r|de[u>>2];de[u>>2]=n;if((r|0)<6)n=r;else break}}else{n=de[u>>2]|0;r=o}de[u>>2]=n<<6;de[f>>2]=r+-6;o=(n>>>26)+7|0}if((i|0)==0|o>>>0>a>>>0){r=0;break e}r=i+-1|0;if((de[d>>2]|0)>>>0<=r>>>0){de[S>>2]=1154;de[S+4>>2]=903;de[S+8>>2]=1781;xe(I,1100,S)|0;be(I,A)|0}n=pe[(de[p>>2]|0)+r>>0]|0;if(!(n<<24>>24)){r=0;break e}r=o+i|0;if(i>>>0>=r>>>0){r=i;break r}do{if((de[d>>2]|0)>>>0<=i>>>0){de[k>>2]=1154;de[k+4>>2]=903;de[k+8>>2]=1781;xe(I,1100,k)|0;be(I,O)|0}pe[(de[p>>2]|0)+i>>0]=n;i=i+1|0}while((i|0)!=(r|0))}}}while(0);if(C>>>0>r>>>0)i=r;else break}if((M|0)==90){de[P>>2]=1154;de[P+4>>2]=3140;de[P+8>>2]=1632;xe(I,1100,P)|0;be(I,R)|0;r=0;break}if((C|0)==(r|0))r=Ot(t)|0;else r=0}else r=0}else{pe[D+16>>0]=1;r=0}}while(0);N(D);t=r;ge=L;return t|0}function Pt(e,t){e=e|0;t=t|0;var r=0,i=0,n=0,o=0,a=0,s=0,l=0,u=0,h=0;h=ge;ge=ge+544|0;s=h+16|0;a=h;o=h+24|0;if(!t){u=0;ge=h;return u|0}if(t>>>0<=16){u=Rt(e,t)|0;ge=h;return u|0}l=Rt(e,t+-16|0)|0;u=e+20|0;t=de[u>>2]|0;if((t|0)<16){i=e+4|0;n=e+8|0;r=e+16|0;do{e=de[i>>2]|0;if((e|0)==(de[n>>2]|0))e=0;else{de[i>>2]=e+1;e=me[e>>0]|0}t=t+8|0;de[u>>2]=t;if((t|0)>=33){de[a>>2]=1154;de[a+4>>2]=3199;de[a+8>>2]=1650;xe(o,1100,a)|0;be(o,s)|0;t=de[u>>2]|0}e=e<<32-t|de[r>>2];de[r>>2]=e}while((t|0)<16)}else{e=e+16|0;r=e;e=de[e>>2]|0}de[r>>2]=e<<16;de[u>>2]=t+-16;u=e>>>16|l<<16;ge=h;return u|0}function ye(e,t){e=e|0;t=t|0;var r=0,i=0,n=0,o=0,a=0,s=0,l=0,u=0,h=0,c=0,f=0,p=0,d=0,m=0,_=0,g=0,v=0,y=0;y=ge;ge=ge+608|0;m=y+88|0;d=y+72|0;f=y+64|0;c=y+48|0;h=y+40|0;p=y+24|0;u=y+16|0;l=y;g=y+96|0;_=de[t+20>>2]|0;v=e+20|0;s=de[v>>2]|0;do{if((s|0)<24){a=e+4|0;i=de[a>>2]|0;n=de[e+8>>2]|0;r=i>>>0>>0;if((s|0)>=16){if(r){de[a>>2]=i+1;r=me[i>>0]|0}else r=0;de[v>>2]=s+8;a=e+16|0;o=r<<24-s|de[a>>2];de[a>>2]=o;break}if(r){o=(me[i>>0]|0)<<8;r=i+1|0}else{o=0;r=i}if(r>>>0>>0){i=me[r>>0]|0;r=r+1|0}else i=0;de[a>>2]=r;de[v>>2]=s+16;a=e+16|0;o=(i|o)<<16-s|de[a>>2];de[a>>2]=o}else{o=e+16|0;a=o;o=de[o>>2]|0}}while(0);n=(o>>>16)+1|0;do{if(n>>>0<=(de[_+16>>2]|0)>>>0){i=de[(de[_+168>>2]|0)+(o>>>(32-(de[_+8>>2]|0)|0)<<2)>>2]|0;if((i|0)==-1){de[l>>2]=1154;de[l+4>>2]=3244;de[l+8>>2]=1677;xe(g,1100,l)|0;be(g,u)|0}r=i&65535;i=i>>>16;if((de[t+8>>2]|0)>>>0<=r>>>0){de[p>>2]=1154;de[p+4>>2]=902;de[p+8>>2]=1781;xe(g,1100,p)|0;be(g,h)|0}if((me[(de[t+4>>2]|0)+r>>0]|0|0)!=(i|0)){de[c>>2]=1154;de[c+4>>2]=3248;de[c+8>>2]=1694;xe(g,1100,c)|0;be(g,f)|0}}else{i=de[_+20>>2]|0;while(1){r=i+-1|0;if(n>>>0>(de[_+28+(r<<2)>>2]|0)>>>0)i=i+1|0;else break}r=(o>>>(32-i|0))+(de[_+96+(r<<2)>>2]|0)|0;if(r>>>0<(de[t>>2]|0)>>>0){r=_e[(de[_+176>>2]|0)+(r<<1)>>1]|0;break}de[d>>2]=1154;de[d+4>>2]=3266;de[d+8>>2]=1632;xe(g,1100,d)|0;be(g,m)|0;v=0;ge=y;return v|0}}while(0);de[a>>2]=de[a>>2]<>2]=(de[v>>2]|0)-i;v=r;ge=y;return v|0}function Rt(e,t){e=e|0;t=t|0;var r=0,i=0,n=0,o=0,a=0,s=0,l=0,u=0,h=0;h=ge;ge=ge+560|0;s=h+40|0;l=h+24|0;r=h;a=h+48|0;if(t>>>0>=33){de[r>>2]=1154;de[r+4>>2]=3190;de[r+8>>2]=1634;xe(a,1100,r)|0;be(a,h+16|0)|0}u=e+20|0;r=de[u>>2]|0;if((r|0)>=(t|0)){o=e+16|0;a=o;o=de[o>>2]|0;s=r;l=32-t|0;l=o>>>l;o=o<>2]=o;t=s-t|0;de[u>>2]=t;ge=h;return l|0}n=e+4|0;o=e+8|0;i=e+16|0;do{e=de[n>>2]|0;if((e|0)==(de[o>>2]|0))e=0;else{de[n>>2]=e+1;e=me[e>>0]|0}r=r+8|0;de[u>>2]=r;if((r|0)>=33){de[l>>2]=1154;de[l+4>>2]=3199;de[l+8>>2]=1650;xe(a,1100,l)|0;be(a,s)|0;r=de[u>>2]|0}e=e<<32-r|de[i>>2];de[i>>2]=e}while((r|0)<(t|0));l=32-t|0;l=e>>>l;s=e<>2]=s;t=r-t|0;de[u>>2]=t;ge=h;return l|0}function Ct(e,t){e=e|0;t=t|0;var r=0,i=0,n=0,o=0,a=0,s=0,l=0,u=0,h=0,c=0,f=0,p=0,d=0,m=0,_=0;d=ge;ge=ge+544|0;f=d+16|0;c=d;h=d+24|0;if((e|0)==0|t>>>0<62){p=0;ge=d;return p|0}u=j(300,0)|0;if(!u){p=0;ge=d;return p|0}de[u>>2]=519686845;r=u+4|0;de[r>>2]=0;i=u+8|0;de[i>>2]=0;l=u+88|0;n=u+136|0;o=u+160|0;a=l;s=a+44|0;do{de[a>>2]=0;a=a+4|0}while((a|0)<(s|0));pe[l+44>>0]=0;m=u+184|0;a=u+208|0;s=u+232|0;_=u+252|0;de[_>>2]=0;de[_+4>>2]=0;de[_+8>>2]=0;pe[_+12>>0]=0;_=u+268|0;de[_>>2]=0;de[_+4>>2]=0;de[_+8>>2]=0;pe[_+12>>0]=0;_=u+284|0;de[_>>2]=0;de[_+4>>2]=0;de[_+8>>2]=0;pe[_+12>>0]=0;de[n>>2]=0;de[n+4>>2]=0;de[n+8>>2]=0;de[n+12>>2]=0;de[n+16>>2]=0;pe[n+20>>0]=0;de[o>>2]=0;de[o+4>>2]=0;de[o+8>>2]=0;de[o+12>>2]=0;de[o+16>>2]=0;pe[o+20>>0]=0;de[m>>2]=0;de[m+4>>2]=0;de[m+8>>2]=0;de[m+12>>2]=0;de[m+16>>2]=0;pe[m+20>>0]=0;de[a>>2]=0;de[a+4>>2]=0;de[a+8>>2]=0;de[a+12>>2]=0;de[a+16>>2]=0;pe[a+20>>0]=0;de[s>>2]=0;de[s+4>>2]=0;de[s+8>>2]=0;de[s+12>>2]=0;pe[s+16>>0]=0;do{if(((t>>>0>=74?((me[e>>0]|0)<<8|(me[e+1>>0]|0)|0)==18552:0)?((me[e+2>>0]|0)<<8|(me[e+3>>0]|0))>>>0>=74:0)?((me[e+7>>0]|0)<<16|(me[e+6>>0]|0)<<24|(me[e+8>>0]|0)<<8|(me[e+9>>0]|0))>>>0<=t>>>0:0){de[l>>2]=e;de[r>>2]=e;de[i>>2]=t;if(jt(u)|0){r=de[l>>2]|0;if((me[r+39>>0]|0)<<8|(me[r+40>>0]|0)){if(!(Ut(u)|0))break;if(!(Gt(u)|0))break;r=de[l>>2]|0}if(!((me[r+55>>0]|0)<<8|(me[r+56>>0]|0))){_=u;ge=d;return _|0}if(Xt(u)|0?Ht(u)|0:0){_=u;ge=d;return _|0}}}else p=7}while(0);if((p|0)==7)de[l>>2]=0;Kt(u);if(!(u&7)){X[de[104>>2]&1](u,0,0,1,de[27]|0)|0;_=0;ge=d;return _|0}else{de[c>>2]=1154;de[c+4>>2]=2499;de[c+8>>2]=1516;xe(h,1100,c)|0;be(h,f)|0;_=0;ge=d;return _|0}return 0}function Mt(e,t,r,i,n){e=e|0;t=t|0;r=r|0;i=i|0;n=n|0;var o=0,a=0,s=0,l=0,u=0,h=0;h=ge;ge=ge+544|0;u=h;l=h+24|0;o=de[e+88>>2]|0;s=(me[o+70+(n<<2)+1>>0]|0)<<16|(me[o+70+(n<<2)>>0]|0)<<24|(me[o+70+(n<<2)+2>>0]|0)<<8|(me[o+70+(n<<2)+3>>0]|0);a=n+1|0;if(a>>>0<(me[o+16>>0]|0)>>>0)o=(me[o+70+(a<<2)+1>>0]|0)<<16|(me[o+70+(a<<2)>>0]|0)<<24|(me[o+70+(a<<2)+2>>0]|0)<<8|(me[o+70+(a<<2)+3>>0]|0);else o=de[e+8>>2]|0;if(o>>>0>s>>>0){l=e+4|0;l=de[l>>2]|0;l=l+s|0;u=o-s|0;u=It(e,l,u,t,r,i,n)|0;ge=h;return u|0}de[u>>2]=1154;de[u+4>>2]=3704;de[u+8>>2]=1792;xe(l,1100,u)|0;be(l,h+16|0)|0;l=e+4|0;l=de[l>>2]|0;l=l+s|0;u=o-s|0;u=It(e,l,u,t,r,i,n)|0;ge=h;return u|0}function It(e,t,r,i,n,o,a){e=e|0;t=t|0;r=r|0;i=i|0;n=n|0;o=o|0;a=a|0;var s=0,l=0,u=0,h=0;h=de[e+88>>2]|0;l=((me[h+12>>0]|0)<<8|(me[h+13>>0]|0))>>>a;u=((me[h+14>>0]|0)<<8|(me[h+15>>0]|0))>>>a;l=l>>>0>1?(l+3|0)>>>2:1;u=u>>>0>1?(u+3|0)>>>2:1;h=h+18|0;a=pe[h>>0]|0;a=ve(a<<24>>24==0|a<<24>>24==9?8:16,l)|0;if(o)if((o&3|0)==0&a>>>0<=o>>>0)a=o;else{e=0;return e|0}if((ve(a,u)|0)>>>0>n>>>0){e=0;return e|0}o=(l+1|0)>>>1;s=(u+1|0)>>>1;if(!r){e=0;return e|0}de[e+92>>2]=t;de[e+96>>2]=t;de[e+104>>2]=r;de[e+100>>2]=t+r;de[e+108>>2]=0;de[e+112>>2]=0;switch(me[h>>0]|0|0){case 0:{Yt(e,i,n,a,l,u,o,s)|0;e=1;return e|0}case 4:case 6:case 5:case 3:case 2:{Wt(e,i,n,a,l,u,o,s)|0;e=1;return e|0}case 9:{qt(e,i,n,a,l,u,o,s)|0;e=1;return e|0}case 8:case 7:{Vt(e,i,n,a,l,u,o,s)|0;e=1;return e|0}default:{e=0;return e|0}}return 0}function Dt(e,t){e=e|0;t=t|0;var r=0,i=0;i=ge;ge=ge+48|0;r=i;de[r>>2]=40;_(e,t,r)|0;ge=i;return de[r+4>>2]|0}function Lt(e,t){e=e|0;t=t|0;var r=0,i=0;i=ge;ge=ge+48|0;r=i;de[r>>2]=40;_(e,t,r)|0;ge=i;return de[r+8>>2]|0}function Ft(e,t){e=e|0;t=t|0;var r=0,i=0;i=ge;ge=ge+48|0;r=i;de[r>>2]=40;_(e,t,r)|0;ge=i;return de[r+12>>2]|0}function Nt(e,t){e=e|0;t=t|0;var r=0,i=0;i=ge;ge=ge+48|0;r=i;de[r>>2]=40;_(e,t,r)|0;ge=i;return de[r+32>>2]|0}function zt(e,t,r){e=e|0;t=t|0;r=r|0;var i=0,n=0,o=0,a=0,s=0,l=0,u=0;l=ge;ge=ge+576|0;a=l+56|0;o=l+40|0;n=l+64|0;u=l;de[u>>2]=40;_(e,t,u)|0;i=(((de[u+4>>2]|0)>>>r)+3|0)>>>2;t=(((de[u+8>>2]|0)>>>r)+3|0)>>>2;r=u+32|0;e=de[r+4>>2]|0;do{switch(de[r>>2]|0){case 0:{if(!e)e=8;else s=13;break}case 1:{if(!e)s=12;else s=13;break}case 2:{if(!e)s=12;else s=13;break}case 3:{if(!e)s=12;else s=13;break}case 4:{if(!e)s=12;else s=13;break}case 5:{if(!e)s=12;else s=13;break}case 6:{if(!e)s=12;else s=13;break}case 7:{if(!e)s=12;else s=13;break}case 8:{if(!e)s=12;else s=13;break}case 9:{if(!e)e=8;else s=13;break}default:s=13}}while(0);if((s|0)==12)e=16;else if((s|0)==13){de[o>>2]=1154;de[o+4>>2]=2663;de[o+8>>2]=1535;xe(n,1100,o)|0;be(n,a)|0;e=0}u=ve(ve(t,i)|0,e)|0;ge=l;return u|0}function Bt(e,t,r,i,n){e=e|0;t=t|0;r=r|0;i=i|0;n=n|0;var o=0,a=0,s=0,l=0,u=0,h=0,c=0,f=0,p=0,d=0,m=0;d=ge;ge=ge+608|0;f=d+80|0;p=d+64|0;s=d+56|0;a=d+40|0;h=d+88|0;m=d;c=d+84|0;de[m>>2]=40;_(e,t,m)|0;l=(((de[m+4>>2]|0)>>>n)+3|0)>>>2;m=m+32|0;o=de[m+4>>2]|0;do{switch(de[m>>2]|0){case 0:{if(!o)o=8;else u=13;break}case 1:{if(!o)u=12;else u=13;break}case 2:{if(!o)u=12;else u=13;break}case 3:{if(!o)u=12;else u=13;break}case 4:{if(!o)u=12;else u=13;break}case 5:{if(!o)u=12;else u=13;break}case 6:{if(!o)u=12;else u=13;break}case 7:{if(!o)u=12;else u=13;break}case 8:{if(!o)u=12;else u=13;break}case 9:{if(!o)o=8;else u=13;break}default:u=13}}while(0);if((u|0)==12)o=16;else if((u|0)==13){de[a>>2]=1154;de[a+4>>2]=2663;de[a+8>>2]=1535;xe(h,1100,a)|0;be(h,s)|0;o=0}s=ve(o,l)|0;a=Ct(e,t)|0;de[c>>2]=r;o=(a|0)==0;if(!(n>>>0>15|(i>>>0<8|o))?(de[a>>2]|0)==519686845:0)Mt(a,c,i,s,n)|0;if(o){ge=d;return}if((de[a>>2]|0)!=519686845){ge=d;return}Kt(a);if(!(a&7)){X[de[104>>2]&1](a,0,0,1,de[27]|0)|0;ge=d;return}else{de[p>>2]=1154;de[p+4>>2]=2499;de[p+8>>2]=1516;xe(h,1100,p)|0;be(h,f)|0;ge=d;return}}function jt(e){e=e|0;var t=0,r=0,i=0,n=0,o=0,a=0;a=e+92|0;i=de[e+4>>2]|0;o=e+88|0;n=de[o>>2]|0;t=(me[n+68>>0]|0)<<8|(me[n+67>>0]|0)<<16|(me[n+69>>0]|0);r=i+t|0;n=(me[n+65>>0]|0)<<8|(me[n+66>>0]|0);if(!n){e=0;return e|0}de[a>>2]=r;de[e+96>>2]=r;de[e+104>>2]=n;de[e+100>>2]=i+(n+t);de[e+108>>2]=0;de[e+112>>2]=0;if(!(U(a,e+116|0)|0)){e=0;return e|0}t=de[o>>2]|0;do{if(!((me[t+39>>0]|0)<<8|(me[t+40>>0]|0))){if(!((me[t+55>>0]|0)<<8|(me[t+56>>0]|0))){e=0;return e|0}}else{if(!(U(a,e+140|0)|0)){e=0;return e|0}if(U(a,e+188|0)|0){t=de[o>>2]|0;break}else{e=0;return e|0}}}while(0);if((me[t+55>>0]|0)<<8|(me[t+56>>0]|0)){if(!(U(a,e+164|0)|0)){e=0;return e|0}if(!(U(a,e+212|0)|0)){e=0;return e|0}}e=1;return e|0}function Ut(e){e=e|0;var t=0,r=0,i=0,n=0,o=0,a=0,s=0,l=0,u=0,h=0,c=0,f=0,p=0,d=0;d=ge;ge=ge+592|0;l=d+16|0;s=d;a=d+72|0;p=d+24|0;i=e+88|0;t=de[i>>2]|0;f=(me[t+39>>0]|0)<<8|(me[t+40>>0]|0);h=e+236|0;o=e+240|0;r=de[o>>2]|0;if((r|0)!=(f|0)){if(r>>>0<=f>>>0){do{if((de[e+244>>2]|0)>>>0>>0){if(F(h,f,(r+1|0)==(f|0),4,0)|0){t=de[o>>2]|0;break}pe[e+248>>0]=1;p=0;ge=d;return p|0}else t=r}while(0);G((de[h>>2]|0)+(t<<2)|0,0,f-t<<2|0)|0;t=de[i>>2]|0}de[o>>2]=f}u=e+92|0;r=de[e+4>>2]|0;i=(me[t+34>>0]|0)<<8|(me[t+33>>0]|0)<<16|(me[t+35>>0]|0);n=r+i|0;t=(me[t+37>>0]|0)<<8|(me[t+36>>0]|0)<<16|(me[t+38>>0]|0);if(!t){p=0;ge=d;return p|0}de[u>>2]=n;de[e+96>>2]=n;de[e+104>>2]=t;de[e+100>>2]=r+(t+i);de[e+108>>2]=0;de[e+112>>2]=0;de[p+20>>2]=0;de[p>>2]=0;de[p+4>>2]=0;de[p+8>>2]=0;de[p+12>>2]=0;pe[p+16>>0]=0;e=p+24|0;de[p+44>>2]=0;de[e>>2]=0;de[e+4>>2]=0;de[e+8>>2]=0;de[e+12>>2]=0;pe[e+16>>0]=0;if(U(u,p)|0?(c=p+24|0,U(u,c)|0):0){if(!(de[o>>2]|0)){de[s>>2]=1154;de[s+4>>2]=903;de[s+8>>2]=1781;xe(a,1100,s)|0;be(a,l)|0}if(!f)t=1;else{i=0;n=0;o=0;t=0;a=0;e=0;s=0;r=de[h>>2]|0;while(1){i=(ye(u,p)|0)+i&31;n=(ye(u,c)|0)+n&63;o=(ye(u,p)|0)+o&31;t=(ye(u,p)|0)+t|0;a=(ye(u,c)|0)+a&63;e=(ye(u,p)|0)+e&31;de[r>>2]=n<<5|i<<11|o|t<<27|a<<21|e<<16;s=s+1|0;if((s|0)==(f|0)){t=1;break}else{t=t&31;r=r+4|0}}}}else t=0;N(p+24|0);N(p);p=t;ge=d;return p|0}function Gt(e){e=e|0;var t=0,r=0,i=0,n=0,o=0,a=0,s=0,l=0,u=0,h=0,c=0,f=0,p=0,d=0,m=0,_=0,g=0,v=0,y=0,b=0,x=0,T=0,w=0,E=0,S=0,A=0,k=0;S=ge;ge=ge+1024|0;s=S+16|0;a=S;o=S+504|0;E=S+480|0;T=S+284|0;w=S+88|0;x=S+24|0;n=de[e+88>>2]|0;b=(me[n+47>>0]|0)<<8|(me[n+48>>0]|0);y=e+92|0;t=de[e+4>>2]|0;r=(me[n+42>>0]|0)<<8|(me[n+41>>0]|0)<<16|(me[n+43>>0]|0);i=t+r|0;n=(me[n+45>>0]|0)<<8|(me[n+44>>0]|0)<<16|(me[n+46>>0]|0);if(!n){E=0;ge=S;return E|0}de[y>>2]=i;de[e+96>>2]=i;de[e+104>>2]=n;de[e+100>>2]=t+(n+r);de[e+108>>2]=0;de[e+112>>2]=0;de[E+20>>2]=0;de[E>>2]=0;de[E+4>>2]=0;de[E+8>>2]=0;de[E+12>>2]=0;pe[E+16>>0]=0;if(U(y,E)|0){r=0;i=-3;n=-3;while(1){de[T+(r<<2)>>2]=i;de[w+(r<<2)>>2]=n;t=(i|0)>2;r=r+1|0;if((r|0)==49)break;else{i=t?-3:i+1|0;n=(t&1)+n|0}}t=x;r=t+64|0;do{de[t>>2]=0;t=t+4|0}while((t|0)<(r|0));v=e+252|0;r=e+256|0;t=de[r>>2]|0;e:do{if((t|0)==(b|0))l=13;else{if(t>>>0<=b>>>0){do{if((de[e+260>>2]|0)>>>0>>0)if(F(v,b,(t+1|0)==(b|0),4,0)|0){t=de[r>>2]|0;break}else{pe[e+264>>0]=1;t=0;break e}}while(0);G((de[v>>2]|0)+(t<<2)|0,0,b-t<<2|0)|0}de[r>>2]=b;l=13}}while(0);do{if((l|0)==13){if(!b){de[a>>2]=1154;de[a+4>>2]=903;de[a+8>>2]=1781;xe(o,1100,a)|0;be(o,s)|0;t=1;break}i=x+4|0;n=x+8|0;e=x+12|0;o=x+16|0;a=x+20|0;s=x+24|0;l=x+28|0;u=x+32|0;h=x+36|0;c=x+40|0;f=x+44|0;p=x+48|0;d=x+52|0;m=x+56|0;_=x+60|0;g=0;r=de[v>>2]|0;while(1){t=0;do{A=ye(y,E)|0;v=t<<1;k=x+(v<<2)|0;de[k>>2]=(de[k>>2]|0)+(de[T+(A<<2)>>2]|0)&3;v=x+((v|1)<<2)|0;de[v>>2]=(de[v>>2]|0)+(de[w+(A<<2)>>2]|0)&3;t=t+1|0}while((t|0)!=8);de[r>>2]=(me[1725+(de[i>>2]|0)>>0]|0)<<2|(me[1725+(de[x>>2]|0)>>0]|0)|(me[1725+(de[n>>2]|0)>>0]|0)<<4|(me[1725+(de[e>>2]|0)>>0]|0)<<6|(me[1725+(de[o>>2]|0)>>0]|0)<<8|(me[1725+(de[a>>2]|0)>>0]|0)<<10|(me[1725+(de[s>>2]|0)>>0]|0)<<12|(me[1725+(de[l>>2]|0)>>0]|0)<<14|(me[1725+(de[u>>2]|0)>>0]|0)<<16|(me[1725+(de[h>>2]|0)>>0]|0)<<18|(me[1725+(de[c>>2]|0)>>0]|0)<<20|(me[1725+(de[f>>2]|0)>>0]|0)<<22|(me[1725+(de[p>>2]|0)>>0]|0)<<24|(me[1725+(de[d>>2]|0)>>0]|0)<<26|(me[1725+(de[m>>2]|0)>>0]|0)<<28|(me[1725+(de[_>>2]|0)>>0]|0)<<30;g=g+1|0;if((g|0)==(b|0)){t=1;break}else r=r+4|0}}}while(0)}else t=0;N(E);k=t;ge=S;return k|0}function Xt(e){e=e|0;var t=0,r=0,i=0,n=0,o=0,a=0,s=0,l=0,u=0,h=0,c=0,f=0;f=ge;ge=ge+560|0;l=f+16|0;s=f;a=f+48|0;c=f+24|0;n=de[e+88>>2]|0;h=(me[n+55>>0]|0)<<8|(me[n+56>>0]|0);u=e+92|0;t=de[e+4>>2]|0;r=(me[n+50>>0]|0)<<8|(me[n+49>>0]|0)<<16|(me[n+51>>0]|0);i=t+r|0;n=(me[n+53>>0]|0)<<8|(me[n+52>>0]|0)<<16|(me[n+54>>0]|0);if(!n){c=0;ge=f;return c|0}de[u>>2]=i;de[e+96>>2]=i;de[e+104>>2]=n;de[e+100>>2]=t+(n+r);de[e+108>>2]=0;de[e+112>>2]=0;de[c+20>>2]=0;de[c>>2]=0;de[c+4>>2]=0;de[c+8>>2]=0;de[c+12>>2]=0;pe[c+16>>0]=0;e:do{if(U(u,c)|0){o=e+268|0;r=e+272|0;t=de[r>>2]|0;if((t|0)!=(h|0)){if(t>>>0<=h>>>0){do{if((de[e+276>>2]|0)>>>0>>0)if(F(o,h,(t+1|0)==(h|0),2,0)|0){t=de[r>>2]|0;break}else{pe[e+280>>0]=1;t=0;break e}}while(0);G((de[o>>2]|0)+(t<<1)|0,0,h-t<<1|0)|0}de[r>>2]=h}if(!h){de[s>>2]=1154;de[s+4>>2]=903;de[s+8>>2]=1781;xe(a,1100,s)|0;be(a,l)|0;t=1;break}r=0;i=0;n=0;t=de[o>>2]|0;while(1){l=ye(u,c)|0;r=l+r&255;i=(ye(u,c)|0)+i&255;$[t>>1]=i<<8|r;n=n+1|0;if((n|0)==(h|0)){t=1;break}else t=t+2|0}}else t=0}while(0);N(c);c=t;ge=f;return c|0}function Ht(e){e=e|0;var t=0,r=0,i=0,n=0,o=0,a=0,s=0,l=0,u=0,h=0,c=0,f=0,p=0,d=0,m=0,_=0,g=0,v=0,y=0,b=0,x=0,T=0,w=0,E=0,S=0,A=0,k=0;S=ge;ge=ge+2432|0;s=S+16|0;a=S;o=S+1912|0;E=S+1888|0;T=S+988|0;w=S+88|0;x=S+24|0;n=de[e+88>>2]|0;b=(me[n+63>>0]|0)<<8|(me[n+64>>0]|0);y=e+92|0;t=de[e+4>>2]|0;r=(me[n+58>>0]|0)<<8|(me[n+57>>0]|0)<<16|(me[n+59>>0]|0);i=t+r|0;n=(me[n+61>>0]|0)<<8|(me[n+60>>0]|0)<<16|(me[n+62>>0]|0);if(!n){E=0;ge=S;return E|0}de[y>>2]=i;de[e+96>>2]=i;de[e+104>>2]=n;de[e+100>>2]=t+(n+r);de[e+108>>2]=0;de[e+112>>2]=0;de[E+20>>2]=0;de[E>>2]=0;de[E+4>>2]=0;de[E+8>>2]=0;de[E+12>>2]=0;pe[E+16>>0]=0;if(U(y,E)|0){r=0;i=-7;n=-7;while(1){de[T+(r<<2)>>2]=i;de[w+(r<<2)>>2]=n;t=(i|0)>6;r=r+1|0;if((r|0)==225)break;else{i=t?-7:i+1|0;n=(t&1)+n|0}}t=x;r=t+64|0;do{de[t>>2]=0;t=t+4|0}while((t|0)<(r|0));v=e+284|0;r=b*3|0;i=e+288|0;t=de[i>>2]|0;e:do{if((t|0)==(r|0))l=13;else{if(t>>>0<=r>>>0){do{if((de[e+292>>2]|0)>>>0>>0)if(F(v,r,(t+1|0)==(r|0),2,0)|0){t=de[i>>2]|0;break}else{pe[e+296>>0]=1;t=0;break e}}while(0);G((de[v>>2]|0)+(t<<1)|0,0,r-t<<1|0)|0}de[i>>2]=r;l=13}}while(0);do{if((l|0)==13){if(!b){de[a>>2]=1154;de[a+4>>2]=903;de[a+8>>2]=1781;xe(o,1100,a)|0;be(o,s)|0;t=1;break}i=x+4|0;n=x+8|0;e=x+12|0;o=x+16|0;a=x+20|0;s=x+24|0;l=x+28|0;u=x+32|0;h=x+36|0;c=x+40|0;f=x+44|0;p=x+48|0;d=x+52|0;m=x+56|0;_=x+60|0;g=0;r=de[v>>2]|0;while(1){t=0;do{A=ye(y,E)|0;v=t<<1;k=x+(v<<2)|0;de[k>>2]=(de[k>>2]|0)+(de[T+(A<<2)>>2]|0)&7;v=x+((v|1)<<2)|0;de[v>>2]=(de[v>>2]|0)+(de[w+(A<<2)>>2]|0)&7;t=t+1|0}while((t|0)!=8);A=me[1729+(de[a>>2]|0)>>0]|0;$[r>>1]=(me[1729+(de[i>>2]|0)>>0]|0)<<3|(me[1729+(de[x>>2]|0)>>0]|0)|(me[1729+(de[n>>2]|0)>>0]|0)<<6|(me[1729+(de[e>>2]|0)>>0]|0)<<9|(me[1729+(de[o>>2]|0)>>0]|0)<<12|A<<15;k=me[1729+(de[c>>2]|0)>>0]|0;$[r+2>>1]=(me[1729+(de[s>>2]|0)>>0]|0)<<2|A>>>1|(me[1729+(de[l>>2]|0)>>0]|0)<<5|(me[1729+(de[u>>2]|0)>>0]|0)<<8|(me[1729+(de[h>>2]|0)>>0]|0)<<11|k<<14;$[r+4>>1]=(me[1729+(de[f>>2]|0)>>0]|0)<<1|k>>>2|(me[1729+(de[p>>2]|0)>>0]|0)<<4|(me[1729+(de[d>>2]|0)>>0]|0)<<7|(me[1729+(de[m>>2]|0)>>0]|0)<<10|(me[1729+(de[_>>2]|0)>>0]|0)<<13;g=g+1|0;if((g|0)==(b|0)){t=1;break}else r=r+6|0}}}while(0)}else t=0;N(E);k=t;ge=S;return k|0}function Yt(e,F,t,r,i,n,N,o){e=e|0;F=F|0;t=t|0;r=r|0;i=i|0;n=n|0;N=N|0;o=o|0;var a=0,s=0,l=0,z=0,u=0,h=0,c=0,f=0,B=0,j=0,p=0,U=0,G=0,d=0,m=0,X=0,_=0,g=0,H=0,Y=0,W=0,q=0,v=0,V=0,K=0,J=0,y=0,Z=0,Q=0,$=0,ee=0,te=0,re=0,ie=0,ne=0,b=0,x=0,T=0,w=0,E=0,S=0,oe=0,A=0,ae=0,k=0,se=0,O=0,le=0,ue=0,P=0,he=0,R=0,ce=0,C=0,M=0,fe=0,I=0,D=0,L=0;I=ge;ge=ge+720|0;fe=I+184|0;C=I+168|0;ce=I+160|0;R=I+144|0;he=I+136|0;P=I+120|0;ue=I+112|0;O=I+96|0;se=I+88|0;k=I+72|0;ae=I+64|0;A=I+48|0;oe=I+40|0;M=I+24|0;le=I+16|0;S=I;w=I+208|0;E=I+192|0;te=e+240|0;re=de[te>>2]|0;b=e+256|0;x=de[b>>2]|0;t=pe[(de[e+88>>2]|0)+17>>0]|0;T=r>>>2;if(!(t<<24>>24)){ge=I;return 1}ie=(o|0)==0;ne=o+-1|0;K=(n&1|0)!=0;J=r<<1;y=e+92|0;Z=e+116|0;Q=e+140|0;$=e+236|0;ee=N+-1|0;V=(i&1|0)!=0;v=e+188|0;g=e+252|0;H=T+1|0;Y=T+2|0;W=T+3|0;q=ee<<4;X=t&255;t=0;n=0;i=1;_=0;do{if(!ie){d=de[F+(_<<2)>>2]|0;m=0;while(1){p=m&1;a=(p|0)==0;j=(p<<5^32)+-16|0;p=(p<<1^2)+-1|0;G=a?N:-1;s=a?0:ee;e=(m|0)==(ne|0);U=K&e;if((s|0)!=(G|0)){B=K&e^1;f=a?d:d+q|0;while(1){if((i|0)==1)i=ye(y,Z)|0|512;c=i&7;i=i>>>3;a=me[1823+c>>0]|0;e=0;do{u=(ye(y,Q)|0)+n|0;h=u-re|0;n=h>>31;n=n&u|h&~n;if((de[te>>2]|0)>>>0<=n>>>0){de[S>>2]=1154;de[S+4>>2]=903;de[S+8>>2]=1781;xe(w,1100,S)|0;be(w,le)|0}de[E+(e<<2)>>2]=de[(de[$>>2]|0)+(n<<2)>>2];e=e+1|0}while(e>>>0>>0);h=V&(s|0)==(ee|0);if(U|h){u=0;do{l=ve(u,r)|0;e=f+l|0;a=(u|0)==0|B;z=u<<1;L=(ye(y,v)|0)+t|0;D=L-x|0;t=D>>31;t=t&L|D&~t;do{if(h){if(!a){D=(ye(y,v)|0)+t|0;L=D-x|0;t=L>>31;t=t&D|L&~t;break}de[e>>2]=de[E+((me[1831+(c<<2)+z>>0]|0)<<2)>>2];if((de[b>>2]|0)>>>0<=t>>>0){de[R>>2]=1154;de[R+4>>2]=903;de[R+8>>2]=1781;xe(w,1100,R)|0;be(w,ce)|0}de[f+(l+4)>>2]=de[(de[g>>2]|0)+(t<<2)>>2];D=(ye(y,v)|0)+t|0;L=D-x|0;t=L>>31;t=t&D|L&~t}else{if(!a){D=(ye(y,v)|0)+t|0;L=D-x|0;t=L>>31;t=t&D|L&~t;break}de[e>>2]=de[E+((me[1831+(c<<2)+z>>0]|0)<<2)>>2];if((de[b>>2]|0)>>>0<=t>>>0){de[P>>2]=1154;de[P+4>>2]=903;de[P+8>>2]=1781;xe(w,1100,P)|0;be(w,he)|0}de[f+(l+4)>>2]=de[(de[g>>2]|0)+(t<<2)>>2];D=(ye(y,v)|0)+t|0;L=D-x|0;t=L>>31;t=t&D|L&~t;de[f+(l+8)>>2]=de[E+((me[(z|1)+(1831+(c<<2))>>0]|0)<<2)>>2];if((de[b>>2]|0)>>>0<=t>>>0){de[C>>2]=1154;de[C+4>>2]=903;de[C+8>>2]=1781;xe(w,1100,C)|0;be(w,fe)|0}de[f+(l+12)>>2]=de[(de[g>>2]|0)+(t<<2)>>2]}}while(0);u=u+1|0}while((u|0)!=2)}else{de[f>>2]=de[E+((me[1831+(c<<2)>>0]|0)<<2)>>2];D=(ye(y,v)|0)+t|0;L=D-x|0;t=L>>31;t=t&D|L&~t;if((de[b>>2]|0)>>>0<=t>>>0){de[M>>2]=1154;de[M+4>>2]=903;de[M+8>>2]=1781;xe(w,1100,M)|0;be(w,oe)|0}de[f+4>>2]=de[(de[g>>2]|0)+(t<<2)>>2];de[f+8>>2]=de[E+((me[1831+(c<<2)+1>>0]|0)<<2)>>2];D=(ye(y,v)|0)+t|0;L=D-x|0;t=L>>31;t=t&D|L&~t;if((de[b>>2]|0)>>>0<=t>>>0){de[A>>2]=1154;de[A+4>>2]=903;de[A+8>>2]=1781;xe(w,1100,A)|0;be(w,ae)|0}de[f+12>>2]=de[(de[g>>2]|0)+(t<<2)>>2];de[f+(T<<2)>>2]=de[E+((me[1831+(c<<2)+2>>0]|0)<<2)>>2];D=(ye(y,v)|0)+t|0;L=D-x|0;t=L>>31;t=t&D|L&~t;if((de[b>>2]|0)>>>0<=t>>>0){de[k>>2]=1154;de[k+4>>2]=903;de[k+8>>2]=1781;xe(w,1100,k)|0;be(w,se)|0}de[f+(H<<2)>>2]=de[(de[g>>2]|0)+(t<<2)>>2];de[f+(Y<<2)>>2]=de[E+((me[1831+(c<<2)+3>>0]|0)<<2)>>2];D=(ye(y,v)|0)+t|0;L=D-x|0;t=L>>31;t=t&D|L&~t;if((de[b>>2]|0)>>>0<=t>>>0){de[O>>2]=1154;de[O+4>>2]=903;de[O+8>>2]=1781;xe(w,1100,O)|0;be(w,ue)|0}de[f+(W<<2)>>2]=de[(de[g>>2]|0)+(t<<2)>>2]}s=s+p|0;if((s|0)==(G|0))break;else f=f+j|0}}m=m+1|0;if((m|0)==(o|0))break;else d=d+J|0}}_=_+1|0}while((_|0)!=(X|0));ge=I;return 1}function Wt(e,t,r,i,n,o,a,s){e=e|0;t=t|0;r=r|0;i=i|0;n=n|0;o=o|0;a=a|0;s=s|0;var l=0,u=0,h=0,c=0,f=0,p=0,F=0,N=0,d=0,m=0,_=0,g=0,v=0,z=0,B=0,y=0,b=0,x=0,T=0,j=0,w=0,U=0,G=0,X=0,H=0,Y=0,W=0,q=0,V=0,K=0,J=0,E=0,Z=0,Q=0,$=0,S=0,ee=0,te=0,A=0,re=0,k=0,ie=0,ne=0,oe=0,O=0,ae=0,se=0,P=0,le=0,R=0,ue=0,C=0,he=0,M=0,ce=0,fe=0,I=0,D=0,L=0;D=ge;ge=ge+640|0;ce=D+88|0;M=D+72|0;he=D+64|0;C=D+48|0;ue=D+40|0;I=D+24|0;fe=D+16|0;R=D;P=D+128|0;le=D+112|0;se=D+96|0;E=e+240|0;Z=de[E>>2]|0;S=e+256|0;oe=de[S>>2]|0;O=e+272|0;ae=de[O>>2]|0;r=de[e+88>>2]|0;Q=(me[r+63>>0]|0)<<8|(me[r+64>>0]|0);r=pe[r+17>>0]|0;if(!(r<<24>>24)){ge=D;return 1}$=(s|0)==0;ee=s+-1|0;te=i<<1;A=e+92|0;re=e+116|0;k=a+-1|0;ie=e+212|0;ne=e+188|0;J=(n&1|0)==0;K=(o&1|0)==0;X=e+288|0;H=e+284|0;Y=e+252|0;W=e+140|0;q=e+236|0;V=e+164|0;U=e+268|0;G=k<<5;j=r&255;r=0;n=0;o=0;e=0;l=1;w=0;do{if(!$){x=de[t+(w<<2)>>2]|0;T=0;while(1){y=T&1;u=(y|0)==0;B=(y<<6^64)+-32|0;y=(y<<1^2)+-1|0;b=u?a:-1;h=u?0:k;if((h|0)!=(b|0)){z=K|(T|0)!=(ee|0);v=u?x:x+G|0;while(1){if((l|0)==1)l=ye(A,re)|0|512;g=l&7;l=l>>>3;c=me[1823+g>>0]|0;u=0;do{m=(ye(A,V)|0)+n|0;_=m-ae|0;n=_>>31;n=n&m|_&~n;if((de[O>>2]|0)>>>0<=n>>>0){de[R>>2]=1154;de[R+4>>2]=903;de[R+8>>2]=1781;xe(P,1100,R)|0;be(P,fe)|0}de[se+(u<<2)>>2]=_e[(de[U>>2]|0)+(n<<1)>>1];u=u+1|0}while(u>>>0>>0);u=0;do{m=(ye(A,W)|0)+e|0;_=m-Z|0;e=_>>31;e=e&m|_&~e;if((de[E>>2]|0)>>>0<=e>>>0){de[I>>2]=1154;de[I+4>>2]=903;de[I+8>>2]=1781;xe(P,1100,I)|0;be(P,ue)|0}de[le+(u<<2)>>2]=de[(de[q>>2]|0)+(e<<2)>>2];u=u+1|0}while(u>>>0>>0);_=J|(h|0)!=(k|0);d=0;m=v;while(1){N=z|(d|0)==0;F=d<<1;f=0;p=m;while(1){c=(ye(A,ie)|0)+r|0;u=c-Q|0;r=u>>31;r=r&c|u&~r;u=(ye(A,ne)|0)+o|0;c=u-oe|0;o=c>>31;o=o&u|c&~o;if((_|(f|0)==0)&N){u=me[f+F+(1831+(g<<2))>>0]|0;c=r*3|0;if((de[X>>2]|0)>>>0<=c>>>0){de[C>>2]=1154;de[C+4>>2]=903;de[C+8>>2]=1781;xe(P,1100,C)|0;be(P,he)|0}L=de[H>>2]|0;de[p>>2]=(_e[L+(c<<1)>>1]|0)<<16|de[se+(u<<2)>>2];de[p+4>>2]=(_e[L+(c+2<<1)>>1]|0)<<16|(_e[L+(c+1<<1)>>1]|0);de[p+8>>2]=de[le+(u<<2)>>2];if((de[S>>2]|0)>>>0<=o>>>0){de[M>>2]=1154;de[M+4>>2]=903;de[M+8>>2]=1781;xe(P,1100,M)|0;be(P,ce)|0}de[p+12>>2]=de[(de[Y>>2]|0)+(o<<2)>>2]}f=f+1|0;if((f|0)==2)break;else p=p+16|0}d=d+1|0;if((d|0)==2)break;else m=m+i|0}h=h+y|0;if((h|0)==(b|0))break;else v=v+B|0}}T=T+1|0;if((T|0)==(s|0))break;else x=x+te|0}}w=w+1|0}while((w|0)!=(j|0));ge=D;return 1}function qt(e,t,r,i,n,o,a,s){e=e|0;t=t|0;r=r|0;i=i|0;n=n|0;o=o|0;a=a|0;s=s|0;var l=0,u=0,h=0,c=0,f=0,p=0,d=0,m=0,_=0,g=0,F=0,N=0,v=0,y=0,b=0,x=0,T=0,z=0,B=0,j=0,U=0,w=0,E=0,G=0,X=0,S=0,H=0,A=0,Y=0,W=0,q=0,k=0,V=0,O=0,P=0,R=0,C=0,M=0,K=0,I=0,J=0,Z=0,D=0,L=0;L=ge;ge=ge+608|0;J=L+64|0;I=L+48|0;K=L+40|0;D=L+24|0;Z=L+16|0;M=L;C=L+88|0;R=L+72|0;S=e+272|0;H=de[S>>2]|0;r=de[e+88>>2]|0;A=(me[r+63>>0]|0)<<8|(me[r+64>>0]|0);r=pe[r+17>>0]|0;if(!(r<<24>>24)){ge=L;return 1}Y=(s|0)==0;W=s+-1|0;q=i<<1;k=e+92|0;V=e+116|0;O=a+-1|0;P=e+212|0;X=(o&1|0)==0;w=e+288|0;E=e+284|0;G=e+164|0;j=e+268|0;U=O<<4;B=r&255;z=(n&1|0)!=0;r=0;o=0;e=1;T=0;do{if(!Y){b=de[t+(T<<2)>>2]|0;x=0;while(1){v=x&1;n=(v|0)==0;N=(v<<5^32)+-16|0;v=(v<<1^2)+-1|0;y=n?a:-1;l=n?0:O;if((l|0)!=(y|0)){F=X|(x|0)!=(W|0);g=n?b:b+U|0;while(1){if((e|0)==1)e=ye(k,V)|0|512;_=e&7;e=e>>>3;u=me[1823+_>>0]|0;n=0;do{d=(ye(k,G)|0)+o|0;m=d-H|0;o=m>>31;o=o&d|m&~o;if((de[S>>2]|0)>>>0<=o>>>0){de[M>>2]=1154;de[M+4>>2]=903;de[M+8>>2]=1781;xe(C,1100,M)|0;be(C,Z)|0}de[R+(n<<2)>>2]=_e[(de[j>>2]|0)+(o<<1)>>1];n=n+1|0}while(n>>>0>>0);m=(l|0)==(O|0)&z;p=0;d=g;while(1){f=F|(p|0)==0;c=p<<1;n=(ye(k,P)|0)+r|0;h=n-A|0;u=h>>31;u=u&n|h&~u;if(f){r=me[1831+(_<<2)+c>>0]|0;n=u*3|0;if((de[w>>2]|0)>>>0<=n>>>0){de[D>>2]=1154;de[D+4>>2]=903;de[D+8>>2]=1781;xe(C,1100,D)|0;be(C,K)|0}h=de[E>>2]|0;de[d>>2]=(_e[h+(n<<1)>>1]|0)<<16|de[R+(r<<2)>>2];de[d+4>>2]=(_e[h+(n+2<<1)>>1]|0)<<16|(_e[h+(n+1<<1)>>1]|0)}h=d+8|0;n=(ye(k,P)|0)+u|0;u=n-A|0;r=u>>31;r=r&n|u&~r;if(!(m|f^1)){n=me[(c|1)+(1831+(_<<2))>>0]|0;u=r*3|0;if((de[w>>2]|0)>>>0<=u>>>0){de[I>>2]=1154;de[I+4>>2]=903;de[I+8>>2]=1781;xe(C,1100,I)|0;be(C,J)|0}f=de[E>>2]|0;de[h>>2]=(_e[f+(u<<1)>>1]|0)<<16|de[R+(n<<2)>>2];de[d+12>>2]=(_e[f+(u+2<<1)>>1]|0)<<16|(_e[f+(u+1<<1)>>1]|0)}p=p+1|0;if((p|0)==2)break;else d=d+i|0}l=l+v|0;if((l|0)==(y|0))break;else g=g+N|0}}x=x+1|0;if((x|0)==(s|0))break;else b=b+q|0}}T=T+1|0}while((T|0)!=(B|0));ge=L;return 1}function Vt(e,t,r,i,n,o,a,s){e=e|0;t=t|0;r=r|0;i=i|0;n=n|0;o=o|0;a=a|0;s=s|0;var l=0,u=0,h=0,c=0,f=0,p=0,d=0,m=0,_=0,F=0,N=0,g=0,v=0,y=0,b=0,x=0,z=0,B=0,T=0,w=0,E=0,S=0,j=0,A=0,U=0,G=0,X=0,H=0,Y=0,W=0,q=0,k=0,V=0,K=0,J=0,Z=0,Q=0,O=0,$=0,P=0,ee=0,te=0,re=0,R=0,C=0,ie=0,M=0,ne=0,I=0,oe=0,ae=0,D=0,L=0;L=ge;ge=ge+640|0;oe=L+88|0;I=L+72|0;ne=L+64|0;M=L+48|0;ie=L+40|0;D=L+24|0;ae=L+16|0;C=L;R=L+128|0;te=L+112|0;re=L+96|0;k=e+272|0;V=de[k>>2]|0;r=de[e+88>>2]|0;K=(me[r+63>>0]|0)<<8|(me[r+64>>0]|0);r=pe[r+17>>0]|0;if(!(r<<24>>24)){ge=L;return 1}J=(s|0)==0;Z=s+-1|0;Q=i<<1;O=e+92|0;$=e+116|0;P=a+-1|0;ee=e+212|0;q=(n&1|0)==0;W=(o&1|0)==0;X=e+288|0;H=e+284|0;Y=e+164|0;U=e+268|0;G=P<<5;j=r&255;r=0;n=0;o=0;e=0;l=1;A=0;do{if(!J){E=de[t+(A<<2)>>2]|0;S=0;while(1){T=S&1;u=(T|0)==0;B=(T<<6^64)+-32|0;T=(T<<1^2)+-1|0;w=u?a:-1;h=u?0:P;if((h|0)!=(w|0)){z=W|(S|0)!=(Z|0);x=u?E:E+G|0;while(1){if((l|0)==1)l=ye(O,$)|0|512;b=l&7;l=l>>>3;c=me[1823+b>>0]|0;u=0;do{v=(ye(O,Y)|0)+e|0;y=v-V|0;e=y>>31;e=e&v|y&~e;if((de[k>>2]|0)>>>0<=e>>>0){de[C>>2]=1154;de[C+4>>2]=903;de[C+8>>2]=1781;xe(R,1100,C)|0;be(R,ae)|0}de[te+(u<<2)>>2]=_e[(de[U>>2]|0)+(e<<1)>>1];u=u+1|0}while(u>>>0>>0);u=0;do{v=(ye(O,Y)|0)+n|0;y=v-V|0;n=y>>31;n=n&v|y&~n;if((de[k>>2]|0)>>>0<=n>>>0){de[D>>2]=1154;de[D+4>>2]=903;de[D+8>>2]=1781;xe(R,1100,D)|0;be(R,ie)|0}de[re+(u<<2)>>2]=_e[(de[U>>2]|0)+(n<<1)>>1];u=u+1|0}while(u>>>0>>0);y=q|(h|0)!=(P|0);g=0;v=x;while(1){N=z|(g|0)==0;F=g<<1;m=0;_=v;while(1){d=(ye(O,ee)|0)+o|0;p=d-K|0;o=p>>31;o=o&d|p&~o;p=(ye(O,ee)|0)+r|0;d=p-K|0;r=d>>31;r=r&p|d&~r;if((y|(m|0)==0)&N){p=me[m+F+(1831+(b<<2))>>0]|0;d=o*3|0;u=de[X>>2]|0;if(u>>>0<=d>>>0){de[M>>2]=1154;de[M+4>>2]=903;de[M+8>>2]=1781;xe(R,1100,M)|0;be(R,ne)|0;u=de[X>>2]|0}c=de[H>>2]|0;f=r*3|0;if(u>>>0>f>>>0)u=c;else{de[I>>2]=1154;de[I+4>>2]=903;de[I+8>>2]=1781;xe(R,1100,I)|0;be(R,oe)|0;u=de[H>>2]|0}de[_>>2]=(_e[c+(d<<1)>>1]|0)<<16|de[te+(p<<2)>>2];de[_+4>>2]=(_e[c+(d+2<<1)>>1]|0)<<16|(_e[c+(d+1<<1)>>1]|0);de[_+8>>2]=(_e[u+(f<<1)>>1]|0)<<16|de[re+(p<<2)>>2];de[_+12>>2]=(_e[u+(f+2<<1)>>1]|0)<<16|(_e[u+(f+1<<1)>>1]|0)}m=m+1|0;if((m|0)==2)break;else _=_+16|0}g=g+1|0;if((g|0)==2)break;else v=v+i|0}h=h+T|0;if((h|0)==(w|0))break;else x=x+B|0}}S=S+1|0;if((S|0)==(s|0))break;else E=E+Q|0}}A=A+1|0}while((A|0)!=(j|0));ge=L;return 1}function Kt(e){e=e|0;var t=0,r=0,i=0,n=0,o=0,a=0,s=0,l=0,u=0,h=0,c=0,f=0;f=ge;ge=ge+608|0;c=f+88|0;h=f+72|0;l=f+64|0;s=f+48|0;o=f+40|0;a=f+24|0;n=f+16|0;i=f;u=f+96|0;de[e>>2]=0;t=e+284|0;r=de[t>>2]|0;if(r){if(!(r&7))X[de[104>>2]&1](r,0,0,1,de[27]|0)|0;else{de[i>>2]=1154;de[i+4>>2]=2499;de[i+8>>2]=1516;xe(u,1100,i)|0;be(u,n)|0}de[t>>2]=0;de[e+288>>2]=0;de[e+292>>2]=0}pe[e+296>>0]=0;t=e+268|0;r=de[t>>2]|0;if(r){if(!(r&7))X[de[104>>2]&1](r,0,0,1,de[27]|0)|0;else{de[a>>2]=1154;de[a+4>>2]=2499;de[a+8>>2]=1516;xe(u,1100,a)|0;be(u,o)|0}de[t>>2]=0;de[e+272>>2]=0;de[e+276>>2]=0}pe[e+280>>0]=0;t=e+252|0;r=de[t>>2]|0;if(r){if(!(r&7))X[de[104>>2]&1](r,0,0,1,de[27]|0)|0;else{de[s>>2]=1154;de[s+4>>2]=2499;de[s+8>>2]=1516;xe(u,1100,s)|0;be(u,l)|0}de[t>>2]=0;de[e+256>>2]=0;de[e+260>>2]=0}pe[e+264>>0]=0;t=e+236|0;r=de[t>>2]|0;if(!r){c=e+248|0;pe[c>>0]=0;c=e+212|0;N(c);c=e+188|0;N(c);c=e+164|0;N(c);c=e+140|0;N(c);c=e+116|0;N(c);ge=f;return}if(!(r&7))X[de[104>>2]&1](r,0,0,1,de[27]|0)|0;else{de[h>>2]=1154;de[h+4>>2]=2499;de[h+8>>2]=1516;xe(u,1100,h)|0;be(u,c)|0}de[t>>2]=0;de[e+240>>2]=0;de[e+244>>2]=0;c=e+248|0;pe[c>>0]=0;c=e+212|0;N(c);c=e+188|0;N(c);c=e+164|0;N(c);c=e+140|0;N(c);c=e+116|0;N(c);ge=f}function l(e,t){e=e|0;t=t|0;var r=0;r=ge;ge=ge+16|0;de[r>>2]=t;t=de[63]|0;Pr(t,e,r)|0;Or(10,t)|0;B()}function Jt(){var e=0,t=0;e=ge;ge=ge+16|0;if(!(rt(200,2)|0)){t=et(de[49]|0)|0;ge=e;return t|0}else l(2090,e);return 0}function Zt(e){e=e|0;b(e)}function Qt(e){e=e|0;var t=0;t=ge;ge=ge+16|0;Mi[e&3]();l(2139,t)}function $t(){var e=0,t=0;e=Jt()|0;if(((e|0)!=0?(t=de[e>>2]|0,(t|0)!=0):0)?(e=t+48|0,(de[e>>2]&-256|0)==1126902528?(de[e+4>>2]|0)==1129074247:0):0)Qt(de[t+12>>2]|0);t=de[28]|0;de[28]=t+0;Qt(t)}function er(e){e=e|0}function tr(e){e=e|0;return}function rr(e){e=e|0;return}function ir(e){e=e|0;return}function nr(e){e=e|0;Zt(e);return}function or(e){e=e|0;Zt(e);return}function ar(e,t,r){e=e|0;t=t|0;r=r|0;var i=0,n=0,o=0,a=0;a=ge;ge=ge+64|0;o=a;if((e|0)!=(t|0))if((t|0)!=0?(n=hr(t,24,40,0)|0,(n|0)!=0):0){t=o;i=t+56|0;do{de[t>>2]=0;t=t+4|0}while((t|0)<(i|0));de[o>>2]=n;de[o+8>>2]=e;de[o+12>>2]=-1;de[o+48>>2]=1;Di[de[(de[n>>2]|0)+28>>2]&3](n,o,de[r>>2]|0,1);if((de[o+24>>2]|0)==1){de[r>>2]=de[o+16>>2];t=1}else t=0}else t=0;else t=1;ge=a;return t|0}function sr(e,t,r,i){e=e|0;t=t|0;r=r|0;i=i|0;var n=0;e=t+16|0;n=de[e>>2]|0;do{if(n){if((n|0)!=(r|0)){i=t+36|0;de[i>>2]=(de[i>>2]|0)+1;de[t+24>>2]=2;pe[t+54>>0]=1;break}e=t+24|0;if((de[e>>2]|0)==2)de[e>>2]=i}else{de[e>>2]=r;de[t+24>>2]=i;de[t+36>>2]=1}}while(0)}function lr(e,t,r,i){e=e|0;t=t|0;r=r|0;i=i|0;if((e|0)==(de[t+8>>2]|0))sr(0,t,r,i);return}function ur(e,t,r,i){e=e|0;t=t|0;r=r|0;i=i|0;if((e|0)==(de[t+8>>2]|0))sr(0,t,r,i);else{e=de[e+8>>2]|0;Di[de[(de[e>>2]|0)+28>>2]&3](e,t,r,i)}return}function hr(e,t,r,i){e=e|0;t=t|0;r=r|0;i=i|0;var n=0,o=0,a=0,s=0,l=0,u=0,h=0,c=0,f=0,p=0;p=ge;ge=ge+64|0;f=p;c=de[e>>2]|0;h=e+(de[c+-8>>2]|0)|0;c=de[c+-4>>2]|0;de[f>>2]=r;de[f+4>>2]=e;de[f+8>>2]=t;de[f+12>>2]=i;i=f+16|0;e=f+20|0;t=f+24|0;n=f+28|0;o=f+32|0;a=f+40|0;s=(c|0)==(r|0);l=i;u=l+36|0;do{de[l>>2]=0;l=l+4|0}while((l|0)<(u|0));$[i+36>>1]=0;pe[i+38>>0]=0;e:do{if(s){de[f+48>>2]=1;Ii[de[(de[r>>2]|0)+20>>2]&3](r,f,h,h,1,0);i=(de[t>>2]|0)==1?h:0}else{Oi[de[(de[c>>2]|0)+24>>2]&3](c,f,h,1,0);switch(de[f+36>>2]|0){case 0:{i=(de[a>>2]|0)==1&(de[n>>2]|0)==1&(de[o>>2]|0)==1?de[e>>2]|0:0;break e}case 1:break;default:{i=0;break e}}if((de[t>>2]|0)!=1?!((de[a>>2]|0)==0&(de[n>>2]|0)==1&(de[o>>2]|0)==1):0){i=0;break}i=de[i>>2]|0}}while(0);ge=p;return i|0}function cr(e,t,r,i,n){e=e|0;t=t|0;r=r|0;i=i|0;n=n|0;pe[t+53>>0]=1;do{if((de[t+4>>2]|0)==(i|0)){pe[t+52>>0]=1;i=t+16|0;e=de[i>>2]|0;if(!e){de[i>>2]=r;de[t+24>>2]=n;de[t+36>>2]=1;if(!((n|0)==1?(de[t+48>>2]|0)==1:0))break;pe[t+54>>0]=1;break}if((e|0)!=(r|0)){n=t+36|0;de[n>>2]=(de[n>>2]|0)+1;pe[t+54>>0]=1;break}e=t+24|0;i=de[e>>2]|0;if((i|0)==2){de[e>>2]=n;i=n}if((i|0)==1?(de[t+48>>2]|0)==1:0)pe[t+54>>0]=1}}while(0)}function fr(e,t,r,i,n){e=e|0;t=t|0;r=r|0;i=i|0;n=n|0;var o=0,a=0,s=0,l=0;e:do{if((e|0)==(de[t+8>>2]|0)){if((de[t+4>>2]|0)==(r|0)?(o=t+28|0,(de[o>>2]|0)!=1):0)de[o>>2]=i}else{if((e|0)!=(de[t>>2]|0)){s=de[e+8>>2]|0;Oi[de[(de[s>>2]|0)+24>>2]&3](s,t,r,i,n);break}if((de[t+16>>2]|0)!=(r|0)?(a=t+20|0,(de[a>>2]|0)!=(r|0)):0){de[t+32>>2]=i;i=t+44|0;if((de[i>>2]|0)==4)break;o=t+52|0;pe[o>>0]=0;l=t+53|0;pe[l>>0]=0;e=de[e+8>>2]|0;Ii[de[(de[e>>2]|0)+20>>2]&3](e,t,r,r,1,n);if(pe[l>>0]|0){if(!(pe[o>>0]|0)){o=1;s=13}}else{o=0;s=13}do{if((s|0)==13){de[a>>2]=r;l=t+40|0;de[l>>2]=(de[l>>2]|0)+1;if((de[t+36>>2]|0)==1?(de[t+24>>2]|0)==2:0){pe[t+54>>0]=1;if(o)break}else s=16;if((s|0)==16?o:0)break;de[i>>2]=4;break e}}while(0);de[i>>2]=3;break}if((i|0)==1)de[t+32>>2]=1}}while(0);return}function pr(e,t,r,i,n){e=e|0;t=t|0;r=r|0;i=i|0;n=n|0;var o=0,a=0;do{if((e|0)==(de[t+8>>2]|0)){if((de[t+4>>2]|0)==(r|0)?(a=t+28|0,(de[a>>2]|0)!=1):0)de[a>>2]=i}else if((e|0)==(de[t>>2]|0)){if((de[t+16>>2]|0)!=(r|0)?(o=t+20|0,(de[o>>2]|0)!=(r|0)):0){de[t+32>>2]=i;de[o>>2]=r;n=t+40|0;de[n>>2]=(de[n>>2]|0)+1;if((de[t+36>>2]|0)==1?(de[t+24>>2]|0)==2:0)pe[t+54>>0]=1;de[t+44>>2]=4;break}if((i|0)==1)de[t+32>>2]=1}}while(0);return}function dr(e,t,r,i,n,o){e=e|0;t=t|0;r=r|0;i=i|0;n=n|0;o=o|0;if((e|0)==(de[t+8>>2]|0))cr(0,t,r,i,n);else{e=de[e+8>>2]|0;Ii[de[(de[e>>2]|0)+20>>2]&3](e,t,r,i,n,o)}return}function mr(e,t,r,i,n,o){e=e|0;t=t|0;r=r|0;i=i|0;n=n|0;o=o|0;if((e|0)==(de[t+8>>2]|0))cr(0,t,r,i,n);return}function _r(e,t,r){e=e|0;t=t|0;r=r|0;var i=0,n=0;n=ge;ge=ge+16|0;i=n;de[i>>2]=de[r>>2];e=v[de[(de[e>>2]|0)+16>>2]&7](e,t,i)|0;if(e)de[r>>2]=de[i>>2];ge=n;return e&1|0}function gr(e){e=e|0;if(!e)e=0;else e=(hr(e,24,72,0)|0)!=0;return e&1|0}function vr(){var e=0,t=0,r=0,i=0,n=0,o=0,a=0,s=0;n=ge;ge=ge+48|0;a=n+32|0;r=n+24|0;s=n+16|0;o=n;n=n+36|0;e=Jt()|0;if((e|0)!=0?(i=de[e>>2]|0,(i|0)!=0):0){e=i+48|0;t=de[e>>2]|0;e=de[e+4>>2]|0;if(!((t&-256|0)==1126902528&(e|0)==1129074247)){de[r>>2]=de[51];l(2368,r)}if((t|0)==1126902529&(e|0)==1129074247)e=de[i+44>>2]|0;else e=i+80|0;de[n>>2]=e;i=de[i>>2]|0;e=de[i+4>>2]|0;if(v[de[(de[8>>2]|0)+16>>2]&7](8,i,n)|0){s=de[n>>2]|0;n=de[51]|0;s=Ri[de[(de[s>>2]|0)+8>>2]&1](s)|0;de[o>>2]=n;de[o+4>>2]=e;de[o+8>>2]=s;l(2282,o)}else{de[s>>2]=de[51];de[s+4>>2]=e;l(2327,s)}}l(2406,a)}function yr(){var e=0;e=ge;ge=ge+16|0;if(!(it(196,6)|0)){ge=e;return}else l(2179,e)}function br(e){e=e|0;var t=0;t=ge;ge=ge+16|0;b(e);if(!(at(de[49]|0,0)|0)){ge=t;return}else l(2229,t)}function xr(e){e=e|0;var t=0,r=0;t=0;while(1){if((me[2427+t>>0]|0)==(e|0)){r=2;break}t=t+1|0;if((t|0)==87){t=87;e=2515;r=5;break}}if((r|0)==2)if(!t)e=2515;else{e=2515;r=5}if((r|0)==5)while(1){r=e;while(1){e=r+1|0;if(!(pe[r>>0]|0))break;else r=e}t=t+-1|0;if(!t)break;else r=5}return e|0}function ie(){var e=0;if(!(de[52]|0))e=264;else{e=(tt()|0)+60|0;e=de[e>>2]|0}return e|0}function Tr(e){e=e|0;var t=0;if(e>>>0>4294963200){t=ie()|0;de[t>>2]=0-e;e=-1}return e|0}function wr(e,t){e=+e;t=t|0;var r=0,i=0,n=0;ee[te>>3]=e;r=de[te>>2]|0;i=de[te+4>>2]|0;n=Zr(r|0,i|0,52)|0;n=n&2047;switch(n|0){case 0:{if(e!=0.0){e=+wr(e*18446744073709552.0e3,t);r=(de[t>>2]|0)+-64|0}else r=0;de[t>>2]=r;break}case 2047:break;default:{de[t>>2]=n+-1022;de[te>>2]=r;de[te+4>>2]=i&-2146435073|1071644672;e=+ee[te>>3]}}return+e}function Er(e,t){e=+e;t=t|0;return+ +wr(e,t)}function Sr(e,t,r){e=e|0;t=t|0;r=r|0;do{if(e){if(t>>>0<128){pe[e>>0]=t;e=1;break}if(t>>>0<2048){pe[e>>0]=t>>>6|192;pe[e+1>>0]=t&63|128;e=2;break}if(t>>>0<55296|(t&-8192|0)==57344){pe[e>>0]=t>>>12|224;pe[e+1>>0]=t>>>6&63|128;pe[e+2>>0]=t&63|128;e=3;break}if((t+-65536|0)>>>0<1048576){pe[e>>0]=t>>>18|240;pe[e+1>>0]=t>>>12&63|128;pe[e+2>>0]=t>>>6&63|128;pe[e+3>>0]=t&63|128;e=4;break}else{e=ie()|0;de[e>>2]=84;e=-1;break}}else e=1}while(0);return e|0}function Ar(e,t){e=e|0;t=t|0;if(!e)e=0;else e=Sr(e,t,0)|0;return e|0}function kr(e){e=e|0;var t=0,r=0;do{if(e){if((de[e+76>>2]|0)<=-1){t=jr(e)|0;break}r=(Mr(e)|0)==0;t=jr(e)|0;if(!r)g(e)}else{if(!(de[65]|0))t=0;else t=kr(de[65]|0)|0;st(236);e=de[58]|0;if(e)do{if((de[e+76>>2]|0)>-1)r=Mr(e)|0;else r=0;if((de[e+20>>2]|0)>>>0>(de[e+28>>2]|0)>>>0)t=jr(e)|0|t;if(r)g(e);e=de[e+56>>2]|0}while((e|0)!=0);nt(236)}}while(0);return t|0}function Or(e,t){e=e|0;t=t|0;var r=0,i=0,n=0,o=0,a=0;if((de[t+76>>2]|0)>=0?(Mr(t)|0)!=0:0){if((pe[t+75>>0]|0)!=(e|0)?(i=t+20|0,n=de[i>>2]|0,n>>>0<(de[t+16>>2]|0)>>>0):0){de[i>>2]=n+1;pe[n>>0]=e;r=e&255}else r=Ir(t,e)|0;g(t)}else a=3;do{if((a|0)==3){if((pe[t+75>>0]|0)!=(e|0)?(o=t+20|0,r=de[o>>2]|0,r>>>0<(de[t+16>>2]|0)>>>0):0){de[o>>2]=r+1;pe[r>>0]=e;r=e&255;break}r=Ir(t,e)|0}}while(0);return r|0}function ne(e,t,r){e=e|0;t=t|0;r=r|0;var i=0,n=0,o=0,a=0;i=r+16|0;n=de[i>>2]|0;if(!n)if(!(zr(r)|0)){n=de[i>>2]|0;o=4}else i=0;else o=4;e:do{if((o|0)==4){a=r+20|0;o=de[a>>2]|0;if((n-o|0)>>>0>>0){i=v[de[r+36>>2]&7](r,e,t)|0;break}t:do{if((pe[r+75>>0]|0)>-1){i=t;while(1){if(!i){n=o;i=0;break t}n=i+-1|0;if((pe[e+n>>0]|0)==10)break;else i=n}if((v[de[r+36>>2]&7](r,e,i)|0)>>>0>>0)break e;t=t-i|0;e=e+i|0;n=de[a>>2]|0}else{n=o;i=0}}while(0);ei(n|0,e|0,t|0)|0;de[a>>2]=(de[a>>2]|0)+t;i=i+t|0}}while(0);return i|0}function be(e,t){e=e|0;t=t|0;var r=0,i=0;r=ge;ge=ge+16|0;i=r;de[i>>2]=t;t=Pr(de[64]|0,e,i)|0;ge=r;return t|0}function xe(e,t,r){e=e|0;t=t|0;r=r|0;var i=0,n=0;i=ge;ge=ge+16|0;n=i;de[n>>2]=r;r=Cr(e,t,n)|0;ge=i;return r|0}function Pr(e,t,r){e=e|0;t=t|0;r=r|0;var i=0,n=0,o=0,a=0,s=0,l=0,u=0,h=0,c=0,f=0,p=0,d=0,m=0;m=ge;ge=ge+224|0;c=m+120|0;d=m+80|0;p=m;f=m+136|0;i=d;n=i+40|0;do{de[i>>2]=0;i=i+4|0}while((i|0)<(n|0));de[c>>2]=de[r>>2];if((Ur(0,t,c,p,d)|0)<0)r=-1;else{if((de[e+76>>2]|0)>-1)u=Mr(e)|0;else u=0;r=de[e>>2]|0;h=r&32;if((pe[e+74>>0]|0)<1)de[e>>2]=r&-33;r=e+48|0;if(!(de[r>>2]|0)){n=e+44|0;o=de[n>>2]|0;de[n>>2]=f;a=e+28|0;de[a>>2]=f;s=e+20|0;de[s>>2]=f;de[r>>2]=80;l=e+16|0;de[l>>2]=f+80;i=Ur(e,t,c,p,d)|0;if(o){v[de[e+36>>2]&7](e,0,0)|0;i=(de[s>>2]|0)==0?-1:i;de[n>>2]=o;de[r>>2]=0;de[l>>2]=0;de[a>>2]=0;de[s>>2]=0}}else i=Ur(e,t,c,p,d)|0;r=de[e>>2]|0;de[e>>2]=r|h;if(u)g(e);r=(r&32|0)==0?i:-1}ge=m;return r|0}function Rr(e,t,r,i){e=e|0;t=t|0;r=r|0;i=i|0;var n=0,o=0,a=0,s=0,l=0,u=0,h=0;h=ge;ge=ge+128|0;n=h+112|0;u=h;o=u;a=268;s=o+112|0;do{de[o>>2]=de[a>>2];o=o+4|0;a=a+4|0}while((o|0)<(s|0));if((t+-1|0)>>>0>2147483646)if(!t){t=1;l=4}else{t=ie()|0;de[t>>2]=75;t=-1}else{n=e;l=4}if((l|0)==4){l=-2-n|0;l=t>>>0>l>>>0?l:t;de[u+48>>2]=l;e=u+20|0;de[e>>2]=n;de[u+44>>2]=n;t=n+l|0;n=u+16|0;de[n>>2]=t;de[u+28>>2]=t;t=Pr(u,r,i)|0;if(l){r=de[e>>2]|0;pe[r+(((r|0)==(de[n>>2]|0))<<31>>31)>>0]=0}}ge=h;return t|0}function Cr(e,t,r){e=e|0;t=t|0;r=r|0;return Rr(e,2147483647,t,r)|0}function Mr(e){e=e|0;return 0}function g(e){e=e|0}function Ir(e,t){e=e|0;t=t|0;var r=0,i=0,n=0,o=0,a=0,s=0,l=0;l=ge;ge=ge+16|0;s=l;a=t&255;pe[s>>0]=a;i=e+16|0;n=de[i>>2]|0;if(!n)if(!(zr(e)|0)){n=de[i>>2]|0;o=4}else r=-1;else o=4;do{if((o|0)==4){i=e+20|0;o=de[i>>2]|0;if(o>>>0>>0?(r=t&255,(r|0)!=(pe[e+75>>0]|0)):0){de[i>>2]=o+1;pe[o>>0]=a;break}if((v[de[e+36>>2]&7](e,s,1)|0)==1)r=me[s>>0]|0;else r=-1}}while(0);ge=l;return r|0}function Dr(e){e=e|0;var t=0,r=0;t=ge;ge=ge+16|0;r=t;de[r>>2]=de[e+60>>2];e=Tr(qe(6,r|0)|0)|0;ge=t;return e|0}function Lr(e,t,r){e=e|0;t=t|0;r=r|0;var i=0,n=0,o=0;n=ge;ge=ge+32|0;o=n;i=n+20|0;de[o>>2]=de[e+60>>2];de[o+4>>2]=0;de[o+8>>2]=t;de[o+12>>2]=i;de[o+16>>2]=r;if((Tr(ht(140,o|0)|0)|0)<0){de[i>>2]=-1;e=-1}else e=de[i>>2]|0;ge=n;return e|0}function Fr(e,t,r){e=e|0;t=t|0;r=r|0;var i=0,n=0,o=0,a=0,s=0,l=0,u=0,h=0,c=0,f=0,p=0,d=0;d=ge;ge=ge+48|0;c=d+16|0;h=d;i=d+32|0;f=e+28|0;n=de[f>>2]|0;de[i>>2]=n;p=e+20|0;n=(de[p>>2]|0)-n|0;de[i+4>>2]=n;de[i+8>>2]=t;de[i+12>>2]=r;l=e+60|0;u=e+44|0;t=2;n=n+r|0;while(1){if(!(de[52]|0)){de[c>>2]=de[l>>2];de[c+4>>2]=i;de[c+8>>2]=t;a=Tr(ct(146,c|0)|0)|0}else{lt(7,e|0);de[h>>2]=de[l>>2];de[h+4>>2]=i;de[h+8>>2]=t;a=Tr(ct(146,h|0)|0)|0;Ye(0)}if((n|0)==(a|0)){n=6;break}if((a|0)<0){n=8;break}n=n-a|0;o=de[i+4>>2]|0;if(a>>>0<=o>>>0)if((t|0)==2){de[f>>2]=(de[f>>2]|0)+a;s=o;t=2}else s=o;else{s=de[u>>2]|0;de[f>>2]=s;de[p>>2]=s;s=de[i+12>>2]|0;a=a-o|0;i=i+8|0;t=t+-1|0}de[i>>2]=(de[i>>2]|0)+a;de[i+4>>2]=s-a}if((n|0)==6){c=de[u>>2]|0;de[e+16>>2]=c+(de[e+48>>2]|0);e=c;de[f>>2]=e;de[p>>2]=e}else if((n|0)==8){de[e+16>>2]=0;de[f>>2]=0;de[p>>2]=0;de[e>>2]=de[e>>2]|32;if((t|0)==2)r=0;else r=r-(de[i+4>>2]|0)|0}ge=d;return r|0}function Nr(e,t,r){e=e|0;t=t|0;r=r|0;var i=0,n=0;n=ge;ge=ge+80|0;i=n;de[e+36>>2]=3;if((de[e>>2]&64|0)==0?(de[i>>2]=de[e+60>>2],de[i+4>>2]=21505,de[i+8>>2]=n+12,(We(54,i|0)|0)!=0):0)pe[e+75>>0]=-1;i=Fr(e,t,r)|0;ge=n;return i|0}function zr(e){e=e|0;var t=0,r=0;t=e+74|0;r=pe[t>>0]|0;pe[t>>0]=r+255|r;t=de[e>>2]|0;if(!(t&8)){de[e+8>>2]=0;de[e+4>>2]=0;t=de[e+44>>2]|0;de[e+28>>2]=t;de[e+20>>2]=t;de[e+16>>2]=t+(de[e+48>>2]|0);t=0}else{de[e>>2]=t|32;t=-1}return t|0}function Br(e,t,r){e=e|0;t=t|0;r=r|0;var i=0,n=0,o=0,a=0;o=t&255;i=(r|0)!=0;e:do{if(i&(e&3|0)!=0){n=t&255;while(1){if((pe[e>>0]|0)==n<<24>>24){a=6;break e}e=e+1|0;r=r+-1|0;i=(r|0)!=0;if(!(i&(e&3|0)!=0)){a=5;break}}}else a=5}while(0);if((a|0)==5)if(i)a=6;else r=0;e:do{if((a|0)==6){n=t&255;if((pe[e>>0]|0)!=n<<24>>24){i=ve(o,16843009)|0;t:do{if(r>>>0>3)while(1){o=de[e>>2]^i;if((o&-2139062144^-2139062144)&o+-16843009)break;e=e+4|0;r=r+-4|0;if(r>>>0<=3){a=11;break t}}else a=11}while(0);if((a|0)==11)if(!r){r=0;break}while(1){if((pe[e>>0]|0)==n<<24>>24)break e;e=e+1|0;r=r+-1|0;if(!r){r=0;break}}}}}while(0);return((r|0)!=0?e:0)|0}function jr(e){e=e|0;var t=0,r=0,i=0,n=0,o=0,a=0;t=e+20|0;o=e+28|0;if((de[t>>2]|0)>>>0>(de[o>>2]|0)>>>0?(v[de[e+36>>2]&7](e,0,0)|0,(de[t>>2]|0)==0):0)t=-1;else{a=e+4|0;r=de[a>>2]|0;i=e+8|0;n=de[i>>2]|0;if(r>>>0>>0)v[de[e+40>>2]&7](e,r-n|0,1)|0;de[e+16>>2]=0;de[o>>2]=0;de[t>>2]=0;de[i>>2]=0;de[a>>2]=0;t=0}return t|0}function Ur(e,t,r,i,n){e=e|0;t=t|0;r=r|0;i=i|0;n=n|0;var o=0,a=0,s=0,l=0,u=0.0,h=0,c=0,f=0,p=0,d=0.0,m=0,_=0,g=0,v=0,F=0,y=0,b=0,x=0,T=0,w=0,E=0,S=0,A=0,k=0,O=0,N=0,P=0,z=0,B=0,j=0,R=0,U=0,G=0,X=0,H=0,Y=0,W=0,q=0,V=0,C=0,K=0,M=0,J=0,I=0,D=0,Z=0,Q=0,L=0;L=ge;ge=ge+624|0;J=L+24|0;D=L+16|0;I=L+588|0;q=L+576|0;M=L;H=L+536|0;Q=L+8|0;Z=L+528|0;N=(e|0)!=0;P=H+40|0;X=P;H=H+39|0;Y=Q+4|0;W=q+12|0;q=q+11|0;V=I;C=W;K=C-V|0;z=-2-V|0;B=C+2|0;j=J+288|0;R=I+9|0;U=R;G=I+8|0;o=0;m=t;a=0;t=0;e:while(1){do{if((o|0)>-1)if((a|0)>(2147483647-o|0)){o=ie()|0;de[o>>2]=75;o=-1;break}else{o=a+o|0;break}}while(0);a=pe[m>>0]|0;if(!(a<<24>>24)){O=245;break}else s=m;t:while(1){switch(a<<24>>24){case 37:{a=s;O=9;break t}case 0:{a=s;break t}default:{}}k=s+1|0;a=pe[k>>0]|0;s=k}t:do{if((O|0)==9)while(1){O=0;if((pe[a+1>>0]|0)!=37)break t;s=s+1|0;a=a+2|0;if((pe[a>>0]|0)==37)O=9;else break}}while(0);g=s-m|0;if(N?(de[e>>2]&32|0)==0:0)ne(m,g,e)|0;if((s|0)!=(m|0)){m=a;a=g;continue}h=a+1|0;s=pe[h>>0]|0;l=(s<<24>>24)+-48|0;if(l>>>0<10){k=(pe[a+2>>0]|0)==36;h=k?a+3|0:h;s=pe[h>>0]|0;p=k?l:-1;t=k?1:t}else p=-1;a=s<<24>>24;t:do{if((a&-32|0)==32){l=0;while(1){if(!(1<>24)+-32|l;h=h+1|0;s=pe[h>>0]|0;a=s<<24>>24;if((a&-32|0)!=32){c=l;a=h;break}}}else{c=0;a=h}}while(0);do{if(s<<24>>24==42){l=a+1|0;s=(pe[l>>0]|0)+-48|0;if(s>>>0<10?(pe[a+2>>0]|0)==36:0){de[n+(s<<2)>>2]=10;t=1;a=a+3|0;s=de[i+((pe[l>>0]|0)+-48<<3)>>2]|0}else{if(t){o=-1;break e}if(!N){_=c;a=l;t=0;k=0;break}t=(de[r>>2]|0)+(4-1)&~(4-1);s=de[t>>2]|0;de[r>>2]=t+4;t=0;a=l}if((s|0)<0){_=c|8192;k=0-s|0}else{_=c;k=s}}else{l=(s<<24>>24)+-48|0;if(l>>>0<10){s=0;do{s=(s*10|0)+l|0;a=a+1|0;l=(pe[a>>0]|0)+-48|0}while(l>>>0<10);if((s|0)<0){o=-1;break e}else{_=c;k=s}}else{_=c;k=0}}}while(0);t:do{if((pe[a>>0]|0)==46){l=a+1|0;s=pe[l>>0]|0;if(s<<24>>24!=42){h=(s<<24>>24)+-48|0;if(h>>>0<10){a=l;s=0}else{a=l;h=0;break}while(1){s=(s*10|0)+h|0;a=a+1|0;h=(pe[a>>0]|0)+-48|0;if(h>>>0>=10){h=s;break t}}}l=a+2|0;s=(pe[l>>0]|0)+-48|0;if(s>>>0<10?(pe[a+3>>0]|0)==36:0){de[n+(s<<2)>>2]=10;a=a+4|0;h=de[i+((pe[l>>0]|0)+-48<<3)>>2]|0;break}if(t){o=-1;break e}if(N){a=(de[r>>2]|0)+(4-1)&~(4-1);h=de[a>>2]|0;de[r>>2]=a+4;a=l}else{a=l;h=0}}else h=-1}while(0);f=0;while(1){s=(pe[a>>0]|0)+-65|0;if(s>>>0>57){o=-1;break e}l=a+1|0;s=pe[5359+(f*58|0)+s>>0]|0;c=s&255;if((c+-1|0)>>>0<8){a=l;f=c}else{A=l;break}}if(!(s<<24>>24)){o=-1;break}l=(p|0)>-1;do{if(s<<24>>24==19)if(l){o=-1;break e}else O=52;else{if(l){de[n+(p<<2)>>2]=c;E=i+(p<<3)|0;S=de[E+4>>2]|0;O=M;de[O>>2]=de[E>>2];de[O+4>>2]=S;O=52;break}if(!N){o=0;break e}Hr(M,c,r)}}while(0);if((O|0)==52?(O=0,!N):0){m=A;a=g;continue}p=pe[a>>0]|0;p=(f|0)!=0&(p&15|0)==3?p&-33:p;l=_&-65537;S=(_&8192|0)==0?_:l;t:do{switch(p|0){case 110:switch(f|0){case 0:{de[de[M>>2]>>2]=o;m=A;a=g;continue e}case 1:{de[de[M>>2]>>2]=o;m=A;a=g;continue e}case 2:{m=de[M>>2]|0;de[m>>2]=o;de[m+4>>2]=((o|0)<0)<<31>>31;m=A;a=g;continue e}case 3:{$[de[M>>2]>>1]=o;m=A;a=g;continue e}case 4:{pe[de[M>>2]>>0]=o;m=A;a=g;continue e}case 6:{de[de[M>>2]>>2]=o;m=A;a=g;continue e}case 7:{m=de[M>>2]|0;de[m>>2]=o;de[m+4>>2]=((o|0)<0)<<31>>31;m=A;a=g;continue e}default:{m=A;a=g;continue e}}case 112:{f=S|8;h=h>>>0>8?h:8;p=120;O=64;break}case 88:case 120:{f=S;O=64;break}case 111:{l=M;s=de[l>>2]|0;l=de[l+4>>2]|0;if((s|0)==0&(l|0)==0)a=P;else{a=P;do{a=a+-1|0;pe[a>>0]=s&7|48;s=Zr(s|0,l|0,3)|0;l=re}while(!((s|0)==0&(l|0)==0))}if(!(S&8)){s=S;f=0;c=5839;O=77}else{f=X-a+1|0;s=S;h=(h|0)<(f|0)?f:h;f=0;c=5839;O=77}break}case 105:case 100:{s=M;a=de[s>>2]|0;s=de[s+4>>2]|0;if((s|0)<0){a=se(0,0,a|0,s|0)|0;s=re;l=M;de[l>>2]=a;de[l+4>>2]=s;l=1;c=5839;O=76;break t}if(!(S&2048)){c=S&1;l=c;c=(c|0)==0?5839:5841;O=76}else{l=1;c=5840;O=76}break}case 117:{s=M;a=de[s>>2]|0;s=de[s+4>>2]|0;l=0;c=5839;O=76;break}case 99:{pe[H>>0]=de[M>>2];m=H;s=1;f=0;p=5839;a=P;break}case 109:{a=ie()|0;a=xr(de[a>>2]|0)|0;O=82;break}case 115:{a=de[M>>2]|0;a=(a|0)!=0?a:5849;O=82;break}case 67:{de[Q>>2]=de[M>>2];de[Y>>2]=0;de[M>>2]=Q;h=-1;O=86;break}case 83:{if(!h){ae(e,32,k,0,S);a=0;O=98}else O=86;break}case 65:case 71:case 70:case 69:case 97:case 103:case 102:case 101:{u=+ee[M>>3];de[D>>2]=0;ee[te>>3]=u;if((de[te+4>>2]|0)>=0)if(!(S&2048)){E=S&1;w=E;E=(E|0)==0?5857:5862}else{w=1;E=5859}else{u=-u;w=1;E=5856}ee[te>>3]=u;T=de[te+4>>2]&2146435072;do{if(T>>>0<2146435072|(T|0)==2146435072&0<0){d=+Er(u,D)*2.0;s=d!=0.0;if(s)de[D>>2]=(de[D>>2]|0)+-1;b=p|32;if((b|0)==97){m=p&32;g=(m|0)==0?E:E+9|0;_=w|2;a=12-h|0;do{if(!(h>>>0>11|(a|0)==0)){u=8.0;do{a=a+-1|0;u=u*16.0}while((a|0)!=0);if((pe[g>>0]|0)==45){u=-(u+(-d-u));break}else{u=d+u-u;break}}else u=d}while(0);s=de[D>>2]|0;a=(s|0)<0?0-s|0:s;a=oe(a,((a|0)<0)<<31>>31,W)|0;if((a|0)==(W|0)){pe[q>>0]=48;a=q}pe[a+-1>>0]=(s>>31&2)+43;f=a+-2|0;pe[f>>0]=p+15;c=(h|0)<1;l=(S&8|0)==0;s=I;while(1){E=~~u;a=s+1|0;pe[s>>0]=me[5823+E>>0]|m;u=(u-+(E|0))*16.0;do{if((a-V|0)==1){if(l&(c&u==0.0))break;pe[a>>0]=46;a=s+2|0}}while(0);if(!(u!=0.0))break;else s=a}h=(h|0)!=0&(z+a|0)<(h|0)?B+h-f|0:K-f+a|0;l=h+_|0;ae(e,32,k,l,S);if(!(de[e>>2]&32))ne(g,_,e)|0;ae(e,48,k,l,S^65536);a=a-V|0;if(!(de[e>>2]&32))ne(I,a,e)|0;s=C-f|0;ae(e,48,h-(a+s)|0,0,0);if(!(de[e>>2]&32))ne(f,s,e)|0;ae(e,32,k,l,S^8192);a=(l|0)<(k|0)?k:l;break}a=(h|0)<0?6:h;if(s){s=(de[D>>2]|0)+-28|0;de[D>>2]=s;u=d*268435456.0}else{u=d;s=de[D>>2]|0}T=(s|0)<0?J:j;x=T;s=T;do{y=~~u>>>0;de[s>>2]=y;s=s+4|0;u=(u-+(y>>>0))*1.0e9}while(u!=0.0);l=s;s=de[D>>2]|0;if((s|0)>0){c=T;while(1){f=(s|0)>29?29:s;h=l+-4|0;do{if(h>>>0>>0)h=c;else{s=0;do{y=Qr(de[h>>2]|0,0,f|0)|0;y=$r(y|0,re|0,s|0,0)|0;s=re;F=li(y|0,s|0,1e9,0)|0;de[h>>2]=F;s=si(y|0,s|0,1e9,0)|0;h=h+-4|0}while(h>>>0>=c>>>0);if(!s){h=c;break}h=c+-4|0;de[h>>2]=s}}while(0);while(1){if(l>>>0<=h>>>0)break;s=l+-4|0;if(!(de[s>>2]|0))l=s;else break}s=(de[D>>2]|0)-f|0;de[D>>2]=s;if((s|0)>0)c=h;else break}}else h=T;if((s|0)<0){g=((a+25|0)/9|0)+1|0;v=(b|0)==102;m=h;while(1){_=0-s|0;_=(_|0)>9?9:_;do{if(m>>>0>>0){s=(1<<_)+-1|0;c=1e9>>>_;h=0;f=m;do{y=de[f>>2]|0;de[f>>2]=(y>>>_)+h;h=ve(y&s,c)|0;f=f+4|0}while(f>>>0>>0);s=(de[m>>2]|0)==0?m+4|0:m;if(!h){h=s;break}de[l>>2]=h;h=s;l=l+4|0}else h=(de[m>>2]|0)==0?m+4|0:m}while(0);s=v?T:h;l=(l-s>>2|0)>(g|0)?s+(g<<2)|0:l;s=(de[D>>2]|0)+_|0;de[D>>2]=s;if((s|0)>=0){m=h;break}else m=h}}else m=h;do{if(m>>>0>>0){s=(x-m>>2)*9|0;c=de[m>>2]|0;if(c>>>0<10)break;else h=10;do{h=h*10|0;s=s+1|0}while(c>>>0>=h>>>0)}else s=0}while(0);F=(b|0)==103;y=(a|0)!=0;h=a-((b|0)!=102?s:0)+((y&F)<<31>>31)|0;if((h|0)<(((l-x>>2)*9|0)+-9|0)){f=h+9216|0;v=(f|0)/9|0;h=T+(v+-1023<<2)|0;f=((f|0)%9|0)+1|0;if((f|0)<9){c=10;do{c=c*10|0;f=f+1|0}while((f|0)!=9)}else c=10;_=de[h>>2]|0;g=(_>>>0)%(c>>>0)|0;if((g|0)==0?(T+(v+-1022<<2)|0)==(l|0):0)c=m;else O=163;do{if((O|0)==163){O=0;d=(((_>>>0)/(c>>>0)|0)&1|0)==0?9007199254740992.0:9007199254740994.0;f=(c|0)/2|0;do{if(g>>>0>>0)u=.5;else{if((g|0)==(f|0)?(T+(v+-1022<<2)|0)==(l|0):0){u=1.0;break}u=1.5}}while(0);do{if(w){if((pe[E>>0]|0)!=45)break;d=-d;u=-u}}while(0);f=_-g|0;de[h>>2]=f;if(!(d+u!=d)){c=m;break}b=f+c|0;de[h>>2]=b;if(b>>>0>999999999){s=m;while(1){c=h+-4|0;de[h>>2]=0;if(c>>>0>>0){s=s+-4|0;de[s>>2]=0}b=(de[c>>2]|0)+1|0;de[c>>2]=b;if(b>>>0>999999999)h=c;else{m=s;h=c;break}}}s=(x-m>>2)*9|0;f=de[m>>2]|0;if(f>>>0<10){c=m;break}else c=10;do{c=c*10|0;s=s+1|0}while(f>>>0>=c>>>0);c=m}}while(0);b=h+4|0;m=c;l=l>>>0>b>>>0?b:l}g=0-s|0;while(1){if(l>>>0<=m>>>0){v=0;b=l;break}h=l+-4|0;if(!(de[h>>2]|0))l=h;else{v=1;b=l;break}}do{if(F){a=(y&1^1)+a|0;if((a|0)>(s|0)&(s|0)>-5){p=p+-1|0;a=a+-1-s|0}else{p=p+-2|0;a=a+-1|0}l=S&8;if(l)break;do{if(v){l=de[b+-4>>2]|0;if(!l){h=9;break}if(!((l>>>0)%10|0)){c=10;h=0}else{h=0;break}do{c=c*10|0;h=h+1|0}while(((l>>>0)%(c>>>0)|0|0)==0)}else h=9}while(0);l=((b-x>>2)*9|0)+-9|0;if((p|32|0)==102){l=l-h|0;l=(l|0)<0?0:l;a=(a|0)<(l|0)?a:l;l=0;break}else{l=l+s-h|0;l=(l|0)<0?0:l;a=(a|0)<(l|0)?a:l;l=0;break}}else l=S&8}while(0);_=a|l;c=(_|0)!=0&1;f=(p|32|0)==102;if(f){s=(s|0)>0?s:0;p=0}else{h=(s|0)<0?g:s;h=oe(h,((h|0)<0)<<31>>31,W)|0;if((C-h|0)<2)do{h=h+-1|0;pe[h>>0]=48}while((C-h|0)<2);pe[h+-1>>0]=(s>>31&2)+43;x=h+-2|0;pe[x>>0]=p;s=C-x|0;p=x}g=w+1+a+c+s|0;ae(e,32,k,g,S);if(!(de[e>>2]&32))ne(E,w,e)|0;ae(e,48,k,g,S^65536);do{if(f){h=m>>>0>T>>>0?T:m;s=h;do{l=oe(de[s>>2]|0,0,R)|0;do{if((s|0)==(h|0)){if((l|0)!=(R|0))break;pe[G>>0]=48;l=G}else{if(l>>>0<=I>>>0)break;do{l=l+-1|0;pe[l>>0]=48}while(l>>>0>I>>>0)}}while(0);if(!(de[e>>2]&32))ne(l,U-l|0,e)|0;s=s+4|0}while(s>>>0<=T>>>0);do{if(_){if(de[e>>2]&32)break;ne(5891,1,e)|0}}while(0);if((a|0)>0&s>>>0>>0){l=s;while(1){s=oe(de[l>>2]|0,0,R)|0;if(s>>>0>I>>>0)do{s=s+-1|0;pe[s>>0]=48}while(s>>>0>I>>>0);if(!(de[e>>2]&32))ne(s,(a|0)>9?9:a,e)|0;l=l+4|0;s=a+-9|0;if(!((a|0)>9&l>>>0>>0)){a=s;break}else a=s}}ae(e,48,a+9|0,9,0)}else{f=v?b:m+4|0;if((a|0)>-1){c=(l|0)==0;h=m;do{s=oe(de[h>>2]|0,0,R)|0;if((s|0)==(R|0)){pe[G>>0]=48;s=G}do{if((h|0)==(m|0)){l=s+1|0;if(!(de[e>>2]&32))ne(s,1,e)|0;if(c&(a|0)<1){s=l;break}if(de[e>>2]&32){s=l;break}ne(5891,1,e)|0;s=l}else{if(s>>>0<=I>>>0)break;do{s=s+-1|0;pe[s>>0]=48}while(s>>>0>I>>>0)}}while(0);l=U-s|0;if(!(de[e>>2]&32))ne(s,(a|0)>(l|0)?l:a,e)|0;a=a-l|0;h=h+4|0}while(h>>>0>>0&(a|0)>-1)}ae(e,48,a+18|0,18,0);if(de[e>>2]&32)break;ne(p,C-p|0,e)|0}}while(0);ae(e,32,k,g,S^8192);a=(g|0)<(k|0)?k:g}else{f=(p&32|0)!=0;c=u!=u|0.0!=0.0;s=c?0:w;h=s+3|0;ae(e,32,k,h,l);a=de[e>>2]|0;if(!(a&32)){ne(E,s,e)|0;a=de[e>>2]|0}if(!(a&32))ne(c?f?5883:5887:f?5875:5879,3,e)|0;ae(e,32,k,h,S^8192);a=(h|0)<(k|0)?k:h}}while(0);m=A;continue e}default:{l=S;s=h;f=0;p=5839;a=P}}}while(0);t:do{if((O|0)==64){l=M;s=de[l>>2]|0;l=de[l+4>>2]|0;c=p&32;if(!((s|0)==0&(l|0)==0)){a=P;do{a=a+-1|0;pe[a>>0]=me[5823+(s&15)>>0]|c;s=Zr(s|0,l|0,4)|0;l=re}while(!((s|0)==0&(l|0)==0));O=M;if((f&8|0)==0|(de[O>>2]|0)==0&(de[O+4>>2]|0)==0){s=f;f=0;c=5839;O=77}else{s=f;f=2;c=5839+(p>>4)|0;O=77}}else{a=P;s=f;f=0;c=5839;O=77}}else if((O|0)==76){a=oe(a,s,P)|0;s=S;f=l;O=77}else if((O|0)==82){O=0;S=Br(a,0,h)|0;E=(S|0)==0;m=a;s=E?h:S-a|0;f=0;p=5839;a=E?a+h|0:S}else if((O|0)==86){O=0;s=0;a=0;c=de[M>>2]|0;while(1){l=de[c>>2]|0;if(!l)break;a=Ar(Z,l)|0;if((a|0)<0|a>>>0>(h-s|0)>>>0)break;s=a+s|0;if(h>>>0>s>>>0)c=c+4|0;else break}if((a|0)<0){o=-1;break e}ae(e,32,k,s,S);if(!s){a=0;O=98}else{l=0;h=de[M>>2]|0;while(1){a=de[h>>2]|0;if(!a){a=s;O=98;break t}a=Ar(Z,a)|0;l=a+l|0;if((l|0)>(s|0)){a=s;O=98;break t}if(!(de[e>>2]&32))ne(Z,a,e)|0;if(l>>>0>=s>>>0){a=s;O=98;break}else h=h+4|0}}}}while(0);if((O|0)==98){O=0;ae(e,32,k,a,S^8192);m=A;a=(k|0)>(a|0)?k:a;continue}if((O|0)==77){O=0;l=(h|0)>-1?s&-65537:s;s=M;s=(de[s>>2]|0)!=0|(de[s+4>>2]|0)!=0;if((h|0)!=0|s){s=(s&1^1)+(X-a)|0;m=a;s=(h|0)>(s|0)?h:s;p=c;a=P}else{m=P;s=0;p=c;a=P}}c=a-m|0;s=(s|0)<(c|0)?c:s;h=f+s|0;a=(k|0)<(h|0)?h:k;ae(e,32,a,h,l);if(!(de[e>>2]&32))ne(p,f,e)|0;ae(e,48,a,h,l^65536);ae(e,48,s,c,0);if(!(de[e>>2]&32))ne(m,c,e)|0;ae(e,32,a,h,l^8192);m=A}e:do{if((O|0)==245)if(!e)if(t){o=1;while(1){t=de[n+(o<<2)>>2]|0;if(!t)break;Hr(i+(o<<3)|0,t,r);o=o+1|0;if((o|0)>=10){o=1;break e}}if((o|0)<10)while(1){if(de[n+(o<<2)>>2]|0){o=-1;break e}o=o+1|0;if((o|0)>=10){o=1;break}}else o=1}else o=0}while(0);ge=L;return o|0}function Gr(e){e=e|0;if(!(de[e+68>>2]|0))g(e);return}function Xr(e,t,r){e=e|0;t=t|0;r=r|0;var i=0,n=0;i=e+20|0;n=de[i>>2]|0;e=(de[e+16>>2]|0)-n|0;e=e>>>0>r>>>0?r:e;ei(n|0,t|0,e|0)|0;de[i>>2]=(de[i>>2]|0)+e;return r|0}function Hr(e,t,r){e=e|0;t=t|0;r=r|0;var i=0,n=0,o=0.0;e:do{if(t>>>0<=20)do{switch(t|0){case 9:{i=(de[r>>2]|0)+(4-1)&~(4-1);t=de[i>>2]|0;de[r>>2]=i+4;de[e>>2]=t;break e}case 10:{i=(de[r>>2]|0)+(4-1)&~(4-1);t=de[i>>2]|0;de[r>>2]=i+4;i=e;de[i>>2]=t;de[i+4>>2]=((t|0)<0)<<31>>31;break e}case 11:{i=(de[r>>2]|0)+(4-1)&~(4-1);t=de[i>>2]|0;de[r>>2]=i+4;i=e;de[i>>2]=t;de[i+4>>2]=0;break e}case 12:{i=(de[r>>2]|0)+(8-1)&~(8-1);t=i;n=de[t>>2]|0;t=de[t+4>>2]|0;de[r>>2]=i+8;i=e;de[i>>2]=n;de[i+4>>2]=t;break e}case 13:{n=(de[r>>2]|0)+(4-1)&~(4-1);i=de[n>>2]|0;de[r>>2]=n+4;i=(i&65535)<<16>>16;n=e;de[n>>2]=i;de[n+4>>2]=((i|0)<0)<<31>>31;break e}case 14:{n=(de[r>>2]|0)+(4-1)&~(4-1);i=de[n>>2]|0;de[r>>2]=n+4;n=e;de[n>>2]=i&65535;de[n+4>>2]=0;break e}case 15:{n=(de[r>>2]|0)+(4-1)&~(4-1);i=de[n>>2]|0;de[r>>2]=n+4;i=(i&255)<<24>>24;n=e;de[n>>2]=i;de[n+4>>2]=((i|0)<0)<<31>>31;break e}case 16:{n=(de[r>>2]|0)+(4-1)&~(4-1);i=de[n>>2]|0;de[r>>2]=n+4;n=e;de[n>>2]=i&255;de[n+4>>2]=0;break e}case 17:{n=(de[r>>2]|0)+(8-1)&~(8-1);o=+ee[n>>3];de[r>>2]=n+8;ee[e>>3]=o;break e}case 18:{n=(de[r>>2]|0)+(8-1)&~(8-1);o=+ee[n>>3];de[r>>2]=n+8;ee[e>>3]=o;break e}default:break e}}while(0)}while(0)}function oe(e,t,r){e=e|0;t=t|0;r=r|0;var i=0;if(t>>>0>0|(t|0)==0&e>>>0>4294967295)while(1){i=li(e|0,t|0,10,0)|0;r=r+-1|0;pe[r>>0]=i|48;i=si(e|0,t|0,10,0)|0;if(t>>>0>9|(t|0)==9&e>>>0>4294967295){e=i;t=re}else{e=i;break}}if(e)while(1){r=r+-1|0;pe[r>>0]=(e>>>0)%10|0|48;if(e>>>0<10)break;else e=(e>>>0)/10|0}return r|0}function ae(e,t,r,i,n){e=e|0;t=t|0;r=r|0;i=i|0;n=n|0;var o=0,a=0,s=0;s=ge;ge=ge+256|0;a=s;do{if((r|0)>(i|0)&(n&73728|0)==0){n=r-i|0;G(a|0,t|0,(n>>>0>256?256:n)|0)|0;t=de[e>>2]|0;o=(t&32|0)==0;if(n>>>0>255){i=r-i|0;do{if(o){ne(a,256,e)|0;t=de[e>>2]|0}n=n+-256|0;o=(t&32|0)==0}while(n>>>0>255);if(o)n=i&255;else break}else if(!o)break;ne(a,n,e)|0}}while(0);ge=s}function Yr(e){e=e|0;var t=0,r=0,i=0,n=0,o=0,a=0,s=0,l=0,u=0,h=0,c=0,f=0,p=0,d=0,m=0,_=0,g=0,v=0,y=0,b=0,x=0,T=0,w=0,E=0,S=0,A=0,k=0,F=0,N=0,O=0,P=0,R=0,C=0,M=0,I=0,D=0,L=0;do{if(e>>>0<245){p=e>>>0<11?16:e+11&-8;e=p>>>3;s=de[151]|0;r=s>>>e;if(r&3){e=(r&1^1)+e|0;i=e<<1;r=644+(i<<2)|0;i=644+(i+2<<2)|0;n=de[i>>2]|0;o=n+8|0;a=de[o>>2]|0;do{if((r|0)!=(a|0)){if(a>>>0<(de[155]|0)>>>0)B();t=a+12|0;if((de[t>>2]|0)==(n|0)){de[t>>2]=r;de[i>>2]=a;break}else B()}else de[151]=s&~(1<>2]=L|3;L=n+(L|4)|0;de[L>>2]=de[L>>2]|1;L=o;return L|0}a=de[153]|0;if(p>>>0>a>>>0){if(r){i=2<>>12&16;i=i>>>l;n=i>>>5&8;i=i>>>n;o=i>>>2&4;i=i>>>o;r=i>>>1&2;i=i>>>r;e=i>>>1&1;e=(n|l|o|r|e)+(i>>>e)|0;i=e<<1;r=644+(i<<2)|0;i=644+(i+2<<2)|0;o=de[i>>2]|0;l=o+8|0;n=de[l>>2]|0;do{if((r|0)!=(n|0)){if(n>>>0<(de[155]|0)>>>0)B();t=n+12|0;if((de[t>>2]|0)==(o|0)){de[t>>2]=r;de[i>>2]=n;u=de[153]|0;break}else B()}else{de[151]=s&~(1<>2]=p|3;s=o+p|0;de[o+(p|4)>>2]=a|1;de[o+L>>2]=a;if(u){n=de[156]|0;r=u>>>3;t=r<<1;i=644+(t<<2)|0;e=de[151]|0;r=1<>2]|0;if(t>>>0<(de[155]|0)>>>0)B();else{h=e;c=t}}else{de[151]=e|r;h=644+(t+2<<2)|0;c=i}de[h>>2]=n;de[c+12>>2]=n;de[n+8>>2]=c;de[n+12>>2]=i}de[153]=a;de[156]=s;L=l;return L|0}e=de[152]|0;if(e){r=(e&0-e)+-1|0;D=r>>>12&16;r=r>>>D;I=r>>>5&8;r=r>>>I;L=r>>>2&4;r=r>>>L;e=r>>>1&2;r=r>>>e;i=r>>>1&1;i=de[908+((I|D|L|e|i)+(r>>>i)<<2)>>2]|0;r=(de[i+4>>2]&-8)-p|0;e=i;while(1){t=de[e+16>>2]|0;if(!t){t=de[e+20>>2]|0;if(!t){l=r;break}}e=(de[t+4>>2]&-8)-p|0;L=e>>>0>>0;r=L?e:r;e=t;i=L?t:i}o=de[155]|0;if(i>>>0>>0)B();s=i+p|0;if(i>>>0>=s>>>0)B();a=de[i+24>>2]|0;r=de[i+12>>2]|0;do{if((r|0)==(i|0)){e=i+20|0;t=de[e>>2]|0;if(!t){e=i+16|0;t=de[e>>2]|0;if(!t){f=0;break}}while(1){r=t+20|0;n=de[r>>2]|0;if(n){t=n;e=r;continue}r=t+16|0;n=de[r>>2]|0;if(!n)break;else{t=n;e=r}}if(e>>>0>>0)B();else{de[e>>2]=0;f=t;break}}else{n=de[i+8>>2]|0;if(n>>>0>>0)B();t=n+12|0;if((de[t>>2]|0)!=(i|0))B();e=r+8|0;if((de[e>>2]|0)==(i|0)){de[t>>2]=r;de[e>>2]=n;f=r;break}else B()}}while(0);do{if(a){t=de[i+28>>2]|0;e=908+(t<<2)|0;if((i|0)==(de[e>>2]|0)){de[e>>2]=f;if(!f){de[152]=de[152]&~(1<>>0<(de[155]|0)>>>0)B();t=a+16|0;if((de[t>>2]|0)==(i|0))de[t>>2]=f;else de[a+20>>2]=f;if(!f)break}e=de[155]|0;if(f>>>0>>0)B();de[f+24>>2]=a;t=de[i+16>>2]|0;do{if(t)if(t>>>0>>0)B();else{de[f+16>>2]=t;de[t+24>>2]=f;break}}while(0);t=de[i+20>>2]|0;if(t)if(t>>>0<(de[155]|0)>>>0)B();else{de[f+20>>2]=t;de[t+24>>2]=f;break}}}while(0);if(l>>>0<16){L=l+p|0;de[i+4>>2]=L|3;L=i+(L+4)|0;de[L>>2]=de[L>>2]|1}else{de[i+4>>2]=p|3;de[i+(p|4)>>2]=l|1;de[i+(l+p)>>2]=l;t=de[153]|0;if(t){o=de[156]|0;r=t>>>3;t=r<<1;n=644+(t<<2)|0;e=de[151]|0;r=1<>2]|0;if(e>>>0<(de[155]|0)>>>0)B();else{d=t;m=e}}else{de[151]=e|r;d=644+(t+2<<2)|0;m=n}de[d>>2]=o;de[m+12>>2]=o;de[o+8>>2]=m;de[o+12>>2]=n}de[153]=l;de[156]=s}L=i+8|0;return L|0}else m=p}else m=p}else if(e>>>0<=4294967231){e=e+11|0;c=e&-8;h=de[152]|0;if(h){r=0-c|0;e=e>>>8;if(e)if(c>>>0>16777215)u=31;else{m=(e+1048320|0)>>>16&8;b=e<>>16&4;b=b<>>16&2;u=14-(d|m|u)+(b<>>15)|0;u=c>>>(u+7|0)&1|u<<1}else u=0;e=de[908+(u<<2)>>2]|0;e:do{if(!e){n=0;e=0;b=86}else{a=r;n=0;s=c<<((u|0)==31?0:25-(u>>>1)|0);l=e;e=0;while(1){o=de[l+4>>2]&-8;r=o-c|0;if(r>>>0>>0)if((o|0)==(c|0)){o=l;e=l;b=90;break e}else e=l;else r=a;b=de[l+20>>2]|0;l=de[l+16+(s>>>31<<2)>>2]|0;n=(b|0)==0|(b|0)==(l|0)?n:b;if(!l){b=86;break}else{a=r;s=s<<1}}}}while(0);if((b|0)==86){if((n|0)==0&(e|0)==0){e=2<>>12&16;e=e>>>f;h=e>>>5&8;e=e>>>h;d=e>>>2&4;e=e>>>d;m=e>>>1&2;e=e>>>m;n=e>>>1&1;n=de[908+((h|f|d|m|n)+(e>>>n)<<2)>>2]|0;e=0}if(!n){s=r;l=e}else{o=n;b=90}}if((b|0)==90)while(1){b=0;m=(de[o+4>>2]&-8)-c|0;n=m>>>0>>0;r=n?m:r;e=n?o:e;n=de[o+16>>2]|0;if(n){o=n;b=90;continue}o=de[o+20>>2]|0;if(!o){s=r;l=e;break}else b=90}if((l|0)!=0?s>>>0<((de[153]|0)-c|0)>>>0:0){n=de[155]|0;if(l>>>0>>0)B();a=l+c|0;if(l>>>0>=a>>>0)B();o=de[l+24>>2]|0;r=de[l+12>>2]|0;do{if((r|0)==(l|0)){e=l+20|0;t=de[e>>2]|0;if(!t){e=l+16|0;t=de[e>>2]|0;if(!t){p=0;break}}while(1){r=t+20|0;i=de[r>>2]|0;if(i){t=i;e=r;continue}r=t+16|0;i=de[r>>2]|0;if(!i)break;else{t=i;e=r}}if(e>>>0>>0)B();else{de[e>>2]=0;p=t;break}}else{i=de[l+8>>2]|0;if(i>>>0>>0)B();t=i+12|0;if((de[t>>2]|0)!=(l|0))B();e=r+8|0;if((de[e>>2]|0)==(l|0)){de[t>>2]=r;de[e>>2]=i;p=r;break}else B()}}while(0);do{if(o){t=de[l+28>>2]|0;e=908+(t<<2)|0;if((l|0)==(de[e>>2]|0)){de[e>>2]=p;if(!p){de[152]=de[152]&~(1<>>0<(de[155]|0)>>>0)B();t=o+16|0;if((de[t>>2]|0)==(l|0))de[t>>2]=p;else de[o+20>>2]=p;if(!p)break}e=de[155]|0;if(p>>>0>>0)B();de[p+24>>2]=o;t=de[l+16>>2]|0;do{if(t)if(t>>>0>>0)B();else{de[p+16>>2]=t;de[t+24>>2]=p;break}}while(0);t=de[l+20>>2]|0;if(t)if(t>>>0<(de[155]|0)>>>0)B();else{de[p+20>>2]=t;de[t+24>>2]=p;break}}}while(0);e:do{if(s>>>0>=16){de[l+4>>2]=c|3;de[l+(c|4)>>2]=s|1;de[l+(s+c)>>2]=s;t=s>>>3;if(s>>>0<256){e=t<<1;i=644+(e<<2)|0;r=de[151]|0;t=1<>2]|0;if(e>>>0<(de[155]|0)>>>0)B();else{g=t;v=e}}else{de[151]=r|t;g=644+(e+2<<2)|0;v=i}de[g>>2]=a;de[v+12>>2]=a;de[l+(c+8)>>2]=v;de[l+(c+12)>>2]=i;break}t=s>>>8;if(t)if(s>>>0>16777215)i=31;else{D=(t+1048320|0)>>>16&8;L=t<>>16&4;L=L<>>16&2;i=14-(I|D|i)+(L<>>15)|0;i=s>>>(i+7|0)&1|i<<1}else i=0;t=908+(i<<2)|0;de[l+(c+28)>>2]=i;de[l+(c+20)>>2]=0;de[l+(c+16)>>2]=0;e=de[152]|0;r=1<>2]=a;de[l+(c+24)>>2]=t;de[l+(c+12)>>2]=a;de[l+(c+8)>>2]=a;break}t=de[t>>2]|0;t:do{if((de[t+4>>2]&-8|0)!=(s|0)){i=s<<((i|0)==31?0:25-(i>>>1)|0);while(1){e=t+16+(i>>>31<<2)|0;r=de[e>>2]|0;if(!r)break;if((de[r+4>>2]&-8|0)==(s|0)){w=r;break t}else{i=i<<1;t=r}}if(e>>>0<(de[155]|0)>>>0)B();else{de[e>>2]=a;de[l+(c+24)>>2]=t;de[l+(c+12)>>2]=a;de[l+(c+8)>>2]=a;break e}}else w=t}while(0);t=w+8|0;e=de[t>>2]|0;L=de[155]|0;if(e>>>0>=L>>>0&w>>>0>=L>>>0){de[e+12>>2]=a;de[t>>2]=a;de[l+(c+8)>>2]=e;de[l+(c+12)>>2]=w;de[l+(c+24)>>2]=0;break}else B()}else{L=s+c|0;de[l+4>>2]=L|3;L=l+(L+4)|0;de[L>>2]=de[L>>2]|1}}while(0);L=l+8|0;return L|0}else m=c}else m=c}else m=-1}while(0);r=de[153]|0;if(r>>>0>=m>>>0){t=r-m|0;e=de[156]|0;if(t>>>0>15){de[156]=e+m;de[153]=t;de[e+(m+4)>>2]=t|1;de[e+r>>2]=t;de[e+4>>2]=m|3}else{de[153]=0;de[156]=0;de[e+4>>2]=r|3;L=e+(r+4)|0;de[L>>2]=de[L>>2]|1}L=e+8|0;return L|0}e=de[154]|0;if(e>>>0>m>>>0){D=e-m|0;de[154]=D;L=de[157]|0;de[157]=L+m;de[L+(m+4)>>2]=D|1;de[L+4>>2]=m|3;L=L+8|0;return L|0}do{if(!(de[269]|0)){e=$e(30)|0;if(!(e+-1&e)){de[271]=e;de[270]=e;de[272]=-1;de[273]=-1;de[274]=0;de[262]=0;w=(ut(0)|0)&-16^1431655768;de[269]=w;break}else B()}}while(0);l=m+48|0;s=de[271]|0;u=m+47|0;a=s+u|0;s=0-s|0;h=a&s;if(h>>>0<=m>>>0){L=0;return L|0}e=de[261]|0;if((e|0)!=0?(v=de[259]|0,w=v+h|0,w>>>0<=v>>>0|w>>>0>e>>>0):0){L=0;return L|0}e:do{if(!(de[262]&4)){e=de[157]|0;t:do{if(e){n=1052;while(1){r=de[n>>2]|0;if(r>>>0<=e>>>0?(_=n+4|0,(r+(de[_>>2]|0)|0)>>>0>e>>>0):0){o=n;e=_;break}n=de[n+8>>2]|0;if(!n){b=174;break t}}r=a-(de[154]|0)&s;if(r>>>0<2147483647){n=z(r|0)|0;w=(n|0)==((de[o>>2]|0)+(de[e>>2]|0)|0);e=w?r:0;if(w){if((n|0)!=(-1|0)){x=n;d=e;b=194;break e}}else b=184}else e=0}else b=174}while(0);do{if((b|0)==174){o=z(0)|0;if((o|0)!=(-1|0)){e=o;r=de[270]|0;n=r+-1|0;if(!(n&e))r=h;else r=h-e+(n+e&0-r)|0;e=de[259]|0;n=e+r|0;if(r>>>0>m>>>0&r>>>0<2147483647){w=de[261]|0;if((w|0)!=0?n>>>0<=e>>>0|n>>>0>w>>>0:0){e=0;break}n=z(r|0)|0;w=(n|0)==(o|0);e=w?r:0;if(w){x=o;d=e;b=194;break e}else b=184}else e=0}else e=0}}while(0);t:do{if((b|0)==184){o=0-r|0;do{if(l>>>0>r>>>0&(r>>>0<2147483647&(n|0)!=(-1|0))?(y=de[271]|0,y=u-r+y&0-y,y>>>0<2147483647):0)if((z(y|0)|0)==(-1|0)){z(o|0)|0;break t}else{r=y+r|0;break}}while(0);if((n|0)!=(-1|0)){x=n;d=r;b=194;break e}}}while(0);de[262]=de[262]|4;b=191}else{e=0;b=191}}while(0);if((((b|0)==191?h>>>0<2147483647:0)?(x=z(h|0)|0,T=z(0)|0,x>>>0>>0&((x|0)!=(-1|0)&(T|0)!=(-1|0))):0)?(E=T-x|0,S=E>>>0>(m+40|0)>>>0,S):0){d=S?E:e;b=194}if((b|0)==194){e=(de[259]|0)+d|0;de[259]=e;if(e>>>0>(de[260]|0)>>>0)de[260]=e;a=de[157]|0;e:do{if(a){o=1052;do{e=de[o>>2]|0;r=o+4|0;n=de[r>>2]|0;if((x|0)==(e+n|0)){A=e;k=r;F=n;N=o;b=204;break}o=de[o+8>>2]|0}while((o|0)!=0);if(((b|0)==204?(de[N+12>>2]&8|0)==0:0)?a>>>0>>0&a>>>0>=A>>>0:0){de[k>>2]=F+d;L=(de[154]|0)+d|0;D=a+8|0;D=(D&7|0)==0?0:0-D&7;I=L-D|0;de[157]=a+D;de[154]=I;de[a+(D+4)>>2]=I|1;de[a+(L+4)>>2]=40;de[158]=de[273];break}e=de[155]|0;if(x>>>0>>0){de[155]=x;e=x}r=x+d|0;o=1052;while(1){if((de[o>>2]|0)==(r|0)){n=o;r=o;b=212;break}o=de[o+8>>2]|0;if(!o){r=1052;break}}if((b|0)==212)if(!(de[r+12>>2]&8)){de[n>>2]=x;f=r+4|0;de[f>>2]=(de[f>>2]|0)+d;f=x+8|0;f=(f&7|0)==0?0:0-f&7;u=x+(d+8)|0;u=(u&7|0)==0?0:0-u&7;t=x+(u+d)|0;c=f+m|0;p=x+c|0;h=t-(x+f)-m|0;de[x+(f+4)>>2]=m|3;t:do{if((t|0)!=(a|0)){if((t|0)==(de[156]|0)){L=(de[153]|0)+h|0;de[153]=L;de[156]=p;de[x+(c+4)>>2]=L|1;de[x+(L+c)>>2]=L;break}s=d+4|0;r=de[x+(s+u)>>2]|0;if((r&3|0)==1){l=r&-8;o=r>>>3;r:do{if(r>>>0>=256){a=de[x+((u|24)+d)>>2]|0;i=de[x+(d+12+u)>>2]|0;do{if((i|0)==(t|0)){n=u|16;i=x+(s+n)|0;r=de[i>>2]|0;if(!r){i=x+(n+d)|0;r=de[i>>2]|0;if(!r){M=0;break}}while(1){n=r+20|0;o=de[n>>2]|0;if(o){r=o;i=n;continue}n=r+16|0;o=de[n>>2]|0;if(!o)break;else{r=o;i=n}}if(i>>>0>>0)B();else{de[i>>2]=0;M=r;break}}else{n=de[x+((u|8)+d)>>2]|0;if(n>>>0>>0)B();e=n+12|0;if((de[e>>2]|0)!=(t|0))B();r=i+8|0;if((de[r>>2]|0)==(t|0)){de[e>>2]=i;de[r>>2]=n;M=i;break}else B()}}while(0);if(!a)break;e=de[x+(d+28+u)>>2]|0;r=908+(e<<2)|0;do{if((t|0)!=(de[r>>2]|0)){if(a>>>0<(de[155]|0)>>>0)B();e=a+16|0;if((de[e>>2]|0)==(t|0))de[e>>2]=M;else de[a+20>>2]=M;if(!M)break r}else{de[r>>2]=M;if(M)break;de[152]=de[152]&~(1<>>0>>0)B();de[M+24>>2]=a;t=u|16;e=de[x+(t+d)>>2]|0;do{if(e)if(e>>>0>>0)B();else{de[M+16>>2]=e;de[e+24>>2]=M;break}}while(0);t=de[x+(s+t)>>2]|0;if(!t)break;if(t>>>0<(de[155]|0)>>>0)B();else{de[M+20>>2]=t;de[t+24>>2]=M;break}}else{i=de[x+((u|8)+d)>>2]|0;n=de[x+(d+12+u)>>2]|0;r=644+(o<<1<<2)|0;do{if((i|0)!=(r|0)){if(i>>>0>>0)B();if((de[i+12>>2]|0)==(t|0))break;B()}}while(0);if((n|0)==(i|0)){de[151]=de[151]&~(1<>>0>>0)B();e=n+8|0;if((de[e>>2]|0)==(t|0)){O=e;break}B()}}while(0);de[i+12>>2]=n;de[O>>2]=i}}while(0);t=x+((l|u)+d)|0;n=l+h|0}else n=h;t=t+4|0;de[t>>2]=de[t>>2]&-2;de[x+(c+4)>>2]=n|1;de[x+(n+c)>>2]=n;t=n>>>3;if(n>>>0<256){e=t<<1;i=644+(e<<2)|0;r=de[151]|0;t=1<>2]|0;if(e>>>0>=(de[155]|0)>>>0){I=t;D=e;break}B()}}while(0);de[I>>2]=p;de[D+12>>2]=p;de[x+(c+8)>>2]=D;de[x+(c+12)>>2]=i;break}t=n>>>8;do{if(!t)i=0;else{if(n>>>0>16777215){i=31;break}I=(t+1048320|0)>>>16&8;D=t<>>16&4;D=D<>>16&2;i=14-(M|I|i)+(D<>>15)|0;i=n>>>(i+7|0)&1|i<<1}}while(0);t=908+(i<<2)|0;de[x+(c+28)>>2]=i;de[x+(c+20)>>2]=0;de[x+(c+16)>>2]=0;e=de[152]|0;r=1<>2]=p;de[x+(c+24)>>2]=t;de[x+(c+12)>>2]=p;de[x+(c+8)>>2]=p;break}t=de[t>>2]|0;r:do{if((de[t+4>>2]&-8|0)!=(n|0)){i=n<<((i|0)==31?0:25-(i>>>1)|0);while(1){e=t+16+(i>>>31<<2)|0;r=de[e>>2]|0;if(!r)break;if((de[r+4>>2]&-8|0)==(n|0)){L=r;break r}else{i=i<<1;t=r}}if(e>>>0<(de[155]|0)>>>0)B();else{de[e>>2]=p;de[x+(c+24)>>2]=t;de[x+(c+12)>>2]=p;de[x+(c+8)>>2]=p;break t}}else L=t}while(0);t=L+8|0;e=de[t>>2]|0;D=de[155]|0;if(e>>>0>=D>>>0&L>>>0>=D>>>0){de[e+12>>2]=p;de[t>>2]=p;de[x+(c+8)>>2]=e;de[x+(c+12)>>2]=L;de[x+(c+24)>>2]=0;break}else B()}else{L=(de[154]|0)+h|0;de[154]=L;de[157]=p;de[x+(c+4)>>2]=L|1}}while(0);L=x+(f|8)|0;return L|0}else r=1052;while(1){e=de[r>>2]|0;if(e>>>0<=a>>>0?(t=de[r+4>>2]|0,i=e+t|0,i>>>0>a>>>0):0)break;r=de[r+8>>2]|0}n=e+(t+-39)|0;e=e+(t+-47+((n&7|0)==0?0:0-n&7))|0;n=a+16|0;e=e>>>0>>0?a:e;t=e+8|0;r=x+8|0;r=(r&7|0)==0?0:0-r&7;L=d+-40-r|0;de[157]=x+r;de[154]=L;de[x+(r+4)>>2]=L|1;de[x+(d+-36)>>2]=40;de[158]=de[273];r=e+4|0;de[r>>2]=27;de[t>>2]=de[263];de[t+4>>2]=de[264];de[t+8>>2]=de[265];de[t+12>>2]=de[266];de[263]=x;de[264]=d;de[266]=0;de[265]=t;t=e+28|0;de[t>>2]=7;if((e+32|0)>>>0>>0)do{L=t;t=t+4|0;de[t>>2]=7}while((L+8|0)>>>0>>0);if((e|0)!=(a|0)){o=e-a|0;de[r>>2]=de[r>>2]&-2;de[a+4>>2]=o|1;de[e>>2]=o;t=o>>>3;if(o>>>0<256){e=t<<1;i=644+(e<<2)|0;r=de[151]|0;t=1<>2]|0;if(e>>>0<(de[155]|0)>>>0)B();else{P=t;R=e}}else{de[151]=r|t;P=644+(e+2<<2)|0;R=i}de[P>>2]=a;de[R+12>>2]=a;de[a+8>>2]=R;de[a+12>>2]=i;break}t=o>>>8;if(t)if(o>>>0>16777215)i=31;else{D=(t+1048320|0)>>>16&8;L=t<>>16&4;L=L<>>16&2;i=14-(I|D|i)+(L<>>15)|0;i=o>>>(i+7|0)&1|i<<1}else i=0;r=908+(i<<2)|0;de[a+28>>2]=i;de[a+20>>2]=0;de[n>>2]=0;t=de[152]|0;e=1<>2]=a;de[a+24>>2]=r;de[a+12>>2]=a;de[a+8>>2]=a;break}t=de[r>>2]|0;t:do{if((de[t+4>>2]&-8|0)!=(o|0)){i=o<<((i|0)==31?0:25-(i>>>1)|0);while(1){e=t+16+(i>>>31<<2)|0;r=de[e>>2]|0;if(!r)break;if((de[r+4>>2]&-8|0)==(o|0)){C=r;break t}else{i=i<<1;t=r}}if(e>>>0<(de[155]|0)>>>0)B();else{de[e>>2]=a;de[a+24>>2]=t;de[a+12>>2]=a;de[a+8>>2]=a;break e}}else C=t}while(0);t=C+8|0;e=de[t>>2]|0;L=de[155]|0;if(e>>>0>=L>>>0&C>>>0>=L>>>0){de[e+12>>2]=a;de[t>>2]=a;de[a+8>>2]=e;de[a+12>>2]=C;de[a+24>>2]=0;break}else B()}}else{L=de[155]|0;if((L|0)==0|x>>>0>>0)de[155]=x;de[263]=x;de[264]=d;de[266]=0;de[160]=de[269];de[159]=-1;t=0;do{L=t<<1;D=644+(L<<2)|0;de[644+(L+3<<2)>>2]=D;de[644+(L+2<<2)>>2]=D;t=t+1|0}while((t|0)!=32);L=x+8|0;L=(L&7|0)==0?0:0-L&7;D=d+-40-L|0;de[157]=x+L;de[154]=D;de[x+(L+4)>>2]=D|1;de[x+(d+-36)>>2]=40;de[158]=de[273]}}while(0);t=de[154]|0;if(t>>>0>m>>>0){D=t-m|0;de[154]=D;L=de[157]|0;de[157]=L+m;de[L+(m+4)>>2]=D|1;de[L+4>>2]=m|3;L=L+8|0;return L|0}}L=ie()|0;de[L>>2]=12;L=0;return L|0}function b(e){e=e|0;var t=0,r=0,i=0,n=0,o=0,a=0,s=0,l=0,u=0,h=0,c=0,f=0,p=0,d=0,m=0,_=0,g=0,v=0,y=0;if(!e)return;t=e+-8|0;s=de[155]|0;if(t>>>0>>0)B();r=de[e+-4>>2]|0;i=r&3;if((i|0)==1)B();p=r&-8;m=e+(p+-8)|0;do{if(!(r&1)){t=de[t>>2]|0;if(!i)return;l=-8-t|0;h=e+l|0;c=t+p|0;if(h>>>0>>0)B();if((h|0)==(de[156]|0)){t=e+(p+-4)|0;r=de[t>>2]|0;if((r&3|0)!=3){y=h;o=c;break}de[153]=c;de[t>>2]=r&-2;de[e+(l+4)>>2]=c|1;de[m>>2]=c;return}n=t>>>3;if(t>>>0<256){i=de[e+(l+8)>>2]|0;r=de[e+(l+12)>>2]|0;t=644+(n<<1<<2)|0;if((i|0)!=(t|0)){if(i>>>0>>0)B();if((de[i+12>>2]|0)!=(h|0))B()}if((r|0)==(i|0)){de[151]=de[151]&~(1<>>0>>0)B();t=r+8|0;if((de[t>>2]|0)==(h|0))a=t;else B()}else a=r+8|0;de[i+12>>2]=r;de[a>>2]=i;y=h;o=c;break}a=de[e+(l+24)>>2]|0;i=de[e+(l+12)>>2]|0;do{if((i|0)==(h|0)){r=e+(l+20)|0;t=de[r>>2]|0;if(!t){r=e+(l+16)|0;t=de[r>>2]|0;if(!t){u=0;break}}while(1){i=t+20|0;n=de[i>>2]|0;if(n){t=n;r=i;continue}i=t+16|0;n=de[i>>2]|0;if(!n)break;else{t=n;r=i}}if(r>>>0>>0)B();else{de[r>>2]=0;u=t;break}}else{n=de[e+(l+8)>>2]|0;if(n>>>0>>0)B();t=n+12|0;if((de[t>>2]|0)!=(h|0))B();r=i+8|0;if((de[r>>2]|0)==(h|0)){de[t>>2]=i;de[r>>2]=n;u=i;break}else B()}}while(0);if(a){t=de[e+(l+28)>>2]|0;r=908+(t<<2)|0;if((h|0)==(de[r>>2]|0)){de[r>>2]=u;if(!u){de[152]=de[152]&~(1<>>0<(de[155]|0)>>>0)B();t=a+16|0;if((de[t>>2]|0)==(h|0))de[t>>2]=u;else de[a+20>>2]=u;if(!u){y=h;o=c;break}}r=de[155]|0;if(u>>>0>>0)B();de[u+24>>2]=a;t=de[e+(l+16)>>2]|0;do{if(t)if(t>>>0>>0)B();else{de[u+16>>2]=t;de[t+24>>2]=u;break}}while(0);t=de[e+(l+20)>>2]|0;if(t)if(t>>>0<(de[155]|0)>>>0)B();else{de[u+20>>2]=t;de[t+24>>2]=u;y=h;o=c;break}else{y=h;o=c}}else{y=h;o=c}}else{y=t;o=p}}while(0);if(y>>>0>=m>>>0)B();t=e+(p+-4)|0;r=de[t>>2]|0;if(!(r&1))B();if(!(r&2)){if((m|0)==(de[157]|0)){v=(de[154]|0)+o|0;de[154]=v;de[157]=y;de[y+4>>2]=v|1;if((y|0)!=(de[156]|0))return;de[156]=0;de[153]=0;return}if((m|0)==(de[156]|0)){v=(de[153]|0)+o|0;de[153]=v;de[156]=y;de[y+4>>2]=v|1;de[y+v>>2]=v;return}o=(r&-8)+o|0;n=r>>>3;do{if(r>>>0>=256){a=de[e+(p+16)>>2]|0;t=de[e+(p|4)>>2]|0;do{if((t|0)==(m|0)){r=e+(p+12)|0;t=de[r>>2]|0;if(!t){r=e+(p+8)|0;t=de[r>>2]|0;if(!t){d=0;break}}while(1){i=t+20|0;n=de[i>>2]|0;if(n){t=n;r=i;continue}i=t+16|0;n=de[i>>2]|0;if(!n)break;else{t=n;r=i}}if(r>>>0<(de[155]|0)>>>0)B();else{de[r>>2]=0;d=t;break}}else{r=de[e+p>>2]|0;if(r>>>0<(de[155]|0)>>>0)B();i=r+12|0;if((de[i>>2]|0)!=(m|0))B();n=t+8|0;if((de[n>>2]|0)==(m|0)){de[i>>2]=t;de[n>>2]=r;d=t;break}else B()}}while(0);if(a){t=de[e+(p+20)>>2]|0;r=908+(t<<2)|0;if((m|0)==(de[r>>2]|0)){de[r>>2]=d;if(!d){de[152]=de[152]&~(1<>>0<(de[155]|0)>>>0)B();t=a+16|0;if((de[t>>2]|0)==(m|0))de[t>>2]=d;else de[a+20>>2]=d;if(!d)break}r=de[155]|0;if(d>>>0>>0)B();de[d+24>>2]=a;t=de[e+(p+8)>>2]|0;do{if(t)if(t>>>0>>0)B();else{de[d+16>>2]=t;de[t+24>>2]=d;break}}while(0);t=de[e+(p+12)>>2]|0;if(t)if(t>>>0<(de[155]|0)>>>0)B();else{de[d+20>>2]=t;de[t+24>>2]=d;break}}}else{i=de[e+p>>2]|0;r=de[e+(p|4)>>2]|0;t=644+(n<<1<<2)|0;if((i|0)!=(t|0)){if(i>>>0<(de[155]|0)>>>0)B();if((de[i+12>>2]|0)!=(m|0))B()}if((r|0)==(i|0)){de[151]=de[151]&~(1<>>0<(de[155]|0)>>>0)B();t=r+8|0;if((de[t>>2]|0)==(m|0))f=t;else B()}else f=r+8|0;de[i+12>>2]=r;de[f>>2]=i}}while(0);de[y+4>>2]=o|1;de[y+o>>2]=o;if((y|0)==(de[156]|0)){de[153]=o;return}}else{de[t>>2]=r&-2;de[y+4>>2]=o|1;de[y+o>>2]=o}t=o>>>3;if(o>>>0<256){r=t<<1;n=644+(r<<2)|0;i=de[151]|0;t=1<>2]|0;if(r>>>0<(de[155]|0)>>>0)B();else{_=t;g=r}}else{de[151]=i|t;_=644+(r+2<<2)|0;g=n}de[_>>2]=y;de[g+12>>2]=y;de[y+8>>2]=g;de[y+12>>2]=n;return}t=o>>>8;if(t)if(o>>>0>16777215)n=31;else{_=(t+1048320|0)>>>16&8;g=t<<_;m=(g+520192|0)>>>16&4;g=g<>>16&2;n=14-(m|_|n)+(g<>>15)|0;n=o>>>(n+7|0)&1|n<<1}else n=0;t=908+(n<<2)|0;de[y+28>>2]=n;de[y+20>>2]=0;de[y+16>>2]=0;r=de[152]|0;i=1<>2]|0;t:do{if((de[t+4>>2]&-8|0)!=(o|0)){n=o<<((n|0)==31?0:25-(n>>>1)|0);while(1){r=t+16+(n>>>31<<2)|0;i=de[r>>2]|0;if(!i)break;if((de[i+4>>2]&-8|0)==(o|0)){v=i;break t}else{n=n<<1;t=i}}if(r>>>0<(de[155]|0)>>>0)B();else{de[r>>2]=y;de[y+24>>2]=t;de[y+12>>2]=y;de[y+8>>2]=y;break e}}else v=t}while(0);t=v+8|0;r=de[t>>2]|0;g=de[155]|0;if(r>>>0>=g>>>0&v>>>0>=g>>>0){de[r+12>>2]=y;de[t>>2]=y;de[y+8>>2]=r;de[y+12>>2]=v;de[y+24>>2]=0;break}else B()}else{de[152]=r|i;de[t>>2]=y;de[y+24>>2]=t;de[y+12>>2]=y;de[y+8>>2]=y}}while(0);y=(de[159]|0)+-1|0;de[159]=y;if(!y)t=1060;else return;while(1){t=de[t>>2]|0;if(!t)break;else t=t+8|0}de[159]=-1;return}function Wr(e,t){e=e|0;t=t|0;var r=0,i=0;if(!e){e=Yr(t)|0;return e|0}if(t>>>0>4294967231){e=ie()|0;de[e>>2]=12;e=0;return e|0}r=Vr(e+-8|0,t>>>0<11?16:t+11&-8)|0;if(r){e=r+8|0;return e|0}r=Yr(t)|0;if(!r){e=0;return e|0}i=de[e+-4>>2]|0;i=(i&-8)-((i&3|0)==0?8:4)|0;ei(r|0,e|0,(i>>>0>>0?i:t)|0)|0;b(e);e=r;return e|0}function qr(e){e=e|0;var t=0;if(!e){t=0;return t|0}e=de[e+-4>>2]|0;t=e&3;if((t|0)==1){t=0;return t|0}t=(e&-8)-((t|0)==0?8:4)|0;return t|0}function Vr(e,t){e=e|0;t=t|0;var r=0,i=0,n=0,o=0,a=0,s=0,l=0,u=0,h=0,c=0,f=0,p=0,d=0;p=e+4|0;d=de[p>>2]|0;l=d&-8;h=e+l|0;s=de[155]|0;r=d&3;if(!((r|0)!=1&e>>>0>=s>>>0&e>>>0>>0))B();i=e+(l|4)|0;n=de[i>>2]|0;if(!(n&1))B();if(!r){if(t>>>0<256){e=0;return e|0}if(l>>>0>=(t+4|0)>>>0?(l-t|0)>>>0<=de[271]<<1>>>0:0)return e|0;e=0;return e|0}if(l>>>0>=t>>>0){r=l-t|0;if(r>>>0<=15)return e|0;de[p>>2]=d&1|t|2;de[e+(t+4)>>2]=r|3;de[i>>2]=de[i>>2]|1;Kr(e+t|0,r);return e|0}if((h|0)==(de[157]|0)){r=(de[154]|0)+l|0;if(r>>>0<=t>>>0){e=0;return e|0}f=r-t|0;de[p>>2]=d&1|t|2;de[e+(t+4)>>2]=f|1;de[157]=e+t;de[154]=f;return e|0}if((h|0)==(de[156]|0)){i=(de[153]|0)+l|0;if(i>>>0>>0){e=0;return e|0}r=i-t|0;if(r>>>0>15){de[p>>2]=d&1|t|2;de[e+(t+4)>>2]=r|1;de[e+i>>2]=r;i=e+(i+4)|0;de[i>>2]=de[i>>2]&-2;i=e+t|0}else{de[p>>2]=d&1|i|2;i=e+(i+4)|0;de[i>>2]=de[i>>2]|1;i=0;r=0}de[153]=r;de[156]=i;return e|0}if(n&2){e=0;return e|0}c=(n&-8)+l|0;if(c>>>0>>0){e=0;return e|0}f=c-t|0;o=n>>>3;do{if(n>>>0>=256){a=de[e+(l+24)>>2]|0;o=de[e+(l+12)>>2]|0;do{if((o|0)==(h|0)){i=e+(l+20)|0;r=de[i>>2]|0;if(!r){i=e+(l+16)|0;r=de[i>>2]|0;if(!r){u=0;break}}while(1){n=r+20|0;o=de[n>>2]|0;if(o){r=o;i=n;continue}n=r+16|0;o=de[n>>2]|0;if(!o)break;else{r=o;i=n}}if(i>>>0>>0)B();else{de[i>>2]=0;u=r;break}}else{n=de[e+(l+8)>>2]|0;if(n>>>0>>0)B();r=n+12|0;if((de[r>>2]|0)!=(h|0))B();i=o+8|0;if((de[i>>2]|0)==(h|0)){de[r>>2]=o;de[i>>2]=n;u=o;break}else B()}}while(0);if(a){r=de[e+(l+28)>>2]|0;i=908+(r<<2)|0;if((h|0)==(de[i>>2]|0)){de[i>>2]=u;if(!u){de[152]=de[152]&~(1<>>0<(de[155]|0)>>>0)B();r=a+16|0;if((de[r>>2]|0)==(h|0))de[r>>2]=u;else de[a+20>>2]=u;if(!u)break}i=de[155]|0;if(u>>>0>>0)B();de[u+24>>2]=a;r=de[e+(l+16)>>2]|0;do{if(r)if(r>>>0>>0)B();else{de[u+16>>2]=r;de[r+24>>2]=u;break}}while(0);r=de[e+(l+20)>>2]|0;if(r)if(r>>>0<(de[155]|0)>>>0)B();else{de[u+20>>2]=r;de[r+24>>2]=u;break}}}else{n=de[e+(l+8)>>2]|0;i=de[e+(l+12)>>2]|0;r=644+(o<<1<<2)|0;if((n|0)!=(r|0)){if(n>>>0>>0)B();if((de[n+12>>2]|0)!=(h|0))B()}if((i|0)==(n|0)){de[151]=de[151]&~(1<>>0>>0)B();r=i+8|0;if((de[r>>2]|0)==(h|0))a=r;else B()}else a=i+8|0;de[n+12>>2]=i;de[a>>2]=n}}while(0);if(f>>>0<16){de[p>>2]=c|d&1|2;t=e+(c|4)|0;de[t>>2]=de[t>>2]|1;return e|0}else{de[p>>2]=d&1|t|2;de[e+(t+4)>>2]=f|3;d=e+(c|4)|0;de[d>>2]=de[d>>2]|1;Kr(e+t|0,f);return e|0}return 0}function Kr(e,t){e=e|0;t=t|0;var r=0,i=0,n=0,o=0,a=0,s=0,l=0,u=0,h=0,c=0,f=0,p=0,d=0,m=0,_=0,g=0,v=0;m=e+t|0;r=de[e+4>>2]|0;do{if(!(r&1)){u=de[e>>2]|0;if(!(r&3))return;f=e+(0-u)|0;c=u+t|0;l=de[155]|0;if(f>>>0>>0)B();if((f|0)==(de[156]|0)){i=e+(t+4)|0;r=de[i>>2]|0;if((r&3|0)!=3){v=f;a=c;break}de[153]=c;de[i>>2]=r&-2;de[e+(4-u)>>2]=c|1;de[m>>2]=c;return}o=u>>>3;if(u>>>0<256){n=de[e+(8-u)>>2]|0;i=de[e+(12-u)>>2]|0;r=644+(o<<1<<2)|0;if((n|0)!=(r|0)){if(n>>>0>>0)B();if((de[n+12>>2]|0)!=(f|0))B()}if((i|0)==(n|0)){de[151]=de[151]&~(1<>>0>>0)B();r=i+8|0;if((de[r>>2]|0)==(f|0))s=r;else B()}else s=i+8|0;de[n+12>>2]=i;de[s>>2]=n;v=f;a=c;break}s=de[e+(24-u)>>2]|0;n=de[e+(12-u)>>2]|0;do{if((n|0)==(f|0)){n=16-u|0;i=e+(n+4)|0;r=de[i>>2]|0;if(!r){i=e+n|0;r=de[i>>2]|0;if(!r){h=0;break}}while(1){n=r+20|0;o=de[n>>2]|0;if(o){r=o;i=n;continue}n=r+16|0;o=de[n>>2]|0;if(!o)break;else{r=o;i=n}}if(i>>>0>>0)B();else{de[i>>2]=0;h=r;break}}else{o=de[e+(8-u)>>2]|0;if(o>>>0>>0)B();r=o+12|0;if((de[r>>2]|0)!=(f|0))B();i=n+8|0;if((de[i>>2]|0)==(f|0)){de[r>>2]=n;de[i>>2]=o;h=n;break}else B()}}while(0);if(s){r=de[e+(28-u)>>2]|0;i=908+(r<<2)|0;if((f|0)==(de[i>>2]|0)){de[i>>2]=h;if(!h){de[152]=de[152]&~(1<>>0<(de[155]|0)>>>0)B();r=s+16|0;if((de[r>>2]|0)==(f|0))de[r>>2]=h;else de[s+20>>2]=h;if(!h){v=f;a=c;break}}n=de[155]|0;if(h>>>0>>0)B();de[h+24>>2]=s;r=16-u|0;i=de[e+r>>2]|0;do{if(i)if(i>>>0>>0)B();else{de[h+16>>2]=i;de[i+24>>2]=h;break}}while(0);r=de[e+(r+4)>>2]|0;if(r)if(r>>>0<(de[155]|0)>>>0)B();else{de[h+20>>2]=r;de[r+24>>2]=h;v=f;a=c;break}else{v=f;a=c}}else{v=f;a=c}}else{v=e;a=t}}while(0);l=de[155]|0;if(m>>>0>>0)B();r=e+(t+4)|0;i=de[r>>2]|0;if(!(i&2)){if((m|0)==(de[157]|0)){g=(de[154]|0)+a|0;de[154]=g;de[157]=v;de[v+4>>2]=g|1;if((v|0)!=(de[156]|0))return;de[156]=0;de[153]=0;return}if((m|0)==(de[156]|0)){g=(de[153]|0)+a|0;de[153]=g;de[156]=v;de[v+4>>2]=g|1;de[v+g>>2]=g;return}a=(i&-8)+a|0;o=i>>>3;do{if(i>>>0>=256){s=de[e+(t+24)>>2]|0;n=de[e+(t+12)>>2]|0;do{if((n|0)==(m|0)){i=e+(t+20)|0;r=de[i>>2]|0;if(!r){i=e+(t+16)|0;r=de[i>>2]|0;if(!r){d=0;break}}while(1){n=r+20|0;o=de[n>>2]|0;if(o){r=o;i=n;continue}n=r+16|0;o=de[n>>2]|0;if(!o)break;else{r=o;i=n}}if(i>>>0>>0)B();else{de[i>>2]=0;d=r;break}}else{o=de[e+(t+8)>>2]|0;if(o>>>0>>0)B();r=o+12|0;if((de[r>>2]|0)!=(m|0))B();i=n+8|0;if((de[i>>2]|0)==(m|0)){de[r>>2]=n;de[i>>2]=o;d=n;break}else B()}}while(0);if(s){r=de[e+(t+28)>>2]|0;i=908+(r<<2)|0;if((m|0)==(de[i>>2]|0)){de[i>>2]=d;if(!d){de[152]=de[152]&~(1<>>0<(de[155]|0)>>>0)B();r=s+16|0;if((de[r>>2]|0)==(m|0))de[r>>2]=d;else de[s+20>>2]=d;if(!d)break}i=de[155]|0;if(d>>>0>>0)B();de[d+24>>2]=s;r=de[e+(t+16)>>2]|0;do{if(r)if(r>>>0>>0)B();else{de[d+16>>2]=r;de[r+24>>2]=d;break}}while(0);r=de[e+(t+20)>>2]|0;if(r)if(r>>>0<(de[155]|0)>>>0)B();else{de[d+20>>2]=r;de[r+24>>2]=d;break}}}else{n=de[e+(t+8)>>2]|0;i=de[e+(t+12)>>2]|0;r=644+(o<<1<<2)|0;if((n|0)!=(r|0)){if(n>>>0>>0)B();if((de[n+12>>2]|0)!=(m|0))B()}if((i|0)==(n|0)){de[151]=de[151]&~(1<>>0>>0)B();r=i+8|0;if((de[r>>2]|0)==(m|0))p=r;else B()}else p=i+8|0;de[n+12>>2]=i;de[p>>2]=n}}while(0);de[v+4>>2]=a|1;de[v+a>>2]=a;if((v|0)==(de[156]|0)){de[153]=a;return}}else{de[r>>2]=i&-2;de[v+4>>2]=a|1;de[v+a>>2]=a}r=a>>>3;if(a>>>0<256){i=r<<1;o=644+(i<<2)|0;n=de[151]|0;r=1<>2]|0;if(i>>>0<(de[155]|0)>>>0)B();else{_=r;g=i}}else{de[151]=n|r;_=644+(i+2<<2)|0;g=o}de[_>>2]=v;de[g+12>>2]=v;de[v+8>>2]=g;de[v+12>>2]=o;return}r=a>>>8;if(r)if(a>>>0>16777215)o=31;else{_=(r+1048320|0)>>>16&8;g=r<<_;m=(g+520192|0)>>>16&4;g=g<>>16&2;o=14-(m|_|o)+(g<>>15)|0;o=a>>>(o+7|0)&1|o<<1}else o=0;r=908+(o<<2)|0;de[v+28>>2]=o;de[v+20>>2]=0;de[v+16>>2]=0;i=de[152]|0;n=1<>2]=v;de[v+24>>2]=r;de[v+12>>2]=v;de[v+8>>2]=v;return}r=de[r>>2]|0;e:do{if((de[r+4>>2]&-8|0)!=(a|0)){o=a<<((o|0)==31?0:25-(o>>>1)|0);while(1){i=r+16+(o>>>31<<2)|0;n=de[i>>2]|0;if(!n)break;if((de[n+4>>2]&-8|0)==(a|0)){r=n;break e}else{o=o<<1;r=n}}if(i>>>0<(de[155]|0)>>>0)B();de[i>>2]=v;de[v+24>>2]=r;de[v+12>>2]=v;de[v+8>>2]=v;return}}while(0);i=r+8|0;n=de[i>>2]|0;g=de[155]|0;if(!(n>>>0>=g>>>0&r>>>0>=g>>>0))B();de[n+12>>2]=v;de[i>>2]=v;de[v+8>>2]=n;de[v+12>>2]=r;de[v+24>>2]=0}function Jr(){}function se(e,t,r,i){e=e|0;t=t|0;r=r|0;i=i|0;i=t-i-(r>>>0>e>>>0|0)>>>0;return(re=i,e-r>>>0|0)|0}function G(e,t,r){e=e|0;t=t|0;r=r|0;var i=0,n=0,o=0,a=0;i=e+r|0;if((r|0)>=20){t=t&255;o=e&3;a=t|t<<8|t<<16|t<<24;n=i&~3;if(o){o=e+4-o|0;while((e|0)<(o|0)){pe[e>>0]=t;e=e+1|0}}while((e|0)<(n|0)){de[e>>2]=a;e=e+4|0}}while((e|0)<(i|0)){pe[e>>0]=t;e=e+1|0}return e-r|0}function Zr(e,t,r){e=e|0;t=t|0;r=r|0;if((r|0)<32){re=t>>>r;return e>>>r|(t&(1<>>r-32|0}function Qr(e,t,r){e=e|0;t=t|0;r=r|0;if((r|0)<32){re=t<>>32-r;return e<>>0;return(re=t+i+(r>>>0>>0|0)>>>0,r|0)|0}function ei(e,t,r){e=e|0;t=t|0;r=r|0;var i=0;if((r|0)>=4096)return Qe(e|0,t|0,r|0)|0;i=e|0;if((e&3)==(t&3)){while(e&3){if(!r)return i|0;pe[e>>0]=pe[t>>0]|0;e=e+1|0;t=t+1|0;r=r-1|0}while((r|0)>=4){de[e>>2]=de[t>>2];e=e+4|0;t=t+4|0;r=r-4|0}}while((r|0)>0){pe[e>>0]=pe[t>>0]|0;e=e+1|0;t=t+1|0;r=r-1|0}return i|0}function ti(e,t,r){e=e|0;t=t|0;r=r|0;if((r|0)<32){re=t>>r;return}re=(t|0)<0?-1:0}function ri(e){e=e|0;var t=0;t=pe[w+(e&255)>>0]|0;if((t|0)<8)return t|0;t=pe[w+(e>>8&255)>>0]|0;if((t|0)<8)return t+8|0;t=pe[w+(e>>16&255)>>0]|0;if((t|0)<8)return t+16|0;return(pe[w+(e>>>24)>>0]|0)+24|0}function ii(e,t){e=e|0;t=t|0;var r=0,i=0,n=0,o=0;o=e&65535;n=t&65535;r=ve(n,o)|0;i=e>>>16;e=(r>>>16)+(ve(n,i)|0)|0;n=t>>>16;t=ve(n,o)|0;return(re=(e>>>16)+(ve(n,i)|0)+(((e&65535)+t|0)>>>16)|0,e+t<<16|r&65535|0)|0}function ni(e,t,r,i){e=e|0;t=t|0;r=r|0;i=i|0;var n=0,o=0,a=0,s=0,l=0,u=0;u=t>>31|((t|0)<0?-1:0)<<1;l=((t|0)<0?-1:0)>>31|((t|0)<0?-1:0)<<1;o=i>>31|((i|0)<0?-1:0)<<1;n=((i|0)<0?-1:0)>>31|((i|0)<0?-1:0)<<1;s=se(u^e,l^t,u,l)|0;a=re;e=o^u;t=n^l;se((ui(s,a,se(o^r,n^i,o,n)|0,re,0)|0)^e,re^t,e,t)}function oi(e,t,r,i){e=e|0;t=t|0;r=r|0;i=i|0;var n=0,o=0,a=0,s=0,l=0,u=0;n=ge;ge=ge+16|0;s=n|0;a=t>>31|((t|0)<0?-1:0)<<1;o=((t|0)<0?-1:0)>>31|((t|0)<0?-1:0)<<1;u=i>>31|((i|0)<0?-1:0)<<1;l=((i|0)<0?-1:0)>>31|((i|0)<0?-1:0)<<1;e=se(a^e,o^t,a,o)|0;t=re;ui(e,t,se(u^r,l^i,u,l)|0,re,s)|0;i=se(de[s>>2]^a,de[s+4>>2]^o,a,o)|0;r=re;ge=n;re=r}function ai(e,t,r,i){e=e|0;t=t|0;r=r|0;i=i|0;var n=0,o=0;n=e;o=r;r=ii(n,o)|0;e=re;re=(ve(t,o)|0)+(ve(i,n)|0)+e|e&0}function si(e,t,r,i){e=e|0;t=t|0;r=r|0;i=i|0;return ui(e,t,r,i,0)|0}function li(e,t,r,i){e=e|0;t=t|0;r=r|0;i=i|0;var n=0,o=0;o=ge;ge=ge+16|0;n=o|0;ui(e,t,r,i,n)|0;ge=o;return(re=de[n+4>>2]|0,de[n>>2]|0)|0}function ui(e,t,r,i,n){e=e|0;t=t|0;r=r|0;i=i|0;n=n|0;var o=0,a=0,s=0,l=0,u=0,h=0,c=0,f=0,p=0,d=0;h=e;l=t;u=l;a=r;f=i;s=f;if(!u){o=(n|0)!=0;if(!s){if(o){de[n>>2]=(h>>>0)%(a>>>0);de[n+4>>2]=0}f=0;n=(h>>>0)/(a>>>0)>>>0;return(re=f,n)|0}else{if(!o){f=0;n=0;return(re=f,n)|0}de[n>>2]=e|0;de[n+4>>2]=t&0;f=0;n=0;return(re=f,n)|0}}o=(s|0)==0;do{if(a){if(!o){o=(m(s|0)|0)-(m(u|0)|0)|0;if(o>>>0<=31){c=o+1|0;s=31-o|0;t=o-31>>31;a=c;e=h>>>(c>>>0)&t|u<>>(c>>>0)&t;o=0;s=h<>2]=e|0;de[n+4>>2]=l|t&0;f=0;n=0;return(re=f,n)|0}o=a-1|0;if(o&a){s=(m(a|0)|0)+33-(m(u|0)|0)|0;d=64-s|0;c=32-s|0;l=c>>31;p=s-32|0;t=p>>31;a=s;e=c-1>>31&u>>>(p>>>0)|(u<>>(s>>>0))&t;t=t&u>>>(s>>>0);o=h<>>(p>>>0))&l|h<>31;break}if(n){de[n>>2]=o&h;de[n+4>>2]=0}if((a|0)==1){p=l|t&0;d=e|0|0;return(re=p,d)|0}else{d=ri(a|0)|0;p=u>>>(d>>>0)|0;d=u<<32-d|h>>>(d>>>0)|0;return(re=p,d)|0}}else{if(o){if(n){de[n>>2]=(u>>>0)%(a>>>0);de[n+4>>2]=0}p=0;d=(u>>>0)/(a>>>0)>>>0;return(re=p,d)|0}if(!h){if(n){de[n>>2]=0;de[n+4>>2]=(u>>>0)%(s>>>0)}p=0;d=(u>>>0)/(s>>>0)>>>0;return(re=p,d)|0}o=s-1|0;if(!(o&s)){if(n){de[n>>2]=e|0;de[n+4>>2]=o&u|t&0}p=0;d=u>>>((ri(s|0)|0)>>>0);return(re=p,d)|0}o=(m(s|0)|0)-(m(u|0)|0)|0;if(o>>>0<=30){t=o+1|0;s=31-o|0;a=t;e=u<>>(t>>>0);t=u>>>(t>>>0);o=0;s=h<>2]=e|0;de[n+4>>2]=l|t&0;p=0;d=0;return(re=p,d)|0}}while(0);if(!a){u=s;l=0;s=0}else{c=r|0|0;h=f|i&0;u=$r(c|0,h|0,-1,-1)|0;r=re;l=s;s=0;do{i=l;l=o>>>31|l<<1;o=s|o<<1;i=e<<1|i>>>31|0;f=e>>>31|t<<1|0;se(u,r,i,f)|0;d=re;p=d>>31|((d|0)<0?-1:0)<<1;s=p&1;e=se(i,f,p&c,(((d|0)<0?-1:0)>>31|((d|0)<0?-1:0)<<1)&h)|0;t=re;a=a-1|0}while((a|0)!=0);u=l;l=0}a=0;if(n){de[n>>2]=e;de[n+4>>2]=t}p=(o|0)>>>31|(u|a)<<1|(a<<1|o>>>31)&0|l;d=(o<<1|0>>>31)&-2|s;return(re=p,d)|0}function hi(e,t,r,i){e=e|0;t=t|0;r=r|0;i=i|0;return v[e&7](t|0,r|0,i|0)|0}function ci(e,t,r,i,n,o){e=e|0;t=t|0;r=r|0;i=i|0;n=n|0;o=o|0;Oi[e&3](t|0,r|0,i|0,n|0,o|0)}function fi(e,t){e=e|0;t=t|0;Pi[e&7](t|0)}function pi(e,t){e=e|0;t=t|0;return Ri[e&1](t|0)|0}function di(e,t,r,i){e=e|0;t=t|0;r=r|0;i=i|0;Ci[e&0](t|0,r|0,i|0)}function mi(e){e=e|0;Mi[e&3]()}function _i(e,t,r,i,n,o,a){e=e|0;t=t|0;r=r|0;i=i|0;n=n|0;o=o|0;a=a|0;Ii[e&3](t|0,r|0,i|0,n|0,o|0,a|0)}function gi(e,t,r,i,n,o){e=e|0;t=t|0;r=r|0;i=i|0;n=n|0;o=o|0;return X[e&1](t|0,r|0,i|0,n|0,o|0)|0}function vi(e,t,r,i,n){e=e|0;t=t|0;r=r|0;i=i|0;n=n|0;Di[e&3](t|0,r|0,i|0,n|0)}function yi(e,t,r){e=e|0;t=t|0;r=r|0;a(0);return 0}function bi(e,t,r,i,n){e=e|0;t=t|0;r=r|0;i=i|0;n=n|0;a(1)}function xi(e){e=e|0;a(2)}function Ti(e){e=e|0;a(3);return 0}function wi(e,t,r){e=e|0;t=t|0;r=r|0;a(4)}function Ei(){a(5)}function Si(e,t,r,i,n,o){e=e|0;t=t|0;r=r|0;i=i|0;n=n|0;o=o|0;a(6)}function Ai(e,t,r,i,n){e=e|0;t=t|0;r=r|0;i=i|0;n=n|0;a(7);return 0}function ki(e,t,r,i){e=e|0;t=t|0;r=r|0;i=i|0;a(8)}var v=[yi,ar,Xr,Fr,Lr,Nr,yi,yi];var Oi=[bi,pr,fr,bi];var Pi=[xi,tr,nr,rr,ir,or,br,Gr];var Ri=[Ti,Dr];var Ci=[wi];var Mi=[Ei,vr,yr,Ei];var Ii=[Si,mr,dr,Si];var X=[Ai,St];var Di=[ki,lr,ur,ki];return{___cxa_can_catch:_r,_crn_get_levels:Ft,_crn_get_uncompressed_size:zt,_crn_decompress:Bt,_i64Add:$r,_crn_get_width:Dt,___cxa_is_pointer_type:gr,_i64Subtract:se,_memset:G,_malloc:Yr,_free:b,_memcpy:ei,_bitshift64Lshr:Zr,_fflush:kr,_bitshift64Shl:Qr,_crn_get_height:Lt,___errno_location:ie,_crn_get_dxt_format:Nt,runPostSets:Jr,_emscripten_replace_memory:pt,stackAlloc:dt,stackSave:mt,stackRestore:_t,establishStackSpace:gt,setThrew:vt,setTempRet0:xt,getTempRet0:Tt,dynCall_iiii:hi,dynCall_viiiii:ci,dynCall_vi:fi,dynCall_ii:pi,dynCall_viii:di,dynCall_v:mi,dynCall_viiiiii:_i,dynCall_iiiiii:gi,dynCall_viiii:vi}}(e.Ya,e.Za,buffer)),zc=(e.___cxa_can_catch=Z.___cxa_can_catch,e._crn_get_levels=Z._crn_get_levels,e.runPostSets=Z.runPostSets,e._crn_get_uncompressed_size=Z._crn_get_uncompressed_size,e._crn_decompress=Z._crn_decompress,e._i64Add=Z._i64Add),nb=(e._crn_get_height=Z._crn_get_height,e.___cxa_is_pointer_type=Z.___cxa_is_pointer_type,e._i64Subtract=Z._i64Subtract),qb=e._memset=Z._memset,Ea=e._malloc=Z._malloc,Bc=e._memcpy=Z._memcpy,Xa=e._emscripten_replace_memory=Z._emscripten_replace_memory,rb=(e._crn_get_dxt_format=Z._crn_get_dxt_format,e._bitshift64Lshr=Z._bitshift64Lshr),Na=e._free=Z._free,sb=(e._fflush=Z._fflush,e._crn_get_width=Z._crn_get_width,e.___errno_location=Z.___errno_location,e._bitshift64Shl=Z._bitshift64Shl);function ia(e){this.name="ExitStatus",this.message="Program terminated with exit("+e+")",this.status=e}e.dynCall_iiii=Z.dynCall_iiii,e.dynCall_viiiii=Z.dynCall_viiiii,e.dynCall_vi=Z.dynCall_vi,e.dynCall_ii=Z.dynCall_ii,e.dynCall_viii=Z.dynCall_viii,e.dynCall_v=Z.dynCall_v,e.dynCall_viiiiii=Z.dynCall_viiiiii,e.dynCall_iiiiii=Z.dynCall_iiiiii,e.dynCall_viiii=Z.dynCall_viiii,n.aa=Z.stackAlloc,n.ua=Z.stackSave,n.ba=Z.stackRestore,n.Cd=Z.establishStackSpace,n.rb=Z.setTempRet0,n.fb=Z.getTempRet0,ia.prototype=Error(),ia.prototype.constructor=ia;var rd=null,jb=function t(){e.calledRun||td(),e.calledRun||(jb=t)};function td(t){function r(){if(!e.calledRun&&(e.calledRun=!0,!na)){if(Ha||(Ha=!0,ab(cb)),ab(db),e.onRuntimeInitialized&&e.onRuntimeInitialized(),e._main&&vd&&e.callMain(t),e.postRun)for("function"==typeof e.postRun&&(e.postRun=[e.postRun]);e.postRun.length;)gb(e.postRun.shift());ab(eb)}}if(t=t||e.arguments,null===rd&&(rd=Date.now()),!(0>8&255,e>>16&255,e>>24&255)}!function(s){s.loadFromArrayBuffer=function(e,t,r){return new i(t).loadFromArrayBuffer(e,r)};l=PIXI.resources.Resource,__extends(e,l),e.prototype.init=function(e,t,r,i,n,o,a){void 0===i&&(i=-1),void 0===n&&(n=-1),this.src=e,this.resize(i,n),this._width=i,this._height=n,this.data=t,this.type=r,this.levels=o,this.internalFormat=a;e=this.complete;return this.complete=!!t,!e&&this.complete&&this.onload&&this.onload({target:this}),this.update(),this},e.prototype.dispose=function(){this.data=null},e.prototype.bind=function(e){void 0!==e.alphaMode?e.alphaMode=PIXI.ALPHA_MODES.NO_PREMULTIPLIED_ALPHA:e.premultiplyAlpha=!1,l.prototype.bind.call(this,e)},e.prototype.upload=function(e,t,r){var i=e.state.gl;if(r.compressed=!1,e.texture.initCompressed(),null===this.data)throw"Trying to create a second (or more) webgl texture from the same CompressedImage : "+this.src;for(var n=this.levels,o=this.width,a=this.height,s=0,l=0;l>=1)<1&&(o=1),(a>>=1)<1&&(a=1),s+=u}return this._internalLoader.free(),this.preserveSource||(this.data=null),!0},e.prototype.style=function(e,t,r){var e=e.state.gl,i=this.levels;return t.scaleMode===PIXI.SCALE_MODES.LINEAR?1>2)*(t+3>>2)*8;case 33778:case 33779:case 35987:case 34798:return(e+3>>2)*(t+3>>2)*16;default:return 0}},h.type="DDS",h);function h(e){return r.call(this,e)||this}e.DDSLoader=i}(pixi_compressed_textures=pixi_compressed_textures||{}),!function(e){(r={})[0]=35841,r[1]=35843,r[2]=35840,r[3]=35842,r[6]=36196,r[7]=33776,r[9]=33778,r[5]=33779;var t,a=r,r=(t=e.AbstractInternalLoader,__extends(s,t),s.prototype.load=function(e){var t,r,i,n,o;if(s.test(e))return t=(o=new Int32Array(e,0,13))[2],t=a[t]||-1,r=o[7],i=o[6],n=o[11],o=o[12]+52,e=new Uint8Array(e,o),o=this._image,this._format=t,o.init(o.src,e,"PVR",r,i,n,t),o;throw"Invalid magic number in PVR header"},s.test=function(e){return 55727696===new Int32Array(e,0,1)[0]},s.prototype.levelBufferSize=function(e,t,r){switch(void 0===r&&(r=0),this._format){case 33776:case 36196:return(e+3>>2)*(t+3>>2)*8;case 33778:case 33779:return(e+3>>2)*(t+3>>2)*16;case 35840:case 35842:return Math.floor((Math.max(e,8)*Math.max(t,8)*4+7)/8);case 35841:case 35843:return Math.floor((Math.max(e,16)*Math.max(t,8)*2+7)/8);default:return 0}},s.type="PVR",s);function s(e){return t.call(this,e)||this}e.PVRTCLoader=r}(pixi_compressed_textures=pixi_compressed_textures||{}),!function(l){var e,t,r=0,i=2,n=3,o=8,a=9,s=10,u=11,h=((e={})[3]=!0,e[9]=!0,e[10]=!0,e[11]=!0,e),c=((e={})[u]=-1,e[r]=36196,e[i]=33776,e[n]=33779,e[o]=35840,e[a]=35842,e[s]=37808,e),f=Object.keys(c).reduce(function(e,t){return e[c[+t]]=+t,e},{}),u=(t=l.AbstractInternalLoader,__extends(p,t),p.test=function(e){var e=1262195===new Uint32Array(e,0,1)[0]&&!!p.BASIS_BINDING,t=p.RGB_FORMAT&&p.RGBA_FORMAT;return!e&&t&&console.warn("[BASIS LOADER] Is Supported, but transcoder not binded or file is not BASIS file!"),t&&e},p.bindTranscoder=function(e,r){if(!e||!r)throw"Invalid state! undef fileCtr or ext invalid!";var t,i=Object.keys(r).reduce(function(e,t){t=r[t];return t?Object.assign(e,t.__proto__):e},{}),n=void 0,o=void 0;for(t in i){var a,s=i[t];void 0!==f[s]&&(a=f[s],h[a]?o={native:s,name:t,basis:a}:n={native:s,name:t,basis:a})}p.RGB_FORMAT=n||o,p.RGBA_FORMAT=o||n,p.BASIS_BINDING=e,console.log("[BASISLoader] Supported formats:","\nRGB:"+p.RGB_FORMAT.name+"\nRGBA:"+p.RGBA_FORMAT.name),l.RegisterCompressedLoader(p),l.RegisterCompressedExtensions("basis")},p.prototype.load=function(e){if(p.test(e))return this._loadAsync(e),this._image;throw"BASIS Transcoder not binded or transcoding not supported =(!"},p.prototype._loadAsync=function(e){var t=performance.now(),e=new p.BASIS_BINDING(new Uint8Array(e)),r=e.getImageWidth(0,0),i=e.getImageHeight(0,0),n=e.getHasAlpha(),o=this._image;if(!e.startTranscoding())throw"Transcoding error!";var n=n?p.RGBA_FORMAT:p.RGB_FORMAT,a=(console.log("Grats! BASIS will be transcoded to:",n),new Uint8Array(e.getImageTranscodedSizeInBytes(0,0,n.basis)));if(!e.transcodeImage(a,0,0,n.basis,!1,!1))throw"Transcoding error!";console.log("[BASISLoader] Totla transcoding time:",performance.now()-t),this._format=n.native,this._file=e;t=n.name.replace("COMPRESSED_","");return Promise.resolve(o.init(o.src,a,"BASIS|"+t,r,i,1,n.native))},p.prototype.levelBufferSize=function(e,t,r){return this._file?this._file.getImageTranscodedSizeInBytes(0,r,f[this._format]):void 0},p.BASIS_BINDING=void 0,p);function p(e){e=t.call(this,e)||this;return e.type="BASIS",e._file=void 0,e}l.BASISLoader=u}(pixi_compressed_textures=pixi_compressed_textures||{}),!function(i){var g=window.CRN_Module;var t,v=[33776,33778,33779],e=(t=i.AbstractInternalLoader,__extends(r,t),r.prototype.load=function(e){for(var t=e.byteLength,e=new Uint8Array(e),r=g._malloc(t),i=e,n=g.HEAPU8,o=r,a=t,s=o/4,e=a%4,l=new Uint32Array(i.buffer,0,(a-e)/4),u=new Uint32Array(n.buffer),h=0;hn.count))return e=new a,n.workers.push(e),e.init(t,r).then(function(){r=e.binary,i()})}var n=this,o=0;return i().then(function(){return n})},r.prototype.transcode=function(t,r){var n,o,a,s;if(this.workers&&this.workers.length)return n=this.workers,o=void 0,a=0,s=function(e){for(var t=0,r=n;t>0,i=e[t];e[t]=e[r],e[r]=i}},E.prototype._randomizeOffsets=function(){for(var e=0;e>0,e,1+a>>0),i+=a}t.baseTexture.update(),this.uniforms.displacementMap=t},Object.defineProperty(E.prototype,"sizes",{get:function(){return this._sizes},set:function(e){for(var t=Math.min(this._slices,e.length),r=0;r>0)},Object.defineProperty(x.prototype,"offset",{get:function(){return this.uniforms.uOffset},set:function(e){this.uniforms.uOffset=e},enumerable:!1,configurable:!0}),x),Ge=(t(b,$=s.Filter),Object.defineProperty(b.prototype,"replacements",{get:function(){return this._replacements},set:function(e){var t=this.uniforms.originalColors,r=this.uniforms.targetColors,i=e.length;if(i>this._maxColors)throw new Error("Length of replacements ("+i+") exceeds the maximum colors length ("+this._maxColors+")");t[3*i]=-1;for(var n=0;n= 0.0 && dist > radius) { // radius < 0 means it's infinity\n delta = dist - radius;\n gap = gradient;\n }\n\n if (delta > 0.0) {\n float normalCount = gap / filterArea.x;\n delta = (normalCount - delta) / normalCount;\n countLimit *= delta;\n strength *= delta;\n if (countLimit < 1.0)\n {\n gl_FragColor = texture2D(uSampler, vTextureCoord);\n return;\n }\n }\n\n // randomize the lookup values to hide the fixed number of samples\n float offset = rand(vTextureCoord, 0.0);\n\n float total = 0.0;\n vec4 color = vec4(0.0);\n\n dir *= strength;\n\n for (float t = 0.0; t < MAX_KERNEL_SIZE; t++) {\n float percent = (t + offset) / MAX_KERNEL_SIZE;\n float weight = 4.0 * (percent - percent * percent);\n vec2 p = vTextureCoord + dir * percent;\n vec4 sample = texture2D(uSampler, p);\n\n // switch to pre-multiplied alpha to correctly blur transparent images\n // sample.rgb *= sample.a;\n\n color += sample * weight;\n total += weight;\n\n if (t > countLimit){\n break;\n }\n }\n\n color /= total;\n // switch back from pre-multiplied alpha\n // color.rgb /= color.a + 0.00001;\n\n gl_FragColor = color;\n}\n".replace("${maxKernelSize}",t.toFixed(1)))||this;return Object.assign(t,e),t}function i(e){var t=j.call(this,f,"varying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\nuniform float radius;\nuniform float angle;\nuniform vec2 offset;\nuniform vec4 filterArea;\n\nvec2 mapCoord( vec2 coord )\n{\n coord *= filterArea.xy;\n coord += filterArea.zw;\n\n return coord;\n}\n\nvec2 unmapCoord( vec2 coord )\n{\n coord -= filterArea.zw;\n coord /= filterArea.xy;\n\n return coord;\n}\n\nvec2 twist(vec2 coord)\n{\n coord -= offset;\n\n float dist = length(coord);\n\n if (dist < radius)\n {\n float ratioDist = (radius - dist) / radius;\n float angleMod = ratioDist * ratioDist * angle;\n float s = sin(angleMod);\n float c = cos(angleMod);\n coord = vec2(coord.x * c - coord.y * s, coord.x * s + coord.y * c);\n }\n\n coord += offset;\n\n return coord;\n}\n\nvoid main(void)\n{\n\n vec2 coord = mapCoord(vTextureCoord);\n\n coord = twist(coord);\n\n coord = unmapCoord(coord);\n\n gl_FragColor = texture2D(uSampler, coord );\n\n}\n")||this;return Object.assign(t,i.defaults,e),t}function n(e,t,r,i){void 0===e&&(e=100),void 0===t&&(t=600);var n=U.call(this)||this;return n.tiltShiftXFilter=new Qe(e,t,r,i),n.tiltShiftYFilter=new $e(e,t,r,i),n}function it(){return null!==G&&G.apply(this,arguments)||this}function nt(){return null!==X&&X.apply(this,arguments)||this}function o(e,t,r,i){void 0===e&&(e=100),void 0===t&&(t=600);var n=H.call(this,f,"varying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\nuniform float blur;\nuniform float gradientBlur;\nuniform vec2 start;\nuniform vec2 end;\nuniform vec2 delta;\nuniform vec2 texSize;\n\nfloat random(vec3 scale, float seed)\n{\n return fract(sin(dot(gl_FragCoord.xyz + seed, scale)) * 43758.5453 + seed);\n}\n\nvoid main(void)\n{\n vec4 color = vec4(0.0);\n float total = 0.0;\n\n float offset = random(vec3(12.9898, 78.233, 151.7182), 0.0);\n vec2 normal = normalize(vec2(start.y - end.y, end.x - start.x));\n float radius = smoothstep(0.0, 1.0, abs(dot(vTextureCoord * texSize - start, normal)) / gradientBlur) * blur;\n\n for (float t = -30.0; t <= 30.0; t++)\n {\n float percent = (t + offset - 0.5) / 30.0;\n float weight = 1.0 - abs(percent);\n vec4 sample = texture2D(uSampler, vTextureCoord + delta / texSize * percent * radius);\n sample.rgb *= sample.a;\n color += sample * weight;\n total += weight;\n }\n\n color /= total;\n color.rgb /= color.a + 0.00001;\n\n gl_FragColor = color;\n}\n")||this;return n.uniforms.blur=e,n.uniforms.gradientBlur=t,n.uniforms.start=r||new l.Point(0,window.innerHeight/2),n.uniforms.end=i||new l.Point(600,window.innerHeight/2),n.uniforms.delta=new l.Point(30,30),n.uniforms.texSize=new l.Point(window.innerWidth,window.innerHeight),n.updateDelta(),n}function a(e,t,r){void 0===t&&(t=0),void 0===r&&(r=1);var i=Y.call(this,f,"varying vec2 vTextureCoord;\nuniform sampler2D uSampler;\nuniform sampler2D uLightmap;\nuniform vec4 filterArea;\nuniform vec2 dimensions;\nuniform vec4 ambientColor;\nvoid main() {\n vec4 diffuseColor = texture2D(uSampler, vTextureCoord);\n vec2 lightCoord = (vTextureCoord * filterArea.xy) / dimensions;\n vec4 light = texture2D(uLightmap, lightCoord);\n vec3 ambient = ambientColor.rgb * ambientColor.a;\n vec3 intensity = ambient + light.rgb;\n vec3 finalColor = diffuseColor.rgb * intensity;\n gl_FragColor = vec4(finalColor, diffuseColor.a);\n}\n")||this;return i._color=0,i.uniforms.dimensions=new Float32Array(2),i.uniforms.ambientColor=new Float32Array([0,0,0,r]),i.texture=e,i.color=t,i}function d(e,t,r){void 0===e&&(e=[0,0]),void 0===r&&(r=0);var i=W.call(this,f,"varying vec2 vTextureCoord;\nuniform sampler2D uSampler;\nuniform vec4 filterArea;\nuniform vec4 filterClamp;\n\nuniform vec2 center;\n\nuniform float amplitude;\nuniform float wavelength;\n// uniform float power;\nuniform float brightness;\nuniform float speed;\nuniform float radius;\n\nuniform float time;\n\nconst float PI = 3.14159;\n\nvoid main()\n{\n float halfWavelength = wavelength * 0.5 / filterArea.x;\n float maxRadius = radius / filterArea.x;\n float currentRadius = time * speed / filterArea.x;\n\n float fade = 1.0;\n\n if (maxRadius > 0.0) {\n if (currentRadius > maxRadius) {\n gl_FragColor = texture2D(uSampler, vTextureCoord);\n return;\n }\n fade = 1.0 - pow(currentRadius / maxRadius, 2.0);\n }\n\n vec2 dir = vec2(vTextureCoord - center / filterArea.xy);\n dir.y *= filterArea.y / filterArea.x;\n float dist = length(dir);\n\n if (dist <= 0.0 || dist < currentRadius - halfWavelength || dist > currentRadius + halfWavelength) {\n gl_FragColor = texture2D(uSampler, vTextureCoord);\n return;\n }\n\n vec2 diffUV = normalize(dir);\n\n float diff = (dist - currentRadius) / halfWavelength;\n\n float p = 1.0 - pow(abs(diff), 2.0);\n\n // float powDiff = diff * pow(p, 2.0) * ( amplitude * fade );\n float powDiff = 1.25 * sin(diff * PI) * p * ( amplitude * fade );\n\n vec2 offset = diffUV * powDiff / filterArea.xy;\n\n // Do clamp :\n vec2 coord = vTextureCoord + offset;\n vec2 clampedCoord = clamp(coord, filterClamp.xy, filterClamp.zw);\n vec4 color = texture2D(uSampler, clampedCoord);\n if (coord != clampedCoord) {\n color *= max(0.0, 1.0 - length(coord - clampedCoord));\n }\n\n // No clamp :\n // gl_FragColor = texture2D(uSampler, vTextureCoord + offset);\n\n color.rgb *= 1.0 + (brightness - 1.0) * p * fade;\n\n gl_FragColor = color;\n}\n")||this;return i.center=e,Object.assign(i,d.defaults,t),i.time=r,i}function m(e,t,r){void 0===e&&(e=[-10,0]),void 0===t&&(t=[0,10]),void 0===r&&(r=[0,0]);var i=q.call(this,f,"precision mediump float;\n\nvarying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\nuniform vec4 filterArea;\nuniform vec2 red;\nuniform vec2 green;\nuniform vec2 blue;\n\nvoid main(void)\n{\n gl_FragColor.r = texture2D(uSampler, vTextureCoord + red/filterArea.xy).r;\n gl_FragColor.g = texture2D(uSampler, vTextureCoord + green/filterArea.xy).g;\n gl_FragColor.b = texture2D(uSampler, vTextureCoord + blue/filterArea.xy).b;\n gl_FragColor.a = texture2D(uSampler, vTextureCoord).a;\n}\n")||this;return i.red=e,i.green=t,i.blue=r,i}function _(e){var t=V.call(this,f,"varying vec2 vTextureCoord;\nuniform sampler2D uSampler;\n\nuniform vec4 filterArea;\nuniform vec4 filterClamp;\nuniform vec2 dimensions;\n\nuniform bool mirror;\nuniform float boundary;\nuniform vec2 amplitude;\nuniform vec2 waveLength;\nuniform vec2 alpha;\nuniform float time;\n\nfloat rand(vec2 co) {\n return fract(sin(dot(co.xy, vec2(12.9898, 78.233))) * 43758.5453);\n}\n\nvoid main(void)\n{\n vec2 pixelCoord = vTextureCoord.xy * filterArea.xy;\n vec2 coord = pixelCoord / dimensions;\n\n if (coord.y < boundary) {\n gl_FragColor = texture2D(uSampler, vTextureCoord);\n return;\n }\n\n float k = (coord.y - boundary) / (1. - boundary + 0.0001);\n float areaY = boundary * dimensions.y / filterArea.y;\n float v = areaY + areaY - vTextureCoord.y;\n float y = mirror ? v : vTextureCoord.y;\n\n float _amplitude = ((amplitude.y - amplitude.x) * k + amplitude.x ) / filterArea.x;\n float _waveLength = ((waveLength.y - waveLength.x) * k + waveLength.x) / filterArea.y;\n float _alpha = (alpha.y - alpha.x) * k + alpha.x;\n\n float x = vTextureCoord.x + cos(v * 6.28 / _waveLength - time) * _amplitude;\n x = clamp(x, filterClamp.x, filterClamp.z);\n\n vec4 color = texture2D(uSampler, vec2(x, y));\n\n gl_FragColor = color * _alpha;\n}\n")||this;return t.time=0,t.uniforms.amplitude=new Float32Array(2),t.uniforms.waveLength=new Float32Array(2),t.uniforms.alpha=new Float32Array(2),t.uniforms.dimensions=new Float32Array(2),Object.assign(t,_.defaults,e),t}function g(e,t,r,i){void 0===e&&(e=0),void 0===t&&(t=[0,0]),void 0===r&&(r=5),void 0===i&&(i=-1);var n=K.call(this,f,"varying vec2 vTextureCoord;\nuniform sampler2D uSampler;\nuniform vec4 filterArea;\n\nuniform float uRadian;\nuniform vec2 uCenter;\nuniform float uRadius;\nuniform int uKernelSize;\n\nconst int MAX_KERNEL_SIZE = 2048;\n\nvoid main(void)\n{\n vec4 color = texture2D(uSampler, vTextureCoord);\n\n if (uKernelSize == 0)\n {\n gl_FragColor = color;\n return;\n }\n\n float aspect = filterArea.y / filterArea.x;\n vec2 center = uCenter.xy / filterArea.xy;\n float gradient = uRadius / filterArea.x * 0.3;\n float radius = uRadius / filterArea.x - gradient * 0.5;\n int k = uKernelSize - 1;\n\n vec2 coord = vTextureCoord;\n vec2 dir = vec2(center - coord);\n float dist = length(vec2(dir.x, dir.y * aspect));\n\n float radianStep = uRadian;\n if (radius >= 0.0 && dist > radius) {\n float delta = dist - radius;\n float gap = gradient;\n float scale = 1.0 - abs(delta / gap);\n if (scale <= 0.0) {\n gl_FragColor = color;\n return;\n }\n radianStep *= scale;\n }\n radianStep /= float(k);\n\n float s = sin(radianStep);\n float c = cos(radianStep);\n mat2 rotationMatrix = mat2(vec2(c, -s), vec2(s, c));\n\n for(int i = 0; i < MAX_KERNEL_SIZE - 1; i++) {\n if (i == k) {\n break;\n }\n\n coord -= center;\n coord.y *= aspect;\n coord = rotationMatrix * coord;\n coord.y /= aspect;\n coord += center;\n\n vec4 sample = texture2D(uSampler, coord);\n\n // switch to pre-multiplied alpha to correctly blur transparent images\n // sample.rgb *= sample.a;\n\n color += sample;\n }\n\n gl_FragColor = color / float(uKernelSize);\n}\n")||this;return n._angle=0,n.angle=e,n.center=t,n.kernelSize=r,n.radius=i,n}function ot(e){void 0===e&&(e=10);var t=J.call(this,f,"precision mediump float;\n\nvarying vec2 vTextureCoord;\n\nuniform vec2 size;\nuniform sampler2D uSampler;\n\nuniform vec4 filterArea;\n\nvec2 mapCoord( vec2 coord )\n{\n coord *= filterArea.xy;\n coord += filterArea.zw;\n\n return coord;\n}\n\nvec2 unmapCoord( vec2 coord )\n{\n coord -= filterArea.zw;\n coord /= filterArea.xy;\n\n return coord;\n}\n\nvec2 pixelate(vec2 coord, vec2 size)\n{\n\treturn floor( coord / size ) * size;\n}\n\nvoid main(void)\n{\n vec2 coord = mapCoord(vTextureCoord);\n\n coord = pixelate(coord, size);\n\n coord = unmapCoord(coord);\n\n gl_FragColor = texture2D(uSampler, coord);\n}\n")||this;return t.size=e,t}function v(e,t,r){void 0===e&&(e=1),void 0===t&&(t=0);var i=Z.call(this,f,"varying vec2 vTextureCoord;\nuniform sampler2D uSampler;\n\nuniform vec2 thickness;\nuniform vec4 outlineColor;\nuniform vec4 filterClamp;\n\nconst float DOUBLE_PI = 3.14159265358979323846264 * 2.;\n\nvoid main(void) {\n vec4 ownColor = texture2D(uSampler, vTextureCoord);\n vec4 curColor;\n float maxAlpha = 0.;\n vec2 displaced;\n for (float angle = 0.; angle <= DOUBLE_PI; angle += ${angleStep}) {\n displaced.x = vTextureCoord.x + thickness.x * cos(angle);\n displaced.y = vTextureCoord.y + thickness.y * sin(angle);\n curColor = texture2D(uSampler, clamp(displaced, filterClamp.xy, filterClamp.zw));\n maxAlpha = max(maxAlpha, curColor.a);\n }\n float resultAlpha = max(maxAlpha, ownColor.a);\n gl_FragColor = vec4((ownColor.rgb + outlineColor.rgb * (1. - ownColor.a)) * resultAlpha, resultAlpha);\n}\n".replace(/\$\{angleStep\}/,v.getAngleStep(r=void 0===r?.1:r)))||this;return i._thickness=1,i.uniforms.thickness=new Float32Array([0,0]),i.uniforms.outlineColor=new Float32Array([0,0,0,1]),Object.assign(i,{thickness:e,color:t,quality:r}),i}function y(e,t){void 0===t&&(t=0);var r=Q.call(this,f,"varying vec2 vTextureCoord;\nuniform sampler2D uSampler;\nuniform vec4 filterArea;\nuniform vec2 dimensions;\n\nuniform float sepia;\nuniform float noise;\nuniform float noiseSize;\nuniform float scratch;\nuniform float scratchDensity;\nuniform float scratchWidth;\nuniform float vignetting;\nuniform float vignettingAlpha;\nuniform float vignettingBlur;\nuniform float seed;\n\nconst float SQRT_2 = 1.414213;\nconst vec3 SEPIA_RGB = vec3(112.0 / 255.0, 66.0 / 255.0, 20.0 / 255.0);\n\nfloat rand(vec2 co) {\n return fract(sin(dot(co.xy, vec2(12.9898, 78.233))) * 43758.5453);\n}\n\nvec3 Overlay(vec3 src, vec3 dst)\n{\n // if (dst <= 0.5) then: 2 * src * dst\n // if (dst > 0.5) then: 1 - 2 * (1 - dst) * (1 - src)\n return vec3((dst.x <= 0.5) ? (2.0 * src.x * dst.x) : (1.0 - 2.0 * (1.0 - dst.x) * (1.0 - src.x)),\n (dst.y <= 0.5) ? (2.0 * src.y * dst.y) : (1.0 - 2.0 * (1.0 - dst.y) * (1.0 - src.y)),\n (dst.z <= 0.5) ? (2.0 * src.z * dst.z) : (1.0 - 2.0 * (1.0 - dst.z) * (1.0 - src.z)));\n}\n\n\nvoid main()\n{\n gl_FragColor = texture2D(uSampler, vTextureCoord);\n vec3 color = gl_FragColor.rgb;\n\n if (sepia > 0.0)\n {\n float gray = (color.x + color.y + color.z) / 3.0;\n vec3 grayscale = vec3(gray);\n\n color = Overlay(SEPIA_RGB, grayscale);\n\n color = grayscale + sepia * (color - grayscale);\n }\n\n vec2 coord = vTextureCoord * filterArea.xy / dimensions.xy;\n\n if (vignetting > 0.0)\n {\n float outter = SQRT_2 - vignetting * SQRT_2;\n vec2 dir = vec2(vec2(0.5, 0.5) - coord);\n dir.y *= dimensions.y / dimensions.x;\n float darker = clamp((outter - length(dir) * SQRT_2) / ( 0.00001 + vignettingBlur * SQRT_2), 0.0, 1.0);\n color.rgb *= darker + (1.0 - darker) * (1.0 - vignettingAlpha);\n }\n\n if (scratchDensity > seed && scratch != 0.0)\n {\n float phase = seed * 256.0;\n float s = mod(floor(phase), 2.0);\n float dist = 1.0 / scratchDensity;\n float d = distance(coord, vec2(seed * dist, abs(s - seed * dist)));\n if (d < seed * 0.6 + 0.4)\n {\n highp float period = scratchDensity * 10.0;\n\n float xx = coord.x * period + phase;\n float aa = abs(mod(xx, 0.5) * 4.0);\n float bb = mod(floor(xx / 0.5), 2.0);\n float yy = (1.0 - bb) * aa + bb * (2.0 - aa);\n\n float kk = 2.0 * period;\n float dw = scratchWidth / dimensions.x * (0.75 + seed);\n float dh = dw * kk;\n\n float tine = (yy - (2.0 - dh));\n\n if (tine > 0.0) {\n float _sign = sign(scratch);\n\n tine = s * tine / period + scratch + 0.1;\n tine = clamp(tine + 1.0, 0.5 + _sign * 0.5, 1.5 + _sign * 0.5);\n\n color.rgb *= tine;\n }\n }\n }\n\n if (noise > 0.0 && noiseSize > 0.0)\n {\n vec2 pixelCoord = vTextureCoord.xy * filterArea.xy;\n pixelCoord.x = floor(pixelCoord.x / noiseSize);\n pixelCoord.y = floor(pixelCoord.y / noiseSize);\n // vec2 d = pixelCoord * noiseSize * vec2(1024.0 + seed * 512.0, 1024.0 - seed * 512.0);\n // float _noise = snoise(d) * 0.5;\n float _noise = rand(pixelCoord * noiseSize * seed) - 0.5;\n color += _noise * noise;\n }\n\n gl_FragColor.rgb = color;\n}\n")||this;return r.seed=0,r.uniforms.dimensions=new Float32Array(2),"number"==typeof e?(r.seed=e,e=void 0):r.seed=t,Object.assign(r,y.defaults,e),r}function b(e,t,r){void 0===t&&(t=.05),void 0===r&&(r=e.length);var i=$.call(this,f,"varying vec2 vTextureCoord;\nuniform sampler2D uSampler;\n\nuniform float epsilon;\n\nconst int MAX_COLORS = %maxColors%;\n\nuniform vec3 originalColors[MAX_COLORS];\nuniform vec3 targetColors[MAX_COLORS];\n\nvoid main(void)\n{\n gl_FragColor = texture2D(uSampler, vTextureCoord);\n\n float alpha = gl_FragColor.a;\n if (alpha < 0.0001)\n {\n return;\n }\n\n vec3 color = gl_FragColor.rgb / alpha;\n\n for(int i = 0; i < MAX_COLORS; i++)\n {\n vec3 origColor = originalColors[i];\n if (origColor.r < 0.0)\n {\n break;\n }\n vec3 colorDiff = origColor - color;\n if (length(colorDiff) < epsilon)\n {\n vec3 targetColor = targetColors[i];\n gl_FragColor = vec4((targetColor + colorDiff) * alpha, alpha);\n return;\n }\n }\n}\n".replace(/%maxColors%/g,r.toFixed(0)))||this;return i._replacements=[],i._maxColors=0,i.epsilon=t,i._maxColors=r,i.uniforms.originalColors=new Float32Array(3*r),i.uniforms.targetColors=new Float32Array(3*r),i.replacements=e,i}function x(e,t,r){void 0===e&&(e=[0,0]),void 0===t&&(t=5),void 0===r&&(r=0);var i=ee.call(this,f,"varying vec2 vTextureCoord;\nuniform sampler2D uSampler;\nuniform vec4 filterArea;\n\nuniform vec2 uVelocity;\nuniform int uKernelSize;\nuniform float uOffset;\n\nconst int MAX_KERNEL_SIZE = 2048;\n\n// Notice:\n// the perfect way:\n// int kernelSize = min(uKernelSize, MAX_KERNELSIZE);\n// BUT in real use-case , uKernelSize < MAX_KERNELSIZE almost always.\n// So use uKernelSize directly.\n\nvoid main(void)\n{\n vec4 color = texture2D(uSampler, vTextureCoord);\n\n if (uKernelSize == 0)\n {\n gl_FragColor = color;\n return;\n }\n\n vec2 velocity = uVelocity / filterArea.xy;\n float offset = -uOffset / length(uVelocity) - 0.5;\n int k = uKernelSize - 1;\n\n for(int i = 0; i < MAX_KERNEL_SIZE - 1; i++) {\n if (i == k) {\n break;\n }\n vec2 bias = velocity * (float(i) / float(k) + offset);\n color += texture2D(uSampler, vTextureCoord + bias);\n }\n gl_FragColor = color / float(uKernelSize);\n}\n")||this;return i.kernelSize=5,i.uniforms.uVelocity=new Float32Array(2),i._velocity=new l.ObservablePoint(i.velocityChanged,i),i.setVelocity(e),i.kernelSize=t,i.offset=r,i}function T(e){var t=te.call(this,f,"varying vec2 vTextureCoord;\nuniform sampler2D uSampler;\nuniform vec4 filterArea;\nuniform vec2 dimensions;\n\nuniform vec2 light;\nuniform bool parallel;\nuniform float aspect;\n\nuniform float gain;\nuniform float lacunarity;\nuniform float time;\nuniform float alpha;\n\n${perlin}\n\nvoid main(void) {\n vec2 coord = vTextureCoord * filterArea.xy / dimensions.xy;\n\n float d;\n\n if (parallel) {\n float _cos = light.x;\n float _sin = light.y;\n d = (_cos * coord.x) + (_sin * coord.y * aspect);\n } else {\n float dx = coord.x - light.x / dimensions.x;\n float dy = (coord.y - light.y / dimensions.y) * aspect;\n float dis = sqrt(dx * dx + dy * dy) + 0.00001;\n d = dy / dis;\n }\n\n vec3 dir = vec3(d, d, 0.0);\n\n float noise = turb(dir + vec3(time, 0.0, 62.1 + time) * 0.05, vec3(480.0, 320.0, 480.0), lacunarity, gain);\n noise = mix(noise, 0.0, 0.3);\n //fade vertically.\n vec4 mist = vec4(noise, noise, noise, 1.0) * (1.0 - coord.y);\n mist.a = 1.0;\n // apply user alpha\n mist *= alpha;\n\n gl_FragColor = texture2D(uSampler, vTextureCoord) + mist;\n\n}\n".replace("${perlin}","vec3 mod289(vec3 x)\n{\n return x - floor(x * (1.0 / 289.0)) * 289.0;\n}\nvec4 mod289(vec4 x)\n{\n return x - floor(x * (1.0 / 289.0)) * 289.0;\n}\nvec4 permute(vec4 x)\n{\n return mod289(((x * 34.0) + 1.0) * x);\n}\nvec4 taylorInvSqrt(vec4 r)\n{\n return 1.79284291400159 - 0.85373472095314 * r;\n}\nvec3 fade(vec3 t)\n{\n return t * t * t * (t * (t * 6.0 - 15.0) + 10.0);\n}\n// Classic Perlin noise, periodic variant\nfloat pnoise(vec3 P, vec3 rep)\n{\n vec3 Pi0 = mod(floor(P), rep); // Integer part, modulo period\n vec3 Pi1 = mod(Pi0 + vec3(1.0), rep); // Integer part + 1, mod period\n Pi0 = mod289(Pi0);\n Pi1 = mod289(Pi1);\n vec3 Pf0 = fract(P); // Fractional part for interpolation\n vec3 Pf1 = Pf0 - vec3(1.0); // Fractional part - 1.0\n vec4 ix = vec4(Pi0.x, Pi1.x, Pi0.x, Pi1.x);\n vec4 iy = vec4(Pi0.yy, Pi1.yy);\n vec4 iz0 = Pi0.zzzz;\n vec4 iz1 = Pi1.zzzz;\n vec4 ixy = permute(permute(ix) + iy);\n vec4 ixy0 = permute(ixy + iz0);\n vec4 ixy1 = permute(ixy + iz1);\n vec4 gx0 = ixy0 * (1.0 / 7.0);\n vec4 gy0 = fract(floor(gx0) * (1.0 / 7.0)) - 0.5;\n gx0 = fract(gx0);\n vec4 gz0 = vec4(0.5) - abs(gx0) - abs(gy0);\n vec4 sz0 = step(gz0, vec4(0.0));\n gx0 -= sz0 * (step(0.0, gx0) - 0.5);\n gy0 -= sz0 * (step(0.0, gy0) - 0.5);\n vec4 gx1 = ixy1 * (1.0 / 7.0);\n vec4 gy1 = fract(floor(gx1) * (1.0 / 7.0)) - 0.5;\n gx1 = fract(gx1);\n vec4 gz1 = vec4(0.5) - abs(gx1) - abs(gy1);\n vec4 sz1 = step(gz1, vec4(0.0));\n gx1 -= sz1 * (step(0.0, gx1) - 0.5);\n gy1 -= sz1 * (step(0.0, gy1) - 0.5);\n vec3 g000 = vec3(gx0.x, gy0.x, gz0.x);\n vec3 g100 = vec3(gx0.y, gy0.y, gz0.y);\n vec3 g010 = vec3(gx0.z, gy0.z, gz0.z);\n vec3 g110 = vec3(gx0.w, gy0.w, gz0.w);\n vec3 g001 = vec3(gx1.x, gy1.x, gz1.x);\n vec3 g101 = vec3(gx1.y, gy1.y, gz1.y);\n vec3 g011 = vec3(gx1.z, gy1.z, gz1.z);\n vec3 g111 = vec3(gx1.w, gy1.w, gz1.w);\n vec4 norm0 = taylorInvSqrt(vec4(dot(g000, g000), dot(g010, g010), dot(g100, g100), dot(g110, g110)));\n g000 *= norm0.x;\n g010 *= norm0.y;\n g100 *= norm0.z;\n g110 *= norm0.w;\n vec4 norm1 = taylorInvSqrt(vec4(dot(g001, g001), dot(g011, g011), dot(g101, g101), dot(g111, g111)));\n g001 *= norm1.x;\n g011 *= norm1.y;\n g101 *= norm1.z;\n g111 *= norm1.w;\n float n000 = dot(g000, Pf0);\n float n100 = dot(g100, vec3(Pf1.x, Pf0.yz));\n float n010 = dot(g010, vec3(Pf0.x, Pf1.y, Pf0.z));\n float n110 = dot(g110, vec3(Pf1.xy, Pf0.z));\n float n001 = dot(g001, vec3(Pf0.xy, Pf1.z));\n float n101 = dot(g101, vec3(Pf1.x, Pf0.y, Pf1.z));\n float n011 = dot(g011, vec3(Pf0.x, Pf1.yz));\n float n111 = dot(g111, Pf1);\n vec3 fade_xyz = fade(Pf0);\n vec4 n_z = mix(vec4(n000, n100, n010, n110), vec4(n001, n101, n011, n111), fade_xyz.z);\n vec2 n_yz = mix(n_z.xy, n_z.zw, fade_xyz.y);\n float n_xyz = mix(n_yz.x, n_yz.y, fade_xyz.x);\n return 2.2 * n_xyz;\n}\nfloat turb(vec3 P, vec3 rep, float lacunarity, float gain)\n{\n float sum = 0.0;\n float sc = 1.0;\n float totalgain = 1.0;\n for (float i = 0.0; i < 6.0; i++)\n {\n sum += totalgain * pnoise(P * sc, rep);\n sc *= lacunarity;\n totalgain *= gain;\n }\n return abs(sum);\n}\n"))||this,e=(t.parallel=!0,t.time=0,t._angle=0,t.uniforms.dimensions=new Float32Array(2),Object.assign(T.defaults,e));return t._angleLight=new l.Point,t.angle=e.angle,t.gain=e.gain,t.lacunarity=e.lacunarity,t.alpha=e.alpha,t.parallel=e.parallel,t.center=e.center,t.time=e.time,t}function w(e){var t=this,e=Object.assign({},w.defaults,e),r=e.outerStrength,i=e.innerStrength,n=e.color,o=e.knockout,a=e.quality,e=Math.round(e.distance);return(t=re.call(this,f,"varying vec2 vTextureCoord;\nvarying vec4 vColor;\n\nuniform sampler2D uSampler;\n\nuniform float outerStrength;\nuniform float innerStrength;\n\nuniform vec4 glowColor;\n\nuniform vec4 filterArea;\nuniform vec4 filterClamp;\nuniform bool knockout;\n\nconst float PI = 3.14159265358979323846264;\n\nconst float DIST = __DIST__;\nconst float ANGLE_STEP_SIZE = min(__ANGLE_STEP_SIZE__, PI * 2.0);\nconst float ANGLE_STEP_NUM = ceil(PI * 2.0 / ANGLE_STEP_SIZE);\n\nconst float MAX_TOTAL_ALPHA = ANGLE_STEP_NUM * DIST * (DIST + 1.0) / 2.0;\n\nvoid main(void) {\n vec2 px = vec2(1.0 / filterArea.x, 1.0 / filterArea.y);\n\n float totalAlpha = 0.0;\n\n vec2 direction;\n vec2 displaced;\n vec4 curColor;\n\n for (float angle = 0.0; angle < PI * 2.0; angle += ANGLE_STEP_SIZE) {\n direction = vec2(cos(angle), sin(angle)) * px;\n\n for (float curDistance = 0.0; curDistance < DIST; curDistance++) {\n displaced = clamp(vTextureCoord + direction * \n (curDistance + 1.0), filterClamp.xy, filterClamp.zw);\n\n curColor = texture2D(uSampler, displaced);\n\n totalAlpha += (DIST - curDistance) * curColor.a;\n }\n }\n \n curColor = texture2D(uSampler, vTextureCoord);\n\n float alphaRatio = (totalAlpha / MAX_TOTAL_ALPHA);\n\n float innerGlowAlpha = (1.0 - alphaRatio) * innerStrength * curColor.a;\n float innerGlowStrength = min(1.0, innerGlowAlpha);\n \n vec4 innerColor = mix(curColor, glowColor, innerGlowStrength);\n\n float outerGlowAlpha = alphaRatio * outerStrength * (1. - curColor.a);\n float outerGlowStrength = min(1.0 - innerColor.a, outerGlowAlpha);\n\n vec4 outerGlowColor = outerGlowStrength * glowColor.rgba;\n \n if (knockout) {\n float resultAlpha = outerGlowAlpha + innerGlowAlpha;\n gl_FragColor = vec4(glowColor.rgb * resultAlpha, resultAlpha);\n }\n else {\n gl_FragColor = innerColor + outerGlowColor;\n }\n}\n".replace(/__ANGLE_STEP_SIZE__/gi,""+(1/a/e).toFixed(7)).replace(/__DIST__/gi,e.toFixed(0)+".0"))||this).uniforms.glowColor=new Float32Array([0,0,0,1]),Object.assign(t,{color:n,outerStrength:r,innerStrength:i,padding:e,knockout:o}),t}function E(e){var t=ie.call(this,f,"// precision highp float;\n\nvarying vec2 vTextureCoord;\nuniform sampler2D uSampler;\n\nuniform vec4 filterArea;\nuniform vec4 filterClamp;\nuniform vec2 dimensions;\nuniform float aspect;\n\nuniform sampler2D displacementMap;\nuniform float offset;\nuniform float sinDir;\nuniform float cosDir;\nuniform int fillMode;\n\nuniform float seed;\nuniform vec2 red;\nuniform vec2 green;\nuniform vec2 blue;\n\nconst int TRANSPARENT = 0;\nconst int ORIGINAL = 1;\nconst int LOOP = 2;\nconst int CLAMP = 3;\nconst int MIRROR = 4;\n\nvoid main(void)\n{\n vec2 coord = (vTextureCoord * filterArea.xy) / dimensions;\n\n if (coord.x > 1.0 || coord.y > 1.0) {\n return;\n }\n\n float cx = coord.x - 0.5;\n float cy = (coord.y - 0.5) * aspect;\n float ny = (-sinDir * cx + cosDir * cy) / aspect + 0.5;\n\n // displacementMap: repeat\n // ny = ny > 1.0 ? ny - 1.0 : (ny < 0.0 ? 1.0 + ny : ny);\n\n // displacementMap: mirror\n ny = ny > 1.0 ? 2.0 - ny : (ny < 0.0 ? -ny : ny);\n\n vec4 dc = texture2D(displacementMap, vec2(0.5, ny));\n\n float displacement = (dc.r - dc.g) * (offset / filterArea.x);\n\n coord = vTextureCoord + vec2(cosDir * displacement, sinDir * displacement * aspect);\n\n if (fillMode == CLAMP) {\n coord = clamp(coord, filterClamp.xy, filterClamp.zw);\n } else {\n if( coord.x > filterClamp.z ) {\n if (fillMode == TRANSPARENT) {\n discard;\n } else if (fillMode == LOOP) {\n coord.x -= filterClamp.z;\n } else if (fillMode == MIRROR) {\n coord.x = filterClamp.z * 2.0 - coord.x;\n }\n } else if( coord.x < filterClamp.x ) {\n if (fillMode == TRANSPARENT) {\n discard;\n } else if (fillMode == LOOP) {\n coord.x += filterClamp.z;\n } else if (fillMode == MIRROR) {\n coord.x *= -filterClamp.z;\n }\n }\n\n if( coord.y > filterClamp.w ) {\n if (fillMode == TRANSPARENT) {\n discard;\n } else if (fillMode == LOOP) {\n coord.y -= filterClamp.w;\n } else if (fillMode == MIRROR) {\n coord.y = filterClamp.w * 2.0 - coord.y;\n }\n } else if( coord.y < filterClamp.y ) {\n if (fillMode == TRANSPARENT) {\n discard;\n } else if (fillMode == LOOP) {\n coord.y += filterClamp.w;\n } else if (fillMode == MIRROR) {\n coord.y *= -filterClamp.w;\n }\n }\n }\n\n gl_FragColor.r = texture2D(uSampler, coord + red * (1.0 - seed * 0.4) / filterArea.xy).r;\n gl_FragColor.g = texture2D(uSampler, coord + green * (1.0 - seed * 0.3) / filterArea.xy).g;\n gl_FragColor.b = texture2D(uSampler, coord + blue * (1.0 - seed * 0.2) / filterArea.xy).b;\n gl_FragColor.a = texture2D(uSampler, coord).a;\n}\n")||this;return t.offset=100,t.fillMode=E.TRANSPARENT,t.average=!1,t.seed=0,t.minSize=8,t.sampleSize=512,t._slices=0,t._offsets=new Float32Array(1),t._sizes=new Float32Array(1),t._direction=-1,t.uniforms.dimensions=new Float32Array(2),t._canvas=document.createElement("canvas"),t._canvas.width=4,t._canvas.height=t.sampleSize,t.texture=s.Texture.from(t._canvas,{scaleMode:c.SCALE_MODES.NEAREST}),Object.assign(t,E.defaults,e),t}function at(e){void 0===e&&(e=5);var t=ne.call(this,f,"precision mediump float;\n\nvarying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\nuniform float strength;\nuniform vec4 filterArea;\n\n\nvoid main(void)\n{\n\tvec2 onePixel = vec2(1.0 / filterArea);\n\n\tvec4 color;\n\n\tcolor.rgb = vec3(0.5);\n\n\tcolor -= texture2D(uSampler, vTextureCoord - onePixel) * strength;\n\tcolor += texture2D(uSampler, vTextureCoord + onePixel) * strength;\n\n\tcolor.rgb = vec3((color.r + color.g + color.b) / 3.0);\n\n\tfloat alpha = texture2D(uSampler, vTextureCoord).a;\n\n\tgl_FragColor = vec4(color.rgb * alpha, alpha);\n}\n")||this;return t.strength=e,t}function S(e){var t=oe.call(this)||this,e=(t.angle=45,t._distance=5,t._resolution=u.settings.FILTER_RESOLUTION,e?xe(xe({},S.defaults),e):S.defaults),r=e.kernels,i=e.blur,n=e.quality,o=e.pixelSize,a=e.resolution,r=(t._tintFilter=new s.Filter(f,"varying vec2 vTextureCoord;\nuniform sampler2D uSampler;\nuniform float alpha;\nuniform vec3 color;\n\nuniform vec2 shift;\nuniform vec4 inputSize;\n\nvoid main(void){\n vec4 sample = texture2D(uSampler, vTextureCoord - shift * inputSize.zw);\n\n // Premultiply alpha\n sample.rgb = color.rgb * sample.a;\n\n // alpha user alpha\n sample *= alpha;\n\n gl_FragColor = sample;\n}"),t._tintFilter.uniforms.color=new Float32Array(4),t._tintFilter.uniforms.shift=new l.Point,t._tintFilter.resolution=a,t._blurFilter=r?new p(r):new p(i,n),t.pixelSize=o,t.resolution=a,e.shadowOnly),i=e.rotation,n=e.distance,o=e.alpha,a=e.color;return t.shadowOnly=r,t.rotation=i,t.distance=n,t.alpha=o,t.color=a,t._updatePadding(),t}function A(e,t){void 0===e&&(e=1),void 0===t&&(t=5);var r=ae.call(this,f,"precision mediump float;\n\nvarying vec2 vTextureCoord;\nvarying vec4 vColor;\n\nuniform vec4 filterArea;\nuniform sampler2D uSampler;\n\nuniform float angle;\nuniform float scale;\n\nfloat pattern()\n{\n float s = sin(angle), c = cos(angle);\n vec2 tex = vTextureCoord * filterArea.xy;\n vec2 point = vec2(\n c * tex.x - s * tex.y,\n s * tex.x + c * tex.y\n ) * scale;\n return (sin(point.x) * sin(point.y)) * 4.0;\n}\n\nvoid main()\n{\n vec4 color = texture2D(uSampler, vTextureCoord);\n float average = (color.r + color.g + color.b) / 3.0;\n gl_FragColor = vec4(vec3(average * 10.0 - 5.0 + pattern()), color.a);\n}\n")||this;return r.scale=e,r.angle=t,r}function k(e){var t=se.call(this,f,"varying vec2 vTextureCoord;\nuniform sampler2D uSampler;\n\nuniform vec4 filterArea;\nuniform vec2 dimensions;\n\nconst float SQRT_2 = 1.414213;\n\nconst float light = 1.0;\n\nuniform float curvature;\nuniform float lineWidth;\nuniform float lineContrast;\nuniform bool verticalLine;\nuniform float noise;\nuniform float noiseSize;\n\nuniform float vignetting;\nuniform float vignettingAlpha;\nuniform float vignettingBlur;\n\nuniform float seed;\nuniform float time;\n\nfloat rand(vec2 co) {\n return fract(sin(dot(co.xy, vec2(12.9898, 78.233))) * 43758.5453);\n}\n\nvoid main(void)\n{\n vec2 pixelCoord = vTextureCoord.xy * filterArea.xy;\n vec2 dir = vec2(vTextureCoord.xy * filterArea.xy / dimensions - vec2(0.5, 0.5));\n \n gl_FragColor = texture2D(uSampler, vTextureCoord);\n vec3 rgb = gl_FragColor.rgb;\n\n if (noise > 0.0 && noiseSize > 0.0)\n {\n pixelCoord.x = floor(pixelCoord.x / noiseSize);\n pixelCoord.y = floor(pixelCoord.y / noiseSize);\n float _noise = rand(pixelCoord * noiseSize * seed) - 0.5;\n rgb += _noise * noise;\n }\n\n if (lineWidth > 0.0)\n {\n float _c = curvature > 0. ? curvature : 1.;\n float k = curvature > 0. ?(length(dir * dir) * 0.25 * _c * _c + 0.935 * _c) : 1.;\n vec2 uv = dir * k;\n\n float v = (verticalLine ? uv.x * dimensions.x : uv.y * dimensions.y) * min(1.0, 2.0 / lineWidth ) / _c;\n float j = 1. + cos(v * 1.2 - time) * 0.5 * lineContrast;\n rgb *= j;\n float segment = verticalLine ? mod((dir.x + .5) * dimensions.x, 4.) : mod((dir.y + .5) * dimensions.y, 4.);\n rgb *= 0.99 + ceil(segment) * 0.015;\n }\n\n if (vignetting > 0.0)\n {\n float outter = SQRT_2 - vignetting * SQRT_2;\n float darker = clamp((outter - length(dir) * SQRT_2) / ( 0.00001 + vignettingBlur * SQRT_2), 0.0, 1.0);\n rgb *= darker + (1.0 - darker) * (1.0 - vignettingAlpha);\n }\n\n gl_FragColor.rgb = rgb;\n}\n")||this;return t.time=0,t.seed=0,t.uniforms.dimensions=new Float32Array(2),Object.assign(t,k.defaults,e),t}function st(){return le.call(this,f,"precision mediump float;\n\nvarying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\n\nvoid main(void)\n{\n float lum = length(texture2D(uSampler, vTextureCoord.xy).rgb);\n\n gl_FragColor = vec4(1.0, 1.0, 1.0, 1.0);\n\n if (lum < 1.00)\n {\n if (mod(gl_FragCoord.x + gl_FragCoord.y, 10.0) == 0.0)\n {\n gl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);\n }\n }\n\n if (lum < 0.75)\n {\n if (mod(gl_FragCoord.x - gl_FragCoord.y, 10.0) == 0.0)\n {\n gl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);\n }\n }\n\n if (lum < 0.50)\n {\n if (mod(gl_FragCoord.x + gl_FragCoord.y - 5.0, 10.0) == 0.0)\n {\n gl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);\n }\n }\n\n if (lum < 0.3)\n {\n if (mod(gl_FragCoord.x - gl_FragCoord.y - 5.0, 10.0) == 0.0)\n {\n gl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);\n }\n }\n}\n")||this}function O(e,t,r){void 0===t&&(t=200),void 0===r&&(r=200);var i=ue.call(this,f,"precision mediump float;\n\nvarying mediump vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\nuniform vec2 texelSize;\nuniform float matrix[9];\n\nvoid main(void)\n{\n vec4 c11 = texture2D(uSampler, vTextureCoord - texelSize); // top left\n vec4 c12 = texture2D(uSampler, vec2(vTextureCoord.x, vTextureCoord.y - texelSize.y)); // top center\n vec4 c13 = texture2D(uSampler, vec2(vTextureCoord.x + texelSize.x, vTextureCoord.y - texelSize.y)); // top right\n\n vec4 c21 = texture2D(uSampler, vec2(vTextureCoord.x - texelSize.x, vTextureCoord.y)); // mid left\n vec4 c22 = texture2D(uSampler, vTextureCoord); // mid center\n vec4 c23 = texture2D(uSampler, vec2(vTextureCoord.x + texelSize.x, vTextureCoord.y)); // mid right\n\n vec4 c31 = texture2D(uSampler, vec2(vTextureCoord.x - texelSize.x, vTextureCoord.y + texelSize.y)); // bottom left\n vec4 c32 = texture2D(uSampler, vec2(vTextureCoord.x, vTextureCoord.y + texelSize.y)); // bottom center\n vec4 c33 = texture2D(uSampler, vTextureCoord + texelSize); // bottom right\n\n gl_FragColor =\n c11 * matrix[0] + c12 * matrix[1] + c13 * matrix[2] +\n c21 * matrix[3] + c22 * matrix[4] + c23 * matrix[5] +\n c31 * matrix[6] + c32 * matrix[7] + c33 * matrix[8];\n\n gl_FragColor.a = c22.a;\n}\n")||this;return i.uniforms.texelSize=new Float32Array(2),i.uniforms.matrix=new Float32Array(9),void 0!==e&&(i.matrix=e),i.width=t,i.height=r,i}function P(e,t,r){void 0===e&&(e=16711680),void 0===t&&(t=0),void 0===r&&(r=.4);var i=he.call(this,f,"varying vec2 vTextureCoord;\nuniform sampler2D uSampler;\nuniform vec3 originalColor;\nuniform vec3 newColor;\nuniform float epsilon;\nvoid main(void) {\n vec4 currentColor = texture2D(uSampler, vTextureCoord);\n vec3 colorDiff = originalColor - (currentColor.rgb / max(currentColor.a, 0.0000000001));\n float colorDistance = length(colorDiff);\n float doReplace = step(colorDistance, epsilon);\n gl_FragColor = vec4(mix(currentColor.rgb, (newColor + colorDiff) * currentColor.a, doReplace), currentColor.a);\n}\n")||this;return i._originalColor=16711680,i._newColor=0,i.uniforms.originalColor=new Float32Array(3),i.uniforms.newColor=new Float32Array(3),i.originalColor=e,i.newColor=t,i.epsilon=r,i}function lt(e,t){void 0===e&&(e=0),void 0===t&&(t=1);var r=ce.call(this,f,"varying vec2 vTextureCoord;\nuniform sampler2D uSampler;\nuniform vec3 color;\nuniform float alpha;\n\nvoid main(void) {\n vec4 currentColor = texture2D(uSampler, vTextureCoord);\n gl_FragColor = vec4(mix(currentColor.rgb, color.rgb, currentColor.a * alpha), currentColor.a);\n}\n")||this;return r._color=0,r._alpha=1,r.uniforms.color=new Float32Array(3),r.color=e,r.alpha=t,r}function R(e,t,r){void 0===t&&(t=!1),void 0===r&&(r=1);var i=fe.call(this,f,"varying vec2 vTextureCoord;\nuniform sampler2D uSampler;\nuniform sampler2D colorMap;\nuniform float _mix;\nuniform float _size;\nuniform float _sliceSize;\nuniform float _slicePixelSize;\nuniform float _sliceInnerSize;\nvoid main() {\n vec4 color = texture2D(uSampler, vTextureCoord.xy);\n\n vec4 adjusted;\n if (color.a > 0.0) {\n color.rgb /= color.a;\n float innerWidth = _size - 1.0;\n float zSlice0 = min(floor(color.b * innerWidth), innerWidth);\n float zSlice1 = min(zSlice0 + 1.0, innerWidth);\n float xOffset = _slicePixelSize * 0.5 + color.r * _sliceInnerSize;\n float s0 = xOffset + (zSlice0 * _sliceSize);\n float s1 = xOffset + (zSlice1 * _sliceSize);\n float yOffset = _sliceSize * 0.5 + color.g * (1.0 - _sliceSize);\n vec4 slice0Color = texture2D(colorMap, vec2(s0,yOffset));\n vec4 slice1Color = texture2D(colorMap, vec2(s1,yOffset));\n float zOffset = fract(color.b * innerWidth);\n adjusted = mix(slice0Color, slice1Color, zOffset);\n\n color.rgb *= color.a;\n }\n gl_FragColor = vec4(mix(color, adjusted, _mix).rgb, color.a);\n\n}")||this;return i.mix=1,i._size=0,i._sliceSize=0,i._slicePixelSize=0,i._sliceInnerSize=0,i._nearest=!1,i._scaleMode=null,i._colorMap=null,i._scaleMode=null,i.nearest=t,i.mix=r,i.colorMap=e,i}function C(e){var t=pe.call(this,f,"uniform float radius;\nuniform float strength;\nuniform vec2 center;\nuniform sampler2D uSampler;\nvarying vec2 vTextureCoord;\n\nuniform vec4 filterArea;\nuniform vec4 filterClamp;\nuniform vec2 dimensions;\n\nvoid main()\n{\n vec2 coord = vTextureCoord * filterArea.xy;\n coord -= center * dimensions.xy;\n float distance = length(coord);\n if (distance < radius) {\n float percent = distance / radius;\n if (strength > 0.0) {\n coord *= mix(1.0, smoothstep(0.0, radius / distance, percent), strength * 0.75);\n } else {\n coord *= mix(1.0, pow(percent, 1.0 + strength * 0.75) * radius / distance, 1.0 - percent);\n }\n }\n coord += center * dimensions.xy;\n coord /= filterArea.xy;\n vec2 clampedCoord = clamp(coord, filterClamp.xy, filterClamp.zw);\n vec4 color = texture2D(uSampler, clampedCoord);\n if (coord != clampedCoord) {\n color *= max(0.0, 1.0 - length(coord - clampedCoord));\n }\n\n gl_FragColor = color;\n}\n")||this;return t.uniforms.dimensions=new Float32Array(2),Object.assign(t,C.defaults,e),t}function M(e,t,r,i){void 0===e&&(e=2),void 0===t&&(t=4),void 0===r&&(r=u.settings.FILTER_RESOLUTION),void 0===i&&(i=5);var n,o,a=de.call(this)||this;return"number"==typeof e?o=n=e:e instanceof l.Point?(n=e.x,o=e.y):Array.isArray(e)&&(n=e[0],o=e[1]),a.blurXFilter=new N.BlurFilterPass(!0,n,t,r,i),a.blurYFilter=new N.BlurFilterPass(!1,o,t,r,i),a.blurYFilter.blendMode=c.BLEND_MODES.SCREEN,a.defaultFilter=new F.AlphaFilter,a}function I(e){var t=me.call(this,f,"precision mediump float;\n\nvarying vec2 vTextureCoord;\nuniform sampler2D uSampler;\nuniform vec4 filterArea;\n\nuniform float transformX;\nuniform float transformY;\nuniform vec3 lightColor;\nuniform float lightAlpha;\nuniform vec3 shadowColor;\nuniform float shadowAlpha;\n\nvoid main(void) {\n vec2 transform = vec2(1.0 / filterArea) * vec2(transformX, transformY);\n vec4 color = texture2D(uSampler, vTextureCoord);\n float light = texture2D(uSampler, vTextureCoord - transform).a;\n float shadow = texture2D(uSampler, vTextureCoord + transform).a;\n\n color.rgb = mix(color.rgb, lightColor, clamp((color.a - light) * lightAlpha, 0.0, 1.0));\n color.rgb = mix(color.rgb, shadowColor, clamp((color.a - shadow) * shadowAlpha, 0.0, 1.0));\n gl_FragColor = vec4(color.rgb * color.a, color.a);\n}\n")||this;return t._thickness=2,t._angle=0,t.uniforms.lightColor=new Float32Array(3),t.uniforms.shadowColor=new Float32Array(3),Object.assign(t,{rotation:45,thickness:2,lightColor:16777215,lightAlpha:.7,shadowColor:0,shadowAlpha:.7},e),t.padding=1,t}function ut(e){void 0===e&&(e=8);var t=_e.call(this,f,"varying vec2 vTextureCoord;\n\nuniform vec4 filterArea;\nuniform float pixelSize;\nuniform sampler2D uSampler;\n\nvec2 mapCoord( vec2 coord )\n{\n coord *= filterArea.xy;\n coord += filterArea.zw;\n\n return coord;\n}\n\nvec2 unmapCoord( vec2 coord )\n{\n coord -= filterArea.zw;\n coord /= filterArea.xy;\n\n return coord;\n}\n\nvec2 pixelate(vec2 coord, vec2 size)\n{\n return floor( coord / size ) * size;\n}\n\nvec2 getMod(vec2 coord, vec2 size)\n{\n return mod( coord , size) / size;\n}\n\nfloat character(float n, vec2 p)\n{\n p = floor(p*vec2(4.0, -4.0) + 2.5);\n\n if (clamp(p.x, 0.0, 4.0) == p.x)\n {\n if (clamp(p.y, 0.0, 4.0) == p.y)\n {\n if (int(mod(n/exp2(p.x + 5.0*p.y), 2.0)) == 1) return 1.0;\n }\n }\n return 0.0;\n}\n\nvoid main()\n{\n vec2 coord = mapCoord(vTextureCoord);\n\n // get the rounded color..\n vec2 pixCoord = pixelate(coord, vec2(pixelSize));\n pixCoord = unmapCoord(pixCoord);\n\n vec4 color = texture2D(uSampler, pixCoord);\n\n // determine the character to use\n float gray = (color.r + color.g + color.b) / 3.0;\n\n float n = 65536.0; // .\n if (gray > 0.2) n = 65600.0; // :\n if (gray > 0.3) n = 332772.0; // *\n if (gray > 0.4) n = 15255086.0; // o\n if (gray > 0.5) n = 23385164.0; // &\n if (gray > 0.6) n = 15252014.0; // 8\n if (gray > 0.7) n = 13199452.0; // @\n if (gray > 0.8) n = 11512810.0; // #\n\n // get the mod..\n vec2 modd = getMod(coord, vec2(pixelSize));\n\n gl_FragColor = color * character( n, vec2(-1.0) + modd * 2.0);\n\n}\n")||this;return t.size=e,t}function D(e){var t=ge.call(this,f,"uniform sampler2D uSampler;\nvarying vec2 vTextureCoord;\n\nuniform sampler2D bloomTexture;\nuniform float bloomScale;\nuniform float brightness;\n\nvoid main() {\n vec4 color = texture2D(uSampler, vTextureCoord);\n color.rgb *= brightness;\n vec4 bloomColor = vec4(texture2D(bloomTexture, vTextureCoord).rgb, 0.0);\n bloomColor.rgb *= bloomScale;\n gl_FragColor = color + bloomColor;\n}\n")||this,e=(t.bloomScale=1,t.brightness=1,t._resolution=u.settings.FILTER_RESOLUTION,"number"==typeof e&&(e={threshold:e}),Object.assign(D.defaults,e)),r=(t.bloomScale=e.bloomScale,t.brightness=e.brightness,e.kernels),i=e.blur,n=e.quality,o=e.pixelSize,a=e.resolution;return t._extractFilter=new we(e.threshold),t._extractFilter.resolution=a,t._blurFilter=r?new p(r):new p(i,n),t.pixelSize=o,t.resolution=a,t}function L(e,t,r){void 0===e&&(e=4),void 0===t&&(t=3);var i=ve.call(this,f,(r=void 0===r?!1:r)?"\nvarying vec2 vTextureCoord;\nuniform sampler2D uSampler;\n\nuniform vec2 uOffset;\nuniform vec4 filterClamp;\n\nvoid main(void)\n{\n vec4 color = vec4(0.0);\n\n // Sample top left pixel\n color += texture2D(uSampler, clamp(vec2(vTextureCoord.x - uOffset.x, vTextureCoord.y + uOffset.y), filterClamp.xy, filterClamp.zw));\n\n // Sample top right pixel\n color += texture2D(uSampler, clamp(vec2(vTextureCoord.x + uOffset.x, vTextureCoord.y + uOffset.y), filterClamp.xy, filterClamp.zw));\n\n // Sample bottom right pixel\n color += texture2D(uSampler, clamp(vec2(vTextureCoord.x + uOffset.x, vTextureCoord.y - uOffset.y), filterClamp.xy, filterClamp.zw));\n\n // Sample bottom left pixel\n color += texture2D(uSampler, clamp(vec2(vTextureCoord.x - uOffset.x, vTextureCoord.y - uOffset.y), filterClamp.xy, filterClamp.zw));\n\n // Average\n color *= 0.25;\n\n gl_FragColor = color;\n}\n":"\nvarying vec2 vTextureCoord;\nuniform sampler2D uSampler;\n\nuniform vec2 uOffset;\n\nvoid main(void)\n{\n vec4 color = vec4(0.0);\n\n // Sample top left pixel\n color += texture2D(uSampler, vec2(vTextureCoord.x - uOffset.x, vTextureCoord.y + uOffset.y));\n\n // Sample top right pixel\n color += texture2D(uSampler, vec2(vTextureCoord.x + uOffset.x, vTextureCoord.y + uOffset.y));\n\n // Sample bottom right pixel\n color += texture2D(uSampler, vec2(vTextureCoord.x + uOffset.x, vTextureCoord.y - uOffset.y));\n\n // Sample bottom left pixel\n color += texture2D(uSampler, vec2(vTextureCoord.x - uOffset.x, vTextureCoord.y - uOffset.y));\n\n // Average\n color *= 0.25;\n\n gl_FragColor = color;\n}")||this;return i._kernels=[],i._blur=4,i._quality=3,i.uniforms.uOffset=new Float32Array(2),i._pixelSize=new l.Point,i.pixelSize=1,i._clamp=r,Array.isArray(e)?i.kernels=e:(i._blur=e,i.quality=t),i}function ht(e){void 0===e&&(e=.5);var t=ye.call(this,f,"\nuniform sampler2D uSampler;\nvarying vec2 vTextureCoord;\n\nuniform float threshold;\n\nvoid main() {\n vec4 color = texture2D(uSampler, vTextureCoord);\n\n // A simple & fast algorithm for getting brightness.\n // It's inaccuracy , but good enought for this feature.\n float _max = max(max(color.r, color.g), color.b);\n float _min = min(min(color.r, color.g), color.b);\n float brightness = (_max + _min) * 0.5;\n\n if(brightness > threshold) {\n gl_FragColor = color;\n } else {\n gl_FragColor = vec4(0.0, 0.0, 0.0, 0.0);\n }\n}\n")||this;return t.threshold=e,t}function ct(e){var t=be.call(this,f,"varying vec2 vTextureCoord;\nuniform sampler2D uSampler;\n\nuniform float gamma;\nuniform float contrast;\nuniform float saturation;\nuniform float brightness;\nuniform float red;\nuniform float green;\nuniform float blue;\nuniform float alpha;\n\nvoid main(void)\n{\n vec4 c = texture2D(uSampler, vTextureCoord);\n\n if (c.a > 0.0) {\n c.rgb /= c.a;\n\n vec3 rgb = pow(c.rgb, vec3(1. / gamma));\n rgb = mix(vec3(.5), mix(vec3(dot(vec3(.2125, .7154, .0721), rgb)), rgb, saturation), contrast);\n rgb.r *= red;\n rgb.g *= green;\n rgb.b *= blue;\n c.rgb = rgb * brightness;\n\n c.rgb *= c.a;\n }\n\n gl_FragColor = c * alpha;\n}\n")||this;return t.gamma=1,t.saturation=1,t.contrast=1,t.brightness=1,t.red=1,t.green=1,t.blue=1,t.alpha=1,Object.assign(t,e),t}return e.AdjustmentFilter=Te,e.AdvancedBloomFilter=Ee,e.AsciiFilter=Se,e.BevelFilter=Ae,e.BloomFilter=ke,e.BulgePinchFilter=Oe,e.CRTFilter=De,e.ColorMapFilter=Pe,e.ColorOverlayFilter=Re,e.ColorReplaceFilter=Ce,e.ConvolutionFilter=Me,e.CrossHatchFilter=Ie,e.DotFilter=Le,e.DropShadowFilter=Fe,e.EmbossFilter=Ne,e.GlitchFilter=ze,e.GlowFilter=Be,e.GodrayFilter=je,e.KawaseBlurFilter=p,e.MotionBlurFilter=Ue,e.MultiColorReplaceFilter=Ge,e.OldFilmFilter=Xe,e.OutlineFilter=He,e.PixelateFilter=Ye,e.RGBSplitFilter=Ve,e.RadialBlurFilter=We,e.ReflectionFilter=qe,e.ShockwaveFilter=Ke,e.SimpleLightmapFilter=Je,e.TiltShiftAxisFilter=Ze,e.TiltShiftFilter=et,e.TiltShiftXFilter=Qe,e.TiltShiftYFilter=$e,e.TwistFilter=tt,e.ZoomBlurFilter=rt,Object.defineProperty(e,"__esModule",{value:!0}),e}({},PIXI,PIXI,PIXI,PIXI.utils,PIXI,PIXI.filters,PIXI.filters),_gsScope=(Object.assign(PIXI.filters,__filters),this.PIXI=this.PIXI||{},!function(l,m){"use strict";u.createList=function(e){if("list"in e){var t=e.list,r=void 0,i=t[0],n=i.value,i=i.time,i=r=new u("string"==typeof n?l.ParticleUtils.hexToRGB(n):n,i,e.ease);if(2a.time;)n=a,a=e[++o];var l=(l-n.time)/(a.time-n.time),u=f.hexToRGB(n.value),h=f.hexToRGB(a.value),h={r:(h.r-u.r)*l+u.r,g:(h.g-u.g)*l+u.g,b:(h.b-u.b)*l+u.b};i.next=new c(h,s/t),i=i.next}return r};var i=function(e,t){return(i=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])})(e,t)};function r(e,t){function r(){this.constructor=e}i(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)}function n(e){return this.ease&&(e=this.ease(e)),(this.next.value-this.current.value)*e+this.current.value}function o(e){this.ease&&(e=this.ease(e));var t=this.current.value,r=this.next.value,i=(r.r-t.r)*e+t.r,n=(r.g-t.g)*e+t.g,r=(r.b-t.b)*e+t.b;return l.ParticleUtils.combineRGBComponents(i,n,r)}function a(e){for(this.ease&&(e=this.ease(e));e>this.next.time;)this.current=this.next,this.next=this.next.next;return e=(e-this.current.time)/(this.next.time-this.current.time),(this.next.value-this.current.value)*e+this.current.value}function s(e){for(this.ease&&(e=this.ease(e));e>this.next.time;)this.current=this.next,this.next=this.next.next;e=(e-this.current.time)/(this.next.time-this.current.time);var t=this.current.value,r=this.next.value,i=(r.r-t.r)*e+t.r,n=(r.g-t.g)*e+t.g,r=(r.b-t.b)*e+t.b;return l.ParticleUtils.combineRGBComponents(i,n,r)}function p(e){for(this.ease&&(e=this.ease(e));this.next&&e>this.next.time;)this.current=this.next,this.next=this.next.next;return this.current.value}function d(e){for(this.ease&&(e=this.ease(e));this.next&&e>this.next.time;)this.current=this.next,this.next=this.next.next;var t=this.current.value;return l.ParticleUtils.combineRGBComponents(t.r,t.g,t.b)}g.prototype.reset=function(e){this.current=e,this.next=e.next,this.next&&1<=this.next.time?this.interpolate=this.isColor?o:n:e.isStepped?this.interpolate=this.isColor?d:p:this.interpolate=this.isColor?s:a,this.ease=this.current.ease};var _=g;function g(e){void 0===e&&(e=!1),this.current=null,this.next=null,this.isColor=!!e,this.interpolate=null,this.ease=null}r(b,v=m.Sprite),b.prototype.init=function(){this.age=0,this.velocity.x=this.speedList.current.value*this.speedMultiplier,this.velocity.y=0,l.ParticleUtils.rotatePoint(this.rotation,this.velocity),this.noRotation?this.rotation=0:this.rotation*=l.ParticleUtils.DEG_TO_RADS,this.rotationSpeed*=l.ParticleUtils.DEG_TO_RADS,this.rotationAcceleration*=l.ParticleUtils.DEG_TO_RADS,this.alpha=this.alphaList.current.value,this.scale.x=this.scale.y=this.scaleList.current.value,this._doAlpha=!!this.alphaList.current.next,this._doSpeed=!!this.speedList.current.next,this._doScale=!!this.scaleList.current.next,this._doColor=!!this.colorList.current.next,this._doAcceleration=0!==this.acceleration.x||0!==this.acceleration.y,this._doNormalMovement=this._doSpeed||0!==this.speedList.current.value||this._doAcceleration,this._oneOverLife=1/this.maxLife;var e=this.colorList.current.value;this.tint=l.ParticleUtils.combineRGBComponents(e.r,e.g,e.b),this.visible=!0},b.prototype.applyArt=function(e){this.texture=e||m.Texture.EMPTY},b.prototype.update=function(e){var t,r,i,n,o,a;return this.age+=e,this.age>=this.maxLife||this.age<0?(this.kill(),-1):(t=this.age*this._oneOverLife,this.ease&&(t=4===this.ease.length?this.ease(t,0,1,1):this.ease(t)),this._doAlpha&&(this.alpha=this.alphaList.interpolate(t)),this._doScale&&(r=this.scaleList.interpolate(t)*this.scaleMultiplier,this.scale.x=this.scale.y=r),this._doNormalMovement&&(o=r=void 0,o=this._doSpeed?(i=this.speedList.interpolate(t)*this.speedMultiplier,l.ParticleUtils.normalize(this.velocity),l.ParticleUtils.scaleBy(this.velocity,i),r=this.velocity.x*e,this.velocity.y*e):this._doAcceleration?(i=this.velocity.x,n=this.velocity.y,this.velocity.x+=this.acceleration.x*e,this.velocity.y+=this.acceleration.y*e,this.maxSpeed&&(a=l.ParticleUtils.length(this.velocity))>this.maxSpeed&&l.ParticleUtils.scaleBy(this.velocity,this.maxSpeed/a),r=(i+this.velocity.x)/2*e,(n+this.velocity.y)/2*e):(r=this.velocity.x*e,this.velocity.y*e),this.position.x+=r,this.position.y+=o),this._doColor&&(this.tint=this.colorList.interpolate(t)),0!==this.rotationAcceleration?(a=this.rotationSpeed+this.rotationAcceleration*e,this.rotation+=(this.rotationSpeed+a)/2*e,this.rotationSpeed=a):0!==this.rotationSpeed?this.rotation+=this.rotationSpeed*e:this.acceleration&&!this.noRotation&&(this.rotation=Math.atan2(this.velocity.y,this.velocity.x)),t)},b.prototype.kill=function(){this.emitter.recycle(this)},b.prototype.destroy=function(){this.parent&&this.parent.removeChild(this),this.Sprite_destroy(),this.emitter=this.velocity=this.colorList=this.scaleList=this.alphaList=this.speedList=this.ease=this.next=this.prev=null},b.parseArt=function(e){for(var t=e.length;0<=t;--t)"string"==typeof e[t]&&(e[t]=h(e[t]));if(l.ParticleUtils.verbose)for(t=e.length-1;0=this.maxParticles);else{var l=void 0,l=this.minLifetime===this.maxLifetime?this.minLifetime:Math.random()*(this.maxLifetime-this.minLifetime)+this.minLifetime;if(-this._spawnTimer=this.spawnChance||(f=void 0,this._poolFirst?(f=this._poolFirst,this._poolFirst=this._poolFirst.next,f.next=null):f=new this.particleConstructor(this),1=this.particleImages.length)&&(this._currentImageIndex=0)):f.applyArt(this.particleImages[Math.floor(Math.random()*this.particleImages.length)]):f.applyArt(this.particleImages[0]),f.alphaList.reset(this.startAlpha),1!==this.minimumSpeedMultiplier&&(f.speedMultiplier=Math.random()*(1-this.minimumSpeedMultiplier)+this.minimumSpeedMultiplier),f.speedList.reset(this.startSpeed),f.acceleration.x=this.acceleration.x,f.acceleration.y=this.acceleration.y,f.maxSpeed=this.maxSpeed,1!==this.minimumScaleMultiplier&&(f.scaleMultiplier=Math.random()*(1-this.minimumScaleMultiplier)+this.minimumScaleMultiplier),f.scaleList.reset(this.startScale),f.colorList.reset(this.startColor),this.minRotationSpeed===this.maxRotationSpeed?f.rotationSpeed=this.minRotationSpeed:f.rotationSpeed=Math.random()*(this.maxRotationSpeed-this.minRotationSpeed)+this.minRotationSpeed,f.rotationAcceleration=this.rotationAcceleration,f.noRotation=this.noRotation,f.maxLife=l,f.blendMode=this.particleBlendMode,f.ease=this.customEase,f.extraData=this.extraData,this.applyAdditionalProperties(f),this._spawnFunc(f,h,c,p),f.init(),this.addAtBack?this._parent.addChildAt(f,0):this._parent.addChild(f),this._activeParticlesLast?((this._activeParticlesLast.next=f).prev=this._activeParticlesLast,this._activeParticlesLast=f):this._activeParticlesLast=this._activeParticlesFirst=f,++this.particleCount,f.update(-this._spawnTimer))}}this._spawnTimer+=this._frequency}this._posChanged&&(this._prevEmitterPos.x=a,this._prevEmitterPos.y=s,this._prevPosIsValid=!0,this._posChanged=!1),this._emit||this._activeParticlesFirst||(this._completeCallback&&(o=this._completeCallback,this._completeCallback=null,o()),this._destroyWhenComplete&&this.destroy())}},S.prototype.applyAdditionalProperties=function(e){},S.prototype._spawnPoint=function(e,t,r){this.minStartRotation===this.maxStartRotation?e.rotation=this.minStartRotation+this.rotation:e.rotation=Math.random()*(this.maxStartRotation-this.minStartRotation)+this.minStartRotation+this.rotation,e.position.x=t,e.position.y=r},S.prototype._spawnRect=function(e,t,r){this.minStartRotation===this.maxStartRotation?e.rotation=this.minStartRotation+this.rotation:e.rotation=Math.random()*(this.maxStartRotation-this.minStartRotation)+this.minStartRotation+this.rotation,E.x=Math.random()*this.spawnRect.width+this.spawnRect.x,E.y=Math.random()*this.spawnRect.height+this.spawnRect.y,0!==this.rotation&&l.ParticleUtils.rotatePoint(this.rotation,E),e.position.x=t+E.x,e.position.y=r+E.y},S.prototype._spawnCircle=function(e,t,r){this.minStartRotation===this.maxStartRotation?e.rotation=this.minStartRotation+this.rotation:e.rotation=Math.random()*(this.maxStartRotation-this.minStartRotation)+this.minStartRotation+this.rotation,E.x=Math.random()*this.spawnCircle.radius,E.y=0,l.ParticleUtils.rotatePoint(360*Math.random(),E),E.x+=this.spawnCircle.x,E.y+=this.spawnCircle.y,0!==this.rotation&&l.ParticleUtils.rotatePoint(this.rotation,E),e.position.x=t+E.x,e.position.y=r+E.y},S.prototype._spawnRing=function(e,t,r){var i=this.spawnCircle,i=(this.minStartRotation===this.maxStartRotation?e.rotation=this.minStartRotation+this.rotation:e.rotation=Math.random()*(this.maxStartRotation-this.minStartRotation)+this.minStartRotation+this.rotation,i.minRadius!==i.radius?E.x=Math.random()*(i.radius-i.minRadius)+i.minRadius:E.x=i.radius,E.y=0,360*Math.random());e.rotation+=i,l.ParticleUtils.rotatePoint(i,E),E.x+=this.spawnCircle.x,E.y+=this.spawnCircle.y,0!==this.rotation&&l.ParticleUtils.rotatePoint(this.rotation,E),e.position.x=t+E.x,e.position.y=r+E.y},S.prototype._spawnPolygonalChain=function(e,t,r){this.minStartRotation===this.maxStartRotation?e.rotation=this.minStartRotation+this.rotation:e.rotation=Math.random()*(this.maxStartRotation-this.minStartRotation)+this.minStartRotation+this.rotation,this.spawnPolygonalChain.getRandomPoint(E),0!==this.rotation&&l.ParticleUtils.rotatePoint(this.rotation,E),e.position.x=t+E.x,e.position.y=r+E.y},S.prototype._spawnBurst=function(e,t,r,i){0===this.particleSpacing?e.rotation=360*Math.random():e.rotation=this.angleStart+this.particleSpacing*i+this.rotation,e.position.x=t,e.position.y=r},S.prototype.cleanup=function(){for(var e,t=this._activeParticlesFirst;t;t=e)e=t.next,this.recycle(t),t.parent&&t.parent.removeChild(t);this._activeParticlesFirst=this._activeParticlesLast=null,this.particleCount=0},S.prototype.destroy=function(){var e;this.autoUpdate=!1,this.cleanup();for(var t=this._poolFirst;t;t=e)e=t.next,t.destroy();this._poolFirst=this._parent=this.particleImages=this.spawnPos=this.ownerPos=this.startColor=this.startScale=this.startAlpha=this.startSpeed=this.customEase=this._completeCallback=null},S);function S(e,t,r){this._currentImageIndex=-1,this._particleConstructor=y,this.particleImages=null,this.startAlpha=null,this.startSpeed=null,this.minimumSpeedMultiplier=1,this.acceleration=null,this.maxSpeed=NaN,this.startScale=null,this.minimumScaleMultiplier=1,this.startColor=null,this.minLifetime=0,this.maxLifetime=0,this.minStartRotation=0,this.maxStartRotation=0,this.noRotation=!1,this.minRotationSpeed=0,this.maxRotationSpeed=0,this.particleBlendMode=0,this.customEase=null,this.extraData=null,this._frequency=1,this.spawnChance=1,this.maxParticles=1e3,this.emitterLifetime=-1,this.spawnPos=null,this.spawnType=null,this._spawnFunc=null,this.spawnRect=null,this.spawnCircle=null,this.spawnPolygonalChain=null,this.particlesPerWave=1,this.particleSpacing=0,this.angleStart=0,this.rotation=0,this.ownerPos=null,this._prevEmitterPos=null,this._prevPosIsValid=!1,this._posChanged=!1,this._parent=null,this.addAtBack=!1,this.particleCount=0,this._emit=!1,this._spawnTimer=0,this._emitterLife=-1,this._activeParticlesFirst=null,this._activeParticlesLast=null,this._poolFirst=null,this._origConfig=null,this._origArt=null,this._autoUpdate=!1,this._currentImageIndex=-1,this._destroyWhenComplete=!1,this._completeCallback=null,this.parent=e,t&&r&&this.init(t,r),this.recycle=this.recycle,this.update=this.update,this.rotate=this.rotate,this.updateSpawnPos=this.updateSpawnPos,this.updateOwnerPos=this.updateOwnerPos}var A=new m.Point,k=["pow","sqrt","abs","floor","round","ceil","E","PI","sin","cos","tan","asin","acos","atan","atan2","log"],O=new RegExp(["[01234567890\\.\\*\\-\\+\\/\\(\\)x ,]"].concat(k).join("|"),"g");r(C,P=y),C.prototype.init=function(){this.initialRotation=this.rotation,this.Particle_init(),this.path=this.extraData.path,this._doNormalMovement=!this.path,this.movement=0,this.initialPosition.x=this.position.x,this.initialPosition.y=this.position.y},C.prototype.update=function(e){var t,r=this.Particle_update(e);return 0<=r&&this.path&&(t=this._doSpeed?this.speedList.interpolate(r)*this.speedMultiplier:this.speedList.current.value*this.speedMultiplier,this.movement+=t*e,A.x=this.movement,A.y=this.path(this.movement),l.ParticleUtils.rotatePoint(this.initialRotation,A),this.position.x=this.initialPosition.x+A.x,this.position.y=this.initialPosition.y+A.y),r},C.prototype.destroy=function(){this.Particle_destroy(),this.path=this.initialPosition=null},C.parseArt=function(e){return y.parseArt(e)},C.parseData=function(e){var t={};if(e&&e.path)try{t.path=function(e){for(var t=e.match(O),r=t.length-1;0<=r;--r)0<=k.indexOf(t[r])&&(t[r]="Math."+t[r]);return e=t.join(""),new Function("x","return "+e+";")}(e.path)}catch(e){l.ParticleUtils.verbose&&console.error("PathParticle: error in parsing path expression"),t.path=null}else l.ParticleUtils.verbose&&console.error("PathParticle requires a path string in extraData!"),t.path=null;return t};var P,R=C;function C(e){e=P.call(this,e)||this;return e.path=null,e.initialRotation=0,e.initialPosition=new m.Point,e.movement=0,e}r(I,M=y),I.prototype.init=function(){this.Particle_init(),this.elapsed=0,this.framerate<0&&(this.duration=this.maxLife,this.framerate=this.textures.length/this.duration)},I.prototype.applyArt=function(e){this.textures=e.textures,this.framerate=e.framerate,this.duration=e.duration,this.loop=e.loop},I.prototype.update=function(e){var t=this.Particle_update(e);return 0<=t&&(this.elapsed+=e,this.elapsed>=this.duration&&(this.loop?this.elapsed=this.elapsed%this.duration:this.elapsed=this.duration-1e-6),e=this.elapsed*this.framerate+1e-7|0,this.texture=this.textures[e]||this.textures[this.textures.length-1]||m.Texture.EMPTY),t},I.prototype.destroy=function(){this.Particle_destroy(),this.textures=null},I.parseArt=function(e){for(var t=[],r=0;rthis._childCount)throw new Error("addChildAt: The index "+t+" supplied is out of bounds "+this._childCount);e.parent&&e.parent.removeChild(e),(e.parent=this).sortDirty=!0,e.transform._parentID=-1;var r=e;if(this._firstChild)if(0===t)(this._firstChild.prevChild=r).nextChild=this._firstChild,this._firstChild=r;else if(t===this._childCount)(this._lastChild.nextChild=r).prevChild=this._lastChild,this._lastChild=r;else{for(var i=0,n=this._firstChild;i=this._childCount)throw new Error("The index "+t+" supplied is out of bounds "+this._childCount);if(e.parent!==this)throw new Error("The supplied DisplayObject must be a child of the caller");if(e.nextChild&&(e.nextChild.prevChild=e.prevChild),e.prevChild&&(e.prevChild.nextChild=e.nextChild),this._firstChild===e&&(this._firstChild=e.nextChild),this._lastChild===e&&(this._lastChild=e.prevChild),e.nextChild=null,e.prevChild=null,this._firstChild)if(0===t)(this._firstChild.prevChild=e).nextChild=this._firstChild,this._firstChild=e;else if(t===this._childCount)(this._lastChild.nextChild=e).prevChild=this._lastChild,this._lastChild=e;else{for(var r=0,i=this._firstChild;r=this._childCount)throw new Error("getChildAt: Index ("+e+") does not exist.");if(0===e)return this._firstChild;if(e===this._childCount)return this._lastChild;for(var t=0,r=this._firstChild;t=s.TRANSFORM_STEP.PROJ?(i||this.displayObjectUpdateTransform(),(this.proj.affine?this.transform.worldTransform:this.proj.world).applyInverse(e,r)):(this.parent?r=this.parent.worldTransform.applyInverse(e,r):(r.x=e.x,r.y=e.y),n===s.TRANSFORM_STEP.NONE?r:this.transform.localTransform.applyInverse(r,r))}get worldTransform(){return this.proj.affine?this.transform.worldTransform:this.proj.world}}const $=Q.prototype.toLocal;class d extends o.Mesh{static __initStatic(){this.defaultVertexShader=`precision highp float; +attribute vec2 aVertexPosition; +attribute vec2 aTextureCoord; + +uniform mat3 projectionMatrix; +uniform mat3 translationMatrix; +uniform mat3 uTextureMatrix; + +varying vec2 vTextureCoord; + +void main(void) +{ +gl_Position.xyw = projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0); +gl_Position.z = 0.0; + +vTextureCoord = (uTextureMatrix * vec3(aTextureCoord, 1.0)).xy; +} +`}static __initStatic2(){this.defaultFragmentShader=` +varying vec2 vTextureCoord; +uniform vec4 uColor; + +uniform sampler2D uSampler; + +void main(void) +{ +gl_FragColor = texture2D(uSampler, vTextureCoord) * uColor; +}`}constructor(e,t,r,i){super(e,t,r,i),d.prototype.__init.call(this),this.proj=new l(this.transform)}__init(){this.vertexData2d=null}calculateVertices(){if(this.proj._affine)this.vertexData2d=null,super.calculateVertices();else{var e=this.geometry,t=e.buffers[0].data;if(e.vertexDirtyId!==this.vertexDirty||this._transformID!==this.transform._worldID){this._transformID=this.transform._worldID,this.vertexData.length!==t.length&&(this.vertexData=new Float32Array(t.length)),this.vertexData2d&&this.vertexData2d.length===3*t.length/2||(this.vertexData2d=new Float32Array(3*t.length));var r=this.proj.world.mat3;const s=this.vertexData2d,l=this.vertexData;for(let e=0;er.call(t,...e)),t=void 0)}return r}([t,"access",e=>e.program,"access",e=>e.uniformData,"optionalAccess",e=>e.translationMatrix])&&(t.uniforms.translationMatrix=this.worldTransform.toArray(!0)),e.shader.bind(t,!1),e.state.set(this.state),e.geometry.bind(this.geometry,t),e.geometry.draw(this.drawMode,this.size,this.start,this.geometry.instanceCount)}toLocal(e,t,r,i,n=s.TRANSFORM_STEP.ALL){return $.call(this,e,t,r,i,n)}get worldTransform(){return this.proj.affine?this.transform.worldTransform:this.proj.world}}d.__initStatic(),d.__initStatic2();class ee extends d{constructor(e,t,r,i,n){super(new o.MeshGeometry(t,r,i),new o.MeshMaterial(e,{program:_.Program.from(d.defaultVertexShader,d.defaultFragmentShader),pluginName:"batch2d"}),null,n),ee.prototype.__init2.call(this),this.geometry.getBuffer("aVertexPosition").static=!1}__init2(){this.autoUpdate=!0}get vertices(){return this.geometry.getBuffer("aVertexPosition").data}set vertices(e){this.geometry.getBuffer("aVertexPosition").data=e}_render(e){this.autoUpdate&&this.geometry.getBuffer("aVertexPosition").update(),super._render(e)}}class m extends t.Sprite{constructor(e){super(e),m.prototype.__init.call(this),this.proj=new l(this.transform),this.pluginName="batch2d"}__init(){this.vertexData2d=null}_calculateBounds(){this.calculateTrimmedVertices(),this._bounds.addQuad(this.vertexTrimmedData)}calculateVertices(){var n=this._texture;if(this.proj._affine)this.vertexData2d=null,super.calculateVertices();else{this.vertexData2d||(this.vertexData2d=new Float32Array(12));var o=this.transform._worldID,a=n._updateID;if(this._transformID!==o||this._textureID!==a){this._textureID!==a&&(this.uvs=n._uvs.uvsFloat32),this._transformID=o,this._textureID=a;o=this.proj.world.mat3;const l=this.vertexData2d,u=this.vertexData;var a=n.trim,n=n.orig,s=this._anchor;let e,t,r,i;r=a?(t=a.x-s._x*n.width,e=t+a.width,(i=a.y-s._y*n.height)+a.height):(t=-s._x*n.width,e=t+n.width,(i=-s._y*n.height)+n.height),l[0]=o[0]*t+o[3]*i+o[6],l[1]=o[1]*t+o[4]*i+o[7],l[2]=o[2]*t+o[5]*i+o[8],l[3]=o[0]*e+o[3]*i+o[6],l[4]=o[1]*e+o[4]*i+o[7],l[5]=o[2]*e+o[5]*i+o[8],l[6]=o[0]*e+o[3]*r+o[6],l[7]=o[1]*e+o[4]*r+o[7],l[8]=o[2]*e+o[5]*r+o[8],l[9]=o[0]*t+o[3]*r+o[6],l[10]=o[1]*t+o[4]*r+o[7],l[11]=o[2]*t+o[5]*r+o[8],u[0]=l[0]/l[2],u[1]=l[1]/l[2],u[2]=l[3]/l[5],u[3]=l[4]/l[5],u[4]=l[6]/l[8],u[5]=l[7]/l[8],u[6]=l[9]/l[11],u[7]=l[10]/l[11]}}}calculateTrimmedVertices(){if(this.proj._affine)super.calculateTrimmedVertices();else{var e=this.transform._worldID,t=this._texture._updateID;if(this.vertexTrimmedData){if(this._transformTrimmedID===e&&this._textureTrimmedID===t)return}else this.vertexTrimmedData=new Float32Array(8);this._transformTrimmedID=e,this._textureTrimmedID=t;e=this._texture;const a=this.vertexTrimmedData;var t=e.orig,e=this.tileProj?this._width:t.width,t=this.tileProj?this._height:t.height,r=this._anchor,i=this.proj.world.mat3,n=-r._x*e,e=n+e,r=-r._y*t,t=r+t,o=1/(i[2]*n+i[5]*r+i[8]);a[0]=o*(i[0]*n+i[3]*r+i[6]),a[1]=o*(i[1]*n+i[4]*r+i[7]),o=1/(i[2]*e+i[5]*r+i[8]),a[2]=o*(i[0]*e+i[3]*r+i[6]),a[3]=o*(i[1]*e+i[4]*r+i[7]),o=1/(i[2]*e+i[5]*t+i[8]),a[4]=o*(i[0]*e+i[3]*t+i[6]),a[5]=o*(i[1]*e+i[4]*t+i[7]),o=1/(i[2]*n+i[5]*t+i[8]),a[6]=o*(i[0]*n+i[3]*t+i[6]),a[7]=o*(i[1]*n+i[4]*t+i[7])}}toLocal(e,t,r,i,n=s.TRANSFORM_STEP.ALL){return $.call(this,e,t,r,i,n)}get worldTransform(){return this.proj.affine?this.transform.worldTransform:this.proj.world}}const te=new p.Transform;class re extends F.TilingSprite{constructor(e,t,r){super(e,t,r),this.tileProj=new l(this.tileTransform),this.tileProj.reverseLocalOrder=!0,this.proj=new l(this.transform),this.pluginName="tilingSprite2d",this.uvRespectAnchor=!0}get worldTransform(){return this.proj.affine?this.transform.worldTransform:this.proj.world}toLocal(e,t,r,i,n=s.TRANSFORM_STEP.ALL){return $.call(this,e,t,r,i,n)}_render(e){var t=this._texture;t&&t.valid&&(this.tileTransform.updateTransform(te),this.uvMatrix.update(),e.batch.setObjectRenderer(e.plugins[this.pluginName]),e.plugins[this.pluginName].render(this))}}function ie(){this.proj||(this.proj=new l(this.transform),this.toLocal=Q.prototype.toLocal,Object.defineProperty(this,"worldTransform",{get:Z,enumerable:!0,configurable:!0}))}e.Container.prototype.convertTo2d=ie,t.Sprite.prototype.convertTo2d=function(){this.proj||(this.calculateVertices=m.prototype.calculateVertices,this.calculateTrimmedVertices=m.prototype.calculateTrimmedVertices,this._calculateBounds=m.prototype._calculateBounds,this.pluginName="batch2d",ie.call(this))},e.Container.prototype.convertSubtreeTo2d=function(){this.convertTo2d();for(let e=0;e vFrame.z || +pixels.y < vFrame.y || pixels.y > vFrame.w) { +uv.x = vTrans1.x * surface2.x + vTrans1.y * surface2.y + vTrans1.z; +uv.y = vTrans2.x * surface2.x + vTrans2.y * surface2.y + vTrans2.z; +pixels = uv * vSamplerSize; + +if (pixels.x < vFrame.x || pixels.x > vFrame.z || + pixels.y < vFrame.y || pixels.y > vFrame.w) { + discard; +} +} + +vec4 edge; +edge.xy = clamp(pixels - vFrame.xy + 0.5, vec2(0.0, 0.0), vec2(1.0, 1.0)); +edge.zw = clamp(vFrame.zw - pixels + 0.5, vec2(0.0, 0.0), vec2(1.0, 1.0)); + +float alpha = 1.0; //edge.x * edge.y * edge.z * edge.w; +vec4 rColor = vColor * alpha; + +float textureId = floor(vTextureId+0.5); +vec2 vTextureCoord = uv; +vec4 color; +%forloop% +gl_FragColor = color * rColor; +}`,geometryClass:_e,vertexSize:16},e);return X=class extends Y{constructor(e){super(e),X.prototype.__init.call(this),X.prototype.__init2.call(this),X.prototype.__init3.call(this),this.shaderGenerator=new _.BatchShaderGenerator(t,r),this.geometryClass=n,this.vertexSize=i}__init(){this.defUniforms={translationMatrix:new p.Matrix,distortion:new Float32Array([0,0,1/0,1/0])}}__init2(){this.size=1e3}__init3(){this.forceMaxTextures=1}getUniforms(e){e=e.proj;return null!==e.surface?e.uniforms:null!==e._activeProjection?e._activeProjection.uniforms:this.defUniforms}packInterleavedGeometry(e,t,r,i,n){const{uint32View:o,float32View:a}=t;var s=i/this.vertexSize,l=e.indices,u=e.vertexData,h=e._texture._frame,c=e.aTrans,{_batchLocation:f,realWidth:p,realHeight:d,resolution:m}=e._texture.baseTexture,t=Math.min(e.worldAlpha,1),_=t<1&&e._texture.baseTexture.alphaMode?g.premultiplyTint(e._tintRGB,t):e._tintRGB+(255*t<<24);for(let e=0;et[e]&&(i=t[e]),ot[e+1]&&(n=t[e+1]),aR[e]&&(l=P[t],P[t]=P[e],P[e]=l,l=R[t],R[t]=R[e],R[e]=l)}t[0]=P[0].x,t[1]=P[0].y,t[2]=P[1].x,t[3]=P[1].y,t[4]=P[2].x,t[5]=P[2].y,t[6]=P[3].x,t[7]=P[3].y,(P[3].x-P[2].x)*(P[1].y-P[2].y)-(P[1].x-P[2].x)*(P[3].y-P[2].y)<0&&(t[4]=P[3].x,t[5]=P[3].y)}}}const ve=new p.Matrix,M=new p.Rectangle,I=new p.Point;class ye extends C{constructor(...e){super(...e),ye.prototype.__init.call(this)}__init(){this.distortion=new p.Point}clear(){this.distortion.set(0,0)}apply(e,t){t=t||new p.Point;var r=this.distortion,i=e.x*e.y;return t.x=e.x+r.x*i,t.y=e.y+r.y*i,t}applyInverse(e,t){t=t||new p.Point;var r=e.x,e=e.y,i=this.distortion.x,n=this.distortion.y;if(0===i)t.x=r,t.y=e/(1+n*r);else if(0===n)t.y=e,t.x=r/(1+i*e);else{var e=.5*(e*i-r*n+1)/n,o=e*e+r/n;if(o<=1e-5)return t.set(NaN,NaN),t;t.x=0>0,0!==h._cycle&&h._cycle===h._totalTime/c&&p<=e&&h._cycle--,h._time=h._totalTime-h._cycle*c,h._yoyo&&0!=(1&h._cycle)&&(h._time=m-h._time,(u=h._yoyoEase||h.vars.yoyoEase)&&(h._yoyoEase||(!0!==u||h._initted?h._yoyoEase=u=!0===u?h._ease:u instanceof Ease?u:Ease.map[u]:(u=h.vars.ease,h._yoyoEase=u=u?u instanceof Ease?u:"function"==typeof u?new Ease(u,h.vars.easeParams):Ease.map[u]||g.defaultEase:g.defaultEase)),h.ratio=u?1-u.getRatio((m-h._time)/m):0)),h._time>m?h._time=m:h._time<0&&(h._time=0)),h._easeType&&!u?(c=h._time/m,(1===(a=h._easeType)||3===a&&.5<=c)&&(c=1-c),3===a&&(c*=2),1===(s=h._easePower)?c*=c:2===s?c*=c*c:3===s?c*=c*c*c:4===s&&(c*=c*c*c*c),h.ratio=1===a?1-c:2===a?c:h._time/m<.5?c/2:1-c/2):u||(h.ratio=h._ease.getRatio(h._time/m))),f!==h._time||r||d!==h._cycle){if(!h._initted){if(h._init(),!h._initted||h._gc)return;if(!r&&h._firstPT&&(!1!==h.vars.lazy&&h._duration||h.vars.lazy&&!h._duration))return h._time=f,h._totalTime=p,h._rawPrevTime=_,h._cycle=d,x.lazyTweens.push(h),void(h._lazy=[e,t]);!h._time||i||u?i&&this._ease._calcEnd&&!u&&(h.ratio=h._ease.getRatio(0===h._time?0:1)):h.ratio=h._ease.getRatio(h._time/m)}for(!1!==h._lazy&&(h._lazy=!1),h._active||!h._paused&&h._time!==f&&0<=e&&(h._active=!0),0===p&&(2===h._initted&&0e._startTime;l._timeline;)u&&l._timeline.smoothChildTiming?l.totalTime(l._totalTime,!0):l._gc&&l._enabled(!0,!1),l=l._timeline;return h},e.remove=function(e){var t;if(e instanceof c)return this._remove(e,!1),t=e._timeline=e.vars.useFrames?c._rootFramesTimeline:c._rootTimeline,e._startTime=(e._paused?e._pauseTime:t._time)-(e._reversed?e.totalDuration()-e._totalTime:e._totalTime)/e._timeScale,this;if(e instanceof Array||e&&e.push&&p(e)){for(var r=e.length;-1<--r;)this.remove(e[r]);return this}return"string"==typeof e?this.removeLabel(e):this.kill(null,e)},e._remove=function(e,t){return f.prototype._remove.call(this,e,t),this._last?this._time>this.duration()&&(this._time=this._duration,this._totalTime=this._totalDuration):this._time=this._totalTime=this._duration=this._totalDuration=0,this},e.append=function(e,t){return this.add(e,this._parseTimeOrLabel(null,t,!0,e))},e.insert=e.insertMultiple=function(e,t,r,i){return this.add(e,t||0,r,i)},e.appendMultiple=function(e,t,r,i){return this.add(e,this._parseTimeOrLabel(null,t,!0,e),r,i)},e.addLabel=function(e,t){return this._labels[e]=this._parseTimeOrLabel(t),this},e.addPause=function(e,t,r,i){r=d.delayedCall(0,n,r,i||this);return r.vars.onComplete=r.vars.onReverseComplete=t,r.data="isPause",this._hasPause=!0,this.add(r,e)},e.removeLabel=function(e){return delete this._labels[e],this},e.getLabelTime=function(e){return null!=this._labels[e]?this._labels[e]:-1},e._parseTimeOrLabel=function(e,t,r,i){var n,o;if(i instanceof c&&i.timeline===this)this.remove(i);else if(i&&(i instanceof Array||i.push&&p(i)))for(o=i.length;-1<--o;)i[o]instanceof c&&i[o].timeline===this&&this.remove(i[o]);if(n="number"!=typeof e||t?99999999999=e&&!l;)i._duration||"isPause"===i.data&&0c._time;)l.render(l._reversed?l.totalDuration()-(e-l._startTime)*l._timeScale:(e-l._startTime)*l._timeScale,t,r),l=l._prev;l=null,c.pause(),c._pauseTime=h}i._reversed?i.render((i._dirty?i.totalDuration():i._totalDuration)-(e-i._startTime)*i._timeScale,t,r):i.render((e-i._startTime)*i._timeScale,t,r)}i=o}!c._onUpdate||t||(b.length&&x(),c._callback("onUpdate")),!a||c._gc||d!==c._startTime&&m===c._timeScale||(0===c._time||p>=c.totalDuration())&&(n&&(b.length&&x(),c._timeline.autoRemoveChildren&&c._enabled(!1,!1),c._active=!1),!t&&c.vars[a]&&c._callback(a))}},e._hasPausedChild=function(){for(var e=this._first;e;){if(e._paused||e instanceof m&&e._hasPausedChild())return!0;e=e._next}return!1},e.getChildren=function(e,t,r,i){i=i||-9999999999;for(var n=[],o=this._first,a=0;o;)o._startTime=r&&(n._startTime+=e),n=n._next;if(t)for(i in o)o[i]>=r&&(o[i]+=e);return this._uncache(!0)},e._kill=function(e,t){if(!e&&!t)return this._enabled(!1,!1);for(var r=t?this.getTweensOf(t):this.getChildren(!0,!0,!1),i=r.length,n=!1;-1<--i;)r[i]._kill(e,t)&&(n=!0);return n},e.clear=function(e){var t=this.getChildren(!1,!0,!0),r=t.length;for(this._time=this._totalTime=0;-1<--r;)t[r]._enabled(!1,!1);return!1!==e&&(this._labels={}),this._uncache(!0)},e.invalidate=function(){for(var e=this._first;e;)e.invalidate(),e=e._next;return c.prototype.invalidate.call(this)},e._enabled=function(e,t){if(e===this._gc)for(var r=this._first;r;)r._enabled(e,!0),r=r._next;return f.prototype._enabled.call(this,e,t)},e.totalTime=function(e,t,r){this._forcingPlayhead=!0;var i=c.prototype.totalTime.apply(this,arguments);return this._forcingPlayhead=!1,i},e.duration=function(e){return arguments.length?(0!==this.duration()&&0!==e&&this.timeScale(this._duration/e),this):(this._dirty&&this.totalDuration(),this._duration)},e.totalDuration=function(e){if(arguments.length)return e&&this.totalDuration()?this.timeScale(this._totalDuration/e):this;if(this._dirty){for(var t,r,i=0,n=this,o=n._last,a=999999999999;o;)t=o._prev,o._dirty&&o.totalDuration(),o._startTime>a&&n._sortChildren&&!o._paused&&!n._calculatingDuration?(n._calculatingDuration=1,n.add(o,o._startTime-o._delay),n._calculatingDuration=0):a=o._startTime,o._startTime<0&&!o._paused&&(i-=o._startTime,n._timeline.smoothChildTiming&&(n._startTime+=o._startTime/n._timeScale,n._time-=o._startTime,n._totalTime-=o._startTime,n._rawPrevTime-=o._startTime),n.shiftChildren(-o._startTime,!1,-9999999999),a=0),i<(r=o._startTime+o._totalDuration/o._timeScale)&&(i=r),o=t;n._duration=n._totalDuration=i,n._dirty=!1}return this._totalDuration},e.paused=function(e){if(!1===e&&this._paused)for(var t=this._first;t;)t._startTime===this._time&&"isPause"===t.data&&(t._rawPrevTime=0),t=t._next;return c.prototype.paused.apply(this,arguments)},e.usesFrames=function(){for(var e=this._timeline;e._timeline;)e=e._timeline;return e===c._rootFramesTimeline},e.rawTime=function(e){return e&&(this._paused||this._repeat&&0>0,c._cycle&&c._cycle===c._totalTime/x&&m<=e&&c._cycle--,c._time=c._totalTime-c._cycle*x,c._yoyo&&1&c._cycle&&(c._time=d-c._time),c._time>d?e=(c._time=d)+1e-4:c._time<0?c._time=e=0:e=c._time));if(c._hasPause&&!c._forcingPlayhead&&!t){if(f<(e=c._time)||c._repeat&&b!==c._cycle)for(i=c._first;i&&i._startTime<=e&&!l;)i._duration||"isPause"!==i.data||i.ratio||0===i._startTime&&0===c._rawPrevTime||(l=i),i=i._next;else for(i=c._last;i&&i._startTime>=e&&!l;)i._duration||"isPause"===i.data&&0c._time;)l.render(l._reversed?l.totalDuration()-(e-l._startTime)*l._timeScale:(e-l._startTime)*l._timeScale,t,r),l=l._prev;l=null,c.pause(),c._pauseTime=h}i._reversed?i.render((i._dirty?i.totalDuration():i._totalDuration)-(e-i._startTime)*i._timeScale,t,r):i.render((e-i._startTime)*i._timeScale,t,r)}i=o}!c._onUpdate||t||(O.length&&P(),c._callback("onUpdate")),!a||c._locked||c._gc||_!==c._startTime&&g===c._timeScale||(0===c._time||p>=c.totalDuration())&&(n&&(O.length&&P(),c._timeline.autoRemoveChildren&&c._enabled(!1,!1),c._active=!1),!t&&c.vars[a]&&c._callback(a))}else m!==c._totalTime&&c._onUpdate&&!t&&c._callback("onUpdate")},i.getActive=function(e,t,r){for(var i,n=[],o=this.getChildren(e||null==e,t||null==e,!!r),a=0,s=o.length,l=0;le)return t[i].name;return null},i.getLabelBefore=function(e){null==e&&(e=this._time);for(var t=this.getLabelsArray(),r=t.length;-1<--r;)if(t[r].time>0||6)-1,c=[],f=[];for(r in e){x=b=y=v=x=g=_=m=d=p=y=A=S=void 0;for(var p,d,m,_,g,v,y,b,x,T=e[r],w=a,E=t,S=1/E,A=T.length;-1<--A;)for(d=(b=T[A]).a,m=b.d-d,_=b.c-d,g=b.b-d,p=0,v=1;v<=E;v++)y=p-(p=((x=S*v)*x*m+3*(y=1-x)*(x*_+y*g))*x),w[x=A*E+v-1]=(w[x]||0)+y*y}for(n=a.length,i=0;i>0]=f,s[o]=u,l=0,f=[]);return{length:u,lengths:s,segments:c}}(this._beziers,this._timeRes),this._length=h.length,this._lengths=h.lengths,this._segments=h.segments,this._l1=this._li=this._s1=this._si=0,this._l2=this._lengths[0],this._curSeg=this._segments[0],this._s2=this._curSeg[0],this._prec=1/this._curSeg.length),c=this._autoRotate)for(this._initialRotations=[],c[0]instanceof Array||(this._autoRotate=c=[c]),o=c.length;-1<--o;){for(a=0;a<3;a++)i=c[o][a],this._func[i]="function"==typeof e[i]&&e[i.indexOf("set")||"function"!=typeof e["get"+i.substr(3)]?i:"get"+i.substr(3)];i=c[o][2],this._initialRotations[o]=(this._func[i]?this._func[i].call(this._target):this._target[i])||0,this._overwriteProps.push(i)}return this._startRatio=r.vars.runBackwards?1:0,!0},set:function(e){var t,r,i,n,o,a,s,l,u,h,c=this._segCount,f=this._func,p=this._target,d=e!==this._startRatio;if(this._timeRes){if(l=this._lengths,u=this._curSeg,h=e*this._length,w=this._li,h>this._l2&&w=h;);0===w&&hthis._s2&&w=h;);0===w&&h>0)*(1/c))*c;for(r=1-o,w=this._props.length;-1<--w;)i=this._props[w],a=(o*o*(n=this._beziers[i][t]).da+3*r*(o*n.ca+r*n.ba))*o+n.a,this._mod[i]&&(a=this._mod[i](a,p)),f[i]?p[i](a):p[i]=a;if(this._autoRotate)for(var m,_,g,v,y,b,x,T=this._autoRotate,w=T.length;-1<--w;)i=T[w][2],b=T[w][3]||0,x=!0===T[w][4]?1:E,n=this._beziers[T[w][0]],m=this._beziers[T[w][1]],n&&m&&(n=n[t],m=m[t],_=n.a+(n.b-n.a)*o,_+=((v=n.b+(n.c-n.b)*o)-_)*o,v+=(n.c+(n.d-n.c)*o-v)*o,g=m.a+(m.b-m.a)*o,g+=((y=m.b+(m.c-m.b)*o)-g)*o,y+=(m.c+(m.d-m.c)*o-y)*o,a=d?Math.atan2(y-g,v-_)*x+b:this._initialRotations[w],this._mod[i]&&(a=this._mod[i](a,p)),f[i]?p[i](a):p[i]=a)}}),e=_.prototype,_.bezierThrough=f,_.cubicToQuadratic=j,_._autoCSS=!0,_.quadraticToCubic=function(e,t,r){return new B(e,(2*t+e)/3,(2*t+r)/3,r)},_._cssRegister=function(){var p,d,m,e=t.CSSPlugin;e&&(e=e._internals,p=e._parseToProxy,d=e._setPluginRatio,m=e.CSSPropTween,e._registerComplexSpecialProp("bezier",{parser:function(e,t,r,i,n,o){t instanceof Array&&(t={values:t}),o=new _;var a,s,l,u=t.values,h=u.length-1,c=[],f={};if(!(h<0)){for(a=0;a<=h;a++)l=p(e,u[a],i,n,o,h!==a),c[a]=l.end;for(s in t)f[s]=t[s];f.values=c,(n=new m(e,"bezier",0,0,l.pt,2)).data=l,n.plugin=o,n.setRatio=d,0===f.autoRotate&&(f.autoRotate=!0),!f.autoRotate||f.autoRotate instanceof Array||(a=!0===f.autoRotate?0:Number(f.autoRotate),f.autoRotate=null!=l.end.left?[["left","top","rotation",a,!1]]:null!=l.end.x&&[["x","y","rotation",a,!1]]),f.autoRotate&&(i._transform||i._enableTransforms(!1),l.autoRotate=i._target._gsTransform,l.proxy.rotation=l.autoRotate.rotation||0,i._overwriteProps.push("rotation")),o._onInitTween(l.proxy,f,i._tween)}return n}}))},e._mod=function(e){for(var t,r=this._overwriteProps,i=r.length;-1<--i;)(t=e[r[i]])&&"function"==typeof t&&(this._mod[r[i]]=t)},e._kill=function(e){var t,r,i=this._props;for(t in this._beziers)if(t in e)for(delete this._beziers[t],delete this._func[t],r=i.length;-1<--r;)i[r]===t&&i.splice(r,1);if(i=this._autoRotate)for(r=i.length;-1<--r;)e[i[r][2]]&&i.splice(r,1);return this._super._kill.call(this,e)},_gsScope._gsDefine("plugins.CSSPlugin",["plugins.TweenPlugin","TweenLite"],function(a,R){function C(){a.call(this,"css"),this._overwriteProps.length=0,this.setRatio=C.prototype.setRatio}function s(e,t){return t.toUpperCase()}function l(e,t){return(t=L.createElementNS?L.createElementNS(t||"http://www.w3.org/1999/xhtml",e):L.createElement(e)).style?t:L.createElement(e)}function u(e){return ne.test("string"==typeof e?e:(e.currentStyle||e.style).filter||"")?parseFloat(RegExp.$1)/100:1}function _(e){_gsScope.console&&console.log(e)}function T(e,t){var r,i,n=(t=t||F).style;if(void 0!==n[e])return e;for(e=e.charAt(0).toUpperCase()+e.substr(1),r=["O","Moz","ms","Ms","Webkit"],i=5;-1<--i&&void 0===n[r[i]+e];);return 0<=i?(ve="-"+(ye=3===i?"ms":r[i]).toLowerCase()+"-",ye+e):null}function d(e){return be.getComputedStyle(e)}function f(e,t){var r,i,n={};if(t=t||d(e))if(r=t.length)for(;-1<--r;)-1!==(i=t[r]).indexOf("-transform")&&Ge!==i||(n[i.replace(ue,s)]=t.getPropertyValue(i));else for(r in t)-1!==r.indexOf("Transform")&&H!==r||(n[r]=t[r]);else if(t=e.currentStyle||e.style)for(r in t)"string"==typeof r&&void 0===n[r]&&(n[r.replace(ue,s)]=t[r]);return N||(n.opacity=u(e)),e=Je(e,t,!1),n.rotation=e.rotation,n.skewX=e.skewX,n.scaleX=e.scaleX,n.scaleY=e.scaleY,n.x=e.x,n.y=e.y,Y&&(n.z=e.z,n.rotationX=e.rotationX,n.rotationY=e.rotationY,n.scaleZ=e.scaleZ),n.filters&&delete n.filters,n}function g(e,t,r,i,n){var o,a,s,l={},u=e.style;for(a in r)"cssText"===a||"length"!==a&&isNaN(a)&&(t[a]!==(o=r[a])||n&&n[a])&&-1===a.indexOf("Origin")&&("number"==typeof o||"string"==typeof o)&&(l[a]="auto"!==o||"left"!==a&&"top"!==a?""!==o&&"auto"!==o&&"none"!==o||"string"!=typeof t[a]||""===t[a].replace(re,"")?o:0:xe(e,a),void 0!==u[a]&&(s=new Oe(u,a,u[a],s)));if(i)for(a in i)"className"!==a&&(l[a]=i[a]);return{difs:l,firstMPT:s}}function A(e,t){return"string"==typeof(e="function"==typeof e?e(P,O):e)&&"="===e.charAt(1)?parseInt(e.charAt(0)+"1",10)*parseFloat(e.substr(2)):parseFloat(e)-parseFloat(t)||0}function E(e,t){var r="string"==typeof(e="function"==typeof e?e(P,O):e)&&"="===e.charAt(1);return null==(e="string"==typeof e&&"v"===e.charAt(e.length-2)?(r?e.substr(0,2):0)+window["inner"+("vh"===e.substr(-2)?"Height":"Width")]*(parseFloat(r?e.substr(2):e)/100):e)?t:r?parseInt(e.charAt(0)+"1",10)*parseFloat(e.substr(2))+t:parseFloat(e)||0}function S(e,t,r,i){var n,o;return n=(n=null==(e="function"==typeof e?e(P,O):e)?t:"number"==typeof e?e:(n=e.split("_"),o=((o="="===e.charAt(1))?parseInt(e.charAt(0)+"1",10)*parseFloat(n[0].substr(2)):parseFloat(n[0]))*(-1===e.indexOf("rad")?1:D)-(o?0:t),n.length&&(i&&(i[r]=t+o),-1!==e.indexOf("short")&&(o%=360)!==o%180&&(o=o<0?o+360:o-360),-1!==e.indexOf("_cw")&&o<0?o=(o+3599999999640)%360-360*(o/360|0):-1!==e.indexOf("ccw")&&0>16,e>>8&255,255&e];else{if(","===e.charAt(e.length-1)&&(e=e.substr(0,e.length-1)),Ee[e])r=Ee[e];else if("#"===e.charAt(0))4===e.length&&(e="#"+(i=e.charAt(1))+i+(n=e.charAt(2))+n+(o=e.charAt(3))+o),r=[(e=parseInt(e.substr(1),16))>>16,e>>8&255,255&e];else if("hsl"===e.substr(0,3))if(r=u=e.match(Q),t){if(-1!==e.indexOf("="))return e.match($)}else a=Number(r[0])%360/360,s=Number(r[1])/100,i=2*(l=Number(r[2])/100)-(n=l<=.5?l*(s+1):l+s-l*s),3i--)for(;++ii--)for(;++i>0];return i.parse(e,a,n,o)}}function Oe(e,t,r,i,n){this.t=e,this.p=t,this.v=r,this.r=n,i&&((i._prev=this)._next=i)}t._setPluginRatio=function(e){this.plugin.setRatio(e);for(var t,r,i,n,o,a=this.data,s=a.proxy,l=a.firstMPT;l;)t=s[l.v],l.r?t=l.r(t):t<1e-6&&-1e-6s.length?l:s).length,a=0;an.pr;)o=o._next;(n._prev=o?o._prev:s)?n._prev._next=n:a=n,(n._next=o)?o._prev=n:s=n,n=l}this._firstPT=a}return!0},e.parse=function(e,t,r,i){var n,o,a,s,l,u,h,c,f=e.style;for(n in t){if(l=t[n],s=m[n],"function"!=typeof l||s&&s.allowFunc||(l=l(P,O)),s)r=s.parse(e,l,n,this,r,i,t);else{if("--"===n.substr(0,2)){this._tween._propLookup[n]=this._addTween.call(this._tween,e.style,"setProperty",d(e).getPropertyValue(n)+"",l+"",n,!1,n);continue}s=z(e,n,k)+"",h="string"==typeof l,"color"===n||"fill"===n||"stroke"===n||-1!==n.indexOf("Color")||h&&se.test(l)?(h||(l=(3<(l=Se(l)).length?"rgba(":"rgb(")+l.join(",")+")"),r=Re(f,n,s,l,!0,"transparent",r,0,i)):h&&de.test(l)?r=Re(f,n,s,l,!0,null,r,0,i):(u=(o=parseFloat(s))||0===o?s.substr((o+"").length):"",""!==s&&"auto"!==s||(u="width"===n||"height"===n?(o=function(e,t,r){if("svg"===(e.nodeName+"").toLowerCase())return(r||d(e))[t]||0;if(e.getCTM&&Ve(e))return e.getBBox()[t]||0;var i=parseFloat("width"===t?e.offsetWidth:e.offsetHeight),n=Te[t],o=n.length;for(r=r||d(e);-1<--o;)i=(i-=parseFloat(z(e,"padding"+n[o],r,!0))||0)-(parseFloat(z(e,"border"+n[o]+"Width",r,!0))||0);return i}(e,n,k),"px"):"left"===n||"top"===n?(o=xe(e,n,k),"px"):(o="opacity"!==n?0:1,"")),""===(h=(c=h&&"="===l.charAt(1))?(a=parseInt(l.charAt(0)+"1",10),l=l.substr(2),a*=parseFloat(l),l.replace(ie,"")):(a=parseFloat(l),h?l.replace(ie,""):""))&&(h=n in W?W[n]:u),l=a||0===a?(c?a+o:a)+h:t[n],u===h||""===h&&"lineHeight"!==n||(a||0===a)&&o&&(o=w(e,n,o,u),"%"===h?(o/=w(e,n,100,"%")/100,!0!==t.strictUnits&&(s=o+"%")):"em"===h||"rem"===h||"vw"===h||"vh"===h?o/=w(e,n,1,h):"px"!==h&&(a=w(e,n,a,h),h="px"),c&&(a||0===a)&&(l=a+o+h)),c&&(a+=o),!o&&0!==o||!a&&0!==a?void 0!==f[n]&&(l||l+""!="NaN"&&null!=l)?(r=new U(f,n,a||o||0,0,r,-1,n,!1,0,s,l)).xs0="none"!==l||"display"!==n&&-1===n.indexOf("Style")?l:s:_("invalid "+n+" tween value: "+t[n]):(r=new U(f,n,o,a-o,r,0,n,!1!==q&&("px"===h||"zIndex"===n),0,s,l)).xs0=h)}i&&r&&!r.plugin&&(r.plugin=i)}return r},e.setRatio=function(e){var t,r,i,n=this._firstPT;if(1!==e||this._tween._time!==this._tween._duration&&0!==this._tween._time)if(e||this._tween._time!==this._tween._duration&&0!==this._tween._time||-1e-6===this._tween._rawPrevTime)for(;n;){if(t=n.c*e+n.s,n.r?t=n.r(t):t<1e-6&&-1e-6this._p3?this._calcEnd?1===e?0:1-(e=(e-this._p3)/this._p1)*e:t+(e-t)*(e=(e-this._p3)/this._p1)*e*e*e:this._calcEnd?1:t},f.ease=new f(.7,.7),p.config=f.config=function(e,t,r){return new f(e,t,r)},(p=(i=h("easing.SteppedEase",function(e,t){this._p1=1/(e=e||1),this._p2=e+(t?0:1),this._p3=t?1:0},!0)).prototype=new _).constructor=i,p.getRatio=function(e){return e<0?e=0:1<=e&&(e=.999999999),((this._p2*e|0)+this._p3)*this._p1},p.config=i.config=function(e,t){return new i(e,t)},(p=(n=h("easing.ExpoScaleEase",function(e,t,r){this._p1=Math.log(t/e),this._p2=t-e,this._p3=e,this._ease=r},!0)).prototype=new _).constructor=n,p.getRatio=function(e){return this._ease&&(e=this._ease.getRatio(e)),(this._p3*Math.exp(this._p1*e)-this._p3)/this._p2},p.config=n.config=function(e,t,r){return new n(e,t,r)},(p=(o=h("easing.RoughEase",function(e){for(var t,r,i,n,o,a,s=(e=e||{}).taper||"none",l=[],u=0,h=0|(e.points||20),c=h,f=!1!==e.randomize,p=!0===e.clamp,d=e.template instanceof _?e.template:null,m="number"==typeof e.strength?.4*e.strength:.4;-1<--c;)t=f?Math.random():1/h*c,r=d?d.getRatio(t):t,i="none"===s?m:"out"===s?(n=1-t)*n*m:"in"===s?t*t*m:t<.5?(n=2*t)*n*.5*m:(n=2*(1-t))*n*.5*m,f?r+=Math.random()*i-.5*i:c%2?r+=.5*i:r-=.5*i,p&&(1t.t){for(;t.next&&e>=t.t;)t=t.next;t=t.prev}else for(;t.prev&&e<=t.t;)t=t.prev;return(this._prev=t).v+(e-t.t)/t.gap*t.c},p.config=function(e){return new o(e)},o.ease=new o,t("Bounce",e("BounceOut",function(e){return e<1/2.75?7.5625*e*e:e<2/2.75?7.5625*(e-=1.5/2.75)*e+.75:e<2.5/2.75?7.5625*(e-=2.25/2.75)*e+.9375:7.5625*(e-=2.625/2.75)*e+.984375}),e("BounceIn",function(e){return(e=1-e)<1/2.75?1-7.5625*e*e:e<2/2.75?1-(7.5625*(e-=1.5/2.75)*e+.75):e<2.5/2.75?1-(7.5625*(e-=2.25/2.75)*e+.9375):1-(7.5625*(e-=2.625/2.75)*e+.984375)}),e("BounceInOut",function(e){var t=e<.5;return(e=t?1-2*e:2*e-1)<1/2.75?e*=7.5625*e:e=e<2/2.75?7.5625*(e-=1.5/2.75)*e+.75:e<2.5/2.75?7.5625*(e-=2.25/2.75)*e+.9375:7.5625*(e-=2.625/2.75)*e+.984375,t?.5*(1-e):.5*e+.5})),t("Circ",e("CircOut",function(e){return Math.sqrt(1-(e-=1)*e)}),e("CircIn",function(e){return-(Math.sqrt(1-e*e)-1)}),e("CircInOut",function(e){return(e*=2)<1?-.5*(Math.sqrt(1-e*e)-1):.5*(Math.sqrt(1-(e-=2)*e)+1)})),t("Elastic",(p=function(e,t,r){var i=h("easing."+e,function(e,t){this._p1=1<=e?e:1,this._p2=(t||r)/(e<1?e:1),this._p3=this._p2/l*(Math.asin(1/this._p1)||0),this._p2=l/this._p2},!0),e=i.prototype=new _;return e.constructor=i,e.getRatio=t,e.config=function(e,t){return new i(e,t)},i})("ElasticOut",function(e){return this._p1*Math.pow(2,-10*e)*Math.sin((e-this._p3)*this._p2)+1},.3),p("ElasticIn",function(e){return-(this._p1*Math.pow(2,10*--e)*Math.sin((e-this._p3)*this._p2))},.3),p("ElasticInOut",function(e){return(e*=2)<1?this._p1*Math.pow(2,10*--e)*Math.sin((e-this._p3)*this._p2)*-.5:this._p1*Math.pow(2,-10*--e)*Math.sin((e-this._p3)*this._p2)*.5+1},.45)),t("Expo",e("ExpoOut",function(e){return 1-Math.pow(2,-10*e)}),e("ExpoIn",function(e){return Math.pow(2,10*(e-1))-.001}),e("ExpoInOut",function(e){return(e*=2)<1?.5*Math.pow(2,10*(e-1)):.5*(2-Math.pow(2,-10*(e-1)))})),t("Sine",e("SineOut",function(e){return Math.sin(e*u)}),e("SineIn",function(e){return 1-Math.cos(e*u)}),e("SineInOut",function(e){return-.5*(Math.cos(Math.PI*e)-1)})),h("easing.EaseLookup",{find:function(e){return _.map[e]}},!0),c(a.SlowMo,"SlowMo","ease,"),c(o,"RoughEase","ease,"),c(i,"SteppedEase","ease,"),s},!0)}),_gsScope._gsDefine&&_gsScope._gsQueue.pop()(),!function(m,f){"use strict";var p={},d=m.document,_=m.GreenSockGlobals=m.GreenSockGlobals||m,e=_[f];if(e)"undefined"!=typeof module&&module.exports&&(module.exports=e);else{var g,t,F,N=function(e){for(var t=e.split("."),r=_,i=0;i=t&&ethis._duration?this._duration:e,t)):this._time},n.totalTime=function(e,t,r){if(g||O.wake(),!arguments.length)return this._totalTime;if(this._timeline){if(e<0&&!r&&(e+=this.totalDuration()),this._timeline.smoothChildTiming){this._dirty&&this.totalDuration();var i=this._totalDuration,n=this._timeline;if(io;)n=n._prev;return n?(e._next=n._next,n._next=e):(e._next=this._first,this._first=e),e._next?e._next._prev=e:this._last=e,e._prev=n,this._recent=e,this._timeline&&this._uncache(!0),this},n._remove=function(e,t){return e.timeline===this&&(t||e._enabled(!1,!0),e._prev?e._prev._next=e._next:this._first===e&&(this._first=e._next),e._next?e._next._prev=e._prev:this._last===e&&(this._last=e._prev),e._next=e._prev=e.timeline=null,e===this._recent&&(this._recent=this._last),this._timeline&&this._uncache(!0)),this},n.render=function(e,t,r){var i,n=this._first;for(this._totalTime=this._time=this._rawPrevTime=e;n;)i=n._next,(n._active||e>=n._startTime&&!n._paused&&!n._gc)&&(n._reversed?n.render((n._dirty?n.totalDuration():n._totalDuration)-(e-n._startTime)*n._timeScale,t,r):n.render((e-n._startTime)*n._timeScale,t,r)),n=i},n.rawTime=function(){return g||O.wake(),this._totalTime},x("TweenLite",function(e,t,r){if(s.call(this,t,r),this.render=P.prototype.render,null==e)throw"Cannot tween a null target.";this.target=e="string"==typeof e&&P.selector(e)||e;var i,n,o,r=e.jquery||e.length&&e!==m&&e[0]&&(e[0]===m||e[0].nodeType&&e[0].style&&!e.nodeType),a=this.vars.overwrite;if(this._overwrite=a=null==a?ee[P.defaultOverwrite]:"number"==typeof a?a>>0:ee[a],(r||e instanceof Array||e.push&&y(e))&&"number"!=typeof e[0])for(this._targets=o=z(e),this._propLookup=[],this._siblings=[],i=0;i=te){for(r in te=O.frame+(parseInt(P.autoSleep,10)||120),l){for(e=(t=l[r].tweens).length;-1<--e;)t[e]._gc&&t.splice(e,1);0===t.length&&delete l[r]}if((!(r=h._first)||r._paused)&&P.autoSleep&&!u._first&&1===O._listeners.tick.length){for(;r&&r._paused;)r=r._next;r||O.sleep()}}},O.addEventListener("tick",s._updateRoot),function(e,t,r){var i,n,o=e._gsTweenID;if(l[o||(e._gsTweenID=o="t"+Q++)]||(l[o]={target:e,tweens:[]}),t&&((i=l[o].tweens)[n=i.length]=t,r))for(;-1<--n;)i[n]===t&&i.splice(n,1);return l[o].tweens}),re=function(e,t,r,i){var n,o,a=e.vars.onOverwrite;return a&&(n=a(e,t,r,i)),(a=P.onOverwrite)&&(o=a(e,t,r,i)),!1!==n&&!1!==o},ie=function(e,t,r,i,n){var o,a,s;if(1===i||4<=i){for(s=n.length,p=0;pu&&((f||!a._initted)&&u-a._startTime<=2e-8||(h[c++]=a)));for(p=c;-1<--p;)s=(a=h[p])._firstPT,2===i&&a._kill(r,e,t)&&(o=!0),(2!==i||!a._firstPT&&a._initted&&s)&&(2===i||re(a,t))&&a._enabled(!1,!1)&&(o=!0)}return o},ne=function(e,t,r){for(var i=e._timeline,n=i._timeScale,o=e._startTime;i._timeline;){if(o+=i._startTime,n*=i._timeScale,i._paused)return-100;i=i._timeline}return t<(o/=n)?o-t:r&&o===t||!e._initted&&o-t<2e-8?v:(o+=e.totalDuration()/e._timeScale/n)>t+v?0:o-t-v},L=(n._init=function(){var e,t,r,i,n,o,a=this.vars,s=this._overwrittenProps,l=this._duration,u=!!a.immediateRender,h=a.ease,c=this._startAt;if(a.startAt){for(i in c&&(c.render(-1,!0),c.kill()),n={},a.startAt)n[i]=a.startAt[i];if(n.data="isStart",n.overwrite=!1,n.immediateRender=!0,n.lazy=u&&!1!==a.lazy,n.startAt=n.delay=null,n.onUpdate=a.onUpdate,n.onUpdateParams=a.onUpdateParams,n.onUpdateScope=a.onUpdateScope||a.callbackScope||this,this._startAt=P.to(this.target||{},0,n),u)if(0s.pr;)i=i._next;(s._prev=i?i._prev:o)?s._prev._next=s:n=s,(s._next=i)?i._prev=s:o=s,s=a}s=t._firstPT=n}for(;s;)s.pg&&"function"==typeof s.t[e]&&s.t[e]()&&(r=!0),s=s._next;return r},L.activate=function(e){for(var t=e.length;-1<--t;)e[t].API===L.API&&(M[(new e[t])._propName]=e[t]);return!0},i.plugin=function(e){if(!(e&&e.propName&&e.init&&e.API))throw"illegal plugin definition.";var t,r=e.propName,i=e.priority||0,n=e.overwriteProps,o={init:"_onInitTween",set:"setRatio",kill:"_kill",round:"_mod",mod:"_mod",initAll:"_onInitAllProps"},a=x("plugins."+r.charAt(0).toUpperCase()+r.substr(1)+"Plugin",function(){L.call(this,r,i),this._overwriteProps=n||[]},!0===e.global),s=a.prototype=new L(r);for(t in(s.constructor=a).API=e.API,o)"function"==typeof e[t]&&(s[o[t]]=e[t]);return a.version=e.version,L.activate([a]),a},o=m._gsQueue){for(a=0;a>0,c._cycle&&c._cycle===c._totalTime/x&&m<=e&&c._cycle--,c._time=c._totalTime-c._cycle*x,c._yoyo&&1&c._cycle&&(c._time=d-c._time),c._time>d?e=(c._time=d)+1e-4:c._time<0?c._time=e=0:e=c._time));if(c._hasPause&&!c._forcingPlayhead&&!t){if(f<(e=c._time)||c._repeat&&b!==c._cycle)for(i=c._first;i&&i._startTime<=e&&!l;)i._duration||"isPause"!==i.data||i.ratio||0===i._startTime&&0===c._rawPrevTime||(l=i),i=i._next;else for(i=c._last;i&&i._startTime>=e&&!l;)i._duration||"isPause"===i.data&&0c._time;)l.render(l._reversed?l.totalDuration()-(e-l._startTime)*l._timeScale:(e-l._startTime)*l._timeScale,t,r),l=l._prev;l=null,c.pause(),c._pauseTime=h}i._reversed?i.render((i._dirty?i.totalDuration():i._totalDuration)-(e-i._startTime)*i._timeScale,t,r):i.render((e-i._startTime)*i._timeScale,t,r)}i=o}!c._onUpdate||t||(O.length&&P(),c._callback("onUpdate")),!a||c._locked||c._gc||_!==c._startTime&&g===c._timeScale||(0===c._time||p>=c.totalDuration())&&(n&&(O.length&&P(),c._timeline.autoRemoveChildren&&c._enabled(!1,!1),c._active=!1),!t&&c.vars[a]&&c._callback(a))}else m!==c._totalTime&&c._onUpdate&&!t&&c._callback("onUpdate")},i.getActive=function(e,t,r){for(var i,n=[],o=this.getChildren(e||null==e,t||null==e,!!r),a=0,s=o.length,l=0;le)return t[i].name;return null},i.getLabelBefore=function(e){null==e&&(e=this._time);for(var t=this.getLabelsArray(),r=t.length;-1<--r;)if(t[r].timee._startTime;l._timeline;)u&&l._timeline.smoothChildTiming?l.totalTime(l._totalTime,!0):l._gc&&l._enabled(!0,!1),l=l._timeline;return h},e.remove=function(e){var t;if(e instanceof c)return this._remove(e,!1),t=e._timeline=e.vars.useFrames?c._rootFramesTimeline:c._rootTimeline,e._startTime=(e._paused?e._pauseTime:t._time)-(e._reversed?e.totalDuration()-e._totalTime:e._totalTime)/e._timeScale,this;if(e instanceof Array||e&&e.push&&p(e)){for(var r=e.length;-1<--r;)this.remove(e[r]);return this}return"string"==typeof e?this.removeLabel(e):this.kill(null,e)},e._remove=function(e,t){return f.prototype._remove.call(this,e,t),this._last?this._time>this.duration()&&(this._time=this._duration,this._totalTime=this._totalDuration):this._time=this._totalTime=this._duration=this._totalDuration=0,this},e.append=function(e,t){return this.add(e,this._parseTimeOrLabel(null,t,!0,e))},e.insert=e.insertMultiple=function(e,t,r,i){return this.add(e,t||0,r,i)},e.appendMultiple=function(e,t,r,i){return this.add(e,this._parseTimeOrLabel(null,t,!0,e),r,i)},e.addLabel=function(e,t){return this._labels[e]=this._parseTimeOrLabel(t),this},e.addPause=function(e,t,r,i){r=d.delayedCall(0,n,r,i||this);return r.vars.onComplete=r.vars.onReverseComplete=t,r.data="isPause",this._hasPause=!0,this.add(r,e)},e.removeLabel=function(e){return delete this._labels[e],this},e.getLabelTime=function(e){return null!=this._labels[e]?this._labels[e]:-1},e._parseTimeOrLabel=function(e,t,r,i){var n,o;if(i instanceof c&&i.timeline===this)this.remove(i);else if(i&&(i instanceof Array||i.push&&p(i)))for(o=i.length;-1<--o;)i[o]instanceof c&&i[o].timeline===this&&this.remove(i[o]);if(n="number"!=typeof e||t?99999999999=e&&!l;)i._duration||"isPause"===i.data&&0c._time;)l.render(l._reversed?l.totalDuration()-(e-l._startTime)*l._timeScale:(e-l._startTime)*l._timeScale,t,r),l=l._prev;l=null,c.pause(),c._pauseTime=h}i._reversed?i.render((i._dirty?i.totalDuration():i._totalDuration)-(e-i._startTime)*i._timeScale,t,r):i.render((e-i._startTime)*i._timeScale,t,r)}i=o}!c._onUpdate||t||(b.length&&x(),c._callback("onUpdate")),!a||c._gc||d!==c._startTime&&m===c._timeScale||(0===c._time||p>=c.totalDuration())&&(n&&(b.length&&x(),c._timeline.autoRemoveChildren&&c._enabled(!1,!1),c._active=!1),!t&&c.vars[a]&&c._callback(a))}},e._hasPausedChild=function(){for(var e=this._first;e;){if(e._paused||e instanceof m&&e._hasPausedChild())return!0;e=e._next}return!1},e.getChildren=function(e,t,r,i){i=i||-9999999999;for(var n=[],o=this._first,a=0;o;)o._startTime=r&&(n._startTime+=e),n=n._next;if(t)for(i in o)o[i]>=r&&(o[i]+=e);return this._uncache(!0)},e._kill=function(e,t){if(!e&&!t)return this._enabled(!1,!1);for(var r=t?this.getTweensOf(t):this.getChildren(!0,!0,!1),i=r.length,n=!1;-1<--i;)r[i]._kill(e,t)&&(n=!0);return n},e.clear=function(e){var t=this.getChildren(!1,!0,!0),r=t.length;for(this._time=this._totalTime=0;-1<--r;)t[r]._enabled(!1,!1);return!1!==e&&(this._labels={}),this._uncache(!0)},e.invalidate=function(){for(var e=this._first;e;)e.invalidate(),e=e._next;return c.prototype.invalidate.call(this)},e._enabled=function(e,t){if(e===this._gc)for(var r=this._first;r;)r._enabled(e,!0),r=r._next;return f.prototype._enabled.call(this,e,t)},e.totalTime=function(e,t,r){this._forcingPlayhead=!0;var i=c.prototype.totalTime.apply(this,arguments);return this._forcingPlayhead=!1,i},e.duration=function(e){return arguments.length?(0!==this.duration()&&0!==e&&this.timeScale(this._duration/e),this):(this._dirty&&this.totalDuration(),this._duration)},e.totalDuration=function(e){if(arguments.length)return e&&this.totalDuration()?this.timeScale(this._totalDuration/e):this;if(this._dirty){for(var t,r,i=0,n=this,o=n._last,a=999999999999;o;)t=o._prev,o._dirty&&o.totalDuration(),o._startTime>a&&n._sortChildren&&!o._paused&&!n._calculatingDuration?(n._calculatingDuration=1,n.add(o,o._startTime-o._delay),n._calculatingDuration=0):a=o._startTime,o._startTime<0&&!o._paused&&(i-=o._startTime,n._timeline.smoothChildTiming&&(n._startTime+=o._startTime/n._timeScale,n._time-=o._startTime,n._totalTime-=o._startTime,n._rawPrevTime-=o._startTime),n.shiftChildren(-o._startTime,!1,-9999999999),a=0),i<(r=o._startTime+o._totalDuration/o._timeScale)&&(i=r),o=t;n._duration=n._totalDuration=i,n._dirty=!1}return this._totalDuration},e.paused=function(e){if(!1===e&&this._paused)for(var t=this._first;t;)t._startTime===this._time&&"isPause"===t.data&&(t._rawPrevTime=0),t=t._next;return c.prototype.paused.apply(this,arguments)},e.usesFrames=function(){for(var e=this._timeline;e._timeline;)e=e._timeline;return e===c._rootFramesTimeline},e.rawTime=function(e){return e&&(this._paused||this._repeat&&0>10|55296,1023&i|56320)}function N(e,t){return t?"\0"===e?"�":e.slice(0,-1)+"\\"+e.charCodeAt(e.length-1).toString(16)+" ":"\\"+e}function z(){T()}var e,p,b,o,B,d,j,U,x,l,u,T,w,r,E,m,i,n,_,S="sizzle"+ +new Date,g=F.document,A=0,G=0,X=ce(),H=ce(),v=ce(),Y=function(e,t){return e===t&&(u=!0),0},W={}.hasOwnProperty,t=[],q=t.pop,V=t.push,k=t.push,K=t.slice,y=function(e,t){for(var r=0,i=e.length;r+~]|"+a+")"+a+"*"),re=new RegExp("="+a+"*([^\\]'\"]*?)"+a+"*\\]","g"),ie=new RegExp(Q),ne=new RegExp("^"+s+"$"),f={ID:new RegExp("^#("+s+")"),CLASS:new RegExp("^\\.("+s+")"),TAG:new RegExp("^("+s+"|[*])"),ATTR:new RegExp("^"+Z),PSEUDO:new RegExp("^"+Q),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+a+"*(even|odd|(([+-]|)(\\d*)n|)"+a+"*(?:([+-]|)"+a+"*(\\d+)|))"+a+"*\\)|)","i"),bool:new RegExp("^(?:"+J+")$","i"),needsContext:new RegExp("^"+a+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+a+"*((?:-\\d)?\\d*)"+a+"*\\)|)(?=[^-]|$)","i")},oe=/^(?:input|select|textarea|button)$/i,ae=/^h\d$/i,h=/^[^{]+\{\s*\[native \w/,se=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,le=/[+~]/,P=new RegExp("\\\\([\\da-f]{1,6}"+a+"?|("+a+")|.)","ig"),ue=/([\0-\x1f\x7f]|^-?\d)|^-$|[^\0-\x1f\x7f-\uFFFF\w-]/g,he=L(function(e){return!0===e.disabled&&("form"in e||"label"in e)},{dir:"parentNode",next:"legend"});try{k.apply(t=K.call(g.childNodes),g.childNodes),t[g.childNodes.length].nodeType}catch(e){k={apply:t.length?function(e,t){V.apply(e,K.call(t))}:function(e,t){for(var r=e.length,i=0;e[r++]=t[i++];);e.length=r-1}}}function R(e,t,r,i){var n,o,a,s,l,u,h,c=t&&t.ownerDocument,f=t?t.nodeType:9;if(r=r||[],"string"!=typeof e||!e||1!==f&&9!==f&&11!==f)return r;if(!i&&((t?t.ownerDocument||t:g)!==w&&T(t),t=t||w,E)){if(11!==f&&(l=se.exec(e)))if(n=l[1]){if(9===f){if(!(a=t.getElementById(n)))return r;if(a.id===n)return r.push(a),r}else if(c&&(a=c.getElementById(n))&&_(t,a)&&a.id===n)return r.push(a),r}else{if(l[2])return k.apply(r,t.getElementsByTagName(e)),r;if((n=l[3])&&p.getElementsByClassName&&t.getElementsByClassName)return k.apply(r,t.getElementsByClassName(n)),r}if(p.qsa&&!v[e+" "]&&(!m||!m.test(e))){if(1!==f)c=t,h=e;else if("object"!==t.nodeName.toLowerCase()){for((s=t.getAttribute("id"))?s=s.replace(ue,N):t.setAttribute("id",s=S),o=(u=d(e)).length;o--;)u[o]="#"+s+" "+D(u[o]);h=u.join(","),c=le.test(e)&&me(t.parentNode)||t}if(h)try{return k.apply(r,c.querySelectorAll(h)),r}catch(e){}finally{s===S&&t.removeAttribute("id")}}}return U(e.replace(O,"$1"),t,r,i)}function ce(){var r=[];function i(e,t){return r.push(e+" ")>b.cacheLength&&delete i[r.shift()],i[e+" "]=t}return i}function C(e){return e[S]=!0,e}function M(e){var t=w.createElement("fieldset");try{return!!e(t)}catch(e){return!1}finally{t.parentNode&&t.parentNode.removeChild(t)}}function fe(e,t){for(var r=e.split("|"),i=r.length;i--;)b.attrHandle[r[i]]=t}function pe(e,t){var r=t&&e,i=r&&1===e.nodeType&&1===t.nodeType&&e.sourceIndex-t.sourceIndex;if(i)return i;if(r)for(;r=r.nextSibling;)if(r===t)return-1;return e?1:-1}function de(t){return function(e){return"form"in e?e.parentNode&&!1===e.disabled?"label"in e?"label"in e.parentNode?e.parentNode.disabled===t:e.disabled===t:e.isDisabled===t||e.isDisabled!==!t&&he(e)===t:e.disabled===t:"label"in e&&e.disabled===t}}function I(a){return C(function(o){return o=+o,C(function(e,t){for(var r,i=a([],e.length,o),n=i.length;n--;)e[r=i[n]]&&(e[r]=!(t[r]=e[r]))})})}function me(e){return e&&void 0!==e.getElementsByTagName&&e}for(e in p=R.support={},B=R.isXML=function(e){e=e&&(e.ownerDocument||e).documentElement;return!!e&&"HTML"!==e.nodeName},T=R.setDocument=function(e){var e=e?e.ownerDocument||e:g;return e!==w&&9===e.nodeType&&e.documentElement&&(r=(w=e).documentElement,E=!B(w),g!==w&&(e=w.defaultView)&&e.top!==e&&(e.addEventListener?e.addEventListener("unload",z,!1):e.attachEvent&&e.attachEvent("onunload",z)),p.attributes=M(function(e){return e.className="i",!e.getAttribute("className")}),p.getElementsByTagName=M(function(e){return e.appendChild(w.createComment("")),!e.getElementsByTagName("*").length}),p.getElementsByClassName=h.test(w.getElementsByClassName),p.getById=M(function(e){return r.appendChild(e).id=S,!w.getElementsByName||!w.getElementsByName(S).length}),p.getById?(b.filter.ID=function(e){var t=e.replace(P,c);return function(e){return e.getAttribute("id")===t}},b.find.ID=function(e,t){if(void 0!==t.getElementById&&E)return(t=t.getElementById(e))?[t]:[]}):(b.filter.ID=function(e){var t=e.replace(P,c);return function(e){e=void 0!==e.getAttributeNode&&e.getAttributeNode("id");return e&&e.value===t}},b.find.ID=function(e,t){if(void 0!==t.getElementById&&E){var r,i,n,o=t.getElementById(e);if(o){if((r=o.getAttributeNode("id"))&&r.value===e)return[o];for(n=t.getElementsByName(e),i=0;o=n[i++];)if((r=o.getAttributeNode("id"))&&r.value===e)return[o]}return[]}}),b.find.TAG=p.getElementsByTagName?function(e,t){return void 0!==t.getElementsByTagName?t.getElementsByTagName(e):p.qsa?t.querySelectorAll(e):void 0}:function(e,t){var r,i=[],n=0,o=t.getElementsByTagName(e);if("*"!==e)return o;for(;r=o[n++];)1===r.nodeType&&i.push(r);return i},b.find.CLASS=p.getElementsByClassName&&function(e,t){if(void 0!==t.getElementsByClassName&&E)return t.getElementsByClassName(e)},i=[],m=[],(p.qsa=h.test(w.querySelectorAll))&&(M(function(e){r.appendChild(e).innerHTML="",e.querySelectorAll("[msallowcapture^='']").length&&m.push("[*^$]="+a+"*(?:''|\"\")"),e.querySelectorAll("[selected]").length||m.push("\\["+a+"*(?:value|"+J+")"),e.querySelectorAll("[id~="+S+"-]").length||m.push("~="),e.querySelectorAll(":checked").length||m.push(":checked"),e.querySelectorAll("a#"+S+"+*").length||m.push(".#.+[+~]")}),M(function(e){e.innerHTML="";var t=w.createElement("input");t.setAttribute("type","hidden"),e.appendChild(t).setAttribute("name","D"),e.querySelectorAll("[name=d]").length&&m.push("name"+a+"*[*^$|!~]?="),2!==e.querySelectorAll(":enabled").length&&m.push(":enabled",":disabled"),r.appendChild(e).disabled=!0,2!==e.querySelectorAll(":disabled").length&&m.push(":enabled",":disabled"),e.querySelectorAll("*,:x"),m.push(",.*:")})),(p.matchesSelector=h.test(n=r.matches||r.webkitMatchesSelector||r.mozMatchesSelector||r.oMatchesSelector||r.msMatchesSelector))&&M(function(e){p.disconnectedMatch=n.call(e,"*"),n.call(e,"[s!='']:x"),i.push("!=",Q)}),m=m.length&&new RegExp(m.join("|")),i=i.length&&new RegExp(i.join("|")),e=h.test(r.compareDocumentPosition),_=e||h.test(r.contains)?function(e,t){var r=9===e.nodeType?e.documentElement:e,t=t&&t.parentNode;return e===t||!(!t||1!==t.nodeType||!(r.contains?r.contains(t):e.compareDocumentPosition&&16&e.compareDocumentPosition(t)))}:function(e,t){if(t)for(;t=t.parentNode;)if(t===e)return!0;return!1},Y=e?function(e,t){var r;return e===t?(u=!0,0):(r=!e.compareDocumentPosition-!t.compareDocumentPosition)||(1&(r=(e.ownerDocument||e)===(t.ownerDocument||t)?e.compareDocumentPosition(t):1)||!p.sortDetached&&t.compareDocumentPosition(e)===r?e===w||e.ownerDocument===g&&_(g,e)?-1:t===w||t.ownerDocument===g&&_(g,t)?1:l?y(l,e)-y(l,t):0:4&r?-1:1)}:function(e,t){if(e===t)return u=!0,0;var r,i=0,n=e.parentNode,o=t.parentNode,a=[e],s=[t];if(!n||!o)return e===w?-1:t===w?1:n?-1:o?1:l?y(l,e)-y(l,t):0;if(n===o)return pe(e,t);for(r=e;r=r.parentNode;)a.unshift(r);for(r=t;r=r.parentNode;)s.unshift(r);for(;a[i]===s[i];)i++;return i?pe(a[i],s[i]):a[i]===g?-1:s[i]===g?1:0}),w},R.matches=function(e,t){return R(e,null,null,t)},R.matchesSelector=function(e,t){if((e.ownerDocument||e)!==w&&T(e),t=t.replace(re,"='$1']"),p.matchesSelector&&E&&!v[t+" "]&&(!i||!i.test(t))&&(!m||!m.test(t)))try{var r=n.call(e,t);if(r||p.disconnectedMatch||e.document&&11!==e.document.nodeType)return r}catch(e){}return 0":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(e){return e[1]=e[1].replace(P,c),e[3]=(e[3]||e[4]||e[5]||"").replace(P,c),"~="===e[2]&&(e[3]=" "+e[3]+" "),e.slice(0,4)},CHILD:function(e){return e[1]=e[1].toLowerCase(),"nth"===e[1].slice(0,3)?(e[3]||R.error(e[0]),e[4]=+(e[4]?e[5]+(e[6]||1):2*("even"===e[3]||"odd"===e[3])),e[5]=+(e[7]+e[8]||"odd"===e[3])):e[3]&&R.error(e[0]),e},PSEUDO:function(e){var t,r=!e[6]&&e[2];return f.CHILD.test(e[0])?null:(e[3]?e[2]=e[4]||e[5]||"":r&&ie.test(r)&&(t=d(r,!0))&&(t=r.indexOf(")",r.length-t)-r.length)&&(e[0]=e[0].slice(0,t),e[2]=r.slice(0,t)),e.slice(0,3))}},filter:{TAG:function(e){var t=e.replace(P,c).toLowerCase();return"*"===e?function(){return!0}:function(e){return e.nodeName&&e.nodeName.toLowerCase()===t}},CLASS:function(e){var t=X[e+" "];return t||(t=new RegExp("(^|"+a+")"+e+"("+a+"|$)"))&&X(e,function(e){return t.test("string"==typeof e.className&&e.className||void 0!==e.getAttribute&&e.getAttribute("class")||"")})},ATTR:function(t,r,i){return function(e){e=R.attr(e,t);return null==e?"!="===r:!r||(e+="","="===r?e===i:"!="===r?e!==i:"^="===r?i&&0===e.indexOf(i):"*="===r?i&&-1:\x20\t\r\n\f]*)[\x20\t\r\n\f]*\/?>(?:<\/\1>|)$/i;function $(e,r,i){return v(r)?w.grep(e,function(e,t){return!!r.call(e,t,e)!==i}):r.nodeType?w.grep(e,function(e){return e===r!==i}):"string"!=typeof r?w.grep(e,function(e){return-1)[^>]*|#([\w-]+))$/,re=((w.fn.init=function(e,t,r){if(e){if(r=r||ee,"string"!=typeof e)return e.nodeType?(this[0]=e,this.length=1,this):v(e)?void 0!==r.ready?r.ready(e):e(w):w.makeArray(e,this);if(!(i="<"===e[0]&&">"===e[e.length-1]&&3<=e.length?[null,e,null]:te.exec(e))||!i[1]&&t)return(!t||t.jquery?t||r:this.constructor(t)).find(e);if(i[1]){if(t=t instanceof w?t[0]:t,w.merge(this,w.parseHTML(i[1],t&&t.nodeType?t.ownerDocument||t:T,!0)),Q.test(i[1])&&w.isPlainObject(t))for(var i in t)v(this[i])?this[i](t[i]):this.attr(i,t[i])}else(r=T.getElementById(i[2]))&&(this[0]=r,this.length=1)}return this}).prototype=w.fn,ee=w(T),/^(?:parents|prev(?:Until|All))/),ie={children:!0,contents:!0,next:!0,prev:!0};function ne(e,t){for(;(e=e[t])&&1!==e.nodeType;);return e}w.fn.extend({has:function(e){var t=w(e,this),r=t.length;return this.filter(function(){for(var e=0;e\x20\t\r\n\f]+)/i,we=/^$|^module$|\/(?:java|ecma)script/i,S={option:[1,""],thead:[1,"","
"],col:[2,"","
"],tr:[2,"","
"],td:[3,"","
"],_default:[0,"",""]};function A(e,t){var r=void 0!==e.getElementsByTagName?e.getElementsByTagName(t||"*"):void 0!==e.querySelectorAll?e.querySelectorAll(t||"*"):[];return void 0===t||t&&l(e,t)?w.merge([e],r):r}function Ee(e,t){for(var r=0,i=e.length;rx",_.noCloneChecked=!!C.cloneNode(!0).lastChild.defaultValue;var ke=T.documentElement,Oe=/^key/,Pe=/^(?:mouse|pointer|contextmenu|drag|drop)|click/,Re=/^([^.]*)(?:\.(.+)|)/;function Ce(){return!0}function k(){return!1}function Me(){try{return T.activeElement}catch(e){}}function Ie(e,t,r,i,n,o){var a,s;if("object"==typeof t){for(s in"string"!=typeof r&&(i=i||r,r=void 0),t)Ie(e,s,r,i,t[s],o);return e}if(null==i&&null==n?(n=r,i=r=void 0):null==n&&("string"==typeof r?(n=i,i=void 0):(n=i,i=r,r=void 0)),!1===n)n=k;else if(!n)return e;return 1===o&&(a=n,(n=function(e){return w().off(e),a.apply(this,arguments)}).guid=a.guid||(a.guid=w.guid++)),e.each(function(){w.event.add(this,t,n,i,r)})}w.event={global:{},add:function(t,e,r,i,n){var o,a,s,l,u,h,c,f,p,d=g.get(t);if(d)for(r.handler&&(r=(o=r).handler,n=o.selector),n&&w.find.matchesSelector(ke,n),r.guid||(r.guid=w.guid++),(s=d.events)||(s=d.events={}),(a=d.handle)||(a=d.handle=function(e){return void 0!==w&&w.event.triggered!==e.type?w.event.dispatch.apply(t,arguments):void 0}),l=(e=(e||"").match(E)||[""]).length;l--;)c=p=(f=Re.exec(e[l])||[])[1],f=(f[2]||"").split(".").sort(),c&&(u=w.event.special[c]||{},c=(n?u.delegateType:u.bindType)||c,u=w.event.special[c]||{},p=w.extend({type:c,origType:p,data:i,handler:r,guid:r.guid,selector:n,needsContext:n&&w.expr.match.needsContext.test(n),namespace:f.join(".")},o),(h=s[c])||((h=s[c]=[]).delegateCount=0,u.setup&&!1!==u.setup.call(t,i,f,a)||t.addEventListener&&t.addEventListener(c,a)),u.add&&(u.add.call(t,p),p.handler.guid||(p.handler.guid=r.guid)),n?h.splice(h.delegateCount++,0,p):h.push(p),w.event.global[c]=!0)},remove:function(e,t,r,i,n){var o,a,s,l,u,h,c,f,p,d,m,_=g.hasData(e)&&g.get(e);if(_&&(l=_.events)){for(u=(t=(t||"").match(E)||[""]).length;u--;)if(p=m=(s=Re.exec(t[u])||[])[1],d=(s[2]||"").split(".").sort(),p){for(c=w.event.special[p]||{},f=l[p=(i?c.delegateType:c.bindType)||p]||[],s=s[2]&&new RegExp("(^|\\.)"+d.join("\\.(?:.*\\.|)")+"(\\.|$)"),a=o=f.length;o--;)h=f[o],!n&&m!==h.origType||r&&r.guid!==h.guid||s&&!s.test(h.namespace)||i&&i!==h.selector&&("**"!==i||!h.selector)||(f.splice(o,1),h.selector&&f.delegateCount--,c.remove&&c.remove.call(e,h));a&&!f.length&&(c.teardown&&!1!==c.teardown.call(e,d,_.handle)||w.removeEvent(e,p,_.handle),delete l[p])}else for(p in l)w.event.remove(e,p+t[u],r,i,!0);w.isEmptyObject(l)&&g.remove(e,"handle events")}},dispatch:function(e){var t,r,i,n,o,a=w.event.fix(e),s=new Array(arguments.length),e=(g.get(this,"events")||{})[a.type]||[],l=w.event.special[a.type]||{};for(s[0]=a,t=1;t\x20\t\r\n\f]*)[^>]*)\/>/gi,Le=/\s*$/g;function ze(e,t){return l(e,"table")&&l(11!==t.nodeType?t:t.firstChild,"tr")&&w(e).children("tbody")[0]||e}function Be(e){return e.type=(null!==e.getAttribute("type"))+"/"+e.type,e}function je(e){return"true/"===(e.type||"").slice(0,5)?e.type=e.type.slice(5):e.removeAttribute("type"),e}function Ue(e,t){var r,i,n,o,a,s;if(1===t.nodeType){if(g.hasData(e)&&(o=g.access(e),a=g.set(t,o),s=o.events))for(n in delete a.handle,a.events={},s)for(r=0,i=s[n].length;r")},clone:function(e,t,r){var i,n,o,a,s,l,u,h=e.cloneNode(!0),c=w.contains(e.ownerDocument,e);if(!(_.noCloneChecked||1!==e.nodeType&&11!==e.nodeType||w.isXMLDoc(e)))for(a=A(h),i=0,n=(o=A(e)).length;i").prop({charset:r.scriptCharset,src:r.url}).on("load error",n=function(e){i.remove(),n=null,e&&t("error"===e.type?404:200,e.type)}),T.head.appendChild(i[0])},abort:function(){n&&n()}}}),[]),qt=/(=)\?(?=&|$)|\?\?/,Vt=(w.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var e=Wt.pop()||w.expando+"_"+St++;return this[e]=!0,e}}),w.ajaxPrefilter("json jsonp",function(e,t,r){var i,n,o,a=!1!==e.jsonp&&(qt.test(e.url)?"url":"string"==typeof e.data&&0===(e.contentType||"").indexOf("application/x-www-form-urlencoded")&&qt.test(e.data)&&"data");if(a||"jsonp"===e.dataTypes[0])return i=e.jsonpCallback=v(e.jsonpCallback)?e.jsonpCallback():e.jsonpCallback,a?e[a]=e[a].replace(qt,"$1"+i):!1!==e.jsonp&&(e.url+=(At.test(e.url)?"&":"?")+e.jsonp+"="+i),e.converters["script json"]=function(){return o||w.error(i+" was not called"),o[0]},e.dataTypes[0]="json",n=x[i],x[i]=function(){o=arguments},r.always(function(){void 0===n?w(x).removeProp(i):x[i]=n,e[i]&&(e.jsonpCallback=t.jsonpCallback,Wt.push(i)),o&&v(n)&&n(o[0]),o=n=void 0}),"script"}),_.createHTMLDocument=((e=T.implementation.createHTMLDocument("").body).innerHTML="
",2===e.childNodes.length),w.parseHTML=function(e,t,r){var i;return"string"!=typeof e?[]:("boolean"==typeof t&&(r=t,t=!1),t||(_.createHTMLDocument?((i=(t=T.implementation.createHTMLDocument("")).createElement("base")).href=T.location.href,t.head.appendChild(i)):t=T),i=!r&&[],(r=Q.exec(e))?[t.createElement(r[1])]:(r=Ae([e],t,i),i&&i.length&&w(i).remove(),w.merge([],r.childNodes)))},w.fn.load=function(e,t,r){var i,n,o,a=this,s=e.indexOf(" ");return-1").append(w.parseHTML(e)).find(i):e)}).always(r&&function(e,t){a.each(function(){r.apply(this,o||[e.responseText,t,e])})}),this},w.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(e,t){w.fn[t]=function(e){return this.on(t,e)}}),w.expr.pseudos.animated=function(t){return w.grep(w.timers,function(e){return t===e.elem}).length},w.offset={setOffset:function(e,t,r){var i,n,o,a,s=w.css(e,"position"),l=w(e),u={};"static"===s&&(e.style.position="relative"),o=l.offset(),i=w.css(e,"top"),a=w.css(e,"left"),s=("absolute"===s||"fixed"===s)&&-1<(i+a).indexOf("auto")?(n=(s=l.position()).top,s.left):(n=parseFloat(i)||0,parseFloat(a)||0),null!=(t=v(t)?t.call(e,r,w.extend({},o)):t).top&&(u.top=t.top-o.top+n),null!=t.left&&(u.left=t.left-o.left+s),"using"in t?t.using.call(e,u):l.css(u)}},w.fn.extend({offset:function(t){var e,r;return arguments.length?void 0===t?this:this.each(function(e){w.offset.setOffset(this,t,e)}):(r=this[0])?r.getClientRects().length?(e=r.getBoundingClientRect(),r=r.ownerDocument.defaultView,{top:e.top+r.pageYOffset,left:e.left+r.pageXOffset}):{top:0,left:0}:void 0},position:function(){if(this[0]){var e,t,r,i=this[0],n={top:0,left:0};if("fixed"===w.css(i,"position"))t=i.getBoundingClientRect();else{for(t=this.offset(),r=i.ownerDocument,e=i.offsetParent||r.documentElement;e&&(e===r.body||e===r.documentElement)&&"static"===w.css(e,"position");)e=e.parentNode;e&&e!==i&&1===e.nodeType&&((n=w(e).offset()).top+=w.css(e,"borderTopWidth",!0),n.left+=w.css(e,"borderLeftWidth",!0))}return{top:t.top-n.top-w.css(i,"marginTop",!0),left:t.left-n.left-w.css(i,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){for(var e=this.offsetParent;e&&"static"===w.css(e,"position");)e=e.offsetParent;return e||ke})}}),w.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(t,n){var o="pageYOffset"===n;w.fn[t]=function(e){return c(this,function(e,t,r){var i;if(m(e)?i=e:9===e.nodeType&&(i=e.defaultView),void 0===r)return i?i[n]:e[t];i?i.scrollTo(o?i.pageXOffset:r,o?r:i.pageYOffset):e[t]=r},t,e,arguments.length)}}),w.each(["top","left"],function(e,r){w.cssHooks[r]=$e(_.pixelPosition,function(e,t){if(t)return t=P(e,r),Je.test(t)?w(e).position()[r]+"px":t})}),w.each({Height:"height",Width:"width"},function(a,s){w.each({padding:"inner"+a,content:s,"":"outer"+a},function(i,o){w.fn[o]=function(e,t){var r=arguments.length&&(i||"boolean"!=typeof e),n=i||(!0===e||!0===t?"margin":"border");return c(this,function(e,t,r){var i;return m(e)?0===o.indexOf("outer")?e["inner"+a]:e.document.documentElement["client"+a]:9===e.nodeType?(i=e.documentElement,Math.max(e.body["scroll"+a],i["scroll"+a],e.body["offset"+a],i["offset"+a],i["client"+a])):void 0===r?w.css(e,t,n):w.style(e,t,r,n)},s,r?e:void 0,r)}})}),w.each("blur focus focusin focusout resize scroll click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup contextmenu".split(" "),function(e,r){w.fn[r]=function(e,t){return 0>>0))*i)>>>0,i+=4294967296*(r-=i)}return 2.3283064365386963e-10*(i>>>0)});t.next=function(){var e=2091639*t.s0+2.3283064365386963e-10*t.c;return t.s0=t.s1,t.s1=t.s2,t.s2=e-(t.c=0|e)},t.c=1,t.s0=r(" "),t.s1=r(" "),t.s2=r(" "),t.s0-=r(e),t.s0<0&&(t.s0+=1),t.s1-=r(e),t.s1<0&&(t.s1+=1),t.s2-=r(e),t.s2<0&&(t.s2+=1)}function o(e,t){return t.c=e.c,t.s0=e.s0,t.s1=e.s1,t.s2=e.s2,t}function r(e,t){var r=new n(e),e=t&&t.state,i=r.next;return i.int32=function(){return 4294967296*r.next()|0},i.double=function(){return i()+11102230246251565e-32*(2097152*i()|0)},i.quick=i,e&&("object"==typeof e&&o(e,r),i.state=function(){return o(r,{})}),i}e&&e.exports?e.exports=r:t&&t.amd?t(function(){return r}):this.alea=r}("object"==typeof t&&t,"function"==typeof define&&define)},{}],16:[function(e,t,r){!function(e,t){function n(e){var n=this,t="";n.next=function(){var e=(e=n.b)<<25^e>>>7^(t=n.c),t=t-(r=n.d)|0,r=r<<24^r>>>8^(i=n.a),i=i-e|0;return n.b=e=e<<20^e>>>12^t,n.c=t=t-r|0,n.d=r<<16^t>>>16^i,n.a=i-e|0},n.a=0,n.b=0,n.c=-1640531527,n.d=1367130551,e===Math.floor(e)?(n.a=e/4294967296|0,n.b=0|e):t+=e;for(var r=0;r>>0)/4294967296}var i=new n(e),e=t&&t.state;return r.double=function(){do{var e=((i.next()>>>11)+(i.next()>>>0)/4294967296)/(1<<21)}while(0===e);return e},r.int32=i.next,r.quick=r,e&&("object"==typeof e&&o(e,i),r.state=function(){return o(i,{})}),r}e&&e.exports?e.exports=r:t&&t.amd?t(function(){return r}):this.tychei=r}("object"==typeof t&&t,"function"==typeof define&&define)},{}],17:[function(e,t,r){!function(e,t){function n(e){var t=this,r="";t.x=0,t.y=0,t.z=0,t.w=0,t.next=function(){var e=t.x^t.x<<11;return t.x=t.y,t.y=t.z,t.z=t.w,t.w^=t.w>>>19^e^e>>>8},e===(0|e)?t.x=e:r+=e;for(var i=0;i>>0)/4294967296}var i=new n(e),e=t&&t.state;return r.double=function(){do{var e=((i.next()>>>11)+(i.next()>>>0)/4294967296)/(1<<21)}while(0===e);return e},r.int32=i.next,r.quick=r,e&&("object"==typeof e&&o(e,i),r.state=function(){return o(i,{})}),r}e&&e.exports?e.exports=r:t&&t.amd?t(function(){return r}):this.xor128=r}("object"==typeof t&&t,"function"==typeof define&&define)},{}],18:[function(e,t,r){!function(e,t){function n(e){var o=this;o.next=function(){var e,t,r=o.w,i=o.X,n=o.i;return o.w=r=r+1640531527|0,t=i[n+34&127],e=i[n=n+1&127],t=i[n]=(t^=t<<13)^t>>>15^((e^=e<<17)^e>>>12),o.i=n,t+(r^r>>>16)|0};var t,r,i,n,a,s=o,l=e,u=[],h=128;for(l===(0|l)?(r=l,l=null):(l+="\0",r=0,h=Math.max(h,l.length)),i=0,n=-32;n>>15)^r<<4)^r>>>13,0<=n&&(i=0==(t=u[127&n]^=r+(a=a+1640531527|0))?i+1:0);for(128<=i&&(u[127&(l&&l.length||0)]=-1),i=127,n=512;0>>15,t=(t^=t<<17)^t>>>12,u[i]=r^t;s.w=a,s.X=u,s.i=i}function o(e,t){return t.i=e.i,t.w=e.w,t.X=e.X.slice(),t}function r(e,t){function r(){return(i.next()>>>0)/4294967296}var i=new n(e=null==e?+new Date:e),e=t&&t.state;return r.double=function(){do{var e=((i.next()>>>11)+(i.next()>>>0)/4294967296)/(1<<21)}while(0===e);return e},r.int32=i.next,r.quick=r,e&&(e.X&&o(e,i),r.state=function(){return o(i,{})}),r}e&&e.exports?e.exports=r:t&&t.amd?t(function(){return r}):this.xor4096=r}("object"==typeof t&&t,"function"==typeof define&&define)},{}],19:[function(e,t,r){!function(e,t){function n(e){var n=this;n.next=function(){var e=n.x,t=n.i,r=e[t],i=(r^=r>>>7)^r<<24;return i=(i^=(r=e[t+1&7])^r>>>10)^((r=e[t+3&7])^r>>>3)^((r=e[t+4&7])^r<<7),r=e[t+7&7],e[t]=i^=(r^=r<<13)^r<<9,n.i=t+1&7,i};var t,r=n,i=e,o=[];if(i===(0|i))o[0]=i;else for(i=""+i,t=0;t>>0)/4294967296}var i=new n(e=null==e?+new Date:e),e=t&&t.state;return r.double=function(){do{var e=((i.next()>>>11)+(i.next()>>>0)/4294967296)/(1<<21)}while(0===e);return e},r.int32=i.next,r.quick=r,e&&(e.x&&o(e,i),r.state=function(){return o(i,{})}),r}e&&e.exports?e.exports=r:t&&t.amd?t(function(){return r}):this.xorshift7=r}("object"==typeof t&&t,"function"==typeof define&&define)},{}],20:[function(e,t,r){!function(e,t){function n(e){var t=this,r="";t.next=function(){var e=t.x^t.x>>>2;return t.x=t.y,t.y=t.z,t.z=t.w,t.w=t.v,(t.d=t.d+362437|0)+(t.v=t.v^t.v<<4^e^e<<1)|0},t.x=0,t.y=0,t.z=0,t.w=0,e===((t.v=0)|e)?t.x=e:r+=e;for(var i=0;i>>4),t.next()}function o(e,t){return t.x=e.x,t.y=e.y,t.z=e.z,t.w=e.w,t.v=e.v,t.d=e.d,t}function r(e,t){function r(){return(i.next()>>>0)/4294967296}var i=new n(e),e=t&&t.state;return r.double=function(){do{var e=((i.next()>>>11)+(i.next()>>>0)/4294967296)/(1<<21)}while(0===e);return e},r.int32=i.next,r.quick=r,e&&("object"==typeof e&&o(e,i),r.state=function(){return o(i,{})}),r}e&&e.exports?e.exports=r:t&&t.amd?t(function(){return r}):this.xorwow=r}("object"==typeof t&&t,"function"==typeof define&&define)},{}],21:[function(t,r,e){!function(a,s){var l,u=this,h=256,c=6,f="random",p=s.pow(h,c),d=s.pow(2,52),m=2*d,_=h-1;function e(e,t,r){function i(){for(var e=o.g(c),t=p,r=0;e>>=1;return(e+r)/t}var n=[],e=y(function e(t,r){var i,n=[],o=typeof t;if(r&&"object"==o)for(i in t)try{n.push(e(t[i],r-1))}catch(e){}return n.length?n:"string"==o?t:t+"\0"}((t=1==t?{entropy:!0}:t||{}).entropy?[e,b(a)]:null==e?function(){try{return l&&(t=l.randomBytes)?t=t(h):(t=new Uint8Array(h),(u.crypto||u.msCrypto).getRandomValues(t)),b(t)}catch(e){var t=u.navigator,t=t&&t.plugins;return[+new Date,u,t,u.screen,b(a)]}}():e,3),n),o=new g(n);return i.int32=function(){return 0|o.g(4)},i.quick=function(){return o.g(4)/4294967296},i.double=i,y(b(o.S),a),(t.pass||r||function(e,t,r,i){return i&&(i.S&&v(i,o),e.state=function(){return v(o,{})}),r?(s[f]=e,t):e})(i,e,"global"in t?t.global:this==s,t.state)}function g(e){var t,r=e.length,a=this,i=0,n=a.i=a.j=0,o=a.S=[];for(r||(e=[r++]);iMath.PI?l-e:e}function p(e){return e-l*Math.floor(e/l)}t.exports={UP:o,DOWN:a,LEFT:s,RIGHT:0,NORTH:o,SOUTH:a,WEST:s,EAST:0,PI_2:l,PI_QUARTER:u,PI_HALF:h,toDegrees:function(e){return e*i},toRadians:function(e){return e*n},isAngleBetween:function(e,t,r){var i;return((r-t)%l+l)%l>=Math.PI&&(i=t,t=r,r=i),t<=r?t<=e&&e<=r:t<=e||e<=r},differenceAnglesSign:c,differenceAngles:f,shortestAngle:function(e,t){return f(t,e)*c(t,e)+e},normalize:p,angleTwoPoints:function(){return 4===arguments.length?Math.atan2(arguments[3]-arguments[1],arguments[2]-arguments[0]):Math.atan2(arguments[1].y-arguments[0].y,arguments[1].x-arguments[0].x)},distanceTwoPoints:function(){return 2===arguments.length?Math.sqrt(Math.pow(arguments[1].x-arguments[0].x,2)+Math.pow(arguments[1].y-arguments[0].y,2)):Math.sqrt(Math.pow(arguments[2]-arguments[0],2)+Math.pow(arguments[3]-arguments[1],2))},distanceTwoPointsSquared:function(){return 2===arguments.length?Math.pow(arguments[1].x-arguments[0].x,2)+Math.pow(arguments[1].y-arguments[0].y,2):Math.pow(arguments[2]-arguments[0],2)+Math.pow(arguments[3]-arguments[1],2)},closestAngle:function(e){var t=f(e,s),r=f(e,0),i=f(e,o),e=f(e,a);return t<=r&&t<=i&&t<=e?s:r<=i&&r<=e?0:i<=e?o:a},equals:function(e,t,r){return r?f(e,t)>16)+e*(r>>16)<<16|i*(t>>8&255)+e*(r>>8&255)<<8|i*(255&t)+e*(255&r)},random:function(e,t){function r(){return a.range(e,t)}var i=a.pick([{r:1,g:1,b:1},{r:1,g:1,b:0},{r:1,g:0,b:1},{r:0,g:1,b:1},{r:1,g:0,b:0},{r:0,g:1,b:0},{r:0,g:0,b:1}]);return e=e||0,t=t||255,this.rgbToHex(i.r?r():0,i.g?r():0,i.b?r():0)},randomHSL:function(e,t,r,i,n,o){return e={h:a.range(e,t),s:a.range(r,i,!0),l:a.range(n,o,!0)},this.hslToHex(e)},randomGoldenRatioHSL:function(e,t,r){for(var i=a.get(1,!0),n=[],o=0;o=this.time?(this.parent.x=t.end,this.toX=null,this.parent.emit("bounce-x-end",this.parent)):this.parent.x=this.ease(t.time,t.start,t.delta,this.time),this.parent.dirty=!0),this.toY&&((t=this.toY).time+=e,this.parent.emit("moved",{viewport:this.parent,type:"bounce-y"}),t.time>=this.time?(this.parent.y=t.end,this.toY=null,this.parent.emit("bounce-y-end",this.parent)):this.parent.y=this.ease(t.time,t.start,t.delta,this.time),this.parent.dirty=!0))}},{key:"calcUnderflowX",value:function(){var e=void 0;switch(this.underflowX){case-1:e=0;break;case 1:e=this.parent.screenWidth-this.parent.screenWorldWidth;break;default:e=(this.parent.screenWidth-this.parent.screenWorldWidth)/2}return e}},{key:"calcUnderflowY",value:function(){var e=void 0;switch(this.underflowY){case-1:e=0;break;case 1:e=this.parent.screenHeight-this.parent.screenWorldHeight;break;default:e=(this.parent.screenHeight-this.parent.screenWorldHeight)/2}return e}},{key:"bounce",value:function(){var e,t,r,i;this.paused||(e=void 0,(i=this.parent.plugins.decelerate)&&(i.x||i.y)&&(i.x&&i.percentChangeX===i.friction||i.y&&i.percentChangeY===i.friction)&&(((e=this.parent.OOB()).left&&this.left||e.right&&this.right)&&(i.percentChangeX=this.friction),(e.top&&this.top||e.bottom&&this.bottom)&&(i.percentChangeY=this.friction)),t=this.parent.plugins.drag||{},r=this.parent.plugins.pinch||{},i=i||{},t.active||r.active||this.toX&&this.toY||i.x&&i.y||(t=(e=e||this.parent.OOB()).cornerPoint,this.toX||i.x||(r=null,e.left&&this.left?r=this.parent.screenWorldWidththis.maxWidth&&(this.parent.fitWidth(this.maxWidth),e=this.parent.worldScreenWidth,t=this.parent.worldScreenHeight,this.parent.emit("zoomed",{viewport:this.parent,type:"clamp-zoom"})),this.minHeight&&tthis.maxHeight&&(this.parent.fitHeight(this.maxHeight),this.parent.emit("zoomed",{viewport:this.parent,type:"clamp-zoom"})))}}]),r}()},{"./plugin":9}],3:[function(e,t,r){"use strict";var i=function(e,t,r){return t&&n(e.prototype,t),r&&n(e,r),e};function n(e,t){for(var r=0;r(!0===this.right?this.parent.worldWidth:this.right)&&(this.parent.x=-(!0===this.right?this.parent.worldWidth:this.right)*this.parent.scale.x+this.parent.screenWidth,t=!(e.x=0));t&&this.parent.emit("moved",{viewport:this.parent,type:"clamp-x"})}if(null!==this.top||null!==this.bottom){var r=void 0;if(this.parent.screenWorldHeight(!0===this.bottom?this.parent.worldHeight:this.bottom)&&(this.parent.y=-(!0===this.bottom?this.parent.worldHeight:this.bottom)*this.parent.scale.y+this.parent.screenHeight,r=!(e.y=0));r&&this.parent.emit("moved",{viewport:this.parent,type:"clamp-y"})}}}}]),r}()},{"./plugin":9,"./utils":12}],4:[function(e,t,r){"use strict";var i=function(e,t,r){return t&&n(e.prototype,t),r&&n(e,r),e};function n(e,t){for(var r=0;r=e-100){var s=e-a.time;this.x=(this.parent.x-a.x)/s,this.y=(this.parent.y-a.y)/s,this.percentChangeX=this.percentChangeY=this.friction;break}}}catch(e){r=!0,i=e}finally{try{!t&&o.return&&o.return()}finally{if(r)throw i}}}}},{key:"activate",value:function(e){void 0!==(e=e||{}).x&&(this.x=e.x,this.percentChangeX=this.friction),void 0!==e.y&&(this.y=e.y,this.percentChangeY=this.friction)}},{key:"update",value:function(e){var t;this.paused||(t=void 0,this.x&&(this.parent.x+=this.x*e,this.x*=this.percentChangeX,Math.abs(this.x)this.parent.worldWidth&&(this.parent.x=-this.parent.worldWidth*this.parent.scale.x+this.parent.screenWidth,e.x=0);if("x"!==this.clampWheel)if(this.parent.screenWorldHeightthis.parent.worldHeight&&(this.parent.y=-this.parent.worldHeight*this.parent.scale.y+this.parent.screenHeight,e.y=0)}},{key:"active",get:function(){return this.moved}}]),r}()},{"./plugin":9,"./utils":12}],6:[function(e,t,r){"use strict";var n=function(e,t,r){return t&&i(e.prototype,t),r&&i(e,r),e};function i(e,t){for(var r=0;rthis.radius))return;var a=Math.atan2(this.target.y-i.y,this.target.x-i.x),n=this.target.x-Math.cos(a)*this.radius,o=this.target.y-Math.sin(a)*this.radius}this.speed?(a=n-i.x,e=o-i.y,(a||e)&&(t=Math.atan2(o-i.y,n-i.x),r=Math.cos(t)*this.speed,t=Math.sin(t)*this.speed,a=Math.abs(r)>Math.abs(a)?n:i.x+r,r=Math.abs(t)>Math.abs(e)?o:i.y+t,this.parent.moveCenter(a,r),this.parent.emit("moved",{viewport:this.parent,type:"follow"}))):(this.parent.moveCenter(n,o),this.parent.emit("moved",{viewport:this.parent,type:"follow"}))}}}]),i}()},{"./plugin":9}],7:[function(e,t,r){"use strict";var i=function(e,t,r){return t&&n(e.prototype,t),r&&n(e,r),e};function n(e,t){for(var r=0;r=this.radiusSquared?(r=Math.atan2(r.y-e,r.x-t),this.linear?(this.horizontal=Math.round(Math.cos(r))*this.speed*this.reverse*.06,this.vertical=Math.round(Math.sin(r))*this.speed*this.reverse*.06):(this.horizontal=Math.cos(r)*this.speed*this.reverse*.06,this.vertical=Math.sin(r)*this.speed*this.reverse*.06)):(this.horizontal&&this.decelerateHorizontal(),this.vertical&&this.decelerateVertical(),this.horizontal=this.vertical=0)):(o.exists(this.left)&&tthis.right?this.horizontal=-1*this.reverse*this.speed*.06:(this.decelerateHorizontal(),this.horizontal=0),o.exists(this.top)&&ethis.bottom?this.vertical=-1*this.reverse*this.speed*.06:(this.decelerateVertical(),this.vertical=0)))}},{key:"decelerateHorizontal",value:function(){var e=this.parent.plugins.decelerate;this.horizontal&&e&&!this.noDecelerate&&e.activate({x:this.horizontal*this.speed*this.reverse/(1e3/60)})}},{key:"decelerateVertical",value:function(){var e=this.parent.plugins.decelerate;this.vertical&&e&&!this.noDecelerate&&e.activate({y:this.vertical*this.speed*this.reverse/(1e3/60)})}},{key:"up",value:function(){this.horizontal&&this.decelerateHorizontal(),this.vertical&&this.decelerateVertical(),this.horizontal=this.vertical=null}},{key:"update",value:function(){var e;this.paused||(this.horizontal||this.vertical)&&(e=this.parent.center,this.horizontal&&(e.x+=this.horizontal*this.speed),this.vertical&&(e.y+=this.vertical*this.speed),this.parent.moveCenter(e),this.parent.emit("moved",{viewport:this.parent,type:"mouse-edges"}))}}]),r}()},{"./plugin":9,"./utils":12}],8:[function(e,t,r){"use strict";var i=function(e,t,r){return t&&n(e.prototype,t),r&&n(e,r),e};function n(e,t){for(var r=0;r=this.time?(this.parent.scale.set(this.x_scale,this.y_scale),this.removeOnComplete&&this.parent.removePlugin("snap-zoom"),this.parent.emit("snap-zoom-end",this.parent),this.snapping=null):(e=this.snapping,this.parent.scale.x=this.ease(e.time,e.startX,e.deltaX,this.time),this.parent.scale.y=this.ease(e.time,e.startY,e.deltaY,this.time)),(r=this.parent.plugins["clamp-zoom"])&&r.clamp(),this.noMove||(this.center?this.parent.moveCenter(this.center):this.parent.moveCenter(t))):this.parent.scale.x===this.x_scale&&this.parent.scale.y===this.y_scale||this.createSnapping())}},{key:"resume",value:function(){this.snapping=null,o(i.prototype.__proto__||Object.getPrototypeOf(i.prototype),"resume",this).call(this)}}]),i}()},{"./plugin":9,"./utils":12}],11:[function(e,t,r){"use strict";var i=function(e,t,r){return t&&n(e.prototype,t),r&&n(e,r),e};function n(e,t){for(var r=0;rthis.time?(e=!0,t=this.startX+this.deltaX,this.startY+this.deltaY):(i=this.ease(i.time,0,1,this.time),t=this.startX+this.deltaX*i,this.startY+this.deltaY*i),this.topLeft?this.parent.moveCorner(t,r):this.parent.moveCenter(t,r),this.parent.emit("moved",{viewport:this.parent,type:"snap"}),e&&(this.removeOnComplete&&this.parent.removePlugin("snap"),this.parent.emit("snap-end",this.parent),this.snapping=null)):(i=this.topLeft?this.parent.corner:this.parent.center).x===this.x&&i.y===this.y||this.snapStart())}}]),n}()},{"./plugin":9,"./utils":12}],12:[function(e,t,r){"use strict";var i=e("penner");function n(e){return null!=e}t.exports={exists:n,defaults:function(e,t){return null!=e?e:t},ease:function(e,t){return n(e)?"function"==typeof e?e:"string"==typeof e?i[e]:void 0:i[t]}}},{penner:15}],13:[function(e,t,r){"use strict";var i=function(e,t,r){return t&&n(e.prototype,t),r&&n(e,r),e};function n(e,t){for(var r=0;r=this.threshold}},{key:"move",value:function(e){if(!this.pause){var t=!0,r=!1,i=void 0;try{for(var n,o=this.pluginsList[Symbol.iterator]();!(t=(n=o.next()).done);t=!0)n.value.move(e)}catch(e){r=!0,i=e}finally{try{!t&&o.return&&o.return()}finally{if(r)throw i}}this.clickedAvailable&&(r=e.data.global.x-this.last.x,i=e.data.global.y-this.last.y,(this.checkThreshold(r)||this.checkThreshold(i))&&(this.clickedAvailable=!1))}}},{key:"up",value:function(e){if(!this.pause){if(e.data.originalEvent instanceof MouseEvent&&0==e.data.originalEvent.button&&(this.leftDown=!1),"mouse"!==e.data.pointerType)for(var t=0;tthis._worldWidth,e.top=this.top<0,e.bottom=this.bottom>this._worldHeight,e.cornerPoint={x:this._worldWidth*this.scale.x-this._screenWidth,y:this._worldHeight*this.scale.y-this._screenHeight},e}},{key:"countDownPointers",value:function(){return(this.leftDown?1:0)+this.touches.length}},{key:"getTouchPointers",value:function(){var e,t=[],r=this.trackedPointers;for(e in r){var i=r[e];-1!==this.touches.indexOf(i.pointerId)&&t.push(i)}return t}},{key:"getPointers",value:function(){var e,t=[],r=this.trackedPointers;for(e in r)t.push(r[e]);return t}},{key:"_reset",value:function(){this.plugins.bounce&&(this.plugins.bounce.reset(),this.plugins.bounce.bounce()),this.plugins.decelerate&&this.plugins.decelerate.reset(),this.plugins.snap&&this.plugins.snap.reset(),this.plugins.clamp&&this.plugins.clamp.update(),this.plugins["clamp-zoom"]&&this.plugins["clamp-zoom"].clamp(),this.dirty=!0}},{key:"removePlugin",value:function(e){this.plugins[e]&&(this.plugins[e]=null,this.emit(e+"-remove"),this.pluginsSort())}},{key:"pausePlugin",value:function(e){this.plugins[e]&&this.plugins[e].pause()}},{key:"resumePlugin",value:function(e){this.plugins[e]&&this.plugins[e].resume()}},{key:"pluginsSort",value:function(){var e=!0,t=!(this.pluginsList=[]),r=void 0;try{for(var i,n=v[Symbol.iterator]();!(e=(i=n.next()).done);e=!0){var o=i.value;this.plugins[o]&&this.pluginsList.push(this.plugins[o])}}catch(e){t=!0,r=e}finally{try{!e&&n.return&&n.return()}finally{if(t)throw r}}}},{key:"drag",value:function(e){return this.plugins.drag=new s(this,e),this.pluginsSort(),this}},{key:"clamp",value:function(e){return this.plugins.clamp=new u(this,e),this.pluginsSort(),this}},{key:"decelerate",value:function(e){return this.plugins.decelerate=new c(this,e),this.pluginsSort(),this}},{key:"bounce",value:function(e){return this.plugins.bounce=new f(this,e),this.pluginsSort(),this}},{key:"pinch",value:function(e){return this.plugins.pinch=new l(this,e),this.pluginsSort(),this}},{key:"snap",value:function(e,t,r){return this.plugins.snap=new p(this,e,t,r),this.pluginsSort(),this}},{key:"follow",value:function(e,t){return this.plugins.follow=new m(this,e,t),this.pluginsSort(),this}},{key:"wheel",value:function(e){return this.plugins.wheel=new _(this,e),this.pluginsSort(),this}},{key:"clampZoom",value:function(e){return this.plugins["clamp-zoom"]=new h(this,e),this.pluginsSort(),this}},{key:"mouseEdges",value:function(e){return this.plugins["mouse-edges"]=new g(this,e),this.pluginsSort(),this}},{key:"screenWidth",get:function(){return this._screenWidth},set:function(e){this._screenWidth=e}},{key:"screenHeight",get:function(){return this._screenHeight},set:function(e){this._screenHeight=e}},{key:"worldWidth",get:function(){return this._worldWidth||this.width},set:function(e){this._worldWidth=e,this.resizePlugins()}},{key:"worldHeight",get:function(){return this._worldHeight||this.height},set:function(e){this._worldHeight=e,this.resizePlugins()}},{key:"worldScreenWidth",get:function(){return this._screenWidth/this.scale.x}},{key:"worldScreenHeight",get:function(){return this._screenHeight/this.scale.y}},{key:"screenWorldWidth",get:function(){return this._worldWidth*this.scale.x}},{key:"screenWorldHeight",get:function(){return this._worldHeight*this.scale.y}},{key:"center",get:function(){return{x:this.worldScreenWidth/2-this.x/this.scale.x,y:this.worldScreenHeight/2-this.y/this.scale.y}},set:function(e){this.moveCenter(e)}},{key:"corner",get:function(){return{x:-this.x/this.scale.x,y:-this.y/this.scale.y}},set:function(e){this.moveCorner(e)}},{key:"right",get:function(){return-this.x/this.scale.x+this.worldScreenWidth},set:function(e){this.x=-e*this.scale.x+this.screenWidth,this._reset()}},{key:"left",get:function(){return-this.x/this.scale.x},set:function(e){this.x=-e*this.scale.x,this._reset()}},{key:"top",get:function(){return-this.y/this.scale.y},set:function(e){this.y=-e*this.scale.y,this._reset()}},{key:"bottom",get:function(){return-this.y/this.scale.y+this.worldScreenHeight},set:function(e){this.y=-e*this.scale.y+this.screenHeight,this._reset()}},{key:"dirty",get:function(){return this._dirty},set:function(e){this._dirty=e}},{key:"forceHitArea",get:function(){return this._forceHitArea},set:function(e){e?(this._forceHitArea=e,this.hitArea=e):(this._forceHitArea=!1,this.hitArea=new PIXI.Rectangle(0,0,this.worldWidth,this.worldHeight))}},{key:"pause",get:function(){return this._pause},set:function(e){(this._pause=e)&&(this.touches=[],this.leftDown=!1)}}]),r}(PIXI.Container);PIXI.extras.Viewport=e,t.exports=e},{"./bounce":1,"./clamp":3,"./clamp-zoom":2,"./decelerate":4,"./drag":5,"./follow":6,"./mouse-edges":7,"./pinch":8,"./snap":11,"./snap-zoom":10,"./utils":12,"./wheel":14}],14:[function(e,t,r){"use strict";var i=function(e,t,r){return t&&n(e.prototype,t),r&&n(e,r),e};function n(e,t){for(var r=0;rt&&(r[i]=this.hyphenate(r[i]).join("­"));return r.join("")},t.prototype.hyphenate=function(e){var t,r,i,n,o,a,s,l,u,h=[],c=[],f=e.toLowerCase(),p=Math.max,d=this.trie,m=[""];if(this.exceptions.hasOwnProperty(f))return e.match(this.exceptions[f]).slice(1);if(-1!==e.indexOf("­"))return[e];for(t=(e="_"+e+"_").toLowerCase().split(""),r=e.split(""),s=t.length,i=0;ithis.leftMin&&i= 0) { - var p = new Point(i === 0 || i === 1 ? 0 : w, i === 0 || i === 3 ? 0 : h, - 0).transformBy(transformationMatrix) + var p = new Point(i === 0 || i === 1 ? 0 : w, i === 0 || i === 3 ? 0 : h, 0).transformBy( + transformationMatrix + ) if (p.x < left) { left = p.x } @@ -8173,20 +8174,19 @@ if (_gsScope._gsDefine) { _gsScope._gsQueue.pop()(); } //necessary in case Tween } } var rect = element.getBoundingClientRect() - transformationMatrix = I.translate(window.pageXOffset + rect.left - left, - window.pageYOffset + rect.top - top, 0) - .multiply(transformationMatrix) + transformationMatrix = I.translate( + window.pageXOffset + rect.left - left, + window.pageYOffset + rect.top - top, + 0 + ).multiply(transformationMatrix) return transformationMatrix } window.convertPointFromPageToNode = function (element, pageX, pageY) { - return new Point(pageX, pageY, 0).transformBy( - getTransformationMatrix(element).inverse()) + return new Point(pageX, pageY, 0).transformBy(getTransformationMatrix(element).inverse()) } window.convertPointFromNodeToPage = function (element, offsetX, offsetY) { - return new Point(offsetX, offsetY, 0).transformBy( - getTransformationMatrix(element)) + return new Point(offsetX, offsetY, 0).transformBy(getTransformationMatrix(element)) } - -}()); +})() diff --git a/dist/iwmlib.3rdparty.preload.min.js b/dist/iwmlib.3rdparty.preload.min.js index 3935523..eb21af8 100644 --- a/dist/iwmlib.3rdparty.preload.min.js +++ b/dist/iwmlib.3rdparty.preload.min.js @@ -1 +1 @@ -var _gsScope="undefined"!=typeof module&&module.exports&&"undefined"!=typeof global?global:this||window;(_gsScope._gsQueue||(_gsScope._gsQueue=[])).push(function(){"use strict";var P,x,b,w,g,i,y,S,v,T,c,p,d,t,e,l,h,r;_gsScope._gsDefine("TweenMax",["core.Animation","core.SimpleTimeline","TweenLite"],function(r,_,v){var m=function(t){var e,i=[],r=t.length;for(e=0;e!==r;i.push(t[e++]));return i},d=function(t,e,i){var r,n,s=t.cycle;for(r in s)n=s[r],t[r]="function"==typeof n?n(i,e[i],e):n[i%n.length];delete t.cycle},g=function(t){if("function"==typeof t)return t;var p="object"==typeof t?t:{each:t},m=p.ease,d=p.from||0,g=p.base||0,y={},v=isNaN(d),T=p.axis,x={center:.5,end:1}[d]||0;return function(t,e,i){var r,n,s,a,o,l,h,_,u,f=(i||p).length,c=y[f];if(!c){if(!(u="auto"===p.grid?0:(p.grid||[1/0])[0])){for(h=-1/0;h<(h=i[u++].getBoundingClientRect().left)&&u>0,0!==f._cycle&&f._cycle===f._totalTime/a&&m<=t&&f._cycle--,f._time=f._totalTime-f._cycle*a,f._yoyo&&0!=(1&f._cycle)&&(f._time=g-f._time,(u=f._yoyoEase||f.vars.yoyoEase)&&(f._yoyoEase||(!0!==u||f._initted?f._yoyoEase=u=!0===u?f._ease:u instanceof Ease?u:Ease.map[u]:(u=f.vars.ease,f._yoyoEase=u=u?u instanceof Ease?u:"function"==typeof u?new Ease(u,f.vars.easeParams):Ease.map[u]||v.defaultEase:v.defaultEase)),f.ratio=u?1-u.getRatio((g-f._time)/g):0)),f._time>g?f._time=g:f._time<0&&(f._time=0)),f._easeType&&!u?(o=f._time/g,(1===(l=f._easeType)||3===l&&.5<=o)&&(o=1-o),3===l&&(o*=2),1===(h=f._easePower)?o*=o:2===h?o*=o*o:3===h?o*=o*o*o:4===h&&(o*=o*o*o*o),f.ratio=1===l?1-o:2===l?o:f._time/g<.5?o/2:1-o/2):u||(f.ratio=f._ease.getRatio(f._time/g))),p!==f._time||i||d!==f._cycle){if(!f._initted){if(f._init(),!f._initted||f._gc)return;if(!i&&f._firstPT&&(!1!==f.vars.lazy&&f._duration||f.vars.lazy&&!f._duration))return f._time=p,f._totalTime=m,f._rawPrevTime=y,f._cycle=d,x.lazyTweens.push(f),void(f._lazy=[t,e]);!f._time||r||u?r&&this._ease._calcEnd&&!u&&(f.ratio=f._ease.getRatio(0===f._time?0:1)):f.ratio=f._ease.getRatio(f._time/g)}for(!1!==f._lazy&&(f._lazy=!1),f._active||!f._paused&&f._time!==p&&0<=t&&(f._active=!0),0===m&&(2===f._initted&&0t._startTime;l._timeline;)h&&l._timeline.smoothChildTiming?l.totalTime(l._totalTime,!0):l._gc&&l._enabled(!0,!1),l=l._timeline;return _},i.remove=function(t){if(t instanceof u){this._remove(t,!1);var e=t._timeline=t.vars.useFrames?u._rootFramesTimeline:u._rootTimeline;return t._startTime=(t._paused?t._pauseTime:e._time)-(t._reversed?t.totalDuration()-t._totalTime:t._totalTime)/t._timeScale,this}if(t instanceof Array||t&&t.push&&c(t)){for(var i=t.length;-1<--i;)this.remove(t[i]);return this}return"string"==typeof t?this.removeLabel(t):this.kill(null,t)},i._remove=function(t,e){return f.prototype._remove.call(this,t,e),this._last?this._time>this.duration()&&(this._time=this._duration,this._totalTime=this._totalDuration):this._time=this._totalTime=this._duration=this._totalDuration=0,this},i.append=function(t,e){return this.add(t,this._parseTimeOrLabel(null,e,!0,t))},i.insert=i.insertMultiple=function(t,e,i,r){return this.add(t,e||0,i,r)},i.appendMultiple=function(t,e,i,r){return this.add(t,this._parseTimeOrLabel(null,e,!0,t),i,r)},i.addLabel=function(t,e){return this._labels[t]=this._parseTimeOrLabel(e),this},i.addPause=function(t,e,i,r){var n=p.delayedCall(0,s,i,r||this);return n.vars.onComplete=n.vars.onReverseComplete=e,n.data="isPause",this._hasPause=!0,this.add(n,t)},i.removeLabel=function(t){return delete this._labels[t],this},i.getLabelTime=function(t){return null!=this._labels[t]?this._labels[t]:-1},i._parseTimeOrLabel=function(t,e,i,r){var n,s;if(r instanceof u&&r.timeline===this)this.remove(r);else if(r&&(r instanceof Array||r.push&&c(r)))for(s=r.length;-1<--s;)r[s]instanceof u&&r[s].timeline===this&&this.remove(r[s]);if(n="number"!=typeof t||e?99999999999=t&&!l;)r._duration||"isPause"===r.data&&0g&&(a="onReverseComplete"))),u._rawPrevTime=u._duration||!e||t||u._rawPrevTime===t?t:g,t=c+1e-4;else if(tu._time;)l.render(l._reversed?l.totalDuration()-(t-l._startTime)*l._timeScale:(t-l._startTime)*l._timeScale,e,i),l=l._prev;l=null,u.pause(),u._pauseTime=_}r._reversed?r.render((r._dirty?r.totalDuration():r._totalDuration)-(t-r._startTime)*r._timeScale,e,i):r.render((t-r._startTime)*r._timeScale,e,i)}r=s}u._onUpdate&&(e||(y.length&&v(),u._callback("onUpdate"))),a&&(u._gc||p!==u._startTime&&m===u._timeScale||(0===u._time||c>=u.totalDuration())&&(n&&(y.length&&v(),u._timeline.autoRemoveChildren&&u._enabled(!1,!1),u._active=!1),!e&&u.vars[a]&&u._callback(a)))}},i._hasPausedChild=function(){for(var t=this._first;t;){if(t._paused||t instanceof m&&t._hasPausedChild())return!0;t=t._next}return!1},i.getChildren=function(t,e,i,r){r=r||-9999999999;for(var n=[],s=this._first,a=0;s;)s._startTime=i&&(n._startTime+=t),n=n._next;if(e)for(r in s)s[r]>=i&&(s[r]+=t);return this._uncache(!0)},i._kill=function(t,e){if(!t&&!e)return this._enabled(!1,!1);for(var i=e?this.getTweensOf(e):this.getChildren(!0,!0,!1),r=i.length,n=!1;-1<--r;)i[r]._kill(t,e)&&(n=!0);return n},i.clear=function(t){var e=this.getChildren(!1,!0,!0),i=e.length;for(this._time=this._totalTime=0;-1<--i;)e[i]._enabled(!1,!1);return!1!==t&&(this._labels={}),this._uncache(!0)},i.invalidate=function(){for(var t=this._first;t;)t.invalidate(),t=t._next;return u.prototype.invalidate.call(this)},i._enabled=function(t,e){if(t===this._gc)for(var i=this._first;i;)i._enabled(t,!0),i=i._next;return f.prototype._enabled.call(this,t,e)},i.totalTime=function(t,e,i){this._forcingPlayhead=!0;var r=u.prototype.totalTime.apply(this,arguments);return this._forcingPlayhead=!1,r},i.duration=function(t){return arguments.length?(0!==this.duration()&&0!==t&&this.timeScale(this._duration/t),this):(this._dirty&&this.totalDuration(),this._duration)},i.totalDuration=function(t){if(arguments.length)return t&&this.totalDuration()?this.timeScale(this._totalDuration/t):this;if(this._dirty){for(var e,i,r=0,n=this,s=n._last,a=999999999999;s;)e=s._prev,s._dirty&&s.totalDuration(),s._startTime>a&&n._sortChildren&&!s._paused&&!n._calculatingDuration?(n._calculatingDuration=1,n.add(s,s._startTime-s._delay),n._calculatingDuration=0):a=s._startTime,s._startTime<0&&!s._paused&&(r-=s._startTime,n._timeline.smoothChildTiming&&(n._startTime+=s._startTime/n._timeScale,n._time-=s._startTime,n._totalTime-=s._startTime,n._rawPrevTime-=s._startTime),n.shiftChildren(-s._startTime,!1,-9999999999),a=0),r<(i=s._startTime+s._totalDuration/s._timeScale)&&(r=i),s=e;n._duration=n._totalDuration=r,n._dirty=!1}return this._totalDuration},i.paused=function(t){if(!1===t&&this._paused)for(var e=this._first;e;)e._startTime===this._time&&"isPause"===e.data&&(e._rawPrevTime=0),e=e._next;return u.prototype.paused.apply(this,arguments)},i.usesFrames=function(){for(var t=this._timeline;t._timeline;)t=t._timeline;return t===u._rootFramesTimeline},i.rawTime=function(t){return t&&(this._paused||this._repeat&&0>0,f._cycle&&f._cycle===f._totalTime/l&&d<=t&&f._cycle--,f._time=f._totalTime-f._cycle*l,f._yoyo&&1&f._cycle&&(f._time=m-f._time),f._time>m?t=(f._time=m)+1e-4:f._time<0?f._time=t=0:t=f._time));if(f._hasPause&&!f._forcingPlayhead&&!e){if(c<(t=f._time)||f._repeat&&x!==f._cycle)for(r=f._first;r&&r._startTime<=t&&!h;)r._duration||"isPause"!==r.data||r.ratio||0===r._startTime&&0===f._rawPrevTime||(h=r),r=r._next;else for(r=f._last;r&&r._startTime>=t&&!h;)r._duration||"isPause"===r.data&&0f._time;)h.render(h._reversed?h.totalDuration()-(t-h._startTime)*h._timeScale:(t-h._startTime)*h._timeScale,e,i),h=h._prev;h=null,f.pause(),f._pauseTime=u}r._reversed?r.render((r._dirty?r.totalDuration():r._totalDuration)-(t-r._startTime)*r._timeScale,e,i):r.render((t-r._startTime)*r._timeScale,e,i)}r=s}f._onUpdate&&(e||(C.length&&A(),f._callback("onUpdate"))),a&&(f._locked||f._gc||g!==f._startTime&&y===f._timeScale||(0===f._time||p>=f.totalDuration())&&(n&&(C.length&&A(),f._timeline.autoRemoveChildren&&f._enabled(!1,!1),f._active=!1),!e&&f.vars[a]&&f._callback(a)))}else d!==f._totalTime&&f._onUpdate&&(e||f._callback("onUpdate"))},n.getActive=function(t,e,i){var r,n,s=[],a=this.getChildren(t||null==t,e||null==t,!!i),o=0,l=a.length;for(r=0;rt)return i[e].name;return null},n.getLabelBefore=function(t){null==t&&(t=this._time);for(var e=this.getLabelsArray(),i=e.length;-1<--i;)if(e[i].time>0||6)-1,u=[],f=[];for(i in t)p(t[i],a,e);for(n=a.length,r=0;r>0]=f,o[s]=h,l=0,f=[]);return{length:h,lengths:o,segments:u}}(this._beziers,this._timeRes);this._length=f.length,this._lengths=f.lengths,this._segments=f.segments,this._l1=this._li=this._s1=this._si=0,this._l2=this._lengths[0],this._curSeg=this._segments[0],this._s2=this._curSeg[0],this._prec=1/this._curSeg.length}if(u=this._autoRotate)for(this._initialRotations=[],u[0]instanceof Array||(this._autoRotate=u=[u]),s=u.length;-1<--s;){for(a=0;a<3;a++)r=u[s][a],this._func[r]="function"==typeof t[r]&&t[r.indexOf("set")||"function"!=typeof t["get"+r.substr(3)]?r:"get"+r.substr(3)];r=u[s][2],this._initialRotations[s]=(this._func[r]?this._func[r].call(this._target):this._target[r])||0,this._overwriteProps.push(r)}return this._startRatio=i.vars.runBackwards?1:0,!0},set:function(t){var e,i,r,n,s,a,o,l,h,_,u,f=this._segCount,c=this._func,p=this._target,m=t!==this._startRatio;if(this._timeRes){if(h=this._lengths,_=this._curSeg,u=t*this._length,r=this._li,u>this._l2&&r=u;);0===r&&uthis._s2&&r<_.length-1){for(l=_.length-1;r=u;);0===r&&u>0)*(1/f))*f;for(i=1-a,r=this._props.length;-1<--r;)n=this._props[r],o=(a*a*(s=this._beziers[n][e]).da+3*i*(a*s.ca+i*s.ba))*a+s.a,this._mod[n]&&(o=this._mod[n](o,p)),c[n]?p[n](o):p[n]=o;if(this._autoRotate){var d,g,y,v,T,x,b,w=this._autoRotate;for(r=w.length;-1<--r;)n=w[r][2],x=w[r][3]||0,b=!0===w[r][4]?1:P,s=this._beziers[w[r][0]],d=this._beziers[w[r][1]],s&&d&&(s=s[e],d=d[e],g=s.a+(s.b-s.a)*a,g+=((v=s.b+(s.c-s.b)*a)-g)*a,v+=(s.c+(s.d-s.c)*a-v)*a,y=d.a+(d.b-d.a)*a,y+=((T=d.b+(d.c-d.b)*a)-y)*a,T+=(d.c+(d.d-d.c)*a-T)*a,o=m?Math.atan2(T-y,v-g)*b+x:this._initialRotations[r],this._mod[n]&&(o=this._mod[n](o,p)),c[n]?p[n](o):p[n]=o)}}}),t=d.prototype,d.bezierThrough=c,d.cubicToQuadratic=S,d._autoCSS=!0,d.quadraticToCubic=function(t,e,i){return new y(t,(2*e+t)/3,(2*e+i)/3,i)},d._cssRegister=function(){var t=i.CSSPlugin;if(t){var e=t._internals,c=e._parseToProxy,p=e._setPluginRatio,m=e.CSSPropTween;e._registerComplexSpecialProp("bezier",{parser:function(t,e,i,r,n,s){e instanceof Array&&(e={values:e}),s=new d;var a,o,l,h=e.values,_=h.length-1,u=[],f={};if(_<0)return n;for(a=0;a<=_;a++)l=c(t,h[a],r,n,s,_!==a),u[a]=l.end;for(o in e)f[o]=e[o];return f.values=u,(n=new m(t,"bezier",0,0,l.pt,2)).data=l,n.plugin=s,n.setRatio=p,0===f.autoRotate&&(f.autoRotate=!0),!f.autoRotate||f.autoRotate instanceof Array||(a=!0===f.autoRotate?0:Number(f.autoRotate),f.autoRotate=null!=l.end.left?[["left","top","rotation",a,!1]]:null!=l.end.x&&[["x","y","rotation",a,!1]]),f.autoRotate&&(r._transform||r._enableTransforms(!1),l.autoRotate=r._target._gsTransform,l.proxy.rotation=l.autoRotate.rotation||0,r._overwriteProps.push("rotation")),s._onInitTween(l.proxy,f,r._tween),n}})}},t._mod=function(t){for(var e,i=this._overwriteProps,r=i.length;-1<--r;)(e=t[i[r]])&&"function"==typeof e&&(this._mod[i[r]]=e)},t._kill=function(t){var e,i,r=this._props;for(e in this._beziers)if(e in t)for(delete this._beziers[e],delete this._func[e],i=r.length;-1<--i;)r[i]===e&&r.splice(i,1);if(r=this._autoRotate)for(i=r.length;-1<--i;)t[r[i][2]]&&r.splice(i,1);return this._super._kill.call(this,t)},_gsScope._gsDefine("plugins.CSSPlugin",["plugins.TweenPlugin","TweenLite"],function(s,B){var p,P,S,m,Y=function(){s.call(this,"css"),this._overwriteProps.length=0,this.setRatio=Y.prototype.setRatio},h=_gsScope._gsDefine.globals,d={},t=Y.prototype=new s("css");(t.constructor=Y).version="2.1.3",Y.API=2,Y.defaultTransformPerspective=0,Y.defaultSkewType="compensated",Y.defaultSmoothOrigin=!0,t="px",Y.suffixMap={top:t,right:t,bottom:t,left:t,width:t,height:t,fontSize:t,padding:t,margin:t,perspective:t,lineHeight:""};var k,g,y,j,v,O,R,C,e,i,A=/(?:\-|\.|\b)(\d|\.|e\-)+/g,M=/(?:\d|\-\d|\.\d|\-\.\d|\+=\d|\-=\d|\+=.\d|\-=\.\d)+/g,T=/(?:\+=|\-=|\-|\b)[\d\-\.]+[a-zA-Z0-9]*(?:%|\b)/gi,n=/(?:\+=|\-=|\-|\b)[\d\-\.]+[a-zA-Z0-9]*(?:%|\b),?/gi,_=/(?![+-]?\d*\.?\d+|[+-]|e[+-]\d+)[^0-9]/g,D=/(?:\d|\-|\+|=|#|\.)*/g,F=/opacity *= *([^)]*)/i,x=/opacity:([^;]*)/i,a=/alpha\(opacity *=.+?\)/i,b=/^(rgb|hsl)/,o=/([A-Z])/g,l=/-([a-z])/gi,w=/(^(?:url\(\"|url\())|(?:(\"\))$|\)$)/gi,u=function(t,e){return e.toUpperCase()},c=/(?:Left|Right|Width)/i,f=/(M11|M12|M21|M22)=[\d\-\.e]+/gi,z=/progid\:DXImageTransform\.Microsoft\.Matrix\(.+?\)/i,E=/,(?=[^\)]*(?:\(|$))/gi,I=/[\s,\(]/i,U=Math.PI/180,V=180/Math.PI,N={},r={style:{}},X=_gsScope.document||{createElement:function(){return r}},L=function(t,e){var i=X.createElementNS?X.createElementNS(e||"http://www.w3.org/1999/xhtml",t):X.createElement(t);return i.style?i:X.createElement(t)},q=L("div"),W=L("img"),G=Y._internals={_specialProps:d},Z=(_gsScope.navigator||{}).userAgent||"",H=(e=Z.indexOf("Android"),i=L("a"),y=-1!==Z.indexOf("Safari")&&-1===Z.indexOf("Chrome")&&(-1===e||3>16,t>>8&255,255&t];else{if(","===t.charAt(t.length-1)&&(t=t.substr(0,t.length-1)),mt[t])i=mt[t];else if("#"===t.charAt(0))4===t.length&&(t="#"+(r=t.charAt(1))+r+(n=t.charAt(2))+n+(s=t.charAt(3))+s),i=[(t=parseInt(t.substr(1),16))>>16,t>>8&255,255&t];else if("hsl"===t.substr(0,3))if(i=f=t.match(A),e){if(-1!==t.indexOf("="))return t.match(M)}else a=Number(i[0])%360/360,o=Number(i[1])/100,r=2*(l=Number(i[2])/100)-(n=l<=.5?l*(o+1):l+o-l*o),3r--)for(;++rr--)for(;++r>0];return r.parse(t,a,n,s)}},bt=(G._setPluginRatio=function(t){this.plugin.setRatio(t);for(var e,i,r,n,s,a=this.data,o=a.proxy,l=a.firstMPT;l;)e=o[l.v],l.r?e=l.r(e):e<1e-6&&-1e-6o.length?l.length:o.length,a=0;as.pr;)a=a._next;(s._prev=a?a._prev:l)?s._prev._next=s:o=s,(s._next=a)?a._prev=s:l=s,s=h}this._firstPT=o}return!0},t.parse=function(t,e,i,r){var n,s,a,o,l,h,_,u,f,c,p=t.style;for(n in e){if(h=e[n],s=d[n],"function"!=typeof h||s&&s.allowFunc||(h=h(C,R)),s)i=s.parse(t,h,n,this,i,r,e);else{if("--"===n.substr(0,2)){this._tween._propLookup[n]=this._addTween.call(this._tween,t.style,"setProperty",it(t).getPropertyValue(n)+"",h+"",n,!1,n);continue}l=rt(t,n,S)+"",f="string"==typeof h,"color"===n||"fill"===n||"stroke"===n||-1!==n.indexOf("Color")||f&&b.test(h)?(f||(h=(3<(h=gt(h)).length?"rgba(":"rgb(")+h.join(",")+")"),i=St(p,n,l,h,!0,"transparent",i,0,r)):f&&I.test(h)?i=St(p,n,l,h,!0,null,i,0,r):(_=(a=parseFloat(l))||0===a?l.substr((a+"").length):"",""!==l&&"auto"!==l||(_="width"===n||"height"===n?(a=_t(t,n,S),"px"):"left"===n||"top"===n?(a=st(t,n,S),"px"):(a="opacity"!==n?0:1,"")),""===(u=(c=f&&"="===h.charAt(1))?(o=parseInt(h.charAt(0)+"1",10),h=h.substr(2),o*=parseFloat(h),h.replace(D,"")):(o=parseFloat(h),f?h.replace(D,""):""))&&(u=n in P?P[n]:_),h=o||0===o?(c?o+a:o)+u:e[n],_!==u&&(""===u&&"lineHeight"!==n||(o||0===o)&&a&&(a=nt(t,n,a,_),"%"===u?(a/=nt(t,n,100,"%")/100,!0!==e.strictUnits&&(l=a+"%")):"em"===u||"rem"===u||"vw"===u||"vh"===u?a/=nt(t,n,1,u):"px"!==u&&(o=nt(t,n,o,u),u="px"),c&&(o||0===o)&&(h=o+a+u))),c&&(o+=a),!a&&0!==a||!o&&0!==o?void 0!==p[n]&&(h||h+""!="NaN"&&null!=h)?(i=new wt(p,n,o||a||0,0,i,-1,n,!1,0,l,h)).xs0="none"!==h||"display"!==n&&-1===n.indexOf("Style")?h:l:Q("invalid "+n+" tween value: "+e[n]):(i=new wt(p,n,a,o-a,i,0,n,!1!==k&&("px"===u||"zIndex"===n),0,l,h)).xs0=u)}r&&i&&!i.plugin&&(i.plugin=r)}return i},t.setRatio=function(t){var e,i,r,n=this._firstPT;if(1!==t||this._tween._time!==this._tween._duration&&0!==this._tween._time)if(t||this._tween._time!==this._tween._duration&&0!==this._tween._time||-1e-6===this._tween._rawPrevTime)for(;n;){if(e=n.c*t+n.s,n.r?e=n.r(e):e<1e-6&&-1e-6this._p3?this._calcEnd?1===t?0:1-(t=(t-this._p3)/this._p1)*t:e+(t-e)*(t=(t-this._p3)/this._p1)*t*t*t:this._calcEnd?1:e},p.ease=new p(.7,.7),m.config=p.config=function(t,e,i){return new p(t,e,i)},(m=(i=l("easing.SteppedEase",function(t,e){t=t||1,this._p1=1/t,this._p2=t+(e?0:1),this._p3=e?1:0},!0)).prototype=new d).constructor=i,m.getRatio=function(t){return t<0?t=0:1<=t&&(t=.999999999),((this._p2*t|0)+this._p3)*this._p1},m.config=i.config=function(t,e){return new i(t,e)},(m=(r=l("easing.ExpoScaleEase",function(t,e,i){this._p1=Math.log(e/t),this._p2=e-t,this._p3=t,this._ease=i},!0)).prototype=new d).constructor=r,m.getRatio=function(t){return this._ease&&(t=this._ease.getRatio(t)),(this._p3*Math.exp(this._p1*t)-this._p3)/this._p2},m.config=r.config=function(t,e,i){return new r(t,e,i)},(m=(e=l("easing.RoughEase",function(t){for(var e,i,r,n,s,a,o=(t=t||{}).taper||"none",l=[],h=0,_=0|(t.points||20),u=_,f=!1!==t.randomize,c=!0===t.clamp,p=t.template instanceof d?t.template:null,m="number"==typeof t.strength?.4*t.strength:.4;-1<--u;)e=f?Math.random():1/_*u,i=p?p.getRatio(e):e,r="none"===o?m:"out"===o?(n=1-e)*n*m:"in"===o?e*e*m:e<.5?(n=2*e)*n*.5*m:(n=2*(1-e))*n*.5*m,f?i+=Math.random()*r-.5*r:u%2?i+=.5*r:i-=.5*r,c&&(1e.t){for(;e.next&&t>=e.t;)e=e.next;e=e.prev}else for(;e.prev&&t<=e.t;)e=e.prev;return(this._prev=e).v+(t-e.t)/e.gap*e.c},m.config=function(t){return new e(t)},e.ease=new e,u("Bounce",h("BounceOut",function(t){return t<1/2.75?7.5625*t*t:t<2/2.75?7.5625*(t-=1.5/2.75)*t+.75:t<2.5/2.75?7.5625*(t-=2.25/2.75)*t+.9375:7.5625*(t-=2.625/2.75)*t+.984375}),h("BounceIn",function(t){return(t=1-t)<1/2.75?1-7.5625*t*t:t<2/2.75?1-(7.5625*(t-=1.5/2.75)*t+.75):t<2.5/2.75?1-(7.5625*(t-=2.25/2.75)*t+.9375):1-(7.5625*(t-=2.625/2.75)*t+.984375)}),h("BounceInOut",function(t){var e=t<.5;return(t=e?1-2*t:2*t-1)<1/2.75?t*=7.5625*t:t=t<2/2.75?7.5625*(t-=1.5/2.75)*t+.75:t<2.5/2.75?7.5625*(t-=2.25/2.75)*t+.9375:7.5625*(t-=2.625/2.75)*t+.984375,e?.5*(1-t):.5*t+.5})),u("Circ",h("CircOut",function(t){return Math.sqrt(1-(t-=1)*t)}),h("CircIn",function(t){return-(Math.sqrt(1-t*t)-1)}),h("CircInOut",function(t){return(t*=2)<1?-.5*(Math.sqrt(1-t*t)-1):.5*(Math.sqrt(1-(t-=2)*t)+1)})),u("Elastic",(t=function(t,e,i){var r=l("easing."+t,function(t,e){this._p1=1<=t?t:1,this._p2=(e||i)/(t<1?t:1),this._p3=this._p2/a*(Math.asin(1/this._p1)||0),this._p2=a/this._p2},!0),n=r.prototype=new d;return n.constructor=r,n.getRatio=e,n.config=function(t,e){return new r(t,e)},r})("ElasticOut",function(t){return this._p1*Math.pow(2,-10*t)*Math.sin((t-this._p3)*this._p2)+1},.3),t("ElasticIn",function(t){return-this._p1*Math.pow(2,10*(t-=1))*Math.sin((t-this._p3)*this._p2)},.3),t("ElasticInOut",function(t){return(t*=2)<1?this._p1*Math.pow(2,10*(t-=1))*Math.sin((t-this._p3)*this._p2)*-.5:this._p1*Math.pow(2,-10*(t-=1))*Math.sin((t-this._p3)*this._p2)*.5+1},.45)),u("Expo",h("ExpoOut",function(t){return 1-Math.pow(2,-10*t)}),h("ExpoIn",function(t){return Math.pow(2,10*(t-1))-.001}),h("ExpoInOut",function(t){return(t*=2)<1?.5*Math.pow(2,10*(t-1)):.5*(2-Math.pow(2,-10*(t-1)))})),u("Sine",h("SineOut",function(t){return Math.sin(t*o)}),h("SineIn",function(t){return 1-Math.cos(t*o)}),h("SineInOut",function(t){return-.5*(Math.cos(Math.PI*t)-1)})),l("easing.EaseLookup",{find:function(t){return d.map[t]}},!0),_(n.SlowMo,"SlowMo","ease,"),_(e,"RoughEase","ease,"),_(i,"SteppedEase","ease,"),c},!0)}),_gsScope._gsDefine&&_gsScope._gsQueue.pop()(),function(f,c){"use strict";var p={},r=f.document,m=f.GreenSockGlobals=f.GreenSockGlobals||f,t=m[c];if(t)return"undefined"!=typeof module&&module.exports&&(module.exports=t);var e,i,n,d,g,s,a,y=function(t){var e,i=t.split("."),r=m;for(e=0;e=i&&tthis._duration?this._duration:t,e)):this._time},n.totalTime=function(t,e,i){if(g||d.wake(),!arguments.length)return this._totalTime;if(this._timeline){if(t<0&&!i&&(t+=this.totalDuration()),this._timeline.smoothChildTiming){this._dirty&&this.totalDuration();var r=this._totalDuration,n=this._timeline;if(rs;)n=n._prev;return n?(t._next=n._next,n._next=t):(t._next=this._first,this._first=t),t._next?t._next._prev=t:this._last=t,t._prev=n,this._recent=t,this._timeline&&this._uncache(!0),this},n._remove=function(t,e){return t.timeline===this&&(e||t._enabled(!1,!0),t._prev?t._prev._next=t._next:this._first===t&&(this._first=t._next),t._next?t._next._prev=t._prev:this._last===t&&(this._last=t._prev),t._next=t._prev=t.timeline=null,t===this._recent&&(this._recent=this._last),this._timeline&&this._uncache(!0)),this},n.render=function(t,e,i){var r,n=this._first;for(this._totalTime=this._time=this._rawPrevTime=t;n;)r=n._next,(n._active||t>=n._startTime&&!n._paused&&!n._gc)&&(n._reversed?n.render((n._dirty?n.totalDuration():n._totalDuration)-(t-n._startTime)*n._timeScale,e,i):n.render((t-n._startTime)*n._timeScale,e,i)),n=r},n.rawTime=function(){return g||d.wake(),this._totalTime};var E=P("TweenLite",function(t,e,i){if(D.call(this,e,i),this.render=E.prototype.render,null==t)throw"Cannot tween a null target.";this.target=t="string"!=typeof t?t:E.selector(t)||t;var r,n,s,a=t.jquery||t.length&&t!==f&&t[0]&&(t[0]===f||t[0].nodeType&&t[0].style&&!t.nodeType),o=this.vars.overwrite;if(this._overwrite=o=null==o?$[E.defaultOverwrite]:"number"==typeof o?o>>0:$[o],(a||t instanceof Array||t.push&&x(t))&&"number"!=typeof t[0])for(this._targets=s=l(t),this._propLookup=[],this._siblings=[],r=0;r=J){for(i in J=d.frame+(parseInt(E.autoSleep,10)||120),G){for(t=(e=G[i].tweens).length;-1<--t;)e[t]._gc&&e.splice(t,1);0===e.length&&delete G[i]}if((!(i=K._first)||i._paused)&&E.autoSleep&&!Q._first&&1===d._listeners.tick.length){for(;i&&i._paused;)i=i._next;i||d.sleep()}}},d.addEventListener("tick",D._updateRoot);var et=function(t,e,i){var r,n,s=t._gsTweenID;if(G[s||(t._gsTweenID=s="t"+Z++)]||(G[s]={target:t,tweens:[]}),e&&((r=G[s].tweens)[n=r.length]=e,i))for(;-1<--n;)r[n]===e&&r.splice(n,1);return G[s].tweens},it=function(t,e,i,r){var n,s,a=t.vars.onOverwrite;return a&&(n=a(t,e,i,r)),(a=E.onOverwrite)&&(s=a(t,e,i,r)),!1!==n&&!1!==s},rt=function(t,e,i,r,n){var s,a,o,l;if(1===r||4<=r){for(l=n.length,s=0;s_&&((c||!o._initted)&&_-o._startTime<=2e-8||(u[f++]=o)));for(s=f;-1<--s;)if(l=(o=u[s])._firstPT,2===r&&o._kill(i,t,e)&&(a=!0),2!==r||!o._firstPT&&o._initted&&l){if(2!==r&&!it(o,e))continue;o._enabled(!1,!1)&&(a=!0)}return a},nt=function(t,e,i){for(var r=t._timeline,n=r._timeScale,s=t._startTime;r._timeline;){if(s+=r._startTime,n*=r._timeScale,r._paused)return-100;r=r._timeline}return e<(s/=n)?s-e:i&&s===e||!t._initted&&s-e<2e-8?v:(s+=t.totalDuration()/t._timeScale/n)>e+v?0:s-e-v};n._init=function(){var t,e,i,r,n,s,a=this.vars,o=this._overwrittenProps,l=this._duration,h=!!a.immediateRender,_=a.ease,u=this._startAt;if(a.startAt){for(r in u&&(u.render(-1,!0),u.kill()),n={},a.startAt)n[r]=a.startAt[r];if(n.data="isStart",n.overwrite=!1,n.immediateRender=!0,n.lazy=h&&!1!==a.lazy,n.startAt=n.delay=null,n.onUpdate=a.onUpdate,n.onUpdateParams=a.onUpdateParams,n.onUpdateScope=a.onUpdateScope||a.callbackScope||this,this._startAt=E.to(this.target||{},0,n),h)if(0o.pr;)r=r._next;(o._prev=r?r._prev:s)?o._prev._next=o:n=o,(o._next=r)?r._prev=o:s=o,o=a}o=e._firstPT=n}for(;o;)o.pg&&"function"==typeof o.t[t]&&o.t[t]()&&(i=!0),o=o._next;return i},st.activate=function(t){for(var e=t.length;-1<--e;)t[e].API===st.API&&(W[(new t[e])._propName]=t[e]);return!0},o.plugin=function(t){if(!(t&&t.propName&&t.init&&t.API))throw"illegal plugin definition.";var e,i=t.propName,r=t.priority||0,n=t.overwriteProps,s={init:"_onInitTween",set:"setRatio",kill:"_kill",round:"_mod",mod:"_mod",initAll:"_onInitAllProps"},a=P("plugins."+i.charAt(0).toUpperCase()+i.substr(1)+"Plugin",function(){st.call(this,i,r),this._overwriteProps=n||[]},!0===t.global),o=a.prototype=new st(i);for(e in(o.constructor=a).API=t.API,s)"function"==typeof t[e]&&(o[s[e]]=t[e]);return a.version=t.version,st.activate([a]),a},e=f._gsQueue){for(i=0;i>0,0!==_._cycle&&_._cycle===_._totalTime/u&&c<=t&&_._cycle--,_._time=_._totalTime-_._cycle*u,_._yoyo&&0!=(1&_._cycle)&&(_._time=m-_._time,(h=_._yoyoEase||_.vars.yoyoEase)&&(_._yoyoEase||(!0!==h||_._initted?_._yoyoEase=h=!0===h?_._ease:h instanceof Ease?h:Ease.map[h]:(h=_.vars.ease,_._yoyoEase=h=h?h instanceof Ease?h:"function"==typeof h?new Ease(h,_.vars.easeParams):Ease.map[h]||g.defaultEase:g.defaultEase)),_.ratio=h?1-h.getRatio((m-_._time)/m):0)),_._time>m?_._time=m:_._time<0&&(_._time=0)),_._easeType&&!h?(u=_._time/m,(1===(a=_._easeType)||3===a&&.5<=u)&&(u=1-u),3===a&&(u*=2),1===(o=_._easePower)?u*=u:2===o?u*=u*u:3===o?u*=u*u*u:4===o&&(u*=u*u*u*u),_.ratio=1===a?1-u:2===a?u:_._time/m<.5?u/2:1-u/2):h||(_.ratio=_._ease.getRatio(_._time/m))),f!==_._time||i||p!==_._cycle){if(!_._initted){if(_._init(),!_._initted||_._gc)return;if(!i&&_._firstPT&&(!1!==_.vars.lazy&&_._duration||_.vars.lazy&&!_._duration))return _._time=f,_._totalTime=c,_._rawPrevTime=d,_._cycle=p,x.lazyTweens.push(_),void(_._lazy=[t,e]);!_._time||r||h?r&&this._ease._calcEnd&&!h&&(_.ratio=_._ease.getRatio(0===_._time?0:1)):_.ratio=_._ease.getRatio(_._time/m)}for(!1!==_._lazy&&(_._lazy=!1),_._active||!_._paused&&_._time!==f&&0<=t&&(_._active=!0),0===c&&(2===_._initted&&0t._startTime;l._timeline;)h&&l._timeline.smoothChildTiming?l.totalTime(l._totalTime,!0):l._gc&&l._enabled(!0,!1),l=l._timeline;return _},t.remove=function(t){var e;if(t instanceof u)return this._remove(t,!1),e=t._timeline=t.vars.useFrames?u._rootFramesTimeline:u._rootTimeline,t._startTime=(t._paused?t._pauseTime:e._time)-(t._reversed?t.totalDuration()-t._totalTime:t._totalTime)/t._timeScale,this;if(t instanceof Array||t&&t.push&&c(t)){for(var i=t.length;-1<--i;)this.remove(t[i]);return this}return"string"==typeof t?this.removeLabel(t):this.kill(null,t)},t._remove=function(t,e){return f.prototype._remove.call(this,t,e),this._last?this._time>this.duration()&&(this._time=this._duration,this._totalTime=this._totalDuration):this._time=this._totalTime=this._duration=this._totalDuration=0,this},t.append=function(t,e){return this.add(t,this._parseTimeOrLabel(null,e,!0,t))},t.insert=t.insertMultiple=function(t,e,i,r){return this.add(t,e||0,i,r)},t.appendMultiple=function(t,e,i,r){return this.add(t,this._parseTimeOrLabel(null,e,!0,t),i,r)},t.addLabel=function(t,e){return this._labels[t]=this._parseTimeOrLabel(e),this},t.addPause=function(t,e,i,r){i=p.delayedCall(0,n,i,r||this);return i.vars.onComplete=i.vars.onReverseComplete=e,i.data="isPause",this._hasPause=!0,this.add(i,t)},t.removeLabel=function(t){return delete this._labels[t],this},t.getLabelTime=function(t){return null!=this._labels[t]?this._labels[t]:-1},t._parseTimeOrLabel=function(t,e,i,r){var n,s;if(r instanceof u&&r.timeline===this)this.remove(r);else if(r&&(r instanceof Array||r.push&&c(r)))for(s=r.length;-1<--s;)r[s]instanceof u&&r[s].timeline===this&&this.remove(r[s]);if(n="number"!=typeof t||e?99999999999=t&&!l;)r._duration||"isPause"===r.data&&0v&&(a="onReverseComplete"))),u._rawPrevTime=u._duration||!e||t||u._rawPrevTime===t?t:v,t=c+1e-4;else if(tu._time;)l.render(l._reversed?l.totalDuration()-(t-l._startTime)*l._timeScale:(t-l._startTime)*l._timeScale,e,i),l=l._prev;l=null,u.pause(),u._pauseTime=_}r._reversed?r.render((r._dirty?r.totalDuration():r._totalDuration)-(t-r._startTime)*r._timeScale,e,i):r.render((t-r._startTime)*r._timeScale,e,i)}r=s}!u._onUpdate||e||(x.length&&b(),u._callback("onUpdate")),!a||u._gc||p!==u._startTime&&m===u._timeScale||(0===u._time||c>=u.totalDuration())&&(n&&(x.length&&b(),u._timeline.autoRemoveChildren&&u._enabled(!1,!1),u._active=!1),!e&&u.vars[a]&&u._callback(a))}},t._hasPausedChild=function(){for(var t=this._first;t;){if(t._paused||t instanceof m&&t._hasPausedChild())return!0;t=t._next}return!1},t.getChildren=function(t,e,i,r){r=r||-9999999999;for(var n=[],s=this._first,a=0;s;)s._startTime=i&&(n._startTime+=t),n=n._next;if(e)for(r in s)s[r]>=i&&(s[r]+=t);return this._uncache(!0)},t._kill=function(t,e){if(!t&&!e)return this._enabled(!1,!1);for(var i=e?this.getTweensOf(e):this.getChildren(!0,!0,!1),r=i.length,n=!1;-1<--r;)i[r]._kill(t,e)&&(n=!0);return n},t.clear=function(t){var e=this.getChildren(!1,!0,!0),i=e.length;for(this._time=this._totalTime=0;-1<--i;)e[i]._enabled(!1,!1);return!1!==t&&(this._labels={}),this._uncache(!0)},t.invalidate=function(){for(var t=this._first;t;)t.invalidate(),t=t._next;return u.prototype.invalidate.call(this)},t._enabled=function(t,e){if(t===this._gc)for(var i=this._first;i;)i._enabled(t,!0),i=i._next;return f.prototype._enabled.call(this,t,e)},t.totalTime=function(t,e,i){this._forcingPlayhead=!0;var r=u.prototype.totalTime.apply(this,arguments);return this._forcingPlayhead=!1,r},t.duration=function(t){return arguments.length?(0!==this.duration()&&0!==t&&this.timeScale(this._duration/t),this):(this._dirty&&this.totalDuration(),this._duration)},t.totalDuration=function(t){if(arguments.length)return t&&this.totalDuration()?this.timeScale(this._totalDuration/t):this;if(this._dirty){for(var e,i,r=0,n=this,s=n._last,a=999999999999;s;)e=s._prev,s._dirty&&s.totalDuration(),s._startTime>a&&n._sortChildren&&!s._paused&&!n._calculatingDuration?(n._calculatingDuration=1,n.add(s,s._startTime-s._delay),n._calculatingDuration=0):a=s._startTime,s._startTime<0&&!s._paused&&(r-=s._startTime,n._timeline.smoothChildTiming&&(n._startTime+=s._startTime/n._timeScale,n._time-=s._startTime,n._totalTime-=s._startTime,n._rawPrevTime-=s._startTime),n.shiftChildren(-s._startTime,!1,-9999999999),a=0),r<(i=s._startTime+s._totalDuration/s._timeScale)&&(r=i),s=e;n._duration=n._totalDuration=r,n._dirty=!1}return this._totalDuration},t.paused=function(t){if(!1===t&&this._paused)for(var e=this._first;e;)e._startTime===this._time&&"isPause"===e.data&&(e._rawPrevTime=0),e=e._next;return u.prototype.paused.apply(this,arguments)},t.usesFrames=function(){for(var t=this._timeline;t._timeline;)t=t._timeline;return t===u._rootFramesTimeline},t.rawTime=function(t){return t&&(this._paused||this._repeat&&0>0,u._cycle&&u._cycle===u._totalTime/x&&m<=t&&u._cycle--,u._time=u._totalTime-u._cycle*x,u._yoyo&&1&u._cycle&&(u._time=p-u._time),u._time>p?t=(u._time=p)+1e-4:u._time<0?u._time=t=0:t=u._time));if(u._hasPause&&!u._forcingPlayhead&&!e){if(f<(t=u._time)||u._repeat&&T!==u._cycle)for(r=u._first;r&&r._startTime<=t&&!l;)r._duration||"isPause"!==r.data||r.ratio||0===r._startTime&&0===u._rawPrevTime||(l=r),r=r._next;else for(r=u._last;r&&r._startTime>=t&&!l;)r._duration||"isPause"===r.data&&0u._time;)l.render(l._reversed?l.totalDuration()-(t-l._startTime)*l._timeScale:(t-l._startTime)*l._timeScale,e,i),l=l._prev;l=null,u.pause(),u._pauseTime=_}r._reversed?r.render((r._dirty?r.totalDuration():r._totalDuration)-(t-r._startTime)*r._timeScale,e,i):r.render((t-r._startTime)*r._timeScale,e,i)}r=s}!u._onUpdate||e||(R.length&&C(),u._callback("onUpdate")),!a||u._locked||u._gc||d!==u._startTime&&g===u._timeScale||(0===u._time||c>=u.totalDuration())&&(n&&(R.length&&C(),u._timeline.autoRemoveChildren&&u._enabled(!1,!1),u._active=!1),!e&&u.vars[a]&&u._callback(a))}else m!==u._totalTime&&u._onUpdate&&!e&&u._callback("onUpdate")},r.getActive=function(t,e,i){for(var r,n=[],s=this.getChildren(t||null==t,e||null==t,!!i),a=0,o=s.length,l=0;lt)return e[r].name;return null},r.getLabelBefore=function(t){null==t&&(t=this._time);for(var e=this.getLabelsArray(),i=e.length;-1<--i;)if(e[i].time>0||6)-1,u=[],f=[];for(i in t){x=T=v=y=x=g=d=m=p=c=v=O=S=void 0;for(var c,p,m,d,g,y,v,T,x,b=t[i],w=a,P=e,S=1/P,O=b.length;-1<--O;)for(p=(T=b[O]).a,m=T.d-p,d=T.c-p,g=T.b-p,c=0,y=1;y<=P;y++)v=c-(c=((x=S*y)*x*m+3*(v=1-x)*(x*d+v*g))*x),w[x=O*P+y-1]=(w[x]||0)+v*v}for(n=a.length,r=0;r>0]=f,o[s]=h,l=0,f=[]);return{length:h,lengths:o,segments:u}}(this._beziers,this._timeRes),this._length=_.length,this._lengths=_.lengths,this._segments=_.segments,this._l1=this._li=this._s1=this._si=0,this._l2=this._lengths[0],this._curSeg=this._segments[0],this._s2=this._curSeg[0],this._prec=1/this._curSeg.length),u=this._autoRotate)for(this._initialRotations=[],u[0]instanceof Array||(this._autoRotate=u=[u]),s=u.length;-1<--s;){for(a=0;a<3;a++)r=u[s][a],this._func[r]="function"==typeof t[r]&&t[r.indexOf("set")||"function"!=typeof t["get"+r.substr(3)]?r:"get"+r.substr(3)];r=u[s][2],this._initialRotations[s]=(this._func[r]?this._func[r].call(this._target):this._target[r])||0,this._overwriteProps.push(r)}return this._startRatio=i.vars.runBackwards?1:0,!0},set:function(t){var e,i,r,n,s,a,o,l,h,_,u=this._segCount,f=this._func,c=this._target,p=t!==this._startRatio;if(this._timeRes){if(l=this._lengths,h=this._curSeg,_=t*this._length,w=this._li,_>this._l2&&w=_;);0===w&&_this._s2&&w=_;);0===w&&_>0)*(1/u))*u;for(i=1-s,w=this._props.length;-1<--w;)r=this._props[w],a=(s*s*(n=this._beziers[r][e]).da+3*i*(s*n.ca+i*n.ba))*s+n.a,this._mod[r]&&(a=this._mod[r](a,c)),f[r]?c[r](a):c[r]=a;if(this._autoRotate)for(var m,d,g,y,v,T,x,b=this._autoRotate,w=b.length;-1<--w;)r=b[w][2],T=b[w][3]||0,x=!0===b[w][4]?1:P,n=this._beziers[b[w][0]],m=this._beziers[b[w][1]],n&&m&&(n=n[e],m=m[e],d=n.a+(n.b-n.a)*s,d+=((y=n.b+(n.c-n.b)*s)-d)*s,y+=(n.c+(n.d-n.c)*s-y)*s,g=m.a+(m.b-m.a)*s,g+=((v=m.b+(m.c-m.b)*s)-g)*s,v+=(m.c+(m.d-m.c)*s-v)*s,a=p?Math.atan2(v-g,y-d)*x+T:this._initialRotations[w],this._mod[r]&&(a=this._mod[r](a,c)),f[r]?c[r](a):c[r]=a)}}),t=d.prototype,d.bezierThrough=f,d.cubicToQuadratic=B,d._autoCSS=!0,d.quadraticToCubic=function(t,e,i){return new L(t,(2*e+t)/3,(2*e+i)/3,i)},d._cssRegister=function(){var c,p,m,t=e.CSSPlugin;t&&(t=t._internals,c=t._parseToProxy,p=t._setPluginRatio,m=t.CSSPropTween,t._registerComplexSpecialProp("bezier",{parser:function(t,e,i,r,n,s){e instanceof Array&&(e={values:e}),s=new d;var a,o,l,h=e.values,_=h.length-1,u=[],f={};if(!(_<0)){for(a=0;a<=_;a++)l=c(t,h[a],r,n,s,_!==a),u[a]=l.end;for(o in e)f[o]=e[o];f.values=u,(n=new m(t,"bezier",0,0,l.pt,2)).data=l,n.plugin=s,n.setRatio=p,0===f.autoRotate&&(f.autoRotate=!0),!f.autoRotate||f.autoRotate instanceof Array||(a=!0===f.autoRotate?0:Number(f.autoRotate),f.autoRotate=null!=l.end.left?[["left","top","rotation",a,!1]]:null!=l.end.x&&[["x","y","rotation",a,!1]]),f.autoRotate&&(r._transform||r._enableTransforms(!1),l.autoRotate=r._target._gsTransform,l.proxy.rotation=l.autoRotate.rotation||0,r._overwriteProps.push("rotation")),s._onInitTween(l.proxy,f,r._tween)}return n}}))},t._mod=function(t){for(var e,i=this._overwriteProps,r=i.length;-1<--r;)(e=t[i[r]])&&"function"==typeof e&&(this._mod[i[r]]=e)},t._kill=function(t){var e,i,r=this._props;for(e in this._beziers)if(e in t)for(delete this._beziers[e],delete this._func[e],i=r.length;-1<--i;)r[i]===e&&r.splice(i,1);if(r=this._autoRotate)for(i=r.length;-1<--i;)t[r[i][2]]&&r.splice(i,1);return this._super._kill.call(this,t)},_gsScope._gsDefine("plugins.CSSPlugin",["plugins.TweenPlugin","TweenLite"],function(a,A){function M(){a.call(this,"css"),this._overwriteProps.length=0,this.setRatio=M.prototype.setRatio}function o(t,e){return e.toUpperCase()}function l(t,e){return(e=z.createElementNS?z.createElementNS(e||"http://www.w3.org/1999/xhtml",t):z.createElement(t)).style?e:z.createElement(t)}function h(t){return nt.test("string"==typeof t?t:(t.currentStyle||t.style).filter||"")?parseFloat(RegExp.$1)/100:1}function d(t){_gsScope.console&&console.log(t)}function b(t,e){var i,r,n=(e=e||I).style;if(void 0!==n[t])return t;for(t=t.charAt(0).toUpperCase()+t.substr(1),i=["O","Moz","ms","Ms","Webkit"],r=5;-1<--r&&void 0===n[i[r]+t];);return 0<=r?(yt="-"+(vt=3===r?"ms":i[r]).toLowerCase()+"-",vt+t):null}function p(t){return Tt.getComputedStyle(t)}function f(t,e){var i,r,n={};if(e=e||p(t))if(i=e.length)for(;-1<--i;)-1!==(r=e[i]).indexOf("-transform")&&jt!==r||(n[r.replace(ht,o)]=e.getPropertyValue(r));else for(i in e)-1!==i.indexOf("Transform")&&V!==i||(n[i]=e[i]);else if(e=t.currentStyle||t.style)for(i in e)"string"==typeof i&&void 0===n[i]&&(n[i.replace(ht,o)]=e[i]);return N||(n.opacity=h(t)),t=$t(t,e,!1),n.rotation=t.rotation,n.skewX=t.skewX,n.scaleX=t.scaleX,n.scaleY=t.scaleY,n.x=t.x,n.y=t.y,q&&(n.z=t.z,n.rotationX=t.rotationX,n.rotationY=t.rotationY,n.scaleZ=t.scaleZ),n.filters&&delete n.filters,n}function g(t,e,i,r,n){var s,a,o,l={},h=t.style;for(a in i)"cssText"===a||"length"!==a&&isNaN(a)&&(e[a]!==(s=i[a])||n&&n[a])&&-1===a.indexOf("Origin")&&("number"==typeof s||"string"==typeof s)&&(l[a]="auto"!==s||"left"!==a&&"top"!==a?""!==s&&"auto"!==s&&"none"!==s||"string"!=typeof e[a]||""===e[a].replace(it,"")?s:0:xt(t,a),void 0!==h[a]&&(o=new Rt(h,a,h[a],o)));if(r)for(a in r)"className"!==a&&(l[a]=r[a]);return{difs:l,firstMPT:o}}function O(t,e){return"string"==typeof(t="function"==typeof t?t(C,R):t)&&"="===t.charAt(1)?parseInt(t.charAt(0)+"1",10)*parseFloat(t.substr(2)):parseFloat(t)-parseFloat(e)||0}function P(t,e){var i="string"==typeof(t="function"==typeof t?t(C,R):t)&&"="===t.charAt(1);return null==(t="string"==typeof t&&"v"===t.charAt(t.length-2)?(i?t.substr(0,2):0)+window["inner"+("vh"===t.substr(-2)?"Height":"Width")]*(parseFloat(i?t.substr(2):t)/100):t)?e:i?parseInt(t.charAt(0)+"1",10)*parseFloat(t.substr(2))+e:parseFloat(t)||0}function S(t,e,i,r){var n,s,a;return s=(s=null==(t="function"==typeof t?t(C,R):t)?e:"number"==typeof t?t:(n=360,s=t.split("_"),a=((a="="===t.charAt(1))?parseInt(t.charAt(0)+"1",10)*parseFloat(s[0].substr(2)):parseFloat(s[0]))*(-1===t.indexOf("rad")?1:F)-(a?0:e),s.length&&(r&&(r[i]=e+a),-1!==t.indexOf("short")&&(a%=n)!==a%180&&(a=a<0?a+n:a-n),-1!==t.indexOf("_cw")&&a<0?a=(a+3599999999640)%n-(a/n|0)*n:-1!==t.indexOf("ccw")&&0>16,t>>8&255,255&t];else{if(","===t.charAt(t.length-1)&&(t=t.substr(0,t.length-1)),Pt[t])i=Pt[t];else if("#"===t.charAt(0))4===t.length&&(t="#"+(r=t.charAt(1))+r+(n=t.charAt(2))+n+(s=t.charAt(3))+s),i=[(t=parseInt(t.substr(1),16))>>16,t>>8&255,255&t];else if("hsl"===t.substr(0,3))if(i=h=t.match(K),e){if(-1!==t.indexOf("="))return t.match(J)}else a=Number(i[0])%360/360,o=Number(i[1])/100,r=2*(l=Number(i[2])/100)-(n=l<=.5?l*(o+1):l+o-l*o),3r--)for(;++rr--)for(;++r>0];return r.parse(t,a,n,s)}}function Rt(t,e,i,r,n){this.t=t,this.p=e,this.v=i,this.r=n,r&&((r._prev=this)._next=r)}e._setPluginRatio=function(t){this.plugin.setRatio(t);for(var e,i,r,n,s,a=this.data,o=a.proxy,l=a.firstMPT;l;)e=o[l.v],l.r?e=l.r(e):e<1e-6&&-1e-6o.length?l:o).length,a=0;an.pr;)s=s._next;(n._prev=s?s._prev:o)?n._prev._next=n:a=n,(n._next=s)?s._prev=n:o=n,n=l}this._firstPT=a}return!0},t.parse=function(t,e,i,r){var n,s,a,o,l,h,_,u,f=t.style;for(n in e){if(l=e[n],o=m[n],"function"!=typeof l||o&&o.allowFunc||(l=l(C,R)),o)i=o.parse(t,l,n,this,i,r,e);else{if("--"===n.substr(0,2)){this._tween._propLookup[n]=this._addTween.call(this._tween,t.style,"setProperty",p(t).getPropertyValue(n)+"",l+"",n,!1,n);continue}o=X(t,n,k)+"",_="string"==typeof l,"color"===n||"fill"===n||"stroke"===n||-1!==n.indexOf("Color")||_&&ot.test(l)?(_||(l=(3<(l=St(l)).length?"rgba(":"rgb(")+l.join(",")+")"),i=At(f,n,o,l,!0,"transparent",i,0,r)):_&&pt.test(l)?i=At(f,n,o,l,!0,null,i,0,r):(h=(s=parseFloat(o))||0===s?o.substr((s+"").length):"",""!==o&&"auto"!==o||(h="width"===n||"height"===n?(s=function(t,e,i){if("svg"===(t.nodeName+"").toLowerCase())return(i||p(t))[e]||0;if(t.getCTM&&Zt(t))return t.getBBox()[e]||0;var r=parseFloat("width"===e?t.offsetWidth:t.offsetHeight),n=bt[e],s=n.length;for(i=i||p(t);-1<--s;)r=(r-=parseFloat(X(t,"padding"+n[s],i,!0))||0)-(parseFloat(X(t,"border"+n[s]+"Width",i,!0))||0);return r}(t,n,k),"px"):"left"===n||"top"===n?(s=xt(t,n,k),"px"):(s="opacity"!==n?0:1,"")),""===(_=(u=_&&"="===l.charAt(1))?(a=parseInt(l.charAt(0)+"1",10),l=l.substr(2),a*=parseFloat(l),l.replace(rt,"")):(a=parseFloat(l),_?l.replace(rt,""):""))&&(_=n in W?W[n]:h),l=a||0===a?(u?a+s:a)+_:e[n],h===_||""===_&&"lineHeight"!==n||(a||0===a)&&s&&(s=w(t,n,s,h),"%"===_?(s/=w(t,n,100,"%")/100,!0!==e.strictUnits&&(o=s+"%")):"em"===_||"rem"===_||"vw"===_||"vh"===_?s/=w(t,n,1,_):"px"!==_&&(a=w(t,n,a,_),_="px"),u&&(a||0===a)&&(l=a+s+_)),u&&(a+=s),!s&&0!==s||!a&&0!==a?void 0!==f[n]&&(l||l+""!="NaN"&&null!=l)?(i=new Y(f,n,a||s||0,0,i,-1,n,!1,0,o,l)).xs0="none"!==l||"display"!==n&&-1===n.indexOf("Style")?l:o:d("invalid "+n+" tween value: "+e[n]):(i=new Y(f,n,s,a-s,i,0,n,!1!==G&&("px"===_||"zIndex"===n),0,o,l)).xs0=_)}r&&i&&!i.plugin&&(i.plugin=r)}return i},t.setRatio=function(t){var e,i,r,n=this._firstPT;if(1!==t||this._tween._time!==this._tween._duration&&0!==this._tween._time)if(t||this._tween._time!==this._tween._duration&&0!==this._tween._time||-1e-6===this._tween._rawPrevTime)for(;n;){if(e=n.c*t+n.s,n.r?e=n.r(e):e<1e-6&&-1e-6this._p3?this._calcEnd?1===t?0:1-(t=(t-this._p3)/this._p1)*t:e+(t-e)*(t=(t-this._p3)/this._p1)*t*t*t:this._calcEnd?1:e},f.ease=new f(.7,.7),c.config=f.config=function(t,e,i){return new f(t,e,i)},(c=(r=_("easing.SteppedEase",function(t,e){this._p1=1/(t=t||1),this._p2=t+(e?0:1),this._p3=e?1:0},!0)).prototype=new d).constructor=r,c.getRatio=function(t){return t<0?t=0:1<=t&&(t=.999999999),((this._p2*t|0)+this._p3)*this._p1},c.config=r.config=function(t,e){return new r(t,e)},(c=(n=_("easing.ExpoScaleEase",function(t,e,i){this._p1=Math.log(e/t),this._p2=e-t,this._p3=t,this._ease=i},!0)).prototype=new d).constructor=n,c.getRatio=function(t){return this._ease&&(t=this._ease.getRatio(t)),(this._p3*Math.exp(this._p1*t)-this._p3)/this._p2},c.config=n.config=function(t,e,i){return new n(t,e,i)},(c=(s=_("easing.RoughEase",function(t){for(var e,i,r,n,s,a,o=(t=t||{}).taper||"none",l=[],h=0,_=0|(t.points||20),u=_,f=!1!==t.randomize,c=!0===t.clamp,p=t.template instanceof d?t.template:null,m="number"==typeof t.strength?.4*t.strength:.4;-1<--u;)e=f?Math.random():1/_*u,i=p?p.getRatio(e):e,r="none"===o?m:"out"===o?(n=1-e)*n*m:"in"===o?e*e*m:e<.5?(n=2*e)*n*.5*m:(n=2*(1-e))*n*.5*m,f?i+=Math.random()*r-.5*r:u%2?i+=.5*r:i-=.5*r,c&&(1e.t){for(;e.next&&t>=e.t;)e=e.next;e=e.prev}else for(;e.prev&&t<=e.t;)e=e.prev;return(this._prev=e).v+(t-e.t)/e.gap*e.c},c.config=function(t){return new s(t)},s.ease=new s,e("Bounce",t("BounceOut",function(t){return t<1/2.75?7.5625*t*t:t<2/2.75?7.5625*(t-=1.5/2.75)*t+.75:t<2.5/2.75?7.5625*(t-=2.25/2.75)*t+.9375:7.5625*(t-=2.625/2.75)*t+.984375}),t("BounceIn",function(t){return(t=1-t)<1/2.75?1-7.5625*t*t:t<2/2.75?1-(7.5625*(t-=1.5/2.75)*t+.75):t<2.5/2.75?1-(7.5625*(t-=2.25/2.75)*t+.9375):1-(7.5625*(t-=2.625/2.75)*t+.984375)}),t("BounceInOut",function(t){var e=t<.5;return(t=e?1-2*t:2*t-1)<1/2.75?t*=7.5625*t:t=t<2/2.75?7.5625*(t-=1.5/2.75)*t+.75:t<2.5/2.75?7.5625*(t-=2.25/2.75)*t+.9375:7.5625*(t-=2.625/2.75)*t+.984375,e?.5*(1-t):.5*t+.5})),e("Circ",t("CircOut",function(t){return Math.sqrt(1-(t-=1)*t)}),t("CircIn",function(t){return-(Math.sqrt(1-t*t)-1)}),t("CircInOut",function(t){return(t*=2)<1?-.5*(Math.sqrt(1-t*t)-1):.5*(Math.sqrt(1-(t-=2)*t)+1)})),e("Elastic",(c=function(t,e,i){var r=_("easing."+t,function(t,e){this._p1=1<=t?t:1,this._p2=(e||i)/(t<1?t:1),this._p3=this._p2/l*(Math.asin(1/this._p1)||0),this._p2=l/this._p2},!0),t=r.prototype=new d;return t.constructor=r,t.getRatio=e,t.config=function(t,e){return new r(t,e)},r})("ElasticOut",function(t){return this._p1*Math.pow(2,-10*t)*Math.sin((t-this._p3)*this._p2)+1},.3),c("ElasticIn",function(t){return-(this._p1*Math.pow(2,10*--t)*Math.sin((t-this._p3)*this._p2))},.3),c("ElasticInOut",function(t){return(t*=2)<1?this._p1*Math.pow(2,10*--t)*Math.sin((t-this._p3)*this._p2)*-.5:this._p1*Math.pow(2,-10*--t)*Math.sin((t-this._p3)*this._p2)*.5+1},.45)),e("Expo",t("ExpoOut",function(t){return 1-Math.pow(2,-10*t)}),t("ExpoIn",function(t){return Math.pow(2,10*(t-1))-.001}),t("ExpoInOut",function(t){return(t*=2)<1?.5*Math.pow(2,10*(t-1)):.5*(2-Math.pow(2,-10*(t-1)))})),e("Sine",t("SineOut",function(t){return Math.sin(t*h)}),t("SineIn",function(t){return 1-Math.cos(t*h)}),t("SineInOut",function(t){return-.5*(Math.cos(Math.PI*t)-1)})),_("easing.EaseLookup",{find:function(t){return d.map[t]}},!0),u(a.SlowMo,"SlowMo","ease,"),u(s,"RoughEase","ease,"),u(r,"SteppedEase","ease,"),o},!0)}),_gsScope._gsDefine&&_gsScope._gsQueue.pop()(),function(m,f){"use strict";var c={},p=m.document,d=m.GreenSockGlobals=m.GreenSockGlobals||m,t=d[f];if(t)"undefined"!=typeof module&&module.exports&&(module.exports=t);else{var g,e,I,N=function(t){for(var e=t.split("."),i=d,r=0;r=e&&tthis._duration?this._duration:t,e)):this._time},n.totalTime=function(t,e,i){if(g||R.wake(),!arguments.length)return this._totalTime;if(this._timeline){if(t<0&&!i&&(t+=this.totalDuration()),this._timeline.smoothChildTiming){this._dirty&&this.totalDuration();var r=this._totalDuration,n=this._timeline;if(rs;)n=n._prev;return n?(t._next=n._next,n._next=t):(t._next=this._first,this._first=t),t._next?t._next._prev=t:this._last=t,t._prev=n,this._recent=t,this._timeline&&this._uncache(!0),this},n._remove=function(t,e){return t.timeline===this&&(e||t._enabled(!1,!0),t._prev?t._prev._next=t._next:this._first===t&&(this._first=t._next),t._next?t._next._prev=t._prev:this._last===t&&(this._last=t._prev),t._next=t._prev=t.timeline=null,t===this._recent&&(this._recent=this._last),this._timeline&&this._uncache(!0)),this},n.render=function(t,e,i){var r,n=this._first;for(this._totalTime=this._time=this._rawPrevTime=t;n;)r=n._next,(n._active||t>=n._startTime&&!n._paused&&!n._gc)&&(n._reversed?n.render((n._dirty?n.totalDuration():n._totalDuration)-(t-n._startTime)*n._timeScale,e,i):n.render((t-n._startTime)*n._timeScale,e,i)),n=r},n.rawTime=function(){return g||R.wake(),this._totalTime},x("TweenLite",function(t,e,i){if(o.call(this,e,i),this.render=C.prototype.render,null==t)throw"Cannot tween a null target.";this.target=t="string"==typeof t&&C.selector(t)||t;var r,n,s,i=t.jquery||t.length&&t!==m&&t[0]&&(t[0]===m||t[0].nodeType&&t[0].style&&!t.nodeType),a=this.vars.overwrite;if(this._overwrite=a=null==a?tt[C.defaultOverwrite]:"number"==typeof a?a>>0:tt[a],(i||t instanceof Array||t.push&&v(t))&&"number"!=typeof t[0])for(this._targets=s=X(t),this._propLookup=[],this._siblings=[],r=0;r=et){for(i in et=R.frame+(parseInt(C.autoSleep,10)||120),l){for(t=(e=l[i].tweens).length;-1<--t;)e[t]._gc&&e.splice(t,1);0===e.length&&delete l[i]}if((!(i=_._first)||i._paused)&&C.autoSleep&&!h._first&&1===R._listeners.tick.length){for(;i&&i._paused;)i=i._next;i||R.sleep()}}},R.addEventListener("tick",o._updateRoot),function(t,e,i){var r,n,s=t._gsTweenID;if(l[s||(t._gsTweenID=s="t"+K++)]||(l[s]={target:t,tweens:[]}),e&&((r=l[s].tweens)[n=r.length]=e,i))for(;-1<--n;)r[n]===e&&r.splice(n,1);return l[s].tweens}),it=function(t,e,i,r){var n,s,a=t.vars.onOverwrite;return a&&(n=a(t,e,i,r)),(a=C.onOverwrite)&&(s=a(t,e,i,r)),!1!==n&&!1!==s},rt=function(t,e,i,r,n){var s,a,o;if(1===r||4<=r){for(o=n.length,c=0;ch&&((f||!a._initted)&&h-a._startTime<=2e-8||(_[u++]=a)));for(c=u;-1<--c;)o=(a=_[c])._firstPT,2===r&&a._kill(i,t,e)&&(s=!0),(2!==r||!a._firstPT&&a._initted&&o)&&(2===r||it(a,e))&&a._enabled(!1,!1)&&(s=!0)}return s},nt=function(t,e,i){for(var r=t._timeline,n=r._timeScale,s=t._startTime;r._timeline;){if(s+=r._startTime,n*=r._timeScale,r._paused)return-100;r=r._timeline}return e<(s/=n)?s-e:i&&s===e||!t._initted&&s-e<2e-8?y:(s+=t.totalDuration()/t._timeScale/n)>e+y?0:s-e-y},E=(n._init=function(){var t,e,i,r,n,s,a=this.vars,o=this._overwrittenProps,l=this._duration,h=!!a.immediateRender,_=a.ease,u=this._startAt;if(a.startAt){for(r in u&&(u.render(-1,!0),u.kill()),n={},a.startAt)n[r]=a.startAt[r];if(n.data="isStart",n.overwrite=!1,n.immediateRender=!0,n.lazy=h&&!1!==a.lazy,n.startAt=n.delay=null,n.onUpdate=a.onUpdate,n.onUpdateParams=a.onUpdateParams,n.onUpdateScope=a.onUpdateScope||a.callbackScope||this,this._startAt=C.to(this.target||{},0,n),h)if(0o.pr;)r=r._next;(o._prev=r?r._prev:s)?o._prev._next=o:n=o,(o._next=r)?r._prev=o:s=o,o=a}o=e._firstPT=n}for(;o;)o.pg&&"function"==typeof o.t[t]&&o.t[t]()&&(i=!0),o=o._next;return i},E.activate=function(t){for(var e=t.length;-1<--e;)t[e].API===E.API&&(D[(new t[e])._propName]=t[e]);return!0},r.plugin=function(t){if(!(t&&t.propName&&t.init&&t.API))throw"illegal plugin definition.";var e,i=t.propName,r=t.priority||0,n=t.overwriteProps,s={init:"_onInitTween",set:"setRatio",kill:"_kill",round:"_mod",mod:"_mod",initAll:"_onInitAllProps"},a=x("plugins."+i.charAt(0).toUpperCase()+i.substr(1)+"Plugin",function(){E.call(this,i,r),this._overwriteProps=n||[]},!0===t.global),o=a.prototype=new E(i);for(e in(o.constructor=a).API=t.API,s)"function"==typeof t[e]&&(o[s[e]]=t[e]);return a.version=t.version,E.activate([a]),a},s=m._gsQueue){for(a=0;a 0) { - infos.forEach(info => errors.removeChild(info)); + infos.forEach((info) => errors.removeChild(info)); } else { this.expandErrors(); } @@ -428,7 +428,7 @@ // Register more informative error handler window.addEventListener( 'error', - event => { + (event) => { if (typeof event.error == 'undefined') { // This sometimes happens in Edge. Since we have no error // position, we cannot do much beside an info log. @@ -440,7 +440,7 @@ true ); - document.addEventListener('DOMContentLoaded', event => { + document.addEventListener('DOMContentLoaded', (event) => { this.showErrors(); }); } @@ -465,7 +465,7 @@ static stop(event) { event.preventDefault(); // I removed this, as it destroys all the Hammer.js events. - // And also the click event. + // And also the click event. // It seems to have no (apparent) negative impact. -SO // event.stopPropagation() } @@ -528,7 +528,7 @@ clientX: t.clientX, clientY: t.clientY, pageX: t.pageX, - pageY: t.pageY + pageY: t.pageY, }); } return touches @@ -568,8 +568,8 @@ ctrlKey: event.ctrlKey, altKey: event.altKey, shiftKey: event.shiftKey, - metaKey: event.metaKey - } + metaKey: event.metaKey, + }, }; if (event.type.startsWith('touch')) { // On Safari-WebKit the TouchEvent has layerX, layerY coordinates @@ -666,7 +666,7 @@ width: '480px', height: '640px', overflow: 'auto', - backgroundColor: 'lightgray' + backgroundColor: 'lightgray', }); document.body.appendChild(element); this.popup = element; @@ -687,7 +687,7 @@ } Elements.setStyle(this.popup, { left: event.clientX + 'px', - top: event.clientY + 'px' + top: event.clientY + 'px', }); } } @@ -789,10 +789,10 @@ // Taken from: https://davidwalsh.name/essential-javascript-functions function debounce(func, wait, immediate) { let timeout; - return function() { + return function () { let context = this, args = arguments; - let later = function() { + let later = function () { timeout = null; if (!immediate) func.apply(context, args); }; @@ -936,14 +936,14 @@ // long version let r = hex.match(/^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i); if (r) { - return r.slice(1, 4).map(x => { + return r.slice(1, 4).map((x) => { return parseInt(x, 16) }) } // short version r = hex.match(/^#([0-9a-f])([0-9a-f])([0-9a-f])$/i); if (r) { - return r.slice(1, 4).map(x => { + return r.slice(1, 4).map((x) => { return 0x11 * parseInt(x, 16) }) } @@ -962,7 +962,7 @@ return { r: Math.round(lerp(rgb1.r, rgb2.r, amount)), g: Math.round(lerp(rgb1.g, rgb2.g, amount)), - b: Math.round(lerp(rgb1.b, rgb2.b, amount)) + b: Math.round(lerp(rgb1.b, rgb2.b, amount)), } } @@ -1073,7 +1073,7 @@ static arc(p, alpha, radius) { return { x: p.x + radius * Math.cos(alpha), - y: p.y + radius * Math.sin(alpha) + y: p.y + radius * Math.sin(alpha), } } @@ -1100,19 +1100,17 @@ } static fromPageToNode(element, p) { - // if (window.webkitConvertPointFromPageToNode) { - // return window.webkitConvertPointFromPageToNode(element, - // new WebKitPoint(p.x, p.y)) - // } - return window.convertPointFromPageToNode(element, p.x, p.y) + if (window.webkitConvertPointFromPageToNode) { + return window.webkitConvertPointFromPageToNode(element, new WebKitPoint(p.x, p.y)) + } + //return window.convertPointFromPageToNode(element, p.x, p.y) } static fromNodeToPage(element, p) { - // if (window.webkitConvertPointFromNodeToPage) { - // return window.webkitConvertPointFromNodeToPage(element, - // new WebKitPoint(p.x, p.y)) - // } - return window.convertPointFromNodeToPage(element, p.x, p.y) + if (window.webkitConvertPointFromNodeToPage) { + return window.webkitConvertPointFromNodeToPage(element, new WebKitPoint(p.x, p.y)) + } + //return window.convertPointFromNodeToPage(element, p.x, p.y) } } @@ -1136,7 +1134,7 @@ const i = sets.reduce((m, s, i) => (s.size < sets[m].size ? i : m), 0); const [smallest] = sets.splice(i, 1); const res = new Set(); - for (let val of smallest) if (sets.every(s => s.has(val))) res.add(val); + for (let val of smallest) if (sets.every((s) => s.has(val))) res.add(val); return res } @@ -1619,14 +1617,14 @@ static toUpperCaseEachWord(str, delim = ' ') { return str .split(delim) - .map(v => v.toUpperCaseFirstChar()) + .map((v) => v.toUpperCaseFirstChar()) .join(delim) } static toLowerCaseEachWord(str, delim = ' ') { return str .split(delim) - .map(v => v.toLowerCaseFirstChar()) + .map((v) => v.toLowerCaseFirstChar()) .join(delim) } } @@ -1720,14 +1718,14 @@ let logHandlers = { log: console.log, warn: console.warn, - error: console.error + error: console.error, }; try { ipc = window.ipcRenderer || require('electron').ipcRenderer; - logHandlers.log = message => ipc.send('log', message); - logHandlers.warn = message => ipc.send('warn', message); - logHandlers.error = message => ipc.send('error', message); + logHandlers.log = (message) => ipc.send('log', message); + logHandlers.warn = (message) => ipc.send('warn', message); + logHandlers.error = (message) => ipc.send('error', message); } catch (e) { console.log('Cannot use electron logging.'); } @@ -2328,7 +2326,7 @@ useCapture = true, capturePointerEvents = true, cancelOnWindowOut = true, - debug = false + debug = false, } = {} ) { this.debug = debug; @@ -2364,7 +2362,7 @@ if (this.debug) console.log('Pointer API' + window.PointerEvent); element.addEventListener( 'pointerdown', - e => { + (e) => { if (this.debug) console.log('pointerdown', e.pointerId); if (this.capture(e)) { if (this.capturePointerEvents) { @@ -2381,7 +2379,7 @@ ); element.addEventListener( 'pointermove', - e => { + (e) => { if (this.debug) console.log('pointermove', e.pointerId, e.pointerType); if (e.pointerType == 'touch' || (e.pointerType == 'mouse' && Events.isPointerDown(e))) { @@ -2394,7 +2392,7 @@ ); element.addEventListener( 'pointerup', - e => { + (e) => { if (this.debug) console.log('pointerup', e.pointerId, e.pointerType); this.onEnd(e); if (this.capturePointerEvents) { @@ -2409,7 +2407,7 @@ ); element.addEventListener( 'pointercancel', - e => { + (e) => { if (this.debug) console.log('pointercancel', e.pointerId, e.pointerType); this.onEnd(e); if (this.capturePointerEvents) element.releasePointerCapture(e.pointerId); @@ -2420,7 +2418,7 @@ if (!this.capturePointerEvents) { element.addEventListener( 'pointerleave', - e => { + (e) => { if (this.debug) console.log('pointerleave', e.pointerId, e.pointerType); if (e.target == element) this.onEnd(e); }, @@ -2431,7 +2429,7 @@ if (!this.capturePointerEvents) { element.addEventListener( 'pointerout', - e => { + (e) => { if (this.debug) console.log('pointerout', e.pointerId, e.pointerType); if (e.target == element) this.onEnd(e); }, @@ -2442,7 +2440,7 @@ if (this.cancelOnWindowOut) { window.addEventListener( 'pointerout', - e => { + (e) => { if (this.debug) console.log('pointerout', e.pointerId, e.pointerType, e.target); if (e.target == element) { this.onEnd(e); @@ -2455,7 +2453,7 @@ if (this.debug) console.log('Touch API'); element.addEventListener( 'touchstart', - e => { + (e) => { if (this.debug) console.log('touchstart', this.touchPoints(e)); if (this.capture(e)) { for (let touch of e.changedTouches) { @@ -2467,7 +2465,7 @@ ); element.addEventListener( 'touchmove', - e => { + (e) => { if (this.debug) console.log('touchmove', this.touchPoints(e), e); for (let touch of e.changedTouches) { this.onMove(touch); @@ -2480,7 +2478,7 @@ ); element.addEventListener( 'touchend', - e => { + (e) => { if (this.debug) console.log('touchend', this.touchPoints(e)); for (let touch of e.changedTouches) { this.onEnd(touch); @@ -2490,7 +2488,7 @@ ); element.addEventListener( 'touchcancel', - e => { + (e) => { if (this.debug) console.log('touchcancel', e.targetTouches.length, e.changedTouches.length); for (let touch of e.changedTouches) { this.onEnd(touch); @@ -2503,7 +2501,7 @@ element.addEventListener( 'mousedown', - e => { + (e) => { if (this.debug) console.log('mousedown', e); if (this.capture(e)) { this.onStart(e); @@ -2513,7 +2511,7 @@ ); element.addEventListener( 'mousemove', - e => { + (e) => { // Dow we only use move events if the mouse is down? // HOver effects have to be implemented by other means // && Events.isMouseDown(e)) @@ -2527,7 +2525,7 @@ ); element.addEventListener( 'mouseup', - e => { + (e) => { if (this.debug) console.log('mouseup', e); this.onEnd(e); }, @@ -2537,7 +2535,7 @@ if (!this.capturePointerEvents) { element.addEventListener( 'mouseout', - e => { + (e) => { if (e.target == element) { this.onEnd(e); console.warn("Shouldn't happen: mouseout ends interaction"); @@ -2549,7 +2547,7 @@ if (this.cancelOnWindowOut) { window.addEventListener( 'mouseout', - e => { + (e) => { if (e.target == element) { this.onEnd(e); } @@ -2722,7 +2720,7 @@ useCapture = true, capturePointerEvents = true, mouseWheelElement = null, - logInteractionsAbove = 12 + logInteractionsAbove = 12, } = {} ) { super(element, target, { @@ -2730,7 +2728,7 @@ useCapture, capturePointerEvents, longPressTime, - mouseWheelElement + mouseWheelElement, }); this.logInteractionsAbove = logInteractionsAbove; } @@ -2884,7 +2882,7 @@ hammer.get('tap').set(opts); } - hammer.on(type, event => { + hammer.on(type, (event) => { cb(event); }); @@ -2898,7 +2896,7 @@ } } else { for (let j = 0; j < elements.length; j++) { - Hammer.on(elements[j], type, event => { + Hammer.on(elements[j], type, (event) => { cb(event); }); } @@ -2929,7 +2927,7 @@ if (Hammer.__hammers.has(element)) { const elementHammers = Hammer.__hammers.get(element); - elementHammers.forEach(it => it.destroy()); + elementHammers.forEach((it) => it.destroy()); Hammer.__hammers.delete(element); } } @@ -3148,7 +3146,8 @@ */ class ScatterEvent extends BaseEvent { constructor( - target, { translate = { x: 0, y: 0 }, scale = null, rotate = 0, about = null, fast = false, type = null } = {} + target, + { translate = { x: 0, y: 0 }, scale = null, rotate = 0, about = null, fast = false, type = null } = {} ) { super('scatterTransformed', { target: target }); this.translate = translate; @@ -3198,7 +3197,7 @@ throwVisibility = 44, throwDamping = 0.95, autoThrow = true, - onThrowFinished = null + onThrowFinished = null, } = {}) { this.movableX = movableX; this.movableY = movableY; @@ -3209,7 +3208,7 @@ this.velocity = null; this.timestamp = null; this.onThrowFinished = onThrowFinished; - //console.log("onThrowFinished", onThrowFinished) + //console.log("onThrowFinished", onThrowFinished) } observeVelocity() { @@ -3231,13 +3230,12 @@ t: t, dt: dt, dx: delta.x / number, - dy: delta.y / number + dy: delta.y / number, }; this.velocities.push(velocity); while (this.velocities.length > buffer) { this.velocities.shift(); } - } } @@ -3287,7 +3285,7 @@ animateThrow(time) { if (this.velocity != null) { let dt = this._throwDeltaTime(); - // console.log("animateThrow", dt) + // console.log("animateThrow", dt) let next = this.nextVelocity(this.velocity); let prevLength = Points$1.length(this.velocity); let nextLength = Points$1.length(next); @@ -3330,7 +3328,7 @@ let next = Points$1.multiplyScalar(velocity, this.throwDamping); return { x: this.movableX ? next.x : 0, - y: this.movableY ? next.y : 0 + y: this.movableY ? next.y : 0, } } @@ -3375,7 +3373,7 @@ scaleCloseBuffer = 0.05, maxRotation = Angle.degree2radian(5), minInteractionDistance = 0, - useLowPassFilter = false + useLowPassFilter = false, } = {}) { if (rotationDegrees != null && rotation != null) { throw new Error('Use rotationDegrees or rotation but not both') @@ -3390,7 +3388,7 @@ throwVisibility, throwDamping, autoThrow, - onThrowFinished + onThrowFinished, }); /** @@ -3465,7 +3463,7 @@ _callCloseCallbacks() { if (this.onClose) { - this.onClose.forEach(callback => callback(this)); + this.onClose.forEach((callback) => callback(this)); } } @@ -3485,7 +3483,6 @@ let delta = interaction.delta(); if (delta != null) { - let rotate = delta.rotate; let zoom = delta.zoom; if (this.maxRotation != null) { @@ -3572,8 +3569,8 @@ keepOnStage(velocity, collision = 0.5) { let stagePolygon = this.containerPolygon; - // UO: since keepOnStage is called in nextVelocity we need to - // ensure a return value + // UO: since keepOnStage is called in nextVelocity we need to + // ensure a return value if (!stagePolygon) return { x: 0, y: 0 } this.polygon; let bounced = this.bouncing(); @@ -3584,7 +3581,7 @@ let dx = this.movableX ? velocity.x : 0; let dy = this.movableY ? velocity.y : 0; let factor = this.throwDamping; - // if (recentered) { + // if (recentered) { if (x < 0) { dx = -dx; factor = collision; @@ -3617,13 +3614,13 @@ if (this.scale < this.minScale + this.scaleCloseThreshold - this.scaleCloseBuffer) { this.zoom(this.minScale, { animate: 0.2, - onComplete: this.close.bind(this) + onComplete: this.close.bind(this), }); } else if (this.scale < this.minScale + this.scaleCloseThreshold) { - this.zoom(this.minScale + this.scaleCloseThreshold, { - animate: 0.4 - }); - } + this.zoom(this.minScale + this.scaleCloseThreshold, { + animate: 0.4, + }); + } } rotateDegrees(degrees, anchor) { @@ -3643,12 +3640,12 @@ x: '+=' + d.x, y: '+=' + d.y, /* scale: scale, uo: not defined, why was this here? */ - onUpdate: e => { + onUpdate: (e) => { let p = this.position; let dx = p.x - startPos.x; let dy = p.x - startPos.y; this.onMoved(dx, dy); - } + }, }); } else { this._move(d); @@ -3677,7 +3674,7 @@ scale: scale, delay: delay, onComplete: onComplete, - onUpdate: this.onZoomed.bind(this) + onUpdate: this.onZoomed.bind(this), }); } else { this.scale = scale; @@ -3687,7 +3684,7 @@ } _move(delta) { - // this.addVelocity(delta) uo: reverted commit fa0256d782dd498c6d3e51321260ca375ca9f855 + // this.addVelocity(delta) uo: reverted commit fa0256d782dd498c6d3e51321260ca375ca9f855 this.x += this.movableX ? delta.x : 0; this.y += this.movableX ? delta.y : 0; } @@ -3695,7 +3692,7 @@ transform(translate, zoom, rotate, anchor) { let delta = { x: this.movableX ? translate.x : 0, - y: this.movableY ? translate.y : 0 + y: this.movableY ? translate.y : 0, }; if (this.resizable) var vzoom = zoom; if (!this.translatable) delta = { x: 0, y: 0 }; @@ -3710,9 +3707,9 @@ rotate: 0, about: anchor, fast: false, - type: UPDATE + type: UPDATE, }); - this.onTransform.forEach(function(f) { + this.onTransform.forEach(function (f) { f(event); }); } @@ -3726,7 +3723,7 @@ let newOrigin = Points$1.arc(anchor, beta + rotate, distance * thresholdedZoom); let extra = Points$1.subtract(newOrigin, origin); const anchorOffset = Points$1.subtract(anchor, origin); - // this._move(offset) + // this._move(offset) this.scale = newScale; this.rotation += rotate; let offset = Points$1.negate(anchorOffset); @@ -3741,9 +3738,9 @@ translate: delta, scale: newScale, rotate: rotate, - about: anchor + about: anchor, }); - this.onTransform.forEach(function(f) { + this.onTransform.forEach(function (f) { f(event); }); } @@ -3809,7 +3806,7 @@ if (this.scale > this.maxScale) zoom = 1 - amount; if (zoom != 1) { this.transform({ x: 0, y: 0 }, zoom, 0, this.zoomAnchor); - requestAnimationFrame(dt => { + requestAnimationFrame((dt) => { this.animateZoomBounce(dt); }); return @@ -3866,9 +3863,9 @@ rotate: 0, about: null, fast: false, - type: START + type: START, }); - this.onTransform.forEach(function(f) { + this.onTransform.forEach(function (f) { f(event); }); } @@ -3902,9 +3899,9 @@ rotate: 0, about: null, fast: false, - type: END + type: END, }); - this.onTransform.forEach(function(f) { + this.onTransform.forEach(function (f) { f(event); }); } @@ -3932,9 +3929,9 @@ translate: delta, scale: this.scale, about: this.currentAbout, - type: null + type: null, }); - this.onTransform.forEach(function(f) { + this.onTransform.forEach(function (f) { f(event); }); } @@ -3946,9 +3943,9 @@ scale: this.scale, about: this.currentAbout, fast: false, - type: null + type: null, }); - this.onTransform.forEach(function(f) { + this.onTransform.forEach(function (f) { f(event); }); } @@ -3960,9 +3957,9 @@ translate: { x: dx, y: dy }, about: about, fast: true, - type: null + type: null, }); - this.onTransform.forEach(function(f) { + this.onTransform.forEach(function (f) { f(event); }); } @@ -3973,9 +3970,9 @@ let event = new ScatterEvent(this, { scale: this.scale, fast: false, - type: null + type: null, }); - this.onTransform.forEach(function(f) { + this.onTransform.forEach(function (f) { f(event); }); } @@ -3989,9 +3986,9 @@ scale: this.scale, about: about, fast: false, - type: null + type: null, }); - this.onTransform.forEach(function(f) { + this.onTransform.forEach(function (f) { f(event); }); } @@ -4016,13 +4013,14 @@ * @param {DOM node} debugCanvas - Shows debug infos about touches if not null */ constructor( - element, { + element, + { stopEvents = 'auto', claimEvents = true, useCapture = true, capturePointerEvents = true, touchAction = 'none', - debugCanvas = null + debugCanvas = null, } = {} ) { this.onCapture = null; @@ -4034,7 +4032,7 @@ movement of scatter objects, the touchmove event has to be bound again. */ if (Capabilities.isSafari) { - document.addEventListener('touchmove', event => this.preventPinch(event), false); + document.addEventListener('touchmove', (event) => this.preventPinch(event), false); stopEvents = false; } else { stopEvents = true; @@ -4049,11 +4047,11 @@ this.delegate = new InteractionMapper$1(element, this, { useCapture, capturePointerEvents, - mouseWheelElement: window + mouseWheelElement: window, }); if (debugCanvas !== null) { - requestAnimationFrame(dt => { + requestAnimationFrame((dt) => { this.showTouches(dt, debugCanvas); }); } @@ -4075,7 +4073,7 @@ context.fill(); context.stroke(); } - requestAnimationFrame(dt => { + requestAnimationFrame((dt) => { this.showTouches(dt, canvas); }); } @@ -4180,7 +4178,8 @@ class DOMScatter$1 extends AbstractScatter { constructor( element, - container, { + container, + { startScale = 1.0, minScale = 0.1, maxScale = 1.0, @@ -4216,7 +4215,7 @@ scaleCloseBuffer = 0.05, useLowPassFilter = false, maxRotation = Angle.degree2radian(15), - minInteractionDistance = 200 + minInteractionDistance = 200, } = {} ) { super({ @@ -4243,7 +4242,7 @@ onClose, useLowPassFilter, maxRotation, - minInteractionDistance + minInteractionDistance, }); if (container == null || width == null || height == null) { throw new Error('Invalid value: null') @@ -4271,7 +4270,7 @@ height: height, scale: startScale, rotation: this.startRotationDegrees, - transformOrigin: transformOrigin + transformOrigin: transformOrigin, }; this.tapNodes = new Map(); @@ -4293,15 +4292,15 @@ button.className = 'interactiveElement'; this.element.appendChild(button); - button.addEventListener('pointerdown', e => { + button.addEventListener('pointerdown', (e) => { this.startResize(e); }); - button.addEventListener('pointermove', e => { + button.addEventListener('pointermove', (e) => { this.resize(e); }); - button.addEventListener('pointerup', e => { + button.addEventListener('pointerup', (e) => { this.stopResize(e); }); this.resizeButton = button; @@ -4318,7 +4317,7 @@ scale: this.scale, x: this.x, y: this.y, - rotation: this.rotation + rotation: this.rotation, } } @@ -4369,7 +4368,7 @@ top: rect.top - stage.top, left: rect.left - stage.left, width: rect.width, - height: rect.height + height: rect.height, } } @@ -4377,10 +4376,10 @@ let r = this.bounds; let w2 = r.width / 2; let h2 = r.height / 2; - // if (this.resizable) { - // w2 *= this.scale - // h2 *= this.scale - // } + // if (this.resizable) { + // w2 *= this.scale + // h2 *= this.scale + // } var x = r.left + w2; var y = r.top + h2; return { x, y } @@ -4410,7 +4409,7 @@ set scale(scale) { TweenLite.set(this.element, { scale: scale, - transformOrigin: this.transformOrigin + transformOrigin: this.transformOrigin, }); this._scale = scale; } @@ -4442,9 +4441,9 @@ hide() { TweenLite.to(this.element, 0.1, { display: 'none', - onComplete: e => { + onComplete: (e) => { this.element.parentNode.removeChild(this.element); - } + }, }); } @@ -4458,7 +4457,7 @@ x: p.x, y: p.y, rotation: rotationDegrees, - transformOrigin: this.transformOrigin + transformOrigin: this.transformOrigin, }); } @@ -4500,7 +4499,7 @@ } this._x = x; this._y = y; - // this.addVelocity({ x: delta.x, y: delta.y }) uo: reverted commit fa0256d782dd498c6d3e51321260ca375ca9f855 + // this.addVelocity({ x: delta.x, y: delta.y }) uo: reverted commit fa0256d782dd498c6d3e51321260ca375ca9f855 TweenLite.set(this.element, { x, y }); } @@ -4519,7 +4518,7 @@ let oldPostition = { x: this.element.getBoundingClientRect().left, - y: this.element.getBoundingClientRect().top + y: this.element.getBoundingClientRect().top, }; this.bringToFront(); @@ -4527,7 +4526,7 @@ let newPostition = { x: this.element.getBoundingClientRect().left, - y: this.element.getBoundingClientRect().top + y: this.element.getBoundingClientRect().top, }; let offset = Points$1.subtract(oldPostition, newPostition); @@ -4572,7 +4571,7 @@ ) TweenLite.to(this.element, 0, { width: this.element.offsetWidth + resizeW / this.scale, - height: this.element.offsetHeight + resizeH / this.scale + height: this.element.offsetHeight + resizeH / this.scale, }); this.oldX = e.clientX; @@ -4589,12 +4588,12 @@ let event = new CustomEvent('resizeEnded'); let oldPostition = { x: this.element.getBoundingClientRect().left, - y: this.element.getBoundingClientRect().top + y: this.element.getBoundingClientRect().top, }; this.element.style.transformOrigin = '50% 50%'; let newPostition = { x: this.element.getBoundingClientRect().left, - y: this.element.getBoundingClientRect().top + y: this.element.getBoundingClientRect().top, }; let offset = Points$1.subtract(oldPostition, newPostition); @@ -4624,7 +4623,7 @@ handleClicks() { this.domNode.addEventListener( 'click', - event => { + (event) => { if (event.isTrusted) { Events.stop(event); if (this.triggerSVGClicks && this.isSVGNode(event.target)) { @@ -4639,7 +4638,7 @@ handleClicksAsTaps() { this.domNode.addEventListener( 'click', - event => { + (event) => { if (event.isTrusted) { Events.stop(event); } @@ -4706,20 +4705,20 @@ let globalClick = event.center ? event.center : { x: event.x, y: event.y }; let localClick = Points$1.fromPageToNode(element, globalClick); - let clickRects = activeNodes.map(link => { + let clickRects = activeNodes.map((link) => { let rect = link.getBoundingClientRect(); // Since the getBoundingClientRect is untransformed we cannot rely on it's size // We need a transformed bottom right to calculate local width and height let bottomRight = Points$1.fromPageToNode(element, { x: rect.x + rect.width, - y: rect.y + rect.height + y: rect.y + rect.height, }); let topLeft = Points$1.fromPageToNode(element, rect); let width = Math.abs(bottomRight.x - topLeft.x); let height = Math.abs(bottomRight.y - topLeft.y); let center = Points$1.fromPageToNode(element, { x: rect.x + width / 2, - y: rect.y + height / 2 + y: rect.y + height / 2, }); return { x: topLeft.x, @@ -4727,12 +4726,12 @@ width, height, center, - link + link, } }); let distances = []; - clickRects.forEach(rect => { + clickRects.forEach((rect) => { let distance = Points$1.distanceToRect(localClick, rect); distances.push(parseInt(distance)); }); @@ -4829,7 +4828,7 @@ scale = 1, minScale = 0.5, maxScale = 1.5, - rotation = 0 + rotation = 0, } = {} ) { this.src = src; @@ -4864,8 +4863,8 @@ load(domNode) { return new Promise((resolve, reject) => { - PDFJS.getDocument(this.src).then(pdf => { - pdf.getPage(1).then(page => { + PDFJS.getDocument(this.src).then((pdf) => { + pdf.getPage(1).then((page) => { let scale = this.scale * app.renderer.resolution; let invScale = 1 / scale; let viewport = page.getViewport(scale); @@ -4879,7 +4878,7 @@ // Render PDF page into canvas context. let renderContext = { canvasContext: context, - viewport: viewport + viewport: viewport, }; page.render(renderContext); domNode.appendChild(canvas); @@ -4899,7 +4898,7 @@ return new Promise((resolve, reject) => { let isImage = domNode instanceof HTMLImageElement; let image = isImage ? domNode : document.createElement('img'); - image.onload = e => { + image.onload = (e) => { if (!isImage) { domNode.appendChild(image); this.addedNode = image; @@ -4915,7 +4914,7 @@ image.height = image.naturalHeight; resolve(this); }; - image.onerror = e => { + image.onerror = (e) => { reject(this); }; image.src = this.src; @@ -4937,10 +4936,10 @@ domNode.appendChild(iframe); this.addedNode = iframe; } - iframe.onload = e => { + iframe.onload = (e) => { resolve(this); }; - iframe.onerror = e => { + iframe.onerror = (e) => { reject(this); }; iframe.src = this.src; @@ -4953,7 +4952,7 @@ return new Promise((resolve, reject) => { let xhr = new XMLHttpRequest(); xhr.open('GET', this.src, false); - xhr.onreadystatechange = e => { + xhr.onreadystatechange = (e) => { if (xhr.readyState == 4) { domNode.innerHTML = this.prepare(xhr.response); this.addedNode = domNode.firstElementChild; @@ -4963,7 +4962,7 @@ resolve(this); } }; - xhr.onerror = e => { + xhr.onerror = (e) => { reject(this); }; xhr.send(); @@ -5021,7 +5020,7 @@ onClose = null, onUpdate = null, onRemoved = null, - onLoaded = null + onLoaded = null, } = {} ) { this.domScatterContainer = domScatterContainer; @@ -5063,8 +5062,8 @@ // call we can access the new dom element by id this.cardWrapper = dom.querySelector('#' + this.id); let front = this.cardWrapper.querySelector('.front'); - this.frontLoader.load(front).then(loader => { - this.frontLoaded(loader).then(obj => { + this.frontLoader.load(front).then((loader) => { + this.frontLoaded(loader).then((obj) => { if (this.onLoaded) this.onLoaded(); resolve(this); }); @@ -5088,7 +5087,7 @@ scalable: this.scalable, rotatable: this.rotatable, overdoScaling: this.overdoScaling, - tapDelegate: this.tapDelegateFactory ? new this.tapDelegateFactory(this.cardWrapper) : null + tapDelegate: this.tapDelegateFactory ? new this.tapDelegateFactory(this.cardWrapper) : null, }); if (this.center) { @@ -5096,7 +5095,7 @@ } if (this.closeOnMinScale) { - const removeOnMinScale = function() { + const removeOnMinScale = function () { if (scatter.scale <= scatter.minScale) { this.flippable.close(); @@ -5118,7 +5117,7 @@ let back = this.cardWrapper.querySelector('.back'); if (this.preloadBack) { - this.backLoader.load(back).then(loader => { + this.backLoader.load(back).then((loader) => { this.setupFlippable(flippable, loader); }); } @@ -5152,7 +5151,7 @@ } else { let back = this.cardWrapper.querySelector('.back'); let flippable = this.flippable; - this.backLoader.load(back).then(loader => { + this.backLoader.load(back).then((loader) => { this.setupFlippable(flippable, loader); flippable.start({ duration: this.flipDuration, targetCenter }); }); @@ -5164,7 +5163,7 @@ opacity: 0, onComplete: () => { this.cardWrapper.remove(); - } + }, }); } @@ -5212,7 +5211,7 @@ TweenLite.set(this.back, { rotationY: -180 }); TweenLite.set([this.back, this.front], { backfaceVisibility: 'hidden', - perspective: 5000 + perspective: 5000, }); TweenLite.set(this.front, { visibility: 'visible' }); this.infoBtn = element.querySelector('.infoBtn'); @@ -5224,18 +5223,18 @@ scatter.tapDelegate = tapDelegate; } if (this.infoBtn) { - scatter.tapDelegate.onTap(this.infoBtn, event => { + scatter.tapDelegate.onTap(this.infoBtn, (event) => { this.flip.start(); }); this.enable(this.infoBtn); } if (this.backBtn) { - scatter.tapDelegate.onTap(this.backBtn, event => { + scatter.tapDelegate.onTap(this.backBtn, (event) => { this.start(); }); } if (this.closeBtn) { - scatter.tapDelegate.onTap(this.closeBtn, event => { + scatter.tapDelegate.onTap(this.closeBtn, (event) => { this.close(); }); this.enable(this.closeBtn); @@ -5259,7 +5258,7 @@ if (this.onRemoved) { this.onRemoved.call(this); } - } + }, }); } } @@ -5288,7 +5287,7 @@ scaleButtons() { TweenLite.set([this.infoBtn, this.backBtn, this.closeBtn], { - scale: this.buttonScale + scale: this.buttonScale, }); } @@ -5401,7 +5400,7 @@ ease: Power1.easeOut, transformOrigin: '50% 50%', onUpdate, - onComplete: e => { + onComplete: (e) => { if (this.flipped) { //this.hide(this.front) this.enable(this.backBtn); @@ -5430,7 +5429,7 @@ this.scatter.translatable = translatable; this.scatter.rotatable = rotatable; }, - force3D: true + force3D: true, }); // See https://greensock.com/forums/topic/7997-rotate-the-shortest-way/ TweenLite.to(this.element, this.flipDuration / 2, { @@ -5442,7 +5441,7 @@ height: h, x: x, y: y, - onComplete: e => { + onComplete: (e) => { if (this.flipped) { this.hide(this.front); // this.hide(this.infoBtn) @@ -5450,7 +5449,7 @@ this.hide(this.back); // this.show(this.infoBtn) } - } + }, }); } } @@ -5476,7 +5475,7 @@ let icon = wrapper.querySelector('.icon'); - icon.onerror = e => { + icon.onerror = (e) => { if (this.notfound) icon.src = this.notfound; }; let iconSrc = src.replace('.html', '.png'); @@ -5504,7 +5503,7 @@ let icon = wrapper.querySelector('.icon'); icon.parentNode.replaceChild(iframe, icon); - iframe.onload = e => { + iframe.onload = (e) => { this.frames(); }; iframe.src = src + window.location.search; @@ -5654,7 +5653,7 @@ onResize = null, onMove = null, noStyle = false, - hideOnUp = true + hideOnUp = true, } = {}) { super(); this.context = context; @@ -5720,7 +5719,7 @@ img.style.top = '0px'; img.style.width = '16px'; img.style.height = '16px'; - img.onclick = e => { + img.onclick = (e) => { this.close(); }; this.element.appendChild(img); @@ -5734,17 +5733,17 @@ img.style.height = '16px'; img.src = this.resizeIcon; img.setAttribute('draggable', true); - img.ondragstart = e => { + img.ondragstart = (e) => { this.currentPos = { x: e.clientX, y: e.clientY }; return true }; - img.ondrag = e => { + img.ondrag = (e) => { e.preventDefault(); let target = this.element.querySelector('iframe') || this.element; let delta = { x: e.clientX - this.currentPos.x, - y: e.clientY - this.currentPos.y + y: e.clientY - this.currentPos.y, }; this.currentPos = { x: e.clientX, y: e.clientY }; @@ -5768,7 +5767,7 @@ this.onResize({ target, delta, width, height }); } }; - img.ondragend = e => {}; + img.ondragend = (e) => {}; this.element.appendChild(img); } @@ -5794,7 +5793,7 @@ let iframe = document.createElement('iframe'); iframe.setAttribute('frameBorder', 0); iframe.src = content[key]; - iframe.onload = e => { + iframe.onload = (e) => { let body = iframe.contentWindow.document.body; let observer = new MutationObserver(() => { this.iframeChanged(iframe); @@ -5803,7 +5802,7 @@ attributes: true, subtree: true, childList: true, - characterData: true + characterData: true, }); let w = Math.max(body.scrollWidth, body.offsetWidth); let h = Math.max(body.scrollHeight, body.offsetHeight); @@ -5845,7 +5844,7 @@ if (!image.complete && !image.src.startsWith('data:')) { total += 1; console.log('image not complete', image.src); - image.onload = e => { + image.onload = (e) => { count += 1; if (count == total) { this.loaded = true; @@ -5894,33 +5893,33 @@ if (window.PointerEvent) this.parent.addEventListener('pointerup', close.bind(this), { capture: true, - once: true + once: true, }); else if (window.TouchEvent) this.parent.addEventListener('touchend', close.bind(this), { capture: true, - once: true + once: true, }); else this.parent.addEventListener('mouseup', close.bind(this), { capture: true, - once: true + once: true, }); } else { if (window.PointerEvent) this.parent.addEventListener('pointerdown', close.bind(this), { capture: true, - once: true + once: true, }); else if (window.TouchEvent) this.parent.addEventListener('touchstart', close.bind(this), { capture: true, - once: true + once: true, }); else this.parent.addEventListener('mousedown', close.bind(this), { capture: true, - once: true + once: true, }); } } @@ -5951,17 +5950,17 @@ if (this.draggable) { let target = this.element; target.setAttribute('draggable', true); - target.ondragstart = e => { + target.ondragstart = (e) => { this.currentPos = { x: e.clientX, y: e.clientY }; var img = document.createElement('img'); img.src = 'data:image/gifbase64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7'; e.dataTransfer.setDragImage(img, 0, 0); }; - target.ondrag = e => { + target.ondrag = (e) => { e.preventDefault(); let delta = { x: e.clientX - this.currentPos.x, - y: e.clientY - this.currentPos.y + y: e.clientY - this.currentPos.y, }; this.currentPos = { x: e.clientX, y: e.clientY }; let left = parseFloat(target.style.left); @@ -5977,7 +5976,7 @@ this.lastDrag = { left, top }; }; - target.ondragend = e => { + target.ondragend = (e) => { target.style.left = this.lastDrag.left + 'px'; target.style.top = this.lastDrag.top + 'px'; this.currentPos = null; @@ -6103,14 +6102,14 @@ withinDimensions() { return { width: this.keepWithin.offsetWidth, - height: this.keepWithin.offsetHeight + height: this.keepWithin.offsetHeight, } } localDimensions() { return { width: this.element.offsetWidth, - height: this.element.offsetHeight + height: this.element.offsetHeight, } } @@ -6261,7 +6260,7 @@ let style = { maxWidth: this.maxWidth + 'px', zIndex: this.zIndex, - position: 'absolute' + position: 'absolute', }; if (this.minWidth) { style.minWidth = this.minWidth + 'px'; @@ -6275,7 +6274,7 @@ fontFamily: this.fontFamily, fontSize: this.fontSize, stroke: 'black', - fill: 'white' + fill: 'white', }); } @@ -6312,7 +6311,7 @@ borderTopWidth: this.notchSize + 'px', borderRight: this.notchSize + 'px solid transparent', borderLeft: this.notchSize + 'px solid transparent', - borderBottom: 0 + borderBottom: 0, } } else { return { @@ -6325,7 +6324,7 @@ borderTop: this.notchSize + 'px solid ' + this.backgroundColor, borderRight: this.notchSize + 'px solid transparent', borderLeft: this.notchSize + 'px solid transparent', - borderBottom: 0 + borderBottom: 0, } } } @@ -6341,7 +6340,7 @@ borderBottomWidth: this.notchSize + 'px', borderRight: this.notchSize + 'px solid transparent', borderLeft: this.notchSize + 'px solid transparent', - borderTop: 0 + borderTop: 0, } } else { return { @@ -6353,7 +6352,7 @@ borderBottom: this.notchSize + 'px solid ' + this.backgroundColor, borderRight: this.notchSize + 'px solid transparent', borderLeft: this.notchSize + 'px solid transparent', - borderTop: 0 + borderTop: 0, } } } @@ -6379,7 +6378,7 @@ borderLeftWidth: this.notchSize, position: 'absolute', borderTop: this.notchSize + 'px solid transparent', - borderBottom: this.notchSize + 'px solid transparent' + borderBottom: this.notchSize + 'px solid transparent', } } else { let borderRight = this.notchSize + 'px solid transparent'; @@ -6408,7 +6407,7 @@ // boxShadow, position: 'absolute', borderTop: this.notchSize + 'px solid transparent', - borderBottom: this.notchSize + 'px solid transparent' + borderBottom: this.notchSize + 'px solid transparent', } } } @@ -6447,7 +6446,7 @@ useEventPosWithBoundingBox = false, interactive = false, onResize = null, - onMove = null + onMove = null, } = {} ) { let notchPosition = switchPos && point.y < 50 ? 'topCenter' : 'bottomCenter'; @@ -6476,7 +6475,7 @@ useEventPosWithBoundingBox, interactive, onResize, - onMove + onMove, }); popup.register(context); popup.showAt(content, point); @@ -6582,7 +6581,7 @@ highlightColor = 'black', notchPosition = 'bottomLeft', keepWithin = null, - autoClose = true + autoClose = true, } = {}) { super({ parent, @@ -6594,7 +6593,7 @@ backgroundColor, keepWithin, normalColor, - autoClose + autoClose, }); this.commands = commands; this.zIndex = zIndex; @@ -6623,21 +6622,21 @@ item.style.paddingBottom = item.style.paddingTop = this.spacing; Elements$1.setStyle(item, { color: this.normalColor, - cursor: 'default' + cursor: 'default', }); Elements$1.addClass(item, 'unselectable'); Elements$1.addClass(item, 'popupMenuItem'); this.items[key] = item; - item.onclick = event => { + item.onclick = (event) => { this.perform(event, key); }; - item.ontap = event => { + item.ontap = (event) => { this.perform(event, key); }; - item.onmouseover = event => { + item.onmouseover = (event) => { this.over(event, key); }; - item.onmouseout = event => { + item.onmouseout = (event) => { this.out(event, key); }; } @@ -6738,7 +6737,7 @@ keepWithin = null, backgroundColor = '#EEE', normalColor = '#444', - autoClose = true + autoClose = true, } = {} ) { let registered = Poppable.get(context); @@ -6762,11 +6761,11 @@ normalColor, notchPosition, keepWithin, - autoClose + autoClose, }); popup.showAt(commands, point); popup.register(context); - popup.closeEventListener = e => { + popup.closeEventListener = (e) => { if (this.eventOutside(e)) this.closePopup(context); }; if (autoClose) { @@ -6798,7 +6797,7 @@ constructor(element) { this.element = element; this.delegate = new InteractionMapper(element, this, { - mouseWheelElement: window + mouseWheelElement: window, }); } @@ -6840,7 +6839,7 @@ bubbles: true, cancelable: true, clientX: p.x, - clientY: p.y + clientY: p.y, }); this.target.dispatchEvent(event); } @@ -6872,7 +6871,7 @@ radiusX: 2.5, radiusY: 2.5, rotationAngle: 10, - force: 0.5 + force: 0.5, }); const touchEvent = new TouchEvent(type, { @@ -6881,7 +6880,7 @@ touches: [touchObj], targetTouches: [touchObj], changedTouches: [touchObj], - shiftKey: false + shiftKey: false, }); if (this.debug) console.log('simulateTouchEventChrome', touchEvent); this.target.dispatchEvent(touchEvent); @@ -6894,7 +6893,7 @@ bubbles: true, cancelable: true, clientX: p.x, - clientY: p.y + clientY: p.y, }; data[touchEventKey] = this.createTouchList(pointMap); let event = new TouchEvent(type, data); @@ -7010,7 +7009,7 @@ timeScale: 1, eventType: 'auto', debug: false, - defaultInterval: null + defaultInterval: null, }, opts ); @@ -7021,7 +7020,7 @@ Object.assign( {}, { - paused: true + paused: true, }, this.opts ) @@ -7137,7 +7136,7 @@ element, position, timelinePosition, - opts + opts, }); // opts @@ -7151,7 +7150,7 @@ eventType: null, context: window, bubbles: true, - cancelable: true + cancelable: true, }, opts ); @@ -7164,7 +7163,7 @@ // timeline //-------------------- this._timeline.addCallback( - position => { + (position) => { // element //-------------------- const elem = Util.extractElement(opts.context, element); @@ -7191,7 +7190,7 @@ //-------------------- const eventOpts = { bubbles: opts.bubbles, - cancelable: opts.cancelable + cancelable: opts.cancelable, }; if (opts.eventTypes[0]) { @@ -7258,7 +7257,7 @@ element, position, timelinePosition, - opts + opts, }); // opts @@ -7275,7 +7274,7 @@ eventTypes: this.resolveEvents(['down', 'move', 'up']), context: window, bubbles: true, - cancelable: true + cancelable: true, }, opts ); @@ -7283,7 +7282,7 @@ // timeline //-------------------- this._timeline.addCallback( - position => { + (position) => { // element //-------------------- const elem = Util.extractElement(opts.context, element); @@ -7296,7 +7295,7 @@ //-------------------- const eventOpts = { bubbles: opts.bubbles, - cancelable: opts.cancelable + cancelable: opts.cancelable, }; const gsOpts = { @@ -7339,7 +7338,7 @@ if (opts.onComplete) { opts.onComplete.call(this, event); } - } + }, }; // to @@ -7392,7 +7391,7 @@ element, position, timelinePosition, - opts + opts, }); // opts @@ -7412,7 +7411,7 @@ eventTypes: this.resolveEvents(['down', 'move', 'up']), context: window, bubbles: true, - cancelable: true + cancelable: true, }, opts ); @@ -7420,7 +7419,7 @@ // timeline //-------------------- this._timeline.addCallback( - position => { + (position) => { // element //-------------------- const elem = Util.extractElement(opts.context, element); @@ -7472,7 +7471,7 @@ bubbles: opts.bubbles, cancelable: opts.cancelable, pointerId: key, - isPrimary: key === 0 + isPrimary: key === 0, }; const gsOpts = { @@ -7515,7 +7514,7 @@ if (opts.onComplete && (opts.doubleCallbacks || key === 0)) { opts.onComplete.call(this, event); } - } + }, }; // to @@ -7644,7 +7643,7 @@ const data = []; if (this.opts.eventType === 'pointer') { - events.forEach(it => { + events.forEach((it) => { if (it === 'down') { data.push('pointerdown'); } else if (it === 'move') { @@ -7654,7 +7653,7 @@ } }); } else if (this.opts.eventType === 'touch') { - events.forEach(it => { + events.forEach((it) => { if (it === 'down') { data.push('touchstart'); } else if (it === 'move') { @@ -7664,7 +7663,7 @@ } }); } else { - events.forEach(it => { + events.forEach((it) => { if (it === 'down') { data.push('mousedown'); } else if (it === 'move') { @@ -7752,11 +7751,11 @@ if (Array.isArray(opts.bezier)) { bezier = { - values: opts.bezier.map(it => Util.extractPosition(it)), - type: 'thru' + values: opts.bezier.map((it) => Util.extractPosition(it)), + type: 'thru', }; } else { - opts.bezier.values = opts.bezier.values.map(it => Util.extractPosition(it)); + opts.bezier.values = opts.bezier.values.map((it) => Util.extractPosition(it)); bezier = opts.bezier; } @@ -7781,29 +7780,29 @@ const objects = []; if (opts.bezier) { - opts.bezier.forEach(it => { + opts.bezier.forEach((it) => { let bezier = null; if (Array.isArray(it)) { bezier = { - values: it.map(it => Util.extractPosition(it)), - type: 'thru' + values: it.map((it) => Util.extractPosition(it)), + type: 'thru', }; } else { - it.values = it.values.map(it => Util.extractPosition(it)); + it.values = it.values.map((it) => Util.extractPosition(it)); bezier = it; } objects.push({ - bezier + bezier, }); }); } else { - opts.to.forEach(it => { + opts.to.forEach((it) => { const to = Util.extractPosition(it); objects.push({ x: to.x, - y: to.y + y: to.y, }); }); } @@ -7900,13 +7899,13 @@ const eventOpts = { bubbles: true, cancelable: true, - composed: false + composed: false, }; // UIEventInit const uiEventOpts = { detail: 0, - view: window + view: window, }; // MouseEvent @@ -7922,7 +7921,7 @@ button: 0, buttons: 1, relatedTarget: null, - region: null + region: null, }; // TouchEvent @@ -7933,7 +7932,7 @@ ctrlKey: false, shiftKey: false, altKey: false, - metaKey: false + metaKey: false, }; // PointerEvent @@ -7947,7 +7946,7 @@ tiltY: 0, twist: 0, pointerType: 'touch', - isPrimary: true + isPrimary: true, }; if (type.startsWith('pointer')) { @@ -8059,7 +8058,7 @@ obj.classList.add(this.expandedClass); obj.setAttribute('stroke-width', stroke / scale); if (onComplete) onComplete(); - } + }, }); } @@ -8078,7 +8077,7 @@ obj.classList.remove('zooming'); obj.classList.remove(this.expandedClass); obj.setAttribute('stroke-width', stroke); - } + }, }); } @@ -8128,7 +8127,7 @@ this.shrink(maskImage, { stroke }); return } - let circles = Array.from(circleGroup.children).filter(e => e.tagName == 'circle'); + let circles = Array.from(circleGroup.children).filter((e) => e.tagName == 'circle'); for (let c of circles) { //console.log("shrinking all circles") this.shrink(c, { stroke }); @@ -8175,18 +8174,18 @@ // eslint-disable-next-line no-unused-vars let [mask, maskImage] = this._getSVGMask(target, { svgRoot, - image + image, }); let center = this._calculateCenterRelativeTo(target, image); console.log('_calculateCenterRelativeTo', center); TweenLite.set(maskImage, { - transformOrigin: `${center.x} ${center.y}` + transformOrigin: `${center.x} ${center.y}`, }); TweenLite.set(target, { transformOrigin: '50% 50%' }); TweenLite.to([target, maskImage], animation, { scale, - onComplete: onExpanded + onComplete: onExpanded, }); target.classList.add(this.expandedClass); @@ -8224,7 +8223,7 @@ [mask, maskImage] = this._createSVGMask(circle, { svgRoot, image, - id + id, }); return [mask, maskImage] @@ -8318,7 +8317,7 @@ let [mask, maskImage] = this._getSVGMask(target); // console.log('Close Highlight', maskImage) TweenLite.to([target, maskImage], animation, { - scale: 1 + scale: 1, }); } @@ -8371,7 +8370,7 @@ context.classList.add('info-card'); context.setAttribute('data-id', Card.id++); - modules.forEach(module => { + modules.forEach((module) => { if (module.apply(context)) { const moduleName = module.constructor.name; context.modules.push(moduleName); @@ -8473,7 +8472,7 @@ */ static _replaceAttributes(context, html, attribute, replaceFunc) { let attributeCarrier = html.querySelectorAll(`[${attribute}]`); - attributeCarrier.forEach(element => { + attributeCarrier.forEach((element) => { let attributeVal = element.getAttribute(attribute); element.removeAttribute(attribute); replaceFunc.call(this, context, element, attributeVal); @@ -8492,7 +8491,7 @@ */ static _replaceCallback(context, element, attributeVal) { if (element.tagName == 'A') { - element.addEventListener('pointerdown', event => { + element.addEventListener('pointerdown', (event) => { event.preventDefault(); }); } @@ -8505,7 +8504,7 @@ trimmedArgs = trimmedArgs.substring(0, trimmedArgs.length - 1); let callParts = funcPart.split('.'); - let argsStrings = trimmedArgs.split(',').filter(entry => { + let argsStrings = trimmedArgs.split(',').filter((entry) => { return entry.trim() != '' }); /** @@ -8534,12 +8533,12 @@ // These are 'hardcoded' inside the convert.js. if (element.tagName == 'circle') return false - this.registerEvent(context, interactionType, element, event => { + this.registerEvent(context, interactionType, element, (event) => { /** * Replaces the strings from the listener with the corresponding variables. */ let args = []; - argsStrings.forEach(arg => { + argsStrings.forEach((arg) => { arg = arg.trim(); if (arg == 'this') args.push(event.target); else if (arg == 'event') args.push(event); @@ -8585,7 +8584,7 @@ */ return html.replace( /<\s*(a|video|img|image|circle)\s(.*?)(xlink:href|href|src)\s*=\s*["'](\..*?)["']\s*(.*?)>/g, - function() { + function () { let path = that._getRelativePath(arguments[4]); const tag = `<${arguments[1]} ${arguments[2]} ${arguments[3]}="${path}" ${arguments[5]}>`; /* if (that.debug) */ console.log('Adjusted: ', tag); @@ -8614,7 +8613,7 @@ return new Promise((resolve, reject) => { let request = new XMLHttpRequest(); - request.onreadystatechange = function() { + request.onreadystatechange = function () { if (this.readyState == 4) { if (this.status == 200 || Card._isLocal()) { try { @@ -8739,7 +8738,7 @@ } this._createPopup(context, position, content, options) - .then(popup => { + .then((popup) => { if ( //Test if meanwhile another popup was registered... this._getPopup(context) || @@ -8757,9 +8756,9 @@ // let unnecessaryPopupElement = popup.element.querySelector(".popupContent > .popup") // unnecessaryPopupElement.classList.remove("popup") - popupParagraphs.forEach(popupParagraph => { + popupParagraphs.forEach((popupParagraph) => { popupParagraph.setAttribute('draggable', false); - popupParagraph.addEventListener('mousedown', event => { + popupParagraph.addEventListener('mousedown', (event) => { event.preventDefault(); }); }); @@ -8767,7 +8766,7 @@ this._setPopup(context, popup, src); } }) - .catch(e => console.error(e)); + .catch((e) => console.error(e)); } /** @@ -8807,14 +8806,14 @@ Object.assign( { parent: context, - content + content, }, Object.assign( { noStyle: true, // TODO: Remove offset when positioning according to element position // is working. - posOffset: 10 + posOffset: 10, }, options ) @@ -8826,7 +8825,7 @@ // We manually prevent this here. popup.element.style.display = 'none'; - let promise = new Promise(resolve => { + let promise = new Promise((resolve) => { if (popup.loaded) resolve(popup); else { popup.onload = () => { @@ -8835,7 +8834,7 @@ } }); - promise.then(popup => { + promise.then((popup) => { popup.element.style.display = 'block'; popup.element.style.visibility = 'hidden'; popup.element.style.opacity = 0; @@ -8847,12 +8846,12 @@ }); Object.assign(popup.element.style, { - zIndex: this.zIndices.popup + zIndex: this.zIndices.popup, }); TweenLite.to(popup.element, this.animation.popup, { autoAlpha: 1, - ease: Power2.easeIn + ease: Power2.easeIn, }); }); @@ -8876,7 +8875,7 @@ popup.remove(); //this._cleanup(context) //overlay.parentNode.removeChild(overlay) - } + }, }); } } @@ -8934,7 +8933,7 @@ let popupPage = parser.parseFromString(xhr.responseText, 'text/html'); //Fix the relative path of loaded images in the popup. - popupPage.querySelectorAll('img').forEach(node => { + popupPage.querySelectorAll('img').forEach((node) => { node.setAttribute('src', that._getRelativePath(node.getAttribute('src'))); }); let html = popupPage.body.innerHTML; @@ -8964,7 +8963,7 @@ if (editable) { let isDirty = mainController.askSaveNode(); if (isDirty) - mainController.saveNode(html.innerHTML, url => { + mainController.saveNode(html.innerHTML, (url) => { if (callback) { callback(); } @@ -8986,12 +8985,12 @@ }; Card._openPopup(context, src, local, content, { - closeCommand: callback + closeCommand: callback, }); } } - overlay.onclick = e => { + overlay.onclick = (e) => { if (editable) e.preventDefault(); }; //console.log("onreadystatechange", editable) @@ -9028,7 +9027,7 @@ for (let highlight of correspondingHighlights) { if (highlight.parentNode && highlight.parentNode.nodeName.toLowerCase() == 'g') { Highlight.openHighlight(highlight, { - animation: Card.highlightAnimation + animation: Card.highlightAnimation, }); this._addHighlight(context, highlight); } @@ -9157,19 +9156,19 @@ // TODO: Adjust to load while animating (Problem: Unload when cancelled). // console.log('loadHighlightPopup', src, position, local) this._loadPopupContent(context, src) - .then(content => { + .then((content) => { this._openPopup(context, src, local, content, { highlight: node, - closeCommand: popup => { + closeCommand: (popup) => { this._overlayCleanup(context, overlay); popup.remove(); - } + }, }); }) - .catch(err => { + .catch((err) => { console.error(err); }); - } + }, }); } } @@ -9253,7 +9252,7 @@ let globalBottomRight = { x: imageWidth, - y: imageHeight + y: imageHeight, }; globalBottomRight = Points.fromNodeToPage(zoomable, globalBottomRight); @@ -9319,7 +9318,7 @@ position: 'absolute', top: 0, left: 0, - zIndex: 200 + zIndex: 200, }); wrapper.appendChild(zoomContainer); @@ -9387,13 +9386,13 @@ y: current.y, width: current.width + borderX, height: current.height + borderY, - transformOrigin + transformOrigin, }); TweenLite.set(zoomable, { opacity: 0 }); let icon = zoomedFig.querySelector('.icon'); TweenLite.set(icon, { - transformOrigin + transformOrigin, }); zoomedFig.style.transformOrigin = 'calc(100% - ' + @@ -9413,8 +9412,8 @@ ease: Power2.easeIn, css: { scaleX: scaleFactor, - scaleY: scaleFactor - } + scaleY: scaleFactor, + }, }, 0 ) @@ -9423,11 +9422,11 @@ display: 'block', opacity: 0, x: -parseFloat(zoomedFigStyle.borderLeftWidth), - width: current.width + borderX - } + width: current.width + borderX, + }, }) .to(zoomCaption, this.animation.fade, { - autoAlpha: 1 + autoAlpha: 1, }); } else this._openZoomableEditorBehaviour(wrapper, img, zoomable, zoomedFig, current); } @@ -9476,7 +9475,7 @@ x: current.x, y: current.y, width: current.width, - height: current.height + height: current.height, }); let editor = mainController.topController().ensureEditor(img); let savedDisplay = zoomIcon.style.display; @@ -9503,13 +9502,13 @@ wrapper.appendChild(iconClone); TweenLite.set(iconClone, { x: current.iconPos.x, y: current.iconPos.y }); - zoomable.onmousedown = event => { + zoomable.onmousedown = (event) => { if (this.debug) console.log('mousedown', event.target); event.preventDefault(); zoomable.dragging = true; zoomable.dragStartPos = { x: event.pageX, y: event.pageY }; }; - zoomable.onmousemove = event => { + zoomable.onmousemove = (event) => { if (this.debug) console.log('onmousemove', event.target); if (zoomable.dragging) { event.preventDefault(); @@ -9517,7 +9516,7 @@ let dy = event.pageY - zoomable.dragStartPos.y; TweenLite.set([zoomable, iconClone], { x: '+=' + dx, - y: '+=' + dy + y: '+=' + dy, }); zoomable.dragStartPos = { x: event.pageX, y: event.pageY }; if (editor) { @@ -9530,7 +9529,7 @@ }; let startZoom = 1; - zoomable.onmousewheel = event => { + zoomable.onmousewheel = (event) => { event.preventDefault(); let direction = event.detail < 0 || event.wheelDelta > 0; const zoomFactor = 1.1; @@ -9566,24 +9565,24 @@ let zoomedCaption = zoomedFig.querySelector('figcaption.zoomcap'); TweenLite.to(zoomedCaption, this.animation.fade, { - autoAlpha: 0 + autoAlpha: 0, }); TweenLite.to(zoomedFig, this.animation.zoomable, { css: { scaleX: 1, - scaleY: 1 + scaleY: 1, }, onComplete: () => { TweenLite.set(zoomable, { - opacity: 1 + opacity: 1, }); let div = zoomedFig.parentNode; let videoElement = div.querySelector('video'); if (videoElement) videoElement.pause(); div.parentNode.removeChild(div); - } + }, }); InteractionMapper.off(zoomedFig); @@ -9657,12 +9656,12 @@ height: globalIndexCardRect.height, maxWidth: '100%', margin: 0, - zIndex: this.zIndices.article - } + zIndex: this.zIndices.article, + }, }); TweenLite.set(articleClone, { - autoAlpha: 0 + autoAlpha: 0, }); TweenLite.set(card, { css: { maxWidth: '100%' } }); @@ -9672,7 +9671,7 @@ scaleX, scaleY, transformOrigin: '0% 0%', - rotation: angle + rotation: angle, }); indexbox.prepend(clone); clone.setAttribute('data-source', src); @@ -9681,7 +9680,7 @@ let title = titlebar.querySelector('h2'); let titlebarStyle = window.getComputedStyle(titlebar); let start = { - height: parseInt(titlebarStyle.height) + height: parseInt(titlebarStyle.height), }; if (this.dynamicHeight) { @@ -9701,10 +9700,7 @@ //jquery hyphenate below if (this._isJQueryPresent()) { - $('.column') - .not('.overview') - .children('p') - .hyphenate('de'); + $('.column').not('.overview').children('p').hyphenate('de'); } //logging @@ -9730,23 +9726,23 @@ card.classList.add('visited'); }, onUpdateParams: ['{self}'], - onUpdate: self => { + onUpdate: (self) => { let transform = self.target._gsTransform; TweenLite.set(title, { - scale: 1 / transform.scaleX + scale: 1 / transform.scaleX, }); TweenLite.set(titlebar, { - height: (start.height * 1) / transform.scaleY + height: (start.height * 1) / transform.scaleY, }); // Retain the border at same visual thickness. titlebar.style.borderBottomWidth = desiredBorderBottomWidth / transform.scaleY + 'px'; - } + }, }); TweenLite.to([articleClone], this.animation.articleTransition / 2, { delay: this.animation.articleTransition / 2, - autoAlpha: 1 + autoAlpha: 1, }); if (editable) { @@ -9785,11 +9781,11 @@ if (editable) { let isDirty = mainController.askSaveNode(); if (isDirty) { - mainController.saveNode(html.innerHTML, url => { + mainController.saveNode(html.innerHTML, (url) => { callback(url); this._closeIndexCard(context, card, clone, articleClone, { eventElements, - src + src, }); }); } else { @@ -9828,7 +9824,7 @@ let scale = { x: globalPreviewRect.width / globalIndexCardRect.width, - y: globalPreviewRect.height / globalIndexCardRect.height + y: globalPreviewRect.height / globalIndexCardRect.height, }; let titlebar = clonedSubcard.querySelector('.titlebar'); @@ -9857,16 +9853,16 @@ let titlebarStyle = window.getComputedStyle(previewTitlebar); TweenLite.to(titlebar, this.animation.articleTransition, { - height: parseInt(titlebarStyle.height) + height: parseInt(titlebarStyle.height), }); TweenLite.to(clonedArticle, this.animation.articleTransition / 2, { - autoAlpha: 0 + autoAlpha: 0, }); let title = titlebar.querySelector('h2'); let original = { - height: parseInt(titlebarStyle.height) + height: parseInt(titlebarStyle.height), }; if (this.dynamicHeight) { @@ -9895,24 +9891,24 @@ mainController.popController(); } clonedSubcard.remove(); - } + }, }); }, onUpdateParams: ['{self}'], - onUpdate: function(self) { + onUpdate: function (self) { let transform = self.target._gsTransform; TweenLite.set(title, { - scale: 1 / transform.scaleX + scale: 1 / transform.scaleX, }); TweenLite.set(titlebar, { - height: (original.height * 1) / transform.scaleY + height: (original.height * 1) / transform.scaleY, }); // Retain the border at same visual thickness. titlebar.style.borderBottomWidth = desiredBorderBottomWidth / transform.scaleY + 'px'; - } + }, }); } @@ -9959,7 +9955,7 @@ * Called by the expandIndexCard(...) */ let target = event.target; - const saveCallback = url => { + const saveCallback = (url) => { let handler = `Card.openIndexCard(event, '${url}')`; if (this.debug) console.log('File has changed', target, handler); @@ -10050,9 +10046,9 @@ } let highlights = this._getHighlights(context); - highlights.forEach(highlight => { + highlights.forEach((highlight) => { Highlight.closeHighlight(highlight, { - animation: Card.highlightAnimation + animation: Card.highlightAnimation, }); }); @@ -10074,13 +10070,13 @@ let global = this._getGlobalRect(element); let localPosition = Points.fromPageToNode(context, { x: global.x, - y: global.y + y: global.y, }); return DOMRectReadOnly.fromRect({ x: localPosition.x, y: localPosition.y, width: global.width, - height: global.height + height: global.height, }) } @@ -10103,7 +10099,7 @@ x: globalPosition.x, y: globalPosition.y, width: cardWidth, - height: cardHeight + height: cardHeight, }) } @@ -10125,19 +10121,19 @@ this._replaceAttributes(context, html, 'onclick', this._replaceCallback); } let zoomableWrappers = html.querySelectorAll('.svg-wrapper'); - zoomableWrappers.forEach(wrapper => { + zoomableWrappers.forEach((wrapper) => { let svg = wrapper.querySelector('svg'); Object.assign(wrapper.style, { width: svg.getAttribute('width') + 'px', - height: svg.getAttribute('height') + 'px' + height: svg.getAttribute('height') + 'px', }); }); let zoomableVideoWrappers = html.querySelectorAll('.video-wrapper'); - zoomableVideoWrappers.forEach(wrapper => { + zoomableVideoWrappers.forEach((wrapper) => { let video = wrapper.querySelector('video'); Object.assign(wrapper.style, { width: video.getAttribute('width') + 'px', - height: video.getAttribute('height') + 'px' + height: video.getAttribute('height') + 'px', }); }); @@ -10176,12 +10172,12 @@ let globalClick = event.center ? event.center : { x: event.x, y: event.y }; let localClick = Points.fromPageToNode(indexbox, globalClick); - let linkRects = links.map(link => { + let linkRects = links.map((link) => { let rect = link.getBoundingClientRect(); let topLeft = Points.fromPageToNode(indexbox, rect); let center = Points.fromPageToNode(indexbox, { x: rect.x + rect.width / 2, - y: rect.y + rect.height / 2 + y: rect.y + rect.height / 2, }); return { x: topLeft.x, @@ -10189,12 +10185,12 @@ width: rect.width, height: rect.height, center, - link + link, } }); let distances = []; - linkRects.forEach(rect => { + linkRects.forEach((rect) => { let distance = Card.pointRectDist(localClick, rect); if (distance == 0.0) { // Distance == 0.0 indicates an inside relation. Since these @@ -10401,7 +10397,7 @@ article: 10, popup: 100, zoomable: 101, - zoomedFigure: 102 + zoomedFigure: 102, }; Card.animation = { @@ -10409,7 +10405,7 @@ fade: 0.2, popup: 0.1, highlight: 0.4, - zoomable: 0.5 + zoomable: 0.5, }; /** @@ -10478,12 +10474,12 @@ scatterContainer.element.appendChild(element); new DOMScatter(element, scatterContainer, { width: 1400, - height: 1200 + height: 1200, }); this.setup(element, html, { basePath, - modules + modules, }); return element } @@ -10544,15 +10540,15 @@ let url = basePath + '/' + item + '/index.html'; console.log('Loading', url); this.loadHTML(url) - .then(html => { + .then((html) => { console.log('Received', html); let element = this.createCardScatter(html, scatterContainer, { basePath, - modules + modules, }); resolve(element); }) - .catch(e => reject(e)); + .catch((e) => reject(e)); }) } @@ -10569,7 +10565,7 @@ ScatterCard.languages = ['Deutsch', 'English']; ScatterCard.languageTags = { Deutsch: 'de', - English: 'en' + English: 'en', }; ScatterCard.scatterContainer = null; @@ -10638,7 +10634,7 @@ let requirements = this._collectAllRequirements(); let missing = []; - requirements.forEach(module => { + requirements.forEach((module) => { if (context.modules.indexOf(module.name) == -1) { missing.push(module.name); } @@ -10696,12 +10692,12 @@ top: 0, left: 0, width: '100%', - height: '100%' + height: '100%', }, this.style, { display: 'none', - position: 'absolute' + position: 'absolute', } ); @@ -10774,7 +10770,7 @@ wrapper.appendChild(icon); Object.assign(wrapper.style, { - cursor: 'pointer' + cursor: 'pointer', }); InteractionMapper.on(this.interactionType, wrapper, () => { @@ -10796,13 +10792,13 @@ Object.assign(imageWrapper.style, { maxWidth: 'none', - maxHeight: 'none' + maxHeight: 'none', }); Object.assign(image.style, { width: '100%', height: '100%', - objectFit: 'cover' + objectFit: 'cover', }); this._replaceIcon(imageWrapper); @@ -10825,7 +10821,7 @@ const max = { width: context.offsetWidth * maxFillRatio, - height: context.offsetHeight * maxFillRatio + height: context.offsetHeight * maxFillRatio, }; let majorSide; @@ -10859,14 +10855,14 @@ let targetDimensions = { width: 0, - height: 0 + height: 0, }; let position = Points.fromPageToNode(context, Points.fromNodeToPage(source, { x: 0, y: 0 })); let targetOffset = { x: 0, - y: 0 + y: 0, }; targetDimensions[majorSide.name] = size; @@ -10886,22 +10882,22 @@ y: position.y, position: 'absolute', width: parseInt(sourceStyle.width), - height: parseInt(sourceStyle.height) + height: parseInt(sourceStyle.height), }); TweenMax.set(overlay, { display: 'flex', - autoAlpha: 0 + autoAlpha: 0, }); TweenMax.to(imageWrapper, this.zoomAnimationDuration, { x: targetOffset.x, y: targetOffset.y, width: targetDimensions.width, - height: targetDimensions.height + height: targetDimensions.height, }); TweenMax.to(overlay, this.fadeAnimationTime, { - autoAlpha: 1 + autoAlpha: 1, }); }; @@ -10933,10 +10929,10 @@ timeline .to(overlay, this.fadeAnimationDuration, { - autoAlpha: 0 + autoAlpha: 0, }) .set(overlay, { - display: 'none' + display: 'none', }); } }; @@ -10993,7 +10989,7 @@ this._end = this._end.bind(this); this._setupUtterance(); - this.utterance.addEventListener('end', event => { + this.utterance.addEventListener('end', (event) => { this._end(); }); } @@ -11026,7 +11022,7 @@ } else { if (subcard) { let clone = subcard.cloneNode(true); - clone.querySelectorAll('figure').forEach(figure => { + clone.querySelectorAll('figure').forEach((figure) => { figure.parentNode.removeChild(figure); }); @@ -11129,10 +11125,10 @@ } async _stop() { - return new Promise(resolve => { + return new Promise((resolve) => { if (this.activeUtterance) { this.activeUtterance.addEventListener('end', resolve, { - once: true + once: true, }); } @@ -11208,7 +11204,7 @@ path = path ? path : './config.json'; let xhttp = new XMLHttpRequest(); - xhttp.onreadystatechange = function() { + xhttp.onreadystatechange = function () { if (this.readyState == 4) { if (this.status == 200 || Theme._isLocal()) { try { diff --git a/dist/iwmlib.pixi.js b/dist/iwmlib.pixi.js index 9d30962..8a30a92 100644 --- a/dist/iwmlib.pixi.js +++ b/dist/iwmlib.pixi.js @@ -115,7 +115,7 @@ textActiveAlpha: 1, iconColor: color2, iconColorActive: colorPrimary, - background: color1 + background: color1, }, opts ); @@ -132,7 +132,7 @@ stroke: color1, strokeThickness: 0, miterLimit: 1, - lineJoin: 'round' + lineJoin: 'round', }, this.opts.textStyle ); @@ -348,7 +348,7 @@ backgroundFillAlpha: 1, radius: theme.radius, destroyOnComplete: true, - visible: true + visible: true, }, opts ); @@ -383,7 +383,7 @@ setup() { // interaction //----------------- - this.on('added', e => { + this.on('added', (e) => { this.show(); }); @@ -528,7 +528,7 @@ hide() { TweenLite.to(this, this.theme.fast, { alpha: 0, - onComplete: () => (this.visible = false) + onComplete: () => (this.visible = false), }); return this @@ -560,10 +560,10 @@ if (value === 100 && this.opts.destroyOnComplete) { TweenLite.to(this, this.theme.fast, { alpha: 0, - onComplete: () => this.destroy({ children: true }) + onComplete: () => this.destroy({ children: true }), }); } - } + }, }); } } @@ -639,7 +639,7 @@ radius: theme.radius, onHidden: null, visible: true, - orientation: null + orientation: null, }, opts ); @@ -673,7 +673,7 @@ // interaction //----------------- this.interactive = true; - this.on('added', e => { + this.on('added', (e) => { this.show(); }); } @@ -853,7 +853,7 @@ if (cb) { cb.call(this); } - } + }, }); return this @@ -873,7 +873,7 @@ if (cb) { cb.call(this); } - } + }, }); if (this.opts.onHidden) { @@ -973,7 +973,7 @@ container: null, offsetLeft: 8, offsetTop: -8, - delay: 0 + delay: 0, }, opts ); @@ -1006,11 +1006,11 @@ let mouseoverTooltip = false; - this.on('mouseover', e => { + this.on('mouseover', (e) => { mouseoverTooltip = true; }); - this.on('mouseout', e => { + this.on('mouseout', (e) => { mouseoverTooltip = false; if (!mouseoverObject) { this.hide(() => { @@ -1026,7 +1026,7 @@ let mouseoverObject = false; - object.on('mouseover', e => { + object.on('mouseover', (e) => { this.timeout = window.setTimeout(() => { mouseoverObject = true; this.visible = true; @@ -1035,13 +1035,13 @@ }, this.opts.delay * 1000); }); - object.on('mousemove', e => { + object.on('mousemove', (e) => { if (mouseoverObject) { this.setPosition(e); } }); - object.on('mouseout', e => { + object.on('mouseout', (e) => { mouseoverObject = false; window.clearTimeout(this.timeout); if (!mouseoverTooltip) { @@ -1118,7 +1118,7 @@ minWidth: 0, minHeight: 0, padding: theme.padding / 2, - tooltip: null + tooltip: null, }, opts ); @@ -1152,7 +1152,7 @@ if (typeof this.opts.tooltip === 'string') { this.tooltip = new Tooltip({ object: this, - content: this.opts.tooltip + content: this.opts.tooltip, }); } else { this.opts.tooltip = Object.assign({}, { object: this }, this.opts.tooltip); @@ -1183,7 +1183,7 @@ static stop(event) { event.preventDefault(); // I removed this, as it destroys all the Hammer.js events. - // And also the click event. + // And also the click event. // It seems to have no (apparent) negative impact. -SO // event.stopPropagation() } @@ -1246,7 +1246,7 @@ clientX: t.clientX, clientY: t.clientY, pageX: t.pageX, - pageY: t.pageY + pageY: t.pageY, }); } return touches @@ -1286,8 +1286,8 @@ ctrlKey: event.ctrlKey, altKey: event.altKey, shiftKey: event.shiftKey, - metaKey: event.metaKey - } + metaKey: event.metaKey, + }, }; if (event.type.startsWith('touch')) { // On Safari-WebKit the TouchEvent has layerX, layerY coordinates @@ -1384,7 +1384,7 @@ width: '480px', height: '640px', overflow: 'auto', - backgroundColor: 'lightgray' + backgroundColor: 'lightgray', }); document.body.appendChild(element); this.popup = element; @@ -1405,7 +1405,7 @@ } Elements.setStyle(this.popup, { left: event.clientX + 'px', - top: event.clientY + 'px' + top: event.clientY + 'px', }); } } @@ -1442,10 +1442,10 @@ // Taken from: https://davidwalsh.name/essential-javascript-functions function debounce(func, wait, immediate) { let timeout; - return function() { + return function () { let context = this, args = arguments; - let later = function() { + let later = function () { timeout = null; if (!immediate) func.apply(context, args); }; @@ -1581,14 +1581,14 @@ // long version let r = hex.match(/^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i); if (r) { - return r.slice(1, 4).map(x => { + return r.slice(1, 4).map((x) => { return parseInt(x, 16) }) } // short version r = hex.match(/^#([0-9a-f])([0-9a-f])([0-9a-f])$/i); if (r) { - return r.slice(1, 4).map(x => { + return r.slice(1, 4).map((x) => { return 0x11 * parseInt(x, 16) }) } @@ -1607,7 +1607,7 @@ return { r: Math.round(lerp(rgb1.r, rgb2.r, amount)), g: Math.round(lerp(rgb1.g, rgb2.g, amount)), - b: Math.round(lerp(rgb1.b, rgb2.b, amount)) + b: Math.round(lerp(rgb1.b, rgb2.b, amount)), } } @@ -1718,7 +1718,7 @@ static arc(p, alpha, radius) { return { x: p.x + radius * Math.cos(alpha), - y: p.y + radius * Math.sin(alpha) + y: p.y + radius * Math.sin(alpha), } } @@ -1745,19 +1745,17 @@ } static fromPageToNode(element, p) { - // if (window.webkitConvertPointFromPageToNode) { - // return window.webkitConvertPointFromPageToNode(element, - // new WebKitPoint(p.x, p.y)) - // } - return window.convertPointFromPageToNode(element, p.x, p.y) + if (window.webkitConvertPointFromPageToNode) { + return window.webkitConvertPointFromPageToNode(element, new WebKitPoint(p.x, p.y)) + } + //return window.convertPointFromPageToNode(element, p.x, p.y) } static fromNodeToPage(element, p) { - // if (window.webkitConvertPointFromNodeToPage) { - // return window.webkitConvertPointFromNodeToPage(element, - // new WebKitPoint(p.x, p.y)) - // } - return window.convertPointFromNodeToPage(element, p.x, p.y) + if (window.webkitConvertPointFromNodeToPage) { + return window.webkitConvertPointFromNodeToPage(element, new WebKitPoint(p.x, p.y)) + } + //return window.convertPointFromNodeToPage(element, p.x, p.y) } } @@ -2389,7 +2387,7 @@ verticalAlign: 'middle', tooltip: null, badge: null, - visible: true + visible: true, }, opts ); @@ -2410,7 +2408,7 @@ strokeAlpha: this.HIDDEN_ALPHA, strokeActiveAlpha: this.HIDDEN_ALPHA, fillAlpha: this.HIDDEN_ALPHA, - fillActiveAlpha: this.HIDDEN_ALPHA + fillActiveAlpha: this.HIDDEN_ALPHA, }); } @@ -2482,15 +2480,15 @@ // interaction //----------------- - this.button.on('pointerover', e => { + this.button.on('pointerover', (e) => { this.capture(e); TweenLite.to([this.button, this.content], this.theme.fast, { alpha: 0.83, - overwrite: 'none' + overwrite: 'none', }); }); - this.button.on('pointermove', e => { + this.button.on('pointermove', (e) => { this.capture(e); }); @@ -2501,17 +2499,17 @@ this.button.on('scroll', this.onEnd.bind(this)); // eslint-disable-next-line no-unused-vars - this.button.on('pointerdown', e => { + this.button.on('pointerdown', (e) => { //this.capture(e) this.__start.x = e.data.global.x; this.__start.y = e.data.global.y; TweenLite.to([this.button, this.content], this.theme.fast, { alpha: 0.7, - overwrite: 'none' + overwrite: 'none', }); }); - this.button.on('pointerup', e => { + this.button.on('pointerup', (e) => { this.capture(e); const distance = Points.distance(e.data.global, this.__start); @@ -2523,7 +2521,7 @@ TweenLite.to([this.button, this.content], this.theme.fast, { alpha: 0.83, - overwrite: 'none' + overwrite: 'none', }); if (this.opts.type === 'checkbox') { @@ -2554,7 +2552,7 @@ if (typeof this.opts.tooltip === 'string') { this.tooltip = new Tooltip({ object: this, - content: this.opts.tooltip + content: this.opts.tooltip, }); } else { this.opts.tooltip = Object.assign({}, { object: this }, this.opts.tooltip); @@ -2571,7 +2569,7 @@ align: 'right', verticalAlign: 'top', offsetLeft: 0, - offsetTop: 0 + offsetTop: 0, } ); if (typeof this.opts.badge === 'string') { @@ -2949,7 +2947,7 @@ this.capture(event); TweenLite.to([this.button, this.content], this.theme.fast, { alpha: 1, - overwrite: 'none' + overwrite: 'none', }); } } @@ -3078,7 +3076,7 @@ orientation: 'horizontal', align: 'center', // left, center, right verticalAlign: 'middle', // top, middle, bottom - visible: true + visible: true, }, opts ); @@ -3168,7 +3166,7 @@ it.verticalAlign = it.verticalAlign || this.opts.verticalAlign; it.afterAction = (event, button) => { if (this.opts.type === 'radio' && button.opts.type === 'default') { - this.buttons.forEach(it => { + this.buttons.forEach((it) => { if (it.opts.type === 'default') { it.active = false; } @@ -3195,7 +3193,7 @@ button.__originalPosition = { x: button.x, - y: button.y + y: button.y, }; position += (this.opts.orientation === 'horizontal' ? button.width : button.height) + this.opts.margin; @@ -3207,7 +3205,7 @@ if (this.opts.orientation === 'vertical') { const maxWidth = this.getMaxButtonWidth(); - this.buttons.forEach(it => { + this.buttons.forEach((it) => { it.opts.minWidth = maxWidth; it.layout(); }); @@ -3235,7 +3233,7 @@ //-------------------- if (this.opts.app) { const app = this.opts.app; - app.view.addEventListener('mousewheel', event => { + app.view.addEventListener('mousewheel', (event) => { const bounds = this.getBounds(); const x = event.clientX - app.view.getBoundingClientRect().left; const y = event.clientY - app.view.getBoundingClientRect().top; @@ -3290,7 +3288,7 @@ */ draw() { if (this.opts.margin === 0) { - this.buttons.forEach(it => it.hide()); + this.buttons.forEach((it) => it.hide()); this.container.clear(); this.container.lineStyle(this.opts.strokeWidth, this.opts.stroke, this.opts.strokeAlpha); @@ -3330,7 +3328,7 @@ set disabled(value) { this._disabled = value; - this.buttons.forEach(it => (it.disabled = value)); + this.buttons.forEach((it) => (it.disabled = value)); } /** @@ -3368,7 +3366,7 @@ * @return {number} The maximum with of a button of the button group. */ getMaxButtonWidth() { - let widths = this.buttons.map(it => it.width); + let widths = this.buttons.map((it) => it.width); return Math.max(...widths) } @@ -3411,7 +3409,7 @@ this.__delta = { x: this.container.position.x - event.data.global.x, - y: this.container.position.y - event.data.global.y + y: this.container.position.y - event.data.global.y, }; TweenLite.killTweensOf(this.container.position, { x: true, y: true }); @@ -3491,7 +3489,7 @@ throwProps, ease: Strong.easeOut, onUpdate: () => this.stack(), - onComplete: () => ThrowPropsPlugin.untrack(this.container.position) + onComplete: () => ThrowPropsPlugin.untrack(this.container.position), }, 0.8, 0.4 @@ -3587,8 +3585,8 @@ sorted.push(it); }); - const min = Math.min(...sorted.map(it => it.x)); - const max = Math.max(...sorted.map(it => it.x + it.button.width)); + const min = Math.min(...sorted.map((it) => it.x)); + const max = Math.max(...sorted.map((it) => it.x + it.button.width)); const center = (min + max) / 2; // z-index @@ -3613,7 +3611,7 @@ return 0 }) - .forEach(it => it.parent.addChild(it)); + .forEach((it) => it.parent.addChild(it)); } /** @@ -3644,8 +3642,8 @@ sorted.push(it); }); - const min = Math.min(...sorted.map(it => it.y)); - const max = Math.max(...sorted.map(it => it.y + it.button.height)); + const min = Math.min(...sorted.map((it) => it.y)); + const max = Math.max(...sorted.map((it) => it.y + it.button.height)); const center = (min + max) / 2; // z-index @@ -3670,7 +3668,7 @@ return 0 }) - .forEach(it => it.parent.addChild(it)); + .forEach((it) => it.parent.addChild(it)); } } @@ -3701,7 +3699,7 @@ closeOnPopup: false, closeButton: true, button: null, - buttonGroup: null + buttonGroup: null, }, opts ); @@ -3734,7 +3732,7 @@ // interaction //----------------- - this.on('pointerup', e => { + this.on('pointerup', (e) => { if (this.opts.closeOnPopup) { this.hide(); } else { @@ -3767,7 +3765,7 @@ closeButton.interactive = true; closeButton.buttonMode = true; - closeButton.on('pointerdown', e => { + closeButton.on('pointerdown', (e) => { this.hide(); }); @@ -3900,7 +3898,7 @@ { closeButton: false, minWidth: 0, - minHeight: 0 + minHeight: 0, }, opts ); @@ -3963,7 +3961,7 @@ backgroundFill: theme.background, backgroundFillAlpha: 0.6, closeOnBackground: true, - visible: true + visible: true, }, opts ); @@ -3995,7 +3993,7 @@ // interaction //----------------- this.interactive = true; - this.on('added', e => { + this.on('added', (e) => { if (this.visible) { this.show(); } @@ -4009,7 +4007,7 @@ if (this.opts.closeOnBackground) { background.interactive = true; - background.on('pointerup', e => { + background.on('pointerup', (e) => { this.hide(); }); } @@ -4020,7 +4018,7 @@ visible: true, onHidden: () => { this.hide(); - } + }, }); let popup = new InteractivePopup(popupOpts); this.popup = popup; @@ -4061,7 +4059,7 @@ show() { TweenLite.to(this, this.theme.fast, { alpha: 1, - onStart: () => (this.visible = true) + onStart: () => (this.visible = true), }); return this @@ -4075,7 +4073,7 @@ hide() { TweenLite.to(this, this.theme.fast, { alpha: 0, - onComplete: () => (this.visible = false) + onComplete: () => (this.visible = false), }); return this @@ -4179,7 +4177,7 @@ verticalAlign: 'top', // top, middle, bottom duration: 5, autoClose: true, - closeDuration: theme.fast + closeDuration: theme.fast, }, opts ); @@ -4250,11 +4248,11 @@ * * @private * @class - * @extends PIXI.interaction.InteractionManager + * @extends PIXI.InteractionManager * @see {@link http://pixijs.download/dev/docs/PIXI.interaction.InteractionManager.html|PIXI.interaction.InteractionManager} * @see {@link https://stackoverflow.com/questions/29710696/webgl-drawing-buffer-size-does-not-equal-canvas-size} */ - class FullscreenInteractionManager extends PIXI.interaction.InteractionManager { + class FullscreenInteractionManager extends PIXI.InteractionManager { mapPositionToPoint(point, x, y) { let resolution = this.renderer.resolution; let extendWidth = 1.0; @@ -4332,7 +4330,7 @@ roundPixels = true, monkeyPatchMapping = true, adaptive = true, - graphql = false + graphql = false, }) { const fullScreen = !width || !height; @@ -4345,12 +4343,12 @@ view, width, height, - transparent, + backgroundAlpha: transparent, antialias, resolution, autoResize, backgroundColor, - forceCanvas + forceCanvas, }); this.width = width; @@ -4371,7 +4369,7 @@ this.graphql = graphql; if (fullScreen || autoResize) { console.log('App is in fullScreen mode or autoResize mode'); - const resizeDebounced = debounce(event => this.resizeApp(event), 50); + const resizeDebounced = debounce((event) => this.resizeApp(event), 50); window.addEventListener('resize', resizeDebounced); document.body.addEventListener('orientationchange', this.checkOrientation.bind(this)); } @@ -4401,25 +4399,25 @@ // GraphQL if (this.graphql && typeof apollo !== 'undefined') { const networkInterface = apollo.createNetworkInterface({ - uri: '/graphql' + uri: '/graphql', }); const wsClient = new subscriptions.SubscriptionClient(`wss://${location.hostname}/subscriptions`, { reconnect: true, - connectionParams: {} + connectionParams: {}, }); const networkInterfaceWithSubscriptions = subscriptions.addGraphQLSubscriptions(networkInterface, wsClient); this.apolloClient = new apollo.ApolloClient({ - networkInterface: networkInterfaceWithSubscriptions + networkInterface: networkInterfaceWithSubscriptions, }); } // progress this._progress = new Progress( Object.assign({ theme: this.theme }, this.progressOpts, { - app: this + app: this, }) ); this._progress.visible = false; @@ -4448,7 +4446,7 @@ if (value != this.orient) { setTimeout( 100, - function() { + function () { this.orientationChanged(true); }.bind(this) ); @@ -4703,7 +4701,7 @@ loadSprites(resources, loaded = null, { resolutionDependent = true, progress = false } = {}) { this.loadTextures( resources, - textures => { + (textures) => { let sprites = new Map(); for (let [key, texture] of textures) { @@ -4762,7 +4760,7 @@ } if (progress) { - loader.on('progress', e => { + loader.on('progress', (e) => { this.progress(e.progress); }); } @@ -4953,7 +4951,7 @@ fontWeight: 'bold', fill: '#f6f6f6', stroke: '#434f4f', - strokeThickness: 3 + strokeThickness: 3, }) ); this.text.position.set(6, 6); @@ -5072,7 +5070,7 @@ x: value.x, y: value.y, width: value.width, - height: value.height + height: value.height, }; } else { const bounds = value.getBounds(); @@ -5081,7 +5079,7 @@ x: bounds.x, y: bounds.y, width: bounds.width, - height: bounds.height + height: bounds.height, }; } @@ -5292,14 +5290,14 @@ let logHandlers = { log: console.log, warn: console.warn, - error: console.error + error: console.error, }; try { ipc = window.ipcRenderer || require('electron').ipcRenderer; - logHandlers.log = message => ipc.send('log', message); - logHandlers.warn = message => ipc.send('warn', message); - logHandlers.error = message => ipc.send('error', message); + logHandlers.log = (message) => ipc.send('log', message); + logHandlers.warn = (message) => ipc.send('warn', message); + logHandlers.error = (message) => ipc.send('error', message); } catch (e) { console.log('Cannot use electron logging.'); } @@ -5900,7 +5898,7 @@ useCapture = true, capturePointerEvents = true, cancelOnWindowOut = true, - debug = false + debug = false, } = {} ) { this.debug = debug; @@ -5936,7 +5934,7 @@ if (this.debug) console.log('Pointer API' + window.PointerEvent); element.addEventListener( 'pointerdown', - e => { + (e) => { if (this.debug) console.log('pointerdown', e.pointerId); if (this.capture(e)) { if (this.capturePointerEvents) { @@ -5953,7 +5951,7 @@ ); element.addEventListener( 'pointermove', - e => { + (e) => { if (this.debug) console.log('pointermove', e.pointerId, e.pointerType); if (e.pointerType == 'touch' || (e.pointerType == 'mouse' && Events$1.isPointerDown(e))) { @@ -5966,7 +5964,7 @@ ); element.addEventListener( 'pointerup', - e => { + (e) => { if (this.debug) console.log('pointerup', e.pointerId, e.pointerType); this.onEnd(e); if (this.capturePointerEvents) { @@ -5981,7 +5979,7 @@ ); element.addEventListener( 'pointercancel', - e => { + (e) => { if (this.debug) console.log('pointercancel', e.pointerId, e.pointerType); this.onEnd(e); if (this.capturePointerEvents) element.releasePointerCapture(e.pointerId); @@ -5992,7 +5990,7 @@ if (!this.capturePointerEvents) { element.addEventListener( 'pointerleave', - e => { + (e) => { if (this.debug) console.log('pointerleave', e.pointerId, e.pointerType); if (e.target == element) this.onEnd(e); }, @@ -6003,7 +6001,7 @@ if (!this.capturePointerEvents) { element.addEventListener( 'pointerout', - e => { + (e) => { if (this.debug) console.log('pointerout', e.pointerId, e.pointerType); if (e.target == element) this.onEnd(e); }, @@ -6014,7 +6012,7 @@ if (this.cancelOnWindowOut) { window.addEventListener( 'pointerout', - e => { + (e) => { if (this.debug) console.log('pointerout', e.pointerId, e.pointerType, e.target); if (e.target == element) { this.onEnd(e); @@ -6027,7 +6025,7 @@ if (this.debug) console.log('Touch API'); element.addEventListener( 'touchstart', - e => { + (e) => { if (this.debug) console.log('touchstart', this.touchPoints(e)); if (this.capture(e)) { for (let touch of e.changedTouches) { @@ -6039,7 +6037,7 @@ ); element.addEventListener( 'touchmove', - e => { + (e) => { if (this.debug) console.log('touchmove', this.touchPoints(e), e); for (let touch of e.changedTouches) { this.onMove(touch); @@ -6052,7 +6050,7 @@ ); element.addEventListener( 'touchend', - e => { + (e) => { if (this.debug) console.log('touchend', this.touchPoints(e)); for (let touch of e.changedTouches) { this.onEnd(touch); @@ -6062,7 +6060,7 @@ ); element.addEventListener( 'touchcancel', - e => { + (e) => { if (this.debug) console.log('touchcancel', e.targetTouches.length, e.changedTouches.length); for (let touch of e.changedTouches) { this.onEnd(touch); @@ -6075,7 +6073,7 @@ element.addEventListener( 'mousedown', - e => { + (e) => { if (this.debug) console.log('mousedown', e); if (this.capture(e)) { this.onStart(e); @@ -6085,7 +6083,7 @@ ); element.addEventListener( 'mousemove', - e => { + (e) => { // Dow we only use move events if the mouse is down? // HOver effects have to be implemented by other means // && Events.isMouseDown(e)) @@ -6099,7 +6097,7 @@ ); element.addEventListener( 'mouseup', - e => { + (e) => { if (this.debug) console.log('mouseup', e); this.onEnd(e); }, @@ -6109,7 +6107,7 @@ if (!this.capturePointerEvents) { element.addEventListener( 'mouseout', - e => { + (e) => { if (e.target == element) { this.onEnd(e); console.warn("Shouldn't happen: mouseout ends interaction"); @@ -6121,7 +6119,7 @@ if (this.cancelOnWindowOut) { window.addEventListener( 'mouseout', - e => { + (e) => { if (e.target == element) { this.onEnd(e); } @@ -6294,7 +6292,7 @@ useCapture = true, capturePointerEvents = true, mouseWheelElement = null, - logInteractionsAbove = 12 + logInteractionsAbove = 12, } = {} ) { super(element, target, { @@ -6302,7 +6300,7 @@ useCapture, capturePointerEvents, longPressTime, - mouseWheelElement + mouseWheelElement, }); this.logInteractionsAbove = logInteractionsAbove; } @@ -6456,7 +6454,7 @@ hammer.get('tap').set(opts); } - hammer.on(type, event => { + hammer.on(type, (event) => { cb(event); }); @@ -6470,7 +6468,7 @@ } } else { for (let j = 0; j < elements.length; j++) { - Hammer.on(elements[j], type, event => { + Hammer.on(elements[j], type, (event) => { cb(event); }); } @@ -6501,7 +6499,7 @@ if (Hammer.__hammers.has(element)) { const elementHammers = Hammer.__hammers.get(element); - elementHammers.forEach(it => it.destroy()); + elementHammers.forEach((it) => it.destroy()); Hammer.__hammers.delete(element); } } @@ -6711,7 +6709,8 @@ */ class ScatterEvent extends BaseEvent { constructor( - target, { translate = { x: 0, y: 0 }, scale = null, rotate = 0, about = null, fast = false, type = null } = {} + target, + { translate = { x: 0, y: 0 }, scale = null, rotate = 0, about = null, fast = false, type = null } = {} ) { super('scatterTransformed', { target: target }); this.translate = translate; @@ -6761,7 +6760,7 @@ throwVisibility = 44, throwDamping = 0.95, autoThrow = true, - onThrowFinished = null + onThrowFinished = null, } = {}) { this.movableX = movableX; this.movableY = movableY; @@ -6772,7 +6771,7 @@ this.velocity = null; this.timestamp = null; this.onThrowFinished = onThrowFinished; - //console.log("onThrowFinished", onThrowFinished) + //console.log("onThrowFinished", onThrowFinished) } observeVelocity() { @@ -6794,13 +6793,12 @@ t: t, dt: dt, dx: delta.x / number, - dy: delta.y / number + dy: delta.y / number, }; this.velocities.push(velocity); while (this.velocities.length > buffer) { this.velocities.shift(); } - } } @@ -6850,7 +6848,7 @@ animateThrow(time) { if (this.velocity != null) { let dt = this._throwDeltaTime(); - // console.log("animateThrow", dt) + // console.log("animateThrow", dt) let next = this.nextVelocity(this.velocity); let prevLength = Points.length(this.velocity); let nextLength = Points.length(next); @@ -6893,7 +6891,7 @@ let next = Points.multiplyScalar(velocity, this.throwDamping); return { x: this.movableX ? next.x : 0, - y: this.movableY ? next.y : 0 + y: this.movableY ? next.y : 0, } } @@ -6938,7 +6936,7 @@ scaleCloseBuffer = 0.05, maxRotation = Angle.degree2radian(5), minInteractionDistance = 0, - useLowPassFilter = false + useLowPassFilter = false, } = {}) { if (rotationDegrees != null && rotation != null) { throw new Error('Use rotationDegrees or rotation but not both') @@ -6953,7 +6951,7 @@ throwVisibility, throwDamping, autoThrow, - onThrowFinished + onThrowFinished, }); /** @@ -7028,7 +7026,7 @@ _callCloseCallbacks() { if (this.onClose) { - this.onClose.forEach(callback => callback(this)); + this.onClose.forEach((callback) => callback(this)); } } @@ -7048,7 +7046,6 @@ let delta = interaction.delta(); if (delta != null) { - let rotate = delta.rotate; let zoom = delta.zoom; if (this.maxRotation != null) { @@ -7135,8 +7132,8 @@ keepOnStage(velocity, collision = 0.5) { let stagePolygon = this.containerPolygon; - // UO: since keepOnStage is called in nextVelocity we need to - // ensure a return value + // UO: since keepOnStage is called in nextVelocity we need to + // ensure a return value if (!stagePolygon) return { x: 0, y: 0 } this.polygon; let bounced = this.bouncing(); @@ -7147,7 +7144,7 @@ let dx = this.movableX ? velocity.x : 0; let dy = this.movableY ? velocity.y : 0; let factor = this.throwDamping; - // if (recentered) { + // if (recentered) { if (x < 0) { dx = -dx; factor = collision; @@ -7180,13 +7177,13 @@ if (this.scale < this.minScale + this.scaleCloseThreshold - this.scaleCloseBuffer) { this.zoom(this.minScale, { animate: 0.2, - onComplete: this.close.bind(this) + onComplete: this.close.bind(this), }); } else if (this.scale < this.minScale + this.scaleCloseThreshold) { - this.zoom(this.minScale + this.scaleCloseThreshold, { - animate: 0.4 - }); - } + this.zoom(this.minScale + this.scaleCloseThreshold, { + animate: 0.4, + }); + } } rotateDegrees(degrees, anchor) { @@ -7206,12 +7203,12 @@ x: '+=' + d.x, y: '+=' + d.y, /* scale: scale, uo: not defined, why was this here? */ - onUpdate: e => { + onUpdate: (e) => { let p = this.position; let dx = p.x - startPos.x; let dy = p.x - startPos.y; this.onMoved(dx, dy); - } + }, }); } else { this._move(d); @@ -7240,7 +7237,7 @@ scale: scale, delay: delay, onComplete: onComplete, - onUpdate: this.onZoomed.bind(this) + onUpdate: this.onZoomed.bind(this), }); } else { this.scale = scale; @@ -7250,7 +7247,7 @@ } _move(delta) { - // this.addVelocity(delta) uo: reverted commit fa0256d782dd498c6d3e51321260ca375ca9f855 + // this.addVelocity(delta) uo: reverted commit fa0256d782dd498c6d3e51321260ca375ca9f855 this.x += this.movableX ? delta.x : 0; this.y += this.movableX ? delta.y : 0; } @@ -7258,7 +7255,7 @@ transform(translate, zoom, rotate, anchor) { let delta = { x: this.movableX ? translate.x : 0, - y: this.movableY ? translate.y : 0 + y: this.movableY ? translate.y : 0, }; if (this.resizable) var vzoom = zoom; if (!this.translatable) delta = { x: 0, y: 0 }; @@ -7273,9 +7270,9 @@ rotate: 0, about: anchor, fast: false, - type: UPDATE + type: UPDATE, }); - this.onTransform.forEach(function(f) { + this.onTransform.forEach(function (f) { f(event); }); } @@ -7289,7 +7286,7 @@ let newOrigin = Points.arc(anchor, beta + rotate, distance * thresholdedZoom); let extra = Points.subtract(newOrigin, origin); const anchorOffset = Points.subtract(anchor, origin); - // this._move(offset) + // this._move(offset) this.scale = newScale; this.rotation += rotate; let offset = Points.negate(anchorOffset); @@ -7304,9 +7301,9 @@ translate: delta, scale: newScale, rotate: rotate, - about: anchor + about: anchor, }); - this.onTransform.forEach(function(f) { + this.onTransform.forEach(function (f) { f(event); }); } @@ -7372,7 +7369,7 @@ if (this.scale > this.maxScale) zoom = 1 - amount; if (zoom != 1) { this.transform({ x: 0, y: 0 }, zoom, 0, this.zoomAnchor); - requestAnimationFrame(dt => { + requestAnimationFrame((dt) => { this.animateZoomBounce(dt); }); return @@ -7429,9 +7426,9 @@ rotate: 0, about: null, fast: false, - type: START + type: START, }); - this.onTransform.forEach(function(f) { + this.onTransform.forEach(function (f) { f(event); }); } @@ -7465,9 +7462,9 @@ rotate: 0, about: null, fast: false, - type: END + type: END, }); - this.onTransform.forEach(function(f) { + this.onTransform.forEach(function (f) { f(event); }); } @@ -7495,9 +7492,9 @@ translate: delta, scale: this.scale, about: this.currentAbout, - type: null + type: null, }); - this.onTransform.forEach(function(f) { + this.onTransform.forEach(function (f) { f(event); }); } @@ -7509,9 +7506,9 @@ scale: this.scale, about: this.currentAbout, fast: false, - type: null + type: null, }); - this.onTransform.forEach(function(f) { + this.onTransform.forEach(function (f) { f(event); }); } @@ -7523,9 +7520,9 @@ translate: { x: dx, y: dy }, about: about, fast: true, - type: null + type: null, }); - this.onTransform.forEach(function(f) { + this.onTransform.forEach(function (f) { f(event); }); } @@ -7536,9 +7533,9 @@ let event = new ScatterEvent(this, { scale: this.scale, fast: false, - type: null + type: null, }); - this.onTransform.forEach(function(f) { + this.onTransform.forEach(function (f) { f(event); }); } @@ -7552,9 +7549,9 @@ scale: this.scale, about: about, fast: false, - type: null + type: null, }); - this.onTransform.forEach(function(f) { + this.onTransform.forEach(function (f) { f(event); }); } @@ -7564,7 +7561,8 @@ class DOMScatter extends AbstractScatter { constructor( element, - container, { + container, + { startScale = 1.0, minScale = 0.1, maxScale = 1.0, @@ -7600,7 +7598,7 @@ scaleCloseBuffer = 0.05, useLowPassFilter = false, maxRotation = Angle.degree2radian(15), - minInteractionDistance = 200 + minInteractionDistance = 200, } = {} ) { super({ @@ -7627,7 +7625,7 @@ onClose, useLowPassFilter, maxRotation, - minInteractionDistance + minInteractionDistance, }); if (container == null || width == null || height == null) { throw new Error('Invalid value: null') @@ -7655,7 +7653,7 @@ height: height, scale: startScale, rotation: this.startRotationDegrees, - transformOrigin: transformOrigin + transformOrigin: transformOrigin, }; this.tapNodes = new Map(); @@ -7677,15 +7675,15 @@ button.className = 'interactiveElement'; this.element.appendChild(button); - button.addEventListener('pointerdown', e => { + button.addEventListener('pointerdown', (e) => { this.startResize(e); }); - button.addEventListener('pointermove', e => { + button.addEventListener('pointermove', (e) => { this.resize(e); }); - button.addEventListener('pointerup', e => { + button.addEventListener('pointerup', (e) => { this.stopResize(e); }); this.resizeButton = button; @@ -7702,7 +7700,7 @@ scale: this.scale, x: this.x, y: this.y, - rotation: this.rotation + rotation: this.rotation, } } @@ -7753,7 +7751,7 @@ top: rect.top - stage.top, left: rect.left - stage.left, width: rect.width, - height: rect.height + height: rect.height, } } @@ -7761,10 +7759,10 @@ let r = this.bounds; let w2 = r.width / 2; let h2 = r.height / 2; - // if (this.resizable) { - // w2 *= this.scale - // h2 *= this.scale - // } + // if (this.resizable) { + // w2 *= this.scale + // h2 *= this.scale + // } var x = r.left + w2; var y = r.top + h2; return { x, y } @@ -7794,7 +7792,7 @@ set scale(scale) { TweenLite.set(this.element, { scale: scale, - transformOrigin: this.transformOrigin + transformOrigin: this.transformOrigin, }); this._scale = scale; } @@ -7826,9 +7824,9 @@ hide() { TweenLite.to(this.element, 0.1, { display: 'none', - onComplete: e => { + onComplete: (e) => { this.element.parentNode.removeChild(this.element); - } + }, }); } @@ -7842,7 +7840,7 @@ x: p.x, y: p.y, rotation: rotationDegrees, - transformOrigin: this.transformOrigin + transformOrigin: this.transformOrigin, }); } @@ -7884,7 +7882,7 @@ } this._x = x; this._y = y; - // this.addVelocity({ x: delta.x, y: delta.y }) uo: reverted commit fa0256d782dd498c6d3e51321260ca375ca9f855 + // this.addVelocity({ x: delta.x, y: delta.y }) uo: reverted commit fa0256d782dd498c6d3e51321260ca375ca9f855 TweenLite.set(this.element, { x, y }); } @@ -7903,7 +7901,7 @@ let oldPostition = { x: this.element.getBoundingClientRect().left, - y: this.element.getBoundingClientRect().top + y: this.element.getBoundingClientRect().top, }; this.bringToFront(); @@ -7911,7 +7909,7 @@ let newPostition = { x: this.element.getBoundingClientRect().left, - y: this.element.getBoundingClientRect().top + y: this.element.getBoundingClientRect().top, }; let offset = Points.subtract(oldPostition, newPostition); @@ -7956,7 +7954,7 @@ ) TweenLite.to(this.element, 0, { width: this.element.offsetWidth + resizeW / this.scale, - height: this.element.offsetHeight + resizeH / this.scale + height: this.element.offsetHeight + resizeH / this.scale, }); this.oldX = e.clientX; @@ -7973,12 +7971,12 @@ let event = new CustomEvent('resizeEnded'); let oldPostition = { x: this.element.getBoundingClientRect().left, - y: this.element.getBoundingClientRect().top + y: this.element.getBoundingClientRect().top, }; this.element.style.transformOrigin = '50% 50%'; let newPostition = { x: this.element.getBoundingClientRect().left, - y: this.element.getBoundingClientRect().top + y: this.element.getBoundingClientRect().top, }; let offset = Points.subtract(oldPostition, newPostition); @@ -8008,7 +8006,7 @@ handleClicks() { this.domNode.addEventListener( 'click', - event => { + (event) => { if (event.isTrusted) { Events$1.stop(event); if (this.triggerSVGClicks && this.isSVGNode(event.target)) { @@ -8023,7 +8021,7 @@ handleClicksAsTaps() { this.domNode.addEventListener( 'click', - event => { + (event) => { if (event.isTrusted) { Events$1.stop(event); } @@ -8090,20 +8088,20 @@ let globalClick = event.center ? event.center : { x: event.x, y: event.y }; let localClick = Points.fromPageToNode(element, globalClick); - let clickRects = activeNodes.map(link => { + let clickRects = activeNodes.map((link) => { let rect = link.getBoundingClientRect(); // Since the getBoundingClientRect is untransformed we cannot rely on it's size // We need a transformed bottom right to calculate local width and height let bottomRight = Points.fromPageToNode(element, { x: rect.x + rect.width, - y: rect.y + rect.height + y: rect.y + rect.height, }); let topLeft = Points.fromPageToNode(element, rect); let width = Math.abs(bottomRight.x - topLeft.x); let height = Math.abs(bottomRight.y - topLeft.y); let center = Points.fromPageToNode(element, { x: rect.x + width / 2, - y: rect.y + height / 2 + y: rect.y + height / 2, }); return { x: topLeft.x, @@ -8111,12 +8109,12 @@ width, height, center, - link + link, } }); let distances = []; - clickRects.forEach(rect => { + clickRects.forEach((rect) => { let distance = Points.distanceToRect(localClick, rect); distances.push(parseInt(distance)); }); @@ -8213,7 +8211,7 @@ scale = 1, minScale = 0.5, maxScale = 1.5, - rotation = 0 + rotation = 0, } = {} ) { this.src = src; @@ -8261,7 +8259,7 @@ onClose = null, onUpdate = null, onRemoved = null, - onLoaded = null + onLoaded = null, } = {} ) { this.domScatterContainer = domScatterContainer; @@ -8303,8 +8301,8 @@ // call we can access the new dom element by id this.cardWrapper = dom.querySelector('#' + this.id); let front = this.cardWrapper.querySelector('.front'); - this.frontLoader.load(front).then(loader => { - this.frontLoaded(loader).then(obj => { + this.frontLoader.load(front).then((loader) => { + this.frontLoaded(loader).then((obj) => { if (this.onLoaded) this.onLoaded(); resolve(this); }); @@ -8328,7 +8326,7 @@ scalable: this.scalable, rotatable: this.rotatable, overdoScaling: this.overdoScaling, - tapDelegate: this.tapDelegateFactory ? new this.tapDelegateFactory(this.cardWrapper) : null + tapDelegate: this.tapDelegateFactory ? new this.tapDelegateFactory(this.cardWrapper) : null, }); if (this.center) { @@ -8336,7 +8334,7 @@ } if (this.closeOnMinScale) { - const removeOnMinScale = function() { + const removeOnMinScale = function () { if (scatter.scale <= scatter.minScale) { this.flippable.close(); @@ -8358,7 +8356,7 @@ let back = this.cardWrapper.querySelector('.back'); if (this.preloadBack) { - this.backLoader.load(back).then(loader => { + this.backLoader.load(back).then((loader) => { this.setupFlippable(flippable, loader); }); } @@ -8392,7 +8390,7 @@ } else { let back = this.cardWrapper.querySelector('.back'); let flippable = this.flippable; - this.backLoader.load(back).then(loader => { + this.backLoader.load(back).then((loader) => { this.setupFlippable(flippable, loader); flippable.start({ duration: this.flipDuration, targetCenter }); }); @@ -8404,7 +8402,7 @@ opacity: 0, onComplete: () => { this.cardWrapper.remove(); - } + }, }); } @@ -8452,7 +8450,7 @@ TweenLite.set(this.back, { rotationY: -180 }); TweenLite.set([this.back, this.front], { backfaceVisibility: 'hidden', - perspective: 5000 + perspective: 5000, }); TweenLite.set(this.front, { visibility: 'visible' }); this.infoBtn = element.querySelector('.infoBtn'); @@ -8464,18 +8462,18 @@ scatter.tapDelegate = tapDelegate; } if (this.infoBtn) { - scatter.tapDelegate.onTap(this.infoBtn, event => { + scatter.tapDelegate.onTap(this.infoBtn, (event) => { this.flip.start(); }); this.enable(this.infoBtn); } if (this.backBtn) { - scatter.tapDelegate.onTap(this.backBtn, event => { + scatter.tapDelegate.onTap(this.backBtn, (event) => { this.start(); }); } if (this.closeBtn) { - scatter.tapDelegate.onTap(this.closeBtn, event => { + scatter.tapDelegate.onTap(this.closeBtn, (event) => { this.close(); }); this.enable(this.closeBtn); @@ -8499,7 +8497,7 @@ if (this.onRemoved) { this.onRemoved.call(this); } - } + }, }); } } @@ -8528,7 +8526,7 @@ scaleButtons() { TweenLite.set([this.infoBtn, this.backBtn, this.closeBtn], { - scale: this.buttonScale + scale: this.buttonScale, }); } @@ -8641,7 +8639,7 @@ ease: Power1.easeOut, transformOrigin: '50% 50%', onUpdate, - onComplete: e => { + onComplete: (e) => { if (this.flipped) { //this.hide(this.front) this.enable(this.backBtn); @@ -8670,7 +8668,7 @@ this.scatter.translatable = translatable; this.scatter.rotatable = rotatable; }, - force3D: true + force3D: true, }); // See https://greensock.com/forums/topic/7997-rotate-the-shortest-way/ TweenLite.to(this.element, this.flipDuration / 2, { @@ -8682,7 +8680,7 @@ height: h, x: x, y: y, - onComplete: e => { + onComplete: (e) => { if (this.flipped) { this.hide(this.front); // this.hide(this.infoBtn) @@ -8690,7 +8688,7 @@ this.hide(this.back); // this.show(this.infoBtn) } - } + }, }); } } @@ -8966,7 +8964,7 @@ if (this.loaded.has(url)) this.loaded.delete(url); if (this.loading.has(url)) this.loading.delete(url); //Tile.unschedule(url) - this.loadQueue = this.loadQueue.filter(item => item != url); + this.loadQueue = this.loadQueue.filter((item) => item != url); } /** Cancels loading by clearing the load queue **/ @@ -9011,8 +9009,8 @@ super(tiles); this.destroyed = false; this.loader = new PIXI.Loader(); - this.loader.on('load', this._onLoaded.bind(this)); - this.loader.on('error', this._onError.bind(this)); + this.loader.onLoad.add(this._onLoaded.bind(this)); + this.loader.onError.add(this._onError.bind(this)); if (compression) { this.loader.use(PIXI.compressedTextures.ImageParser.use); } @@ -9162,7 +9160,7 @@ let worker = (this.worker = new Worker(workerPath)); - worker.onmessage = event => { + worker.onmessage = (event) => { if (event.data.success) { let { url, col, row, buffer } = event.data; //console.log("WorkerTileLoader.loaded", url, buffer) @@ -9257,7 +9255,7 @@ this.infoColor = Colors.random(); this.pprint(); - this.destroyed = false; + //this.destroyed = false } /** Tests whether all tiles are loaded. **/ @@ -9375,7 +9373,7 @@ if (this.showGrid) { this.highlightTile(refCol, refRow); } - urlpos.forEach(d => { + urlpos.forEach((d) => { let [url, col, row] = d; if (this.loader.schedule(url, col, row)) { if (onlyone) { @@ -9435,7 +9433,7 @@ * cancelled. **/ destroy() { - this.destroyed = true; + //this.destroyed = true this.loader.destroy(); super.destroy({ children: true }); // Calls destroyChildren this.available.clear(); @@ -9676,7 +9674,7 @@ this.baseURL = this.urlForTile(this.baseLevel, 0, 0, false); if (loadBaseImage) { - this.imageForURL(this.baseURL, e => { + this.imageForURL(this.baseURL, (e) => { this.size = [e.target.naturalWidth, e.target.naturalHeight]; this.baseImage = e.target; }); @@ -9853,7 +9851,7 @@ useWorker = '', minimumLevel = 0, alpha = 1, - app = window.app + app = window.app, } = {} ) { super(); @@ -10229,7 +10227,7 @@ let changed = { added: [], removed: [] }; let newNeeded = new Map(); let { centerCol, centerRow, needed } = this.neededTiles(tiles, level); - needed.forEach(d => { + needed.forEach((d) => { let [url, col, row] = d; newNeeded.set(url, [col, row]); if (!tiles.requested.has(url)) { @@ -10377,7 +10375,7 @@ } hideTilesAboveLevel(level) { - Object.keys(this.tileLayers).forEach(key => { + Object.keys(this.tileLayers).forEach((key) => { let tiles = this.tileLayers[key]; if (tiles.level > level) { tiles.visible = false; @@ -10390,7 +10388,7 @@ * @param {number} level - The zoom level of the grid */ destroyTilesAboveLevel(level) { - Object.keys(this.tileLayers).forEach(key => { + Object.keys(this.tileLayers).forEach((key) => { let tiles = this.tileLayers[key]; if (tiles.level > level && !tiles.keep) { for (let url of tiles.available.keys()) { @@ -10403,7 +10401,7 @@ } destroyAllTiles() { - Object.keys(this.tileLayers).forEach(key => { + Object.keys(this.tileLayers).forEach((key) => { this.destroyTiles(key); }); } @@ -10414,7 +10412,7 @@ * @memberof DeepZoomImage */ tintObsoleteTiles() { - Object.keys(this.tileLayers).forEach(key => { + Object.keys(this.tileLayers).forEach((key) => { let tiles = this.tileLayers[key]; tiles.untintTiles(); if (!tiles.keep) { @@ -10429,7 +10427,7 @@ * @memberof DeepZoomImage */ destroyUnneededTiles() { - Object.keys(this.tileLayers).forEach(key => { + Object.keys(this.tileLayers).forEach((key) => { let tiles = this.tileLayers[key]; if (!tiles.keep) { tiles.destroyUnneededTiles(); @@ -10443,7 +10441,7 @@ * @memberof DeepZoomImage */ destroyObsoleteTiles() { - Object.keys(this.tileLayers).forEach(key => { + Object.keys(this.tileLayers).forEach((key) => { let tiles = this.tileLayers[key]; if (!tiles.keep) { tiles.destroyObsoleteTiles(); @@ -10458,7 +10456,7 @@ * @memberof DeepZoomImage */ destroyTiles() { - Object.keys(this.tileLayers).forEach(key => { + Object.keys(this.tileLayers).forEach((key) => { let tiles = this.tileLayers[key]; if (!tiles.keep) { tiles.destroyTiles(this.quadTrees); @@ -10470,7 +10468,7 @@ * @param {number} level - The zoom level of the grid */ tintTilesBelowLevel(level) { - Object.keys(this.tileLayers).forEach(key => { + Object.keys(this.tileLayers).forEach((key) => { let tiles = this.tileLayers[key]; if (tiles.level < level) { tiles.tintTiles(this.quadTrees); @@ -10510,7 +10508,7 @@ this.fastLoads += 1; this.populateTiles(currentTiles, this.currentLevel, { onlyone: false, - about: event.about + about: event.about, }); if (this.fastLoads == 3) { this.fastLoads = 0; @@ -10620,7 +10618,7 @@ width: w, height: h, view: canvas, - resolution: resolution + resolution: resolution, }); let displayObject = this.scatter.displayObject; @@ -10661,7 +10659,7 @@ let image = isImage ? domNode : document.createElement('img'); let [x, y, w, h, cloneURL] = this.cloneScatterImage(); let [ww, hh] = this.unscaledSize(); - image.onload = e => { + image.onload = (e) => { if (!isImage) domNode.appendChild(image); this.x = x; this.y = y; @@ -10671,7 +10669,7 @@ this.rotation = this.scatter.rotation; resolve(this); }; - image.onerror = e => { + image.onerror = (e) => { reject(this); }; image.src = cloneURL; @@ -10686,7 +10684,7 @@ this.backLoader = backLoader; this.scatterLoader = new ScatterLoader(scatter); this.domFlip = new DOMFlip(domScatterContainer, flipTemplate, this.scatterLoader, backLoader, { - onBack: this.backCardClosed.bind(this) + onBack: this.backCardClosed.bind(this), }); this.setupInfoButton(); } @@ -10694,7 +10692,7 @@ startFlip() { let center = this.flipCenter(); let loader = this.backLoader; - this.domFlip.load().then(domFlip => { + this.domFlip.load().then((domFlip) => { this.scatter.displayObject.visible = false; domFlip.centerAt(center); domFlip.zoom(this.scatter.scale); @@ -10749,10 +10747,10 @@ this.infoBtn.lineTo(0, 14); this.infoBtn.endFill(); - this.infoBtn.on('click', e => { + this.infoBtn.on('click', (e) => { this.infoSelected(); }); - this.infoBtn.on('tap', e => { + this.infoBtn.on('tap', (e) => { this.infoSelected(); }); @@ -10773,7 +10771,7 @@ displayObject.addChild(this.infoBtn); } - this.scatter.addTransformEventCallback(e => { + this.scatter.addTransformEventCallback((e) => { let displayObject = this.scatter.displayObject; if (displayObject.foreground) { if (e.scale) { @@ -10790,7 +10788,7 @@ let canvas = document.createElement('canvas'); canvas.width = 88 * 4; canvas.height = 44 * 4; - svgImage.onload = e => { + svgImage.onload = (e) => { let displayObject = this.scatter.displayObject; canvas.getContext('2d').drawImage(svgImage, 0, 0, canvas.width, canvas.height); let texure = new PIXI.Texture(new PIXI.BaseTexture(canvas)); @@ -10807,10 +10805,10 @@ this.infoBtn.position = new PIXI.Point(w, h); this.infoBtn.interactive = true; this.infoBtn.updateTransform(); - this.infoBtn.on('click', e => { + this.infoBtn.on('click', (e) => { this.infoSelected(); }); - this.infoBtn.on('tap', e => { + this.infoBtn.on('tap', (e) => { this.infoSelected(); }); }; @@ -10935,7 +10933,7 @@ focus: 800, near: 10, far: 10000, - orthographic: false + orthographic: false, }, opts ); @@ -11077,7 +11075,7 @@ height: this.opts.useBackTransforms ? toObject.height * 2 : fromObject.height * 2, rotation: this.opts.useBackTransforms ? toObject.rotation : fromObject.rotation, skewX: this.opts.useBackTransforms ? toObject.skew.x : fromObject.skew.x, - skewY: this.opts.useBackTransforms ? toObject.skew.y : fromObject.skew.y + skewY: this.opts.useBackTransforms ? toObject.skew.y : fromObject.skew.y, }; // set toObject end values @@ -11114,7 +11112,7 @@ if (this.opts.onComplete) { this.opts.onComplete(this, this); } - } + }, }); // x & y @@ -11122,7 +11120,7 @@ TweenLite.to(this, this.opts.duration, { x: to.x, y: to.y, - ease: this.opts.transformEase + ease: this.opts.transformEase, }); // width & height @@ -11130,7 +11128,7 @@ TweenLite.to([front, back], this.opts.duration, { width: to.width, height: to.height, - ease: this.opts.transformEase + ease: this.opts.transformEase, }); // rotation @@ -11138,9 +11136,9 @@ TweenLite.to(this, this.opts.duration, { directionalRotation: { rotation: `${to.rotation}_short`, - useRadians: true + useRadians: true, }, - ease: this.opts.transformEase + ease: this.opts.transformEase, }); // skewX & skewY @@ -11148,7 +11146,7 @@ TweenLite.to(this.skew, this.opts.duration, { x: to.skewX, y: to.skewY, - ease: this.opts.transformEase + ease: this.opts.transformEase, }); // camera @@ -11157,7 +11155,7 @@ .to(this.euler, half, { x: this.opts.eulerX, y: this.opts.eulerY, - ease + ease, }) .to(this.euler, half, { x: 0, y: 0, ease }); @@ -11234,7 +11232,7 @@ const bounds = displayObject.getBounds(); return { x: bounds.x + bounds.width / 2, - y: bounds.y + bounds.height / 2 + y: bounds.y + bounds.height / 2, } } @@ -11260,7 +11258,7 @@ displayObject.skew.x, displayObject.skew.y, displayObject.pivot.x, - displayObject.pivot.y + displayObject.pivot.y, ]; displayObject.position.set(0, 0); @@ -11309,7 +11307,7 @@ placement = 'top', width = 250, titleStyle = {}, - textStyle = { fontSize: '1.6em' } + textStyle = { fontSize: '1.6em' }, } = {}) { super(); @@ -11321,7 +11319,7 @@ placement, width, titleStyle, - textStyle + textStyle, }; this.padding = 12; @@ -11332,7 +11330,7 @@ stroke: '#f6f6f6', strokeThickness: 3, wordWrap: true, - wordWrapWidth: width - this.padding * 2 + wordWrapWidth: width - this.padding * 2, }; this.titleTextStyle = new PIXI.TextStyle(Object.assign({}, style, titleStyle)); @@ -11528,7 +11526,7 @@ showPolygon = false, showTouches = false, backgroundColor = null, - app = window.app + app = window.app, } = {} ) { super(); @@ -11536,7 +11534,7 @@ if (this.container) this.containerDimensions = { x: this.container.width, - y: this.container.height + y: this.container.height, }; this.backgroundWidth = null; this.backgroundHeight = null; @@ -11551,7 +11549,7 @@ this.backgroundColor = backgroundColor; if (showBounds || showTouches || showPolygon) { //console.log("Show TOUCHES!!!") - this.app.ticker.add(delta => this.update(delta), this); + this.app.ticker.add((delta) => this.update(delta), this); } if (backgroundColor) { this.updateBackground(); @@ -11772,7 +11770,7 @@ overdoScaling = 1.5, onTransform = null, onResize, - onThrowFinished = null + onThrowFinished = null, } = {} ) { // For the simulation of named parameters, @@ -11795,7 +11793,7 @@ onThrowFinished, rotationDegrees, rotation, - onTransform + onTransform, }); this.onResize = onResize; this.displayObject = displayObject; @@ -11820,7 +11818,7 @@ scale: this.scale, x: this.x, y: this.y, - rotation: this.rotation + rotation: this.rotation, } } @@ -12097,7 +12095,7 @@ // Since this delegate might shadow another delegate, we mus avoid // capturing PointerEvents. this.delegate = new InteractionMapper(container, this, { - capturePointerEvents: false + capturePointerEvents: false, }); } @@ -12279,7 +12277,7 @@ result.push(p + '-'); } result.push(last); - return result.filter(p => p.length > 0) + return result.filter((p) => p.length > 0) } static splitWord(word) { @@ -12537,7 +12535,7 @@ } return { text: `${data.text}${i > 0 ? ' ' : ''}${words[i]}`, - length: data.length + wordLength + spaceLength + length: data.length + wordLength + spaceLength, } }, { text: '', length: dotsLength } @@ -12720,7 +12718,7 @@ end: last, visibleStart: visibleFirst, visibleEnd: visibleLast, - units: units + units: units, } } @@ -13261,7 +13259,7 @@ { x: x, y: y, - align + align, }, FontInfo.small ); @@ -13276,21 +13274,21 @@ let start = this.start.toLocaleDateString('de', { year: 'numeric', month: 'numeric', - day: 'numeric' + day: 'numeric', }); let end = this.end.toLocaleDateString('de', { year: 'numeric', month: 'numeric', - day: 'numeric' + day: 'numeric', }); this.ensureLabel(this.labelPrefix + 'start', start, { x: this.toX(this.start), - y: h2 + y: h2, }); this.ensureLabel(this.labelPrefix + 'end', end, { x: this.toX(this.end), y: h2, - align: 'right' + align: 'right', }); } } @@ -13520,13 +13518,13 @@ underflow: 'top-left', fadeScrollbar: false, fadeWait: 3000, - fadeEase: 'easeInOutSine' + fadeEase: 'easeInOutSine', }, options ); this.ease = new PIXI.extras.Ease.list(); - this.on('added', event => { + this.on('added', (event) => { this.update(); }); @@ -13540,7 +13538,7 @@ passiveWheel: this.options.stopPropagation, stopPropagation: this.options.stopPropagation, screenWidth: this.options.boxWidth, - screenHeight: this.options.boxHeight + screenHeight: this.options.boxHeight, }) ); this.content.decelerate().on('moved', () => this._drawScrollbars()); @@ -13870,10 +13868,7 @@ * @private */ _drawMask() { - this._maskContent - .beginFill(0) - .drawRect(0, 0, this.boxWidth, this.boxHeight) - .endFill(); + this._maskContent.beginFill(0).drawRect(0, 0, this.boxWidth, this.boxHeight).endFill(); this.content.mask = this._maskContent; } @@ -13914,7 +13909,7 @@ const time = this.options.fade === true ? 1000 : this.options.fade; this.fade = this.ease.to(this.scrollbar, { alpha: 0 }, time, { wait: this.options.fadeWait, - ease: this.options.fadeEase + ease: this.options.fadeEase, }); this.fade.on('each', () => (this.content.dirty = true)); } @@ -14211,7 +14206,7 @@ onUpdate: null, onComplete: null, tooltip: null, - visible: true + visible: true, }, opts ); @@ -14266,7 +14261,7 @@ //----------------- const container = this.opts.container; - this.on('pointermove', e => { + this.on('pointermove', (e) => { if (this.control.dragging) { const moveX = this.control.event.data.getLocalPosition(this.control.parent).x; this._value = this.pixelToValue(moveX - this.control.delta - this.opts.controlRadius); @@ -14280,20 +14275,20 @@ }); if (container instanceof Element) { - container.addEventListener('pointerup', e => this.onEnd(e), false); - container.addEventListener('pointercancel', e => this.onEnd(e), false); - container.addEventListener('pointerleave', e => this.onEnd(e), false); - container.addEventListener('pointerout', e => this.onEnd(e), false); - container.addEventListener('mouseup', e => this.onEnd(e), false); - container.addEventListener('mousecancel', e => this.onEnd(e), false); - container.addEventListener('mouseleave', e => this.onEnd(e), false); - container.addEventListener('mouseout', e => this.onEnd(e), false); + container.addEventListener('pointerup', (e) => this.onEnd(e), false); + container.addEventListener('pointercancel', (e) => this.onEnd(e), false); + container.addEventListener('pointerleave', (e) => this.onEnd(e), false); + container.addEventListener('pointerout', (e) => this.onEnd(e), false); + container.addEventListener('mouseup', (e) => this.onEnd(e), false); + container.addEventListener('mousecancel', (e) => this.onEnd(e), false); + container.addEventListener('mouseleave', (e) => this.onEnd(e), false); + container.addEventListener('mouseout', (e) => this.onEnd(e), false); } else { container.interactive = true; - container.on('pointerup', e => this.onEnd(e)); - container.on('pointercancel', e => this.onEnd(e)); - container.on('pointerleave', e => this.onEnd(e)); - container.on('pointerout', e => this.onEnd(e)); + container.on('pointerup', (e) => this.onEnd(e)); + container.on('pointercancel', (e) => this.onEnd(e)); + container.on('pointerleave', (e) => this.onEnd(e)); + container.on('pointerout', (e) => this.onEnd(e)); } // Slider @@ -14309,7 +14304,7 @@ control.y = this.opts.controlRadius; // pointerdown on the control for dragndrop - control.on('pointerdown', e => { + control.on('pointerdown', (e) => { control.event = e; control.delta = e.data.getLocalPosition(this.control).x; control.dragging = true; @@ -14325,21 +14320,21 @@ // interaction //----------------- - this.sliderObj.on('pointerover', e => { + this.sliderObj.on('pointerover', (e) => { TweenLite.to(this.control, this.theme.fast, { alpha: 0.83 }); }); - this.sliderObj.on('pointerout', e => { + this.sliderObj.on('pointerout', (e) => { TweenLite.to(this.control, this.theme.fast, { alpha: 1 }); }); - this.sliderObj.on('pointerdown', e => { + this.sliderObj.on('pointerdown', (e) => { this.sliderObj.pointerdowned = true; TweenLite.to(this.control, this.theme.fast, { alpha: 0.7 }); }); // Click on the slider bar - this.sliderObj.on('pointerup', e => { + this.sliderObj.on('pointerup', (e) => { if (this.sliderObj.pointerdowned) { this.sliderObj.pointerdowned = false; const position = e.data.getLocalPosition(this.control.parent); @@ -14358,7 +14353,7 @@ if (typeof this.opts.tooltip === 'string') { this.tooltip = new Tooltip({ object: this, - content: this.opts.tooltip + content: this.opts.tooltip, }); } else { this.opts.tooltip.object = this; @@ -14638,7 +14633,7 @@ captureEvents = true, acceptMouseEvents = true, lineWidth = 16, - minStrokeLength = 4 + minStrokeLength = 4, } = {}) { super(); this.activePointers = 0; @@ -14720,7 +14715,7 @@ } registerEventHandler() { - window.addEventListener('keydown', e => { + window.addEventListener('keydown', (e) => { switch (e.keyCode) { case 38: // up arrow this.tiltX += 5; @@ -14738,7 +14733,7 @@ if (this.debug) console.log('keydown', e.keyCode, this.tiltX, this.tiltY); }); - this.on('pointerdown', e => { + this.on('pointerdown', (e) => { if (this.debug) console.log('pointerdown', e); if (this.eventInside(e)) { this.activePointers += 1; @@ -14748,13 +14743,13 @@ } }); - this.on('pointermove', e => { + this.on('pointermove', (e) => { if (Events$1.isPointerDown(e.data.originalEvent) || this.isStylusPointer(e) || this.isStylusTouch(e)) { if (this.debug) console.log('pointermove', e, this.eventInside(e)); if (this.eventInside(e) && this.singlePointer()) this.moveStroke(this.toStroke(e)); } }); - this.on('pointerup', e => { + this.on('pointerup', (e) => { if (this.eventInside(e)) { if (this.activePointers > 0) { this.activePointers -= 1; @@ -14763,13 +14758,13 @@ } if (this.debug) console.log('pointerup', this.activePointers); }); - this.on('pointerleave', e => { + this.on('pointerleave', (e) => { if (this.activePointers > 0) { this.activePointers -= 1; } this.endStroke(this.toStroke(e)); }); - this.on('pointercancel', e => { + this.on('pointercancel', (e) => { if (this.activePointers > 0) { this.activePointers -= 1; } @@ -14833,7 +14828,7 @@ tiltX: this.tiltX, tiltY: this.tiltY, color: this.color, - lineWidth: this.tiltToLineWidth(this.tiltY) + lineWidth: this.tiltToLineWidth(this.tiltY), }; return desc } @@ -15126,7 +15121,7 @@ beforeAction: null, afterAction: null, tooltip: null, - visible: true + visible: true, }, opts ); @@ -15167,7 +15162,7 @@ controlStroke: this.opts.controlStroke, controlStrokeWidth: this.opts.controlStrokeWidth, controlStrokeAlpha: this.opts.controlStrokeAlpha, - controlRadius: this.opts.controlRadius + controlRadius: this.opts.controlRadius, }; // setup @@ -15207,19 +15202,19 @@ // interaction //----------------- - this.switchObj.on('pointerover', e => { + this.switchObj.on('pointerover', (e) => { TweenLite.to(this.control, this.theme.fast, { alpha: 0.83 }); }); - this.switchObj.on('pointerout', e => { + this.switchObj.on('pointerout', (e) => { TweenLite.to(this.control, this.theme.fast, { alpha: 1 }); }); - this.switchObj.on('pointerdown', e => { + this.switchObj.on('pointerdown', (e) => { TweenLite.to(this.control, this.theme.fast, { alpha: 0.7 }); }); - this.switchObj.on('pointerup', e => { + this.switchObj.on('pointerup', (e) => { if (this.opts.beforeAction) { this.opts.beforeAction.call(this, e, this); } @@ -15257,7 +15252,7 @@ if (typeof this.opts.tooltip === 'string') { this.tooltip = new Tooltip({ object: this, - content: this.opts.tooltip + content: this.opts.tooltip, }); } else { this.opts.tooltip.object = this; @@ -15395,7 +15390,7 @@ stroke: this.opts.strokeActive, controlFill: this.opts.controlFillActive, controlStroke: this.opts.controlStrokeActive, - format: 'number' + format: 'number', }, fillAlpha: this.opts.fillActiveAlpha, strokeWidth: this.opts.strokeActiveWidth, @@ -15405,11 +15400,11 @@ controlStrokeAlpha: this.opts.controlStrokeActiveAlpha, controlRadius: this.opts.controlRadiusActive, onUpdate: () => this.drawAnimated(), - onComplete: () => this.draw() + onComplete: () => this.draw(), }); } else { TweenLite.to(this.control, this.opts.durationActive, { - x: this.xInactive + x: this.xInactive, }); TweenLite.to(this.tempAnimated, this.opts.durationActive, { colorProps: { @@ -15417,7 +15412,7 @@ stroke: this.opts.stroke, controlFill: this.opts.controlFill, controlStroke: this.opts.controlStroke, - format: 'number' + format: 'number', }, fillAlpha: this.opts.fillAlpha, strokeWidth: this.opts.strokeWidth, @@ -15427,7 +15422,7 @@ controlStrokeAlpha: this.opts.controlStrokeAlpha, controlRadius: this.opts.controlRadius, onUpdate: () => this.drawAnimated(), - onComplete: () => this.draw() + onComplete: () => this.draw(), }); } } @@ -15547,7 +15542,7 @@ items: [], margin: theme.margin / 2, textStyle: theme.textStyle, - closeOnPopup: true + closeOnPopup: true, }, opts ); @@ -15585,19 +15580,19 @@ object.interactive = true; object.buttonMode = true; } - object.on('pointerover', e => { + object.on('pointerover', (e) => { TweenLite.to(object, this.theme.fast, { alpha: 0.83, - overwrite: 'none' + overwrite: 'none', }); }); - object.on('pointerout', e => { + object.on('pointerout', (e) => { TweenLite.to(object, this.theme.fast, { alpha: 1, - overwrite: 'none' + overwrite: 'none', }); }); - object.on('pointerup', e => { + object.on('pointerup', (e) => { item.action.call(object, e, object); if (this.opts.closeOnAction) { this.hide(); @@ -15675,7 +15670,7 @@ distance: 160, duration: 1.5, ease: Quad.easeOut, - destroyOnComplete: true + destroyOnComplete: true, }, opts ); @@ -15765,7 +15760,7 @@ if (this.opts.destroyOnComplete) { object.destroy({ children: true }); } - } + }, }); } @@ -15826,7 +15821,7 @@ verticalAlign: 'middle', width: null, height: null, - app: null + app: null, }, opts ); @@ -15879,7 +15874,7 @@ //-------------------- if (this.opts.app) { const app = this.opts.app; - app.view.addEventListener('mousewheel', event => { + app.view.addEventListener('mousewheel', (event) => { const bounds = this.mask ? this.mask.getBounds() : this.getBounds(); const x = event.clientX - app.view.getBoundingClientRect().left; const y = event.clientY - app.view.getBoundingClientRect().top; @@ -15937,13 +15932,13 @@ if (this.opts.orientation === 'vertical') { switch (this.opts.align) { case 'center': - this.__items.forEach(it => (it.x = margin + this.width / 2 - it.width / 2)); + this.__items.forEach((it) => (it.x = margin + this.width / 2 - it.width / 2)); break case 'right': - this.__items.forEach(it => (it.x = margin + this.width - it.width)); + this.__items.forEach((it) => (it.x = margin + this.width - it.width)); break default: - this.__items.forEach(it => (it.x = margin)); + this.__items.forEach((it) => (it.x = margin)); break } @@ -15963,13 +15958,13 @@ if (this.opts.orientation === 'horizontal') { switch (this.opts.verticalAlign) { case 'top': - this.__items.forEach(it => (it.y = margin)); + this.__items.forEach((it) => (it.y = margin)); break case 'bottom': - this.__items.forEach(it => (it.y = margin + this.height - it.height)); + this.__items.forEach((it) => (it.y = margin + this.height - it.height)); break default: - this.__items.forEach(it => (it.y = margin + this.height / 2 - it.height / 2)); + this.__items.forEach((it) => (it.y = margin + this.height / 2 - it.height / 2)); break } @@ -15993,7 +15988,7 @@ get innerWidth() { let size = 0; - this.__items.forEach(it => (size += it.width)); + this.__items.forEach((it) => (size += it.width)); size += this.opts.padding * (this.__items.length - 1); size += 2 * this.opts.margin; @@ -16006,7 +16001,7 @@ get innerHeight() { let size = 0; - this.__items.forEach(it => (size += it.height)); + this.__items.forEach((it) => (size += it.height)); size += this.opts.padding * (this.__items.length - 1); size += 2 * this.opts.margin; @@ -16040,7 +16035,7 @@ this.__delta = { x: this.container.position.x - event.data.global.x, - y: this.container.position.y - event.data.global.y + y: this.container.position.y - event.data.global.y, }; TweenLite.killTweensOf(this.container.position, { x: true, y: true }); @@ -16085,7 +16080,7 @@ throwProps.x = { velocity: 'auto', min, - max: 0 + max: 0, }; } else { let min = this.opts.height - this.innerHeight; @@ -16093,7 +16088,7 @@ throwProps.y = { velocity: 'auto', min, - max: 0 + max: 0, }; } @@ -16103,7 +16098,7 @@ { throwProps, ease: Strong.easeOut, - onComplete: () => ThrowPropsPlugin.untrack(this.container.position) + onComplete: () => ThrowPropsPlugin.untrack(this.container.position), }, 0.8, 0.4 @@ -16295,7 +16290,7 @@ verticalAlign: 'middle', tooltip: null, badge: null, - visible: true + visible: true, }, opts ); @@ -16316,7 +16311,7 @@ strokeAlpha: 0, strokeActiveAlpha: 0, fillAlpha: 0, - fillActiveAlpha: 0 + fillActiveAlpha: 0, }); } @@ -16388,15 +16383,15 @@ // interaction //----------------- - this.button.on('pointerover', e => { + this.button.on('pointerover', (e) => { this.capture(e); TweenLite.to([this.button, this.content], this.theme.fast, { alpha: 0.83, - overwrite: 'none' + overwrite: 'none', }); }); - this.button.on('pointermove', e => { + this.button.on('pointermove', (e) => { this.capture(e); }); @@ -16407,17 +16402,17 @@ this.button.on('scroll', this.onEnd.bind(this)); // eslint-disable-next-line no-unused-vars - this.button.on('pointerdown', e => { + this.button.on('pointerdown', (e) => { //this.capture(e) this.__start.x = e.data.global.x; this.__start.y = e.data.global.y; TweenLite.to([this.button, this.content], this.theme.fast, { alpha: 0.7, - overwrite: 'none' + overwrite: 'none', }); }); - this.button.on('pointerup', e => { + this.button.on('pointerup', (e) => { this.capture(e); const distance = Points.distance(e.data.global, this.__start); @@ -16433,7 +16428,7 @@ TweenLite.to([this.button, this.content], this.theme.fast, { alpha: 0.83, - overwrite: 'none' + overwrite: 'none', }); if (this.opts.type === 'checkbox') { @@ -16460,7 +16455,7 @@ if (typeof this.opts.tooltip === 'string') { this.tooltip = new Tooltip({ object: this, - content: this.opts.tooltip + content: this.opts.tooltip, }); } else { this.opts.tooltip = Object.assign({}, { object: this }, this.opts.tooltip); @@ -16477,7 +16472,7 @@ align: 'right', verticalAlign: 'top', offsetLeft: 0, - offsetTop: 0 + offsetTop: 0, } ); if (typeof this.opts.badge === 'string') { @@ -16853,7 +16848,7 @@ this.capture(event); TweenLite.to([this.button, this.content], this.theme.fast, { alpha: 1, - overwrite: 'none' + overwrite: 'none', }); } } @@ -22298,7 +22293,7 @@ window.DeepZoomMap = DeepZoomMap; window.Projection = { Mercator, - Robinson + Robinson, }; window.MapViewport = MapViewport; diff --git a/gulpfile.js b/gulpfile.js index 71788db..d584526 100644 --- a/gulpfile.js +++ b/gulpfile.js @@ -11,12 +11,12 @@ function vendors() { './node_modules/optimal-select/dist/optimal-select.js', './node_modules/hammerjs/hammer.js', './node_modules/propagating-hammerjs/propagating.js', - './node_modules/pixi.js/dist/pixi.js', + './node_modules/pixi.js/dist/browser/pixi.js', './node_modules/pixi-compressed-textures/lib/crn_decomp.js', './node_modules/pixi-compressed-textures/dist/pixi-compressed-textures.js', './node_modules/pixi-filters/dist/pixi-filters.js', './node_modules/pixi-particles/dist/pixi-particles.js', - './node_modules/pixi-projection/dist/pixi-projection.js', + './node_modules/pixi-projection/dist/pixi-projection.umd.js', './node_modules/gsap/src/uncompressed/TweenMax.js', './node_modules/gsap/src/uncompressed/TimelineMax.js', './lib/3rdparty/jquery.js', diff --git a/lib/3rdparty/convertPointFromPageToNode.js b/lib/3rdparty/convertPointFromPageToNode.js index d568e27..2dfbe0a 100644 --- a/lib/3rdparty/convertPointFromPageToNode.js +++ b/lib/3rdparty/convertPointFromPageToNode.js @@ -10,10 +10,10 @@ css transforms without perspective projection) */ -(function () { +;(function () { 'use strict' - var I = (typeof(WebKitCSSMatrix) == 'undefined') ? new DOMMatrix() : new WebKitCSSMatrix() + var I = typeof WebKitCSSMatrix == 'undefined' ? new DOMMatrix() : new WebKitCSSMatrix() function Point(x, y, z) { this.x = x @@ -28,8 +28,8 @@ function createMatrix(transform) { try { - return (typeof(WebKitCSSMatrix) == 'undefined') ? new DOMMatrix(transform) : new WebKitCSSMatrix(transform) - } catch(e) { + return typeof WebKitCSSMatrix == 'undefined' ? new DOMMatrix(transform) : new WebKitCSSMatrix(transform) + } catch (e) { console.warn(transform) console.warn(e.toString()) return I @@ -54,8 +54,9 @@ var left = +Infinity var top = +Infinity while (--i >= 0) { - var p = new Point(i === 0 || i === 1 ? 0 : w, i === 0 || i === 3 ? 0 : h, - 0).transformBy(transformationMatrix) + var p = new Point(i === 0 || i === 1 ? 0 : w, i === 0 || i === 3 ? 0 : h, 0).transformBy( + transformationMatrix + ) if (p.x < left) { left = p.x } @@ -64,20 +65,19 @@ } } var rect = element.getBoundingClientRect() - transformationMatrix = I.translate(window.pageXOffset + rect.left - left, - window.pageYOffset + rect.top - top, 0) - .multiply(transformationMatrix) + transformationMatrix = I.translate( + window.pageXOffset + rect.left - left, + window.pageYOffset + rect.top - top, + 0 + ).multiply(transformationMatrix) return transformationMatrix } window.convertPointFromPageToNode = function (element, pageX, pageY) { - return new Point(pageX, pageY, 0).transformBy( - getTransformationMatrix(element).inverse()) + return new Point(pageX, pageY, 0).transformBy(getTransformationMatrix(element).inverse()) } window.convertPointFromNodeToPage = function (element, offsetX, offsetY) { - return new Point(offsetX, offsetY, 0).transformBy( - getTransformationMatrix(element)) + return new Point(offsetX, offsetY, 0).transformBy(getTransformationMatrix(element)) } - -}()); +})() diff --git a/lib/bootstrap.js b/lib/bootstrap.js index 9bcf68a..545f19d 100644 --- a/lib/bootstrap.js +++ b/lib/bootstrap.js @@ -122,17 +122,17 @@ class Bootstrap extends Object { baseURL: baseUrl, map: { 'plugin-babel': baseUrl + '/3rdparty/systemjs/plugin-babel.js', - 'systemjs-babel-build': baseUrl + '/3rdparty/systemjs/systemjs-babel-browser.js' + 'systemjs-babel-build': baseUrl + '/3rdparty/systemjs/systemjs-babel-browser.js', }, transpiler: 'plugin-babel', meta: { '*.js': { authorization: true, babelOptions: { - es2015: false - } - } - } + es2015: false, + }, + }, + }, } } diff --git a/lib/bundle.js b/lib/bundle.js index 47c3355..56904e6 100755 --- a/lib/bundle.js +++ b/lib/bundle.js @@ -22,7 +22,7 @@ import { InteractionDelta, InteractionMapper, InteractionDelegate, - IInteractionMapperTarget + IInteractionMapperTarget, } from './interaction.js' import { ITapDelegate, @@ -31,7 +31,7 @@ import { AbstractScatter, DOMScatter, ScatterEvent, - BaseEvent + BaseEvent, } from './scatter.js' import { Cycle, @@ -50,7 +50,7 @@ import { debounce, randomInt, randomFloat, - LowPassFilter + LowPassFilter, } from './utils.js' import UITest from './uitest.js' diff --git a/lib/card/card.js b/lib/card/card.js index c08ae86..80cddd9 100644 --- a/lib/card/card.js +++ b/lib/card/card.js @@ -55,7 +55,7 @@ export default class Card { context.classList.add('info-card') context.setAttribute('data-id', Card.id++) - modules.forEach(module => { + modules.forEach((module) => { if (module.apply(context)) { const moduleName = module.constructor.name context.modules.push(moduleName) @@ -157,7 +157,7 @@ export default class Card { */ static _replaceAttributes(context, html, attribute, replaceFunc) { let attributeCarrier = html.querySelectorAll(`[${attribute}]`) - attributeCarrier.forEach(element => { + attributeCarrier.forEach((element) => { let attributeVal = element.getAttribute(attribute) element.removeAttribute(attribute) replaceFunc.call(this, context, element, attributeVal) @@ -176,7 +176,7 @@ export default class Card { */ static _replaceCallback(context, element, attributeVal) { if (element.tagName == 'A') { - element.addEventListener('pointerdown', event => { + element.addEventListener('pointerdown', (event) => { event.preventDefault() }) } @@ -189,7 +189,7 @@ export default class Card { trimmedArgs = trimmedArgs.substring(0, trimmedArgs.length - 1) let callParts = funcPart.split('.') - let argsStrings = trimmedArgs.split(',').filter(entry => { + let argsStrings = trimmedArgs.split(',').filter((entry) => { return entry.trim() != '' }) /** @@ -218,12 +218,12 @@ export default class Card { // These are 'hardcoded' inside the convert.js. if (element.tagName == 'circle') return false - this.registerEvent(context, interactionType, element, event => { + this.registerEvent(context, interactionType, element, (event) => { /** * Replaces the strings from the listener with the corresponding variables. */ let args = [] - argsStrings.forEach(arg => { + argsStrings.forEach((arg) => { arg = arg.trim() if (arg == 'this') args.push(event.target) else if (arg == 'event') args.push(event) @@ -269,7 +269,7 @@ export default class Card { */ return html.replace( /<\s*(a|video|img|image|circle)\s(.*?)(xlink:href|href|src)\s*=\s*["'](\..*?)["']\s*(.*?)>/g, - function() { + function () { let path = that._getRelativePath(arguments[4]) const tag = `<${arguments[1]} ${arguments[2]} ${arguments[3]}="${path}" ${arguments[5]}>` /* if (that.debug) */ console.log('Adjusted: ', tag) @@ -298,7 +298,7 @@ export default class Card { return new Promise((resolve, reject) => { let request = new XMLHttpRequest() - request.onreadystatechange = function() { + request.onreadystatechange = function () { if (this.readyState == 4) { if (this.status == 200 || Card._isLocal()) { try { @@ -423,7 +423,7 @@ export default class Card { } this._createPopup(context, position, content, options) - .then(popup => { + .then((popup) => { if ( //Test if meanwhile another popup was registered... this._getPopup(context) || @@ -441,9 +441,9 @@ export default class Card { // let unnecessaryPopupElement = popup.element.querySelector(".popupContent > .popup") // unnecessaryPopupElement.classList.remove("popup") - popupParagraphs.forEach(popupParagraph => { + popupParagraphs.forEach((popupParagraph) => { popupParagraph.setAttribute('draggable', false) - popupParagraph.addEventListener('mousedown', event => { + popupParagraph.addEventListener('mousedown', (event) => { event.preventDefault() }) }) @@ -451,7 +451,7 @@ export default class Card { this._setPopup(context, popup, src) } }) - .catch(e => console.error(e)) + .catch((e) => console.error(e)) } /** @@ -491,14 +491,14 @@ export default class Card { Object.assign( { parent: context, - content + content, }, Object.assign( { noStyle: true, // TODO: Remove offset when positioning according to element position // is working. - posOffset: 10 + posOffset: 10, }, options ) @@ -510,7 +510,7 @@ export default class Card { // We manually prevent this here. popup.element.style.display = 'none' - let promise = new Promise(resolve => { + let promise = new Promise((resolve) => { if (popup.loaded) resolve(popup) else { popup.onload = () => { @@ -519,7 +519,7 @@ export default class Card { } }) - promise.then(popup => { + promise.then((popup) => { popup.element.style.display = 'block' popup.element.style.visibility = 'hidden' popup.element.style.opacity = 0 @@ -531,12 +531,12 @@ export default class Card { }) Object.assign(popup.element.style, { - zIndex: this.zIndices.popup + zIndex: this.zIndices.popup, }) TweenLite.to(popup.element, this.animation.popup, { autoAlpha: 1, - ease: Power2.easeIn + ease: Power2.easeIn, }) }) @@ -560,7 +560,7 @@ export default class Card { popup.remove() //this._cleanup(context) //overlay.parentNode.removeChild(overlay) - } + }, }) } } @@ -618,7 +618,7 @@ export default class Card { let popupPage = parser.parseFromString(xhr.responseText, 'text/html') //Fix the relative path of loaded images in the popup. - popupPage.querySelectorAll('img').forEach(node => { + popupPage.querySelectorAll('img').forEach((node) => { node.setAttribute('src', that._getRelativePath(node.getAttribute('src'))) }) let html = popupPage.body.innerHTML @@ -648,7 +648,7 @@ export default class Card { if (editable) { let isDirty = mainController.askSaveNode() if (isDirty) - mainController.saveNode(html.innerHTML, url => { + mainController.saveNode(html.innerHTML, (url) => { if (callback) { callback() } @@ -670,12 +670,12 @@ export default class Card { } Card._openPopup(context, src, local, content, { - closeCommand: callback + closeCommand: callback, }) } } - overlay.onclick = e => { + overlay.onclick = (e) => { if (editable) e.preventDefault() } //console.log("onreadystatechange", editable) @@ -712,7 +712,7 @@ export default class Card { for (let highlight of correspondingHighlights) { if (highlight.parentNode && highlight.parentNode.nodeName.toLowerCase() == 'g') { Highlight.openHighlight(highlight, { - animation: Card.highlightAnimation + animation: Card.highlightAnimation, }) this._addHighlight(context, highlight) } @@ -841,19 +841,19 @@ export default class Card { // TODO: Adjust to load while animating (Problem: Unload when cancelled). // console.log('loadHighlightPopup', src, position, local) this._loadPopupContent(context, src) - .then(content => { + .then((content) => { this._openPopup(context, src, local, content, { highlight: node, - closeCommand: popup => { + closeCommand: (popup) => { this._overlayCleanup(context, overlay) popup.remove() - } + }, }) }) - .catch(err => { + .catch((err) => { console.error(err) }) - } + }, }) } } @@ -937,7 +937,7 @@ export default class Card { let globalBottomRight = { x: imageWidth, - y: imageHeight + y: imageHeight, } globalBottomRight = Points.fromNodeToPage(zoomable, globalBottomRight) @@ -1003,7 +1003,7 @@ export default class Card { position: 'absolute', top: 0, left: 0, - zIndex: 200 + zIndex: 200, }) wrapper.appendChild(zoomContainer) @@ -1071,13 +1071,13 @@ export default class Card { y: current.y, width: current.width + borderX, height: current.height + borderY, - transformOrigin + transformOrigin, }) TweenLite.set(zoomable, { opacity: 0 }) let icon = zoomedFig.querySelector('.icon') TweenLite.set(icon, { - transformOrigin + transformOrigin, }) zoomedFig.style.transformOrigin = 'calc(100% - ' + @@ -1097,8 +1097,8 @@ export default class Card { ease: Power2.easeIn, css: { scaleX: scaleFactor, - scaleY: scaleFactor - } + scaleY: scaleFactor, + }, }, 0 ) @@ -1107,11 +1107,11 @@ export default class Card { display: 'block', opacity: 0, x: -parseFloat(zoomedFigStyle.borderLeftWidth), - width: current.width + borderX - } + width: current.width + borderX, + }, }) .to(zoomCaption, this.animation.fade, { - autoAlpha: 1 + autoAlpha: 1, }) } else this._openZoomableEditorBehaviour(wrapper, img, zoomable, zoomedFig, current) } @@ -1160,7 +1160,7 @@ export default class Card { x: current.x, y: current.y, width: current.width, - height: current.height + height: current.height, }) let editor = mainController.topController().ensureEditor(img) let savedDisplay = zoomIcon.style.display @@ -1187,13 +1187,13 @@ export default class Card { wrapper.appendChild(iconClone) TweenLite.set(iconClone, { x: current.iconPos.x, y: current.iconPos.y }) - zoomable.onmousedown = event => { + zoomable.onmousedown = (event) => { if (this.debug) console.log('mousedown', event.target) event.preventDefault() zoomable.dragging = true zoomable.dragStartPos = { x: event.pageX, y: event.pageY } } - zoomable.onmousemove = event => { + zoomable.onmousemove = (event) => { if (this.debug) console.log('onmousemove', event.target) if (zoomable.dragging) { event.preventDefault() @@ -1201,7 +1201,7 @@ export default class Card { let dy = event.pageY - zoomable.dragStartPos.y TweenLite.set([zoomable, iconClone], { x: '+=' + dx, - y: '+=' + dy + y: '+=' + dy, }) zoomable.dragStartPos = { x: event.pageX, y: event.pageY } if (editor) { @@ -1214,7 +1214,7 @@ export default class Card { } let startZoom = 1 - zoomable.onmousewheel = event => { + zoomable.onmousewheel = (event) => { event.preventDefault() let direction = event.detail < 0 || event.wheelDelta > 0 const zoomFactor = 1.1 @@ -1250,24 +1250,24 @@ export default class Card { let zoomedCaption = zoomedFig.querySelector('figcaption.zoomcap') TweenLite.to(zoomedCaption, this.animation.fade, { - autoAlpha: 0 + autoAlpha: 0, }) TweenLite.to(zoomedFig, this.animation.zoomable, { css: { scaleX: 1, - scaleY: 1 + scaleY: 1, }, onComplete: () => { TweenLite.set(zoomable, { - opacity: 1 + opacity: 1, }) let div = zoomedFig.parentNode let videoElement = div.querySelector('video') if (videoElement) videoElement.pause() div.parentNode.removeChild(div) - } + }, }) InteractionMapper.off(zoomedFig) @@ -1341,12 +1341,12 @@ export default class Card { height: globalIndexCardRect.height, maxWidth: '100%', margin: 0, - zIndex: this.zIndices.article - } + zIndex: this.zIndices.article, + }, }) TweenLite.set(articleClone, { - autoAlpha: 0 + autoAlpha: 0, }) TweenLite.set(card, { css: { maxWidth: '100%' } }) @@ -1356,7 +1356,7 @@ export default class Card { scaleX, scaleY, transformOrigin: '0% 0%', - rotation: angle + rotation: angle, }) indexbox.prepend(clone) clone.setAttribute('data-source', src) @@ -1365,7 +1365,7 @@ export default class Card { let title = titlebar.querySelector('h2') let titlebarStyle = window.getComputedStyle(titlebar) let start = { - height: parseInt(titlebarStyle.height) + height: parseInt(titlebarStyle.height), } if (this.dynamicHeight) { @@ -1385,10 +1385,7 @@ export default class Card { //jquery hyphenate below if (this._isJQueryPresent()) { - $('.column') - .not('.overview') - .children('p') - .hyphenate('de') + $('.column').not('.overview').children('p').hyphenate('de') } //logging @@ -1414,23 +1411,23 @@ export default class Card { card.classList.add('visited') }, onUpdateParams: ['{self}'], - onUpdate: self => { + onUpdate: (self) => { let transform = self.target._gsTransform TweenLite.set(title, { - scale: 1 / transform.scaleX + scale: 1 / transform.scaleX, }) TweenLite.set(titlebar, { - height: (start.height * 1) / transform.scaleY + height: (start.height * 1) / transform.scaleY, }) // Retain the border at same visual thickness. titlebar.style.borderBottomWidth = desiredBorderBottomWidth / transform.scaleY + 'px' - } + }, }) TweenLite.to([articleClone], this.animation.articleTransition / 2, { delay: this.animation.articleTransition / 2, - autoAlpha: 1 + autoAlpha: 1, }) if (editable) { @@ -1479,11 +1476,11 @@ export default class Card { if (editable) { let isDirty = mainController.askSaveNode() if (isDirty) { - mainController.saveNode(html.innerHTML, url => { + mainController.saveNode(html.innerHTML, (url) => { callback(url) this._closeIndexCard(context, card, clone, articleClone, { eventElements, - src + src, }) }) } else { @@ -1522,7 +1519,7 @@ export default class Card { let scale = { x: globalPreviewRect.width / globalIndexCardRect.width, - y: globalPreviewRect.height / globalIndexCardRect.height + y: globalPreviewRect.height / globalIndexCardRect.height, } let titlebar = clonedSubcard.querySelector('.titlebar') @@ -1551,16 +1548,16 @@ export default class Card { let titlebarStyle = window.getComputedStyle(previewTitlebar) TweenLite.to(titlebar, this.animation.articleTransition, { - height: parseInt(titlebarStyle.height) + height: parseInt(titlebarStyle.height), }) TweenLite.to(clonedArticle, this.animation.articleTransition / 2, { - autoAlpha: 0 + autoAlpha: 0, }) let title = titlebar.querySelector('h2') let original = { - height: parseInt(titlebarStyle.height) + height: parseInt(titlebarStyle.height), } if (this.dynamicHeight) { @@ -1589,24 +1586,24 @@ export default class Card { mainController.popController() } clonedSubcard.remove() - } + }, }) }, onUpdateParams: ['{self}'], - onUpdate: function(self) { + onUpdate: function (self) { let transform = self.target._gsTransform TweenLite.set(title, { - scale: 1 / transform.scaleX + scale: 1 / transform.scaleX, }) TweenLite.set(titlebar, { - height: (original.height * 1) / transform.scaleY + height: (original.height * 1) / transform.scaleY, }) // Retain the border at same visual thickness. titlebar.style.borderBottomWidth = desiredBorderBottomWidth / transform.scaleY + 'px' - } + }, }) } @@ -1653,7 +1650,7 @@ export default class Card { * Called by the expandIndexCard(...) */ let target = event.target - const saveCallback = url => { + const saveCallback = (url) => { let handler = `Card.openIndexCard(event, '${url}')` if (this.debug) console.log('File has changed', target, handler) @@ -1744,9 +1741,9 @@ export default class Card { } let highlights = this._getHighlights(context) - highlights.forEach(highlight => { + highlights.forEach((highlight) => { Highlight.closeHighlight(highlight, { - animation: Card.highlightAnimation + animation: Card.highlightAnimation, }) }) @@ -1768,13 +1765,13 @@ export default class Card { let global = this._getGlobalRect(element) let localPosition = Points.fromPageToNode(context, { x: global.x, - y: global.y + y: global.y, }) return DOMRectReadOnly.fromRect({ x: localPosition.x, y: localPosition.y, width: global.width, - height: global.height + height: global.height, }) } @@ -1797,7 +1794,7 @@ export default class Card { x: globalPosition.x, y: globalPosition.y, width: cardWidth, - height: cardHeight + height: cardHeight, }) } @@ -1819,19 +1816,19 @@ export default class Card { this._replaceAttributes(context, html, 'onclick', this._replaceCallback) } let zoomableWrappers = html.querySelectorAll('.svg-wrapper') - zoomableWrappers.forEach(wrapper => { + zoomableWrappers.forEach((wrapper) => { let svg = wrapper.querySelector('svg') Object.assign(wrapper.style, { width: svg.getAttribute('width') + 'px', - height: svg.getAttribute('height') + 'px' + height: svg.getAttribute('height') + 'px', }) }) let zoomableVideoWrappers = html.querySelectorAll('.video-wrapper') - zoomableVideoWrappers.forEach(wrapper => { + zoomableVideoWrappers.forEach((wrapper) => { let video = wrapper.querySelector('video') Object.assign(wrapper.style, { width: video.getAttribute('width') + 'px', - height: video.getAttribute('height') + 'px' + height: video.getAttribute('height') + 'px', }) }) @@ -1870,12 +1867,12 @@ export default class Card { let globalClick = event.center ? event.center : { x: event.x, y: event.y } let localClick = Points.fromPageToNode(indexbox, globalClick) - let linkRects = links.map(link => { + let linkRects = links.map((link) => { let rect = link.getBoundingClientRect() let topLeft = Points.fromPageToNode(indexbox, rect) let center = Points.fromPageToNode(indexbox, { x: rect.x + rect.width / 2, - y: rect.y + rect.height / 2 + y: rect.y + rect.height / 2, }) return { x: topLeft.x, @@ -1883,12 +1880,12 @@ export default class Card { width: rect.width, height: rect.height, center, - link + link, } }) let distances = [] - linkRects.forEach(rect => { + linkRects.forEach((rect) => { let distance = Card.pointRectDist(localClick, rect) if (distance == 0.0) { // Distance == 0.0 indicates an inside relation. Since these @@ -2095,7 +2092,7 @@ Card.zIndices = { article: 10, popup: 100, zoomable: 101, - zoomedFigure: 102 + zoomedFigure: 102, } Card.animation = { @@ -2103,5 +2100,5 @@ Card.animation = { fade: 0.2, popup: 0.1, highlight: 0.4, - zoomable: 0.5 + zoomable: 0.5, } diff --git a/lib/card/highlight.js b/lib/card/highlight.js index 3c734d8..49cb59d 100644 --- a/lib/card/highlight.js +++ b/lib/card/highlight.js @@ -94,7 +94,7 @@ export default class Highlight extends Object { obj.classList.add(this.expandedClass) obj.setAttribute('stroke-width', stroke / scale) if (onComplete) onComplete() - } + }, }) } @@ -113,7 +113,7 @@ export default class Highlight extends Object { obj.classList.remove('zooming') obj.classList.remove(this.expandedClass) obj.setAttribute('stroke-width', stroke) - } + }, }) } @@ -163,7 +163,7 @@ export default class Highlight extends Object { this.shrink(maskImage, { stroke }) return } - let circles = Array.from(circleGroup.children).filter(e => e.tagName == 'circle') + let circles = Array.from(circleGroup.children).filter((e) => e.tagName == 'circle') for (let c of circles) { //console.log("shrinking all circles") this.shrink(c, { stroke }) @@ -210,18 +210,18 @@ export default class Highlight extends Object { // eslint-disable-next-line no-unused-vars let [mask, maskImage] = this._getSVGMask(target, { svgRoot, - image + image, }) let center = this._calculateCenterRelativeTo(target, image) console.log('_calculateCenterRelativeTo', center) TweenLite.set(maskImage, { - transformOrigin: `${center.x} ${center.y}` + transformOrigin: `${center.x} ${center.y}`, }) TweenLite.set(target, { transformOrigin: '50% 50%' }) TweenLite.to([target, maskImage], animation, { scale, - onComplete: onExpanded + onComplete: onExpanded, }) target.classList.add(this.expandedClass) @@ -259,7 +259,7 @@ export default class Highlight extends Object { [mask, maskImage] = this._createSVGMask(circle, { svgRoot, image, - id + id, }) return [mask, maskImage] @@ -353,7 +353,7 @@ export default class Highlight extends Object { let [mask, maskImage] = this._getSVGMask(target) // console.log('Close Highlight', maskImage) TweenLite.to([target, maskImage], animation, { - scale: 1 + scale: 1, }) } diff --git a/lib/card/plugin.js b/lib/card/plugin.js index 050b54d..e71b8a7 100644 --- a/lib/card/plugin.js +++ b/lib/card/plugin.js @@ -63,7 +63,7 @@ export class CardPluginBase { let requirements = this._collectAllRequirements() let missing = [] - requirements.forEach(module => { + requirements.forEach((module) => { if (context.modules.indexOf(module.name) == -1) { missing.push(module.name) } @@ -121,12 +121,12 @@ CardPlugin.LightBox = class LightBox extends CardPluginBase { top: 0, left: 0, width: '100%', - height: '100%' + height: '100%', }, this.style, { display: 'none', - position: 'absolute' + position: 'absolute', } ) @@ -199,7 +199,7 @@ CardPlugin.EnlargeableThumbnail = class EnlargeableThumbnail extends CardPluginB wrapper.appendChild(icon) Object.assign(wrapper.style, { - cursor: 'pointer' + cursor: 'pointer', }) InteractionMapper.on(this.interactionType, wrapper, () => { @@ -221,13 +221,13 @@ CardPlugin.EnlargeableThumbnail = class EnlargeableThumbnail extends CardPluginB Object.assign(imageWrapper.style, { maxWidth: 'none', - maxHeight: 'none' + maxHeight: 'none', }) Object.assign(image.style, { width: '100%', height: '100%', - objectFit: 'cover' + objectFit: 'cover', }) this._replaceIcon(imageWrapper) @@ -250,7 +250,7 @@ CardPlugin.EnlargeableThumbnail = class EnlargeableThumbnail extends CardPluginB const max = { width: context.offsetWidth * maxFillRatio, - height: context.offsetHeight * maxFillRatio + height: context.offsetHeight * maxFillRatio, } let majorSide @@ -284,14 +284,14 @@ CardPlugin.EnlargeableThumbnail = class EnlargeableThumbnail extends CardPluginB let targetDimensions = { width: 0, - height: 0 + height: 0, } let position = Points.fromPageToNode(context, Points.fromNodeToPage(source, { x: 0, y: 0 })) let targetOffset = { x: 0, - y: 0 + y: 0, } targetDimensions[majorSide.name] = size @@ -311,22 +311,22 @@ CardPlugin.EnlargeableThumbnail = class EnlargeableThumbnail extends CardPluginB y: position.y, position: 'absolute', width: parseInt(sourceStyle.width), - height: parseInt(sourceStyle.height) + height: parseInt(sourceStyle.height), }) TweenMax.set(overlay, { display: 'flex', - autoAlpha: 0 + autoAlpha: 0, }) TweenMax.to(imageWrapper, this.zoomAnimationDuration, { x: targetOffset.x, y: targetOffset.y, width: targetDimensions.width, - height: targetDimensions.height + height: targetDimensions.height, }) TweenMax.to(overlay, this.fadeAnimationTime, { - autoAlpha: 1 + autoAlpha: 1, }) } @@ -358,10 +358,10 @@ CardPlugin.EnlargeableThumbnail = class EnlargeableThumbnail extends CardPluginB timeline .to(overlay, this.fadeAnimationDuration, { - autoAlpha: 0 + autoAlpha: 0, }) .set(overlay, { - display: 'none' + display: 'none', }) } } @@ -418,7 +418,7 @@ CardPlugin.Speech = class SpeechPlugin extends CardPluginBase { this._end = this._end.bind(this) this._setupUtterance() - this.utterance.addEventListener('end', event => { + this.utterance.addEventListener('end', (event) => { this._end() }) } @@ -451,7 +451,7 @@ CardPlugin.Speech = class SpeechPlugin extends CardPluginBase { } else { if (subcard) { let clone = subcard.cloneNode(true) - clone.querySelectorAll('figure').forEach(figure => { + clone.querySelectorAll('figure').forEach((figure) => { figure.parentNode.removeChild(figure) }) @@ -554,10 +554,10 @@ CardPlugin.Speech = class SpeechPlugin extends CardPluginBase { } async _stop() { - return new Promise(resolve => { + return new Promise((resolve) => { if (this.activeUtterance) { this.activeUtterance.addEventListener('end', resolve, { - once: true + once: true, }) } diff --git a/lib/card/scatter.js b/lib/card/scatter.js index c978055..53bab2d 100644 --- a/lib/card/scatter.js +++ b/lib/card/scatter.js @@ -66,12 +66,12 @@ export default class ScatterCard extends Card { scatterContainer.element.appendChild(element) new DOMScatter(element, scatterContainer, { width: 1400, - height: 1200 + height: 1200, }) this.setup(element, html, { basePath, - modules + modules, }) return element } @@ -132,15 +132,15 @@ export default class ScatterCard extends Card { let url = basePath + '/' + item + '/index.html' console.log('Loading', url) this.loadHTML(url) - .then(html => { + .then((html) => { console.log('Received', html) let element = this.createCardScatter(html, scatterContainer, { basePath, - modules + modules, }) resolve(element) }) - .catch(e => reject(e)) + .catch((e) => reject(e)) }) } @@ -157,6 +157,6 @@ ScatterCard.selectedLanguage = 0 ScatterCard.languages = ['Deutsch', 'English'] ScatterCard.languageTags = { Deutsch: 'de', - English: 'en' + English: 'en', } ScatterCard.scatterContainer = null diff --git a/lib/card/theme.js b/lib/card/theme.js index 8b30feb..3718dc7 100644 --- a/lib/card/theme.js +++ b/lib/card/theme.js @@ -20,7 +20,7 @@ export default class Theme { path = path ? path : './config.json' let xhttp = new XMLHttpRequest() - xhttp.onreadystatechange = function() { + xhttp.onreadystatechange = function () { if (this.readyState == 4) { if (this.status == 200 || Theme._isLocal()) { try { diff --git a/lib/card/wrapper.js b/lib/card/wrapper.js index ed88a41..23a6ccc 100644 --- a/lib/card/wrapper.js +++ b/lib/card/wrapper.js @@ -17,7 +17,7 @@ export default class CardWrapper extends Object { handleClicks() { this.domNode.addEventListener( 'click', - event => { + (event) => { if (event.isTrusted) { Events.stop(event) if (this.triggerSVGClicks && this.isSVGNode(event.target)) { @@ -32,7 +32,7 @@ export default class CardWrapper extends Object { handleClicksAsTaps() { this.domNode.addEventListener( 'click', - event => { + (event) => { if (event.isTrusted) { Events.stop(event) } @@ -99,20 +99,20 @@ export default class CardWrapper extends Object { let globalClick = event.center ? event.center : { x: event.x, y: event.y } let localClick = Points.fromPageToNode(element, globalClick) - let clickRects = activeNodes.map(link => { + let clickRects = activeNodes.map((link) => { let rect = link.getBoundingClientRect() // Since the getBoundingClientRect is untransformed we cannot rely on it's size // We need a transformed bottom right to calculate local width and height let bottomRight = Points.fromPageToNode(element, { x: rect.x + rect.width, - y: rect.y + rect.height + y: rect.y + rect.height, }) let topLeft = Points.fromPageToNode(element, rect) let width = Math.abs(bottomRight.x - topLeft.x) let height = Math.abs(bottomRight.y - topLeft.y) let center = Points.fromPageToNode(element, { x: rect.x + width / 2, - y: rect.y + height / 2 + y: rect.y + height / 2, }) return { x: topLeft.x, @@ -120,12 +120,12 @@ export default class CardWrapper extends Object { width, height, center, - link + link, } }) let distances = [] - clickRects.forEach(rect => { + clickRects.forEach((rect) => { let distance = Points.distanceToRect(localClick, rect) distances.push(parseInt(distance)) }) diff --git a/lib/doctest.js b/lib/doctest.js index b15f783..1466e23 100755 --- a/lib/doctest.js +++ b/lib/doctest.js @@ -4,10 +4,10 @@ var docTestLogMessages = [] -Array.prototype.equals = function(array) { +Array.prototype.equals = function (array) { return ( this.length == array.length && - this.every(function(this_i, i) { + this.every(function (this_i, i) { return this_i == array[i] }) ) diff --git a/lib/errors.js b/lib/errors.js index 91f43cc..727a746 100755 --- a/lib/errors.js +++ b/lib/errors.js @@ -33,7 +33,7 @@ export default class Errors { errors = document.createElement('div') errors.setAttribute('id', 'runtime-errors') this.setStyle(document.body, { - border: '2px solid red' + border: '2px solid red', }) this.setStyle(errors, { position: 'absolute', @@ -41,7 +41,7 @@ export default class Errors { padding: '8px', width: '100%', background: 'red', - color: 'white' + color: 'white', }) document.body.appendChild(errors) let counter = document.createElement('div') @@ -55,7 +55,7 @@ export default class Errors { fontSize: '18px', textAlign: 'center', lineHeight: '32px', - verticalAlign: 'middle' + verticalAlign: 'middle', }) counter.innerHTML = '1' errors.appendChild(counter) @@ -66,7 +66,7 @@ export default class Errors { top: '6px', left: '48px', height: '44px', - fontSize: '32px' + fontSize: '32px', }) header.innerHTML = 'Runtime Errors' errors.appendChild(header) @@ -97,7 +97,7 @@ export default class Errors { let errors = document.getElementById('runtime-errors') let infos = errors.querySelectorAll('.info') if (infos.length > 0) { - infos.forEach(info => errors.removeChild(info)) + infos.forEach((info) => errors.removeChild(info)) } else { this.expandErrors() } @@ -116,7 +116,7 @@ export default class Errors { // Register more informative error handler window.addEventListener( 'error', - event => { + (event) => { if (typeof event.error == 'undefined') { // This sometimes happens in Edge. Since we have no error // position, we cannot do much beside an info log. @@ -128,7 +128,7 @@ export default class Errors { true ) - document.addEventListener('DOMContentLoaded', event => { + document.addEventListener('DOMContentLoaded', (event) => { this.showErrors() }) } diff --git a/lib/events.js b/lib/events.js index b616505..e3ddad1 100755 --- a/lib/events.js +++ b/lib/events.js @@ -2,7 +2,7 @@ export default class Events { static stop(event) { event.preventDefault() // I removed this, as it destroys all the Hammer.js events. - // And also the click event. + // And also the click event. // It seems to have no (apparent) negative impact. -SO // event.stopPropagation() } @@ -65,7 +65,7 @@ export default class Events { clientX: t.clientX, clientY: t.clientY, pageX: t.pageX, - pageY: t.pageY + pageY: t.pageY, }) } return touches @@ -105,8 +105,8 @@ export default class Events { ctrlKey: event.ctrlKey, altKey: event.altKey, shiftKey: event.shiftKey, - metaKey: event.metaKey - } + metaKey: event.metaKey, + }, } if (event.type.startsWith('touch')) { // On Safari-WebKit the TouchEvent has layerX, layerY coordinates @@ -219,7 +219,7 @@ export default class Events { width: '480px', height: '640px', overflow: 'auto', - backgroundColor: 'lightgray' + backgroundColor: 'lightgray', }) document.body.appendChild(element) this.popup = element @@ -240,7 +240,7 @@ export default class Events { } Elements.setStyle(this.popup, { left: event.clientX + 'px', - top: event.clientY + 'px' + top: event.clientY + 'px', }) } } diff --git a/lib/flippable.js b/lib/flippable.js index bf87b31..be798d9 100644 --- a/lib/flippable.js +++ b/lib/flippable.js @@ -17,7 +17,7 @@ export class CardLoader { scale = 1, minScale = 0.5, maxScale = 1.5, - rotation = 0 + rotation = 0, } = {} ) { this.src = src @@ -52,8 +52,8 @@ export class PDFLoader extends CardLoader { load(domNode) { return new Promise((resolve, reject) => { - PDFJS.getDocument(this.src).then(pdf => { - pdf.getPage(1).then(page => { + PDFJS.getDocument(this.src).then((pdf) => { + pdf.getPage(1).then((page) => { let scale = this.scale * app.renderer.resolution let invScale = 1 / scale let viewport = page.getViewport(scale) @@ -67,7 +67,7 @@ export class PDFLoader extends CardLoader { // Render PDF page into canvas context. let renderContext = { canvasContext: context, - viewport: viewport + viewport: viewport, } page.render(renderContext) domNode.appendChild(canvas) @@ -87,7 +87,7 @@ export class ImageLoader extends CardLoader { return new Promise((resolve, reject) => { let isImage = domNode instanceof HTMLImageElement let image = isImage ? domNode : document.createElement('img') - image.onload = e => { + image.onload = (e) => { if (!isImage) { domNode.appendChild(image) this.addedNode = image @@ -103,7 +103,7 @@ export class ImageLoader extends CardLoader { image.height = image.naturalHeight resolve(this) } - image.onerror = e => { + image.onerror = (e) => { reject(this) } image.src = this.src @@ -125,10 +125,10 @@ export class FrameLoader extends CardLoader { domNode.appendChild(iframe) this.addedNode = iframe } - iframe.onload = e => { + iframe.onload = (e) => { resolve(this) } - iframe.onerror = e => { + iframe.onerror = (e) => { reject(this) } iframe.src = this.src @@ -141,7 +141,7 @@ export class HTMLLoader extends CardLoader { return new Promise((resolve, reject) => { let xhr = new XMLHttpRequest() xhr.open('GET', this.src, false) - xhr.onreadystatechange = e => { + xhr.onreadystatechange = (e) => { if (xhr.readyState == 4) { domNode.innerHTML = this.prepare(xhr.response) this.addedNode = domNode.firstElementChild @@ -151,7 +151,7 @@ export class HTMLLoader extends CardLoader { resolve(this) } } - xhr.onerror = e => { + xhr.onerror = (e) => { reject(this) } xhr.send() @@ -209,7 +209,7 @@ export class DOMFlip { onClose = null, onUpdate = null, onRemoved = null, - onLoaded = null + onLoaded = null, } = {} ) { this.domScatterContainer = domScatterContainer @@ -251,8 +251,8 @@ export class DOMFlip { // call we can access the new dom element by id this.cardWrapper = dom.querySelector('#' + this.id) let front = this.cardWrapper.querySelector('.front') - this.frontLoader.load(front).then(loader => { - this.frontLoaded(loader).then(obj => { + this.frontLoader.load(front).then((loader) => { + this.frontLoaded(loader).then((obj) => { if (this.onLoaded) this.onLoaded() resolve(this) }) @@ -276,7 +276,7 @@ export class DOMFlip { scalable: this.scalable, rotatable: this.rotatable, overdoScaling: this.overdoScaling, - tapDelegate: this.tapDelegateFactory ? new this.tapDelegateFactory(this.cardWrapper) : null + tapDelegate: this.tapDelegateFactory ? new this.tapDelegateFactory(this.cardWrapper) : null, }) if (this.center) { @@ -284,7 +284,7 @@ export class DOMFlip { } if (this.closeOnMinScale) { - const removeOnMinScale = function() { + const removeOnMinScale = function () { if (scatter.scale <= scatter.minScale) { this.flippable.close() @@ -306,7 +306,7 @@ export class DOMFlip { let back = this.cardWrapper.querySelector('.back') if (this.preloadBack) { - this.backLoader.load(back).then(loader => { + this.backLoader.load(back).then((loader) => { this.setupFlippable(flippable, loader) }) } @@ -340,7 +340,7 @@ export class DOMFlip { } else { let back = this.cardWrapper.querySelector('.back') let flippable = this.flippable - this.backLoader.load(back).then(loader => { + this.backLoader.load(back).then((loader) => { this.setupFlippable(flippable, loader) flippable.start({ duration: this.flipDuration, targetCenter }) }) @@ -352,7 +352,7 @@ export class DOMFlip { opacity: 0, onComplete: () => { this.cardWrapper.remove() - } + }, }) } @@ -400,7 +400,7 @@ export class DOMFlippable { TweenLite.set(this.back, { rotationY: -180 }) TweenLite.set([this.back, this.front], { backfaceVisibility: 'hidden', - perspective: 5000 + perspective: 5000, }) TweenLite.set(this.front, { visibility: 'visible' }) this.infoBtn = element.querySelector('.infoBtn') @@ -412,18 +412,18 @@ export class DOMFlippable { scatter.tapDelegate = tapDelegate } if (this.infoBtn) { - scatter.tapDelegate.onTap(this.infoBtn, event => { + scatter.tapDelegate.onTap(this.infoBtn, (event) => { this.flip.start() }) this.enable(this.infoBtn) } if (this.backBtn) { - scatter.tapDelegate.onTap(this.backBtn, event => { + scatter.tapDelegate.onTap(this.backBtn, (event) => { this.start() }) } if (this.closeBtn) { - scatter.tapDelegate.onTap(this.closeBtn, event => { + scatter.tapDelegate.onTap(this.closeBtn, (event) => { this.close() }) this.enable(this.closeBtn) @@ -447,7 +447,7 @@ export class DOMFlippable { if (this.onRemoved) { this.onRemoved.call(this) } - } + }, }) } } @@ -476,7 +476,7 @@ export class DOMFlippable { scaleButtons() { TweenLite.set([this.infoBtn, this.backBtn, this.closeBtn], { - scale: this.buttonScale + scale: this.buttonScale, }) } @@ -589,7 +589,7 @@ export class DOMFlippable { ease: Power1.easeOut, transformOrigin: '50% 50%', onUpdate, - onComplete: e => { + onComplete: (e) => { if (this.flipped) { //this.hide(this.front) this.enable(this.backBtn) @@ -618,7 +618,7 @@ export class DOMFlippable { this.scatter.translatable = translatable this.scatter.rotatable = rotatable }, - force3D: true + force3D: true, }) // See https://greensock.com/forums/topic/7997-rotate-the-shortest-way/ TweenLite.to(this.element, this.flipDuration / 2, { @@ -630,7 +630,7 @@ export class DOMFlippable { height: h, x: x, y: y, - onComplete: e => { + onComplete: (e) => { if (this.flipped) { this.hide(this.front) // this.hide(this.infoBtn) @@ -638,7 +638,7 @@ export class DOMFlippable { this.hide(this.back) // this.show(this.infoBtn) } - } + }, }) } } diff --git a/lib/frames.js b/lib/frames.js index 56893a7..6c8bf75 100755 --- a/lib/frames.js +++ b/lib/frames.js @@ -5,7 +5,7 @@ export class FrameContainer { constructor(element) { this.element = element this.delegate = new InteractionMapper(element, this, { - mouseWheelElement: window + mouseWheelElement: window, }) } @@ -47,7 +47,7 @@ export class FrameTarget { bubbles: true, cancelable: true, clientX: p.x, - clientY: p.y + clientY: p.y, }) this.target.dispatchEvent(event) } @@ -79,7 +79,7 @@ export class FrameTarget { radiusX: 2.5, radiusY: 2.5, rotationAngle: 10, - force: 0.5 + force: 0.5, }) const touchEvent = new TouchEvent(type, { @@ -88,7 +88,7 @@ export class FrameTarget { touches: [touchObj], targetTouches: [touchObj], changedTouches: [touchObj], - shiftKey: false + shiftKey: false, }) if (this.debug) console.log('simulateTouchEventChrome', touchEvent) this.target.dispatchEvent(touchEvent) @@ -101,7 +101,7 @@ export class FrameTarget { bubbles: true, cancelable: true, clientX: p.x, - clientY: p.y + clientY: p.y, } data[touchEventKey] = this.createTouchList(pointMap) let event = new TouchEvent(type, data) diff --git a/lib/imageloader.js b/lib/imageloader.js index abdee0b..a2af33b 100644 --- a/lib/imageloader.js +++ b/lib/imageloader.js @@ -14,7 +14,7 @@ function onerror(event) { } function load() { - loadQueue.forEach(url => { + loadQueue.forEach((url) => { let xhr = new XMLHttpRequest() xhr.responseType = 'blob' xhr.onload = onload @@ -25,7 +25,7 @@ function load() { }) } -self.onmessage = event => { +self.onmessage = (event) => { let msg = event.data switch (msg.command) { case 'load': diff --git a/lib/index.js b/lib/index.js index ee17f3f..46c6488 100755 --- a/lib/index.js +++ b/lib/index.js @@ -21,7 +21,7 @@ export default class Index { let icon = wrapper.querySelector('.icon') - icon.onerror = e => { + icon.onerror = (e) => { if (this.notfound) icon.src = this.notfound } let iconSrc = src.replace('.html', '.png') @@ -49,7 +49,7 @@ export default class Index { let icon = wrapper.querySelector('.icon') icon.parentNode.replaceChild(iframe, icon) - iframe.onload = e => { + iframe.onload = (e) => { this.frames() } iframe.src = src + window.location.search diff --git a/lib/interaction.js b/lib/interaction.js index 8bc67a5..dac95ac 100755 --- a/lib/interaction.js +++ b/lib/interaction.js @@ -553,7 +553,7 @@ export class InteractionDelegate { useCapture = true, capturePointerEvents = true, cancelOnWindowOut = true, - debug = false + debug = false, } = {} ) { this.debug = debug @@ -589,7 +589,7 @@ export class InteractionDelegate { if (this.debug) console.log('Pointer API' + window.PointerEvent) element.addEventListener( 'pointerdown', - e => { + (e) => { if (this.debug) console.log('pointerdown', e.pointerId) if (this.capture(e)) { if (this.capturePointerEvents) { @@ -606,7 +606,7 @@ export class InteractionDelegate { ) element.addEventListener( 'pointermove', - e => { + (e) => { if (this.debug) console.log('pointermove', e.pointerId, e.pointerType) if (e.pointerType == 'touch' || (e.pointerType == 'mouse' && Events.isPointerDown(e))) { @@ -619,7 +619,7 @@ export class InteractionDelegate { ) element.addEventListener( 'pointerup', - e => { + (e) => { if (this.debug) console.log('pointerup', e.pointerId, e.pointerType) this.onEnd(e) if (this.capturePointerEvents) { @@ -634,7 +634,7 @@ export class InteractionDelegate { ) element.addEventListener( 'pointercancel', - e => { + (e) => { if (this.debug) console.log('pointercancel', e.pointerId, e.pointerType) this.onEnd(e) if (this.capturePointerEvents) element.releasePointerCapture(e.pointerId) @@ -645,7 +645,7 @@ export class InteractionDelegate { if (!this.capturePointerEvents) { element.addEventListener( 'pointerleave', - e => { + (e) => { if (this.debug) console.log('pointerleave', e.pointerId, e.pointerType) if (e.target == element) this.onEnd(e) }, @@ -656,7 +656,7 @@ export class InteractionDelegate { if (!this.capturePointerEvents) { element.addEventListener( 'pointerout', - e => { + (e) => { if (this.debug) console.log('pointerout', e.pointerId, e.pointerType) if (e.target == element) this.onEnd(e) }, @@ -667,7 +667,7 @@ export class InteractionDelegate { if (this.cancelOnWindowOut) { window.addEventListener( 'pointerout', - e => { + (e) => { if (this.debug) console.log('pointerout', e.pointerId, e.pointerType, e.target) if (e.target == element) { this.onEnd(e) @@ -680,7 +680,7 @@ export class InteractionDelegate { if (this.debug) console.log('Touch API') element.addEventListener( 'touchstart', - e => { + (e) => { if (this.debug) console.log('touchstart', this.touchPoints(e)) if (this.capture(e)) { for (let touch of e.changedTouches) { @@ -692,7 +692,7 @@ export class InteractionDelegate { ) element.addEventListener( 'touchmove', - e => { + (e) => { if (this.debug) console.log('touchmove', this.touchPoints(e), e) for (let touch of e.changedTouches) { this.onMove(touch) @@ -705,7 +705,7 @@ export class InteractionDelegate { ) element.addEventListener( 'touchend', - e => { + (e) => { if (this.debug) console.log('touchend', this.touchPoints(e)) for (let touch of e.changedTouches) { this.onEnd(touch) @@ -715,7 +715,7 @@ export class InteractionDelegate { ) element.addEventListener( 'touchcancel', - e => { + (e) => { if (this.debug) console.log('touchcancel', e.targetTouches.length, e.changedTouches.length) for (let touch of e.changedTouches) { this.onEnd(touch) @@ -728,7 +728,7 @@ export class InteractionDelegate { element.addEventListener( 'mousedown', - e => { + (e) => { if (this.debug) console.log('mousedown', e) if (this.capture(e)) { this.onStart(e) @@ -738,7 +738,7 @@ export class InteractionDelegate { ) element.addEventListener( 'mousemove', - e => { + (e) => { // Dow we only use move events if the mouse is down? // HOver effects have to be implemented by other means // && Events.isMouseDown(e)) @@ -752,7 +752,7 @@ export class InteractionDelegate { ) element.addEventListener( 'mouseup', - e => { + (e) => { if (this.debug) console.log('mouseup', e) this.onEnd(e) }, @@ -762,7 +762,7 @@ export class InteractionDelegate { if (!this.capturePointerEvents) { element.addEventListener( 'mouseout', - e => { + (e) => { if (e.target == element) { this.onEnd(e) console.warn("Shouldn't happen: mouseout ends interaction") @@ -774,7 +774,7 @@ export class InteractionDelegate { if (this.cancelOnWindowOut) { window.addEventListener( 'mouseout', - e => { + (e) => { if (e.target == element) { this.onEnd(e) } @@ -968,7 +968,7 @@ export class InteractionMapper extends InteractionDelegate { useCapture = true, capturePointerEvents = true, mouseWheelElement = null, - logInteractionsAbove = 12 + logInteractionsAbove = 12, } = {} ) { super(element, target, { @@ -976,7 +976,7 @@ export class InteractionMapper extends InteractionDelegate { useCapture, capturePointerEvents, longPressTime, - mouseWheelElement + mouseWheelElement, }) this.logInteractionsAbove = logInteractionsAbove } @@ -1132,7 +1132,7 @@ export class InteractionMapper extends InteractionDelegate { hammer.get('tap').set(opts) } - hammer.on(type, event => { + hammer.on(type, (event) => { cb(event) }) @@ -1146,7 +1146,7 @@ export class InteractionMapper extends InteractionDelegate { } } else { for (let j = 0; j < elements.length; j++) { - Hammer.on(elements[j], type, event => { + Hammer.on(elements[j], type, (event) => { cb(event) }) } @@ -1177,7 +1177,7 @@ export class InteractionMapper extends InteractionDelegate { if (Hammer.__hammers.has(element)) { const elementHammers = Hammer.__hammers.get(element) - elementHammers.forEach(it => it.destroy()) + elementHammers.forEach((it) => it.destroy()) Hammer.__hammers.delete(element) } } diff --git a/lib/logging.js b/lib/logging.js index e885d13..f14ac6d 100644 --- a/lib/logging.js +++ b/lib/logging.js @@ -6,14 +6,14 @@ let logMessages = new Set() let logHandlers = { log: console.log, warn: console.warn, - error: console.error + error: console.error, } try { ipc = window.ipcRenderer || require('electron').ipcRenderer - logHandlers.log = message => ipc.send('log', message) - logHandlers.warn = message => ipc.send('warn', message) - logHandlers.error = message => ipc.send('error', message) + logHandlers.log = (message) => ipc.send('log', message) + logHandlers.warn = (message) => ipc.send('warn', message) + logHandlers.error = (message) => ipc.send('error', message) } catch (e) { console.log('Cannot use electron logging.') } diff --git a/lib/pixi/abstractpopup.js b/lib/pixi/abstractpopup.js index 990ce84..63ca94e 100644 --- a/lib/pixi/abstractpopup.js +++ b/lib/pixi/abstractpopup.js @@ -71,7 +71,7 @@ export default class AbstractPopup extends PIXI.Graphics { radius: theme.radius, onHidden: null, visible: true, - orientation: null + orientation: null, }, opts ) @@ -105,7 +105,7 @@ export default class AbstractPopup extends PIXI.Graphics { // interaction //----------------- this.interactive = true - this.on('added', e => { + this.on('added', (e) => { this.show() }) } @@ -285,7 +285,7 @@ export default class AbstractPopup extends PIXI.Graphics { if (cb) { cb.call(this) } - } + }, }) return this @@ -305,7 +305,7 @@ export default class AbstractPopup extends PIXI.Graphics { if (cb) { cb.call(this) } - } + }, }) if (this.opts.onHidden) { diff --git a/lib/pixi/app-fullscreen.html b/lib/pixi/app-fullscreen.html index fc32d06..3ad7040 100644 --- a/lib/pixi/app-fullscreen.html +++ b/lib/pixi/app-fullscreen.html @@ -1,5 +1,5 @@ - + diff --git a/lib/pixi/app-resolution.html b/lib/pixi/app-resolution.html index 8ec9d51..818d0b1 100644 --- a/lib/pixi/app-resolution.html +++ b/lib/pixi/app-resolution.html @@ -8,10 +8,8 @@ - - - - + +