@designcombo/video 0.0.0 → 0.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{SharedSystems-BSw9neqH.js → SharedSystems-BhqLJf5z.js} +2 -2
- package/dist/{WebGLRenderer-BrabW-VK.js → WebGLRenderer-BzdmWLtP.js} +3 -3
- package/dist/{WebGPURenderer-BKwBKkzk.js → WebGPURenderer-Cypu9NWE.js} +3 -3
- package/dist/{browserAll-C7HVZtqZ.js → browserAll-7OZQazmn.js} +2 -2
- package/dist/clips/audio-clip.d.ts +1 -1
- package/dist/clips/iclip.d.ts +16 -4
- package/dist/clips/text-clip.d.ts +29 -0
- package/dist/{colorToUniform-Du0ROyNd.js → colorToUniform-B0NRe8Du.js} +1 -1
- package/dist/{index-CjzowIhV.js → index-BuRTeJh6.js} +2609 -2269
- package/dist/index.es.js +1 -1
- package/dist/index.umd.js +105 -105
- package/dist/json-serialization.d.ts +7 -0
- package/dist/sprite/pixi-sprite-renderer.d.ts +3 -3
- package/dist/studio.d.ts +15 -0
- package/dist/transfomer/parts/wireframe.d.ts +1 -1
- package/dist/transfomer/transformer.d.ts +5 -0
- package/dist/utils/audio-codec-detector.d.ts +28 -0
- package/dist/utils/index.d.ts +1 -0
- package/dist/{webworkerAll-DsE6HIYE.js → webworkerAll-DChKIQQa.js} +2 -2
- package/package.json +10 -9
package/dist/index.umd.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
(function(rt,_e){typeof exports=="object"&&typeof module<"u"?_e(exports):typeof define=="function"&&define.amd?define(["exports"],_e):(rt=typeof globalThis<"u"?globalThis:rt||self,_e(rt.core={}))})(this,(function(rt){"use strict";function _e(s){return s&&s.__esModule&&Object.prototype.hasOwnProperty.call(s,"default")?s.default:s}var qr={},va;function fd(){return va||(va=1,(function(s){var t=(function(){var o=new Date,c=4,u=3,p=2,_=1,b=c,v={setLogLevel:function(w){w==this.debug?b=_:w==this.info?b=p:w==this.warn?b=u:(w==this.error,b=c)},debug:function(w,S){console.debug===void 0&&(console.debug=console.log),_>=b&&console.debug("["+t.getDurationString(new Date-o,1e3)+"]","["+w+"]",S)},log:function(w,S){this.debug(w.msg)},info:function(w,S){p>=b&&console.info("["+t.getDurationString(new Date-o,1e3)+"]","["+w+"]",S)},warn:function(w,S){u>=b&&console.warn("["+t.getDurationString(new Date-o,1e3)+"]","["+w+"]",S)},error:function(w,S){c>=b&&console.error("["+t.getDurationString(new Date-o,1e3)+"]","["+w+"]",S)}};return v})();t.getDurationString=function(o,c){var u;function p(T,E){for(var P=""+T,B=P.split(".");B[0].length<E;)B[0]="0"+B[0];return B.join(".")}o<0?(u=!0,o=-o):u=!1;var _=c||1,b=o/_,v=Math.floor(b/3600);b-=v*3600;var w=Math.floor(b/60);b-=w*60;var S=b*1e3;return b=Math.floor(b),S-=b*1e3,S=Math.floor(S),(u?"-":"")+v+":"+p(w,2)+":"+p(b,2)+"."+p(S,3)},t.printRanges=function(o){var c=o.length;if(c>0){for(var u="",p=0;p<c;p++)p>0&&(u+=","),u+="["+t.getDurationString(o.start(p))+","+t.getDurationString(o.end(p))+"]";return u}else return"(empty)"},s.Log=t;var e=function(o){if(o instanceof ArrayBuffer)this.buffer=o,this.dataview=new DataView(o);else throw"Needs an array buffer";this.position=0};e.prototype.getPosition=function(){return this.position},e.prototype.getEndPosition=function(){return this.buffer.byteLength},e.prototype.getLength=function(){return this.buffer.byteLength},e.prototype.seek=function(o){var c=Math.max(0,Math.min(this.buffer.byteLength,o));return this.position=isNaN(c)||!isFinite(c)?0:c,!0},e.prototype.isEos=function(){return this.getPosition()>=this.getEndPosition()},e.prototype.readAnyInt=function(o,c){var u=0;if(this.position+o<=this.buffer.byteLength){switch(o){case 1:c?u=this.dataview.getInt8(this.position):u=this.dataview.getUint8(this.position);break;case 2:c?u=this.dataview.getInt16(this.position):u=this.dataview.getUint16(this.position);break;case 3:if(c)throw"No method for reading signed 24 bits values";u=this.dataview.getUint8(this.position)<<16,u|=this.dataview.getUint8(this.position+1)<<8,u|=this.dataview.getUint8(this.position+2);break;case 4:c?u=this.dataview.getInt32(this.position):u=this.dataview.getUint32(this.position);break;case 8:if(c)throw"No method for reading signed 64 bits values";u=this.dataview.getUint32(this.position)<<32,u|=this.dataview.getUint32(this.position+4);break;default:throw"readInt method not implemented for size: "+o}return this.position+=o,u}else throw"Not enough bytes in buffer"},e.prototype.readUint8=function(){return this.readAnyInt(1,!1)},e.prototype.readUint16=function(){return this.readAnyInt(2,!1)},e.prototype.readUint24=function(){return this.readAnyInt(3,!1)},e.prototype.readUint32=function(){return this.readAnyInt(4,!1)},e.prototype.readUint64=function(){return this.readAnyInt(8,!1)},e.prototype.readString=function(o){if(this.position+o<=this.buffer.byteLength){for(var c="",u=0;u<o;u++)c+=String.fromCharCode(this.readUint8());return c}else throw"Not enough bytes in buffer"},e.prototype.readCString=function(){for(var o=[];;){var c=this.readUint8();if(c!==0)o.push(c);else break}return String.fromCharCode.apply(null,o)},e.prototype.readInt8=function(){return this.readAnyInt(1,!0)},e.prototype.readInt16=function(){return this.readAnyInt(2,!0)},e.prototype.readInt32=function(){return this.readAnyInt(4,!0)},e.prototype.readInt64=function(){return this.readAnyInt(8,!1)},e.prototype.readUint8Array=function(o){for(var c=new Uint8Array(o),u=0;u<o;u++)c[u]=this.readUint8();return c},e.prototype.readInt16Array=function(o){for(var c=new Int16Array(o),u=0;u<o;u++)c[u]=this.readInt16();return c},e.prototype.readUint16Array=function(o){for(var c=new Int16Array(o),u=0;u<o;u++)c[u]=this.readUint16();return c},e.prototype.readUint32Array=function(o){for(var c=new Uint32Array(o),u=0;u<o;u++)c[u]=this.readUint32();return c},e.prototype.readInt32Array=function(o){for(var c=new Int32Array(o),u=0;u<o;u++)c[u]=this.readInt32();return c},s.MP4BoxStream=e;var r=function(o,c,u){this._byteOffset=c||0,o instanceof ArrayBuffer?this.buffer=o:typeof o=="object"?(this.dataView=o,c&&(this._byteOffset+=c)):this.buffer=new ArrayBuffer(o||0),this.position=0,this.endianness=u??r.LITTLE_ENDIAN};r.prototype={},r.prototype.getPosition=function(){return this.position},r.prototype._realloc=function(o){if(this._dynamicSize){var c=this._byteOffset+this.position+o,u=this._buffer.byteLength;if(c<=u){c>this._byteLength&&(this._byteLength=c);return}for(u<1&&(u=1);c>u;)u*=2;var p=new ArrayBuffer(u),_=new Uint8Array(this._buffer),b=new Uint8Array(p,0,_.length);b.set(_),this.buffer=p,this._byteLength=c}},r.prototype._trimAlloc=function(){if(this._byteLength!=this._buffer.byteLength){var o=new ArrayBuffer(this._byteLength),c=new Uint8Array(o),u=new Uint8Array(this._buffer,0,c.length);c.set(u),this.buffer=o}},r.BIG_ENDIAN=!1,r.LITTLE_ENDIAN=!0,r.prototype._byteLength=0,Object.defineProperty(r.prototype,"byteLength",{get:function(){return this._byteLength-this._byteOffset}}),Object.defineProperty(r.prototype,"buffer",{get:function(){return this._trimAlloc(),this._buffer},set:function(o){this._buffer=o,this._dataView=new DataView(this._buffer,this._byteOffset),this._byteLength=this._buffer.byteLength}}),Object.defineProperty(r.prototype,"byteOffset",{get:function(){return this._byteOffset},set:function(o){this._byteOffset=o,this._dataView=new DataView(this._buffer,this._byteOffset),this._byteLength=this._buffer.byteLength}}),Object.defineProperty(r.prototype,"dataView",{get:function(){return this._dataView},set:function(o){this._byteOffset=o.byteOffset,this._buffer=o.buffer,this._dataView=new DataView(this._buffer,this._byteOffset),this._byteLength=this._byteOffset+o.byteLength}}),r.prototype.seek=function(o){var c=Math.max(0,Math.min(this.byteLength,o));this.position=isNaN(c)||!isFinite(c)?0:c},r.prototype.isEof=function(){return this.position>=this._byteLength},r.prototype.mapUint8Array=function(o){this._realloc(o*1);var c=new Uint8Array(this._buffer,this.byteOffset+this.position,o);return this.position+=o*1,c},r.prototype.readInt32Array=function(o,c){o=o??this.byteLength-this.position/4;var u=new Int32Array(o);return r.memcpy(u.buffer,0,this.buffer,this.byteOffset+this.position,o*u.BYTES_PER_ELEMENT),r.arrayToNative(u,c??this.endianness),this.position+=u.byteLength,u},r.prototype.readInt16Array=function(o,c){o=o??this.byteLength-this.position/2;var u=new Int16Array(o);return r.memcpy(u.buffer,0,this.buffer,this.byteOffset+this.position,o*u.BYTES_PER_ELEMENT),r.arrayToNative(u,c??this.endianness),this.position+=u.byteLength,u},r.prototype.readInt8Array=function(o){o=o??this.byteLength-this.position;var c=new Int8Array(o);return r.memcpy(c.buffer,0,this.buffer,this.byteOffset+this.position,o*c.BYTES_PER_ELEMENT),this.position+=c.byteLength,c},r.prototype.readUint32Array=function(o,c){o=o??this.byteLength-this.position/4;var u=new Uint32Array(o);return r.memcpy(u.buffer,0,this.buffer,this.byteOffset+this.position,o*u.BYTES_PER_ELEMENT),r.arrayToNative(u,c??this.endianness),this.position+=u.byteLength,u},r.prototype.readUint16Array=function(o,c){o=o??this.byteLength-this.position/2;var u=new Uint16Array(o);return r.memcpy(u.buffer,0,this.buffer,this.byteOffset+this.position,o*u.BYTES_PER_ELEMENT),r.arrayToNative(u,c??this.endianness),this.position+=u.byteLength,u},r.prototype.readUint8Array=function(o){o=o??this.byteLength-this.position;var c=new Uint8Array(o);return r.memcpy(c.buffer,0,this.buffer,this.byteOffset+this.position,o*c.BYTES_PER_ELEMENT),this.position+=c.byteLength,c},r.prototype.readFloat64Array=function(o,c){o=o??this.byteLength-this.position/8;var u=new Float64Array(o);return r.memcpy(u.buffer,0,this.buffer,this.byteOffset+this.position,o*u.BYTES_PER_ELEMENT),r.arrayToNative(u,c??this.endianness),this.position+=u.byteLength,u},r.prototype.readFloat32Array=function(o,c){o=o??this.byteLength-this.position/4;var u=new Float32Array(o);return r.memcpy(u.buffer,0,this.buffer,this.byteOffset+this.position,o*u.BYTES_PER_ELEMENT),r.arrayToNative(u,c??this.endianness),this.position+=u.byteLength,u},r.prototype.readInt32=function(o){var c=this._dataView.getInt32(this.position,o??this.endianness);return this.position+=4,c},r.prototype.readInt16=function(o){var c=this._dataView.getInt16(this.position,o??this.endianness);return this.position+=2,c},r.prototype.readInt8=function(){var o=this._dataView.getInt8(this.position);return this.position+=1,o},r.prototype.readUint32=function(o){var c=this._dataView.getUint32(this.position,o??this.endianness);return this.position+=4,c},r.prototype.readUint16=function(o){var c=this._dataView.getUint16(this.position,o??this.endianness);return this.position+=2,c},r.prototype.readUint8=function(){var o=this._dataView.getUint8(this.position);return this.position+=1,o},r.prototype.readFloat32=function(o){var c=this._dataView.getFloat32(this.position,o??this.endianness);return this.position+=4,c},r.prototype.readFloat64=function(o){var c=this._dataView.getFloat64(this.position,o??this.endianness);return this.position+=8,c},r.endianness=new Int8Array(new Int16Array([1]).buffer)[0]>0,r.memcpy=function(o,c,u,p,_){var b=new Uint8Array(o,c,_),v=new Uint8Array(u,p,_);b.set(v)},r.arrayToNative=function(o,c){return c==this.endianness?o:this.flipArrayEndianness(o)},r.nativeToEndian=function(o,c){return this.endianness==c?o:this.flipArrayEndianness(o)},r.flipArrayEndianness=function(o){for(var c=new Uint8Array(o.buffer,o.byteOffset,o.byteLength),u=0;u<o.byteLength;u+=o.BYTES_PER_ELEMENT)for(var p=u+o.BYTES_PER_ELEMENT-1,_=u;p>_;p--,_++){var b=c[_];c[_]=c[p],c[p]=b}return o},r.prototype.failurePosition=0,String.fromCharCodeUint8=function(o){for(var c=[],u=0;u<o.length;u++)c[u]=o[u];return String.fromCharCode.apply(null,c)},r.prototype.readString=function(o,c){return c==null||c=="ASCII"?String.fromCharCodeUint8.apply(null,[this.mapUint8Array(o??this.byteLength-this.position)]):new TextDecoder(c).decode(this.mapUint8Array(o))},r.prototype.readCString=function(o){var c=this.byteLength-this.position,u=new Uint8Array(this._buffer,this._byteOffset+this.position),p=c;o!=null&&(p=Math.min(o,c));for(var _=0;_<p&&u[_]!==0;_++);var b=String.fromCharCodeUint8.apply(null,[this.mapUint8Array(_)]);return o!=null?this.position+=p-_:_!=c&&(this.position+=1),b};var n=Math.pow(2,32);r.prototype.readInt64=function(){return this.readInt32()*n+this.readUint32()},r.prototype.readUint64=function(){return this.readUint32()*n+this.readUint32()},r.prototype.readInt64=function(){return this.readUint32()*n+this.readUint32()},r.prototype.readUint24=function(){return(this.readUint8()<<16)+(this.readUint8()<<8)+this.readUint8()},s.DataStream=r,r.prototype.save=function(o){var c=new Blob([this.buffer]);if(window.URL&&URL.createObjectURL){var u=window.URL.createObjectURL(c),p=document.createElement("a");document.body.appendChild(p),p.setAttribute("href",u),p.setAttribute("download",o),p.setAttribute("target","_self"),p.click(),window.URL.revokeObjectURL(u)}else throw"DataStream.save: Can't create object URL."},r.prototype._dynamicSize=!0,Object.defineProperty(r.prototype,"dynamicSize",{get:function(){return this._dynamicSize},set:function(o){o||this._trimAlloc(),this._dynamicSize=o}}),r.prototype.shift=function(o){var c=new ArrayBuffer(this._byteLength-o),u=new Uint8Array(c),p=new Uint8Array(this._buffer,o,u.length);u.set(p),this.buffer=c,this.position-=o},r.prototype.writeInt32Array=function(o,c){if(this._realloc(o.length*4),o instanceof Int32Array&&this.byteOffset+this.position%o.BYTES_PER_ELEMENT===0)r.memcpy(this._buffer,this.byteOffset+this.position,o.buffer,0,o.byteLength),this.mapInt32Array(o.length,c);else for(var u=0;u<o.length;u++)this.writeInt32(o[u],c)},r.prototype.writeInt16Array=function(o,c){if(this._realloc(o.length*2),o instanceof Int16Array&&this.byteOffset+this.position%o.BYTES_PER_ELEMENT===0)r.memcpy(this._buffer,this.byteOffset+this.position,o.buffer,0,o.byteLength),this.mapInt16Array(o.length,c);else for(var u=0;u<o.length;u++)this.writeInt16(o[u],c)},r.prototype.writeInt8Array=function(o){if(this._realloc(o.length*1),o instanceof Int8Array&&this.byteOffset+this.position%o.BYTES_PER_ELEMENT===0)r.memcpy(this._buffer,this.byteOffset+this.position,o.buffer,0,o.byteLength),this.mapInt8Array(o.length);else for(var c=0;c<o.length;c++)this.writeInt8(o[c])},r.prototype.writeUint32Array=function(o,c){if(this._realloc(o.length*4),o instanceof Uint32Array&&this.byteOffset+this.position%o.BYTES_PER_ELEMENT===0)r.memcpy(this._buffer,this.byteOffset+this.position,o.buffer,0,o.byteLength),this.mapUint32Array(o.length,c);else for(var u=0;u<o.length;u++)this.writeUint32(o[u],c)},r.prototype.writeUint16Array=function(o,c){if(this._realloc(o.length*2),o instanceof Uint16Array&&this.byteOffset+this.position%o.BYTES_PER_ELEMENT===0)r.memcpy(this._buffer,this.byteOffset+this.position,o.buffer,0,o.byteLength),this.mapUint16Array(o.length,c);else for(var u=0;u<o.length;u++)this.writeUint16(o[u],c)},r.prototype.writeUint8Array=function(o){if(this._realloc(o.length*1),o instanceof Uint8Array&&this.byteOffset+this.position%o.BYTES_PER_ELEMENT===0)r.memcpy(this._buffer,this.byteOffset+this.position,o.buffer,0,o.byteLength),this.mapUint8Array(o.length);else for(var c=0;c<o.length;c++)this.writeUint8(o[c])},r.prototype.writeFloat64Array=function(o,c){if(this._realloc(o.length*8),o instanceof Float64Array&&this.byteOffset+this.position%o.BYTES_PER_ELEMENT===0)r.memcpy(this._buffer,this.byteOffset+this.position,o.buffer,0,o.byteLength),this.mapFloat64Array(o.length,c);else for(var u=0;u<o.length;u++)this.writeFloat64(o[u],c)},r.prototype.writeFloat32Array=function(o,c){if(this._realloc(o.length*4),o instanceof Float32Array&&this.byteOffset+this.position%o.BYTES_PER_ELEMENT===0)r.memcpy(this._buffer,this.byteOffset+this.position,o.buffer,0,o.byteLength),this.mapFloat32Array(o.length,c);else for(var u=0;u<o.length;u++)this.writeFloat32(o[u],c)},r.prototype.writeInt32=function(o,c){this._realloc(4),this._dataView.setInt32(this.position,o,c??this.endianness),this.position+=4},r.prototype.writeInt16=function(o,c){this._realloc(2),this._dataView.setInt16(this.position,o,c??this.endianness),this.position+=2},r.prototype.writeInt8=function(o){this._realloc(1),this._dataView.setInt8(this.position,o),this.position+=1},r.prototype.writeUint32=function(o,c){this._realloc(4),this._dataView.setUint32(this.position,o,c??this.endianness),this.position+=4},r.prototype.writeUint16=function(o,c){this._realloc(2),this._dataView.setUint16(this.position,o,c??this.endianness),this.position+=2},r.prototype.writeUint8=function(o){this._realloc(1),this._dataView.setUint8(this.position,o),this.position+=1},r.prototype.writeFloat32=function(o,c){this._realloc(4),this._dataView.setFloat32(this.position,o,c??this.endianness),this.position+=4},r.prototype.writeFloat64=function(o,c){this._realloc(8),this._dataView.setFloat64(this.position,o,c??this.endianness),this.position+=8},r.prototype.writeUCS2String=function(o,c,u){u==null&&(u=o.length);for(var p=0;p<o.length&&p<u;p++)this.writeUint16(o.charCodeAt(p),c);for(;p<u;p++)this.writeUint16(0)},r.prototype.writeString=function(o,c,u){var p=0;if(c==null||c=="ASCII")if(u!=null){var _=Math.min(o.length,u);for(p=0;p<_;p++)this.writeUint8(o.charCodeAt(p));for(;p<u;p++)this.writeUint8(0)}else for(p=0;p<o.length;p++)this.writeUint8(o.charCodeAt(p));else this.writeUint8Array(new TextEncoder(c).encode(o.substring(0,u)))},r.prototype.writeCString=function(o,c){var u=0;if(c!=null){var p=Math.min(o.length,c);for(u=0;u<p;u++)this.writeUint8(o.charCodeAt(u));for(;u<c;u++)this.writeUint8(0)}else{for(u=0;u<o.length;u++)this.writeUint8(o.charCodeAt(u));this.writeUint8(0)}},r.prototype.writeStruct=function(o,c){for(var u=0;u<o.length;u+=2){var p=o[u+1];this.writeType(p,c[o[u]],c)}},r.prototype.writeType=function(o,c,u){var p;if(typeof o=="function")return o(this,c);if(typeof o=="object"&&!(o instanceof Array))return o.set(this,c,u);var _=null,b="ASCII",v=this.position;switch(typeof o=="string"&&/:/.test(o)&&(p=o.split(":"),o=p[0],_=parseInt(p[1])),typeof o=="string"&&/,/.test(o)&&(p=o.split(","),o=p[0],b=parseInt(p[1])),o){case"uint8":this.writeUint8(c);break;case"int8":this.writeInt8(c);break;case"uint16":this.writeUint16(c,this.endianness);break;case"int16":this.writeInt16(c,this.endianness);break;case"uint32":this.writeUint32(c,this.endianness);break;case"int32":this.writeInt32(c,this.endianness);break;case"float32":this.writeFloat32(c,this.endianness);break;case"float64":this.writeFloat64(c,this.endianness);break;case"uint16be":this.writeUint16(c,r.BIG_ENDIAN);break;case"int16be":this.writeInt16(c,r.BIG_ENDIAN);break;case"uint32be":this.writeUint32(c,r.BIG_ENDIAN);break;case"int32be":this.writeInt32(c,r.BIG_ENDIAN);break;case"float32be":this.writeFloat32(c,r.BIG_ENDIAN);break;case"float64be":this.writeFloat64(c,r.BIG_ENDIAN);break;case"uint16le":this.writeUint16(c,r.LITTLE_ENDIAN);break;case"int16le":this.writeInt16(c,r.LITTLE_ENDIAN);break;case"uint32le":this.writeUint32(c,r.LITTLE_ENDIAN);break;case"int32le":this.writeInt32(c,r.LITTLE_ENDIAN);break;case"float32le":this.writeFloat32(c,r.LITTLE_ENDIAN);break;case"float64le":this.writeFloat64(c,r.LITTLE_ENDIAN);break;case"cstring":this.writeCString(c,_);break;case"string":this.writeString(c,b,_);break;case"u16string":this.writeUCS2String(c,this.endianness,_);break;case"u16stringle":this.writeUCS2String(c,r.LITTLE_ENDIAN,_);break;case"u16stringbe":this.writeUCS2String(c,r.BIG_ENDIAN,_);break;default:if(o.length==3){for(var w=o[1],S=0;S<c.length;S++)this.writeType(w,c[S]);break}else{this.writeStruct(o,c);break}}_!=null&&(this.position=v,this._realloc(_),this.position=v+_)},r.prototype.writeUint64=function(o){var c=Math.floor(o/n);this.writeUint32(c),this.writeUint32(o&4294967295)},r.prototype.writeUint24=function(o){this.writeUint8((o&16711680)>>16),this.writeUint8((o&65280)>>8),this.writeUint8(o&255)},r.prototype.adjustUint32=function(o,c){var u=this.position;this.seek(o),this.writeUint32(c),this.seek(u)},r.prototype.mapInt32Array=function(o,c){this._realloc(o*4);var u=new Int32Array(this._buffer,this.byteOffset+this.position,o);return r.arrayToNative(u,c??this.endianness),this.position+=o*4,u},r.prototype.mapInt16Array=function(o,c){this._realloc(o*2);var u=new Int16Array(this._buffer,this.byteOffset+this.position,o);return r.arrayToNative(u,c??this.endianness),this.position+=o*2,u},r.prototype.mapInt8Array=function(o){this._realloc(o*1);var c=new Int8Array(this._buffer,this.byteOffset+this.position,o);return this.position+=o*1,c},r.prototype.mapUint32Array=function(o,c){this._realloc(o*4);var u=new Uint32Array(this._buffer,this.byteOffset+this.position,o);return r.arrayToNative(u,c??this.endianness),this.position+=o*4,u},r.prototype.mapUint16Array=function(o,c){this._realloc(o*2);var u=new Uint16Array(this._buffer,this.byteOffset+this.position,o);return r.arrayToNative(u,c??this.endianness),this.position+=o*2,u},r.prototype.mapFloat64Array=function(o,c){this._realloc(o*8);var u=new Float64Array(this._buffer,this.byteOffset+this.position,o);return r.arrayToNative(u,c??this.endianness),this.position+=o*8,u},r.prototype.mapFloat32Array=function(o,c){this._realloc(o*4);var u=new Float32Array(this._buffer,this.byteOffset+this.position,o);return r.arrayToNative(u,c??this.endianness),this.position+=o*4,u};var a=function(o){this.buffers=[],this.bufferIndex=-1,o&&(this.insertBuffer(o),this.bufferIndex=0)};a.prototype=new r(new ArrayBuffer,0,r.BIG_ENDIAN),a.prototype.initialized=function(){var o;return this.bufferIndex>-1?!0:this.buffers.length>0?(o=this.buffers[0],o.fileStart===0?(this.buffer=o,this.bufferIndex=0,t.debug("MultiBufferStream","Stream ready for parsing"),!0):(t.warn("MultiBufferStream","The first buffer should have a fileStart of 0"),this.logBufferLevel(),!1)):(t.warn("MultiBufferStream","No buffer to start parsing from"),this.logBufferLevel(),!1)},ArrayBuffer.concat=function(o,c){t.debug("ArrayBuffer","Trying to create a new buffer of size: "+(o.byteLength+c.byteLength));var u=new Uint8Array(o.byteLength+c.byteLength);return u.set(new Uint8Array(o),0),u.set(new Uint8Array(c),o.byteLength),u.buffer},a.prototype.reduceBuffer=function(o,c,u){var p;return p=new Uint8Array(u),p.set(new Uint8Array(o,c,u)),p.buffer.fileStart=o.fileStart+c,p.buffer.usedBytes=0,p.buffer},a.prototype.insertBuffer=function(o){for(var c=!0,u=0;u<this.buffers.length;u++){var p=this.buffers[u];if(o.fileStart<=p.fileStart){if(o.fileStart===p.fileStart)if(o.byteLength>p.byteLength){this.buffers.splice(u,1),u--;continue}else t.warn("MultiBufferStream","Buffer (fileStart: "+o.fileStart+" - Length: "+o.byteLength+") already appended, ignoring");else o.fileStart+o.byteLength<=p.fileStart||(o=this.reduceBuffer(o,0,p.fileStart-o.fileStart)),t.debug("MultiBufferStream","Appending new buffer (fileStart: "+o.fileStart+" - Length: "+o.byteLength+")"),this.buffers.splice(u,0,o),u===0&&(this.buffer=o);c=!1;break}else if(o.fileStart<p.fileStart+p.byteLength){var _=p.fileStart+p.byteLength-o.fileStart,b=o.byteLength-_;if(b>0)o=this.reduceBuffer(o,_,b);else{c=!1;break}}}c&&(t.debug("MultiBufferStream","Appending new buffer (fileStart: "+o.fileStart+" - Length: "+o.byteLength+")"),this.buffers.push(o),u===0&&(this.buffer=o))},a.prototype.logBufferLevel=function(o){var c,u,p,_,b=[],v,w="";for(p=0,_=0,c=0;c<this.buffers.length;c++)u=this.buffers[c],c===0?(v={},b.push(v),v.start=u.fileStart,v.end=u.fileStart+u.byteLength,w+="["+v.start+"-"):v.end===u.fileStart?v.end=u.fileStart+u.byteLength:(v={},v.start=u.fileStart,w+=b[b.length-1].end-1+"], ["+v.start+"-",v.end=u.fileStart+u.byteLength,b.push(v)),p+=u.usedBytes,_+=u.byteLength;b.length>0&&(w+=v.end-1+"]");var S=o?t.info:t.debug;this.buffers.length===0?S("MultiBufferStream","No more buffer in memory"):S("MultiBufferStream",""+this.buffers.length+" stored buffer(s) ("+p+"/"+_+" bytes), continuous ranges: "+w)},a.prototype.cleanBuffers=function(){var o,c;for(o=0;o<this.buffers.length;o++)c=this.buffers[o],c.usedBytes===c.byteLength&&(t.debug("MultiBufferStream","Removing buffer #"+o),this.buffers.splice(o,1),o--)},a.prototype.mergeNextBuffer=function(){var o;if(this.bufferIndex+1<this.buffers.length)if(o=this.buffers[this.bufferIndex+1],o.fileStart===this.buffer.fileStart+this.buffer.byteLength){var c=this.buffer.byteLength,u=this.buffer.usedBytes,p=this.buffer.fileStart;return this.buffers[this.bufferIndex]=ArrayBuffer.concat(this.buffer,o),this.buffer=this.buffers[this.bufferIndex],this.buffers.splice(this.bufferIndex+1,1),this.buffer.usedBytes=u,this.buffer.fileStart=p,t.debug("ISOFile","Concatenating buffer for box parsing (length: "+c+"->"+this.buffer.byteLength+")"),!0}else return!1;else return!1},a.prototype.findPosition=function(o,c,u){var p,_=null,b=-1;for(o===!0?p=0:p=this.bufferIndex;p<this.buffers.length&&(_=this.buffers[p],_.fileStart<=c);){b=p,u&&(_.fileStart+_.byteLength<=c?_.usedBytes=_.byteLength:_.usedBytes=c-_.fileStart,this.logBufferLevel());p++}return b!==-1?(_=this.buffers[b],_.fileStart+_.byteLength>=c?(t.debug("MultiBufferStream","Found position in existing buffer #"+b),b):-1):-1},a.prototype.findEndContiguousBuf=function(o){var c,u,p,_=o!==void 0?o:this.bufferIndex;if(u=this.buffers[_],this.buffers.length>_+1)for(c=_+1;c<this.buffers.length&&(p=this.buffers[c],p.fileStart===u.fileStart+u.byteLength);c++)u=p;return u.fileStart+u.byteLength},a.prototype.getEndFilePositionAfter=function(o){var c=this.findPosition(!0,o,!1);return c!==-1?this.findEndContiguousBuf(c):o},a.prototype.addUsedBytes=function(o){this.buffer.usedBytes+=o,this.logBufferLevel()},a.prototype.setAllUsedBytes=function(){this.buffer.usedBytes=this.buffer.byteLength,this.logBufferLevel()},a.prototype.seek=function(o,c,u){var p;return p=this.findPosition(c,o,u),p!==-1?(this.buffer=this.buffers[p],this.bufferIndex=p,this.position=o-this.buffer.fileStart,t.debug("MultiBufferStream","Repositioning parser at buffer position: "+this.position),!0):(t.debug("MultiBufferStream","Position "+o+" not found in buffered data"),!1)},a.prototype.getPosition=function(){if(this.bufferIndex===-1||this.buffers[this.bufferIndex]===null)throw"Error accessing position in the MultiBufferStream";return this.buffers[this.bufferIndex].fileStart+this.position},a.prototype.getLength=function(){return this.byteLength},a.prototype.getEndPosition=function(){if(this.bufferIndex===-1||this.buffers[this.bufferIndex]===null)throw"Error accessing position in the MultiBufferStream";return this.buffers[this.bufferIndex].fileStart+this.byteLength},s.MultiBufferStream=a;var l=function(){var o=3,c=4,u=5,p=6,_=[];_[o]="ES_Descriptor",_[c]="DecoderConfigDescriptor",_[u]="DecoderSpecificInfo",_[p]="SLConfigDescriptor",this.getDescriptorName=function(w){return _[w]};var b=this,v={};return this.parseOneDescriptor=function(w){var S=0,T,E,P;for(T=w.readUint8(),P=w.readUint8();P&128;)S=(P&127)<<7,P=w.readUint8();return S+=P&127,t.debug("MPEG4DescriptorParser","Found "+(_[T]||"Descriptor "+T)+", size "+S+" at position "+w.getPosition()),_[T]?E=new v[_[T]](S):E=new v.Descriptor(S),E.parse(w),E},v.Descriptor=function(w,S){this.tag=w,this.size=S,this.descs=[]},v.Descriptor.prototype.parse=function(w){this.data=w.readUint8Array(this.size)},v.Descriptor.prototype.findDescriptor=function(w){for(var S=0;S<this.descs.length;S++)if(this.descs[S].tag==w)return this.descs[S];return null},v.Descriptor.prototype.parseRemainingDescriptors=function(w){for(var S=w.position;w.position<S+this.size;){var T=b.parseOneDescriptor(w);this.descs.push(T)}},v.ES_Descriptor=function(w){v.Descriptor.call(this,o,w)},v.ES_Descriptor.prototype=new v.Descriptor,v.ES_Descriptor.prototype.parse=function(w){if(this.ES_ID=w.readUint16(),this.flags=w.readUint8(),this.size-=3,this.flags&128?(this.dependsOn_ES_ID=w.readUint16(),this.size-=2):this.dependsOn_ES_ID=0,this.flags&64){var S=w.readUint8();this.URL=w.readString(S),this.size-=S+1}else this.URL="";this.flags&32?(this.OCR_ES_ID=w.readUint16(),this.size-=2):this.OCR_ES_ID=0,this.parseRemainingDescriptors(w)},v.ES_Descriptor.prototype.getOTI=function(w){var S=this.findDescriptor(c);return S?S.oti:0},v.ES_Descriptor.prototype.getAudioConfig=function(w){var S=this.findDescriptor(c);if(!S)return null;var T=S.findDescriptor(u);if(T&&T.data){var E=(T.data[0]&248)>>3;return E===31&&T.data.length>=2&&(E=32+((T.data[0]&7)<<3)+((T.data[1]&224)>>5)),E}else return null},v.DecoderConfigDescriptor=function(w){v.Descriptor.call(this,c,w)},v.DecoderConfigDescriptor.prototype=new v.Descriptor,v.DecoderConfigDescriptor.prototype.parse=function(w){this.oti=w.readUint8(),this.streamType=w.readUint8(),this.upStream=(this.streamType>>1&1)!==0,this.streamType=this.streamType>>>2,this.bufferSize=w.readUint24(),this.maxBitrate=w.readUint32(),this.avgBitrate=w.readUint32(),this.size-=13,this.parseRemainingDescriptors(w)},v.DecoderSpecificInfo=function(w){v.Descriptor.call(this,u,w)},v.DecoderSpecificInfo.prototype=new v.Descriptor,v.SLConfigDescriptor=function(w){v.Descriptor.call(this,p,w)},v.SLConfigDescriptor.prototype=new v.Descriptor,this};s.MPEG4DescriptorParser=l;var h={ERR_INVALID_DATA:-1,ERR_NOT_ENOUGH_DATA:0,OK:1,BASIC_BOXES:["mdat","idat","free","skip","meco","strk"],FULL_BOXES:["hmhd","nmhd","iods","xml ","bxml","ipro","mere"],CONTAINER_BOXES:[["moov",["trak","pssh"]],["trak"],["edts"],["mdia"],["minf"],["dinf"],["stbl",["sgpd","sbgp"]],["mvex",["trex"]],["moof",["traf"]],["traf",["trun","sgpd","sbgp"]],["vttc"],["tref"],["iref"],["mfra",["tfra"]],["meco"],["hnti"],["hinf"],["strk"],["strd"],["sinf"],["rinf"],["schi"],["trgr"],["udta",["kind"]],["iprp",["ipma"]],["ipco"],["grpl"],["j2kH"],["etyp",["tyco"]]],boxCodes:[],fullBoxCodes:[],containerBoxCodes:[],sampleEntryCodes:{},sampleGroupEntryCodes:[],trackGroupTypes:[],UUIDBoxes:{},UUIDs:[],initialize:function(){h.FullBox.prototype=new h.Box,h.ContainerBox.prototype=new h.Box,h.SampleEntry.prototype=new h.Box,h.TrackGroupTypeBox.prototype=new h.FullBox,h.BASIC_BOXES.forEach(function(o){h.createBoxCtor(o)}),h.FULL_BOXES.forEach(function(o){h.createFullBoxCtor(o)}),h.CONTAINER_BOXES.forEach(function(o){h.createContainerBoxCtor(o[0],null,o[1])})},Box:function(o,c,u){this.type=o,this.size=c,this.uuid=u},FullBox:function(o,c,u){h.Box.call(this,o,c,u),this.flags=0,this.version=0},ContainerBox:function(o,c,u){h.Box.call(this,o,c,u),this.boxes=[]},SampleEntry:function(o,c,u,p){h.ContainerBox.call(this,o,c),this.hdr_size=u,this.start=p},SampleGroupEntry:function(o){this.grouping_type=o},TrackGroupTypeBox:function(o,c){h.FullBox.call(this,o,c)},createBoxCtor:function(o,c){h.boxCodes.push(o),h[o+"Box"]=function(u){h.Box.call(this,o,u)},h[o+"Box"].prototype=new h.Box,c&&(h[o+"Box"].prototype.parse=c)},createFullBoxCtor:function(o,c){h[o+"Box"]=function(u){h.FullBox.call(this,o,u)},h[o+"Box"].prototype=new h.FullBox,h[o+"Box"].prototype.parse=function(u){this.parseFullHeader(u),c&&c.call(this,u)}},addSubBoxArrays:function(o){if(o){this.subBoxNames=o;for(var c=o.length,u=0;u<c;u++)this[o[u]+"s"]=[]}},createContainerBoxCtor:function(o,c,u){h[o+"Box"]=function(p){h.ContainerBox.call(this,o,p),h.addSubBoxArrays.call(this,u)},h[o+"Box"].prototype=new h.ContainerBox,c&&(h[o+"Box"].prototype.parse=c)},createMediaSampleEntryCtor:function(o,c,u){h.sampleEntryCodes[o]=[],h[o+"SampleEntry"]=function(p,_){h.SampleEntry.call(this,p,_),h.addSubBoxArrays.call(this,u)},h[o+"SampleEntry"].prototype=new h.SampleEntry,c&&(h[o+"SampleEntry"].prototype.parse=c)},createSampleEntryCtor:function(o,c,u,p){h.sampleEntryCodes[o].push(c),h[c+"SampleEntry"]=function(_){h[o+"SampleEntry"].call(this,c,_),h.addSubBoxArrays.call(this,p)},h[c+"SampleEntry"].prototype=new h[o+"SampleEntry"],u&&(h[c+"SampleEntry"].prototype.parse=u)},createEncryptedSampleEntryCtor:function(o,c,u){h.createSampleEntryCtor.call(this,o,c,u,["sinf"])},createSampleGroupCtor:function(o,c){h[o+"SampleGroupEntry"]=function(u){h.SampleGroupEntry.call(this,o,u)},h[o+"SampleGroupEntry"].prototype=new h.SampleGroupEntry,c&&(h[o+"SampleGroupEntry"].prototype.parse=c)},createTrackGroupCtor:function(o,c){h[o+"TrackGroupTypeBox"]=function(u){h.TrackGroupTypeBox.call(this,o,u)},h[o+"TrackGroupTypeBox"].prototype=new h.TrackGroupTypeBox,c&&(h[o+"TrackGroupTypeBox"].prototype.parse=c)},createUUIDBox:function(o,c,u,p){h.UUIDs.push(o),h.UUIDBoxes[o]=function(_){c?h.FullBox.call(this,"uuid",_,o):u?h.ContainerBox.call(this,"uuid",_,o):h.Box.call(this,"uuid",_,o)},h.UUIDBoxes[o].prototype=c?new h.FullBox:u?new h.ContainerBox:new h.Box,p&&(c?h.UUIDBoxes[o].prototype.parse=function(_){this.parseFullHeader(_),p&&p.call(this,_)}:h.UUIDBoxes[o].prototype.parse=p)}};h.initialize(),h.TKHD_FLAG_ENABLED=1,h.TKHD_FLAG_IN_MOVIE=2,h.TKHD_FLAG_IN_PREVIEW=4,h.TFHD_FLAG_BASE_DATA_OFFSET=1,h.TFHD_FLAG_SAMPLE_DESC=2,h.TFHD_FLAG_SAMPLE_DUR=8,h.TFHD_FLAG_SAMPLE_SIZE=16,h.TFHD_FLAG_SAMPLE_FLAGS=32,h.TFHD_FLAG_DUR_EMPTY=65536,h.TFHD_FLAG_DEFAULT_BASE_IS_MOOF=131072,h.TRUN_FLAGS_DATA_OFFSET=1,h.TRUN_FLAGS_FIRST_FLAG=4,h.TRUN_FLAGS_DURATION=256,h.TRUN_FLAGS_SIZE=512,h.TRUN_FLAGS_FLAGS=1024,h.TRUN_FLAGS_CTS_OFFSET=2048,h.Box.prototype.add=function(o){return this.addBox(new h[o+"Box"])},h.Box.prototype.addBox=function(o){return this.boxes.push(o),this[o.type+"s"]?this[o.type+"s"].push(o):this[o.type]=o,o},h.Box.prototype.set=function(o,c){return this[o]=c,this},h.Box.prototype.addEntry=function(o,c){var u=c||"entries";return this[u]||(this[u]=[]),this[u].push(o),this},s.BoxParser=h,h.parseUUID=function(o){return h.parseHex16(o)},h.parseHex16=function(o){for(var c="",u=0;u<16;u++){var p=o.readUint8().toString(16);c+=p.length===1?"0"+p:p}return c},h.parseOneBox=function(o,c,u){var p,_=o.getPosition(),b=0,v,w;if(o.getEndPosition()-_<8)return t.debug("BoxParser","Not enough data in stream to parse the type and size of the box"),{code:h.ERR_NOT_ENOUGH_DATA};if(u&&u<8)return t.debug("BoxParser","Not enough bytes left in the parent box to parse a new box"),{code:h.ERR_NOT_ENOUGH_DATA};var S=o.readUint32(),T=o.readString(4),E=T;if(t.debug("BoxParser","Found box of type '"+T+"' and size "+S+" at position "+_),b=8,T=="uuid"){if(o.getEndPosition()-o.getPosition()<16||u-b<16)return o.seek(_),t.debug("BoxParser","Not enough bytes left in the parent box to parse a UUID box"),{code:h.ERR_NOT_ENOUGH_DATA};w=h.parseUUID(o),b+=16,E=w}if(S==1){if(o.getEndPosition()-o.getPosition()<8||u&&u-b<8)return o.seek(_),t.warn("BoxParser",'Not enough data in stream to parse the extended size of the "'+T+'" box'),{code:h.ERR_NOT_ENOUGH_DATA};S=o.readUint64(),b+=8}else if(S===0){if(u)S=u;else if(T!=="mdat")return t.error("BoxParser","Unlimited box size not supported for type: '"+T+"'"),p=new h.Box(T,S),{code:h.OK,box:p,size:p.size}}return S!==0&&S<b?(t.error("BoxParser","Box of type "+T+" has an invalid size "+S+" (too small to be a box)"),{code:h.ERR_NOT_ENOUGH_DATA,type:T,size:S,hdr_size:b,start:_}):S!==0&&u&&S>u?(t.error("BoxParser","Box of type '"+T+"' has a size "+S+" greater than its container size "+u),{code:h.ERR_NOT_ENOUGH_DATA,type:T,size:S,hdr_size:b,start:_}):S!==0&&_+S>o.getEndPosition()?(o.seek(_),t.info("BoxParser","Not enough data in stream to parse the entire '"+T+"' box"),{code:h.ERR_NOT_ENOUGH_DATA,type:T,size:S,hdr_size:b,start:_}):c?{code:h.OK,type:T,size:S,hdr_size:b,start:_}:(h[T+"Box"]?p=new h[T+"Box"](S):T!=="uuid"?(t.warn("BoxParser","Unknown box type: '"+T+"'"),p=new h.Box(T,S),p.has_unparsed_data=!0):h.UUIDBoxes[w]?p=new h.UUIDBoxes[w](S):(t.warn("BoxParser","Unknown uuid type: '"+w+"'"),p=new h.Box(T,S),p.uuid=w,p.has_unparsed_data=!0),p.hdr_size=b,p.start=_,p.write===h.Box.prototype.write&&p.type!=="mdat"&&(t.info("BoxParser","'"+E+"' box writing not yet implemented, keeping unparsed data in memory for later write"),p.parseDataAndRewind(o)),p.parse(o),v=o.getPosition()-(p.start+p.size),v<0?(t.warn("BoxParser","Parsing of box '"+E+"' did not read the entire indicated box data size (missing "+-v+" bytes), seeking forward"),o.seek(p.start+p.size)):v>0&&(t.error("BoxParser","Parsing of box '"+E+"' read "+v+" more bytes than the indicated box data size, seeking backwards"),p.size!==0&&o.seek(p.start+p.size)),{code:h.OK,box:p,size:p.size})},h.Box.prototype.parse=function(o){this.type!="mdat"?this.data=o.readUint8Array(this.size-this.hdr_size):this.size===0?o.seek(o.getEndPosition()):o.seek(this.start+this.size)},h.Box.prototype.parseDataAndRewind=function(o){this.data=o.readUint8Array(this.size-this.hdr_size),o.position-=this.size-this.hdr_size},h.FullBox.prototype.parseDataAndRewind=function(o){this.parseFullHeader(o),this.data=o.readUint8Array(this.size-this.hdr_size),this.hdr_size-=4,o.position-=this.size-this.hdr_size},h.FullBox.prototype.parseFullHeader=function(o){this.version=o.readUint8(),this.flags=o.readUint24(),this.hdr_size+=4},h.FullBox.prototype.parse=function(o){this.parseFullHeader(o),this.data=o.readUint8Array(this.size-this.hdr_size)},h.ContainerBox.prototype.parse=function(o){for(var c,u;o.getPosition()<this.start+this.size;)if(c=h.parseOneBox(o,!1,this.size-(o.getPosition()-this.start)),c.code===h.OK)if(u=c.box,this.boxes.push(u),this.subBoxNames&&this.subBoxNames.indexOf(u.type)!=-1)this[this.subBoxNames[this.subBoxNames.indexOf(u.type)]+"s"].push(u);else{var p=u.type!=="uuid"?u.type:u.uuid;this[p]?t.warn("Box of type "+p+" already stored in field of this type"):this[p]=u}else return},h.Box.prototype.parseLanguage=function(o){this.language=o.readUint16();var c=[];c[0]=this.language>>10&31,c[1]=this.language>>5&31,c[2]=this.language&31,this.languageString=String.fromCharCode(c[0]+96,c[1]+96,c[2]+96)},h.SAMPLE_ENTRY_TYPE_VISUAL="Visual",h.SAMPLE_ENTRY_TYPE_AUDIO="Audio",h.SAMPLE_ENTRY_TYPE_HINT="Hint",h.SAMPLE_ENTRY_TYPE_METADATA="Metadata",h.SAMPLE_ENTRY_TYPE_SUBTITLE="Subtitle",h.SAMPLE_ENTRY_TYPE_SYSTEM="System",h.SAMPLE_ENTRY_TYPE_TEXT="Text",h.SampleEntry.prototype.parseHeader=function(o){o.readUint8Array(6),this.data_reference_index=o.readUint16(),this.hdr_size+=8},h.SampleEntry.prototype.parse=function(o){this.parseHeader(o),this.data=o.readUint8Array(this.size-this.hdr_size)},h.SampleEntry.prototype.parseDataAndRewind=function(o){this.parseHeader(o),this.data=o.readUint8Array(this.size-this.hdr_size),this.hdr_size-=8,o.position-=this.size-this.hdr_size},h.SampleEntry.prototype.parseFooter=function(o){h.ContainerBox.prototype.parse.call(this,o)},h.createMediaSampleEntryCtor(h.SAMPLE_ENTRY_TYPE_HINT),h.createMediaSampleEntryCtor(h.SAMPLE_ENTRY_TYPE_METADATA),h.createMediaSampleEntryCtor(h.SAMPLE_ENTRY_TYPE_SUBTITLE),h.createMediaSampleEntryCtor(h.SAMPLE_ENTRY_TYPE_SYSTEM),h.createMediaSampleEntryCtor(h.SAMPLE_ENTRY_TYPE_TEXT),h.createMediaSampleEntryCtor(h.SAMPLE_ENTRY_TYPE_VISUAL,function(o){var c;this.parseHeader(o),o.readUint16(),o.readUint16(),o.readUint32Array(3),this.width=o.readUint16(),this.height=o.readUint16(),this.horizresolution=o.readUint32(),this.vertresolution=o.readUint32(),o.readUint32(),this.frame_count=o.readUint16(),c=Math.min(31,o.readUint8()),this.compressorname=o.readString(c),c<31&&o.readString(31-c),this.depth=o.readUint16(),o.readUint16(),this.parseFooter(o)}),h.createMediaSampleEntryCtor(h.SAMPLE_ENTRY_TYPE_AUDIO,function(o){this.parseHeader(o),o.readUint32Array(2),this.channel_count=o.readUint16(),this.samplesize=o.readUint16(),o.readUint16(),o.readUint16(),this.samplerate=o.readUint32()/65536,this.parseFooter(o)}),h.createSampleEntryCtor(h.SAMPLE_ENTRY_TYPE_VISUAL,"avc1"),h.createSampleEntryCtor(h.SAMPLE_ENTRY_TYPE_VISUAL,"avc2"),h.createSampleEntryCtor(h.SAMPLE_ENTRY_TYPE_VISUAL,"avc3"),h.createSampleEntryCtor(h.SAMPLE_ENTRY_TYPE_VISUAL,"avc4"),h.createSampleEntryCtor(h.SAMPLE_ENTRY_TYPE_VISUAL,"av01"),h.createSampleEntryCtor(h.SAMPLE_ENTRY_TYPE_VISUAL,"dav1"),h.createSampleEntryCtor(h.SAMPLE_ENTRY_TYPE_VISUAL,"hvc1"),h.createSampleEntryCtor(h.SAMPLE_ENTRY_TYPE_VISUAL,"hev1"),h.createSampleEntryCtor(h.SAMPLE_ENTRY_TYPE_VISUAL,"hvt1"),h.createSampleEntryCtor(h.SAMPLE_ENTRY_TYPE_VISUAL,"lhe1"),h.createSampleEntryCtor(h.SAMPLE_ENTRY_TYPE_VISUAL,"dvh1"),h.createSampleEntryCtor(h.SAMPLE_ENTRY_TYPE_VISUAL,"dvhe"),h.createSampleEntryCtor(h.SAMPLE_ENTRY_TYPE_VISUAL,"vvc1"),h.createSampleEntryCtor(h.SAMPLE_ENTRY_TYPE_VISUAL,"vvi1"),h.createSampleEntryCtor(h.SAMPLE_ENTRY_TYPE_VISUAL,"vvs1"),h.createSampleEntryCtor(h.SAMPLE_ENTRY_TYPE_VISUAL,"vvcN"),h.createSampleEntryCtor(h.SAMPLE_ENTRY_TYPE_VISUAL,"vp08"),h.createSampleEntryCtor(h.SAMPLE_ENTRY_TYPE_VISUAL,"vp09"),h.createSampleEntryCtor(h.SAMPLE_ENTRY_TYPE_VISUAL,"avs3"),h.createSampleEntryCtor(h.SAMPLE_ENTRY_TYPE_VISUAL,"j2ki"),h.createSampleEntryCtor(h.SAMPLE_ENTRY_TYPE_VISUAL,"mjp2"),h.createSampleEntryCtor(h.SAMPLE_ENTRY_TYPE_VISUAL,"mjpg"),h.createSampleEntryCtor(h.SAMPLE_ENTRY_TYPE_VISUAL,"uncv"),h.createSampleEntryCtor(h.SAMPLE_ENTRY_TYPE_AUDIO,"mp4a"),h.createSampleEntryCtor(h.SAMPLE_ENTRY_TYPE_AUDIO,"ac-3"),h.createSampleEntryCtor(h.SAMPLE_ENTRY_TYPE_AUDIO,"ac-4"),h.createSampleEntryCtor(h.SAMPLE_ENTRY_TYPE_AUDIO,"ec-3"),h.createSampleEntryCtor(h.SAMPLE_ENTRY_TYPE_AUDIO,"Opus"),h.createSampleEntryCtor(h.SAMPLE_ENTRY_TYPE_AUDIO,"mha1"),h.createSampleEntryCtor(h.SAMPLE_ENTRY_TYPE_AUDIO,"mha2"),h.createSampleEntryCtor(h.SAMPLE_ENTRY_TYPE_AUDIO,"mhm1"),h.createSampleEntryCtor(h.SAMPLE_ENTRY_TYPE_AUDIO,"mhm2"),h.createSampleEntryCtor(h.SAMPLE_ENTRY_TYPE_AUDIO,"fLaC"),h.createEncryptedSampleEntryCtor(h.SAMPLE_ENTRY_TYPE_VISUAL,"encv"),h.createEncryptedSampleEntryCtor(h.SAMPLE_ENTRY_TYPE_AUDIO,"enca"),h.createEncryptedSampleEntryCtor(h.SAMPLE_ENTRY_TYPE_SUBTITLE,"encu"),h.createEncryptedSampleEntryCtor(h.SAMPLE_ENTRY_TYPE_SYSTEM,"encs"),h.createEncryptedSampleEntryCtor(h.SAMPLE_ENTRY_TYPE_TEXT,"enct"),h.createEncryptedSampleEntryCtor(h.SAMPLE_ENTRY_TYPE_METADATA,"encm"),h.createBoxCtor("a1lx",function(o){var c=o.readUint8()&1,u=((c&1)+1)*16;this.layer_size=[];for(var p=0;p<3;p++)u==16?this.layer_size[p]=o.readUint16():this.layer_size[p]=o.readUint32()}),h.createBoxCtor("a1op",function(o){this.op_index=o.readUint8()}),h.createFullBoxCtor("auxC",function(o){this.aux_type=o.readCString();var c=this.size-this.hdr_size-(this.aux_type.length+1);this.aux_subtype=o.readUint8Array(c)}),h.createBoxCtor("av1C",function(o){var c=o.readUint8();if(c>>7&!1){t.error("av1C marker problem");return}if(this.version=c&127,this.version!==1){t.error("av1C version "+this.version+" not supported");return}if(c=o.readUint8(),this.seq_profile=c>>5&7,this.seq_level_idx_0=c&31,c=o.readUint8(),this.seq_tier_0=c>>7&1,this.high_bitdepth=c>>6&1,this.twelve_bit=c>>5&1,this.monochrome=c>>4&1,this.chroma_subsampling_x=c>>3&1,this.chroma_subsampling_y=c>>2&1,this.chroma_sample_position=c&3,c=o.readUint8(),this.reserved_1=c>>5&7,this.reserved_1!==0){t.error("av1C reserved_1 parsing problem");return}if(this.initial_presentation_delay_present=c>>4&1,this.initial_presentation_delay_present===1)this.initial_presentation_delay_minus_one=c&15;else if(this.reserved_2=c&15,this.reserved_2!==0){t.error("av1C reserved_2 parsing problem");return}var u=this.size-this.hdr_size-4;this.configOBUs=o.readUint8Array(u)}),h.createBoxCtor("avcC",function(o){var c,u;for(this.configurationVersion=o.readUint8(),this.AVCProfileIndication=o.readUint8(),this.profile_compatibility=o.readUint8(),this.AVCLevelIndication=o.readUint8(),this.lengthSizeMinusOne=o.readUint8()&3,this.nb_SPS_nalus=o.readUint8()&31,u=this.size-this.hdr_size-6,this.SPS=[],c=0;c<this.nb_SPS_nalus;c++)this.SPS[c]={},this.SPS[c].length=o.readUint16(),this.SPS[c].nalu=o.readUint8Array(this.SPS[c].length),u-=2+this.SPS[c].length;for(this.nb_PPS_nalus=o.readUint8(),u--,this.PPS=[],c=0;c<this.nb_PPS_nalus;c++)this.PPS[c]={},this.PPS[c].length=o.readUint16(),this.PPS[c].nalu=o.readUint8Array(this.PPS[c].length),u-=2+this.PPS[c].length;u>0&&(this.ext=o.readUint8Array(u))}),h.createBoxCtor("btrt",function(o){this.bufferSizeDB=o.readUint32(),this.maxBitrate=o.readUint32(),this.avgBitrate=o.readUint32()}),h.createFullBoxCtor("ccst",function(o){var c=o.readUint8();this.all_ref_pics_intra=(c&128)==128,this.intra_pred_used=(c&64)==64,this.max_ref_per_pic=(c&63)>>2,o.readUint24()}),h.createBoxCtor("cdef",function(o){var c;for(this.channel_count=o.readUint16(),this.channel_indexes=[],this.channel_types=[],this.channel_associations=[],c=0;c<this.channel_count;c++)this.channel_indexes.push(o.readUint16()),this.channel_types.push(o.readUint16()),this.channel_associations.push(o.readUint16())}),h.createBoxCtor("clap",function(o){this.cleanApertureWidthN=o.readUint32(),this.cleanApertureWidthD=o.readUint32(),this.cleanApertureHeightN=o.readUint32(),this.cleanApertureHeightD=o.readUint32(),this.horizOffN=o.readUint32(),this.horizOffD=o.readUint32(),this.vertOffN=o.readUint32(),this.vertOffD=o.readUint32()}),h.createBoxCtor("clli",function(o){this.max_content_light_level=o.readUint16(),this.max_pic_average_light_level=o.readUint16()}),h.createFullBoxCtor("cmex",function(o){this.flags&1&&(this.pos_x=o.readInt32()),this.flags&2&&(this.pos_y=o.readInt32()),this.flags&4&&(this.pos_z=o.readInt32()),this.flags&8&&(this.version==0?this.flags&16?(this.quat_x=o.readInt32(),this.quat_y=o.readInt32(),this.quat_z=o.readInt32()):(this.quat_x=o.readInt16(),this.quat_y=o.readInt16(),this.quat_z=o.readInt16()):this.version==1),this.flags&32&&(this.id=o.readUint32())}),h.createFullBoxCtor("cmin",function(o){this.focal_length_x=o.readInt32(),this.principal_point_x=o.readInt32(),this.principal_point_y=o.readInt32(),this.flags&1&&(this.focal_length_y=o.readInt32(),this.skew_factor=o.readInt32())}),h.createBoxCtor("cmpd",function(o){for(this.component_count=o.readUint32(),this.component_types=[],this.component_type_urls=[],i=0;i<this.component_count;i++){var c=o.readUint16();this.component_types.push(c),c>=32768&&this.component_type_urls.push(o.readCString())}}),h.createFullBoxCtor("co64",function(o){var c,u;if(c=o.readUint32(),this.chunk_offsets=[],this.version===0)for(u=0;u<c;u++)this.chunk_offsets.push(o.readUint64())}),h.createFullBoxCtor("CoLL",function(o){this.maxCLL=o.readUint16(),this.maxFALL=o.readUint16()}),h.createBoxCtor("colr",function(o){if(this.colour_type=o.readString(4),this.colour_type==="nclx"){this.colour_primaries=o.readUint16(),this.transfer_characteristics=o.readUint16(),this.matrix_coefficients=o.readUint16();var c=o.readUint8();this.full_range_flag=c>>7}else this.colour_type==="rICC"?this.ICC_profile=o.readUint8Array(this.size-4):this.colour_type==="prof"&&(this.ICC_profile=o.readUint8Array(this.size-4))}),h.createFullBoxCtor("cprt",function(o){this.parseLanguage(o),this.notice=o.readCString()}),h.createFullBoxCtor("cslg",function(o){this.version===0&&(this.compositionToDTSShift=o.readInt32(),this.leastDecodeToDisplayDelta=o.readInt32(),this.greatestDecodeToDisplayDelta=o.readInt32(),this.compositionStartTime=o.readInt32(),this.compositionEndTime=o.readInt32())}),h.createFullBoxCtor("ctts",function(o){var c,u;if(c=o.readUint32(),this.sample_counts=[],this.sample_offsets=[],this.version===0)for(u=0;u<c;u++){this.sample_counts.push(o.readUint32());var p=o.readInt32();p<0&&t.warn("BoxParser","ctts box uses negative values without using version 1"),this.sample_offsets.push(p)}else if(this.version==1)for(u=0;u<c;u++)this.sample_counts.push(o.readUint32()),this.sample_offsets.push(o.readInt32())}),h.createBoxCtor("dac3",function(o){var c=o.readUint8(),u=o.readUint8(),p=o.readUint8();this.fscod=c>>6,this.bsid=c>>1&31,this.bsmod=(c&1)<<2|u>>6&3,this.acmod=u>>3&7,this.lfeon=u>>2&1,this.bit_rate_code=u&3|p>>5&7}),h.createBoxCtor("dec3",function(o){var c=o.readUint16();this.data_rate=c>>3,this.num_ind_sub=c&7,this.ind_subs=[];for(var u=0;u<this.num_ind_sub+1;u++){var p={};this.ind_subs.push(p);var _=o.readUint8(),b=o.readUint8(),v=o.readUint8();p.fscod=_>>6,p.bsid=_>>1&31,p.bsmod=(_&1)<<4|b>>4&15,p.acmod=b>>1&7,p.lfeon=b&1,p.num_dep_sub=v>>1&15,p.num_dep_sub>0&&(p.chan_loc=(v&1)<<8|o.readUint8())}}),h.createFullBoxCtor("dfLa",function(o){var c=127,u=128,p=[],_=["STREAMINFO","PADDING","APPLICATION","SEEKTABLE","VORBIS_COMMENT","CUESHEET","PICTURE","RESERVED"];do{var b=o.readUint8(),v=Math.min(b&c,_.length-1);if(v?o.readUint8Array(o.readUint24()):(o.readUint8Array(13),this.samplerate=o.readUint32()>>12,o.readUint8Array(20)),p.push(_[v]),b&u)break}while(!0);this.numMetadataBlocks=p.length+" ("+p.join(", ")+")"}),h.createBoxCtor("dimm",function(o){this.bytessent=o.readUint64()}),h.createBoxCtor("dmax",function(o){this.time=o.readUint32()}),h.createBoxCtor("dmed",function(o){this.bytessent=o.readUint64()}),h.createBoxCtor("dOps",function(o){if(this.Version=o.readUint8(),this.OutputChannelCount=o.readUint8(),this.PreSkip=o.readUint16(),this.InputSampleRate=o.readUint32(),this.OutputGain=o.readInt16(),this.ChannelMappingFamily=o.readUint8(),this.ChannelMappingFamily!==0){this.StreamCount=o.readUint8(),this.CoupledCount=o.readUint8(),this.ChannelMapping=[];for(var c=0;c<this.OutputChannelCount;c++)this.ChannelMapping[c]=o.readUint8()}}),h.createFullBoxCtor("dref",function(o){var c,u;this.entries=[];for(var p=o.readUint32(),_=0;_<p;_++)if(c=h.parseOneBox(o,!1,this.size-(o.getPosition()-this.start)),c.code===h.OK)u=c.box,this.entries.push(u);else return}),h.createBoxCtor("drep",function(o){this.bytessent=o.readUint64()}),h.createFullBoxCtor("elng",function(o){this.extended_language=o.readString(this.size-this.hdr_size)}),h.createFullBoxCtor("elst",function(o){this.entries=[];for(var c=o.readUint32(),u=0;u<c;u++){var p={};this.entries.push(p),this.version===1?(p.segment_duration=o.readUint64(),p.media_time=o.readInt64()):(p.segment_duration=o.readUint32(),p.media_time=o.readInt32()),p.media_rate_integer=o.readInt16(),p.media_rate_fraction=o.readInt16()}}),h.createFullBoxCtor("emsg",function(o){this.version==1?(this.timescale=o.readUint32(),this.presentation_time=o.readUint64(),this.event_duration=o.readUint32(),this.id=o.readUint32(),this.scheme_id_uri=o.readCString(),this.value=o.readCString()):(this.scheme_id_uri=o.readCString(),this.value=o.readCString(),this.timescale=o.readUint32(),this.presentation_time_delta=o.readUint32(),this.event_duration=o.readUint32(),this.id=o.readUint32());var c=this.size-this.hdr_size-(16+(this.scheme_id_uri.length+1)+(this.value.length+1));this.version==1&&(c-=4),this.message_data=o.readUint8Array(c)}),h.createEntityToGroupCtor=function(o,c){h[o+"Box"]=function(u){h.FullBox.call(this,o,u)},h[o+"Box"].prototype=new h.FullBox,h[o+"Box"].prototype.parse=function(u){if(this.parseFullHeader(u),c)c.call(this,u);else for(this.group_id=u.readUint32(),this.num_entities_in_group=u.readUint32(),this.entity_ids=[],i=0;i<this.num_entities_in_group;i++){var p=u.readUint32();this.entity_ids.push(p)}}},h.createEntityToGroupCtor("aebr"),h.createEntityToGroupCtor("afbr"),h.createEntityToGroupCtor("albc"),h.createEntityToGroupCtor("altr"),h.createEntityToGroupCtor("brst"),h.createEntityToGroupCtor("dobr"),h.createEntityToGroupCtor("eqiv"),h.createEntityToGroupCtor("favc"),h.createEntityToGroupCtor("fobr"),h.createEntityToGroupCtor("iaug"),h.createEntityToGroupCtor("pano"),h.createEntityToGroupCtor("slid"),h.createEntityToGroupCtor("ster"),h.createEntityToGroupCtor("tsyn"),h.createEntityToGroupCtor("wbbr"),h.createEntityToGroupCtor("prgr"),h.createEntityToGroupCtor("pymd",function(o){this.group_id=o.readUint32(),this.num_entities_in_group=o.readUint32(),this.entity_ids=[];for(var c=0;c<this.num_entities_in_group;c++){var u=o.readUint32();this.entity_ids.push(u)}for(this.tile_size_x=o.readUint16(),this.tile_size_y=o.readUint16(),this.layer_binning=[],this.tiles_in_layer_column_minus1=[],this.tiles_in_layer_row_minus1=[],c=0;c<this.num_entities_in_group;c++)this.layer_binning[c]=o.readUint16(),this.tiles_in_layer_row_minus1[c]=o.readUint16(),this.tiles_in_layer_column_minus1[c]=o.readUint16()}),h.createFullBoxCtor("esds",function(o){var c=o.readUint8Array(this.size-this.hdr_size);if(this.data=c,typeof l<"u"){var u=new l;this.esd=u.parseOneDescriptor(new r(c.buffer,0,r.BIG_ENDIAN))}}),h.createBoxCtor("fiel",function(o){this.fieldCount=o.readUint8(),this.fieldOrdering=o.readUint8()}),h.createBoxCtor("frma",function(o){this.data_format=o.readString(4)}),h.createBoxCtor("ftyp",function(o){var c=this.size-this.hdr_size;this.major_brand=o.readString(4),this.minor_version=o.readUint32(),c-=8,this.compatible_brands=[];for(var u=0;c>=4;)this.compatible_brands[u]=o.readString(4),c-=4,u++}),h.createFullBoxCtor("hdlr",function(o){this.version===0&&(o.readUint32(),this.handler=o.readString(4),o.readUint32Array(3),this.name=o.readString(this.size-this.hdr_size-20),this.name[this.name.length-1]==="\0"&&(this.name=this.name.slice(0,-1)))}),h.createBoxCtor("hvcC",function(o){var c,u,p,_;this.configurationVersion=o.readUint8(),_=o.readUint8(),this.general_profile_space=_>>6,this.general_tier_flag=(_&32)>>5,this.general_profile_idc=_&31,this.general_profile_compatibility=o.readUint32(),this.general_constraint_indicator=o.readUint8Array(6),this.general_level_idc=o.readUint8(),this.min_spatial_segmentation_idc=o.readUint16()&4095,this.parallelismType=o.readUint8()&3,this.chroma_format_idc=o.readUint8()&3,this.bit_depth_luma_minus8=o.readUint8()&7,this.bit_depth_chroma_minus8=o.readUint8()&7,this.avgFrameRate=o.readUint16(),_=o.readUint8(),this.constantFrameRate=_>>6,this.numTemporalLayers=(_&13)>>3,this.temporalIdNested=(_&4)>>2,this.lengthSizeMinusOne=_&3,this.nalu_arrays=[];var b=o.readUint8();for(c=0;c<b;c++){var v=[];this.nalu_arrays.push(v),_=o.readUint8(),v.completeness=(_&128)>>7,v.nalu_type=_&63;var w=o.readUint16();for(u=0;u<w;u++){var S={};v.push(S),p=o.readUint16(),S.data=o.readUint8Array(p)}}}),h.createFullBoxCtor("iinf",function(o){var c;this.version===0?this.entry_count=o.readUint16():this.entry_count=o.readUint32(),this.item_infos=[];for(var u=0;u<this.entry_count;u++)if(c=h.parseOneBox(o,!1,this.size-(o.getPosition()-this.start)),c.code===h.OK)c.box.type!=="infe"&&t.error("BoxParser","Expected 'infe' box, got "+c.box.type),this.item_infos[u]=c.box;else return}),h.createFullBoxCtor("iloc",function(o){var c;c=o.readUint8(),this.offset_size=c>>4&15,this.length_size=c&15,c=o.readUint8(),this.base_offset_size=c>>4&15,this.version===1||this.version===2?this.index_size=c&15:this.index_size=0,this.items=[];var u=0;if(this.version<2)u=o.readUint16();else if(this.version===2)u=o.readUint32();else throw"version of iloc box not supported";for(var p=0;p<u;p++){var _={};if(this.items.push(_),this.version<2)_.item_ID=o.readUint16();else if(this.version===2)_.item_ID=o.readUint32();else throw"version of iloc box not supported";switch(this.version===1||this.version===2?_.construction_method=o.readUint16()&15:_.construction_method=0,_.data_reference_index=o.readUint16(),this.base_offset_size){case 0:_.base_offset=0;break;case 4:_.base_offset=o.readUint32();break;case 8:_.base_offset=o.readUint64();break;default:throw"Error reading base offset size"}var b=o.readUint16();_.extents=[];for(var v=0;v<b;v++){var w={};if(_.extents.push(w),this.version===1||this.version===2)switch(this.index_size){case 0:w.extent_index=0;break;case 4:w.extent_index=o.readUint32();break;case 8:w.extent_index=o.readUint64();break;default:throw"Error reading extent index"}switch(this.offset_size){case 0:w.extent_offset=0;break;case 4:w.extent_offset=o.readUint32();break;case 8:w.extent_offset=o.readUint64();break;default:throw"Error reading extent index"}switch(this.length_size){case 0:w.extent_length=0;break;case 4:w.extent_length=o.readUint32();break;case 8:w.extent_length=o.readUint64();break;default:throw"Error reading extent index"}}}}),h.createBoxCtor("imir",function(o){var c=o.readUint8();this.reserved=c>>7,this.axis=c&1}),h.createFullBoxCtor("infe",function(o){if((this.version===0||this.version===1)&&(this.item_ID=o.readUint16(),this.item_protection_index=o.readUint16(),this.item_name=o.readCString(),this.content_type=o.readCString(),this.content_encoding=o.readCString()),this.version===1){this.extension_type=o.readString(4),t.warn("BoxParser","Cannot parse extension type"),o.seek(this.start+this.size);return}this.version>=2&&(this.version===2?this.item_ID=o.readUint16():this.version===3&&(this.item_ID=o.readUint32()),this.item_protection_index=o.readUint16(),this.item_type=o.readString(4),this.item_name=o.readCString(),this.item_type==="mime"?(this.content_type=o.readCString(),this.content_encoding=o.readCString()):this.item_type==="uri "&&(this.item_uri_type=o.readCString()))}),h.createFullBoxCtor("ipma",function(o){var c,u;for(entry_count=o.readUint32(),this.associations=[],c=0;c<entry_count;c++){var p={};this.associations.push(p),this.version<1?p.id=o.readUint16():p.id=o.readUint32();var _=o.readUint8();for(p.props=[],u=0;u<_;u++){var b=o.readUint8(),v={};p.props.push(v),v.essential=(b&128)>>7===1,this.flags&1?v.property_index=(b&127)<<8|o.readUint8():v.property_index=b&127}}}),h.createFullBoxCtor("iref",function(o){var c,u;for(this.references=[];o.getPosition()<this.start+this.size;)if(c=h.parseOneBox(o,!0,this.size-(o.getPosition()-this.start)),c.code===h.OK)this.version===0?u=new h.SingleItemTypeReferenceBox(c.type,c.size,c.hdr_size,c.start):u=new h.SingleItemTypeReferenceBoxLarge(c.type,c.size,c.hdr_size,c.start),u.write===h.Box.prototype.write&&u.type!=="mdat"&&(t.warn("BoxParser",u.type+" box writing not yet implemented, keeping unparsed data in memory for later write"),u.parseDataAndRewind(o)),u.parse(o),this.references.push(u);else return}),h.createBoxCtor("irot",function(o){this.angle=o.readUint8()&3}),h.createFullBoxCtor("ispe",function(o){this.image_width=o.readUint32(),this.image_height=o.readUint32()}),h.createFullBoxCtor("kind",function(o){this.schemeURI=o.readCString(),this.value=o.readCString()}),h.createFullBoxCtor("leva",function(o){var c=o.readUint8();this.levels=[];for(var u=0;u<c;u++){var p={};this.levels[u]=p,p.track_ID=o.readUint32();var _=o.readUint8();switch(p.padding_flag=_>>7,p.assignment_type=_&127,p.assignment_type){case 0:p.grouping_type=o.readString(4);break;case 1:p.grouping_type=o.readString(4),p.grouping_type_parameter=o.readUint32();break;case 2:break;case 3:break;case 4:p.sub_track_id=o.readUint32();break;default:t.warn("BoxParser","Unknown leva assignement type")}}}),h.createBoxCtor("lhvC",function(o){var c,u,p;this.configurationVersion=o.readUint8(),this.min_spatial_segmentation_idc=o.readUint16()&4095,this.parallelismType=o.readUint8()&3,p=o.readUint8(),this.numTemporalLayers=(p&13)>>3,this.temporalIdNested=(p&4)>>2,this.lengthSizeMinusOne=p&3,this.nalu_arrays=[];var _=o.readUint8();for(c=0;c<_;c++){var b=[];this.nalu_arrays.push(b),p=o.readUint8(),b.completeness=(p&128)>>7,b.nalu_type=p&63;var v=o.readUint16();for(u=0;u<v;u++){var w={};b.push(w);var S=o.readUint16();w.data=o.readUint8Array(S)}}}),h.createBoxCtor("lsel",function(o){this.layer_id=o.readUint16()}),h.createBoxCtor("maxr",function(o){this.period=o.readUint32(),this.bytes=o.readUint32()});function d(o,c){this.x=o,this.y=c}d.prototype.toString=function(){return"("+this.x+","+this.y+")"},h.createBoxCtor("mdcv",function(o){this.display_primaries=[],this.display_primaries[0]=new d(o.readUint16(),o.readUint16()),this.display_primaries[1]=new d(o.readUint16(),o.readUint16()),this.display_primaries[2]=new d(o.readUint16(),o.readUint16()),this.white_point=new d(o.readUint16(),o.readUint16()),this.max_display_mastering_luminance=o.readUint32(),this.min_display_mastering_luminance=o.readUint32()}),h.createFullBoxCtor("mdhd",function(o){this.version==1?(this.creation_time=o.readUint64(),this.modification_time=o.readUint64(),this.timescale=o.readUint32(),this.duration=o.readUint64()):(this.creation_time=o.readUint32(),this.modification_time=o.readUint32(),this.timescale=o.readUint32(),this.duration=o.readUint32()),this.parseLanguage(o),o.readUint16()}),h.createFullBoxCtor("mehd",function(o){this.flags&1&&(t.warn("BoxParser","mehd box incorrectly uses flags set to 1, converting version to 1"),this.version=1),this.version==1?this.fragment_duration=o.readUint64():this.fragment_duration=o.readUint32()}),h.createFullBoxCtor("meta",function(o){this.boxes=[],h.ContainerBox.prototype.parse.call(this,o)}),h.createFullBoxCtor("mfhd",function(o){this.sequence_number=o.readUint32()}),h.createFullBoxCtor("mfro",function(o){this._size=o.readUint32()}),h.createFullBoxCtor("mskC",function(o){this.bits_per_pixel=o.readUint8()}),h.createFullBoxCtor("mvhd",function(o){this.version==1?(this.creation_time=o.readUint64(),this.modification_time=o.readUint64(),this.timescale=o.readUint32(),this.duration=o.readUint64()):(this.creation_time=o.readUint32(),this.modification_time=o.readUint32(),this.timescale=o.readUint32(),this.duration=o.readUint32()),this.rate=o.readUint32(),this.volume=o.readUint16()>>8,o.readUint16(),o.readUint32Array(2),this.matrix=o.readUint32Array(9),o.readUint32Array(6),this.next_track_id=o.readUint32()}),h.createBoxCtor("npck",function(o){this.packetssent=o.readUint32()}),h.createBoxCtor("nump",function(o){this.packetssent=o.readUint64()}),h.createFullBoxCtor("padb",function(o){var c=o.readUint32();this.padbits=[];for(var u=0;u<Math.floor((c+1)/2);u++)this.padbits=o.readUint8()}),h.createBoxCtor("pasp",function(o){this.hSpacing=o.readUint32(),this.vSpacing=o.readUint32()}),h.createBoxCtor("payl",function(o){this.text=o.readString(this.size-this.hdr_size)}),h.createBoxCtor("payt",function(o){this.payloadID=o.readUint32();var c=o.readUint8();this.rtpmap_string=o.readString(c)}),h.createFullBoxCtor("pdin",function(o){var c=(this.size-this.hdr_size)/8;this.rate=[],this.initial_delay=[];for(var u=0;u<c;u++)this.rate[u]=o.readUint32(),this.initial_delay[u]=o.readUint32()}),h.createFullBoxCtor("pitm",function(o){this.version===0?this.item_id=o.readUint16():this.item_id=o.readUint32()}),h.createFullBoxCtor("pixi",function(o){var c;for(this.num_channels=o.readUint8(),this.bits_per_channels=[],c=0;c<this.num_channels;c++)this.bits_per_channels[c]=o.readUint8()}),h.createBoxCtor("pmax",function(o){this.bytes=o.readUint32()}),h.createFullBoxCtor("prdi",function(o){if(this.step_count=o.readUint16(),this.item_count=[],this.flags&2)for(var c=0;c<this.step_count;c++)this.item_count[c]=o.readUint16()}),h.createFullBoxCtor("prft",function(o){this.ref_track_id=o.readUint32(),this.ntp_timestamp=o.readUint64(),this.version===0?this.media_time=o.readUint32():this.media_time=o.readUint64()}),h.createFullBoxCtor("pssh",function(o){if(this.system_id=h.parseHex16(o),this.version>0){var c=o.readUint32();this.kid=[];for(var u=0;u<c;u++)this.kid[u]=h.parseHex16(o)}var p=o.readUint32();p>0&&(this.data=o.readUint8Array(p))}),h.createFullBoxCtor("clef",function(o){this.width=o.readUint32(),this.height=o.readUint32()}),h.createFullBoxCtor("enof",function(o){this.width=o.readUint32(),this.height=o.readUint32()}),h.createFullBoxCtor("prof",function(o){this.width=o.readUint32(),this.height=o.readUint32()}),h.createContainerBoxCtor("tapt",null,["clef","prof","enof"]),h.createBoxCtor("rtp ",function(o){this.descriptionformat=o.readString(4),this.sdptext=o.readString(this.size-this.hdr_size-4)}),h.createFullBoxCtor("saio",function(o){this.flags&1&&(this.aux_info_type=o.readUint32(),this.aux_info_type_parameter=o.readUint32());var c=o.readUint32();this.offset=[];for(var u=0;u<c;u++)this.version===0?this.offset[u]=o.readUint32():this.offset[u]=o.readUint64()}),h.createFullBoxCtor("saiz",function(o){this.flags&1&&(this.aux_info_type=o.readUint32(),this.aux_info_type_parameter=o.readUint32()),this.default_sample_info_size=o.readUint8();var c=o.readUint32();if(this.sample_info_size=[],this.default_sample_info_size===0)for(var u=0;u<c;u++)this.sample_info_size[u]=o.readUint8()}),h.createSampleEntryCtor(h.SAMPLE_ENTRY_TYPE_METADATA,"mett",function(o){this.parseHeader(o),this.content_encoding=o.readCString(),this.mime_format=o.readCString(),this.parseFooter(o)}),h.createSampleEntryCtor(h.SAMPLE_ENTRY_TYPE_METADATA,"metx",function(o){this.parseHeader(o),this.content_encoding=o.readCString(),this.namespace=o.readCString(),this.schema_location=o.readCString(),this.parseFooter(o)}),h.createSampleEntryCtor(h.SAMPLE_ENTRY_TYPE_SUBTITLE,"sbtt",function(o){this.parseHeader(o),this.content_encoding=o.readCString(),this.mime_format=o.readCString(),this.parseFooter(o)}),h.createSampleEntryCtor(h.SAMPLE_ENTRY_TYPE_SUBTITLE,"stpp",function(o){this.parseHeader(o),this.namespace=o.readCString(),this.schema_location=o.readCString(),this.auxiliary_mime_types=o.readCString(),this.parseFooter(o)}),h.createSampleEntryCtor(h.SAMPLE_ENTRY_TYPE_SUBTITLE,"stxt",function(o){this.parseHeader(o),this.content_encoding=o.readCString(),this.mime_format=o.readCString(),this.parseFooter(o)}),h.createSampleEntryCtor(h.SAMPLE_ENTRY_TYPE_SUBTITLE,"tx3g",function(o){this.parseHeader(o),this.displayFlags=o.readUint32(),this.horizontal_justification=o.readInt8(),this.vertical_justification=o.readInt8(),this.bg_color_rgba=o.readUint8Array(4),this.box_record=o.readInt16Array(4),this.style_record=o.readUint8Array(12),this.parseFooter(o)}),h.createSampleEntryCtor(h.SAMPLE_ENTRY_TYPE_METADATA,"wvtt",function(o){this.parseHeader(o),this.parseFooter(o)}),h.createSampleGroupCtor("alst",function(o){var c,u=o.readUint16();for(this.first_output_sample=o.readUint16(),this.sample_offset=[],c=0;c<u;c++)this.sample_offset[c]=o.readUint32();var p=this.description_length-4-4*u;for(this.num_output_samples=[],this.num_total_samples=[],c=0;c<p/4;c++)this.num_output_samples[c]=o.readUint16(),this.num_total_samples[c]=o.readUint16()}),h.createSampleGroupCtor("avll",function(o){this.layerNumber=o.readUint8(),this.accurateStatisticsFlag=o.readUint8(),this.avgBitRate=o.readUint16(),this.avgFrameRate=o.readUint16()}),h.createSampleGroupCtor("avss",function(o){this.subSequenceIdentifier=o.readUint16(),this.layerNumber=o.readUint8();var c=o.readUint8();this.durationFlag=c>>7,this.avgRateFlag=c>>6&1,this.durationFlag&&(this.duration=o.readUint32()),this.avgRateFlag&&(this.accurateStatisticsFlag=o.readUint8(),this.avgBitRate=o.readUint16(),this.avgFrameRate=o.readUint16()),this.dependency=[];for(var u=o.readUint8(),p=0;p<u;p++){var _={};this.dependency.push(_),_.subSeqDirectionFlag=o.readUint8(),_.layerNumber=o.readUint8(),_.subSequenceIdentifier=o.readUint16()}}),h.createSampleGroupCtor("dtrt",function(o){t.warn("BoxParser","Sample Group type: "+this.grouping_type+" not fully parsed")}),h.createSampleGroupCtor("mvif",function(o){t.warn("BoxParser","Sample Group type: "+this.grouping_type+" not fully parsed")}),h.createSampleGroupCtor("prol",function(o){this.roll_distance=o.readInt16()}),h.createSampleGroupCtor("rap ",function(o){var c=o.readUint8();this.num_leading_samples_known=c>>7,this.num_leading_samples=c&127}),h.createSampleGroupCtor("rash",function(o){if(this.operation_point_count=o.readUint16(),this.description_length!==2+(this.operation_point_count===1?2:this.operation_point_count*6)+9)t.warn("BoxParser","Mismatch in "+this.grouping_type+" sample group length"),this.data=o.readUint8Array(this.description_length-2);else{if(this.operation_point_count===1)this.target_rate_share=o.readUint16();else{this.target_rate_share=[],this.available_bitrate=[];for(var c=0;c<this.operation_point_count;c++)this.available_bitrate[c]=o.readUint32(),this.target_rate_share[c]=o.readUint16()}this.maximum_bitrate=o.readUint32(),this.minimum_bitrate=o.readUint32(),this.discard_priority=o.readUint8()}}),h.createSampleGroupCtor("roll",function(o){this.roll_distance=o.readInt16()}),h.SampleGroupEntry.prototype.parse=function(o){t.warn("BoxParser","Unknown Sample Group type: "+this.grouping_type),this.data=o.readUint8Array(this.description_length)},h.createSampleGroupCtor("scif",function(o){t.warn("BoxParser","Sample Group type: "+this.grouping_type+" not fully parsed")}),h.createSampleGroupCtor("scnm",function(o){t.warn("BoxParser","Sample Group type: "+this.grouping_type+" not fully parsed")}),h.createSampleGroupCtor("seig",function(o){this.reserved=o.readUint8();var c=o.readUint8();this.crypt_byte_block=c>>4,this.skip_byte_block=c&15,this.isProtected=o.readUint8(),this.Per_Sample_IV_Size=o.readUint8(),this.KID=h.parseHex16(o),this.constant_IV_size=0,this.constant_IV=0,this.isProtected===1&&this.Per_Sample_IV_Size===0&&(this.constant_IV_size=o.readUint8(),this.constant_IV=o.readUint8Array(this.constant_IV_size))}),h.createSampleGroupCtor("stsa",function(o){t.warn("BoxParser","Sample Group type: "+this.grouping_type+" not fully parsed")}),h.createSampleGroupCtor("sync",function(o){var c=o.readUint8();this.NAL_unit_type=c&63}),h.createSampleGroupCtor("tele",function(o){var c=o.readUint8();this.level_independently_decodable=c>>7}),h.createSampleGroupCtor("tsas",function(o){t.warn("BoxParser","Sample Group type: "+this.grouping_type+" not fully parsed")}),h.createSampleGroupCtor("tscl",function(o){t.warn("BoxParser","Sample Group type: "+this.grouping_type+" not fully parsed")}),h.createSampleGroupCtor("vipr",function(o){t.warn("BoxParser","Sample Group type: "+this.grouping_type+" not fully parsed")}),h.createFullBoxCtor("sbgp",function(o){this.grouping_type=o.readString(4),this.version===1?this.grouping_type_parameter=o.readUint32():this.grouping_type_parameter=0,this.entries=[];for(var c=o.readUint32(),u=0;u<c;u++){var p={};this.entries.push(p),p.sample_count=o.readInt32(),p.group_description_index=o.readInt32()}});function f(o,c){this.bad_pixel_row=o,this.bad_pixel_column=c}f.prototype.toString=function(){return"[row: "+this.bad_pixel_row+", column: "+this.bad_pixel_column+"]"},h.createFullBoxCtor("sbpm",function(o){var c;for(this.component_count=o.readUint16(),this.component_index=[],c=0;c<this.component_count;c++)this.component_index.push(o.readUint16());var u=o.readUint8();for(this.correction_applied=(u&128)==128,this.num_bad_rows=o.readUint32(),this.num_bad_cols=o.readUint32(),this.num_bad_pixels=o.readUint32(),this.bad_rows=[],this.bad_columns=[],this.bad_pixels=[],c=0;c<this.num_bad_rows;c++)this.bad_rows.push(o.readUint32());for(c=0;c<this.num_bad_cols;c++)this.bad_columns.push(o.readUint32());for(c=0;c<this.num_bad_pixels;c++){var p=o.readUint32(),_=o.readUint32();this.bad_pixels.push(new f(p,_))}}),h.createFullBoxCtor("schm",function(o){this.scheme_type=o.readString(4),this.scheme_version=o.readUint32(),this.flags&1&&(this.scheme_uri=o.readString(this.size-this.hdr_size-8))}),h.createBoxCtor("sdp ",function(o){this.sdptext=o.readString(this.size-this.hdr_size)}),h.createFullBoxCtor("sdtp",function(o){var c,u=this.size-this.hdr_size;this.is_leading=[],this.sample_depends_on=[],this.sample_is_depended_on=[],this.sample_has_redundancy=[];for(var p=0;p<u;p++)c=o.readUint8(),this.is_leading[p]=c>>6,this.sample_depends_on[p]=c>>4&3,this.sample_is_depended_on[p]=c>>2&3,this.sample_has_redundancy[p]=c&3}),h.createFullBoxCtor("senc"),h.createFullBoxCtor("sgpd",function(o){this.grouping_type=o.readString(4),t.debug("BoxParser","Found Sample Groups of type "+this.grouping_type),this.version===1?this.default_length=o.readUint32():this.default_length=0,this.version>=2&&(this.default_group_description_index=o.readUint32()),this.entries=[];for(var c=o.readUint32(),u=0;u<c;u++){var p;h[this.grouping_type+"SampleGroupEntry"]?p=new h[this.grouping_type+"SampleGroupEntry"](this.grouping_type):p=new h.SampleGroupEntry(this.grouping_type),this.entries.push(p),this.version===1?this.default_length===0?p.description_length=o.readUint32():p.description_length=this.default_length:p.description_length=this.default_length,p.write===h.SampleGroupEntry.prototype.write&&(t.info("BoxParser","SampleGroup for type "+this.grouping_type+" writing not yet implemented, keeping unparsed data in memory for later write"),p.data=o.readUint8Array(p.description_length),o.position-=p.description_length),p.parse(o)}}),h.createFullBoxCtor("sidx",function(o){this.reference_ID=o.readUint32(),this.timescale=o.readUint32(),this.version===0?(this.earliest_presentation_time=o.readUint32(),this.first_offset=o.readUint32()):(this.earliest_presentation_time=o.readUint64(),this.first_offset=o.readUint64()),o.readUint16(),this.references=[];for(var c=o.readUint16(),u=0;u<c;u++){var p={};this.references.push(p);var _=o.readUint32();p.reference_type=_>>31&1,p.referenced_size=_&2147483647,p.subsegment_duration=o.readUint32(),_=o.readUint32(),p.starts_with_SAP=_>>31&1,p.SAP_type=_>>28&7,p.SAP_delta_time=_&268435455}}),h.SingleItemTypeReferenceBox=function(o,c,u,p){h.Box.call(this,o,c),this.hdr_size=u,this.start=p},h.SingleItemTypeReferenceBox.prototype=new h.Box,h.SingleItemTypeReferenceBox.prototype.parse=function(o){this.from_item_ID=o.readUint16();var c=o.readUint16();this.references=[];for(var u=0;u<c;u++)this.references[u]={},this.references[u].to_item_ID=o.readUint16()},h.SingleItemTypeReferenceBoxLarge=function(o,c,u,p){h.Box.call(this,o,c),this.hdr_size=u,this.start=p},h.SingleItemTypeReferenceBoxLarge.prototype=new h.Box,h.SingleItemTypeReferenceBoxLarge.prototype.parse=function(o){this.from_item_ID=o.readUint32();var c=o.readUint16();this.references=[];for(var u=0;u<c;u++)this.references[u]={},this.references[u].to_item_ID=o.readUint32()},h.createFullBoxCtor("SmDm",function(o){this.primaryRChromaticity_x=o.readUint16(),this.primaryRChromaticity_y=o.readUint16(),this.primaryGChromaticity_x=o.readUint16(),this.primaryGChromaticity_y=o.readUint16(),this.primaryBChromaticity_x=o.readUint16(),this.primaryBChromaticity_y=o.readUint16(),this.whitePointChromaticity_x=o.readUint16(),this.whitePointChromaticity_y=o.readUint16(),this.luminanceMax=o.readUint32(),this.luminanceMin=o.readUint32()}),h.createFullBoxCtor("smhd",function(o){this.balance=o.readUint16(),o.readUint16()}),h.createFullBoxCtor("ssix",function(o){this.subsegments=[];for(var c=o.readUint32(),u=0;u<c;u++){var p={};this.subsegments.push(p),p.ranges=[];for(var _=o.readUint32(),b=0;b<_;b++){var v={};p.ranges.push(v),v.level=o.readUint8(),v.range_size=o.readUint24()}}}),h.createFullBoxCtor("stco",function(o){var c;if(c=o.readUint32(),this.chunk_offsets=[],this.version===0)for(var u=0;u<c;u++)this.chunk_offsets.push(o.readUint32())}),h.createFullBoxCtor("stdp",function(o){var c=(this.size-this.hdr_size)/2;this.priority=[];for(var u=0;u<c;u++)this.priority[u]=o.readUint16()}),h.createFullBoxCtor("sthd"),h.createFullBoxCtor("stri",function(o){this.switch_group=o.readUint16(),this.alternate_group=o.readUint16(),this.sub_track_id=o.readUint32();var c=(this.size-this.hdr_size-8)/4;this.attribute_list=[];for(var u=0;u<c;u++)this.attribute_list[u]=o.readUint32()}),h.createFullBoxCtor("stsc",function(o){var c,u;if(c=o.readUint32(),this.first_chunk=[],this.samples_per_chunk=[],this.sample_description_index=[],this.version===0)for(u=0;u<c;u++)this.first_chunk.push(o.readUint32()),this.samples_per_chunk.push(o.readUint32()),this.sample_description_index.push(o.readUint32())}),h.createFullBoxCtor("stsd",function(o){var c,u,p,_;for(this.entries=[],p=o.readUint32(),c=1;c<=p;c++)if(u=h.parseOneBox(o,!0,this.size-(o.getPosition()-this.start)),u.code===h.OK)h[u.type+"SampleEntry"]?(_=new h[u.type+"SampleEntry"](u.size),_.hdr_size=u.hdr_size,_.start=u.start):(t.warn("BoxParser","Unknown sample entry type: "+u.type),_=new h.SampleEntry(u.type,u.size,u.hdr_size,u.start)),_.write===h.SampleEntry.prototype.write&&(t.info("BoxParser","SampleEntry "+_.type+" box writing not yet implemented, keeping unparsed data in memory for later write"),_.parseDataAndRewind(o)),_.parse(o),this.entries.push(_);else return}),h.createFullBoxCtor("stsg",function(o){this.grouping_type=o.readUint32();var c=o.readUint16();this.group_description_index=[];for(var u=0;u<c;u++)this.group_description_index[u]=o.readUint32()}),h.createFullBoxCtor("stsh",function(o){var c,u;if(c=o.readUint32(),this.shadowed_sample_numbers=[],this.sync_sample_numbers=[],this.version===0)for(u=0;u<c;u++)this.shadowed_sample_numbers.push(o.readUint32()),this.sync_sample_numbers.push(o.readUint32())}),h.createFullBoxCtor("stss",function(o){var c,u;if(u=o.readUint32(),this.version===0)for(this.sample_numbers=[],c=0;c<u;c++)this.sample_numbers.push(o.readUint32())}),h.createFullBoxCtor("stsz",function(o){var c;if(this.sample_sizes=[],this.version===0)for(this.sample_size=o.readUint32(),this.sample_count=o.readUint32(),c=0;c<this.sample_count;c++)this.sample_size===0?this.sample_sizes.push(o.readUint32()):this.sample_sizes[c]=this.sample_size}),h.createFullBoxCtor("stts",function(o){var c,u,p;if(c=o.readUint32(),this.sample_counts=[],this.sample_deltas=[],this.version===0)for(u=0;u<c;u++)this.sample_counts.push(o.readUint32()),p=o.readInt32(),p<0&&(t.warn("BoxParser","File uses negative stts sample delta, using value 1 instead, sync may be lost!"),p=1),this.sample_deltas.push(p)}),h.createFullBoxCtor("stvi",function(o){var c=o.readUint32();this.single_view_allowed=c&3,this.stereo_scheme=o.readUint32();var u=o.readUint32();this.stereo_indication_type=o.readString(u);var p,_;for(this.boxes=[];o.getPosition()<this.start+this.size;)if(p=h.parseOneBox(o,!1,this.size-(o.getPosition()-this.start)),p.code===h.OK)_=p.box,this.boxes.push(_),this[_.type]=_;else return}),h.createBoxCtor("styp",function(o){h.ftypBox.prototype.parse.call(this,o)}),h.createFullBoxCtor("stz2",function(o){var c,u;if(this.sample_sizes=[],this.version===0)if(this.reserved=o.readUint24(),this.field_size=o.readUint8(),u=o.readUint32(),this.field_size===4)for(c=0;c<u;c+=2){var p=o.readUint8();this.sample_sizes[c]=p>>4&15,this.sample_sizes[c+1]=p&15}else if(this.field_size===8)for(c=0;c<u;c++)this.sample_sizes[c]=o.readUint8();else if(this.field_size===16)for(c=0;c<u;c++)this.sample_sizes[c]=o.readUint16();else t.error("BoxParser","Error in length field in stz2 box")}),h.createFullBoxCtor("subs",function(o){var c,u,p,_;for(p=o.readUint32(),this.entries=[],c=0;c<p;c++){var b={};if(this.entries[c]=b,b.sample_delta=o.readUint32(),b.subsamples=[],_=o.readUint16(),_>0)for(u=0;u<_;u++){var v={};b.subsamples.push(v),this.version==1?v.size=o.readUint32():v.size=o.readUint16(),v.priority=o.readUint8(),v.discardable=o.readUint8(),v.codec_specific_parameters=o.readUint32()}}}),h.createFullBoxCtor("tenc",function(o){if(o.readUint8(),this.version===0)o.readUint8();else{var c=o.readUint8();this.default_crypt_byte_block=c>>4&15,this.default_skip_byte_block=c&15}this.default_isProtected=o.readUint8(),this.default_Per_Sample_IV_Size=o.readUint8(),this.default_KID=h.parseHex16(o),this.default_isProtected===1&&this.default_Per_Sample_IV_Size===0&&(this.default_constant_IV_size=o.readUint8(),this.default_constant_IV=o.readUint8Array(this.default_constant_IV_size))}),h.createFullBoxCtor("tfdt",function(o){this.version==1?this.baseMediaDecodeTime=o.readUint64():this.baseMediaDecodeTime=o.readUint32()}),h.createFullBoxCtor("tfhd",function(o){var c=0;this.track_id=o.readUint32(),this.size-this.hdr_size>c&&this.flags&h.TFHD_FLAG_BASE_DATA_OFFSET?(this.base_data_offset=o.readUint64(),c+=8):this.base_data_offset=0,this.size-this.hdr_size>c&&this.flags&h.TFHD_FLAG_SAMPLE_DESC?(this.default_sample_description_index=o.readUint32(),c+=4):this.default_sample_description_index=0,this.size-this.hdr_size>c&&this.flags&h.TFHD_FLAG_SAMPLE_DUR?(this.default_sample_duration=o.readUint32(),c+=4):this.default_sample_duration=0,this.size-this.hdr_size>c&&this.flags&h.TFHD_FLAG_SAMPLE_SIZE?(this.default_sample_size=o.readUint32(),c+=4):this.default_sample_size=0,this.size-this.hdr_size>c&&this.flags&h.TFHD_FLAG_SAMPLE_FLAGS?(this.default_sample_flags=o.readUint32(),c+=4):this.default_sample_flags=0}),h.createFullBoxCtor("tfra",function(o){this.track_ID=o.readUint32(),o.readUint24();var c=o.readUint8();this.length_size_of_traf_num=c>>4&3,this.length_size_of_trun_num=c>>2&3,this.length_size_of_sample_num=c&3,this.entries=[];for(var u=o.readUint32(),p=0;p<u;p++)this.version===1?(this.time=o.readUint64(),this.moof_offset=o.readUint64()):(this.time=o.readUint32(),this.moof_offset=o.readUint32()),this.traf_number=o["readUint"+8*(this.length_size_of_traf_num+1)](),this.trun_number=o["readUint"+8*(this.length_size_of_trun_num+1)](),this.sample_number=o["readUint"+8*(this.length_size_of_sample_num+1)]()}),h.createFullBoxCtor("tkhd",function(o){this.version==1?(this.creation_time=o.readUint64(),this.modification_time=o.readUint64(),this.track_id=o.readUint32(),o.readUint32(),this.duration=o.readUint64()):(this.creation_time=o.readUint32(),this.modification_time=o.readUint32(),this.track_id=o.readUint32(),o.readUint32(),this.duration=o.readUint32()),o.readUint32Array(2),this.layer=o.readInt16(),this.alternate_group=o.readInt16(),this.volume=o.readInt16()>>8,o.readUint16(),this.matrix=o.readInt32Array(9),this.width=o.readUint32(),this.height=o.readUint32()}),h.createBoxCtor("tmax",function(o){this.time=o.readUint32()}),h.createBoxCtor("tmin",function(o){this.time=o.readUint32()}),h.createBoxCtor("totl",function(o){this.bytessent=o.readUint32()}),h.createBoxCtor("tpay",function(o){this.bytessent=o.readUint32()}),h.createBoxCtor("tpyl",function(o){this.bytessent=o.readUint64()}),h.TrackGroupTypeBox.prototype.parse=function(o){this.parseFullHeader(o),this.track_group_id=o.readUint32()},h.createTrackGroupCtor("msrc"),h.TrackReferenceTypeBox=function(o,c,u,p){h.Box.call(this,o,c),this.hdr_size=u,this.start=p},h.TrackReferenceTypeBox.prototype=new h.Box,h.TrackReferenceTypeBox.prototype.parse=function(o){this.track_ids=o.readUint32Array((this.size-this.hdr_size)/4)},h.trefBox.prototype.parse=function(o){for(var c,u;o.getPosition()<this.start+this.size;)if(c=h.parseOneBox(o,!0,this.size-(o.getPosition()-this.start)),c.code===h.OK)u=new h.TrackReferenceTypeBox(c.type,c.size,c.hdr_size,c.start),u.write===h.Box.prototype.write&&u.type!=="mdat"&&(t.info("BoxParser","TrackReference "+u.type+" box writing not yet implemented, keeping unparsed data in memory for later write"),u.parseDataAndRewind(o)),u.parse(o),this.boxes.push(u);else return},h.createFullBoxCtor("trep",function(o){for(this.track_ID=o.readUint32(),this.boxes=[];o.getPosition()<this.start+this.size;)if(ret=h.parseOneBox(o,!1,this.size-(o.getPosition()-this.start)),ret.code===h.OK)box=ret.box,this.boxes.push(box);else return}),h.createFullBoxCtor("trex",function(o){this.track_id=o.readUint32(),this.default_sample_description_index=o.readUint32(),this.default_sample_duration=o.readUint32(),this.default_sample_size=o.readUint32(),this.default_sample_flags=o.readUint32()}),h.createBoxCtor("trpy",function(o){this.bytessent=o.readUint64()}),h.createFullBoxCtor("trun",function(o){var c=0;if(this.sample_count=o.readUint32(),c+=4,this.size-this.hdr_size>c&&this.flags&h.TRUN_FLAGS_DATA_OFFSET?(this.data_offset=o.readInt32(),c+=4):this.data_offset=0,this.size-this.hdr_size>c&&this.flags&h.TRUN_FLAGS_FIRST_FLAG?(this.first_sample_flags=o.readUint32(),c+=4):this.first_sample_flags=0,this.sample_duration=[],this.sample_size=[],this.sample_flags=[],this.sample_composition_time_offset=[],this.size-this.hdr_size>c)for(var u=0;u<this.sample_count;u++)this.flags&h.TRUN_FLAGS_DURATION&&(this.sample_duration[u]=o.readUint32()),this.flags&h.TRUN_FLAGS_SIZE&&(this.sample_size[u]=o.readUint32()),this.flags&h.TRUN_FLAGS_FLAGS&&(this.sample_flags[u]=o.readUint32()),this.flags&h.TRUN_FLAGS_CTS_OFFSET&&(this.version===0?this.sample_composition_time_offset[u]=o.readUint32():this.sample_composition_time_offset[u]=o.readInt32())}),h.createFullBoxCtor("tsel",function(o){this.switch_group=o.readUint32();var c=(this.size-this.hdr_size-4)/4;this.attribute_list=[];for(var u=0;u<c;u++)this.attribute_list[u]=o.readUint32()}),h.createFullBoxCtor("txtC",function(o){this.config=o.readCString()}),h.createBoxCtor("tyco",function(o){var c=(this.size-this.hdr_size)/4;this.compatible_brands=[];for(var u=0;u<c;u++)this.compatible_brands[u]=o.readString(4)}),h.createFullBoxCtor("udes",function(o){this.lang=o.readCString(),this.name=o.readCString(),this.description=o.readCString(),this.tags=o.readCString()}),h.createFullBoxCtor("uncC",function(o){var c;if(this.profile=o.readUint32(),this.version!=1){if(this.version==0){for(this.component_count=o.readUint32(),this.component_index=[],this.component_bit_depth_minus_one=[],this.component_format=[],this.component_align_size=[],c=0;c<this.component_count;c++)this.component_index.push(o.readUint16()),this.component_bit_depth_minus_one.push(o.readUint8()),this.component_format.push(o.readUint8()),this.component_align_size.push(o.readUint8());this.sampling_type=o.readUint8(),this.interleave_type=o.readUint8(),this.block_size=o.readUint8();var u=o.readUint8();this.component_little_endian=u>>7&1,this.block_pad_lsb=u>>6&1,this.block_little_endian=u>>5&1,this.block_reversed=u>>4&1,this.pad_unknown=u>>3&1,this.pixel_size=o.readUint32(),this.row_align_size=o.readUint32(),this.tile_align_size=o.readUint32(),this.num_tile_cols_minus_one=o.readUint32(),this.num_tile_rows_minus_one=o.readUint32()}}}),h.createFullBoxCtor("url ",function(o){this.flags!==1&&(this.location=o.readCString())}),h.createFullBoxCtor("urn ",function(o){this.name=o.readCString(),this.size-this.hdr_size-this.name.length-1>0&&(this.location=o.readCString())}),h.createUUIDBox("a5d40b30e81411ddba2f0800200c9a66",!0,!1,function(o){this.LiveServerManifest=o.readString(this.size-this.hdr_size).replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}),h.createUUIDBox("d08a4f1810f34a82b6c832d8aba183d3",!0,!1,function(o){this.system_id=h.parseHex16(o);var c=o.readUint32();c>0&&(this.data=o.readUint8Array(c))}),h.createUUIDBox("a2394f525a9b4f14a2446c427c648df4",!0,!1),h.createUUIDBox("8974dbce7be74c5184f97148f9882554",!0,!1,function(o){this.default_AlgorithmID=o.readUint24(),this.default_IV_size=o.readUint8(),this.default_KID=h.parseHex16(o)}),h.createUUIDBox("d4807ef2ca3946958e5426cb9e46a79f",!0,!1,function(o){this.fragment_count=o.readUint8(),this.entries=[];for(var c=0;c<this.fragment_count;c++){var u={},p=0,_=0;this.version===1?(p=o.readUint64(),_=o.readUint64()):(p=o.readUint32(),_=o.readUint32()),u.absolute_time=p,u.absolute_duration=_,this.entries.push(u)}}),h.createUUIDBox("6d1d9b0542d544e680e2141daff757b2",!0,!1,function(o){this.version===1?(this.absolute_time=o.readUint64(),this.duration=o.readUint64()):(this.absolute_time=o.readUint32(),this.duration=o.readUint32())}),h.createFullBoxCtor("vmhd",function(o){this.graphicsmode=o.readUint16(),this.opcolor=o.readUint16Array(3)}),h.createFullBoxCtor("vpcC",function(o){var c;this.version===1?(this.profile=o.readUint8(),this.level=o.readUint8(),c=o.readUint8(),this.bitDepth=c>>4,this.chromaSubsampling=c>>1&7,this.videoFullRangeFlag=c&1,this.colourPrimaries=o.readUint8(),this.transferCharacteristics=o.readUint8(),this.matrixCoefficients=o.readUint8(),this.codecIntializationDataSize=o.readUint16(),this.codecIntializationData=o.readUint8Array(this.codecIntializationDataSize)):(this.profile=o.readUint8(),this.level=o.readUint8(),c=o.readUint8(),this.bitDepth=c>>4&15,this.colorSpace=c&15,c=o.readUint8(),this.chromaSubsampling=c>>4&15,this.transferFunction=c>>1&7,this.videoFullRangeFlag=c&1,this.codecIntializationDataSize=o.readUint16(),this.codecIntializationData=o.readUint8Array(this.codecIntializationDataSize))}),h.createBoxCtor("vttC",function(o){this.text=o.readString(this.size-this.hdr_size)}),h.createFullBoxCtor("vvcC",function(o){var c,u,p={held_bits:void 0,num_held_bits:0,stream_read_1_bytes:function(A){this.held_bits=A.readUint8(),this.num_held_bits=8},stream_read_2_bytes:function(A){this.held_bits=A.readUint16(),this.num_held_bits=16},extract_bits:function(A){var G=this.held_bits>>this.num_held_bits-A&(1<<A)-1;return this.num_held_bits-=A,G}};if(p.stream_read_1_bytes(o),p.extract_bits(5),this.lengthSizeMinusOne=p.extract_bits(2),this.ptl_present_flag=p.extract_bits(1),this.ptl_present_flag){p.stream_read_2_bytes(o),this.ols_idx=p.extract_bits(9),this.num_sublayers=p.extract_bits(3),this.constant_frame_rate=p.extract_bits(2),this.chroma_format_idc=p.extract_bits(2),p.stream_read_1_bytes(o),this.bit_depth_minus8=p.extract_bits(3),p.extract_bits(5);{if(p.stream_read_2_bytes(o),p.extract_bits(2),this.num_bytes_constraint_info=p.extract_bits(6),this.general_profile_idc=p.extract_bits(7),this.general_tier_flag=p.extract_bits(1),this.general_level_idc=o.readUint8(),p.stream_read_1_bytes(o),this.ptl_frame_only_constraint_flag=p.extract_bits(1),this.ptl_multilayer_enabled_flag=p.extract_bits(1),this.general_constraint_info=new Uint8Array(this.num_bytes_constraint_info),this.num_bytes_constraint_info){for(c=0;c<this.num_bytes_constraint_info-1;c++){var _=p.extract_bits(6);p.stream_read_1_bytes(o);var b=p.extract_bits(2);this.general_constraint_info[c]=_<<2|b}this.general_constraint_info[this.num_bytes_constraint_info-1]=p.extract_bits(6)}else p.extract_bits(6);if(this.num_sublayers>1){for(p.stream_read_1_bytes(o),this.ptl_sublayer_present_mask=0,u=this.num_sublayers-2;u>=0;--u){var v=p.extract_bits(1);this.ptl_sublayer_present_mask|=v<<u}for(u=this.num_sublayers;u<=8&&this.num_sublayers>1;++u)p.extract_bits(1);for(this.sublayer_level_idc=[],u=this.num_sublayers-2;u>=0;--u)this.ptl_sublayer_present_mask&1<<u&&(this.sublayer_level_idc[u]=o.readUint8())}if(this.ptl_num_sub_profiles=o.readUint8(),this.general_sub_profile_idc=[],this.ptl_num_sub_profiles)for(c=0;c<this.ptl_num_sub_profiles;c++)this.general_sub_profile_idc.push(o.readUint32())}this.max_picture_width=o.readUint16(),this.max_picture_height=o.readUint16(),this.avg_frame_rate=o.readUint16()}var w=12,S=13;this.nalu_arrays=[];var T=o.readUint8();for(c=0;c<T;c++){var E=[];this.nalu_arrays.push(E),p.stream_read_1_bytes(o),E.completeness=p.extract_bits(1),p.extract_bits(2),E.nalu_type=p.extract_bits(5);var P=1;for(E.nalu_type!=S&&E.nalu_type!=w&&(P=o.readUint16()),u=0;u<P;u++){var B=o.readUint16();E.push({data:o.readUint8Array(B),length:B})}}}),h.createFullBoxCtor("vvnC",function(o){var c=strm.readUint8();this.lengthSizeMinusOne=c&3}),h.SampleEntry.prototype.isVideo=function(){return!1},h.SampleEntry.prototype.isAudio=function(){return!1},h.SampleEntry.prototype.isSubtitle=function(){return!1},h.SampleEntry.prototype.isMetadata=function(){return!1},h.SampleEntry.prototype.isHint=function(){return!1},h.SampleEntry.prototype.getCodec=function(){return this.type.replace(".","")},h.SampleEntry.prototype.getWidth=function(){return""},h.SampleEntry.prototype.getHeight=function(){return""},h.SampleEntry.prototype.getChannelCount=function(){return""},h.SampleEntry.prototype.getSampleRate=function(){return""},h.SampleEntry.prototype.getSampleSize=function(){return""},h.VisualSampleEntry.prototype.isVideo=function(){return!0},h.VisualSampleEntry.prototype.getWidth=function(){return this.width},h.VisualSampleEntry.prototype.getHeight=function(){return this.height},h.AudioSampleEntry.prototype.isAudio=function(){return!0},h.AudioSampleEntry.prototype.getChannelCount=function(){return this.channel_count},h.AudioSampleEntry.prototype.getSampleRate=function(){return this.samplerate},h.AudioSampleEntry.prototype.getSampleSize=function(){return this.samplesize},h.SubtitleSampleEntry.prototype.isSubtitle=function(){return!0},h.MetadataSampleEntry.prototype.isMetadata=function(){return!0},h.decimalToHex=function(o,c){var u=Number(o).toString(16);for(c=typeof c>"u"||c===null?c=2:c;u.length<c;)u="0"+u;return u},h.avc1SampleEntry.prototype.getCodec=h.avc2SampleEntry.prototype.getCodec=h.avc3SampleEntry.prototype.getCodec=h.avc4SampleEntry.prototype.getCodec=function(){var o=h.SampleEntry.prototype.getCodec.call(this);return this.avcC?o+"."+h.decimalToHex(this.avcC.AVCProfileIndication)+h.decimalToHex(this.avcC.profile_compatibility)+h.decimalToHex(this.avcC.AVCLevelIndication):o},h.hev1SampleEntry.prototype.getCodec=h.hvc1SampleEntry.prototype.getCodec=function(){var o,c=h.SampleEntry.prototype.getCodec.call(this);if(this.hvcC){switch(c+=".",this.hvcC.general_profile_space){case 0:c+="";break;case 1:c+="A";break;case 2:c+="B";break;case 3:c+="C";break}c+=this.hvcC.general_profile_idc,c+=".";var u=this.hvcC.general_profile_compatibility,p=0;for(o=0;o<32&&(p|=u&1,o!=31);o++)p<<=1,u>>=1;c+=h.decimalToHex(p,0),c+=".",this.hvcC.general_tier_flag===0?c+="L":c+="H",c+=this.hvcC.general_level_idc;var _=!1,b="";for(o=5;o>=0;o--)(this.hvcC.general_constraint_indicator[o]||_)&&(b="."+h.decimalToHex(this.hvcC.general_constraint_indicator[o],0)+b,_=!0);c+=b}return c},h.vvc1SampleEntry.prototype.getCodec=h.vvi1SampleEntry.prototype.getCodec=function(){var o,c=h.SampleEntry.prototype.getCodec.call(this);if(this.vvcC){c+="."+this.vvcC.general_profile_idc,this.vvcC.general_tier_flag?c+=".H":c+=".L",c+=this.vvcC.general_level_idc;var u="";if(this.vvcC.general_constraint_info){var p=[],_=0;_|=this.vvcC.ptl_frame_only_constraint<<7,_|=this.vvcC.ptl_multilayer_enabled<<6;var b;for(o=0;o<this.vvcC.general_constraint_info.length;++o)_|=this.vvcC.general_constraint_info[o]>>2&63,p.push(_),_&&(b=o),_=this.vvcC.general_constraint_info[o]>>2&3;if(b===void 0)u=".CA";else{u=".C";var v="ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",w=0,S=0;for(o=0;o<=b;++o)for(w=w<<8|p[o],S+=8;S>=5;){var T=w>>S-5&31;u+=v[T],S-=5,w&=(1<<S)-1}S&&(w<<=5-S,u+=v[w&31])}}c+=u}return c},h.mp4aSampleEntry.prototype.getCodec=function(){var o=h.SampleEntry.prototype.getCodec.call(this);if(this.esds&&this.esds.esd){var c=this.esds.esd.getOTI(),u=this.esds.esd.getAudioConfig();return o+"."+h.decimalToHex(c)+(u?"."+u:"")}else return o},h.stxtSampleEntry.prototype.getCodec=function(){var o=h.SampleEntry.prototype.getCodec.call(this);return this.mime_format?o+"."+this.mime_format:o},h.vp08SampleEntry.prototype.getCodec=h.vp09SampleEntry.prototype.getCodec=function(){var o=h.SampleEntry.prototype.getCodec.call(this),c=this.vpcC.level;c==0&&(c="00");var u=this.vpcC.bitDepth;return u==8&&(u="08"),o+".0"+this.vpcC.profile+"."+c+"."+u},h.av01SampleEntry.prototype.getCodec=function(){var o=h.SampleEntry.prototype.getCodec.call(this),c=this.av1C.seq_level_idx_0;c<10&&(c="0"+c);var u;return this.av1C.seq_profile===2&&this.av1C.high_bitdepth===1?u=this.av1C.twelve_bit===1?"12":"10":this.av1C.seq_profile<=2&&(u=this.av1C.high_bitdepth===1?"10":"08"),o+"."+this.av1C.seq_profile+"."+c+(this.av1C.seq_tier_0?"H":"M")+"."+u},h.Box.prototype.writeHeader=function(o,c){this.size+=8,this.size>n&&(this.size+=8),this.type==="uuid"&&(this.size+=16),t.debug("BoxWriter","Writing box "+this.type+" of size: "+this.size+" at position "+o.getPosition()+(c||"")),this.size>n?o.writeUint32(1):(this.sizePosition=o.getPosition(),o.writeUint32(this.size)),o.writeString(this.type,null,4),this.type==="uuid"&&o.writeUint8Array(this.uuid),this.size>n&&o.writeUint64(this.size)},h.FullBox.prototype.writeHeader=function(o){this.size+=4,h.Box.prototype.writeHeader.call(this,o," v="+this.version+" f="+this.flags),o.writeUint8(this.version),o.writeUint24(this.flags)},h.Box.prototype.write=function(o){this.type==="mdat"?this.data&&(this.size=this.data.length,this.writeHeader(o),o.writeUint8Array(this.data)):(this.size=this.data?this.data.length:0,this.writeHeader(o),this.data&&o.writeUint8Array(this.data))},h.ContainerBox.prototype.write=function(o){this.size=0,this.writeHeader(o);for(var c=0;c<this.boxes.length;c++)this.boxes[c]&&(this.boxes[c].write(o),this.size+=this.boxes[c].size);t.debug("BoxWriter","Adjusting box "+this.type+" with new size "+this.size),o.adjustUint32(this.sizePosition,this.size)},h.TrackReferenceTypeBox.prototype.write=function(o){this.size=this.track_ids.length*4,this.writeHeader(o),o.writeUint32Array(this.track_ids)},h.avcCBox.prototype.write=function(o){var c;for(this.size=7,c=0;c<this.SPS.length;c++)this.size+=2+this.SPS[c].length;for(c=0;c<this.PPS.length;c++)this.size+=2+this.PPS[c].length;for(this.ext&&(this.size+=this.ext.length),this.writeHeader(o),o.writeUint8(this.configurationVersion),o.writeUint8(this.AVCProfileIndication),o.writeUint8(this.profile_compatibility),o.writeUint8(this.AVCLevelIndication),o.writeUint8(this.lengthSizeMinusOne+252),o.writeUint8(this.SPS.length+224),c=0;c<this.SPS.length;c++)o.writeUint16(this.SPS[c].length),o.writeUint8Array(this.SPS[c].nalu);for(o.writeUint8(this.PPS.length),c=0;c<this.PPS.length;c++)o.writeUint16(this.PPS[c].length),o.writeUint8Array(this.PPS[c].nalu);this.ext&&o.writeUint8Array(this.ext)},h.co64Box.prototype.write=function(o){var c;for(this.version=0,this.flags=0,this.size=4+8*this.chunk_offsets.length,this.writeHeader(o),o.writeUint32(this.chunk_offsets.length),c=0;c<this.chunk_offsets.length;c++)o.writeUint64(this.chunk_offsets[c])},h.cslgBox.prototype.write=function(o){this.version=0,this.flags=0,this.size=20,this.writeHeader(o),o.writeInt32(this.compositionToDTSShift),o.writeInt32(this.leastDecodeToDisplayDelta),o.writeInt32(this.greatestDecodeToDisplayDelta),o.writeInt32(this.compositionStartTime),o.writeInt32(this.compositionEndTime)},h.cttsBox.prototype.write=function(o){var c;for(this.version=0,this.flags=0,this.size=4+8*this.sample_counts.length,this.writeHeader(o),o.writeUint32(this.sample_counts.length),c=0;c<this.sample_counts.length;c++)o.writeUint32(this.sample_counts[c]),this.version===1?o.writeInt32(this.sample_offsets[c]):o.writeUint32(this.sample_offsets[c])},h.drefBox.prototype.write=function(o){this.version=0,this.flags=0,this.size=4,this.writeHeader(o),o.writeUint32(this.entries.length);for(var c=0;c<this.entries.length;c++)this.entries[c].write(o),this.size+=this.entries[c].size;t.debug("BoxWriter","Adjusting box "+this.type+" with new size "+this.size),o.adjustUint32(this.sizePosition,this.size)},h.elngBox.prototype.write=function(o){this.version=0,this.flags=0,this.size=this.extended_language.length,this.writeHeader(o),o.writeString(this.extended_language)},h.elstBox.prototype.write=function(o){this.version=0,this.flags=0,this.size=4+12*this.entries.length,this.writeHeader(o),o.writeUint32(this.entries.length);for(var c=0;c<this.entries.length;c++){var u=this.entries[c];o.writeUint32(u.segment_duration),o.writeInt32(u.media_time),o.writeInt16(u.media_rate_integer),o.writeInt16(u.media_rate_fraction)}},h.emsgBox.prototype.write=function(o){this.version=0,this.flags=0,this.size=16+this.message_data.length+(this.scheme_id_uri.length+1)+(this.value.length+1),this.writeHeader(o),o.writeCString(this.scheme_id_uri),o.writeCString(this.value),o.writeUint32(this.timescale),o.writeUint32(this.presentation_time_delta),o.writeUint32(this.event_duration),o.writeUint32(this.id),o.writeUint8Array(this.message_data)},h.ftypBox.prototype.write=function(o){this.size=8+4*this.compatible_brands.length,this.writeHeader(o),o.writeString(this.major_brand,null,4),o.writeUint32(this.minor_version);for(var c=0;c<this.compatible_brands.length;c++)o.writeString(this.compatible_brands[c],null,4)},h.hdlrBox.prototype.write=function(o){this.size=20+this.name.length+1,this.version=0,this.flags=0,this.writeHeader(o),o.writeUint32(0),o.writeString(this.handler,null,4),o.writeUint32(0),o.writeUint32(0),o.writeUint32(0),o.writeCString(this.name)},h.hvcCBox.prototype.write=function(o){var c,u;for(this.size=23,c=0;c<this.nalu_arrays.length;c++)for(this.size+=3,u=0;u<this.nalu_arrays[c].length;u++)this.size+=2+this.nalu_arrays[c][u].data.length;for(this.writeHeader(o),o.writeUint8(this.configurationVersion),o.writeUint8((this.general_profile_space<<6)+(this.general_tier_flag<<5)+this.general_profile_idc),o.writeUint32(this.general_profile_compatibility),o.writeUint8Array(this.general_constraint_indicator),o.writeUint8(this.general_level_idc),o.writeUint16(this.min_spatial_segmentation_idc+(15<<24)),o.writeUint8(this.parallelismType+252),o.writeUint8(this.chroma_format_idc+252),o.writeUint8(this.bit_depth_luma_minus8+248),o.writeUint8(this.bit_depth_chroma_minus8+248),o.writeUint16(this.avgFrameRate),o.writeUint8((this.constantFrameRate<<6)+(this.numTemporalLayers<<3)+(this.temporalIdNested<<2)+this.lengthSizeMinusOne),o.writeUint8(this.nalu_arrays.length),c=0;c<this.nalu_arrays.length;c++)for(o.writeUint8((this.nalu_arrays[c].completeness<<7)+this.nalu_arrays[c].nalu_type),o.writeUint16(this.nalu_arrays[c].length),u=0;u<this.nalu_arrays[c].length;u++)o.writeUint16(this.nalu_arrays[c][u].data.length),o.writeUint8Array(this.nalu_arrays[c][u].data)},h.kindBox.prototype.write=function(o){this.version=0,this.flags=0,this.size=this.schemeURI.length+1+(this.value.length+1),this.writeHeader(o),o.writeCString(this.schemeURI),o.writeCString(this.value)},h.mdhdBox.prototype.write=function(o){this.size=20,this.flags=0,this.version=0,this.writeHeader(o),o.writeUint32(this.creation_time),o.writeUint32(this.modification_time),o.writeUint32(this.timescale),o.writeUint32(this.duration),o.writeUint16(this.language),o.writeUint16(0)},h.mehdBox.prototype.write=function(o){this.version=0,this.flags=0,this.size=4,this.writeHeader(o),o.writeUint32(this.fragment_duration)},h.mfhdBox.prototype.write=function(o){this.version=0,this.flags=0,this.size=4,this.writeHeader(o),o.writeUint32(this.sequence_number)},h.mvhdBox.prototype.write=function(o){this.version=0,this.flags=0,this.size=96,this.writeHeader(o),o.writeUint32(this.creation_time),o.writeUint32(this.modification_time),o.writeUint32(this.timescale),o.writeUint32(this.duration),o.writeUint32(this.rate),o.writeUint16(this.volume<<8),o.writeUint16(0),o.writeUint32(0),o.writeUint32(0),o.writeUint32Array(this.matrix),o.writeUint32(0),o.writeUint32(0),o.writeUint32(0),o.writeUint32(0),o.writeUint32(0),o.writeUint32(0),o.writeUint32(this.next_track_id)},h.SampleEntry.prototype.writeHeader=function(o){this.size=8,h.Box.prototype.writeHeader.call(this,o),o.writeUint8(0),o.writeUint8(0),o.writeUint8(0),o.writeUint8(0),o.writeUint8(0),o.writeUint8(0),o.writeUint16(this.data_reference_index)},h.SampleEntry.prototype.writeFooter=function(o){for(var c=0;c<this.boxes.length;c++)this.boxes[c].write(o),this.size+=this.boxes[c].size;t.debug("BoxWriter","Adjusting box "+this.type+" with new size "+this.size),o.adjustUint32(this.sizePosition,this.size)},h.SampleEntry.prototype.write=function(o){this.writeHeader(o),o.writeUint8Array(this.data),this.size+=this.data.length,t.debug("BoxWriter","Adjusting box "+this.type+" with new size "+this.size),o.adjustUint32(this.sizePosition,this.size)},h.VisualSampleEntry.prototype.write=function(o){this.writeHeader(o),this.size+=70,o.writeUint16(0),o.writeUint16(0),o.writeUint32(0),o.writeUint32(0),o.writeUint32(0),o.writeUint16(this.width),o.writeUint16(this.height),o.writeUint32(this.horizresolution),o.writeUint32(this.vertresolution),o.writeUint32(0),o.writeUint16(this.frame_count),o.writeUint8(Math.min(31,this.compressorname.length)),o.writeString(this.compressorname,null,31),o.writeUint16(this.depth),o.writeInt16(-1),this.writeFooter(o)},h.AudioSampleEntry.prototype.write=function(o){this.writeHeader(o),this.size+=20,o.writeUint32(0),o.writeUint32(0),o.writeUint16(this.channel_count),o.writeUint16(this.samplesize),o.writeUint16(0),o.writeUint16(0),o.writeUint32(this.samplerate<<16),this.writeFooter(o)},h.stppSampleEntry.prototype.write=function(o){this.writeHeader(o),this.size+=this.namespace.length+1+this.schema_location.length+1+this.auxiliary_mime_types.length+1,o.writeCString(this.namespace),o.writeCString(this.schema_location),o.writeCString(this.auxiliary_mime_types),this.writeFooter(o)},h.SampleGroupEntry.prototype.write=function(o){o.writeUint8Array(this.data)},h.sbgpBox.prototype.write=function(o){this.version=1,this.flags=0,this.size=12+8*this.entries.length,this.writeHeader(o),o.writeString(this.grouping_type,null,4),o.writeUint32(this.grouping_type_parameter),o.writeUint32(this.entries.length);for(var c=0;c<this.entries.length;c++){var u=this.entries[c];o.writeInt32(u.sample_count),o.writeInt32(u.group_description_index)}},h.sgpdBox.prototype.write=function(o){var c,u;for(this.flags=0,this.size=12,c=0;c<this.entries.length;c++)u=this.entries[c],this.version===1&&(this.default_length===0&&(this.size+=4),this.size+=u.data.length);for(this.writeHeader(o),o.writeString(this.grouping_type,null,4),this.version===1&&o.writeUint32(this.default_length),this.version>=2&&o.writeUint32(this.default_sample_description_index),o.writeUint32(this.entries.length),c=0;c<this.entries.length;c++)u=this.entries[c],this.version===1&&this.default_length===0&&o.writeUint32(u.description_length),u.write(o)},h.sidxBox.prototype.write=function(o){this.version=0,this.flags=0,this.size=20+12*this.references.length,this.writeHeader(o),o.writeUint32(this.reference_ID),o.writeUint32(this.timescale),o.writeUint32(this.earliest_presentation_time),o.writeUint32(this.first_offset),o.writeUint16(0),o.writeUint16(this.references.length);for(var c=0;c<this.references.length;c++){var u=this.references[c];o.writeUint32(u.reference_type<<31|u.referenced_size),o.writeUint32(u.subsegment_duration),o.writeUint32(u.starts_with_SAP<<31|u.SAP_type<<28|u.SAP_delta_time)}},h.smhdBox.prototype.write=function(o){this.version=0,this.flags=1,this.size=4,this.writeHeader(o),o.writeUint16(this.balance),o.writeUint16(0)},h.stcoBox.prototype.write=function(o){this.version=0,this.flags=0,this.size=4+4*this.chunk_offsets.length,this.writeHeader(o),o.writeUint32(this.chunk_offsets.length),o.writeUint32Array(this.chunk_offsets)},h.stscBox.prototype.write=function(o){var c;for(this.version=0,this.flags=0,this.size=4+12*this.first_chunk.length,this.writeHeader(o),o.writeUint32(this.first_chunk.length),c=0;c<this.first_chunk.length;c++)o.writeUint32(this.first_chunk[c]),o.writeUint32(this.samples_per_chunk[c]),o.writeUint32(this.sample_description_index[c])},h.stsdBox.prototype.write=function(o){var c;for(this.version=0,this.flags=0,this.size=0,this.writeHeader(o),o.writeUint32(this.entries.length),this.size+=4,c=0;c<this.entries.length;c++)this.entries[c].write(o),this.size+=this.entries[c].size;t.debug("BoxWriter","Adjusting box "+this.type+" with new size "+this.size),o.adjustUint32(this.sizePosition,this.size)},h.stshBox.prototype.write=function(o){var c;for(this.version=0,this.flags=0,this.size=4+8*this.shadowed_sample_numbers.length,this.writeHeader(o),o.writeUint32(this.shadowed_sample_numbers.length),c=0;c<this.shadowed_sample_numbers.length;c++)o.writeUint32(this.shadowed_sample_numbers[c]),o.writeUint32(this.sync_sample_numbers[c])},h.stssBox.prototype.write=function(o){this.version=0,this.flags=0,this.size=4+4*this.sample_numbers.length,this.writeHeader(o),o.writeUint32(this.sample_numbers.length),o.writeUint32Array(this.sample_numbers)},h.stszBox.prototype.write=function(o){var c,u=!0;if(this.version=0,this.flags=0,this.sample_sizes.length>0)for(c=0;c+1<this.sample_sizes.length;)if(this.sample_sizes[c+1]!==this.sample_sizes[0]){u=!1;break}else c++;else u=!1;this.size=8,u||(this.size+=4*this.sample_sizes.length),this.writeHeader(o),u?o.writeUint32(this.sample_sizes[0]):o.writeUint32(0),o.writeUint32(this.sample_sizes.length),u||o.writeUint32Array(this.sample_sizes)},h.sttsBox.prototype.write=function(o){var c;for(this.version=0,this.flags=0,this.size=4+8*this.sample_counts.length,this.writeHeader(o),o.writeUint32(this.sample_counts.length),c=0;c<this.sample_counts.length;c++)o.writeUint32(this.sample_counts[c]),o.writeUint32(this.sample_deltas[c])},h.tfdtBox.prototype.write=function(o){var c=Math.pow(2,32)-1;this.version=this.baseMediaDecodeTime>c?1:0,this.flags=0,this.size=4,this.version===1&&(this.size+=4),this.writeHeader(o),this.version===1?o.writeUint64(this.baseMediaDecodeTime):o.writeUint32(this.baseMediaDecodeTime)},h.tfhdBox.prototype.write=function(o){this.version=0,this.size=4,this.flags&h.TFHD_FLAG_BASE_DATA_OFFSET&&(this.size+=8),this.flags&h.TFHD_FLAG_SAMPLE_DESC&&(this.size+=4),this.flags&h.TFHD_FLAG_SAMPLE_DUR&&(this.size+=4),this.flags&h.TFHD_FLAG_SAMPLE_SIZE&&(this.size+=4),this.flags&h.TFHD_FLAG_SAMPLE_FLAGS&&(this.size+=4),this.writeHeader(o),o.writeUint32(this.track_id),this.flags&h.TFHD_FLAG_BASE_DATA_OFFSET&&o.writeUint64(this.base_data_offset),this.flags&h.TFHD_FLAG_SAMPLE_DESC&&o.writeUint32(this.default_sample_description_index),this.flags&h.TFHD_FLAG_SAMPLE_DUR&&o.writeUint32(this.default_sample_duration),this.flags&h.TFHD_FLAG_SAMPLE_SIZE&&o.writeUint32(this.default_sample_size),this.flags&h.TFHD_FLAG_SAMPLE_FLAGS&&o.writeUint32(this.default_sample_flags)},h.tkhdBox.prototype.write=function(o){this.version=0,this.size=80,this.writeHeader(o),o.writeUint32(this.creation_time),o.writeUint32(this.modification_time),o.writeUint32(this.track_id),o.writeUint32(0),o.writeUint32(this.duration),o.writeUint32(0),o.writeUint32(0),o.writeInt16(this.layer),o.writeInt16(this.alternate_group),o.writeInt16(this.volume<<8),o.writeUint16(0),o.writeInt32Array(this.matrix),o.writeUint32(this.width),o.writeUint32(this.height)},h.trexBox.prototype.write=function(o){this.version=0,this.flags=0,this.size=20,this.writeHeader(o),o.writeUint32(this.track_id),o.writeUint32(this.default_sample_description_index),o.writeUint32(this.default_sample_duration),o.writeUint32(this.default_sample_size),o.writeUint32(this.default_sample_flags)},h.trunBox.prototype.write=function(o){this.version=0,this.size=4,this.flags&h.TRUN_FLAGS_DATA_OFFSET&&(this.size+=4),this.flags&h.TRUN_FLAGS_FIRST_FLAG&&(this.size+=4),this.flags&h.TRUN_FLAGS_DURATION&&(this.size+=4*this.sample_duration.length),this.flags&h.TRUN_FLAGS_SIZE&&(this.size+=4*this.sample_size.length),this.flags&h.TRUN_FLAGS_FLAGS&&(this.size+=4*this.sample_flags.length),this.flags&h.TRUN_FLAGS_CTS_OFFSET&&(this.size+=4*this.sample_composition_time_offset.length),this.writeHeader(o),o.writeUint32(this.sample_count),this.flags&h.TRUN_FLAGS_DATA_OFFSET&&(this.data_offset_position=o.getPosition(),o.writeInt32(this.data_offset)),this.flags&h.TRUN_FLAGS_FIRST_FLAG&&o.writeUint32(this.first_sample_flags);for(var c=0;c<this.sample_count;c++)this.flags&h.TRUN_FLAGS_DURATION&&o.writeUint32(this.sample_duration[c]),this.flags&h.TRUN_FLAGS_SIZE&&o.writeUint32(this.sample_size[c]),this.flags&h.TRUN_FLAGS_FLAGS&&o.writeUint32(this.sample_flags[c]),this.flags&h.TRUN_FLAGS_CTS_OFFSET&&(this.version===0?o.writeUint32(this.sample_composition_time_offset[c]):o.writeInt32(this.sample_composition_time_offset[c]))},h["url Box"].prototype.write=function(o){this.version=0,this.location?(this.flags=0,this.size=this.location.length+1):(this.flags=1,this.size=0),this.writeHeader(o),this.location&&o.writeCString(this.location)},h["urn Box"].prototype.write=function(o){this.version=0,this.flags=0,this.size=this.name.length+1+(this.location?this.location.length+1:0),this.writeHeader(o),o.writeCString(this.name),this.location&&o.writeCString(this.location)},h.vmhdBox.prototype.write=function(o){this.version=0,this.flags=1,this.size=8,this.writeHeader(o),o.writeUint16(this.graphicsmode),o.writeUint16Array(this.opcolor)},h.vpcCBox.prototype.write=function(o){this.version=1;const c=8+this.codecIntializationDataSize;this.size=c,this.writeHeader(o),o.writeUint8(this.profile),o.writeUint8(this.level);let u=this.bitDepth<<4|(this.chromaSubsampling&7)<<1|this.videoFullRangeFlag&1;o.writeUint8(u),o.writeUint8(this.colourPrimaries),o.writeUint8(this.transferCharacteristics),o.writeUint8(this.matrixCoefficients),o.writeUint16(this.codecIntializationDataSize),this.codecIntializationDataSize>0&&o.writeUint8Array(this.codecIntializationData)},h.cttsBox.prototype.unpack=function(o){var c,u,p;for(p=0,c=0;c<this.sample_counts.length;c++)for(u=0;u<this.sample_counts[c];u++)o[p].pts=o[p].dts+this.sample_offsets[c],p++},h.sttsBox.prototype.unpack=function(o){var c,u,p;for(p=0,c=0;c<this.sample_counts.length;c++)for(u=0;u<this.sample_counts[c];u++)p===0?o[p].dts=0:o[p].dts=o[p-1].dts+this.sample_deltas[c],p++},h.stcoBox.prototype.unpack=function(o){var c;for(c=0;c<this.chunk_offsets.length;c++)o[c].offset=this.chunk_offsets[c]},h.stscBox.prototype.unpack=function(o){var c,u,p,_,b;for(_=0,b=0,c=0;c<this.first_chunk.length;c++)for(u=0;u<(c+1<this.first_chunk.length?this.first_chunk[c+1]:1/0);u++)for(b++,p=0;p<this.samples_per_chunk[c];p++){if(o[_])o[_].description_index=this.sample_description_index[c],o[_].chunk_index=b;else return;_++}},h.stszBox.prototype.unpack=function(o){var c;for(c=0;c<this.sample_sizes.length;c++)o[c].size=this.sample_sizes[c]},h.DIFF_BOXES_PROP_NAMES=["boxes","entries","references","subsamples","items","item_infos","extents","associations","subsegments","ranges","seekLists","seekPoints","esd","levels"],h.DIFF_PRIMITIVE_ARRAY_PROP_NAMES=["compatible_brands","matrix","opcolor","sample_counts","sample_counts","sample_deltas","first_chunk","samples_per_chunk","sample_sizes","chunk_offsets","sample_offsets","sample_description_index","sample_duration"],h.boxEqualFields=function(o,c){if(o&&!c)return!1;var u;for(u in o)if(!(h.DIFF_BOXES_PROP_NAMES.indexOf(u)>-1)){if(o[u]instanceof h.Box||c[u]instanceof h.Box)continue;if(typeof o[u]>"u"||typeof c[u]>"u")continue;if(typeof o[u]=="function"||typeof c[u]=="function")continue;if(o.subBoxNames&&o.subBoxNames.indexOf(u.slice(0,4))>-1||c.subBoxNames&&c.subBoxNames.indexOf(u.slice(0,4))>-1)continue;if(u==="data"||u==="start"||u==="size"||u==="creation_time"||u==="modification_time")continue;if(h.DIFF_PRIMITIVE_ARRAY_PROP_NAMES.indexOf(u)>-1)continue;if(o[u]!==c[u])return!1}return!0},h.boxEqual=function(o,c){if(!h.boxEqualFields(o,c))return!1;for(var u=0;u<h.DIFF_BOXES_PROP_NAMES.length;u++){var p=h.DIFF_BOXES_PROP_NAMES[u];if(o[p]&&c[p]&&!h.boxEqual(o[p],c[p]))return!1}return!0};var m=function(){};m.prototype.parseSample=function(o){var c={},u;c.resources=[];var p=new e(o.data.buffer);if(!o.subsamples||o.subsamples.length===0)c.documentString=p.readString(o.data.length);else if(c.documentString=p.readString(o.subsamples[0].size),o.subsamples.length>1)for(u=1;u<o.subsamples.length;u++)c.resources[u]=p.readUint8Array(o.subsamples[u].size);return typeof DOMParser<"u"&&(c.document=new DOMParser().parseFromString(c.documentString,"application/xml")),c};var g=function(){};g.prototype.parseSample=function(o){var c,u=new e(o.data.buffer);return c=u.readString(o.data.length),c},g.prototype.parseConfig=function(o){var c,u=new e(o.buffer);return u.readUint32(),c=u.readCString(),c},s.XMLSubtitlein4Parser=m,s.Textin4Parser=g;var y=function(o){this.stream=o||new a,this.boxes=[],this.mdats=[],this.moofs=[],this.isProgressive=!1,this.moovStartFound=!1,this.onMoovStart=null,this.moovStartSent=!1,this.onReady=null,this.readySent=!1,this.onSegment=null,this.onSamples=null,this.onError=null,this.sampleListBuilt=!1,this.fragmentedTracks=[],this.extractedTracks=[],this.isFragmentationInitialized=!1,this.sampleProcessingStarted=!1,this.nextMoofNumber=0,this.itemListBuilt=!1,this.onSidx=null,this.sidxSent=!1};y.prototype.setSegmentOptions=function(o,c,u){var p=this.getTrackById(o);if(p){var _={};this.fragmentedTracks.push(_),_.id=o,_.user=c,_.trak=p,p.nextSample=0,_.segmentStream=null,_.nb_samples=1e3,_.rapAlignement=!0,u&&(u.nbSamples&&(_.nb_samples=u.nbSamples),u.rapAlignement&&(_.rapAlignement=u.rapAlignement))}},y.prototype.unsetSegmentOptions=function(o){for(var c=-1,u=0;u<this.fragmentedTracks.length;u++){var p=this.fragmentedTracks[u];p.id==o&&(c=u)}c>-1&&this.fragmentedTracks.splice(c,1)},y.prototype.setExtractionOptions=function(o,c,u){var p=this.getTrackById(o);if(p){var _={};this.extractedTracks.push(_),_.id=o,_.user=c,_.trak=p,p.nextSample=0,_.nb_samples=1e3,_.samples=[],u&&u.nbSamples&&(_.nb_samples=u.nbSamples)}},y.prototype.unsetExtractionOptions=function(o){for(var c=-1,u=0;u<this.extractedTracks.length;u++){var p=this.extractedTracks[u];p.id==o&&(c=u)}c>-1&&this.extractedTracks.splice(c,1)},y.prototype.parse=function(){var o,c,u=!1;if(!(this.restoreParsePosition&&!this.restoreParsePosition()))for(;;)if(this.hasIncompleteMdat&&this.hasIncompleteMdat()){if(this.processIncompleteMdat())continue;return}else if(this.saveParsePosition&&this.saveParsePosition(),o=h.parseOneBox(this.stream,u),o.code===h.ERR_NOT_ENOUGH_DATA)if(this.processIncompleteBox){if(this.processIncompleteBox(o))continue;return}else return;else{var p;switch(c=o.box,p=c.type!=="uuid"?c.type:c.uuid,this.boxes.push(c),p){case"mdat":this.mdats.push(c);break;case"moof":this.moofs.push(c);break;case"moov":this.moovStartFound=!0,this.mdats.length===0&&(this.isProgressive=!0);default:this[p]!==void 0&&t.warn("ISOFile","Duplicate Box of type: "+p+", overriding previous occurrence"),this[p]=c;break}this.updateUsedBytes&&this.updateUsedBytes(c,o)}},y.prototype.checkBuffer=function(o){if(o==null)throw"Buffer must be defined and non empty";if(o.fileStart===void 0)throw"Buffer must have a fileStart property";return o.byteLength===0?(t.warn("ISOFile","Ignoring empty buffer (fileStart: "+o.fileStart+")"),this.stream.logBufferLevel(),!1):(t.info("ISOFile","Processing buffer (fileStart: "+o.fileStart+")"),o.usedBytes=0,this.stream.insertBuffer(o),this.stream.logBufferLevel(),this.stream.initialized()?!0:(t.warn("ISOFile","Not ready to start parsing"),!1))},y.prototype.appendBuffer=function(o,c){var u;if(this.checkBuffer(o))return this.parse(),this.moovStartFound&&!this.moovStartSent&&(this.moovStartSent=!0,this.onMoovStart&&this.onMoovStart()),this.moov?(this.sampleListBuilt||(this.buildSampleLists(),this.sampleListBuilt=!0),this.updateSampleLists(),this.onReady&&!this.readySent&&(this.readySent=!0,this.onReady(this.getInfo())),this.processSamples(c),this.nextSeekPosition?(u=this.nextSeekPosition,this.nextSeekPosition=void 0):u=this.nextParsePosition,this.stream.getEndFilePositionAfter&&(u=this.stream.getEndFilePositionAfter(u))):this.nextParsePosition?u=this.nextParsePosition:u=0,this.sidx&&this.onSidx&&!this.sidxSent&&(this.onSidx(this.sidx),this.sidxSent=!0),this.meta&&(this.flattenItemInfo&&!this.itemListBuilt&&(this.flattenItemInfo(),this.itemListBuilt=!0),this.processItems&&this.processItems(this.onItem)),this.stream.cleanBuffers&&(t.info("ISOFile","Done processing buffer (fileStart: "+o.fileStart+") - next buffer to fetch should have a fileStart position of "+u),this.stream.logBufferLevel(),this.stream.cleanBuffers(),this.stream.logBufferLevel(!0),t.info("ISOFile","Sample data size in memory: "+this.getAllocatedSampleDataSize())),u},y.prototype.getInfo=function(){var o,c,u={},p,_,b,v,w=new Date("1904-01-01T00:00:00Z").getTime();if(this.moov)for(u.hasMoov=!0,u.duration=this.moov.mvhd.duration,u.timescale=this.moov.mvhd.timescale,u.isFragmented=this.moov.mvex!=null,u.isFragmented&&this.moov.mvex.mehd&&(u.fragment_duration=this.moov.mvex.mehd.fragment_duration),u.isProgressive=this.isProgressive,u.hasIOD=this.moov.iods!=null,u.brands=[],u.brands.push(this.ftyp.major_brand),u.brands=u.brands.concat(this.ftyp.compatible_brands),u.created=new Date(w+this.moov.mvhd.creation_time*1e3),u.modified=new Date(w+this.moov.mvhd.modification_time*1e3),u.tracks=[],u.audioTracks=[],u.videoTracks=[],u.subtitleTracks=[],u.metadataTracks=[],u.hintTracks=[],u.otherTracks=[],o=0;o<this.moov.traks.length;o++){if(p=this.moov.traks[o],v=p.mdia.minf.stbl.stsd.entries[0],_={},u.tracks.push(_),_.id=p.tkhd.track_id,_.name=p.mdia.hdlr.name,_.references=[],p.tref)for(c=0;c<p.tref.boxes.length;c++)b={},_.references.push(b),b.type=p.tref.boxes[c].type,b.track_ids=p.tref.boxes[c].track_ids;p.edts&&(_.edits=p.edts.elst.entries),_.created=new Date(w+p.tkhd.creation_time*1e3),_.modified=new Date(w+p.tkhd.modification_time*1e3),_.movie_duration=p.tkhd.duration,_.movie_timescale=u.timescale,_.layer=p.tkhd.layer,_.alternate_group=p.tkhd.alternate_group,_.volume=p.tkhd.volume,_.matrix=p.tkhd.matrix,_.track_width=p.tkhd.width/65536,_.track_height=p.tkhd.height/65536,_.timescale=p.mdia.mdhd.timescale,_.cts_shift=p.mdia.minf.stbl.cslg,_.duration=p.mdia.mdhd.duration,_.samples_duration=p.samples_duration,_.codec=v.getCodec(),_.kind=p.udta&&p.udta.kinds.length?p.udta.kinds[0]:{schemeURI:"",value:""},_.language=p.mdia.elng?p.mdia.elng.extended_language:p.mdia.mdhd.languageString,_.nb_samples=p.samples.length,_.size=p.samples_size,_.bitrate=_.size*8*_.timescale/_.samples_duration,v.isAudio()?(_.type="audio",u.audioTracks.push(_),_.audio={},_.audio.sample_rate=v.getSampleRate(),_.audio.channel_count=v.getChannelCount(),_.audio.sample_size=v.getSampleSize()):v.isVideo()?(_.type="video",u.videoTracks.push(_),_.video={},_.video.width=v.getWidth(),_.video.height=v.getHeight()):v.isSubtitle()?(_.type="subtitles",u.subtitleTracks.push(_)):v.isHint()?(_.type="metadata",u.hintTracks.push(_)):v.isMetadata()?(_.type="metadata",u.metadataTracks.push(_)):(_.type="metadata",u.otherTracks.push(_))}else u.hasMoov=!1;if(u.mime="",u.hasMoov&&u.tracks){for(u.videoTracks&&u.videoTracks.length>0?u.mime+='video/mp4; codecs="':u.audioTracks&&u.audioTracks.length>0?u.mime+='audio/mp4; codecs="':u.mime+='application/mp4; codecs="',o=0;o<u.tracks.length;o++)o!==0&&(u.mime+=","),u.mime+=u.tracks[o].codec;u.mime+='"; profiles="',u.mime+=this.ftyp.compatible_brands.join(),u.mime+='"'}return u},y.prototype.setNextSeekPositionFromSample=function(o){o&&(this.nextSeekPosition?this.nextSeekPosition=Math.min(o.offset+o.alreadyRead,this.nextSeekPosition):this.nextSeekPosition=o.offset+o.alreadyRead)},y.prototype.processSamples=function(o){var c,u;if(this.sampleProcessingStarted){if(this.isFragmentationInitialized&&this.onSegment!==null)for(c=0;c<this.fragmentedTracks.length;c++){var p=this.fragmentedTracks[c];for(u=p.trak;u.nextSample<u.samples.length&&this.sampleProcessingStarted;){t.debug("ISOFile","Creating media fragment on track #"+p.id+" for sample "+u.nextSample);var _=this.createFragment(p.id,u.nextSample,p.segmentStream);if(_)p.segmentStream=_,u.nextSample++;else break;if((u.nextSample%p.nb_samples===0||o||u.nextSample>=u.samples.length)&&(t.info("ISOFile","Sending fragmented data on track #"+p.id+" for samples ["+Math.max(0,u.nextSample-p.nb_samples)+","+(u.nextSample-1)+"]"),t.info("ISOFile","Sample data size in memory: "+this.getAllocatedSampleDataSize()),this.onSegment&&this.onSegment(p.id,p.user,p.segmentStream.buffer,u.nextSample,o||u.nextSample>=u.samples.length),p.segmentStream=null,p!==this.fragmentedTracks[c]))break}}if(this.onSamples!==null)for(c=0;c<this.extractedTracks.length;c++){var b=this.extractedTracks[c];for(u=b.trak;u.nextSample<u.samples.length&&this.sampleProcessingStarted;){t.debug("ISOFile","Exporting on track #"+b.id+" sample #"+u.nextSample);var v=this.getSample(u,u.nextSample);if(v)u.nextSample++,b.samples.push(v);else{this.setNextSeekPositionFromSample(u.samples[u.nextSample]);break}if((u.nextSample%b.nb_samples===0||u.nextSample>=u.samples.length)&&(t.debug("ISOFile","Sending samples on track #"+b.id+" for sample "+u.nextSample),this.onSamples&&this.onSamples(b.id,b.user,b.samples),b.samples=[],b!==this.extractedTracks[c]))break}}}},y.prototype.getBox=function(o){var c=this.getBoxes(o,!0);return c.length?c[0]:null},y.prototype.getBoxes=function(o,c){var u=[];return y._sweep.call(this,o,u,c),u},y._sweep=function(o,c,u){this.type&&this.type==o&&c.push(this);for(var p in this.boxes){if(c.length&&u)return;y._sweep.call(this.boxes[p],o,c,u)}},y.prototype.getTrackSamplesInfo=function(o){var c=this.getTrackById(o);if(c)return c.samples},y.prototype.getTrackSample=function(o,c){var u=this.getTrackById(o),p=this.getSample(u,c);return p},y.prototype.releaseUsedSamples=function(o,c){var u=0,p=this.getTrackById(o);p.lastValidSample||(p.lastValidSample=0);for(var _=p.lastValidSample;_<c;_++)u+=this.releaseSample(p,_);t.info("ISOFile","Track #"+o+" released samples up to "+c+" (released size: "+u+", remaining: "+this.samplesDataSize+")"),p.lastValidSample=c},y.prototype.start=function(){this.sampleProcessingStarted=!0,this.processSamples(!1)},y.prototype.stop=function(){this.sampleProcessingStarted=!1},y.prototype.flush=function(){t.info("ISOFile","Flushing remaining samples"),this.updateSampleLists(),this.processSamples(!0),this.stream.cleanBuffers(),this.stream.logBufferLevel(!0)},y.prototype.seekTrack=function(o,c,u){var p,_,b=1/0,v=0,w=0,S;if(u.samples.length===0)return t.info("ISOFile","No sample in track, cannot seek! Using time "+t.getDurationString(0,1)+" and offset: 0"),{offset:0,time:0};for(p=0;p<u.samples.length;p++){if(_=u.samples[p],p===0)w=0,S=_.timescale;else if(_.cts>o*_.timescale){w=p-1;break}c&&_.is_sync&&(v=p)}for(c&&(w=v),o=u.samples[w].cts,u.nextSample=w;u.samples[w].alreadyRead===u.samples[w].size&&u.samples[w+1];)w++;return b=u.samples[w].offset+u.samples[w].alreadyRead,t.info("ISOFile","Seeking to "+(c?"RAP":"")+" sample #"+u.nextSample+" on track "+u.tkhd.track_id+", time "+t.getDurationString(o,S)+" and offset: "+b),{offset:b,time:o/S}},y.prototype.getTrackDuration=function(o){var c;return o.samples?(c=o.samples[o.samples.length-1],(c.cts+c.duration)/c.timescale):1/0},y.prototype.seek=function(o,c){var u=this.moov,p,_,b,v={offset:1/0,time:1/0};if(this.moov){for(b=0;b<u.traks.length;b++)p=u.traks[b],!(o>this.getTrackDuration(p))&&(_=this.seekTrack(o,c,p),_.offset<v.offset&&(v.offset=_.offset),_.time<v.time&&(v.time=_.time));return t.info("ISOFile","Seeking at time "+t.getDurationString(v.time,1)+" needs a buffer with a fileStart position of "+v.offset),v.offset===1/0?v={offset:this.nextParsePosition,time:0}:v.offset=this.stream.getEndFilePositionAfter(v.offset),t.info("ISOFile","Adjusted seek position (after checking data already in buffer): "+v.offset),v}else throw"Cannot seek: moov not received!"},y.prototype.equal=function(o){for(var c=0;c<this.boxes.length&&c<o.boxes.length;){var u=this.boxes[c],p=o.boxes[c];if(!h.boxEqual(u,p))return!1;c++}return!0},s.ISOFile=y,y.prototype.lastBoxStartPosition=0,y.prototype.parsingMdat=null,y.prototype.nextParsePosition=0,y.prototype.discardMdatData=!1,y.prototype.processIncompleteBox=function(o){var c,u,p;return o.type==="mdat"?(c=new h[o.type+"Box"](o.size),this.parsingMdat=c,this.boxes.push(c),this.mdats.push(c),c.start=o.start,c.hdr_size=o.hdr_size,this.stream.addUsedBytes(c.hdr_size),this.lastBoxStartPosition=c.start+c.size,p=this.stream.seek(c.start+c.size,!1,this.discardMdatData),p?(this.parsingMdat=null,!0):(this.moovStartFound?this.nextParsePosition=this.stream.findEndContiguousBuf():this.nextParsePosition=c.start+c.size,!1)):(o.type==="moov"&&(this.moovStartFound=!0,this.mdats.length===0&&(this.isProgressive=!0)),u=this.stream.mergeNextBuffer?this.stream.mergeNextBuffer():!1,u?(this.nextParsePosition=this.stream.getEndPosition(),!0):(o.type?this.moovStartFound?this.nextParsePosition=this.stream.getEndPosition():this.nextParsePosition=this.stream.getPosition()+o.size:this.nextParsePosition=this.stream.getEndPosition(),!1))},y.prototype.hasIncompleteMdat=function(){return this.parsingMdat!==null},y.prototype.processIncompleteMdat=function(){var o,c;return o=this.parsingMdat,c=this.stream.seek(o.start+o.size,!1,this.discardMdatData),c?(t.debug("ISOFile","Found 'mdat' end in buffered data"),this.parsingMdat=null,!0):(this.nextParsePosition=this.stream.findEndContiguousBuf(),!1)},y.prototype.restoreParsePosition=function(){return this.stream.seek(this.lastBoxStartPosition,!0,this.discardMdatData)},y.prototype.saveParsePosition=function(){this.lastBoxStartPosition=this.stream.getPosition()},y.prototype.updateUsedBytes=function(o,c){this.stream.addUsedBytes&&(o.type==="mdat"?(this.stream.addUsedBytes(o.hdr_size),this.discardMdatData&&this.stream.addUsedBytes(o.size-o.hdr_size)):this.stream.addUsedBytes(o.size))},y.prototype.add=h.Box.prototype.add,y.prototype.addBox=h.Box.prototype.addBox,y.prototype.init=function(o){var c=o||{};this.add("ftyp").set("major_brand",c.brands&&c.brands[0]||"iso4").set("minor_version",0).set("compatible_brands",c.brands||["iso4"]);var u=this.add("moov");return u.add("mvhd").set("timescale",c.timescale||600).set("rate",c.rate||65536).set("creation_time",0).set("modification_time",0).set("duration",c.duration||0).set("volume",c.width?0:256).set("matrix",[65536,0,0,0,65536,0,0,0,1073741824]).set("next_track_id",1),u.add("mvex"),this},y.prototype.addTrack=function(o){this.moov||this.init(o);var c=o||{};c.width=c.width||320,c.height=c.height||320,c.id=c.id||this.moov.mvhd.next_track_id,c.type=c.type||"avc1";var u=this.moov.add("trak");this.moov.mvhd.next_track_id=c.id+1,u.add("tkhd").set("flags",h.TKHD_FLAG_ENABLED|h.TKHD_FLAG_IN_MOVIE|h.TKHD_FLAG_IN_PREVIEW).set("creation_time",0).set("modification_time",0).set("track_id",c.id).set("duration",c.duration||0).set("layer",c.layer||0).set("alternate_group",0).set("volume",1).set("matrix",[65536,0,0,0,65536,0,0,0,1073741824]).set("width",c.width<<16).set("height",c.height<<16);var p=u.add("mdia");p.add("mdhd").set("creation_time",0).set("modification_time",0).set("timescale",c.timescale||1).set("duration",c.media_duration||0).set("language",c.language||"und"),p.add("hdlr").set("handler",c.hdlr||"vide").set("name",c.name||"Track created with MP4Box.js"),p.add("elng").set("extended_language",c.language||"fr-FR");var _=p.add("minf");if(h[c.type+"SampleEntry"]!==void 0){var b=new h[c.type+"SampleEntry"];b.data_reference_index=1;var v="";for(var w in h.sampleEntryCodes)for(var S=h.sampleEntryCodes[w],T=0;T<S.length;T++)if(S.indexOf(c.type)>-1){v=w;break}switch(v){case"Visual":if(_.add("vmhd").set("graphicsmode",0).set("opcolor",[0,0,0]),b.set("width",c.width).set("height",c.height).set("horizresolution",72<<16).set("vertresolution",72<<16).set("frame_count",1).set("compressorname",c.type+" Compressor").set("depth",24),c.avcDecoderConfigRecord){var E=new h.avcCBox;E.parse(new e(c.avcDecoderConfigRecord)),b.addBox(E)}else if(c.hevcDecoderConfigRecord){var P=new h.hvcCBox;P.parse(new e(c.hevcDecoderConfigRecord)),b.addBox(P)}else if(c.vpcDecoderConfigRecord){var B=new h.vpcCBox;B.parse(new e(c.vpcDecoderConfigRecord)),b.addBox(B)}break;case"Audio":_.add("smhd").set("balance",c.balance||0),b.set("channel_count",c.channel_count||2).set("samplesize",c.samplesize||16).set("samplerate",c.samplerate||65536);break;case"Hint":_.add("hmhd");break;case"Subtitle":switch(_.add("sthd"),c.type){case"stpp":b.set("namespace",c.namespace||"nonamespace").set("schema_location",c.schema_location||"").set("auxiliary_mime_types",c.auxiliary_mime_types||"");break}break;case"Metadata":_.add("nmhd");break;case"System":_.add("nmhd");break;default:_.add("nmhd");break}c.description&&b.addBox(c.description),c.description_boxes&&c.description_boxes.forEach(function(G){b.addBox(G)}),_.add("dinf").add("dref").addEntry(new h["url Box"]().set("flags",1));var A=_.add("stbl");return A.add("stsd").addEntry(b),A.add("stts").set("sample_counts",[]).set("sample_deltas",[]),A.add("stsc").set("first_chunk",[]).set("samples_per_chunk",[]).set("sample_description_index",[]),A.add("stco").set("chunk_offsets",[]),A.add("stsz").set("sample_sizes",[]),this.moov.mvex.add("trex").set("track_id",c.id).set("default_sample_description_index",c.default_sample_description_index||1).set("default_sample_duration",c.default_sample_duration||0).set("default_sample_size",c.default_sample_size||0).set("default_sample_flags",c.default_sample_flags||0),this.buildTrakSampleLists(u),c.id}},h.Box.prototype.computeSize=function(o){var c=o||new r;c.endianness=r.BIG_ENDIAN,this.write(c)},y.prototype.addSample=function(o,c,u){var p=u||{},_={},b=this.getTrackById(o);if(b!==null){_.number=b.samples.length,_.track_id=b.tkhd.track_id,_.timescale=b.mdia.mdhd.timescale,_.description_index=p.sample_description_index?p.sample_description_index-1:0,_.description=b.mdia.minf.stbl.stsd.entries[_.description_index],_.data=c,_.size=c.byteLength,_.alreadyRead=_.size,_.duration=p.duration||1,_.cts=p.cts||0,_.dts=p.dts||0,_.is_sync=p.is_sync||!1,_.is_leading=p.is_leading||0,_.depends_on=p.depends_on||0,_.is_depended_on=p.is_depended_on||0,_.has_redundancy=p.has_redundancy||0,_.degradation_priority=p.degradation_priority||0,_.offset=0,_.subsamples=p.subsamples,b.samples.push(_),b.samples_size+=_.size,b.samples_duration+=_.duration,b.first_dts===void 0&&(b.first_dts=p.dts),this.processSamples();var v=this.createSingleSampleMoof(_);return this.addBox(v),v.computeSize(),v.trafs[0].truns[0].data_offset=v.size+8,this.add("mdat").data=new Uint8Array(c),_}},y.prototype.createSingleSampleMoof=function(o){var c=0;o.is_sync?c=1<<25:c=65536;var u=new h.moofBox;u.add("mfhd").set("sequence_number",this.nextMoofNumber),this.nextMoofNumber++;var p=u.add("traf"),_=this.getTrackById(o.track_id);return p.add("tfhd").set("track_id",o.track_id).set("flags",h.TFHD_FLAG_DEFAULT_BASE_IS_MOOF),p.add("tfdt").set("baseMediaDecodeTime",o.dts-(_.first_dts||0)),p.add("trun").set("flags",h.TRUN_FLAGS_DATA_OFFSET|h.TRUN_FLAGS_DURATION|h.TRUN_FLAGS_SIZE|h.TRUN_FLAGS_FLAGS|h.TRUN_FLAGS_CTS_OFFSET).set("data_offset",0).set("first_sample_flags",0).set("sample_count",1).set("sample_duration",[o.duration]).set("sample_size",[o.size]).set("sample_flags",[c]).set("sample_composition_time_offset",[o.cts-o.dts]),u},y.prototype.lastMoofIndex=0,y.prototype.samplesDataSize=0,y.prototype.resetTables=function(){var o,c,u,p,_,b,v,w;for(this.initial_duration=this.moov.mvhd.duration,this.moov.mvhd.duration=0,o=0;o<this.moov.traks.length;o++){c=this.moov.traks[o],c.tkhd.duration=0,c.mdia.mdhd.duration=0,u=c.mdia.minf.stbl.stco||c.mdia.minf.stbl.co64,u.chunk_offsets=[],p=c.mdia.minf.stbl.stsc,p.first_chunk=[],p.samples_per_chunk=[],p.sample_description_index=[],_=c.mdia.minf.stbl.stsz||c.mdia.minf.stbl.stz2,_.sample_sizes=[],b=c.mdia.minf.stbl.stts,b.sample_counts=[],b.sample_deltas=[],v=c.mdia.minf.stbl.ctts,v&&(v.sample_counts=[],v.sample_offsets=[]),w=c.mdia.minf.stbl.stss;var S=c.mdia.minf.stbl.boxes.indexOf(w);S!=-1&&(c.mdia.minf.stbl.boxes[S]=null)}},y.initSampleGroups=function(o,c,u,p,_){var b,v,w,S;function T(E,P,B){this.grouping_type=E,this.grouping_type_parameter=P,this.sbgp=B,this.last_sample_in_run=-1,this.entry_index=-1}for(c&&(c.sample_groups_info=[]),o.sample_groups_info||(o.sample_groups_info=[]),v=0;v<u.length;v++){for(S=u[v].grouping_type+"/"+u[v].grouping_type_parameter,w=new T(u[v].grouping_type,u[v].grouping_type_parameter,u[v]),c&&(c.sample_groups_info[S]=w),o.sample_groups_info[S]||(o.sample_groups_info[S]=w),b=0;b<p.length;b++)p[b].grouping_type===u[v].grouping_type&&(w.description=p[b],w.description.used=!0);if(_)for(b=0;b<_.length;b++)_[b].grouping_type===u[v].grouping_type&&(w.fragment_description=_[b],w.fragment_description.used=!0,w.is_fragment=!0)}if(c){if(_)for(v=0;v<_.length;v++)!_[v].used&&_[v].version>=2&&(S=_[v].grouping_type+"/0",w=new T(_[v].grouping_type,0),w.is_fragment=!0,c.sample_groups_info[S]||(c.sample_groups_info[S]=w))}else for(v=0;v<p.length;v++)!p[v].used&&p[v].version>=2&&(S=p[v].grouping_type+"/0",w=new T(p[v].grouping_type,0),o.sample_groups_info[S]||(o.sample_groups_info[S]=w))},y.setSampleGroupProperties=function(o,c,u,p){var _,b;c.sample_groups=[];for(_ in p)if(c.sample_groups[_]={},c.sample_groups[_].grouping_type=p[_].grouping_type,c.sample_groups[_].grouping_type_parameter=p[_].grouping_type_parameter,u>=p[_].last_sample_in_run&&(p[_].last_sample_in_run<0&&(p[_].last_sample_in_run=0),p[_].entry_index++,p[_].entry_index<=p[_].sbgp.entries.length-1&&(p[_].last_sample_in_run+=p[_].sbgp.entries[p[_].entry_index].sample_count)),p[_].entry_index<=p[_].sbgp.entries.length-1?c.sample_groups[_].group_description_index=p[_].sbgp.entries[p[_].entry_index].group_description_index:c.sample_groups[_].group_description_index=-1,c.sample_groups[_].group_description_index!==0){var v;p[_].fragment_description?v=p[_].fragment_description:v=p[_].description,c.sample_groups[_].group_description_index>0?(c.sample_groups[_].group_description_index>65535?b=(c.sample_groups[_].group_description_index>>16)-1:b=c.sample_groups[_].group_description_index-1,v&&b>=0&&(c.sample_groups[_].description=v.entries[b])):v&&v.version>=2&&v.default_group_description_index>0&&(c.sample_groups[_].description=v.entries[v.default_group_description_index-1])}},y.process_sdtp=function(o,c,u){c&&(o?(c.is_leading=o.is_leading[u],c.depends_on=o.sample_depends_on[u],c.is_depended_on=o.sample_is_depended_on[u],c.has_redundancy=o.sample_has_redundancy[u]):(c.is_leading=0,c.depends_on=0,c.is_depended_on=0,c.has_redundancy=0))},y.prototype.buildSampleLists=function(){var o,c;for(o=0;o<this.moov.traks.length;o++)c=this.moov.traks[o],this.buildTrakSampleLists(c)},y.prototype.buildTrakSampleLists=function(o){var c,u,p,_,b,v,w,S,T,E,P,B,A,G,O,j,Gt,U,R,wt,V,Ot,St,Xt;if(o.samples=[],o.samples_duration=0,o.samples_size=0,u=o.mdia.minf.stbl.stco||o.mdia.minf.stbl.co64,p=o.mdia.minf.stbl.stsc,_=o.mdia.minf.stbl.stsz||o.mdia.minf.stbl.stz2,b=o.mdia.minf.stbl.stts,v=o.mdia.minf.stbl.ctts,w=o.mdia.minf.stbl.stss,S=o.mdia.minf.stbl.stsd,T=o.mdia.minf.stbl.subs,B=o.mdia.minf.stbl.stdp,E=o.mdia.minf.stbl.sbgps,P=o.mdia.minf.stbl.sgpds,U=-1,R=-1,wt=-1,V=-1,Ot=0,St=0,Xt=0,y.initSampleGroups(o,null,E,P),!(typeof _>"u")){for(c=0;c<_.sample_sizes.length;c++){var N={};N.number=c,N.track_id=o.tkhd.track_id,N.timescale=o.mdia.mdhd.timescale,N.alreadyRead=0,o.samples[c]=N,N.size=_.sample_sizes[c],o.samples_size+=N.size,c===0?(G=1,A=0,N.chunk_index=G,N.chunk_run_index=A,Gt=p.samples_per_chunk[A],j=0,A+1<p.first_chunk.length?O=p.first_chunk[A+1]-1:O=1/0):c<Gt?(N.chunk_index=G,N.chunk_run_index=A):(G++,N.chunk_index=G,j=0,G<=O||(A++,A+1<p.first_chunk.length?O=p.first_chunk[A+1]-1:O=1/0),N.chunk_run_index=A,Gt+=p.samples_per_chunk[A]),N.description_index=p.sample_description_index[N.chunk_run_index]-1,N.description=S.entries[N.description_index],N.offset=u.chunk_offsets[N.chunk_index-1]+j,j+=N.size,c>U&&(R++,U<0&&(U=0),U+=b.sample_counts[R]),c>0?(o.samples[c-1].duration=b.sample_deltas[R],o.samples_duration+=o.samples[c-1].duration,N.dts=o.samples[c-1].dts+o.samples[c-1].duration):N.dts=0,v?(c>=wt&&(V++,wt<0&&(wt=0),wt+=v.sample_counts[V]),N.cts=o.samples[c].dts+v.sample_offsets[V]):N.cts=N.dts,w?(c==w.sample_numbers[Ot]-1?(N.is_sync=!0,Ot++):(N.is_sync=!1,N.degradation_priority=0),T&&T.entries[St].sample_delta+Xt==c+1&&(N.subsamples=T.entries[St].subsamples,Xt+=T.entries[St].sample_delta,St++)):N.is_sync=!0,y.process_sdtp(o.mdia.minf.stbl.sdtp,N,N.number),B?N.degradation_priority=B.priority[c]:N.degradation_priority=0,T&&T.entries[St].sample_delta+Xt==c&&(N.subsamples=T.entries[St].subsamples,Xt+=T.entries[St].sample_delta),(E.length>0||P.length>0)&&y.setSampleGroupProperties(o,N,c,o.sample_groups_info)}c>0&&(o.samples[c-1].duration=Math.max(o.mdia.mdhd.duration-o.samples[c-1].dts,0),o.samples_duration+=o.samples[c-1].duration)}},y.prototype.updateSampleLists=function(){var o,c,u,p,_,b,v,w,S,T,E,P,B,A,G;if(this.moov!==void 0){for(;this.lastMoofIndex<this.moofs.length;)if(S=this.moofs[this.lastMoofIndex],this.lastMoofIndex++,S.type=="moof")for(T=S,o=0;o<T.trafs.length;o++){for(E=T.trafs[o],P=this.getTrackById(E.tfhd.track_id),P.samples==null&&(P.samples=[]),B=this.getTrexById(E.tfhd.track_id),E.tfhd.flags&h.TFHD_FLAG_SAMPLE_DESC?p=E.tfhd.default_sample_description_index:p=B?B.default_sample_description_index:1,E.tfhd.flags&h.TFHD_FLAG_SAMPLE_DUR?_=E.tfhd.default_sample_duration:_=B?B.default_sample_duration:0,E.tfhd.flags&h.TFHD_FLAG_SAMPLE_SIZE?b=E.tfhd.default_sample_size:b=B?B.default_sample_size:0,E.tfhd.flags&h.TFHD_FLAG_SAMPLE_FLAGS?v=E.tfhd.default_sample_flags:v=B?B.default_sample_flags:0,E.sample_number=0,E.sbgps.length>0&&y.initSampleGroups(P,E,E.sbgps,P.mdia.minf.stbl.sgpds,E.sgpds),c=0;c<E.truns.length;c++){var O=E.truns[c];for(u=0;u<O.sample_count;u++){A={},A.moof_number=this.lastMoofIndex,A.number_in_traf=E.sample_number,E.sample_number++,A.number=P.samples.length,E.first_sample_index=P.samples.length,P.samples.push(A),A.track_id=P.tkhd.track_id,A.timescale=P.mdia.mdhd.timescale,A.description_index=p-1,A.description=P.mdia.minf.stbl.stsd.entries[A.description_index],A.size=b,O.flags&h.TRUN_FLAGS_SIZE&&(A.size=O.sample_size[u]),P.samples_size+=A.size,A.duration=_,O.flags&h.TRUN_FLAGS_DURATION&&(A.duration=O.sample_duration[u]),P.samples_duration+=A.duration,P.first_traf_merged||u>0?A.dts=P.samples[P.samples.length-2].dts+P.samples[P.samples.length-2].duration:(E.tfdt?A.dts=E.tfdt.baseMediaDecodeTime:A.dts=0,P.first_traf_merged=!0),A.cts=A.dts,O.flags&h.TRUN_FLAGS_CTS_OFFSET&&(A.cts=A.dts+O.sample_composition_time_offset[u]),G=v,O.flags&h.TRUN_FLAGS_FLAGS?G=O.sample_flags[u]:u===0&&O.flags&h.TRUN_FLAGS_FIRST_FLAG&&(G=O.first_sample_flags),A.is_sync=!(G>>16&1),A.is_leading=G>>26&3,A.depends_on=G>>24&3,A.is_depended_on=G>>22&3,A.has_redundancy=G>>20&3,A.degradation_priority=G&65535;var j=!!(E.tfhd.flags&h.TFHD_FLAG_BASE_DATA_OFFSET),Gt=!!(E.tfhd.flags&h.TFHD_FLAG_DEFAULT_BASE_IS_MOOF),U=!!(O.flags&h.TRUN_FLAGS_DATA_OFFSET),R=0;j?R=E.tfhd.base_data_offset:Gt||c===0?R=T.start:R=w,c===0&&u===0?U?A.offset=R+O.data_offset:A.offset=R:A.offset=w,w=A.offset+A.size,(E.sbgps.length>0||E.sgpds.length>0||P.mdia.minf.stbl.sbgps.length>0||P.mdia.minf.stbl.sgpds.length>0)&&y.setSampleGroupProperties(P,A,A.number_in_traf,E.sample_groups_info)}}if(E.subs){P.has_fragment_subsamples=!0;var wt=E.first_sample_index;for(c=0;c<E.subs.entries.length;c++)wt+=E.subs.entries[c].sample_delta,A=P.samples[wt-1],A.subsamples=E.subs.entries[c].subsamples}}}},y.prototype.getSample=function(o,c){var u,p=o.samples[c];if(!this.moov)return null;if(!p.data)p.data=new Uint8Array(p.size),p.alreadyRead=0,this.samplesDataSize+=p.size,t.debug("ISOFile","Allocating sample #"+c+" on track #"+o.tkhd.track_id+" of size "+p.size+" (total: "+this.samplesDataSize+")");else if(p.alreadyRead==p.size)return p;for(;;){var _=this.stream.findPosition(!0,p.offset+p.alreadyRead,!1);if(_>-1){u=this.stream.buffers[_];var b=u.byteLength-(p.offset+p.alreadyRead-u.fileStart);if(p.size-p.alreadyRead<=b)return t.debug("ISOFile","Getting sample #"+c+" data (alreadyRead: "+p.alreadyRead+" offset: "+(p.offset+p.alreadyRead-u.fileStart)+" read size: "+(p.size-p.alreadyRead)+" full size: "+p.size+")"),r.memcpy(p.data.buffer,p.alreadyRead,u,p.offset+p.alreadyRead-u.fileStart,p.size-p.alreadyRead),u.usedBytes+=p.size-p.alreadyRead,this.stream.logBufferLevel(),p.alreadyRead=p.size,p;if(b===0)return null;t.debug("ISOFile","Getting sample #"+c+" partial data (alreadyRead: "+p.alreadyRead+" offset: "+(p.offset+p.alreadyRead-u.fileStart)+" read size: "+b+" full size: "+p.size+")"),r.memcpy(p.data.buffer,p.alreadyRead,u,p.offset+p.alreadyRead-u.fileStart,b),p.alreadyRead+=b,u.usedBytes+=b,this.stream.logBufferLevel()}else return null}},y.prototype.releaseSample=function(o,c){var u=o.samples[c];return u.data?(this.samplesDataSize-=u.size,u.data=null,u.alreadyRead=0,u.size):0},y.prototype.getAllocatedSampleDataSize=function(){return this.samplesDataSize},y.prototype.getCodecs=function(){var o,c="";for(o=0;o<this.moov.traks.length;o++){var u=this.moov.traks[o];o>0&&(c+=","),c+=u.mdia.minf.stbl.stsd.entries[0].getCodec()}return c},y.prototype.getTrexById=function(o){var c;if(!this.moov||!this.moov.mvex)return null;for(c=0;c<this.moov.mvex.trexs.length;c++){var u=this.moov.mvex.trexs[c];if(u.track_id==o)return u}return null},y.prototype.getTrackById=function(o){if(this.moov===void 0)return null;for(var c=0;c<this.moov.traks.length;c++){var u=this.moov.traks[c];if(u.tkhd.track_id==o)return u}return null},y.prototype.items=[],y.prototype.entity_groups=[],y.prototype.itemsDataSize=0,y.prototype.flattenItemInfo=function(){var o=this.items,c=this.entity_groups,u,p,_,b=this.meta;if(b!=null&&b.hdlr!==void 0&&b.iinf!==void 0){for(u=0;u<b.iinf.item_infos.length;u++)_={},_.id=b.iinf.item_infos[u].item_ID,o[_.id]=_,_.ref_to=[],_.name=b.iinf.item_infos[u].item_name,b.iinf.item_infos[u].protection_index>0&&(_.protection=b.ipro.protections[b.iinf.item_infos[u].protection_index-1]),b.iinf.item_infos[u].item_type?_.type=b.iinf.item_infos[u].item_type:_.type="mime",_.content_type=b.iinf.item_infos[u].content_type,_.content_encoding=b.iinf.item_infos[u].content_encoding;if(b.grpl)for(u=0;u<b.grpl.boxes.length;u++)entity_group={},entity_group.id=b.grpl.boxes[u].group_id,entity_group.entity_ids=b.grpl.boxes[u].entity_ids,entity_group.type=b.grpl.boxes[u].type,c[entity_group.id]=entity_group;if(b.iloc)for(u=0;u<b.iloc.items.length;u++){var v=b.iloc.items[u];switch(_=o[v.item_ID],v.data_reference_index!==0&&(t.warn("Item storage with reference to other files: not supported"),_.source=b.dinf.boxes[v.data_reference_index-1]),v.construction_method){case 0:break;case 1:t.warn("Item storage with construction_method : not supported");break;case 2:t.warn("Item storage with construction_method : not supported");break}for(_.extents=[],_.size=0,p=0;p<v.extents.length;p++)_.extents[p]={},_.extents[p].offset=v.extents[p].extent_offset+v.base_offset,_.extents[p].length=v.extents[p].extent_length,_.extents[p].alreadyRead=0,_.size+=_.extents[p].length}if(b.pitm&&(o[b.pitm.item_id].primary=!0),b.iref)for(u=0;u<b.iref.references.length;u++){var w=b.iref.references[u];for(p=0;p<w.references.length;p++)o[w.from_item_ID].ref_to.push({type:w.type,id:w.references[p]})}if(b.iprp)for(var S=0;S<b.iprp.ipmas.length;S++){var T=b.iprp.ipmas[S];for(u=0;u<T.associations.length;u++){var E=T.associations[u];if(_=o[E.id],_||(_=c[E.id]),_)for(_.properties===void 0&&(_.properties={},_.properties.boxes=[]),p=0;p<E.props.length;p++){var P=E.props[p];if(P.property_index>0&&P.property_index-1<b.iprp.ipco.boxes.length){var B=b.iprp.ipco.boxes[P.property_index-1];_.properties[B.type]=B,_.properties.boxes.push(B)}}}}}},y.prototype.getItem=function(o){var c,u;if(!this.meta)return null;if(u=this.items[o],!u.data&&u.size)u.data=new Uint8Array(u.size),u.alreadyRead=0,this.itemsDataSize+=u.size,t.debug("ISOFile","Allocating item #"+o+" of size "+u.size+" (total: "+this.itemsDataSize+")");else if(u.alreadyRead===u.size)return u;for(var p=0;p<u.extents.length;p++){var _=u.extents[p];if(_.alreadyRead!==_.length){var b=this.stream.findPosition(!0,_.offset+_.alreadyRead,!1);if(b>-1){c=this.stream.buffers[b];var v=c.byteLength-(_.offset+_.alreadyRead-c.fileStart);if(_.length-_.alreadyRead<=v)t.debug("ISOFile","Getting item #"+o+" extent #"+p+" data (alreadyRead: "+_.alreadyRead+" offset: "+(_.offset+_.alreadyRead-c.fileStart)+" read size: "+(_.length-_.alreadyRead)+" full extent size: "+_.length+" full item size: "+u.size+")"),r.memcpy(u.data.buffer,u.alreadyRead,c,_.offset+_.alreadyRead-c.fileStart,_.length-_.alreadyRead),c.usedBytes+=_.length-_.alreadyRead,this.stream.logBufferLevel(),u.alreadyRead+=_.length-_.alreadyRead,_.alreadyRead=_.length;else return t.debug("ISOFile","Getting item #"+o+" extent #"+p+" partial data (alreadyRead: "+_.alreadyRead+" offset: "+(_.offset+_.alreadyRead-c.fileStart)+" read size: "+v+" full extent size: "+_.length+" full item size: "+u.size+")"),r.memcpy(u.data.buffer,u.alreadyRead,c,_.offset+_.alreadyRead-c.fileStart,v),_.alreadyRead+=v,u.alreadyRead+=v,c.usedBytes+=v,this.stream.logBufferLevel(),null}else return null}}return u.alreadyRead===u.size?u:null},y.prototype.releaseItem=function(o){var c=this.items[o];if(c.data){this.itemsDataSize-=c.size,c.data=null,c.alreadyRead=0;for(var u=0;u<c.extents.length;u++){var p=c.extents[u];p.alreadyRead=0}return c.size}else return 0},y.prototype.processItems=function(o){for(var c in this.items){var u=this.items[c];this.getItem(u.id),o&&!u.sent&&(o(u),u.sent=!0,u.data=null)}},y.prototype.hasItem=function(o){for(var c in this.items){var u=this.items[c];if(u.name===o)return u.id}return-1},y.prototype.getMetaHandler=function(){return this.meta?this.meta.hdlr.handler:null},y.prototype.getPrimaryItem=function(){return!this.meta||!this.meta.pitm?null:this.getItem(this.meta.pitm.item_id)},y.prototype.itemToFragmentedTrackFile=function(o){var c=o||{},u=null;if(c.itemId?u=this.getItem(c.itemId):u=this.getPrimaryItem(),u==null)return null;var p=new y;p.discardMdatData=!1;var _={type:u.type,description_boxes:u.properties.boxes};u.properties.ispe&&(_.width=u.properties.ispe.image_width,_.height=u.properties.ispe.image_height);var b=p.addTrack(_);return b?(p.addSample(b,u.data),p):null},y.prototype.write=function(o){for(var c=0;c<this.boxes.length;c++)this.boxes[c].write(o)},y.prototype.createFragment=function(o,c,u){var p=this.getTrackById(o),_=this.getSample(p,c);if(_==null)return this.setNextSeekPositionFromSample(p.samples[c]),null;var b=u||new r;b.endianness=r.BIG_ENDIAN;var v=this.createSingleSampleMoof(_);v.write(b),v.trafs[0].truns[0].data_offset=v.size+8,t.debug("MP4Box","Adjusting data_offset with new value "+v.trafs[0].truns[0].data_offset),b.adjustUint32(v.trafs[0].truns[0].data_offset_position,v.trafs[0].truns[0].data_offset);var w=new h.mdatBox;return w.data=_.data,w.write(b),b},y.writeInitializationSegment=function(o,c,u,p){var _;t.debug("ISOFile","Generating initialization segment");var b=new r;b.endianness=r.BIG_ENDIAN,o.write(b);var v=c.add("mvex");for(u&&v.add("mehd").set("fragment_duration",u),_=0;_<c.traks.length;_++)v.add("trex").set("track_id",c.traks[_].tkhd.track_id).set("default_sample_description_index",1).set("default_sample_duration",p).set("default_sample_size",0).set("default_sample_flags",65536);return c.write(b),b.buffer},y.prototype.save=function(o){var c=new r;c.endianness=r.BIG_ENDIAN,this.write(c),c.save(o)},y.prototype.getBuffer=function(){var o=new r;return o.endianness=r.BIG_ENDIAN,this.write(o),o.buffer},y.prototype.initializeSegmentation=function(){var o,c,u,p;for(this.onSegment===null&&t.warn("MP4Box","No segmentation callback set!"),this.isFragmentationInitialized||(this.isFragmentationInitialized=!0,this.nextMoofNumber=0,this.resetTables()),c=[],o=0;o<this.fragmentedTracks.length;o++){var _=new h.moovBox;_.mvhd=this.moov.mvhd,_.boxes.push(_.mvhd),u=this.getTrackById(this.fragmentedTracks[o].id),_.boxes.push(u),_.traks.push(u),p={},p.id=u.tkhd.track_id,p.user=this.fragmentedTracks[o].user,p.buffer=y.writeInitializationSegment(this.ftyp,_,this.moov.mvex&&this.moov.mvex.mehd?this.moov.mvex.mehd.fragment_duration:void 0,this.moov.traks[o].samples.length>0?this.moov.traks[o].samples[0].duration:0),c.push(p)}return c},h.Box.prototype.printHeader=function(o){this.size+=8,this.size>n&&(this.size+=8),this.type==="uuid"&&(this.size+=16),o.log(o.indent+"size:"+this.size),o.log(o.indent+"type:"+this.type)},h.FullBox.prototype.printHeader=function(o){this.size+=4,h.Box.prototype.printHeader.call(this,o),o.log(o.indent+"version:"+this.version),o.log(o.indent+"flags:"+this.flags)},h.Box.prototype.print=function(o){this.printHeader(o)},h.ContainerBox.prototype.print=function(o){this.printHeader(o);for(var c=0;c<this.boxes.length;c++)if(this.boxes[c]){var u=o.indent;o.indent+=" ",this.boxes[c].print(o),o.indent=u}},y.prototype.print=function(o){o.indent="";for(var c=0;c<this.boxes.length;c++)this.boxes[c]&&this.boxes[c].print(o)},h.mvhdBox.prototype.print=function(o){h.FullBox.prototype.printHeader.call(this,o),o.log(o.indent+"creation_time: "+this.creation_time),o.log(o.indent+"modification_time: "+this.modification_time),o.log(o.indent+"timescale: "+this.timescale),o.log(o.indent+"duration: "+this.duration),o.log(o.indent+"rate: "+this.rate),o.log(o.indent+"volume: "+(this.volume>>8)),o.log(o.indent+"matrix: "+this.matrix.join(", ")),o.log(o.indent+"next_track_id: "+this.next_track_id)},h.tkhdBox.prototype.print=function(o){h.FullBox.prototype.printHeader.call(this,o),o.log(o.indent+"creation_time: "+this.creation_time),o.log(o.indent+"modification_time: "+this.modification_time),o.log(o.indent+"track_id: "+this.track_id),o.log(o.indent+"duration: "+this.duration),o.log(o.indent+"volume: "+(this.volume>>8)),o.log(o.indent+"matrix: "+this.matrix.join(", ")),o.log(o.indent+"layer: "+this.layer),o.log(o.indent+"alternate_group: "+this.alternate_group),o.log(o.indent+"width: "+this.width),o.log(o.indent+"height: "+this.height)};var x={};x.createFile=function(o,c){var u=o!==void 0?o:!0,p=new y(c);return p.discardMdatData=!u,p},s.createFile=x.createFile})(qr)),qr}var pd=fd();const yt=_e(pd);var wa=s=>{throw TypeError(s)},Sa=(s,t,e)=>t.has(s)||wa("Cannot "+e),X=(s,t,e)=>(Sa(s,t,"read from private field"),e?e.call(s):t.get(s)),Mt=(s,t,e)=>t.has(s)?wa("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(s):t.set(s,e),ft=(s,t,e,r)=>(Sa(s,t,"write to private field"),t.set(s,e),e);const Ta="KGZ1bmN0aW9uKCl7InVzZSBzdHJpY3QiO2Z1bmN0aW9uIHUobil7aWYobj09PSIvIilyZXR1cm57cGFyZW50Om51bGwsbmFtZToiIn07Y29uc3QgZT1uLnNwbGl0KCIvIikuZmlsdGVyKGk9PmkubGVuZ3RoPjApO2lmKGUubGVuZ3RoPT09MCl0aHJvdyBFcnJvcigiSW52YWxpZCBwYXRoIik7Y29uc3QgYT1lW2UubGVuZ3RoLTFdLHI9Ii8iK2Uuc2xpY2UoMCwtMSkuam9pbigiLyIpO3JldHVybntuYW1lOmEscGFyZW50OnJ9fWFzeW5jIGZ1bmN0aW9uIHcobixlKXtjb25zdHtwYXJlbnQ6YSxuYW1lOnJ9PXUobik7aWYoYT09bnVsbClyZXR1cm4gYXdhaXQgbmF2aWdhdG9yLnN0b3JhZ2UuZ2V0RGlyZWN0b3J5KCk7Y29uc3QgaT1hLnNwbGl0KCIvIikuZmlsdGVyKHQ9PnQubGVuZ3RoPjApO3RyeXtsZXQgdD1hd2FpdCBuYXZpZ2F0b3Iuc3RvcmFnZS5nZXREaXJlY3RvcnkoKTtmb3IoY29uc3QgcyBvZiBpKXQ9YXdhaXQgdC5nZXREaXJlY3RvcnlIYW5kbGUocyx7Y3JlYXRlOmUuY3JlYXRlfSk7aWYoZS5pc0ZpbGUpcmV0dXJuIGF3YWl0IHQuZ2V0RmlsZUhhbmRsZShyLHtjcmVhdGU6ZS5jcmVhdGV9KX1jYXRjaCh0KXtpZih0Lm5hbWU9PT0iTm90Rm91bmRFcnJvciIpcmV0dXJuIG51bGw7dGhyb3cgdH19Y29uc3QgZj17fTtzZWxmLm9ubWVzc2FnZT1hc3luYyBuPT57dmFyIGk7Y29uc3R7ZXZ0VHlwZTplLGFyZ3M6YX09bi5kYXRhO2xldCByPWZbYS5maWxlSWRdO3RyeXtsZXQgdDtjb25zdCBzPVtdO2lmKGU9PT0icmVnaXN0ZXIiKXtjb25zdCBsPWF3YWl0IHcoYS5maWxlUGF0aCx7Y3JlYXRlOiEwLGlzRmlsZTohMH0pO2lmKGw9PW51bGwpdGhyb3cgRXJyb3IoYG5vdCBmb3VuZCBmaWxlOiAke2EuZmlsZUlkfWApO3I9YXdhaXQgbC5jcmVhdGVTeW5jQWNjZXNzSGFuZGxlKHttb2RlOmEubW9kZX0pLGZbYS5maWxlSWRdPXJ9ZWxzZSBpZihlPT09ImNsb3NlIilhd2FpdCByLmNsb3NlKCksZGVsZXRlIGZbYS5maWxlSWRdO2Vsc2UgaWYoZT09PSJ0cnVuY2F0ZSIpYXdhaXQgci50cnVuY2F0ZShhLm5ld1NpemUpO2Vsc2UgaWYoZT09PSJ3cml0ZSIpe2NvbnN0e2RhdGE6bCxvcHRzOm99PW4uZGF0YS5hcmdzO3Q9YXdhaXQgci53cml0ZShsLG8pfWVsc2UgaWYoZT09PSJyZWFkIil7Y29uc3R7b2Zmc2V0Omwsc2l6ZTpvfT1uLmRhdGEuYXJncyxnPW5ldyBVaW50OEFycmF5KG8pLGQ9YXdhaXQgci5yZWFkKGcse2F0Omx9KSxjPWcuYnVmZmVyO3Q9ZD09PW8/YzooKGk9Yy50cmFuc2Zlcik9PW51bGw/dm9pZCAwOmkuY2FsbChjLGQpKT8/Yy5zbGljZSgwLGQpLHMucHVzaCh0KX1lbHNlIGU9PT0iZ2V0U2l6ZSI/dD1hd2FpdCByLmdldFNpemUoKTplPT09ImZsdXNoIiYmYXdhaXQgci5mbHVzaCgpO3NlbGYucG9zdE1lc3NhZ2Uoe2V2dFR5cGU6ImNhbGxiYWNrIixjYklkOm4uZGF0YS5jYklkLHJldHVyblZhbDp0fSxzKX1jYXRjaCh0KXtjb25zdCBzPXQ7c2VsZi5wb3N0TWVzc2FnZSh7ZXZ0VHlwZToidGhyb3dFcnJvciIsY2JJZDpuLmRhdGEuY2JJZCxlcnJNc2c6cy5uYW1lKyI6ICIrcy5tZXNzYWdlK2AKYCtKU09OLnN0cmluZ2lmeShuLmRhdGEpfSl9fX0pKCk7Ci8vIyBzb3VyY2VNYXBwaW5nVVJMPW9wZnMtd29ya2VyLUY0UldscWNfLmpzLm1hcAo=",md=s=>Uint8Array.from(atob(s),t=>t.charCodeAt(0)),Ca=typeof self<"u"&&self.Blob&&new Blob([md(Ta)],{type:"text/javascript;charset=utf-8"});function gd(s){let t;try{if(t=Ca&&(self.URL||self.webkitURL).createObjectURL(Ca),!t)throw"";const e=new Worker(t,{name:s?.name});return e.addEventListener("error",()=>{(self.URL||self.webkitURL).revokeObjectURL(t)}),e}catch{return new Worker("data:text/javascript;base64,"+Ta,{name:s?.name})}finally{t&&(self.URL||self.webkitURL).revokeObjectURL(t)}}async function _d(s,t,e){const r=yd();return await r("register",{fileId:s,filePath:t,mode:e}),{read:async(n,a)=>await r("read",{fileId:s,offset:n,size:a}),write:async(n,a)=>await r("write",{fileId:s,data:n,opts:a},[ArrayBuffer.isView(n)?n.buffer:n]),close:async()=>await r("close",{fileId:s}),truncate:async n=>await r("truncate",{fileId:s,newSize:n}),getSize:async()=>await r("getSize",{fileId:s}),flush:async()=>await r("flush",{fileId:s})}}const qi=[];let Zr=0;function yd(){if(qi.length<3){const t=s();return qi.push(t),t}else{const t=qi[Zr];return Zr=(Zr+1)%qi.length,t}function s(){const t=new gd;let e=0,r={};return t.onmessage=({data:n})=>{var a,l;n.evtType==="callback"?(a=r[n.cbId])==null||a.resolve(n.returnVal):n.evtType==="throwError"&&((l=r[n.cbId])==null||l.reject(Error(n.errMsg))),delete r[n.cbId]},async function(n,a,l=[]){e+=1;const h=new Promise((d,f)=>{r[e]={resolve:d,reject:f}});return t.postMessage({cbId:e,evtType:n,args:a},l),h}}}function Zi(s){if(s==="/")return{parent:null,name:""};const t=s.split("/").filter(n=>n.length>0);if(t.length===0)throw Error("Invalid path");const e=t[t.length-1],r="/"+t.slice(0,-1).join("/");return{name:e,parent:r}}async function le(s,t){const{parent:e,name:r}=Zi(s);if(e==null)return await navigator.storage.getDirectory();const n=e.split("/").filter(a=>a.length>0);try{let a=await navigator.storage.getDirectory();for(const l of n)a=await a.getDirectoryHandle(l,{create:t.create});return t.isFile?await a.getFileHandle(r,{create:t.create}):await a.getDirectoryHandle(r,{create:t.create})}catch(a){if(a.name==="NotFoundError")return null;throw a}}async function Qr(s){const{parent:t,name:e}=Zi(s);if(t==null){const n=await navigator.storage.getDirectory();for await(const a of n.keys())await n.removeEntry(a,{recursive:!0});return}const r=await le(t,{create:!1,isFile:!1});if(r!=null)try{await r.removeEntry(e,{recursive:!0})}catch(n){if(n.name==="NotFoundError")return;throw n}}function Jr(s,t){return`${s}/${t}`.replace("//","/")}function Fe(s){return new Ea(s)}var $t,Qi,ri;const xd=class Wu{constructor(t){Mt(this,$t),Mt(this,Qi),Mt(this,ri),ft(this,$t,t);const{parent:e,name:r}=Zi(t);ft(this,Qi,r),ft(this,ri,e)}get kind(){return"dir"}get name(){return X(this,Qi)}get path(){return X(this,$t)}get parent(){return X(this,ri)==null?null:Fe(X(this,ri))}async create(){return await le(X(this,$t),{create:!0,isFile:!1}),Fe(X(this,$t))}async exists(){return await le(X(this,$t),{create:!1,isFile:!1})instanceof FileSystemDirectoryHandle}async remove(t={}){for(const e of await this.children())try{await e.remove(t)}catch(r){console.warn(r)}try{await Qr(X(this,$t))}catch(e){console.warn(e)}}async children(){const t=await le(X(this,$t),{create:!1,isFile:!1});if(t==null)return[];const e=[];for await(const r of t.values())e.push((r.kind==="file"?si:Fe)(Jr(X(this,$t),r.name)));return e}async copyTo(t){if(!await this.exists())throw Error(`dir ${this.path} not exists`);if(t instanceof Wu){const e=await t.exists()?Fe(Jr(t.path,this.name)):t;return await e.create(),await Promise.all((await this.children()).map(r=>r.copyTo(e))),e}else if(t instanceof FileSystemDirectoryHandle)return await Promise.all((await this.children()).map(async e=>{e.kind==="file"?await e.copyTo(await t.getFileHandle(e.name,{create:!0})):await e.copyTo(await t.getDirectoryHandle(e.name,{create:!0}))})),null;throw Error("Illegal target type")}async moveTo(t){const e=await this.copyTo(t);return await this.remove(),e}};$t=new WeakMap,Qi=new WeakMap,ri=new WeakMap;let Ea=xd;const ts=new Map;function si(s,t="rw"){if(t==="rw"){const e=ts.get(s)??new rr(s,t);return ts.set(s,e),e}return new rr(s,t)}async function ni(s,t,e={overwrite:!0}){if(t instanceof rr){await ni(s,await t.stream(),e);return}const r=await(s instanceof rr?s:si(s,"rw")).createWriter();try{if(e.overwrite&&await r.truncate(0),t instanceof ReadableStream){const n=t.getReader();for(;;){const{done:a,value:l}=await n.read();if(a)break;await r.write(l)}}else await r.write(t)}catch(n){throw n}finally{await r.close()}}let bd=0;const vd=()=>++bd;var kt,ai,Ji,oi,tr,Zt,er,ir,De;const wd=class Vu{constructor(t,e){Mt(this,kt),Mt(this,ai),Mt(this,Ji),Mt(this,oi),Mt(this,tr),Mt(this,Zt,0),Mt(this,er,async()=>{}),Mt(this,ir,(()=>{let a=null;return()=>(ft(this,Zt,X(this,Zt)+1),a!=null||(a=new Promise(async(l,h)=>{try{const d=await _d(X(this,tr),X(this,kt),X(this,oi));ft(this,er,async()=>{a!=null&&(a=null,ft(this,Zt,0),await d.close().catch(console.error))}),l([d,async()=>{ft(this,Zt,X(this,Zt)-1),!(X(this,Zt)>0)&&(a=null,await d.close())}])}catch(d){h(d)}})),a)})()),Mt(this,De,!1),ft(this,tr,vd()),ft(this,kt,t),ft(this,oi,{r:"read-only",rw:"readwrite","rw-unsafe":"readwrite-unsafe"}[e]);const{parent:r,name:n}=Zi(t);if(r==null)throw Error("Invalid path");ft(this,Ji,n),ft(this,ai,r)}get kind(){return"file"}get path(){return X(this,kt)}get name(){return X(this,Ji)}get parent(){return X(this,ai)==null?null:Fe(X(this,ai))}async createWriter(){if(X(this,oi)==="read-only")throw Error("file is read-only");if(X(this,De))throw Error("Other writer have not been closed");ft(this,De,!0);try{const t=new TextEncoder,[e,r]=await X(this,ir).call(this);let n=await e.getSize(),a=!1;return{write:async(l,h={})=>{if(a)throw Error("Writer is closed");const d=typeof l=="string"?t.encode(l):l,f=h.at??n,m=d.byteLength;return n=f+m,await e.write(d,{at:f})},truncate:async l=>{if(a)throw Error("Writer is closed");await e.truncate(l),n>l&&(n=l)},flush:async()=>{if(a)throw Error("Writer is closed");await e.flush()},close:async()=>{if(a)throw Error("Writer is closed");a=!0,ft(this,De,!1),await r()}}}catch(t){throw ft(this,De,!1),t}}async createReader(){const[t,e]=await X(this,ir).call(this);let r=!1,n=0;return{read:async(a,l={})=>{if(r)throw Error("Reader is closed");const h=l.at??n,d=await t.read(h,a);return n=h+d.byteLength,d},getSize:async()=>{if(r)throw Error("Reader is closed");return await t.getSize()},close:async()=>{r||(r=!0,await e())}}}async text(){return new TextDecoder().decode(await this.arrayBuffer())}async arrayBuffer(){const t=await le(X(this,kt),{create:!1,isFile:!0});return t==null?new ArrayBuffer(0):(await t.getFile()).arrayBuffer()}async stream(){const t=await this.getOriginFile();return t==null?new ReadableStream({pull:e=>{e.close()}}):t.stream()}async getOriginFile(){var t;return(t=await le(X(this,kt),{create:!1,isFile:!0}))==null?void 0:t.getFile()}async getSize(){const t=await le(X(this,kt),{create:!1,isFile:!0});return t==null?0:(await t.getFile()).size}async exists(){return await le(X(this,kt),{create:!1,isFile:!0})instanceof FileSystemFileHandle}async remove(t={}){if(t.force===!0){await X(this,er).call(this),await Qr(X(this,kt)),ts.delete(X(this,kt));return}if(X(this,Zt)>0)throw Error("exists unclosed reader/writer");await Qr(X(this,kt))}async copyTo(t){if(t instanceof Vu)return t.path===this.path?this:(await ni(t,this),t);if(t instanceof Ea){if(!await this.exists())throw Error(`file ${this.path} not exists`);return await this.copyTo(si(Jr(t.path,this.name)))}else if(t instanceof FileSystemFileHandle)return await(await this.stream()).pipeTo(await t.createWritable()),null;throw Error("Illegal target type")}async moveTo(t){const e=await this.copyTo(t);return await this.remove(),e}};kt=new WeakMap,ai=new WeakMap,Ji=new WeakMap,oi=new WeakMap,tr=new WeakMap,Zt=new WeakMap,er=new WeakMap,ir=new WeakMap,De=new WeakMap;let rr=wd;const es="/.opfs-tools-temp-dir";async function Aa(s){try{if(s.kind==="file"){if(!await s.exists())return!0;const t=await s.createWriter();await t.truncate(0),await t.close(),await s.remove()}else await s.remove();return!0}catch(t){return console.warn(t),!1}}function Sd(){setInterval(async()=>{for(const s of await Fe(es).children()){const t=/^\d+-(\d+)$/.exec(s.name);(t==null||Date.now()-Number(t[1])>2592e5)&&await Aa(s)}},60*1e3)}const is=[];let Pa=!1;async function Td(){if(globalThis.localStorage==null)return;const s="OPFS_TOOLS_EXPIRES_TMP_FILES";Pa||(Pa=!0,globalThis.addEventListener("unload",()=>{is.length!==0&&localStorage.setItem(s,`${localStorage.getItem(s)??""},${is.join(",")}`)}));let t=localStorage.getItem(s)??"";for(const e of t.split(","))e.length!==0&&await Aa(si(`${es}/${e}`))&&(t=t.replace(e,""));localStorage.setItem(s,t.replace(/,{2,}/g,","))}(async function(){var s;globalThis.__opfs_tools_tmpfile_init__!==!0&&(globalThis.__opfs_tools_tmpfile_init__=!0,!(globalThis.FileSystemDirectoryHandle==null||globalThis.FileSystemFileHandle==null||((s=globalThis.navigator)==null?void 0:s.storage.getDirectory)==null)&&(Sd(),await Td()))})();function rs(){const s=`${Math.random().toString().slice(2)}-${Date.now()}`;return is.push(s),si(`${es}/${s}`)}class ss{static forwardEvent(t,e,r){const n=r.map(a=>{const[l,h]=Array.isArray(a)?a:[a,a];return t.on(l,(...d)=>{e.emit(h,...d)})});return()=>{n.forEach(a=>a())}}listeners=new Map;on=(t,e)=>{const r=this.listeners.get(t)??new Set;return r.add(e),this.listeners.has(t)||this.listeners.set(t,r),()=>{r.delete(e),r.size===0&&this.listeners.delete(t)}};once=(t,e)=>{const r=this.on(t,(...n)=>{r(),e(...n)});return r};emit=(t,...e)=>{const r=this.listeners.get(t);r?.forEach(n=>n(...e))};destroy(){this.listeners.clear()}}function Cd(s){return s instanceof Error?String(s):typeof s=="object"?JSON.stringify(s,(t,e)=>e instanceof Error?String(e):e):String(s)}function Ed(){const s=new Date;return`${s.getHours()}:${s.getMinutes()}:${s.getSeconds()}.${s.getMilliseconds()}`}let Ba=1;const Ua=[],Ma=["debug","info","warn","error"].reduce((s,t,e)=>Object.assign(s,{[t]:(...r)=>{Ba<=e&&(console[t](...r),Ua.push({lvName:t,timeStr:Ed(),args:r}))}}),{}),hi=new Map,H={setLogLevel:s=>{Ba=hi.get(s)??1},...Ma,create:s=>Object.fromEntries(Object.entries(Ma).map(([t,e])=>[t,(...r)=>e(s,...r)])),async dump(){return Ua.reduce((s,{lvName:t,timeStr:e,args:r})=>s+`[${t}][${e}] ${r.map(n=>Cd(n)).join(" ")}
|
|
2
|
-
`,"")}};hi.set(H.debug,0),hi.set(H.info,1),hi.set(H.warn,2),hi.set(H.error,3),(async function(){if(await Promise.resolve(),!(globalThis.navigator==null||globalThis.document==null)&&(H.info(globalThis.navigator.userAgent),document.addEventListener("visibilitychange",()=>{H.info(`visibilitychange: ${document.visibilityState}`)}),"PressureObserver"in globalThis)){let t="";new PressureObserver(r=>{const n=JSON.stringify(r.map(a=>a.state));n!==t&&(H.info(`cpu state change: ${n}`),t=n)}).observe("cpu")}})();const ns=(s,t)=>{const e=new Uint8Array(8);new DataView(e.buffer).setUint32(0,t);for(let n=0;n<4;n++)e[4+n]=s.charCodeAt(n);return e},Ad=()=>{const s=new TextEncoder,t=s.encode("mdta"),e=s.encode("mp4 handler"),r=32+e.byteLength+1,n=new Uint8Array(r),a=new DataView(n.buffer);return n.set(ns("hdlr",r),0),a.setUint32(8,0),n.set(t,16),n.set(e,32),n},Pd=s=>{const t=new TextEncoder,e=t.encode("mdta"),r=s.map(f=>{const m=t.encode(f),g=8+m.byteLength,y=new Uint8Array(g);return new DataView(y.buffer).setUint32(0,g),y.set(e,4),y.set(m,4+e.byteLength),y}),a=16+r.reduce((f,m)=>f+m.byteLength,0),l=new Uint8Array(a),h=new DataView(l.buffer);l.set(ns("keys",a),0),h.setUint32(8,0),h.setUint32(12,s.length);let d=16;for(const f of r)l.set(f,d),d+=f.byteLength;return l},Bd=s=>{const t=new TextEncoder,e=t.encode("data"),r=Object.entries(s).map(([d,f],m)=>{const g=m+1,y=t.encode(f),x=24+y.byteLength,o=new Uint8Array(x),c=new DataView(o.buffer);return c.setUint32(0,x),c.setUint32(4,g),c.setUint32(8,16+y.byteLength),o.set(e,12),c.setUint32(16,1),o.set(y,24),o}),a=8+r.reduce((d,f)=>d+f.byteLength,0),l=new Uint8Array(a);l.set(ns("ilst",a),0);let h=8;for(const d of r)l.set(d,h),h+=d.byteLength;return l},Ud=s=>{const t=Ad(),e=Pd(Object.keys(s)),r=Bd(s),n=t.length+e.length+r.length,a=new Uint8Array(n);return a.set(t,0),a.set(e,t.length),a.set(r,t.length+e.length),a},Md=()=>{let s,t=16.6;self.onmessage=e=>{e.data.event==="start"&&(self.clearInterval(s),s=self.setInterval(()=>{self.postMessage({})},t)),e.data.event==="stop"&&self.clearInterval(s)}},kd=()=>{const s=new Blob([`(${Md.toString()})()`]),t=URL.createObjectURL(s);return new Worker(t)},Ge=new Map;let as=1,sr=null;globalThis.Worker!=null&&(sr=kd(),sr.onmessage=()=>{as+=1;for(const[s,t]of Ge)if(as%s===0)for(const e of t)e()});const ka=(s,t)=>{const e=Math.round(t/16.6),r=Ge.get(e)??new Set;return r.add(s),Ge.set(e,r),Ge.size===1&&r.size===1&&sr?.postMessage({event:"start"}),()=>{r.delete(s),r.size===0&&Ge.delete(e),Ge.size===0&&(as=0,sr?.postMessage({event:"stop"}))}};function Rd(s){H.info("recodemux opts:",s);const t=yt.createFile(),e=new ss,r=(d,f)=>{const g=d.add("udta").add("meta");g.data=Ud(f),g.size=g.data.byteLength};let n=!1;const a=()=>{t.moov==null||n||(n=!0,s.metaDataTags!=null&&r(t.moov,s.metaDataTags),s.duration!=null&&(t.moov.mvhd.duration=s.duration))};e.once("VideoReady",a),e.once("AudioReady",a);const l=s.video!=null?Id(s.video,t,e):null,h=s.audio!=null?Dd(s.audio,t,e):null;return s.video==null&&e.emit("VideoReady"),s.audio==null&&e.emit("AudioReady"),{encodeVideo:(d,f)=>{l?.encode(d,f),d.close()},encodeAudio:d=>{if(h!=null)try{h.encode(d),d.close()}catch(f){const m=`encode audio chunk error: ${f.message}, state: ${JSON.stringify({qSize:h.encodeQueueSize,state:h.state})}`;throw H.error(m),Error(m)}},getEncodeQueueSize:()=>l?.encodeQueueSize??h?.encodeQueueSize??0,flush:async()=>{await Promise.all([l?.flush(),h?.state==="configured"?h.flush():null])},close:()=>{e.destroy(),l?.close(),h?.state==="configured"&&h.close()},mp4file:t}}function Id(s,t,e){const r={timescale:1e6,width:s.width,height:s.height,brands:["isom","iso2","avc1","mp42","mp41"],avcDecoderConfigRecord:null,hevcDecoderConfigRecord:null,vpcDecoderConfigRecord:null,type:"avc1",name:"Track created with WebAV"};let n=-1,a=!1;e.once("AudioReady",()=>{a=!0});const l={encoder0:[],encoder1:[]},h=(p,_,b)=>{if(n===-1&&b!=null){let v=b.decoderConfig?.description;s.codec.startsWith("avc1")?Fd(v):s.codec.startsWith("vp09")&&b.decoderConfig&&(r.type="vp09",v=Od(b.decoderConfig));const w=[["avc1","avcDecoderConfigRecord"],["hvc1","hevcDecoderConfigRecord"],["vp09","vpcDecoderConfigRecord"]].find(([S])=>s.codec.startsWith(S))?.[1];w!=null&&v!=null&&(r[w]=v),n=t.addTrack(r),e.emit("VideoReady"),H.info("VideoEncoder, video track ready, trackId:",n)}l[p].push(os(_))};let d="encoder1",f=0;const m=Math.floor(1e3/s.expectFPS*1e3);function g(){if(!a)return;const p=d==="encoder1"?"encoder0":"encoder1",_=l[d],b=l[p];if(_.length===0&&b.length===0)return;const v=_[0];if(v!=null&&(!v.is_sync||v.cts-f<m)){const S=y(_);S>f&&(f=S)}const w=b[0];if(w?.is_sync&&w.cts-f<m){d=p,g();return}if(v?.is_sync&&w?.is_sync)if(v.cts<=w.cts){const S=y(_);S>f&&(f=S)}else{d=p,g();return}}function y(p){let _=-1,b=0;for(;b<p.length;b++){const v=p[b];if(b>0&&v.is_sync)break;t.addSample(n,v.data,v),_=v.cts+v.duration}return p.splice(0,b),_}const x=ka(g,15),o=Ra(s,(p,_)=>h("encoder0",p,_)),c=Ra(s,(p,_)=>h("encoder1",p,_));let u=0;return{get encodeQueueSize(){return o.encodeQueueSize+c.encodeQueueSize},encode:(p,_)=>{try{_.keyFrame&&(u+=1),(u%2===0?o:c).encode(p,_)}catch(b){const v=`encode video frame error: ${b.message}, state: ${JSON.stringify({ts:p.timestamp,keyFrame:_.keyFrame,duration:p.duration,gopId:u})}`;throw H.error(v),Error(v)}},flush:async()=>{await Promise.all([o.state==="configured"?await o.flush():null,c.state==="configured"?await c.flush():null]),x(),g()},close:()=>{o.state==="configured"&&o.close(),c.state==="configured"&&c.close()}}}function Fd(s){const t=new Uint8Array(s);t[2].toString(2).slice(-2).includes("1")&&(t[2]=0)}function Ra(s,t){const e={codec:s.codec,framerate:s.expectFPS,hardwareAcceleration:s.__unsafe_hardwareAcceleration__,bitrate:s.bitrate,width:s.width,height:s.height,alpha:"discard",avc:{format:"avc"}},r=new VideoEncoder({error:n=>{const a=`VideoEncoder error: ${n.message}, config: ${JSON.stringify(e)}, state: ${JSON.stringify({qSize:r.encodeQueueSize,state:r.state})}`;throw H.error(a),Error(a)},output:t});return r.configure(e),r}function Dd(s,t,e){const r={timescale:1e6,samplerate:s.sampleRate,channel_count:s.channelCount,hdlr:"soun",type:s.codec==="aac"?"mp4a":"Opus",name:"Track created with WebAV"};let n=-1,a=[],l=!1;e.once("VideoReady",()=>{l=!0,a.forEach(f=>{const m=os(f);t.addSample(n,m.data,m)}),a=[]});const h={codec:s.codec==="aac"?"mp4a.40.2":"opus",sampleRate:s.sampleRate,numberOfChannels:s.channelCount,bitrate:128e3},d=new AudioEncoder({error:f=>{const m=`AudioEncoder error: ${f.message}, config: ${JSON.stringify(h)}, state: ${JSON.stringify({qSize:d.encodeQueueSize,state:d.state})}`;throw H.error(m),Error(m)},output:(f,m)=>{if(n===-1){const g=m?.decoderConfig?.description;n=t.addTrack({...r,description:g==null?void 0:Gd(g)}),e.emit("AudioReady"),H.info("AudioEncoder, audio track ready, trackId:",n)}if(l){const g=os(f);t.addSample(n,g.data,g)}else a.push(f)}});return d.configure(h),d}function Gd(s){const t=s.byteLength,e=new Uint8Array([0,0,0,0,3,23+t,0,2,0,4,18+t,64,21,0,0,0,0,0,0,0,0,0,0,0,5,t,...new Uint8Array(s instanceof ArrayBuffer?s:s.buffer),6,1,2]),r=new yt.BoxParser.esdsBox(e.byteLength);return r.hdr_size=0,r.parse(new yt.DataStream(e,0,yt.DataStream.BIG_ENDIAN)),r}function os(s){const t=new ArrayBuffer(s.byteLength);s.copyTo(t);const e=s.timestamp;return{duration:s.duration??0,dts:e,cts:e,is_sync:s.type==="key",data:t}}function Od(s){const e=s.codec.split("."),r=parseInt(e[1]||"0",10),n=parseInt(e[2]||"40",10),a=parseInt(e[3]||"08",10),l={bt709:1,bt601:5,bt2020:9},h={bt709:1,srgb:13,pq:16,hlg:18},d={bt709:1,bt601:5,bt2020:9},f=l[s.colorSpace?.primaries||"bt709"]||1,m=h[s.colorSpace?.transfer||"bt709"]||1,g=d[s.colorSpace?.matrix||"bt709"]||1,y=s.colorSpace?.fullRange?1:0,x=1,o=0,c=new ArrayBuffer(12),u=new DataView(c);let p=0;return u.setUint32(p,1<<24),p+=4,u.setUint8(p++,r),u.setUint8(p++,n),u.setUint8(p++,a<<4|x<<1|y),u.setUint8(p++,f),u.setUint8(p++,m),u.setUint8(p++,g),u.setUint16(p,o),c}function Ia(s,t){let e=!1;async function r(){const n=s.getReader();for(;!e;){const{value:a,done:l}=await n.read();if(l){t.onDone();return}await t.onChunk(a)}n.releaseLock(),await s.cancel()}return r().catch(console.error),()=>{e=!0}}function Fa(s,t,e){let r=0,n=0;const a=s.boxes;let l=!1;const h=()=>{if(!l)if(a.find(o=>o.type==="moof")!=null)l=!0;else return null;if(n>=a.length)return null;const y=new yt.DataStream;y.endianness=yt.DataStream.BIG_ENDIAN;let x=n;try{for(;x<a.length;)a[x].write(y),delete a[x],x+=1}catch(o){const c=a[x];throw o instanceof Error&&c!=null?Error(`${o.message} | deltaBuf( boxType: ${c.type}, boxSize: ${c.size}, boxDataLen: ${c.data?.length??-1})`):o}return Ld(s),n=a.length,new Uint8Array(y.buffer)};let d=!1,f=!1,m=null;return{stream:new ReadableStream({start(y){r=self.setInterval(()=>{const x=h();x!=null&&!f&&y.enqueue(x)},t),m=x=>{if(clearInterval(r),s.flush(),x!=null){y.error(x);return}const o=h();o!=null&&!f&&y.enqueue(o),f||y.close()},d&&m()},cancel(){f=!0,clearInterval(r),e?.()}}),stop:y=>{d||(d=!0,m?.(y))}}}function Ld(s){if(s.moov!=null){for(var t=0;t<s.moov.traks.length;t++)s.moov.traks[t].samples=[];s.mdats=[],s.moofs=[]}}class zd{constructor(t,e,r){this.length_=t,this.scaleFactor_=(t-1)/e,this.interpolate=this.cubic,r.method==="point"?this.interpolate=this.point:r.method==="linear"?this.interpolate=this.linear:r.method==="sinc"&&(this.interpolate=this.sinc),this.tangentFactor_=1-Math.max(0,Math.min(1,r.tension||0)),this.sincFilterSize_=r.sincFilterSize||1,this.kernel_=Hd(r.sincWindow||Nd)}point(t,e){return this.getClippedInput_(Math.round(this.scaleFactor_*t),e)}linear(t,e){t=this.scaleFactor_*t;let r=Math.floor(t);return t-=r,(1-t)*this.getClippedInput_(r,e)+t*this.getClippedInput_(r+1,e)}cubic(t,e){t=this.scaleFactor_*t;let r=Math.floor(t),n=[this.getTangent_(r,e),this.getTangent_(r+1,e)],a=[this.getClippedInput_(r,e),this.getClippedInput_(r+1,e)];t-=r;let l=t*t,h=t*l;return(2*h-3*l+1)*a[0]+(h-2*l+t)*n[0]+(-2*h+3*l)*a[1]+(h-l)*n[1]}sinc(t,e){t=this.scaleFactor_*t;let r=Math.floor(t),n=r-this.sincFilterSize_+1,a=r+this.sincFilterSize_,l=0;for(let h=n;h<=a;h++)l+=this.kernel_(t-h)*this.getClippedInput_(h,e);return l}getTangent_(t,e){return this.tangentFactor_*(this.getClippedInput_(t+1,e)-this.getClippedInput_(t-1,e))/2}getClippedInput_(t,e){return 0<=t&&t<this.length_?e[t]:0}}function Nd(s){return Math.exp(-s/2*s/2)}function Hd(s){return function(t){return Wd(t)*s(t)}}function Wd(s){return s===0?1:Math.sin(Math.PI*s)/(Math.PI*s)}class Vd{constructor(t,e,r){let n=2*Math.PI*r/e,a=0;this.filters=[];for(let l=0;l<=t;l++)l-t/2===0?this.filters[l]=n:(this.filters[l]=Math.sin(n*(l-t/2))/(l-t/2),this.filters[l]*=.54-.46*Math.cos(2*Math.PI*l/t)),a=a+this.filters[l];for(let l=0;l<=t;l++)this.filters[l]/=a;this.z=this.initZ_()}filter(t){this.z.buf[this.z.pointer]=t;let e=0;for(let r=0,n=this.z.buf.length;r<n;r++)e+=this.filters[r]*this.z.buf[(this.z.pointer+r)%this.z.buf.length];return this.z.pointer=(this.z.pointer+1)%this.z.buf.length,e}reset(){this.z=this.initZ_()}initZ_(){let t=[];for(let e=0;e<this.filters.length-1;e++)t.push(0);return{buf:t,pointer:0}}}class Yd{constructor(t,e,r){let n=[];for(let a=0;a<t;a++)n.push(this.getCoeffs_({Fs:e,Fc:r,Q:.5/Math.sin(Math.PI/(t*2)*(a+.5))}));this.stages=[];for(let a=0;a<n.length;a++)this.stages[a]={b0:n[a].b[0],b1:n[a].b[1],b2:n[a].b[2],a1:n[a].a[0],a2:n[a].a[1],k:n[a].k,z:[0,0]}}filter(t){let e=t;for(let r=0,n=this.stages.length;r<n;r++)e=this.runStage_(r,e);return e}getCoeffs_(t){let e={};e.z=[0,0],e.a=[],e.b=[];let r=this.preCalc_(t,e);return e.k=1,e.b.push((1-r.cw)/(2*r.a0)),e.b.push(2*e.b[0]),e.b.push(e.b[0]),e}preCalc_(t,e){let r={},n=2*Math.PI*t.Fc/t.Fs;return r.alpha=Math.sin(n)/(2*t.Q),r.cw=Math.cos(n),r.a0=1+r.alpha,e.a0=r.a0,e.a.push(-2*r.cw/r.a0),e.k=1,e.a.push((1-r.alpha)/r.a0),r}runStage_(t,e){let r=e*this.stages[t].k-this.stages[t].a1*this.stages[t].z[0]-this.stages[t].a2*this.stages[t].z[1],n=this.stages[t].b0*r+this.stages[t].b1*this.stages[t].z[0]+this.stages[t].b2*this.stages[t].z[1];return this.stages[t].z[1]=this.stages[t].z[0],this.stages[t].z[0]=r,n}reset(){for(let t=0;t<this.stages.length;t++)this.stages[t].z=[0,0]}}const Xd={point:!1,linear:!1,cubic:!0,sinc:!0},Da={IIR:16,FIR:71},$d={IIR:Yd,FIR:Vd};function Kd(s,t,e,r={}){let n=(e-t)/t+1,a=new Float64Array(s.length*n);r.method=r.method||"cubic";let l=new zd(s.length,a.length,{method:r.method,tension:r.tension||0,sincFilterSize:r.sincFilterSize||6,sincWindow:r.sincWindow||void 0});if(r.LPF===void 0&&(r.LPF=Xd[r.method]),r.LPF){r.LPFType=r.LPFType||"IIR";const h=$d[r.LPFType];if(e>t){let d=new h(r.LPFOrder||Da[r.LPFType],e,t/2);jd(s,a,l,d)}else{let d=new h(r.LPFOrder||Da[r.LPFType],t,e/2);qd(s,a,l,d)}}else Ga(s,a,l);return a}function Ga(s,t,e){for(let r=0,n=t.length;r<n;r++)t[r]=e.interpolate(r,s)}function jd(s,t,e,r){for(let n=0,a=t.length;n<a;n++)t[n]=r.filter(e.interpolate(n,s));r.reset();for(let n=t.length-1;n>=0;n--)t[n]=r.filter(t[n])}function qd(s,t,e,r){for(let n=0,a=s.length;n<a;n++)s[n]=r.filter(s[n]);r.reset();for(let n=s.length-1;n>=0;n--)s[n]=r.filter(s[n]);Ga(s,t,e)}function Zd(s){const t=new Float32Array(s.map(r=>r.length).reduce((r,n)=>r+n));let e=0;for(const r of s)t.set(r,e),e+=r.length;return t}function Oa(s){const t=[];for(let e=0;e<s.length;e+=1)for(let r=0;r<s[e].length;r+=1)t[r]==null&&(t[r]=[]),t[r].push(s[e][r]);return t.map(Zd)}function La(s){if(s.format==="f32-planar"){const t=[];for(let e=0;e<s.numberOfChannels;e+=1){const r=s.allocationSize({planeIndex:e}),n=new ArrayBuffer(r);s.copyTo(n,{planeIndex:e}),t.push(new Float32Array(n))}return t}else if(s.format==="f32"){const t=new ArrayBuffer(s.allocationSize({planeIndex:0}));return s.copyTo(t,{planeIndex:0}),Jd(new Float32Array(t),s.numberOfChannels)}else if(s.format==="s16"){const t=new ArrayBuffer(s.allocationSize({planeIndex:0}));return s.copyTo(t,{planeIndex:0}),Qd(new Int16Array(t),s.numberOfChannels)}throw Error("Unsupported audio data format")}function Qd(s,t){const e=s.length/t,r=Array.from({length:t},()=>new Float32Array(e));for(let n=0;n<e;n++)for(let a=0;a<t;a++){const l=s[n*t+a];r[a][n]=l/32768}return r}function Jd(s,t){const e=s.length/t,r=Array.from({length:t},()=>new Float32Array(e));for(let n=0;n<e;n++)for(let a=0;a<t;a++)r[a][n]=s[n*t+a];return r}function hs(s){return Array(s.numberOfChannels).fill(0).map((t,e)=>s.getChannelData(e))}function za(s){const t=Math.max(...s.map(r=>r[0]?.length??0)),e=new Float32Array(t*2);for(let r=0;r<t;r++){let n=0,a=0;for(let l=0;l<s.length;l++){const h=s[l][0]?.[r]??0,d=s[l][1]?.[r]??h;n+=h,a+=d}e[r]=n,e[r+t]=a}return e}async function tf(s,t,e){const r=s.length,n=Array(e.chanCount).fill(0).map(()=>new Float32Array(0));if(r===0)return n;const a=Math.max(...s.map(f=>f.length));if(a===0)return n;if(globalThis.OfflineAudioContext==null)return s.map(f=>new Float32Array(Kd(f,t,e.rate,{method:"sinc",LPF:!1})));const l=new globalThis.OfflineAudioContext(e.chanCount,a*e.rate/t,e.rate),h=l.createBufferSource(),d=l.createBuffer(r,a,t);return s.forEach((f,m)=>d.copyToChannel(new Float32Array(f),m)),h.buffer=d,h.connect(l.destination),h.start(),hs(await l.startRendering())}function ls(s,t,e){const r=e-t,n=new Float32Array(r);let a=0;for(;a<r;)n[a]=s[(t+a)%s.length],a+=1;return n}function Na(s,t){const e=Math.floor(s.length/t),r=new Float32Array(e);for(let n=0;n<e;n++){const a=n*t,l=Math.floor(a),h=a-l;l+1<s.length?r[n]=s[l]*(1-h)+s[l+1]*h:r[n]=s[l]}return r}const ef=`#version 300 es
|
|
1
|
+
(function(rt,ye){typeof exports=="object"&&typeof module<"u"?ye(exports):typeof define=="function"&&define.amd?define(["exports"],ye):(rt=typeof globalThis<"u"?globalThis:rt||self,ye(rt.core={}))})(this,(function(rt){"use strict";function ye(s){return s&&s.__esModule&&Object.prototype.hasOwnProperty.call(s,"default")?s.default:s}var Qr={},Co;function _u(){return Co||(Co=1,(function(s){var t=(function(){var a=new Date,c=4,d=3,p=2,_=1,b=c,v={setLogLevel:function(w){w==this.debug?b=_:w==this.info?b=p:w==this.warn?b=d:(w==this.error,b=c)},debug:function(w,S){console.debug===void 0&&(console.debug=console.log),_>=b&&console.debug("["+t.getDurationString(new Date-a,1e3)+"]","["+w+"]",S)},log:function(w,S){this.debug(w.msg)},info:function(w,S){p>=b&&console.info("["+t.getDurationString(new Date-a,1e3)+"]","["+w+"]",S)},warn:function(w,S){d>=b&&console.warn("["+t.getDurationString(new Date-a,1e3)+"]","["+w+"]",S)},error:function(w,S){c>=b&&console.error("["+t.getDurationString(new Date-a,1e3)+"]","["+w+"]",S)}};return v})();t.getDurationString=function(a,c){var d;function p(T,E){for(var P=""+T,B=P.split(".");B[0].length<E;)B[0]="0"+B[0];return B.join(".")}a<0?(d=!0,a=-a):d=!1;var _=c||1,b=a/_,v=Math.floor(b/3600);b-=v*3600;var w=Math.floor(b/60);b-=w*60;var S=b*1e3;return b=Math.floor(b),S-=b*1e3,S=Math.floor(S),(d?"-":"")+v+":"+p(w,2)+":"+p(b,2)+"."+p(S,3)},t.printRanges=function(a){var c=a.length;if(c>0){for(var d="",p=0;p<c;p++)p>0&&(d+=","),d+="["+t.getDurationString(a.start(p))+","+t.getDurationString(a.end(p))+"]";return d}else return"(empty)"},s.Log=t;var e=function(a){if(a instanceof ArrayBuffer)this.buffer=a,this.dataview=new DataView(a);else throw"Needs an array buffer";this.position=0};e.prototype.getPosition=function(){return this.position},e.prototype.getEndPosition=function(){return this.buffer.byteLength},e.prototype.getLength=function(){return this.buffer.byteLength},e.prototype.seek=function(a){var c=Math.max(0,Math.min(this.buffer.byteLength,a));return this.position=isNaN(c)||!isFinite(c)?0:c,!0},e.prototype.isEos=function(){return this.getPosition()>=this.getEndPosition()},e.prototype.readAnyInt=function(a,c){var d=0;if(this.position+a<=this.buffer.byteLength){switch(a){case 1:c?d=this.dataview.getInt8(this.position):d=this.dataview.getUint8(this.position);break;case 2:c?d=this.dataview.getInt16(this.position):d=this.dataview.getUint16(this.position);break;case 3:if(c)throw"No method for reading signed 24 bits values";d=this.dataview.getUint8(this.position)<<16,d|=this.dataview.getUint8(this.position+1)<<8,d|=this.dataview.getUint8(this.position+2);break;case 4:c?d=this.dataview.getInt32(this.position):d=this.dataview.getUint32(this.position);break;case 8:if(c)throw"No method for reading signed 64 bits values";d=this.dataview.getUint32(this.position)<<32,d|=this.dataview.getUint32(this.position+4);break;default:throw"readInt method not implemented for size: "+a}return this.position+=a,d}else throw"Not enough bytes in buffer"},e.prototype.readUint8=function(){return this.readAnyInt(1,!1)},e.prototype.readUint16=function(){return this.readAnyInt(2,!1)},e.prototype.readUint24=function(){return this.readAnyInt(3,!1)},e.prototype.readUint32=function(){return this.readAnyInt(4,!1)},e.prototype.readUint64=function(){return this.readAnyInt(8,!1)},e.prototype.readString=function(a){if(this.position+a<=this.buffer.byteLength){for(var c="",d=0;d<a;d++)c+=String.fromCharCode(this.readUint8());return c}else throw"Not enough bytes in buffer"},e.prototype.readCString=function(){for(var a=[];;){var c=this.readUint8();if(c!==0)a.push(c);else break}return String.fromCharCode.apply(null,a)},e.prototype.readInt8=function(){return this.readAnyInt(1,!0)},e.prototype.readInt16=function(){return this.readAnyInt(2,!0)},e.prototype.readInt32=function(){return this.readAnyInt(4,!0)},e.prototype.readInt64=function(){return this.readAnyInt(8,!1)},e.prototype.readUint8Array=function(a){for(var c=new Uint8Array(a),d=0;d<a;d++)c[d]=this.readUint8();return c},e.prototype.readInt16Array=function(a){for(var c=new Int16Array(a),d=0;d<a;d++)c[d]=this.readInt16();return c},e.prototype.readUint16Array=function(a){for(var c=new Int16Array(a),d=0;d<a;d++)c[d]=this.readUint16();return c},e.prototype.readUint32Array=function(a){for(var c=new Uint32Array(a),d=0;d<a;d++)c[d]=this.readUint32();return c},e.prototype.readInt32Array=function(a){for(var c=new Int32Array(a),d=0;d<a;d++)c[d]=this.readInt32();return c},s.MP4BoxStream=e;var r=function(a,c,d){this._byteOffset=c||0,a instanceof ArrayBuffer?this.buffer=a:typeof a=="object"?(this.dataView=a,c&&(this._byteOffset+=c)):this.buffer=new ArrayBuffer(a||0),this.position=0,this.endianness=d??r.LITTLE_ENDIAN};r.prototype={},r.prototype.getPosition=function(){return this.position},r.prototype._realloc=function(a){if(this._dynamicSize){var c=this._byteOffset+this.position+a,d=this._buffer.byteLength;if(c<=d){c>this._byteLength&&(this._byteLength=c);return}for(d<1&&(d=1);c>d;)d*=2;var p=new ArrayBuffer(d),_=new Uint8Array(this._buffer),b=new Uint8Array(p,0,_.length);b.set(_),this.buffer=p,this._byteLength=c}},r.prototype._trimAlloc=function(){if(this._byteLength!=this._buffer.byteLength){var a=new ArrayBuffer(this._byteLength),c=new Uint8Array(a),d=new Uint8Array(this._buffer,0,c.length);c.set(d),this.buffer=a}},r.BIG_ENDIAN=!1,r.LITTLE_ENDIAN=!0,r.prototype._byteLength=0,Object.defineProperty(r.prototype,"byteLength",{get:function(){return this._byteLength-this._byteOffset}}),Object.defineProperty(r.prototype,"buffer",{get:function(){return this._trimAlloc(),this._buffer},set:function(a){this._buffer=a,this._dataView=new DataView(this._buffer,this._byteOffset),this._byteLength=this._buffer.byteLength}}),Object.defineProperty(r.prototype,"byteOffset",{get:function(){return this._byteOffset},set:function(a){this._byteOffset=a,this._dataView=new DataView(this._buffer,this._byteOffset),this._byteLength=this._buffer.byteLength}}),Object.defineProperty(r.prototype,"dataView",{get:function(){return this._dataView},set:function(a){this._byteOffset=a.byteOffset,this._buffer=a.buffer,this._dataView=new DataView(this._buffer,this._byteOffset),this._byteLength=this._byteOffset+a.byteLength}}),r.prototype.seek=function(a){var c=Math.max(0,Math.min(this.byteLength,a));this.position=isNaN(c)||!isFinite(c)?0:c},r.prototype.isEof=function(){return this.position>=this._byteLength},r.prototype.mapUint8Array=function(a){this._realloc(a*1);var c=new Uint8Array(this._buffer,this.byteOffset+this.position,a);return this.position+=a*1,c},r.prototype.readInt32Array=function(a,c){a=a??this.byteLength-this.position/4;var d=new Int32Array(a);return r.memcpy(d.buffer,0,this.buffer,this.byteOffset+this.position,a*d.BYTES_PER_ELEMENT),r.arrayToNative(d,c??this.endianness),this.position+=d.byteLength,d},r.prototype.readInt16Array=function(a,c){a=a??this.byteLength-this.position/2;var d=new Int16Array(a);return r.memcpy(d.buffer,0,this.buffer,this.byteOffset+this.position,a*d.BYTES_PER_ELEMENT),r.arrayToNative(d,c??this.endianness),this.position+=d.byteLength,d},r.prototype.readInt8Array=function(a){a=a??this.byteLength-this.position;var c=new Int8Array(a);return r.memcpy(c.buffer,0,this.buffer,this.byteOffset+this.position,a*c.BYTES_PER_ELEMENT),this.position+=c.byteLength,c},r.prototype.readUint32Array=function(a,c){a=a??this.byteLength-this.position/4;var d=new Uint32Array(a);return r.memcpy(d.buffer,0,this.buffer,this.byteOffset+this.position,a*d.BYTES_PER_ELEMENT),r.arrayToNative(d,c??this.endianness),this.position+=d.byteLength,d},r.prototype.readUint16Array=function(a,c){a=a??this.byteLength-this.position/2;var d=new Uint16Array(a);return r.memcpy(d.buffer,0,this.buffer,this.byteOffset+this.position,a*d.BYTES_PER_ELEMENT),r.arrayToNative(d,c??this.endianness),this.position+=d.byteLength,d},r.prototype.readUint8Array=function(a){a=a??this.byteLength-this.position;var c=new Uint8Array(a);return r.memcpy(c.buffer,0,this.buffer,this.byteOffset+this.position,a*c.BYTES_PER_ELEMENT),this.position+=c.byteLength,c},r.prototype.readFloat64Array=function(a,c){a=a??this.byteLength-this.position/8;var d=new Float64Array(a);return r.memcpy(d.buffer,0,this.buffer,this.byteOffset+this.position,a*d.BYTES_PER_ELEMENT),r.arrayToNative(d,c??this.endianness),this.position+=d.byteLength,d},r.prototype.readFloat32Array=function(a,c){a=a??this.byteLength-this.position/4;var d=new Float32Array(a);return r.memcpy(d.buffer,0,this.buffer,this.byteOffset+this.position,a*d.BYTES_PER_ELEMENT),r.arrayToNative(d,c??this.endianness),this.position+=d.byteLength,d},r.prototype.readInt32=function(a){var c=this._dataView.getInt32(this.position,a??this.endianness);return this.position+=4,c},r.prototype.readInt16=function(a){var c=this._dataView.getInt16(this.position,a??this.endianness);return this.position+=2,c},r.prototype.readInt8=function(){var a=this._dataView.getInt8(this.position);return this.position+=1,a},r.prototype.readUint32=function(a){var c=this._dataView.getUint32(this.position,a??this.endianness);return this.position+=4,c},r.prototype.readUint16=function(a){var c=this._dataView.getUint16(this.position,a??this.endianness);return this.position+=2,c},r.prototype.readUint8=function(){var a=this._dataView.getUint8(this.position);return this.position+=1,a},r.prototype.readFloat32=function(a){var c=this._dataView.getFloat32(this.position,a??this.endianness);return this.position+=4,c},r.prototype.readFloat64=function(a){var c=this._dataView.getFloat64(this.position,a??this.endianness);return this.position+=8,c},r.endianness=new Int8Array(new Int16Array([1]).buffer)[0]>0,r.memcpy=function(a,c,d,p,_){var b=new Uint8Array(a,c,_),v=new Uint8Array(d,p,_);b.set(v)},r.arrayToNative=function(a,c){return c==this.endianness?a:this.flipArrayEndianness(a)},r.nativeToEndian=function(a,c){return this.endianness==c?a:this.flipArrayEndianness(a)},r.flipArrayEndianness=function(a){for(var c=new Uint8Array(a.buffer,a.byteOffset,a.byteLength),d=0;d<a.byteLength;d+=a.BYTES_PER_ELEMENT)for(var p=d+a.BYTES_PER_ELEMENT-1,_=d;p>_;p--,_++){var b=c[_];c[_]=c[p],c[p]=b}return a},r.prototype.failurePosition=0,String.fromCharCodeUint8=function(a){for(var c=[],d=0;d<a.length;d++)c[d]=a[d];return String.fromCharCode.apply(null,c)},r.prototype.readString=function(a,c){return c==null||c=="ASCII"?String.fromCharCodeUint8.apply(null,[this.mapUint8Array(a??this.byteLength-this.position)]):new TextDecoder(c).decode(this.mapUint8Array(a))},r.prototype.readCString=function(a){var c=this.byteLength-this.position,d=new Uint8Array(this._buffer,this._byteOffset+this.position),p=c;a!=null&&(p=Math.min(a,c));for(var _=0;_<p&&d[_]!==0;_++);var b=String.fromCharCodeUint8.apply(null,[this.mapUint8Array(_)]);return a!=null?this.position+=p-_:_!=c&&(this.position+=1),b};var n=Math.pow(2,32);r.prototype.readInt64=function(){return this.readInt32()*n+this.readUint32()},r.prototype.readUint64=function(){return this.readUint32()*n+this.readUint32()},r.prototype.readInt64=function(){return this.readUint32()*n+this.readUint32()},r.prototype.readUint24=function(){return(this.readUint8()<<16)+(this.readUint8()<<8)+this.readUint8()},s.DataStream=r,r.prototype.save=function(a){var c=new Blob([this.buffer]);if(window.URL&&URL.createObjectURL){var d=window.URL.createObjectURL(c),p=document.createElement("a");document.body.appendChild(p),p.setAttribute("href",d),p.setAttribute("download",a),p.setAttribute("target","_self"),p.click(),window.URL.revokeObjectURL(d)}else throw"DataStream.save: Can't create object URL."},r.prototype._dynamicSize=!0,Object.defineProperty(r.prototype,"dynamicSize",{get:function(){return this._dynamicSize},set:function(a){a||this._trimAlloc(),this._dynamicSize=a}}),r.prototype.shift=function(a){var c=new ArrayBuffer(this._byteLength-a),d=new Uint8Array(c),p=new Uint8Array(this._buffer,a,d.length);d.set(p),this.buffer=c,this.position-=a},r.prototype.writeInt32Array=function(a,c){if(this._realloc(a.length*4),a instanceof Int32Array&&this.byteOffset+this.position%a.BYTES_PER_ELEMENT===0)r.memcpy(this._buffer,this.byteOffset+this.position,a.buffer,0,a.byteLength),this.mapInt32Array(a.length,c);else for(var d=0;d<a.length;d++)this.writeInt32(a[d],c)},r.prototype.writeInt16Array=function(a,c){if(this._realloc(a.length*2),a instanceof Int16Array&&this.byteOffset+this.position%a.BYTES_PER_ELEMENT===0)r.memcpy(this._buffer,this.byteOffset+this.position,a.buffer,0,a.byteLength),this.mapInt16Array(a.length,c);else for(var d=0;d<a.length;d++)this.writeInt16(a[d],c)},r.prototype.writeInt8Array=function(a){if(this._realloc(a.length*1),a instanceof Int8Array&&this.byteOffset+this.position%a.BYTES_PER_ELEMENT===0)r.memcpy(this._buffer,this.byteOffset+this.position,a.buffer,0,a.byteLength),this.mapInt8Array(a.length);else for(var c=0;c<a.length;c++)this.writeInt8(a[c])},r.prototype.writeUint32Array=function(a,c){if(this._realloc(a.length*4),a instanceof Uint32Array&&this.byteOffset+this.position%a.BYTES_PER_ELEMENT===0)r.memcpy(this._buffer,this.byteOffset+this.position,a.buffer,0,a.byteLength),this.mapUint32Array(a.length,c);else for(var d=0;d<a.length;d++)this.writeUint32(a[d],c)},r.prototype.writeUint16Array=function(a,c){if(this._realloc(a.length*2),a instanceof Uint16Array&&this.byteOffset+this.position%a.BYTES_PER_ELEMENT===0)r.memcpy(this._buffer,this.byteOffset+this.position,a.buffer,0,a.byteLength),this.mapUint16Array(a.length,c);else for(var d=0;d<a.length;d++)this.writeUint16(a[d],c)},r.prototype.writeUint8Array=function(a){if(this._realloc(a.length*1),a instanceof Uint8Array&&this.byteOffset+this.position%a.BYTES_PER_ELEMENT===0)r.memcpy(this._buffer,this.byteOffset+this.position,a.buffer,0,a.byteLength),this.mapUint8Array(a.length);else for(var c=0;c<a.length;c++)this.writeUint8(a[c])},r.prototype.writeFloat64Array=function(a,c){if(this._realloc(a.length*8),a instanceof Float64Array&&this.byteOffset+this.position%a.BYTES_PER_ELEMENT===0)r.memcpy(this._buffer,this.byteOffset+this.position,a.buffer,0,a.byteLength),this.mapFloat64Array(a.length,c);else for(var d=0;d<a.length;d++)this.writeFloat64(a[d],c)},r.prototype.writeFloat32Array=function(a,c){if(this._realloc(a.length*4),a instanceof Float32Array&&this.byteOffset+this.position%a.BYTES_PER_ELEMENT===0)r.memcpy(this._buffer,this.byteOffset+this.position,a.buffer,0,a.byteLength),this.mapFloat32Array(a.length,c);else for(var d=0;d<a.length;d++)this.writeFloat32(a[d],c)},r.prototype.writeInt32=function(a,c){this._realloc(4),this._dataView.setInt32(this.position,a,c??this.endianness),this.position+=4},r.prototype.writeInt16=function(a,c){this._realloc(2),this._dataView.setInt16(this.position,a,c??this.endianness),this.position+=2},r.prototype.writeInt8=function(a){this._realloc(1),this._dataView.setInt8(this.position,a),this.position+=1},r.prototype.writeUint32=function(a,c){this._realloc(4),this._dataView.setUint32(this.position,a,c??this.endianness),this.position+=4},r.prototype.writeUint16=function(a,c){this._realloc(2),this._dataView.setUint16(this.position,a,c??this.endianness),this.position+=2},r.prototype.writeUint8=function(a){this._realloc(1),this._dataView.setUint8(this.position,a),this.position+=1},r.prototype.writeFloat32=function(a,c){this._realloc(4),this._dataView.setFloat32(this.position,a,c??this.endianness),this.position+=4},r.prototype.writeFloat64=function(a,c){this._realloc(8),this._dataView.setFloat64(this.position,a,c??this.endianness),this.position+=8},r.prototype.writeUCS2String=function(a,c,d){d==null&&(d=a.length);for(var p=0;p<a.length&&p<d;p++)this.writeUint16(a.charCodeAt(p),c);for(;p<d;p++)this.writeUint16(0)},r.prototype.writeString=function(a,c,d){var p=0;if(c==null||c=="ASCII")if(d!=null){var _=Math.min(a.length,d);for(p=0;p<_;p++)this.writeUint8(a.charCodeAt(p));for(;p<d;p++)this.writeUint8(0)}else for(p=0;p<a.length;p++)this.writeUint8(a.charCodeAt(p));else this.writeUint8Array(new TextEncoder(c).encode(a.substring(0,d)))},r.prototype.writeCString=function(a,c){var d=0;if(c!=null){var p=Math.min(a.length,c);for(d=0;d<p;d++)this.writeUint8(a.charCodeAt(d));for(;d<c;d++)this.writeUint8(0)}else{for(d=0;d<a.length;d++)this.writeUint8(a.charCodeAt(d));this.writeUint8(0)}},r.prototype.writeStruct=function(a,c){for(var d=0;d<a.length;d+=2){var p=a[d+1];this.writeType(p,c[a[d]],c)}},r.prototype.writeType=function(a,c,d){var p;if(typeof a=="function")return a(this,c);if(typeof a=="object"&&!(a instanceof Array))return a.set(this,c,d);var _=null,b="ASCII",v=this.position;switch(typeof a=="string"&&/:/.test(a)&&(p=a.split(":"),a=p[0],_=parseInt(p[1])),typeof a=="string"&&/,/.test(a)&&(p=a.split(","),a=p[0],b=parseInt(p[1])),a){case"uint8":this.writeUint8(c);break;case"int8":this.writeInt8(c);break;case"uint16":this.writeUint16(c,this.endianness);break;case"int16":this.writeInt16(c,this.endianness);break;case"uint32":this.writeUint32(c,this.endianness);break;case"int32":this.writeInt32(c,this.endianness);break;case"float32":this.writeFloat32(c,this.endianness);break;case"float64":this.writeFloat64(c,this.endianness);break;case"uint16be":this.writeUint16(c,r.BIG_ENDIAN);break;case"int16be":this.writeInt16(c,r.BIG_ENDIAN);break;case"uint32be":this.writeUint32(c,r.BIG_ENDIAN);break;case"int32be":this.writeInt32(c,r.BIG_ENDIAN);break;case"float32be":this.writeFloat32(c,r.BIG_ENDIAN);break;case"float64be":this.writeFloat64(c,r.BIG_ENDIAN);break;case"uint16le":this.writeUint16(c,r.LITTLE_ENDIAN);break;case"int16le":this.writeInt16(c,r.LITTLE_ENDIAN);break;case"uint32le":this.writeUint32(c,r.LITTLE_ENDIAN);break;case"int32le":this.writeInt32(c,r.LITTLE_ENDIAN);break;case"float32le":this.writeFloat32(c,r.LITTLE_ENDIAN);break;case"float64le":this.writeFloat64(c,r.LITTLE_ENDIAN);break;case"cstring":this.writeCString(c,_);break;case"string":this.writeString(c,b,_);break;case"u16string":this.writeUCS2String(c,this.endianness,_);break;case"u16stringle":this.writeUCS2String(c,r.LITTLE_ENDIAN,_);break;case"u16stringbe":this.writeUCS2String(c,r.BIG_ENDIAN,_);break;default:if(a.length==3){for(var w=a[1],S=0;S<c.length;S++)this.writeType(w,c[S]);break}else{this.writeStruct(a,c);break}}_!=null&&(this.position=v,this._realloc(_),this.position=v+_)},r.prototype.writeUint64=function(a){var c=Math.floor(a/n);this.writeUint32(c),this.writeUint32(a&4294967295)},r.prototype.writeUint24=function(a){this.writeUint8((a&16711680)>>16),this.writeUint8((a&65280)>>8),this.writeUint8(a&255)},r.prototype.adjustUint32=function(a,c){var d=this.position;this.seek(a),this.writeUint32(c),this.seek(d)},r.prototype.mapInt32Array=function(a,c){this._realloc(a*4);var d=new Int32Array(this._buffer,this.byteOffset+this.position,a);return r.arrayToNative(d,c??this.endianness),this.position+=a*4,d},r.prototype.mapInt16Array=function(a,c){this._realloc(a*2);var d=new Int16Array(this._buffer,this.byteOffset+this.position,a);return r.arrayToNative(d,c??this.endianness),this.position+=a*2,d},r.prototype.mapInt8Array=function(a){this._realloc(a*1);var c=new Int8Array(this._buffer,this.byteOffset+this.position,a);return this.position+=a*1,c},r.prototype.mapUint32Array=function(a,c){this._realloc(a*4);var d=new Uint32Array(this._buffer,this.byteOffset+this.position,a);return r.arrayToNative(d,c??this.endianness),this.position+=a*4,d},r.prototype.mapUint16Array=function(a,c){this._realloc(a*2);var d=new Uint16Array(this._buffer,this.byteOffset+this.position,a);return r.arrayToNative(d,c??this.endianness),this.position+=a*2,d},r.prototype.mapFloat64Array=function(a,c){this._realloc(a*8);var d=new Float64Array(this._buffer,this.byteOffset+this.position,a);return r.arrayToNative(d,c??this.endianness),this.position+=a*8,d},r.prototype.mapFloat32Array=function(a,c){this._realloc(a*4);var d=new Float32Array(this._buffer,this.byteOffset+this.position,a);return r.arrayToNative(d,c??this.endianness),this.position+=a*4,d};var o=function(a){this.buffers=[],this.bufferIndex=-1,a&&(this.insertBuffer(a),this.bufferIndex=0)};o.prototype=new r(new ArrayBuffer,0,r.BIG_ENDIAN),o.prototype.initialized=function(){var a;return this.bufferIndex>-1?!0:this.buffers.length>0?(a=this.buffers[0],a.fileStart===0?(this.buffer=a,this.bufferIndex=0,t.debug("MultiBufferStream","Stream ready for parsing"),!0):(t.warn("MultiBufferStream","The first buffer should have a fileStart of 0"),this.logBufferLevel(),!1)):(t.warn("MultiBufferStream","No buffer to start parsing from"),this.logBufferLevel(),!1)},ArrayBuffer.concat=function(a,c){t.debug("ArrayBuffer","Trying to create a new buffer of size: "+(a.byteLength+c.byteLength));var d=new Uint8Array(a.byteLength+c.byteLength);return d.set(new Uint8Array(a),0),d.set(new Uint8Array(c),a.byteLength),d.buffer},o.prototype.reduceBuffer=function(a,c,d){var p;return p=new Uint8Array(d),p.set(new Uint8Array(a,c,d)),p.buffer.fileStart=a.fileStart+c,p.buffer.usedBytes=0,p.buffer},o.prototype.insertBuffer=function(a){for(var c=!0,d=0;d<this.buffers.length;d++){var p=this.buffers[d];if(a.fileStart<=p.fileStart){if(a.fileStart===p.fileStart)if(a.byteLength>p.byteLength){this.buffers.splice(d,1),d--;continue}else t.warn("MultiBufferStream","Buffer (fileStart: "+a.fileStart+" - Length: "+a.byteLength+") already appended, ignoring");else a.fileStart+a.byteLength<=p.fileStart||(a=this.reduceBuffer(a,0,p.fileStart-a.fileStart)),t.debug("MultiBufferStream","Appending new buffer (fileStart: "+a.fileStart+" - Length: "+a.byteLength+")"),this.buffers.splice(d,0,a),d===0&&(this.buffer=a);c=!1;break}else if(a.fileStart<p.fileStart+p.byteLength){var _=p.fileStart+p.byteLength-a.fileStart,b=a.byteLength-_;if(b>0)a=this.reduceBuffer(a,_,b);else{c=!1;break}}}c&&(t.debug("MultiBufferStream","Appending new buffer (fileStart: "+a.fileStart+" - Length: "+a.byteLength+")"),this.buffers.push(a),d===0&&(this.buffer=a))},o.prototype.logBufferLevel=function(a){var c,d,p,_,b=[],v,w="";for(p=0,_=0,c=0;c<this.buffers.length;c++)d=this.buffers[c],c===0?(v={},b.push(v),v.start=d.fileStart,v.end=d.fileStart+d.byteLength,w+="["+v.start+"-"):v.end===d.fileStart?v.end=d.fileStart+d.byteLength:(v={},v.start=d.fileStart,w+=b[b.length-1].end-1+"], ["+v.start+"-",v.end=d.fileStart+d.byteLength,b.push(v)),p+=d.usedBytes,_+=d.byteLength;b.length>0&&(w+=v.end-1+"]");var S=a?t.info:t.debug;this.buffers.length===0?S("MultiBufferStream","No more buffer in memory"):S("MultiBufferStream",""+this.buffers.length+" stored buffer(s) ("+p+"/"+_+" bytes), continuous ranges: "+w)},o.prototype.cleanBuffers=function(){var a,c;for(a=0;a<this.buffers.length;a++)c=this.buffers[a],c.usedBytes===c.byteLength&&(t.debug("MultiBufferStream","Removing buffer #"+a),this.buffers.splice(a,1),a--)},o.prototype.mergeNextBuffer=function(){var a;if(this.bufferIndex+1<this.buffers.length)if(a=this.buffers[this.bufferIndex+1],a.fileStart===this.buffer.fileStart+this.buffer.byteLength){var c=this.buffer.byteLength,d=this.buffer.usedBytes,p=this.buffer.fileStart;return this.buffers[this.bufferIndex]=ArrayBuffer.concat(this.buffer,a),this.buffer=this.buffers[this.bufferIndex],this.buffers.splice(this.bufferIndex+1,1),this.buffer.usedBytes=d,this.buffer.fileStart=p,t.debug("ISOFile","Concatenating buffer for box parsing (length: "+c+"->"+this.buffer.byteLength+")"),!0}else return!1;else return!1},o.prototype.findPosition=function(a,c,d){var p,_=null,b=-1;for(a===!0?p=0:p=this.bufferIndex;p<this.buffers.length&&(_=this.buffers[p],_.fileStart<=c);){b=p,d&&(_.fileStart+_.byteLength<=c?_.usedBytes=_.byteLength:_.usedBytes=c-_.fileStart,this.logBufferLevel());p++}return b!==-1?(_=this.buffers[b],_.fileStart+_.byteLength>=c?(t.debug("MultiBufferStream","Found position in existing buffer #"+b),b):-1):-1},o.prototype.findEndContiguousBuf=function(a){var c,d,p,_=a!==void 0?a:this.bufferIndex;if(d=this.buffers[_],this.buffers.length>_+1)for(c=_+1;c<this.buffers.length&&(p=this.buffers[c],p.fileStart===d.fileStart+d.byteLength);c++)d=p;return d.fileStart+d.byteLength},o.prototype.getEndFilePositionAfter=function(a){var c=this.findPosition(!0,a,!1);return c!==-1?this.findEndContiguousBuf(c):a},o.prototype.addUsedBytes=function(a){this.buffer.usedBytes+=a,this.logBufferLevel()},o.prototype.setAllUsedBytes=function(){this.buffer.usedBytes=this.buffer.byteLength,this.logBufferLevel()},o.prototype.seek=function(a,c,d){var p;return p=this.findPosition(c,a,d),p!==-1?(this.buffer=this.buffers[p],this.bufferIndex=p,this.position=a-this.buffer.fileStart,t.debug("MultiBufferStream","Repositioning parser at buffer position: "+this.position),!0):(t.debug("MultiBufferStream","Position "+a+" not found in buffered data"),!1)},o.prototype.getPosition=function(){if(this.bufferIndex===-1||this.buffers[this.bufferIndex]===null)throw"Error accessing position in the MultiBufferStream";return this.buffers[this.bufferIndex].fileStart+this.position},o.prototype.getLength=function(){return this.byteLength},o.prototype.getEndPosition=function(){if(this.bufferIndex===-1||this.buffers[this.bufferIndex]===null)throw"Error accessing position in the MultiBufferStream";return this.buffers[this.bufferIndex].fileStart+this.byteLength},s.MultiBufferStream=o;var l=function(){var a=3,c=4,d=5,p=6,_=[];_[a]="ES_Descriptor",_[c]="DecoderConfigDescriptor",_[d]="DecoderSpecificInfo",_[p]="SLConfigDescriptor",this.getDescriptorName=function(w){return _[w]};var b=this,v={};return this.parseOneDescriptor=function(w){var S=0,T,E,P;for(T=w.readUint8(),P=w.readUint8();P&128;)S=(P&127)<<7,P=w.readUint8();return S+=P&127,t.debug("MPEG4DescriptorParser","Found "+(_[T]||"Descriptor "+T)+", size "+S+" at position "+w.getPosition()),_[T]?E=new v[_[T]](S):E=new v.Descriptor(S),E.parse(w),E},v.Descriptor=function(w,S){this.tag=w,this.size=S,this.descs=[]},v.Descriptor.prototype.parse=function(w){this.data=w.readUint8Array(this.size)},v.Descriptor.prototype.findDescriptor=function(w){for(var S=0;S<this.descs.length;S++)if(this.descs[S].tag==w)return this.descs[S];return null},v.Descriptor.prototype.parseRemainingDescriptors=function(w){for(var S=w.position;w.position<S+this.size;){var T=b.parseOneDescriptor(w);this.descs.push(T)}},v.ES_Descriptor=function(w){v.Descriptor.call(this,a,w)},v.ES_Descriptor.prototype=new v.Descriptor,v.ES_Descriptor.prototype.parse=function(w){if(this.ES_ID=w.readUint16(),this.flags=w.readUint8(),this.size-=3,this.flags&128?(this.dependsOn_ES_ID=w.readUint16(),this.size-=2):this.dependsOn_ES_ID=0,this.flags&64){var S=w.readUint8();this.URL=w.readString(S),this.size-=S+1}else this.URL="";this.flags&32?(this.OCR_ES_ID=w.readUint16(),this.size-=2):this.OCR_ES_ID=0,this.parseRemainingDescriptors(w)},v.ES_Descriptor.prototype.getOTI=function(w){var S=this.findDescriptor(c);return S?S.oti:0},v.ES_Descriptor.prototype.getAudioConfig=function(w){var S=this.findDescriptor(c);if(!S)return null;var T=S.findDescriptor(d);if(T&&T.data){var E=(T.data[0]&248)>>3;return E===31&&T.data.length>=2&&(E=32+((T.data[0]&7)<<3)+((T.data[1]&224)>>5)),E}else return null},v.DecoderConfigDescriptor=function(w){v.Descriptor.call(this,c,w)},v.DecoderConfigDescriptor.prototype=new v.Descriptor,v.DecoderConfigDescriptor.prototype.parse=function(w){this.oti=w.readUint8(),this.streamType=w.readUint8(),this.upStream=(this.streamType>>1&1)!==0,this.streamType=this.streamType>>>2,this.bufferSize=w.readUint24(),this.maxBitrate=w.readUint32(),this.avgBitrate=w.readUint32(),this.size-=13,this.parseRemainingDescriptors(w)},v.DecoderSpecificInfo=function(w){v.Descriptor.call(this,d,w)},v.DecoderSpecificInfo.prototype=new v.Descriptor,v.SLConfigDescriptor=function(w){v.Descriptor.call(this,p,w)},v.SLConfigDescriptor.prototype=new v.Descriptor,this};s.MPEG4DescriptorParser=l;var h={ERR_INVALID_DATA:-1,ERR_NOT_ENOUGH_DATA:0,OK:1,BASIC_BOXES:["mdat","idat","free","skip","meco","strk"],FULL_BOXES:["hmhd","nmhd","iods","xml ","bxml","ipro","mere"],CONTAINER_BOXES:[["moov",["trak","pssh"]],["trak"],["edts"],["mdia"],["minf"],["dinf"],["stbl",["sgpd","sbgp"]],["mvex",["trex"]],["moof",["traf"]],["traf",["trun","sgpd","sbgp"]],["vttc"],["tref"],["iref"],["mfra",["tfra"]],["meco"],["hnti"],["hinf"],["strk"],["strd"],["sinf"],["rinf"],["schi"],["trgr"],["udta",["kind"]],["iprp",["ipma"]],["ipco"],["grpl"],["j2kH"],["etyp",["tyco"]]],boxCodes:[],fullBoxCodes:[],containerBoxCodes:[],sampleEntryCodes:{},sampleGroupEntryCodes:[],trackGroupTypes:[],UUIDBoxes:{},UUIDs:[],initialize:function(){h.FullBox.prototype=new h.Box,h.ContainerBox.prototype=new h.Box,h.SampleEntry.prototype=new h.Box,h.TrackGroupTypeBox.prototype=new h.FullBox,h.BASIC_BOXES.forEach(function(a){h.createBoxCtor(a)}),h.FULL_BOXES.forEach(function(a){h.createFullBoxCtor(a)}),h.CONTAINER_BOXES.forEach(function(a){h.createContainerBoxCtor(a[0],null,a[1])})},Box:function(a,c,d){this.type=a,this.size=c,this.uuid=d},FullBox:function(a,c,d){h.Box.call(this,a,c,d),this.flags=0,this.version=0},ContainerBox:function(a,c,d){h.Box.call(this,a,c,d),this.boxes=[]},SampleEntry:function(a,c,d,p){h.ContainerBox.call(this,a,c),this.hdr_size=d,this.start=p},SampleGroupEntry:function(a){this.grouping_type=a},TrackGroupTypeBox:function(a,c){h.FullBox.call(this,a,c)},createBoxCtor:function(a,c){h.boxCodes.push(a),h[a+"Box"]=function(d){h.Box.call(this,a,d)},h[a+"Box"].prototype=new h.Box,c&&(h[a+"Box"].prototype.parse=c)},createFullBoxCtor:function(a,c){h[a+"Box"]=function(d){h.FullBox.call(this,a,d)},h[a+"Box"].prototype=new h.FullBox,h[a+"Box"].prototype.parse=function(d){this.parseFullHeader(d),c&&c.call(this,d)}},addSubBoxArrays:function(a){if(a){this.subBoxNames=a;for(var c=a.length,d=0;d<c;d++)this[a[d]+"s"]=[]}},createContainerBoxCtor:function(a,c,d){h[a+"Box"]=function(p){h.ContainerBox.call(this,a,p),h.addSubBoxArrays.call(this,d)},h[a+"Box"].prototype=new h.ContainerBox,c&&(h[a+"Box"].prototype.parse=c)},createMediaSampleEntryCtor:function(a,c,d){h.sampleEntryCodes[a]=[],h[a+"SampleEntry"]=function(p,_){h.SampleEntry.call(this,p,_),h.addSubBoxArrays.call(this,d)},h[a+"SampleEntry"].prototype=new h.SampleEntry,c&&(h[a+"SampleEntry"].prototype.parse=c)},createSampleEntryCtor:function(a,c,d,p){h.sampleEntryCodes[a].push(c),h[c+"SampleEntry"]=function(_){h[a+"SampleEntry"].call(this,c,_),h.addSubBoxArrays.call(this,p)},h[c+"SampleEntry"].prototype=new h[a+"SampleEntry"],d&&(h[c+"SampleEntry"].prototype.parse=d)},createEncryptedSampleEntryCtor:function(a,c,d){h.createSampleEntryCtor.call(this,a,c,d,["sinf"])},createSampleGroupCtor:function(a,c){h[a+"SampleGroupEntry"]=function(d){h.SampleGroupEntry.call(this,a,d)},h[a+"SampleGroupEntry"].prototype=new h.SampleGroupEntry,c&&(h[a+"SampleGroupEntry"].prototype.parse=c)},createTrackGroupCtor:function(a,c){h[a+"TrackGroupTypeBox"]=function(d){h.TrackGroupTypeBox.call(this,a,d)},h[a+"TrackGroupTypeBox"].prototype=new h.TrackGroupTypeBox,c&&(h[a+"TrackGroupTypeBox"].prototype.parse=c)},createUUIDBox:function(a,c,d,p){h.UUIDs.push(a),h.UUIDBoxes[a]=function(_){c?h.FullBox.call(this,"uuid",_,a):d?h.ContainerBox.call(this,"uuid",_,a):h.Box.call(this,"uuid",_,a)},h.UUIDBoxes[a].prototype=c?new h.FullBox:d?new h.ContainerBox:new h.Box,p&&(c?h.UUIDBoxes[a].prototype.parse=function(_){this.parseFullHeader(_),p&&p.call(this,_)}:h.UUIDBoxes[a].prototype.parse=p)}};h.initialize(),h.TKHD_FLAG_ENABLED=1,h.TKHD_FLAG_IN_MOVIE=2,h.TKHD_FLAG_IN_PREVIEW=4,h.TFHD_FLAG_BASE_DATA_OFFSET=1,h.TFHD_FLAG_SAMPLE_DESC=2,h.TFHD_FLAG_SAMPLE_DUR=8,h.TFHD_FLAG_SAMPLE_SIZE=16,h.TFHD_FLAG_SAMPLE_FLAGS=32,h.TFHD_FLAG_DUR_EMPTY=65536,h.TFHD_FLAG_DEFAULT_BASE_IS_MOOF=131072,h.TRUN_FLAGS_DATA_OFFSET=1,h.TRUN_FLAGS_FIRST_FLAG=4,h.TRUN_FLAGS_DURATION=256,h.TRUN_FLAGS_SIZE=512,h.TRUN_FLAGS_FLAGS=1024,h.TRUN_FLAGS_CTS_OFFSET=2048,h.Box.prototype.add=function(a){return this.addBox(new h[a+"Box"])},h.Box.prototype.addBox=function(a){return this.boxes.push(a),this[a.type+"s"]?this[a.type+"s"].push(a):this[a.type]=a,a},h.Box.prototype.set=function(a,c){return this[a]=c,this},h.Box.prototype.addEntry=function(a,c){var d=c||"entries";return this[d]||(this[d]=[]),this[d].push(a),this},s.BoxParser=h,h.parseUUID=function(a){return h.parseHex16(a)},h.parseHex16=function(a){for(var c="",d=0;d<16;d++){var p=a.readUint8().toString(16);c+=p.length===1?"0"+p:p}return c},h.parseOneBox=function(a,c,d){var p,_=a.getPosition(),b=0,v,w;if(a.getEndPosition()-_<8)return t.debug("BoxParser","Not enough data in stream to parse the type and size of the box"),{code:h.ERR_NOT_ENOUGH_DATA};if(d&&d<8)return t.debug("BoxParser","Not enough bytes left in the parent box to parse a new box"),{code:h.ERR_NOT_ENOUGH_DATA};var S=a.readUint32(),T=a.readString(4),E=T;if(t.debug("BoxParser","Found box of type '"+T+"' and size "+S+" at position "+_),b=8,T=="uuid"){if(a.getEndPosition()-a.getPosition()<16||d-b<16)return a.seek(_),t.debug("BoxParser","Not enough bytes left in the parent box to parse a UUID box"),{code:h.ERR_NOT_ENOUGH_DATA};w=h.parseUUID(a),b+=16,E=w}if(S==1){if(a.getEndPosition()-a.getPosition()<8||d&&d-b<8)return a.seek(_),t.warn("BoxParser",'Not enough data in stream to parse the extended size of the "'+T+'" box'),{code:h.ERR_NOT_ENOUGH_DATA};S=a.readUint64(),b+=8}else if(S===0){if(d)S=d;else if(T!=="mdat")return t.error("BoxParser","Unlimited box size not supported for type: '"+T+"'"),p=new h.Box(T,S),{code:h.OK,box:p,size:p.size}}return S!==0&&S<b?(t.error("BoxParser","Box of type "+T+" has an invalid size "+S+" (too small to be a box)"),{code:h.ERR_NOT_ENOUGH_DATA,type:T,size:S,hdr_size:b,start:_}):S!==0&&d&&S>d?(t.error("BoxParser","Box of type '"+T+"' has a size "+S+" greater than its container size "+d),{code:h.ERR_NOT_ENOUGH_DATA,type:T,size:S,hdr_size:b,start:_}):S!==0&&_+S>a.getEndPosition()?(a.seek(_),t.info("BoxParser","Not enough data in stream to parse the entire '"+T+"' box"),{code:h.ERR_NOT_ENOUGH_DATA,type:T,size:S,hdr_size:b,start:_}):c?{code:h.OK,type:T,size:S,hdr_size:b,start:_}:(h[T+"Box"]?p=new h[T+"Box"](S):T!=="uuid"?(t.warn("BoxParser","Unknown box type: '"+T+"'"),p=new h.Box(T,S),p.has_unparsed_data=!0):h.UUIDBoxes[w]?p=new h.UUIDBoxes[w](S):(t.warn("BoxParser","Unknown uuid type: '"+w+"'"),p=new h.Box(T,S),p.uuid=w,p.has_unparsed_data=!0),p.hdr_size=b,p.start=_,p.write===h.Box.prototype.write&&p.type!=="mdat"&&(t.info("BoxParser","'"+E+"' box writing not yet implemented, keeping unparsed data in memory for later write"),p.parseDataAndRewind(a)),p.parse(a),v=a.getPosition()-(p.start+p.size),v<0?(t.warn("BoxParser","Parsing of box '"+E+"' did not read the entire indicated box data size (missing "+-v+" bytes), seeking forward"),a.seek(p.start+p.size)):v>0&&(t.error("BoxParser","Parsing of box '"+E+"' read "+v+" more bytes than the indicated box data size, seeking backwards"),p.size!==0&&a.seek(p.start+p.size)),{code:h.OK,box:p,size:p.size})},h.Box.prototype.parse=function(a){this.type!="mdat"?this.data=a.readUint8Array(this.size-this.hdr_size):this.size===0?a.seek(a.getEndPosition()):a.seek(this.start+this.size)},h.Box.prototype.parseDataAndRewind=function(a){this.data=a.readUint8Array(this.size-this.hdr_size),a.position-=this.size-this.hdr_size},h.FullBox.prototype.parseDataAndRewind=function(a){this.parseFullHeader(a),this.data=a.readUint8Array(this.size-this.hdr_size),this.hdr_size-=4,a.position-=this.size-this.hdr_size},h.FullBox.prototype.parseFullHeader=function(a){this.version=a.readUint8(),this.flags=a.readUint24(),this.hdr_size+=4},h.FullBox.prototype.parse=function(a){this.parseFullHeader(a),this.data=a.readUint8Array(this.size-this.hdr_size)},h.ContainerBox.prototype.parse=function(a){for(var c,d;a.getPosition()<this.start+this.size;)if(c=h.parseOneBox(a,!1,this.size-(a.getPosition()-this.start)),c.code===h.OK)if(d=c.box,this.boxes.push(d),this.subBoxNames&&this.subBoxNames.indexOf(d.type)!=-1)this[this.subBoxNames[this.subBoxNames.indexOf(d.type)]+"s"].push(d);else{var p=d.type!=="uuid"?d.type:d.uuid;this[p]?t.warn("Box of type "+p+" already stored in field of this type"):this[p]=d}else return},h.Box.prototype.parseLanguage=function(a){this.language=a.readUint16();var c=[];c[0]=this.language>>10&31,c[1]=this.language>>5&31,c[2]=this.language&31,this.languageString=String.fromCharCode(c[0]+96,c[1]+96,c[2]+96)},h.SAMPLE_ENTRY_TYPE_VISUAL="Visual",h.SAMPLE_ENTRY_TYPE_AUDIO="Audio",h.SAMPLE_ENTRY_TYPE_HINT="Hint",h.SAMPLE_ENTRY_TYPE_METADATA="Metadata",h.SAMPLE_ENTRY_TYPE_SUBTITLE="Subtitle",h.SAMPLE_ENTRY_TYPE_SYSTEM="System",h.SAMPLE_ENTRY_TYPE_TEXT="Text",h.SampleEntry.prototype.parseHeader=function(a){a.readUint8Array(6),this.data_reference_index=a.readUint16(),this.hdr_size+=8},h.SampleEntry.prototype.parse=function(a){this.parseHeader(a),this.data=a.readUint8Array(this.size-this.hdr_size)},h.SampleEntry.prototype.parseDataAndRewind=function(a){this.parseHeader(a),this.data=a.readUint8Array(this.size-this.hdr_size),this.hdr_size-=8,a.position-=this.size-this.hdr_size},h.SampleEntry.prototype.parseFooter=function(a){h.ContainerBox.prototype.parse.call(this,a)},h.createMediaSampleEntryCtor(h.SAMPLE_ENTRY_TYPE_HINT),h.createMediaSampleEntryCtor(h.SAMPLE_ENTRY_TYPE_METADATA),h.createMediaSampleEntryCtor(h.SAMPLE_ENTRY_TYPE_SUBTITLE),h.createMediaSampleEntryCtor(h.SAMPLE_ENTRY_TYPE_SYSTEM),h.createMediaSampleEntryCtor(h.SAMPLE_ENTRY_TYPE_TEXT),h.createMediaSampleEntryCtor(h.SAMPLE_ENTRY_TYPE_VISUAL,function(a){var c;this.parseHeader(a),a.readUint16(),a.readUint16(),a.readUint32Array(3),this.width=a.readUint16(),this.height=a.readUint16(),this.horizresolution=a.readUint32(),this.vertresolution=a.readUint32(),a.readUint32(),this.frame_count=a.readUint16(),c=Math.min(31,a.readUint8()),this.compressorname=a.readString(c),c<31&&a.readString(31-c),this.depth=a.readUint16(),a.readUint16(),this.parseFooter(a)}),h.createMediaSampleEntryCtor(h.SAMPLE_ENTRY_TYPE_AUDIO,function(a){this.parseHeader(a),a.readUint32Array(2),this.channel_count=a.readUint16(),this.samplesize=a.readUint16(),a.readUint16(),a.readUint16(),this.samplerate=a.readUint32()/65536,this.parseFooter(a)}),h.createSampleEntryCtor(h.SAMPLE_ENTRY_TYPE_VISUAL,"avc1"),h.createSampleEntryCtor(h.SAMPLE_ENTRY_TYPE_VISUAL,"avc2"),h.createSampleEntryCtor(h.SAMPLE_ENTRY_TYPE_VISUAL,"avc3"),h.createSampleEntryCtor(h.SAMPLE_ENTRY_TYPE_VISUAL,"avc4"),h.createSampleEntryCtor(h.SAMPLE_ENTRY_TYPE_VISUAL,"av01"),h.createSampleEntryCtor(h.SAMPLE_ENTRY_TYPE_VISUAL,"dav1"),h.createSampleEntryCtor(h.SAMPLE_ENTRY_TYPE_VISUAL,"hvc1"),h.createSampleEntryCtor(h.SAMPLE_ENTRY_TYPE_VISUAL,"hev1"),h.createSampleEntryCtor(h.SAMPLE_ENTRY_TYPE_VISUAL,"hvt1"),h.createSampleEntryCtor(h.SAMPLE_ENTRY_TYPE_VISUAL,"lhe1"),h.createSampleEntryCtor(h.SAMPLE_ENTRY_TYPE_VISUAL,"dvh1"),h.createSampleEntryCtor(h.SAMPLE_ENTRY_TYPE_VISUAL,"dvhe"),h.createSampleEntryCtor(h.SAMPLE_ENTRY_TYPE_VISUAL,"vvc1"),h.createSampleEntryCtor(h.SAMPLE_ENTRY_TYPE_VISUAL,"vvi1"),h.createSampleEntryCtor(h.SAMPLE_ENTRY_TYPE_VISUAL,"vvs1"),h.createSampleEntryCtor(h.SAMPLE_ENTRY_TYPE_VISUAL,"vvcN"),h.createSampleEntryCtor(h.SAMPLE_ENTRY_TYPE_VISUAL,"vp08"),h.createSampleEntryCtor(h.SAMPLE_ENTRY_TYPE_VISUAL,"vp09"),h.createSampleEntryCtor(h.SAMPLE_ENTRY_TYPE_VISUAL,"avs3"),h.createSampleEntryCtor(h.SAMPLE_ENTRY_TYPE_VISUAL,"j2ki"),h.createSampleEntryCtor(h.SAMPLE_ENTRY_TYPE_VISUAL,"mjp2"),h.createSampleEntryCtor(h.SAMPLE_ENTRY_TYPE_VISUAL,"mjpg"),h.createSampleEntryCtor(h.SAMPLE_ENTRY_TYPE_VISUAL,"uncv"),h.createSampleEntryCtor(h.SAMPLE_ENTRY_TYPE_AUDIO,"mp4a"),h.createSampleEntryCtor(h.SAMPLE_ENTRY_TYPE_AUDIO,"ac-3"),h.createSampleEntryCtor(h.SAMPLE_ENTRY_TYPE_AUDIO,"ac-4"),h.createSampleEntryCtor(h.SAMPLE_ENTRY_TYPE_AUDIO,"ec-3"),h.createSampleEntryCtor(h.SAMPLE_ENTRY_TYPE_AUDIO,"Opus"),h.createSampleEntryCtor(h.SAMPLE_ENTRY_TYPE_AUDIO,"mha1"),h.createSampleEntryCtor(h.SAMPLE_ENTRY_TYPE_AUDIO,"mha2"),h.createSampleEntryCtor(h.SAMPLE_ENTRY_TYPE_AUDIO,"mhm1"),h.createSampleEntryCtor(h.SAMPLE_ENTRY_TYPE_AUDIO,"mhm2"),h.createSampleEntryCtor(h.SAMPLE_ENTRY_TYPE_AUDIO,"fLaC"),h.createEncryptedSampleEntryCtor(h.SAMPLE_ENTRY_TYPE_VISUAL,"encv"),h.createEncryptedSampleEntryCtor(h.SAMPLE_ENTRY_TYPE_AUDIO,"enca"),h.createEncryptedSampleEntryCtor(h.SAMPLE_ENTRY_TYPE_SUBTITLE,"encu"),h.createEncryptedSampleEntryCtor(h.SAMPLE_ENTRY_TYPE_SYSTEM,"encs"),h.createEncryptedSampleEntryCtor(h.SAMPLE_ENTRY_TYPE_TEXT,"enct"),h.createEncryptedSampleEntryCtor(h.SAMPLE_ENTRY_TYPE_METADATA,"encm"),h.createBoxCtor("a1lx",function(a){var c=a.readUint8()&1,d=((c&1)+1)*16;this.layer_size=[];for(var p=0;p<3;p++)d==16?this.layer_size[p]=a.readUint16():this.layer_size[p]=a.readUint32()}),h.createBoxCtor("a1op",function(a){this.op_index=a.readUint8()}),h.createFullBoxCtor("auxC",function(a){this.aux_type=a.readCString();var c=this.size-this.hdr_size-(this.aux_type.length+1);this.aux_subtype=a.readUint8Array(c)}),h.createBoxCtor("av1C",function(a){var c=a.readUint8();if(c>>7&!1){t.error("av1C marker problem");return}if(this.version=c&127,this.version!==1){t.error("av1C version "+this.version+" not supported");return}if(c=a.readUint8(),this.seq_profile=c>>5&7,this.seq_level_idx_0=c&31,c=a.readUint8(),this.seq_tier_0=c>>7&1,this.high_bitdepth=c>>6&1,this.twelve_bit=c>>5&1,this.monochrome=c>>4&1,this.chroma_subsampling_x=c>>3&1,this.chroma_subsampling_y=c>>2&1,this.chroma_sample_position=c&3,c=a.readUint8(),this.reserved_1=c>>5&7,this.reserved_1!==0){t.error("av1C reserved_1 parsing problem");return}if(this.initial_presentation_delay_present=c>>4&1,this.initial_presentation_delay_present===1)this.initial_presentation_delay_minus_one=c&15;else if(this.reserved_2=c&15,this.reserved_2!==0){t.error("av1C reserved_2 parsing problem");return}var d=this.size-this.hdr_size-4;this.configOBUs=a.readUint8Array(d)}),h.createBoxCtor("avcC",function(a){var c,d;for(this.configurationVersion=a.readUint8(),this.AVCProfileIndication=a.readUint8(),this.profile_compatibility=a.readUint8(),this.AVCLevelIndication=a.readUint8(),this.lengthSizeMinusOne=a.readUint8()&3,this.nb_SPS_nalus=a.readUint8()&31,d=this.size-this.hdr_size-6,this.SPS=[],c=0;c<this.nb_SPS_nalus;c++)this.SPS[c]={},this.SPS[c].length=a.readUint16(),this.SPS[c].nalu=a.readUint8Array(this.SPS[c].length),d-=2+this.SPS[c].length;for(this.nb_PPS_nalus=a.readUint8(),d--,this.PPS=[],c=0;c<this.nb_PPS_nalus;c++)this.PPS[c]={},this.PPS[c].length=a.readUint16(),this.PPS[c].nalu=a.readUint8Array(this.PPS[c].length),d-=2+this.PPS[c].length;d>0&&(this.ext=a.readUint8Array(d))}),h.createBoxCtor("btrt",function(a){this.bufferSizeDB=a.readUint32(),this.maxBitrate=a.readUint32(),this.avgBitrate=a.readUint32()}),h.createFullBoxCtor("ccst",function(a){var c=a.readUint8();this.all_ref_pics_intra=(c&128)==128,this.intra_pred_used=(c&64)==64,this.max_ref_per_pic=(c&63)>>2,a.readUint24()}),h.createBoxCtor("cdef",function(a){var c;for(this.channel_count=a.readUint16(),this.channel_indexes=[],this.channel_types=[],this.channel_associations=[],c=0;c<this.channel_count;c++)this.channel_indexes.push(a.readUint16()),this.channel_types.push(a.readUint16()),this.channel_associations.push(a.readUint16())}),h.createBoxCtor("clap",function(a){this.cleanApertureWidthN=a.readUint32(),this.cleanApertureWidthD=a.readUint32(),this.cleanApertureHeightN=a.readUint32(),this.cleanApertureHeightD=a.readUint32(),this.horizOffN=a.readUint32(),this.horizOffD=a.readUint32(),this.vertOffN=a.readUint32(),this.vertOffD=a.readUint32()}),h.createBoxCtor("clli",function(a){this.max_content_light_level=a.readUint16(),this.max_pic_average_light_level=a.readUint16()}),h.createFullBoxCtor("cmex",function(a){this.flags&1&&(this.pos_x=a.readInt32()),this.flags&2&&(this.pos_y=a.readInt32()),this.flags&4&&(this.pos_z=a.readInt32()),this.flags&8&&(this.version==0?this.flags&16?(this.quat_x=a.readInt32(),this.quat_y=a.readInt32(),this.quat_z=a.readInt32()):(this.quat_x=a.readInt16(),this.quat_y=a.readInt16(),this.quat_z=a.readInt16()):this.version==1),this.flags&32&&(this.id=a.readUint32())}),h.createFullBoxCtor("cmin",function(a){this.focal_length_x=a.readInt32(),this.principal_point_x=a.readInt32(),this.principal_point_y=a.readInt32(),this.flags&1&&(this.focal_length_y=a.readInt32(),this.skew_factor=a.readInt32())}),h.createBoxCtor("cmpd",function(a){for(this.component_count=a.readUint32(),this.component_types=[],this.component_type_urls=[],i=0;i<this.component_count;i++){var c=a.readUint16();this.component_types.push(c),c>=32768&&this.component_type_urls.push(a.readCString())}}),h.createFullBoxCtor("co64",function(a){var c,d;if(c=a.readUint32(),this.chunk_offsets=[],this.version===0)for(d=0;d<c;d++)this.chunk_offsets.push(a.readUint64())}),h.createFullBoxCtor("CoLL",function(a){this.maxCLL=a.readUint16(),this.maxFALL=a.readUint16()}),h.createBoxCtor("colr",function(a){if(this.colour_type=a.readString(4),this.colour_type==="nclx"){this.colour_primaries=a.readUint16(),this.transfer_characteristics=a.readUint16(),this.matrix_coefficients=a.readUint16();var c=a.readUint8();this.full_range_flag=c>>7}else this.colour_type==="rICC"?this.ICC_profile=a.readUint8Array(this.size-4):this.colour_type==="prof"&&(this.ICC_profile=a.readUint8Array(this.size-4))}),h.createFullBoxCtor("cprt",function(a){this.parseLanguage(a),this.notice=a.readCString()}),h.createFullBoxCtor("cslg",function(a){this.version===0&&(this.compositionToDTSShift=a.readInt32(),this.leastDecodeToDisplayDelta=a.readInt32(),this.greatestDecodeToDisplayDelta=a.readInt32(),this.compositionStartTime=a.readInt32(),this.compositionEndTime=a.readInt32())}),h.createFullBoxCtor("ctts",function(a){var c,d;if(c=a.readUint32(),this.sample_counts=[],this.sample_offsets=[],this.version===0)for(d=0;d<c;d++){this.sample_counts.push(a.readUint32());var p=a.readInt32();p<0&&t.warn("BoxParser","ctts box uses negative values without using version 1"),this.sample_offsets.push(p)}else if(this.version==1)for(d=0;d<c;d++)this.sample_counts.push(a.readUint32()),this.sample_offsets.push(a.readInt32())}),h.createBoxCtor("dac3",function(a){var c=a.readUint8(),d=a.readUint8(),p=a.readUint8();this.fscod=c>>6,this.bsid=c>>1&31,this.bsmod=(c&1)<<2|d>>6&3,this.acmod=d>>3&7,this.lfeon=d>>2&1,this.bit_rate_code=d&3|p>>5&7}),h.createBoxCtor("dec3",function(a){var c=a.readUint16();this.data_rate=c>>3,this.num_ind_sub=c&7,this.ind_subs=[];for(var d=0;d<this.num_ind_sub+1;d++){var p={};this.ind_subs.push(p);var _=a.readUint8(),b=a.readUint8(),v=a.readUint8();p.fscod=_>>6,p.bsid=_>>1&31,p.bsmod=(_&1)<<4|b>>4&15,p.acmod=b>>1&7,p.lfeon=b&1,p.num_dep_sub=v>>1&15,p.num_dep_sub>0&&(p.chan_loc=(v&1)<<8|a.readUint8())}}),h.createFullBoxCtor("dfLa",function(a){var c=127,d=128,p=[],_=["STREAMINFO","PADDING","APPLICATION","SEEKTABLE","VORBIS_COMMENT","CUESHEET","PICTURE","RESERVED"];do{var b=a.readUint8(),v=Math.min(b&c,_.length-1);if(v?a.readUint8Array(a.readUint24()):(a.readUint8Array(13),this.samplerate=a.readUint32()>>12,a.readUint8Array(20)),p.push(_[v]),b&d)break}while(!0);this.numMetadataBlocks=p.length+" ("+p.join(", ")+")"}),h.createBoxCtor("dimm",function(a){this.bytessent=a.readUint64()}),h.createBoxCtor("dmax",function(a){this.time=a.readUint32()}),h.createBoxCtor("dmed",function(a){this.bytessent=a.readUint64()}),h.createBoxCtor("dOps",function(a){if(this.Version=a.readUint8(),this.OutputChannelCount=a.readUint8(),this.PreSkip=a.readUint16(),this.InputSampleRate=a.readUint32(),this.OutputGain=a.readInt16(),this.ChannelMappingFamily=a.readUint8(),this.ChannelMappingFamily!==0){this.StreamCount=a.readUint8(),this.CoupledCount=a.readUint8(),this.ChannelMapping=[];for(var c=0;c<this.OutputChannelCount;c++)this.ChannelMapping[c]=a.readUint8()}}),h.createFullBoxCtor("dref",function(a){var c,d;this.entries=[];for(var p=a.readUint32(),_=0;_<p;_++)if(c=h.parseOneBox(a,!1,this.size-(a.getPosition()-this.start)),c.code===h.OK)d=c.box,this.entries.push(d);else return}),h.createBoxCtor("drep",function(a){this.bytessent=a.readUint64()}),h.createFullBoxCtor("elng",function(a){this.extended_language=a.readString(this.size-this.hdr_size)}),h.createFullBoxCtor("elst",function(a){this.entries=[];for(var c=a.readUint32(),d=0;d<c;d++){var p={};this.entries.push(p),this.version===1?(p.segment_duration=a.readUint64(),p.media_time=a.readInt64()):(p.segment_duration=a.readUint32(),p.media_time=a.readInt32()),p.media_rate_integer=a.readInt16(),p.media_rate_fraction=a.readInt16()}}),h.createFullBoxCtor("emsg",function(a){this.version==1?(this.timescale=a.readUint32(),this.presentation_time=a.readUint64(),this.event_duration=a.readUint32(),this.id=a.readUint32(),this.scheme_id_uri=a.readCString(),this.value=a.readCString()):(this.scheme_id_uri=a.readCString(),this.value=a.readCString(),this.timescale=a.readUint32(),this.presentation_time_delta=a.readUint32(),this.event_duration=a.readUint32(),this.id=a.readUint32());var c=this.size-this.hdr_size-(16+(this.scheme_id_uri.length+1)+(this.value.length+1));this.version==1&&(c-=4),this.message_data=a.readUint8Array(c)}),h.createEntityToGroupCtor=function(a,c){h[a+"Box"]=function(d){h.FullBox.call(this,a,d)},h[a+"Box"].prototype=new h.FullBox,h[a+"Box"].prototype.parse=function(d){if(this.parseFullHeader(d),c)c.call(this,d);else for(this.group_id=d.readUint32(),this.num_entities_in_group=d.readUint32(),this.entity_ids=[],i=0;i<this.num_entities_in_group;i++){var p=d.readUint32();this.entity_ids.push(p)}}},h.createEntityToGroupCtor("aebr"),h.createEntityToGroupCtor("afbr"),h.createEntityToGroupCtor("albc"),h.createEntityToGroupCtor("altr"),h.createEntityToGroupCtor("brst"),h.createEntityToGroupCtor("dobr"),h.createEntityToGroupCtor("eqiv"),h.createEntityToGroupCtor("favc"),h.createEntityToGroupCtor("fobr"),h.createEntityToGroupCtor("iaug"),h.createEntityToGroupCtor("pano"),h.createEntityToGroupCtor("slid"),h.createEntityToGroupCtor("ster"),h.createEntityToGroupCtor("tsyn"),h.createEntityToGroupCtor("wbbr"),h.createEntityToGroupCtor("prgr"),h.createEntityToGroupCtor("pymd",function(a){this.group_id=a.readUint32(),this.num_entities_in_group=a.readUint32(),this.entity_ids=[];for(var c=0;c<this.num_entities_in_group;c++){var d=a.readUint32();this.entity_ids.push(d)}for(this.tile_size_x=a.readUint16(),this.tile_size_y=a.readUint16(),this.layer_binning=[],this.tiles_in_layer_column_minus1=[],this.tiles_in_layer_row_minus1=[],c=0;c<this.num_entities_in_group;c++)this.layer_binning[c]=a.readUint16(),this.tiles_in_layer_row_minus1[c]=a.readUint16(),this.tiles_in_layer_column_minus1[c]=a.readUint16()}),h.createFullBoxCtor("esds",function(a){var c=a.readUint8Array(this.size-this.hdr_size);if(this.data=c,typeof l<"u"){var d=new l;this.esd=d.parseOneDescriptor(new r(c.buffer,0,r.BIG_ENDIAN))}}),h.createBoxCtor("fiel",function(a){this.fieldCount=a.readUint8(),this.fieldOrdering=a.readUint8()}),h.createBoxCtor("frma",function(a){this.data_format=a.readString(4)}),h.createBoxCtor("ftyp",function(a){var c=this.size-this.hdr_size;this.major_brand=a.readString(4),this.minor_version=a.readUint32(),c-=8,this.compatible_brands=[];for(var d=0;c>=4;)this.compatible_brands[d]=a.readString(4),c-=4,d++}),h.createFullBoxCtor("hdlr",function(a){this.version===0&&(a.readUint32(),this.handler=a.readString(4),a.readUint32Array(3),this.name=a.readString(this.size-this.hdr_size-20),this.name[this.name.length-1]==="\0"&&(this.name=this.name.slice(0,-1)))}),h.createBoxCtor("hvcC",function(a){var c,d,p,_;this.configurationVersion=a.readUint8(),_=a.readUint8(),this.general_profile_space=_>>6,this.general_tier_flag=(_&32)>>5,this.general_profile_idc=_&31,this.general_profile_compatibility=a.readUint32(),this.general_constraint_indicator=a.readUint8Array(6),this.general_level_idc=a.readUint8(),this.min_spatial_segmentation_idc=a.readUint16()&4095,this.parallelismType=a.readUint8()&3,this.chroma_format_idc=a.readUint8()&3,this.bit_depth_luma_minus8=a.readUint8()&7,this.bit_depth_chroma_minus8=a.readUint8()&7,this.avgFrameRate=a.readUint16(),_=a.readUint8(),this.constantFrameRate=_>>6,this.numTemporalLayers=(_&13)>>3,this.temporalIdNested=(_&4)>>2,this.lengthSizeMinusOne=_&3,this.nalu_arrays=[];var b=a.readUint8();for(c=0;c<b;c++){var v=[];this.nalu_arrays.push(v),_=a.readUint8(),v.completeness=(_&128)>>7,v.nalu_type=_&63;var w=a.readUint16();for(d=0;d<w;d++){var S={};v.push(S),p=a.readUint16(),S.data=a.readUint8Array(p)}}}),h.createFullBoxCtor("iinf",function(a){var c;this.version===0?this.entry_count=a.readUint16():this.entry_count=a.readUint32(),this.item_infos=[];for(var d=0;d<this.entry_count;d++)if(c=h.parseOneBox(a,!1,this.size-(a.getPosition()-this.start)),c.code===h.OK)c.box.type!=="infe"&&t.error("BoxParser","Expected 'infe' box, got "+c.box.type),this.item_infos[d]=c.box;else return}),h.createFullBoxCtor("iloc",function(a){var c;c=a.readUint8(),this.offset_size=c>>4&15,this.length_size=c&15,c=a.readUint8(),this.base_offset_size=c>>4&15,this.version===1||this.version===2?this.index_size=c&15:this.index_size=0,this.items=[];var d=0;if(this.version<2)d=a.readUint16();else if(this.version===2)d=a.readUint32();else throw"version of iloc box not supported";for(var p=0;p<d;p++){var _={};if(this.items.push(_),this.version<2)_.item_ID=a.readUint16();else if(this.version===2)_.item_ID=a.readUint32();else throw"version of iloc box not supported";switch(this.version===1||this.version===2?_.construction_method=a.readUint16()&15:_.construction_method=0,_.data_reference_index=a.readUint16(),this.base_offset_size){case 0:_.base_offset=0;break;case 4:_.base_offset=a.readUint32();break;case 8:_.base_offset=a.readUint64();break;default:throw"Error reading base offset size"}var b=a.readUint16();_.extents=[];for(var v=0;v<b;v++){var w={};if(_.extents.push(w),this.version===1||this.version===2)switch(this.index_size){case 0:w.extent_index=0;break;case 4:w.extent_index=a.readUint32();break;case 8:w.extent_index=a.readUint64();break;default:throw"Error reading extent index"}switch(this.offset_size){case 0:w.extent_offset=0;break;case 4:w.extent_offset=a.readUint32();break;case 8:w.extent_offset=a.readUint64();break;default:throw"Error reading extent index"}switch(this.length_size){case 0:w.extent_length=0;break;case 4:w.extent_length=a.readUint32();break;case 8:w.extent_length=a.readUint64();break;default:throw"Error reading extent index"}}}}),h.createBoxCtor("imir",function(a){var c=a.readUint8();this.reserved=c>>7,this.axis=c&1}),h.createFullBoxCtor("infe",function(a){if((this.version===0||this.version===1)&&(this.item_ID=a.readUint16(),this.item_protection_index=a.readUint16(),this.item_name=a.readCString(),this.content_type=a.readCString(),this.content_encoding=a.readCString()),this.version===1){this.extension_type=a.readString(4),t.warn("BoxParser","Cannot parse extension type"),a.seek(this.start+this.size);return}this.version>=2&&(this.version===2?this.item_ID=a.readUint16():this.version===3&&(this.item_ID=a.readUint32()),this.item_protection_index=a.readUint16(),this.item_type=a.readString(4),this.item_name=a.readCString(),this.item_type==="mime"?(this.content_type=a.readCString(),this.content_encoding=a.readCString()):this.item_type==="uri "&&(this.item_uri_type=a.readCString()))}),h.createFullBoxCtor("ipma",function(a){var c,d;for(entry_count=a.readUint32(),this.associations=[],c=0;c<entry_count;c++){var p={};this.associations.push(p),this.version<1?p.id=a.readUint16():p.id=a.readUint32();var _=a.readUint8();for(p.props=[],d=0;d<_;d++){var b=a.readUint8(),v={};p.props.push(v),v.essential=(b&128)>>7===1,this.flags&1?v.property_index=(b&127)<<8|a.readUint8():v.property_index=b&127}}}),h.createFullBoxCtor("iref",function(a){var c,d;for(this.references=[];a.getPosition()<this.start+this.size;)if(c=h.parseOneBox(a,!0,this.size-(a.getPosition()-this.start)),c.code===h.OK)this.version===0?d=new h.SingleItemTypeReferenceBox(c.type,c.size,c.hdr_size,c.start):d=new h.SingleItemTypeReferenceBoxLarge(c.type,c.size,c.hdr_size,c.start),d.write===h.Box.prototype.write&&d.type!=="mdat"&&(t.warn("BoxParser",d.type+" box writing not yet implemented, keeping unparsed data in memory for later write"),d.parseDataAndRewind(a)),d.parse(a),this.references.push(d);else return}),h.createBoxCtor("irot",function(a){this.angle=a.readUint8()&3}),h.createFullBoxCtor("ispe",function(a){this.image_width=a.readUint32(),this.image_height=a.readUint32()}),h.createFullBoxCtor("kind",function(a){this.schemeURI=a.readCString(),this.value=a.readCString()}),h.createFullBoxCtor("leva",function(a){var c=a.readUint8();this.levels=[];for(var d=0;d<c;d++){var p={};this.levels[d]=p,p.track_ID=a.readUint32();var _=a.readUint8();switch(p.padding_flag=_>>7,p.assignment_type=_&127,p.assignment_type){case 0:p.grouping_type=a.readString(4);break;case 1:p.grouping_type=a.readString(4),p.grouping_type_parameter=a.readUint32();break;case 2:break;case 3:break;case 4:p.sub_track_id=a.readUint32();break;default:t.warn("BoxParser","Unknown leva assignement type")}}}),h.createBoxCtor("lhvC",function(a){var c,d,p;this.configurationVersion=a.readUint8(),this.min_spatial_segmentation_idc=a.readUint16()&4095,this.parallelismType=a.readUint8()&3,p=a.readUint8(),this.numTemporalLayers=(p&13)>>3,this.temporalIdNested=(p&4)>>2,this.lengthSizeMinusOne=p&3,this.nalu_arrays=[];var _=a.readUint8();for(c=0;c<_;c++){var b=[];this.nalu_arrays.push(b),p=a.readUint8(),b.completeness=(p&128)>>7,b.nalu_type=p&63;var v=a.readUint16();for(d=0;d<v;d++){var w={};b.push(w);var S=a.readUint16();w.data=a.readUint8Array(S)}}}),h.createBoxCtor("lsel",function(a){this.layer_id=a.readUint16()}),h.createBoxCtor("maxr",function(a){this.period=a.readUint32(),this.bytes=a.readUint32()});function u(a,c){this.x=a,this.y=c}u.prototype.toString=function(){return"("+this.x+","+this.y+")"},h.createBoxCtor("mdcv",function(a){this.display_primaries=[],this.display_primaries[0]=new u(a.readUint16(),a.readUint16()),this.display_primaries[1]=new u(a.readUint16(),a.readUint16()),this.display_primaries[2]=new u(a.readUint16(),a.readUint16()),this.white_point=new u(a.readUint16(),a.readUint16()),this.max_display_mastering_luminance=a.readUint32(),this.min_display_mastering_luminance=a.readUint32()}),h.createFullBoxCtor("mdhd",function(a){this.version==1?(this.creation_time=a.readUint64(),this.modification_time=a.readUint64(),this.timescale=a.readUint32(),this.duration=a.readUint64()):(this.creation_time=a.readUint32(),this.modification_time=a.readUint32(),this.timescale=a.readUint32(),this.duration=a.readUint32()),this.parseLanguage(a),a.readUint16()}),h.createFullBoxCtor("mehd",function(a){this.flags&1&&(t.warn("BoxParser","mehd box incorrectly uses flags set to 1, converting version to 1"),this.version=1),this.version==1?this.fragment_duration=a.readUint64():this.fragment_duration=a.readUint32()}),h.createFullBoxCtor("meta",function(a){this.boxes=[],h.ContainerBox.prototype.parse.call(this,a)}),h.createFullBoxCtor("mfhd",function(a){this.sequence_number=a.readUint32()}),h.createFullBoxCtor("mfro",function(a){this._size=a.readUint32()}),h.createFullBoxCtor("mskC",function(a){this.bits_per_pixel=a.readUint8()}),h.createFullBoxCtor("mvhd",function(a){this.version==1?(this.creation_time=a.readUint64(),this.modification_time=a.readUint64(),this.timescale=a.readUint32(),this.duration=a.readUint64()):(this.creation_time=a.readUint32(),this.modification_time=a.readUint32(),this.timescale=a.readUint32(),this.duration=a.readUint32()),this.rate=a.readUint32(),this.volume=a.readUint16()>>8,a.readUint16(),a.readUint32Array(2),this.matrix=a.readUint32Array(9),a.readUint32Array(6),this.next_track_id=a.readUint32()}),h.createBoxCtor("npck",function(a){this.packetssent=a.readUint32()}),h.createBoxCtor("nump",function(a){this.packetssent=a.readUint64()}),h.createFullBoxCtor("padb",function(a){var c=a.readUint32();this.padbits=[];for(var d=0;d<Math.floor((c+1)/2);d++)this.padbits=a.readUint8()}),h.createBoxCtor("pasp",function(a){this.hSpacing=a.readUint32(),this.vSpacing=a.readUint32()}),h.createBoxCtor("payl",function(a){this.text=a.readString(this.size-this.hdr_size)}),h.createBoxCtor("payt",function(a){this.payloadID=a.readUint32();var c=a.readUint8();this.rtpmap_string=a.readString(c)}),h.createFullBoxCtor("pdin",function(a){var c=(this.size-this.hdr_size)/8;this.rate=[],this.initial_delay=[];for(var d=0;d<c;d++)this.rate[d]=a.readUint32(),this.initial_delay[d]=a.readUint32()}),h.createFullBoxCtor("pitm",function(a){this.version===0?this.item_id=a.readUint16():this.item_id=a.readUint32()}),h.createFullBoxCtor("pixi",function(a){var c;for(this.num_channels=a.readUint8(),this.bits_per_channels=[],c=0;c<this.num_channels;c++)this.bits_per_channels[c]=a.readUint8()}),h.createBoxCtor("pmax",function(a){this.bytes=a.readUint32()}),h.createFullBoxCtor("prdi",function(a){if(this.step_count=a.readUint16(),this.item_count=[],this.flags&2)for(var c=0;c<this.step_count;c++)this.item_count[c]=a.readUint16()}),h.createFullBoxCtor("prft",function(a){this.ref_track_id=a.readUint32(),this.ntp_timestamp=a.readUint64(),this.version===0?this.media_time=a.readUint32():this.media_time=a.readUint64()}),h.createFullBoxCtor("pssh",function(a){if(this.system_id=h.parseHex16(a),this.version>0){var c=a.readUint32();this.kid=[];for(var d=0;d<c;d++)this.kid[d]=h.parseHex16(a)}var p=a.readUint32();p>0&&(this.data=a.readUint8Array(p))}),h.createFullBoxCtor("clef",function(a){this.width=a.readUint32(),this.height=a.readUint32()}),h.createFullBoxCtor("enof",function(a){this.width=a.readUint32(),this.height=a.readUint32()}),h.createFullBoxCtor("prof",function(a){this.width=a.readUint32(),this.height=a.readUint32()}),h.createContainerBoxCtor("tapt",null,["clef","prof","enof"]),h.createBoxCtor("rtp ",function(a){this.descriptionformat=a.readString(4),this.sdptext=a.readString(this.size-this.hdr_size-4)}),h.createFullBoxCtor("saio",function(a){this.flags&1&&(this.aux_info_type=a.readUint32(),this.aux_info_type_parameter=a.readUint32());var c=a.readUint32();this.offset=[];for(var d=0;d<c;d++)this.version===0?this.offset[d]=a.readUint32():this.offset[d]=a.readUint64()}),h.createFullBoxCtor("saiz",function(a){this.flags&1&&(this.aux_info_type=a.readUint32(),this.aux_info_type_parameter=a.readUint32()),this.default_sample_info_size=a.readUint8();var c=a.readUint32();if(this.sample_info_size=[],this.default_sample_info_size===0)for(var d=0;d<c;d++)this.sample_info_size[d]=a.readUint8()}),h.createSampleEntryCtor(h.SAMPLE_ENTRY_TYPE_METADATA,"mett",function(a){this.parseHeader(a),this.content_encoding=a.readCString(),this.mime_format=a.readCString(),this.parseFooter(a)}),h.createSampleEntryCtor(h.SAMPLE_ENTRY_TYPE_METADATA,"metx",function(a){this.parseHeader(a),this.content_encoding=a.readCString(),this.namespace=a.readCString(),this.schema_location=a.readCString(),this.parseFooter(a)}),h.createSampleEntryCtor(h.SAMPLE_ENTRY_TYPE_SUBTITLE,"sbtt",function(a){this.parseHeader(a),this.content_encoding=a.readCString(),this.mime_format=a.readCString(),this.parseFooter(a)}),h.createSampleEntryCtor(h.SAMPLE_ENTRY_TYPE_SUBTITLE,"stpp",function(a){this.parseHeader(a),this.namespace=a.readCString(),this.schema_location=a.readCString(),this.auxiliary_mime_types=a.readCString(),this.parseFooter(a)}),h.createSampleEntryCtor(h.SAMPLE_ENTRY_TYPE_SUBTITLE,"stxt",function(a){this.parseHeader(a),this.content_encoding=a.readCString(),this.mime_format=a.readCString(),this.parseFooter(a)}),h.createSampleEntryCtor(h.SAMPLE_ENTRY_TYPE_SUBTITLE,"tx3g",function(a){this.parseHeader(a),this.displayFlags=a.readUint32(),this.horizontal_justification=a.readInt8(),this.vertical_justification=a.readInt8(),this.bg_color_rgba=a.readUint8Array(4),this.box_record=a.readInt16Array(4),this.style_record=a.readUint8Array(12),this.parseFooter(a)}),h.createSampleEntryCtor(h.SAMPLE_ENTRY_TYPE_METADATA,"wvtt",function(a){this.parseHeader(a),this.parseFooter(a)}),h.createSampleGroupCtor("alst",function(a){var c,d=a.readUint16();for(this.first_output_sample=a.readUint16(),this.sample_offset=[],c=0;c<d;c++)this.sample_offset[c]=a.readUint32();var p=this.description_length-4-4*d;for(this.num_output_samples=[],this.num_total_samples=[],c=0;c<p/4;c++)this.num_output_samples[c]=a.readUint16(),this.num_total_samples[c]=a.readUint16()}),h.createSampleGroupCtor("avll",function(a){this.layerNumber=a.readUint8(),this.accurateStatisticsFlag=a.readUint8(),this.avgBitRate=a.readUint16(),this.avgFrameRate=a.readUint16()}),h.createSampleGroupCtor("avss",function(a){this.subSequenceIdentifier=a.readUint16(),this.layerNumber=a.readUint8();var c=a.readUint8();this.durationFlag=c>>7,this.avgRateFlag=c>>6&1,this.durationFlag&&(this.duration=a.readUint32()),this.avgRateFlag&&(this.accurateStatisticsFlag=a.readUint8(),this.avgBitRate=a.readUint16(),this.avgFrameRate=a.readUint16()),this.dependency=[];for(var d=a.readUint8(),p=0;p<d;p++){var _={};this.dependency.push(_),_.subSeqDirectionFlag=a.readUint8(),_.layerNumber=a.readUint8(),_.subSequenceIdentifier=a.readUint16()}}),h.createSampleGroupCtor("dtrt",function(a){t.warn("BoxParser","Sample Group type: "+this.grouping_type+" not fully parsed")}),h.createSampleGroupCtor("mvif",function(a){t.warn("BoxParser","Sample Group type: "+this.grouping_type+" not fully parsed")}),h.createSampleGroupCtor("prol",function(a){this.roll_distance=a.readInt16()}),h.createSampleGroupCtor("rap ",function(a){var c=a.readUint8();this.num_leading_samples_known=c>>7,this.num_leading_samples=c&127}),h.createSampleGroupCtor("rash",function(a){if(this.operation_point_count=a.readUint16(),this.description_length!==2+(this.operation_point_count===1?2:this.operation_point_count*6)+9)t.warn("BoxParser","Mismatch in "+this.grouping_type+" sample group length"),this.data=a.readUint8Array(this.description_length-2);else{if(this.operation_point_count===1)this.target_rate_share=a.readUint16();else{this.target_rate_share=[],this.available_bitrate=[];for(var c=0;c<this.operation_point_count;c++)this.available_bitrate[c]=a.readUint32(),this.target_rate_share[c]=a.readUint16()}this.maximum_bitrate=a.readUint32(),this.minimum_bitrate=a.readUint32(),this.discard_priority=a.readUint8()}}),h.createSampleGroupCtor("roll",function(a){this.roll_distance=a.readInt16()}),h.SampleGroupEntry.prototype.parse=function(a){t.warn("BoxParser","Unknown Sample Group type: "+this.grouping_type),this.data=a.readUint8Array(this.description_length)},h.createSampleGroupCtor("scif",function(a){t.warn("BoxParser","Sample Group type: "+this.grouping_type+" not fully parsed")}),h.createSampleGroupCtor("scnm",function(a){t.warn("BoxParser","Sample Group type: "+this.grouping_type+" not fully parsed")}),h.createSampleGroupCtor("seig",function(a){this.reserved=a.readUint8();var c=a.readUint8();this.crypt_byte_block=c>>4,this.skip_byte_block=c&15,this.isProtected=a.readUint8(),this.Per_Sample_IV_Size=a.readUint8(),this.KID=h.parseHex16(a),this.constant_IV_size=0,this.constant_IV=0,this.isProtected===1&&this.Per_Sample_IV_Size===0&&(this.constant_IV_size=a.readUint8(),this.constant_IV=a.readUint8Array(this.constant_IV_size))}),h.createSampleGroupCtor("stsa",function(a){t.warn("BoxParser","Sample Group type: "+this.grouping_type+" not fully parsed")}),h.createSampleGroupCtor("sync",function(a){var c=a.readUint8();this.NAL_unit_type=c&63}),h.createSampleGroupCtor("tele",function(a){var c=a.readUint8();this.level_independently_decodable=c>>7}),h.createSampleGroupCtor("tsas",function(a){t.warn("BoxParser","Sample Group type: "+this.grouping_type+" not fully parsed")}),h.createSampleGroupCtor("tscl",function(a){t.warn("BoxParser","Sample Group type: "+this.grouping_type+" not fully parsed")}),h.createSampleGroupCtor("vipr",function(a){t.warn("BoxParser","Sample Group type: "+this.grouping_type+" not fully parsed")}),h.createFullBoxCtor("sbgp",function(a){this.grouping_type=a.readString(4),this.version===1?this.grouping_type_parameter=a.readUint32():this.grouping_type_parameter=0,this.entries=[];for(var c=a.readUint32(),d=0;d<c;d++){var p={};this.entries.push(p),p.sample_count=a.readInt32(),p.group_description_index=a.readInt32()}});function f(a,c){this.bad_pixel_row=a,this.bad_pixel_column=c}f.prototype.toString=function(){return"[row: "+this.bad_pixel_row+", column: "+this.bad_pixel_column+"]"},h.createFullBoxCtor("sbpm",function(a){var c;for(this.component_count=a.readUint16(),this.component_index=[],c=0;c<this.component_count;c++)this.component_index.push(a.readUint16());var d=a.readUint8();for(this.correction_applied=(d&128)==128,this.num_bad_rows=a.readUint32(),this.num_bad_cols=a.readUint32(),this.num_bad_pixels=a.readUint32(),this.bad_rows=[],this.bad_columns=[],this.bad_pixels=[],c=0;c<this.num_bad_rows;c++)this.bad_rows.push(a.readUint32());for(c=0;c<this.num_bad_cols;c++)this.bad_columns.push(a.readUint32());for(c=0;c<this.num_bad_pixels;c++){var p=a.readUint32(),_=a.readUint32();this.bad_pixels.push(new f(p,_))}}),h.createFullBoxCtor("schm",function(a){this.scheme_type=a.readString(4),this.scheme_version=a.readUint32(),this.flags&1&&(this.scheme_uri=a.readString(this.size-this.hdr_size-8))}),h.createBoxCtor("sdp ",function(a){this.sdptext=a.readString(this.size-this.hdr_size)}),h.createFullBoxCtor("sdtp",function(a){var c,d=this.size-this.hdr_size;this.is_leading=[],this.sample_depends_on=[],this.sample_is_depended_on=[],this.sample_has_redundancy=[];for(var p=0;p<d;p++)c=a.readUint8(),this.is_leading[p]=c>>6,this.sample_depends_on[p]=c>>4&3,this.sample_is_depended_on[p]=c>>2&3,this.sample_has_redundancy[p]=c&3}),h.createFullBoxCtor("senc"),h.createFullBoxCtor("sgpd",function(a){this.grouping_type=a.readString(4),t.debug("BoxParser","Found Sample Groups of type "+this.grouping_type),this.version===1?this.default_length=a.readUint32():this.default_length=0,this.version>=2&&(this.default_group_description_index=a.readUint32()),this.entries=[];for(var c=a.readUint32(),d=0;d<c;d++){var p;h[this.grouping_type+"SampleGroupEntry"]?p=new h[this.grouping_type+"SampleGroupEntry"](this.grouping_type):p=new h.SampleGroupEntry(this.grouping_type),this.entries.push(p),this.version===1?this.default_length===0?p.description_length=a.readUint32():p.description_length=this.default_length:p.description_length=this.default_length,p.write===h.SampleGroupEntry.prototype.write&&(t.info("BoxParser","SampleGroup for type "+this.grouping_type+" writing not yet implemented, keeping unparsed data in memory for later write"),p.data=a.readUint8Array(p.description_length),a.position-=p.description_length),p.parse(a)}}),h.createFullBoxCtor("sidx",function(a){this.reference_ID=a.readUint32(),this.timescale=a.readUint32(),this.version===0?(this.earliest_presentation_time=a.readUint32(),this.first_offset=a.readUint32()):(this.earliest_presentation_time=a.readUint64(),this.first_offset=a.readUint64()),a.readUint16(),this.references=[];for(var c=a.readUint16(),d=0;d<c;d++){var p={};this.references.push(p);var _=a.readUint32();p.reference_type=_>>31&1,p.referenced_size=_&2147483647,p.subsegment_duration=a.readUint32(),_=a.readUint32(),p.starts_with_SAP=_>>31&1,p.SAP_type=_>>28&7,p.SAP_delta_time=_&268435455}}),h.SingleItemTypeReferenceBox=function(a,c,d,p){h.Box.call(this,a,c),this.hdr_size=d,this.start=p},h.SingleItemTypeReferenceBox.prototype=new h.Box,h.SingleItemTypeReferenceBox.prototype.parse=function(a){this.from_item_ID=a.readUint16();var c=a.readUint16();this.references=[];for(var d=0;d<c;d++)this.references[d]={},this.references[d].to_item_ID=a.readUint16()},h.SingleItemTypeReferenceBoxLarge=function(a,c,d,p){h.Box.call(this,a,c),this.hdr_size=d,this.start=p},h.SingleItemTypeReferenceBoxLarge.prototype=new h.Box,h.SingleItemTypeReferenceBoxLarge.prototype.parse=function(a){this.from_item_ID=a.readUint32();var c=a.readUint16();this.references=[];for(var d=0;d<c;d++)this.references[d]={},this.references[d].to_item_ID=a.readUint32()},h.createFullBoxCtor("SmDm",function(a){this.primaryRChromaticity_x=a.readUint16(),this.primaryRChromaticity_y=a.readUint16(),this.primaryGChromaticity_x=a.readUint16(),this.primaryGChromaticity_y=a.readUint16(),this.primaryBChromaticity_x=a.readUint16(),this.primaryBChromaticity_y=a.readUint16(),this.whitePointChromaticity_x=a.readUint16(),this.whitePointChromaticity_y=a.readUint16(),this.luminanceMax=a.readUint32(),this.luminanceMin=a.readUint32()}),h.createFullBoxCtor("smhd",function(a){this.balance=a.readUint16(),a.readUint16()}),h.createFullBoxCtor("ssix",function(a){this.subsegments=[];for(var c=a.readUint32(),d=0;d<c;d++){var p={};this.subsegments.push(p),p.ranges=[];for(var _=a.readUint32(),b=0;b<_;b++){var v={};p.ranges.push(v),v.level=a.readUint8(),v.range_size=a.readUint24()}}}),h.createFullBoxCtor("stco",function(a){var c;if(c=a.readUint32(),this.chunk_offsets=[],this.version===0)for(var d=0;d<c;d++)this.chunk_offsets.push(a.readUint32())}),h.createFullBoxCtor("stdp",function(a){var c=(this.size-this.hdr_size)/2;this.priority=[];for(var d=0;d<c;d++)this.priority[d]=a.readUint16()}),h.createFullBoxCtor("sthd"),h.createFullBoxCtor("stri",function(a){this.switch_group=a.readUint16(),this.alternate_group=a.readUint16(),this.sub_track_id=a.readUint32();var c=(this.size-this.hdr_size-8)/4;this.attribute_list=[];for(var d=0;d<c;d++)this.attribute_list[d]=a.readUint32()}),h.createFullBoxCtor("stsc",function(a){var c,d;if(c=a.readUint32(),this.first_chunk=[],this.samples_per_chunk=[],this.sample_description_index=[],this.version===0)for(d=0;d<c;d++)this.first_chunk.push(a.readUint32()),this.samples_per_chunk.push(a.readUint32()),this.sample_description_index.push(a.readUint32())}),h.createFullBoxCtor("stsd",function(a){var c,d,p,_;for(this.entries=[],p=a.readUint32(),c=1;c<=p;c++)if(d=h.parseOneBox(a,!0,this.size-(a.getPosition()-this.start)),d.code===h.OK)h[d.type+"SampleEntry"]?(_=new h[d.type+"SampleEntry"](d.size),_.hdr_size=d.hdr_size,_.start=d.start):(t.warn("BoxParser","Unknown sample entry type: "+d.type),_=new h.SampleEntry(d.type,d.size,d.hdr_size,d.start)),_.write===h.SampleEntry.prototype.write&&(t.info("BoxParser","SampleEntry "+_.type+" box writing not yet implemented, keeping unparsed data in memory for later write"),_.parseDataAndRewind(a)),_.parse(a),this.entries.push(_);else return}),h.createFullBoxCtor("stsg",function(a){this.grouping_type=a.readUint32();var c=a.readUint16();this.group_description_index=[];for(var d=0;d<c;d++)this.group_description_index[d]=a.readUint32()}),h.createFullBoxCtor("stsh",function(a){var c,d;if(c=a.readUint32(),this.shadowed_sample_numbers=[],this.sync_sample_numbers=[],this.version===0)for(d=0;d<c;d++)this.shadowed_sample_numbers.push(a.readUint32()),this.sync_sample_numbers.push(a.readUint32())}),h.createFullBoxCtor("stss",function(a){var c,d;if(d=a.readUint32(),this.version===0)for(this.sample_numbers=[],c=0;c<d;c++)this.sample_numbers.push(a.readUint32())}),h.createFullBoxCtor("stsz",function(a){var c;if(this.sample_sizes=[],this.version===0)for(this.sample_size=a.readUint32(),this.sample_count=a.readUint32(),c=0;c<this.sample_count;c++)this.sample_size===0?this.sample_sizes.push(a.readUint32()):this.sample_sizes[c]=this.sample_size}),h.createFullBoxCtor("stts",function(a){var c,d,p;if(c=a.readUint32(),this.sample_counts=[],this.sample_deltas=[],this.version===0)for(d=0;d<c;d++)this.sample_counts.push(a.readUint32()),p=a.readInt32(),p<0&&(t.warn("BoxParser","File uses negative stts sample delta, using value 1 instead, sync may be lost!"),p=1),this.sample_deltas.push(p)}),h.createFullBoxCtor("stvi",function(a){var c=a.readUint32();this.single_view_allowed=c&3,this.stereo_scheme=a.readUint32();var d=a.readUint32();this.stereo_indication_type=a.readString(d);var p,_;for(this.boxes=[];a.getPosition()<this.start+this.size;)if(p=h.parseOneBox(a,!1,this.size-(a.getPosition()-this.start)),p.code===h.OK)_=p.box,this.boxes.push(_),this[_.type]=_;else return}),h.createBoxCtor("styp",function(a){h.ftypBox.prototype.parse.call(this,a)}),h.createFullBoxCtor("stz2",function(a){var c,d;if(this.sample_sizes=[],this.version===0)if(this.reserved=a.readUint24(),this.field_size=a.readUint8(),d=a.readUint32(),this.field_size===4)for(c=0;c<d;c+=2){var p=a.readUint8();this.sample_sizes[c]=p>>4&15,this.sample_sizes[c+1]=p&15}else if(this.field_size===8)for(c=0;c<d;c++)this.sample_sizes[c]=a.readUint8();else if(this.field_size===16)for(c=0;c<d;c++)this.sample_sizes[c]=a.readUint16();else t.error("BoxParser","Error in length field in stz2 box")}),h.createFullBoxCtor("subs",function(a){var c,d,p,_;for(p=a.readUint32(),this.entries=[],c=0;c<p;c++){var b={};if(this.entries[c]=b,b.sample_delta=a.readUint32(),b.subsamples=[],_=a.readUint16(),_>0)for(d=0;d<_;d++){var v={};b.subsamples.push(v),this.version==1?v.size=a.readUint32():v.size=a.readUint16(),v.priority=a.readUint8(),v.discardable=a.readUint8(),v.codec_specific_parameters=a.readUint32()}}}),h.createFullBoxCtor("tenc",function(a){if(a.readUint8(),this.version===0)a.readUint8();else{var c=a.readUint8();this.default_crypt_byte_block=c>>4&15,this.default_skip_byte_block=c&15}this.default_isProtected=a.readUint8(),this.default_Per_Sample_IV_Size=a.readUint8(),this.default_KID=h.parseHex16(a),this.default_isProtected===1&&this.default_Per_Sample_IV_Size===0&&(this.default_constant_IV_size=a.readUint8(),this.default_constant_IV=a.readUint8Array(this.default_constant_IV_size))}),h.createFullBoxCtor("tfdt",function(a){this.version==1?this.baseMediaDecodeTime=a.readUint64():this.baseMediaDecodeTime=a.readUint32()}),h.createFullBoxCtor("tfhd",function(a){var c=0;this.track_id=a.readUint32(),this.size-this.hdr_size>c&&this.flags&h.TFHD_FLAG_BASE_DATA_OFFSET?(this.base_data_offset=a.readUint64(),c+=8):this.base_data_offset=0,this.size-this.hdr_size>c&&this.flags&h.TFHD_FLAG_SAMPLE_DESC?(this.default_sample_description_index=a.readUint32(),c+=4):this.default_sample_description_index=0,this.size-this.hdr_size>c&&this.flags&h.TFHD_FLAG_SAMPLE_DUR?(this.default_sample_duration=a.readUint32(),c+=4):this.default_sample_duration=0,this.size-this.hdr_size>c&&this.flags&h.TFHD_FLAG_SAMPLE_SIZE?(this.default_sample_size=a.readUint32(),c+=4):this.default_sample_size=0,this.size-this.hdr_size>c&&this.flags&h.TFHD_FLAG_SAMPLE_FLAGS?(this.default_sample_flags=a.readUint32(),c+=4):this.default_sample_flags=0}),h.createFullBoxCtor("tfra",function(a){this.track_ID=a.readUint32(),a.readUint24();var c=a.readUint8();this.length_size_of_traf_num=c>>4&3,this.length_size_of_trun_num=c>>2&3,this.length_size_of_sample_num=c&3,this.entries=[];for(var d=a.readUint32(),p=0;p<d;p++)this.version===1?(this.time=a.readUint64(),this.moof_offset=a.readUint64()):(this.time=a.readUint32(),this.moof_offset=a.readUint32()),this.traf_number=a["readUint"+8*(this.length_size_of_traf_num+1)](),this.trun_number=a["readUint"+8*(this.length_size_of_trun_num+1)](),this.sample_number=a["readUint"+8*(this.length_size_of_sample_num+1)]()}),h.createFullBoxCtor("tkhd",function(a){this.version==1?(this.creation_time=a.readUint64(),this.modification_time=a.readUint64(),this.track_id=a.readUint32(),a.readUint32(),this.duration=a.readUint64()):(this.creation_time=a.readUint32(),this.modification_time=a.readUint32(),this.track_id=a.readUint32(),a.readUint32(),this.duration=a.readUint32()),a.readUint32Array(2),this.layer=a.readInt16(),this.alternate_group=a.readInt16(),this.volume=a.readInt16()>>8,a.readUint16(),this.matrix=a.readInt32Array(9),this.width=a.readUint32(),this.height=a.readUint32()}),h.createBoxCtor("tmax",function(a){this.time=a.readUint32()}),h.createBoxCtor("tmin",function(a){this.time=a.readUint32()}),h.createBoxCtor("totl",function(a){this.bytessent=a.readUint32()}),h.createBoxCtor("tpay",function(a){this.bytessent=a.readUint32()}),h.createBoxCtor("tpyl",function(a){this.bytessent=a.readUint64()}),h.TrackGroupTypeBox.prototype.parse=function(a){this.parseFullHeader(a),this.track_group_id=a.readUint32()},h.createTrackGroupCtor("msrc"),h.TrackReferenceTypeBox=function(a,c,d,p){h.Box.call(this,a,c),this.hdr_size=d,this.start=p},h.TrackReferenceTypeBox.prototype=new h.Box,h.TrackReferenceTypeBox.prototype.parse=function(a){this.track_ids=a.readUint32Array((this.size-this.hdr_size)/4)},h.trefBox.prototype.parse=function(a){for(var c,d;a.getPosition()<this.start+this.size;)if(c=h.parseOneBox(a,!0,this.size-(a.getPosition()-this.start)),c.code===h.OK)d=new h.TrackReferenceTypeBox(c.type,c.size,c.hdr_size,c.start),d.write===h.Box.prototype.write&&d.type!=="mdat"&&(t.info("BoxParser","TrackReference "+d.type+" box writing not yet implemented, keeping unparsed data in memory for later write"),d.parseDataAndRewind(a)),d.parse(a),this.boxes.push(d);else return},h.createFullBoxCtor("trep",function(a){for(this.track_ID=a.readUint32(),this.boxes=[];a.getPosition()<this.start+this.size;)if(ret=h.parseOneBox(a,!1,this.size-(a.getPosition()-this.start)),ret.code===h.OK)box=ret.box,this.boxes.push(box);else return}),h.createFullBoxCtor("trex",function(a){this.track_id=a.readUint32(),this.default_sample_description_index=a.readUint32(),this.default_sample_duration=a.readUint32(),this.default_sample_size=a.readUint32(),this.default_sample_flags=a.readUint32()}),h.createBoxCtor("trpy",function(a){this.bytessent=a.readUint64()}),h.createFullBoxCtor("trun",function(a){var c=0;if(this.sample_count=a.readUint32(),c+=4,this.size-this.hdr_size>c&&this.flags&h.TRUN_FLAGS_DATA_OFFSET?(this.data_offset=a.readInt32(),c+=4):this.data_offset=0,this.size-this.hdr_size>c&&this.flags&h.TRUN_FLAGS_FIRST_FLAG?(this.first_sample_flags=a.readUint32(),c+=4):this.first_sample_flags=0,this.sample_duration=[],this.sample_size=[],this.sample_flags=[],this.sample_composition_time_offset=[],this.size-this.hdr_size>c)for(var d=0;d<this.sample_count;d++)this.flags&h.TRUN_FLAGS_DURATION&&(this.sample_duration[d]=a.readUint32()),this.flags&h.TRUN_FLAGS_SIZE&&(this.sample_size[d]=a.readUint32()),this.flags&h.TRUN_FLAGS_FLAGS&&(this.sample_flags[d]=a.readUint32()),this.flags&h.TRUN_FLAGS_CTS_OFFSET&&(this.version===0?this.sample_composition_time_offset[d]=a.readUint32():this.sample_composition_time_offset[d]=a.readInt32())}),h.createFullBoxCtor("tsel",function(a){this.switch_group=a.readUint32();var c=(this.size-this.hdr_size-4)/4;this.attribute_list=[];for(var d=0;d<c;d++)this.attribute_list[d]=a.readUint32()}),h.createFullBoxCtor("txtC",function(a){this.config=a.readCString()}),h.createBoxCtor("tyco",function(a){var c=(this.size-this.hdr_size)/4;this.compatible_brands=[];for(var d=0;d<c;d++)this.compatible_brands[d]=a.readString(4)}),h.createFullBoxCtor("udes",function(a){this.lang=a.readCString(),this.name=a.readCString(),this.description=a.readCString(),this.tags=a.readCString()}),h.createFullBoxCtor("uncC",function(a){var c;if(this.profile=a.readUint32(),this.version!=1){if(this.version==0){for(this.component_count=a.readUint32(),this.component_index=[],this.component_bit_depth_minus_one=[],this.component_format=[],this.component_align_size=[],c=0;c<this.component_count;c++)this.component_index.push(a.readUint16()),this.component_bit_depth_minus_one.push(a.readUint8()),this.component_format.push(a.readUint8()),this.component_align_size.push(a.readUint8());this.sampling_type=a.readUint8(),this.interleave_type=a.readUint8(),this.block_size=a.readUint8();var d=a.readUint8();this.component_little_endian=d>>7&1,this.block_pad_lsb=d>>6&1,this.block_little_endian=d>>5&1,this.block_reversed=d>>4&1,this.pad_unknown=d>>3&1,this.pixel_size=a.readUint32(),this.row_align_size=a.readUint32(),this.tile_align_size=a.readUint32(),this.num_tile_cols_minus_one=a.readUint32(),this.num_tile_rows_minus_one=a.readUint32()}}}),h.createFullBoxCtor("url ",function(a){this.flags!==1&&(this.location=a.readCString())}),h.createFullBoxCtor("urn ",function(a){this.name=a.readCString(),this.size-this.hdr_size-this.name.length-1>0&&(this.location=a.readCString())}),h.createUUIDBox("a5d40b30e81411ddba2f0800200c9a66",!0,!1,function(a){this.LiveServerManifest=a.readString(this.size-this.hdr_size).replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}),h.createUUIDBox("d08a4f1810f34a82b6c832d8aba183d3",!0,!1,function(a){this.system_id=h.parseHex16(a);var c=a.readUint32();c>0&&(this.data=a.readUint8Array(c))}),h.createUUIDBox("a2394f525a9b4f14a2446c427c648df4",!0,!1),h.createUUIDBox("8974dbce7be74c5184f97148f9882554",!0,!1,function(a){this.default_AlgorithmID=a.readUint24(),this.default_IV_size=a.readUint8(),this.default_KID=h.parseHex16(a)}),h.createUUIDBox("d4807ef2ca3946958e5426cb9e46a79f",!0,!1,function(a){this.fragment_count=a.readUint8(),this.entries=[];for(var c=0;c<this.fragment_count;c++){var d={},p=0,_=0;this.version===1?(p=a.readUint64(),_=a.readUint64()):(p=a.readUint32(),_=a.readUint32()),d.absolute_time=p,d.absolute_duration=_,this.entries.push(d)}}),h.createUUIDBox("6d1d9b0542d544e680e2141daff757b2",!0,!1,function(a){this.version===1?(this.absolute_time=a.readUint64(),this.duration=a.readUint64()):(this.absolute_time=a.readUint32(),this.duration=a.readUint32())}),h.createFullBoxCtor("vmhd",function(a){this.graphicsmode=a.readUint16(),this.opcolor=a.readUint16Array(3)}),h.createFullBoxCtor("vpcC",function(a){var c;this.version===1?(this.profile=a.readUint8(),this.level=a.readUint8(),c=a.readUint8(),this.bitDepth=c>>4,this.chromaSubsampling=c>>1&7,this.videoFullRangeFlag=c&1,this.colourPrimaries=a.readUint8(),this.transferCharacteristics=a.readUint8(),this.matrixCoefficients=a.readUint8(),this.codecIntializationDataSize=a.readUint16(),this.codecIntializationData=a.readUint8Array(this.codecIntializationDataSize)):(this.profile=a.readUint8(),this.level=a.readUint8(),c=a.readUint8(),this.bitDepth=c>>4&15,this.colorSpace=c&15,c=a.readUint8(),this.chromaSubsampling=c>>4&15,this.transferFunction=c>>1&7,this.videoFullRangeFlag=c&1,this.codecIntializationDataSize=a.readUint16(),this.codecIntializationData=a.readUint8Array(this.codecIntializationDataSize))}),h.createBoxCtor("vttC",function(a){this.text=a.readString(this.size-this.hdr_size)}),h.createFullBoxCtor("vvcC",function(a){var c,d,p={held_bits:void 0,num_held_bits:0,stream_read_1_bytes:function(A){this.held_bits=A.readUint8(),this.num_held_bits=8},stream_read_2_bytes:function(A){this.held_bits=A.readUint16(),this.num_held_bits=16},extract_bits:function(A){var O=this.held_bits>>this.num_held_bits-A&(1<<A)-1;return this.num_held_bits-=A,O}};if(p.stream_read_1_bytes(a),p.extract_bits(5),this.lengthSizeMinusOne=p.extract_bits(2),this.ptl_present_flag=p.extract_bits(1),this.ptl_present_flag){p.stream_read_2_bytes(a),this.ols_idx=p.extract_bits(9),this.num_sublayers=p.extract_bits(3),this.constant_frame_rate=p.extract_bits(2),this.chroma_format_idc=p.extract_bits(2),p.stream_read_1_bytes(a),this.bit_depth_minus8=p.extract_bits(3),p.extract_bits(5);{if(p.stream_read_2_bytes(a),p.extract_bits(2),this.num_bytes_constraint_info=p.extract_bits(6),this.general_profile_idc=p.extract_bits(7),this.general_tier_flag=p.extract_bits(1),this.general_level_idc=a.readUint8(),p.stream_read_1_bytes(a),this.ptl_frame_only_constraint_flag=p.extract_bits(1),this.ptl_multilayer_enabled_flag=p.extract_bits(1),this.general_constraint_info=new Uint8Array(this.num_bytes_constraint_info),this.num_bytes_constraint_info){for(c=0;c<this.num_bytes_constraint_info-1;c++){var _=p.extract_bits(6);p.stream_read_1_bytes(a);var b=p.extract_bits(2);this.general_constraint_info[c]=_<<2|b}this.general_constraint_info[this.num_bytes_constraint_info-1]=p.extract_bits(6)}else p.extract_bits(6);if(this.num_sublayers>1){for(p.stream_read_1_bytes(a),this.ptl_sublayer_present_mask=0,d=this.num_sublayers-2;d>=0;--d){var v=p.extract_bits(1);this.ptl_sublayer_present_mask|=v<<d}for(d=this.num_sublayers;d<=8&&this.num_sublayers>1;++d)p.extract_bits(1);for(this.sublayer_level_idc=[],d=this.num_sublayers-2;d>=0;--d)this.ptl_sublayer_present_mask&1<<d&&(this.sublayer_level_idc[d]=a.readUint8())}if(this.ptl_num_sub_profiles=a.readUint8(),this.general_sub_profile_idc=[],this.ptl_num_sub_profiles)for(c=0;c<this.ptl_num_sub_profiles;c++)this.general_sub_profile_idc.push(a.readUint32())}this.max_picture_width=a.readUint16(),this.max_picture_height=a.readUint16(),this.avg_frame_rate=a.readUint16()}var w=12,S=13;this.nalu_arrays=[];var T=a.readUint8();for(c=0;c<T;c++){var E=[];this.nalu_arrays.push(E),p.stream_read_1_bytes(a),E.completeness=p.extract_bits(1),p.extract_bits(2),E.nalu_type=p.extract_bits(5);var P=1;for(E.nalu_type!=S&&E.nalu_type!=w&&(P=a.readUint16()),d=0;d<P;d++){var B=a.readUint16();E.push({data:a.readUint8Array(B),length:B})}}}),h.createFullBoxCtor("vvnC",function(a){var c=strm.readUint8();this.lengthSizeMinusOne=c&3}),h.SampleEntry.prototype.isVideo=function(){return!1},h.SampleEntry.prototype.isAudio=function(){return!1},h.SampleEntry.prototype.isSubtitle=function(){return!1},h.SampleEntry.prototype.isMetadata=function(){return!1},h.SampleEntry.prototype.isHint=function(){return!1},h.SampleEntry.prototype.getCodec=function(){return this.type.replace(".","")},h.SampleEntry.prototype.getWidth=function(){return""},h.SampleEntry.prototype.getHeight=function(){return""},h.SampleEntry.prototype.getChannelCount=function(){return""},h.SampleEntry.prototype.getSampleRate=function(){return""},h.SampleEntry.prototype.getSampleSize=function(){return""},h.VisualSampleEntry.prototype.isVideo=function(){return!0},h.VisualSampleEntry.prototype.getWidth=function(){return this.width},h.VisualSampleEntry.prototype.getHeight=function(){return this.height},h.AudioSampleEntry.prototype.isAudio=function(){return!0},h.AudioSampleEntry.prototype.getChannelCount=function(){return this.channel_count},h.AudioSampleEntry.prototype.getSampleRate=function(){return this.samplerate},h.AudioSampleEntry.prototype.getSampleSize=function(){return this.samplesize},h.SubtitleSampleEntry.prototype.isSubtitle=function(){return!0},h.MetadataSampleEntry.prototype.isMetadata=function(){return!0},h.decimalToHex=function(a,c){var d=Number(a).toString(16);for(c=typeof c>"u"||c===null?c=2:c;d.length<c;)d="0"+d;return d},h.avc1SampleEntry.prototype.getCodec=h.avc2SampleEntry.prototype.getCodec=h.avc3SampleEntry.prototype.getCodec=h.avc4SampleEntry.prototype.getCodec=function(){var a=h.SampleEntry.prototype.getCodec.call(this);return this.avcC?a+"."+h.decimalToHex(this.avcC.AVCProfileIndication)+h.decimalToHex(this.avcC.profile_compatibility)+h.decimalToHex(this.avcC.AVCLevelIndication):a},h.hev1SampleEntry.prototype.getCodec=h.hvc1SampleEntry.prototype.getCodec=function(){var a,c=h.SampleEntry.prototype.getCodec.call(this);if(this.hvcC){switch(c+=".",this.hvcC.general_profile_space){case 0:c+="";break;case 1:c+="A";break;case 2:c+="B";break;case 3:c+="C";break}c+=this.hvcC.general_profile_idc,c+=".";var d=this.hvcC.general_profile_compatibility,p=0;for(a=0;a<32&&(p|=d&1,a!=31);a++)p<<=1,d>>=1;c+=h.decimalToHex(p,0),c+=".",this.hvcC.general_tier_flag===0?c+="L":c+="H",c+=this.hvcC.general_level_idc;var _=!1,b="";for(a=5;a>=0;a--)(this.hvcC.general_constraint_indicator[a]||_)&&(b="."+h.decimalToHex(this.hvcC.general_constraint_indicator[a],0)+b,_=!0);c+=b}return c},h.vvc1SampleEntry.prototype.getCodec=h.vvi1SampleEntry.prototype.getCodec=function(){var a,c=h.SampleEntry.prototype.getCodec.call(this);if(this.vvcC){c+="."+this.vvcC.general_profile_idc,this.vvcC.general_tier_flag?c+=".H":c+=".L",c+=this.vvcC.general_level_idc;var d="";if(this.vvcC.general_constraint_info){var p=[],_=0;_|=this.vvcC.ptl_frame_only_constraint<<7,_|=this.vvcC.ptl_multilayer_enabled<<6;var b;for(a=0;a<this.vvcC.general_constraint_info.length;++a)_|=this.vvcC.general_constraint_info[a]>>2&63,p.push(_),_&&(b=a),_=this.vvcC.general_constraint_info[a]>>2&3;if(b===void 0)d=".CA";else{d=".C";var v="ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",w=0,S=0;for(a=0;a<=b;++a)for(w=w<<8|p[a],S+=8;S>=5;){var T=w>>S-5&31;d+=v[T],S-=5,w&=(1<<S)-1}S&&(w<<=5-S,d+=v[w&31])}}c+=d}return c},h.mp4aSampleEntry.prototype.getCodec=function(){var a=h.SampleEntry.prototype.getCodec.call(this);if(this.esds&&this.esds.esd){var c=this.esds.esd.getOTI(),d=this.esds.esd.getAudioConfig();return a+"."+h.decimalToHex(c)+(d?"."+d:"")}else return a},h.stxtSampleEntry.prototype.getCodec=function(){var a=h.SampleEntry.prototype.getCodec.call(this);return this.mime_format?a+"."+this.mime_format:a},h.vp08SampleEntry.prototype.getCodec=h.vp09SampleEntry.prototype.getCodec=function(){var a=h.SampleEntry.prototype.getCodec.call(this),c=this.vpcC.level;c==0&&(c="00");var d=this.vpcC.bitDepth;return d==8&&(d="08"),a+".0"+this.vpcC.profile+"."+c+"."+d},h.av01SampleEntry.prototype.getCodec=function(){var a=h.SampleEntry.prototype.getCodec.call(this),c=this.av1C.seq_level_idx_0;c<10&&(c="0"+c);var d;return this.av1C.seq_profile===2&&this.av1C.high_bitdepth===1?d=this.av1C.twelve_bit===1?"12":"10":this.av1C.seq_profile<=2&&(d=this.av1C.high_bitdepth===1?"10":"08"),a+"."+this.av1C.seq_profile+"."+c+(this.av1C.seq_tier_0?"H":"M")+"."+d},h.Box.prototype.writeHeader=function(a,c){this.size+=8,this.size>n&&(this.size+=8),this.type==="uuid"&&(this.size+=16),t.debug("BoxWriter","Writing box "+this.type+" of size: "+this.size+" at position "+a.getPosition()+(c||"")),this.size>n?a.writeUint32(1):(this.sizePosition=a.getPosition(),a.writeUint32(this.size)),a.writeString(this.type,null,4),this.type==="uuid"&&a.writeUint8Array(this.uuid),this.size>n&&a.writeUint64(this.size)},h.FullBox.prototype.writeHeader=function(a){this.size+=4,h.Box.prototype.writeHeader.call(this,a," v="+this.version+" f="+this.flags),a.writeUint8(this.version),a.writeUint24(this.flags)},h.Box.prototype.write=function(a){this.type==="mdat"?this.data&&(this.size=this.data.length,this.writeHeader(a),a.writeUint8Array(this.data)):(this.size=this.data?this.data.length:0,this.writeHeader(a),this.data&&a.writeUint8Array(this.data))},h.ContainerBox.prototype.write=function(a){this.size=0,this.writeHeader(a);for(var c=0;c<this.boxes.length;c++)this.boxes[c]&&(this.boxes[c].write(a),this.size+=this.boxes[c].size);t.debug("BoxWriter","Adjusting box "+this.type+" with new size "+this.size),a.adjustUint32(this.sizePosition,this.size)},h.TrackReferenceTypeBox.prototype.write=function(a){this.size=this.track_ids.length*4,this.writeHeader(a),a.writeUint32Array(this.track_ids)},h.avcCBox.prototype.write=function(a){var c;for(this.size=7,c=0;c<this.SPS.length;c++)this.size+=2+this.SPS[c].length;for(c=0;c<this.PPS.length;c++)this.size+=2+this.PPS[c].length;for(this.ext&&(this.size+=this.ext.length),this.writeHeader(a),a.writeUint8(this.configurationVersion),a.writeUint8(this.AVCProfileIndication),a.writeUint8(this.profile_compatibility),a.writeUint8(this.AVCLevelIndication),a.writeUint8(this.lengthSizeMinusOne+252),a.writeUint8(this.SPS.length+224),c=0;c<this.SPS.length;c++)a.writeUint16(this.SPS[c].length),a.writeUint8Array(this.SPS[c].nalu);for(a.writeUint8(this.PPS.length),c=0;c<this.PPS.length;c++)a.writeUint16(this.PPS[c].length),a.writeUint8Array(this.PPS[c].nalu);this.ext&&a.writeUint8Array(this.ext)},h.co64Box.prototype.write=function(a){var c;for(this.version=0,this.flags=0,this.size=4+8*this.chunk_offsets.length,this.writeHeader(a),a.writeUint32(this.chunk_offsets.length),c=0;c<this.chunk_offsets.length;c++)a.writeUint64(this.chunk_offsets[c])},h.cslgBox.prototype.write=function(a){this.version=0,this.flags=0,this.size=20,this.writeHeader(a),a.writeInt32(this.compositionToDTSShift),a.writeInt32(this.leastDecodeToDisplayDelta),a.writeInt32(this.greatestDecodeToDisplayDelta),a.writeInt32(this.compositionStartTime),a.writeInt32(this.compositionEndTime)},h.cttsBox.prototype.write=function(a){var c;for(this.version=0,this.flags=0,this.size=4+8*this.sample_counts.length,this.writeHeader(a),a.writeUint32(this.sample_counts.length),c=0;c<this.sample_counts.length;c++)a.writeUint32(this.sample_counts[c]),this.version===1?a.writeInt32(this.sample_offsets[c]):a.writeUint32(this.sample_offsets[c])},h.drefBox.prototype.write=function(a){this.version=0,this.flags=0,this.size=4,this.writeHeader(a),a.writeUint32(this.entries.length);for(var c=0;c<this.entries.length;c++)this.entries[c].write(a),this.size+=this.entries[c].size;t.debug("BoxWriter","Adjusting box "+this.type+" with new size "+this.size),a.adjustUint32(this.sizePosition,this.size)},h.elngBox.prototype.write=function(a){this.version=0,this.flags=0,this.size=this.extended_language.length,this.writeHeader(a),a.writeString(this.extended_language)},h.elstBox.prototype.write=function(a){this.version=0,this.flags=0,this.size=4+12*this.entries.length,this.writeHeader(a),a.writeUint32(this.entries.length);for(var c=0;c<this.entries.length;c++){var d=this.entries[c];a.writeUint32(d.segment_duration),a.writeInt32(d.media_time),a.writeInt16(d.media_rate_integer),a.writeInt16(d.media_rate_fraction)}},h.emsgBox.prototype.write=function(a){this.version=0,this.flags=0,this.size=16+this.message_data.length+(this.scheme_id_uri.length+1)+(this.value.length+1),this.writeHeader(a),a.writeCString(this.scheme_id_uri),a.writeCString(this.value),a.writeUint32(this.timescale),a.writeUint32(this.presentation_time_delta),a.writeUint32(this.event_duration),a.writeUint32(this.id),a.writeUint8Array(this.message_data)},h.ftypBox.prototype.write=function(a){this.size=8+4*this.compatible_brands.length,this.writeHeader(a),a.writeString(this.major_brand,null,4),a.writeUint32(this.minor_version);for(var c=0;c<this.compatible_brands.length;c++)a.writeString(this.compatible_brands[c],null,4)},h.hdlrBox.prototype.write=function(a){this.size=20+this.name.length+1,this.version=0,this.flags=0,this.writeHeader(a),a.writeUint32(0),a.writeString(this.handler,null,4),a.writeUint32(0),a.writeUint32(0),a.writeUint32(0),a.writeCString(this.name)},h.hvcCBox.prototype.write=function(a){var c,d;for(this.size=23,c=0;c<this.nalu_arrays.length;c++)for(this.size+=3,d=0;d<this.nalu_arrays[c].length;d++)this.size+=2+this.nalu_arrays[c][d].data.length;for(this.writeHeader(a),a.writeUint8(this.configurationVersion),a.writeUint8((this.general_profile_space<<6)+(this.general_tier_flag<<5)+this.general_profile_idc),a.writeUint32(this.general_profile_compatibility),a.writeUint8Array(this.general_constraint_indicator),a.writeUint8(this.general_level_idc),a.writeUint16(this.min_spatial_segmentation_idc+(15<<24)),a.writeUint8(this.parallelismType+252),a.writeUint8(this.chroma_format_idc+252),a.writeUint8(this.bit_depth_luma_minus8+248),a.writeUint8(this.bit_depth_chroma_minus8+248),a.writeUint16(this.avgFrameRate),a.writeUint8((this.constantFrameRate<<6)+(this.numTemporalLayers<<3)+(this.temporalIdNested<<2)+this.lengthSizeMinusOne),a.writeUint8(this.nalu_arrays.length),c=0;c<this.nalu_arrays.length;c++)for(a.writeUint8((this.nalu_arrays[c].completeness<<7)+this.nalu_arrays[c].nalu_type),a.writeUint16(this.nalu_arrays[c].length),d=0;d<this.nalu_arrays[c].length;d++)a.writeUint16(this.nalu_arrays[c][d].data.length),a.writeUint8Array(this.nalu_arrays[c][d].data)},h.kindBox.prototype.write=function(a){this.version=0,this.flags=0,this.size=this.schemeURI.length+1+(this.value.length+1),this.writeHeader(a),a.writeCString(this.schemeURI),a.writeCString(this.value)},h.mdhdBox.prototype.write=function(a){this.size=20,this.flags=0,this.version=0,this.writeHeader(a),a.writeUint32(this.creation_time),a.writeUint32(this.modification_time),a.writeUint32(this.timescale),a.writeUint32(this.duration),a.writeUint16(this.language),a.writeUint16(0)},h.mehdBox.prototype.write=function(a){this.version=0,this.flags=0,this.size=4,this.writeHeader(a),a.writeUint32(this.fragment_duration)},h.mfhdBox.prototype.write=function(a){this.version=0,this.flags=0,this.size=4,this.writeHeader(a),a.writeUint32(this.sequence_number)},h.mvhdBox.prototype.write=function(a){this.version=0,this.flags=0,this.size=96,this.writeHeader(a),a.writeUint32(this.creation_time),a.writeUint32(this.modification_time),a.writeUint32(this.timescale),a.writeUint32(this.duration),a.writeUint32(this.rate),a.writeUint16(this.volume<<8),a.writeUint16(0),a.writeUint32(0),a.writeUint32(0),a.writeUint32Array(this.matrix),a.writeUint32(0),a.writeUint32(0),a.writeUint32(0),a.writeUint32(0),a.writeUint32(0),a.writeUint32(0),a.writeUint32(this.next_track_id)},h.SampleEntry.prototype.writeHeader=function(a){this.size=8,h.Box.prototype.writeHeader.call(this,a),a.writeUint8(0),a.writeUint8(0),a.writeUint8(0),a.writeUint8(0),a.writeUint8(0),a.writeUint8(0),a.writeUint16(this.data_reference_index)},h.SampleEntry.prototype.writeFooter=function(a){for(var c=0;c<this.boxes.length;c++)this.boxes[c].write(a),this.size+=this.boxes[c].size;t.debug("BoxWriter","Adjusting box "+this.type+" with new size "+this.size),a.adjustUint32(this.sizePosition,this.size)},h.SampleEntry.prototype.write=function(a){this.writeHeader(a),a.writeUint8Array(this.data),this.size+=this.data.length,t.debug("BoxWriter","Adjusting box "+this.type+" with new size "+this.size),a.adjustUint32(this.sizePosition,this.size)},h.VisualSampleEntry.prototype.write=function(a){this.writeHeader(a),this.size+=70,a.writeUint16(0),a.writeUint16(0),a.writeUint32(0),a.writeUint32(0),a.writeUint32(0),a.writeUint16(this.width),a.writeUint16(this.height),a.writeUint32(this.horizresolution),a.writeUint32(this.vertresolution),a.writeUint32(0),a.writeUint16(this.frame_count),a.writeUint8(Math.min(31,this.compressorname.length)),a.writeString(this.compressorname,null,31),a.writeUint16(this.depth),a.writeInt16(-1),this.writeFooter(a)},h.AudioSampleEntry.prototype.write=function(a){this.writeHeader(a),this.size+=20,a.writeUint32(0),a.writeUint32(0),a.writeUint16(this.channel_count),a.writeUint16(this.samplesize),a.writeUint16(0),a.writeUint16(0),a.writeUint32(this.samplerate<<16),this.writeFooter(a)},h.stppSampleEntry.prototype.write=function(a){this.writeHeader(a),this.size+=this.namespace.length+1+this.schema_location.length+1+this.auxiliary_mime_types.length+1,a.writeCString(this.namespace),a.writeCString(this.schema_location),a.writeCString(this.auxiliary_mime_types),this.writeFooter(a)},h.SampleGroupEntry.prototype.write=function(a){a.writeUint8Array(this.data)},h.sbgpBox.prototype.write=function(a){this.version=1,this.flags=0,this.size=12+8*this.entries.length,this.writeHeader(a),a.writeString(this.grouping_type,null,4),a.writeUint32(this.grouping_type_parameter),a.writeUint32(this.entries.length);for(var c=0;c<this.entries.length;c++){var d=this.entries[c];a.writeInt32(d.sample_count),a.writeInt32(d.group_description_index)}},h.sgpdBox.prototype.write=function(a){var c,d;for(this.flags=0,this.size=12,c=0;c<this.entries.length;c++)d=this.entries[c],this.version===1&&(this.default_length===0&&(this.size+=4),this.size+=d.data.length);for(this.writeHeader(a),a.writeString(this.grouping_type,null,4),this.version===1&&a.writeUint32(this.default_length),this.version>=2&&a.writeUint32(this.default_sample_description_index),a.writeUint32(this.entries.length),c=0;c<this.entries.length;c++)d=this.entries[c],this.version===1&&this.default_length===0&&a.writeUint32(d.description_length),d.write(a)},h.sidxBox.prototype.write=function(a){this.version=0,this.flags=0,this.size=20+12*this.references.length,this.writeHeader(a),a.writeUint32(this.reference_ID),a.writeUint32(this.timescale),a.writeUint32(this.earliest_presentation_time),a.writeUint32(this.first_offset),a.writeUint16(0),a.writeUint16(this.references.length);for(var c=0;c<this.references.length;c++){var d=this.references[c];a.writeUint32(d.reference_type<<31|d.referenced_size),a.writeUint32(d.subsegment_duration),a.writeUint32(d.starts_with_SAP<<31|d.SAP_type<<28|d.SAP_delta_time)}},h.smhdBox.prototype.write=function(a){this.version=0,this.flags=1,this.size=4,this.writeHeader(a),a.writeUint16(this.balance),a.writeUint16(0)},h.stcoBox.prototype.write=function(a){this.version=0,this.flags=0,this.size=4+4*this.chunk_offsets.length,this.writeHeader(a),a.writeUint32(this.chunk_offsets.length),a.writeUint32Array(this.chunk_offsets)},h.stscBox.prototype.write=function(a){var c;for(this.version=0,this.flags=0,this.size=4+12*this.first_chunk.length,this.writeHeader(a),a.writeUint32(this.first_chunk.length),c=0;c<this.first_chunk.length;c++)a.writeUint32(this.first_chunk[c]),a.writeUint32(this.samples_per_chunk[c]),a.writeUint32(this.sample_description_index[c])},h.stsdBox.prototype.write=function(a){var c;for(this.version=0,this.flags=0,this.size=0,this.writeHeader(a),a.writeUint32(this.entries.length),this.size+=4,c=0;c<this.entries.length;c++)this.entries[c].write(a),this.size+=this.entries[c].size;t.debug("BoxWriter","Adjusting box "+this.type+" with new size "+this.size),a.adjustUint32(this.sizePosition,this.size)},h.stshBox.prototype.write=function(a){var c;for(this.version=0,this.flags=0,this.size=4+8*this.shadowed_sample_numbers.length,this.writeHeader(a),a.writeUint32(this.shadowed_sample_numbers.length),c=0;c<this.shadowed_sample_numbers.length;c++)a.writeUint32(this.shadowed_sample_numbers[c]),a.writeUint32(this.sync_sample_numbers[c])},h.stssBox.prototype.write=function(a){this.version=0,this.flags=0,this.size=4+4*this.sample_numbers.length,this.writeHeader(a),a.writeUint32(this.sample_numbers.length),a.writeUint32Array(this.sample_numbers)},h.stszBox.prototype.write=function(a){var c,d=!0;if(this.version=0,this.flags=0,this.sample_sizes.length>0)for(c=0;c+1<this.sample_sizes.length;)if(this.sample_sizes[c+1]!==this.sample_sizes[0]){d=!1;break}else c++;else d=!1;this.size=8,d||(this.size+=4*this.sample_sizes.length),this.writeHeader(a),d?a.writeUint32(this.sample_sizes[0]):a.writeUint32(0),a.writeUint32(this.sample_sizes.length),d||a.writeUint32Array(this.sample_sizes)},h.sttsBox.prototype.write=function(a){var c;for(this.version=0,this.flags=0,this.size=4+8*this.sample_counts.length,this.writeHeader(a),a.writeUint32(this.sample_counts.length),c=0;c<this.sample_counts.length;c++)a.writeUint32(this.sample_counts[c]),a.writeUint32(this.sample_deltas[c])},h.tfdtBox.prototype.write=function(a){var c=Math.pow(2,32)-1;this.version=this.baseMediaDecodeTime>c?1:0,this.flags=0,this.size=4,this.version===1&&(this.size+=4),this.writeHeader(a),this.version===1?a.writeUint64(this.baseMediaDecodeTime):a.writeUint32(this.baseMediaDecodeTime)},h.tfhdBox.prototype.write=function(a){this.version=0,this.size=4,this.flags&h.TFHD_FLAG_BASE_DATA_OFFSET&&(this.size+=8),this.flags&h.TFHD_FLAG_SAMPLE_DESC&&(this.size+=4),this.flags&h.TFHD_FLAG_SAMPLE_DUR&&(this.size+=4),this.flags&h.TFHD_FLAG_SAMPLE_SIZE&&(this.size+=4),this.flags&h.TFHD_FLAG_SAMPLE_FLAGS&&(this.size+=4),this.writeHeader(a),a.writeUint32(this.track_id),this.flags&h.TFHD_FLAG_BASE_DATA_OFFSET&&a.writeUint64(this.base_data_offset),this.flags&h.TFHD_FLAG_SAMPLE_DESC&&a.writeUint32(this.default_sample_description_index),this.flags&h.TFHD_FLAG_SAMPLE_DUR&&a.writeUint32(this.default_sample_duration),this.flags&h.TFHD_FLAG_SAMPLE_SIZE&&a.writeUint32(this.default_sample_size),this.flags&h.TFHD_FLAG_SAMPLE_FLAGS&&a.writeUint32(this.default_sample_flags)},h.tkhdBox.prototype.write=function(a){this.version=0,this.size=80,this.writeHeader(a),a.writeUint32(this.creation_time),a.writeUint32(this.modification_time),a.writeUint32(this.track_id),a.writeUint32(0),a.writeUint32(this.duration),a.writeUint32(0),a.writeUint32(0),a.writeInt16(this.layer),a.writeInt16(this.alternate_group),a.writeInt16(this.volume<<8),a.writeUint16(0),a.writeInt32Array(this.matrix),a.writeUint32(this.width),a.writeUint32(this.height)},h.trexBox.prototype.write=function(a){this.version=0,this.flags=0,this.size=20,this.writeHeader(a),a.writeUint32(this.track_id),a.writeUint32(this.default_sample_description_index),a.writeUint32(this.default_sample_duration),a.writeUint32(this.default_sample_size),a.writeUint32(this.default_sample_flags)},h.trunBox.prototype.write=function(a){this.version=0,this.size=4,this.flags&h.TRUN_FLAGS_DATA_OFFSET&&(this.size+=4),this.flags&h.TRUN_FLAGS_FIRST_FLAG&&(this.size+=4),this.flags&h.TRUN_FLAGS_DURATION&&(this.size+=4*this.sample_duration.length),this.flags&h.TRUN_FLAGS_SIZE&&(this.size+=4*this.sample_size.length),this.flags&h.TRUN_FLAGS_FLAGS&&(this.size+=4*this.sample_flags.length),this.flags&h.TRUN_FLAGS_CTS_OFFSET&&(this.size+=4*this.sample_composition_time_offset.length),this.writeHeader(a),a.writeUint32(this.sample_count),this.flags&h.TRUN_FLAGS_DATA_OFFSET&&(this.data_offset_position=a.getPosition(),a.writeInt32(this.data_offset)),this.flags&h.TRUN_FLAGS_FIRST_FLAG&&a.writeUint32(this.first_sample_flags);for(var c=0;c<this.sample_count;c++)this.flags&h.TRUN_FLAGS_DURATION&&a.writeUint32(this.sample_duration[c]),this.flags&h.TRUN_FLAGS_SIZE&&a.writeUint32(this.sample_size[c]),this.flags&h.TRUN_FLAGS_FLAGS&&a.writeUint32(this.sample_flags[c]),this.flags&h.TRUN_FLAGS_CTS_OFFSET&&(this.version===0?a.writeUint32(this.sample_composition_time_offset[c]):a.writeInt32(this.sample_composition_time_offset[c]))},h["url Box"].prototype.write=function(a){this.version=0,this.location?(this.flags=0,this.size=this.location.length+1):(this.flags=1,this.size=0),this.writeHeader(a),this.location&&a.writeCString(this.location)},h["urn Box"].prototype.write=function(a){this.version=0,this.flags=0,this.size=this.name.length+1+(this.location?this.location.length+1:0),this.writeHeader(a),a.writeCString(this.name),this.location&&a.writeCString(this.location)},h.vmhdBox.prototype.write=function(a){this.version=0,this.flags=1,this.size=8,this.writeHeader(a),a.writeUint16(this.graphicsmode),a.writeUint16Array(this.opcolor)},h.vpcCBox.prototype.write=function(a){this.version=1;const c=8+this.codecIntializationDataSize;this.size=c,this.writeHeader(a),a.writeUint8(this.profile),a.writeUint8(this.level);let d=this.bitDepth<<4|(this.chromaSubsampling&7)<<1|this.videoFullRangeFlag&1;a.writeUint8(d),a.writeUint8(this.colourPrimaries),a.writeUint8(this.transferCharacteristics),a.writeUint8(this.matrixCoefficients),a.writeUint16(this.codecIntializationDataSize),this.codecIntializationDataSize>0&&a.writeUint8Array(this.codecIntializationData)},h.cttsBox.prototype.unpack=function(a){var c,d,p;for(p=0,c=0;c<this.sample_counts.length;c++)for(d=0;d<this.sample_counts[c];d++)a[p].pts=a[p].dts+this.sample_offsets[c],p++},h.sttsBox.prototype.unpack=function(a){var c,d,p;for(p=0,c=0;c<this.sample_counts.length;c++)for(d=0;d<this.sample_counts[c];d++)p===0?a[p].dts=0:a[p].dts=a[p-1].dts+this.sample_deltas[c],p++},h.stcoBox.prototype.unpack=function(a){var c;for(c=0;c<this.chunk_offsets.length;c++)a[c].offset=this.chunk_offsets[c]},h.stscBox.prototype.unpack=function(a){var c,d,p,_,b;for(_=0,b=0,c=0;c<this.first_chunk.length;c++)for(d=0;d<(c+1<this.first_chunk.length?this.first_chunk[c+1]:1/0);d++)for(b++,p=0;p<this.samples_per_chunk[c];p++){if(a[_])a[_].description_index=this.sample_description_index[c],a[_].chunk_index=b;else return;_++}},h.stszBox.prototype.unpack=function(a){var c;for(c=0;c<this.sample_sizes.length;c++)a[c].size=this.sample_sizes[c]},h.DIFF_BOXES_PROP_NAMES=["boxes","entries","references","subsamples","items","item_infos","extents","associations","subsegments","ranges","seekLists","seekPoints","esd","levels"],h.DIFF_PRIMITIVE_ARRAY_PROP_NAMES=["compatible_brands","matrix","opcolor","sample_counts","sample_counts","sample_deltas","first_chunk","samples_per_chunk","sample_sizes","chunk_offsets","sample_offsets","sample_description_index","sample_duration"],h.boxEqualFields=function(a,c){if(a&&!c)return!1;var d;for(d in a)if(!(h.DIFF_BOXES_PROP_NAMES.indexOf(d)>-1)){if(a[d]instanceof h.Box||c[d]instanceof h.Box)continue;if(typeof a[d]>"u"||typeof c[d]>"u")continue;if(typeof a[d]=="function"||typeof c[d]=="function")continue;if(a.subBoxNames&&a.subBoxNames.indexOf(d.slice(0,4))>-1||c.subBoxNames&&c.subBoxNames.indexOf(d.slice(0,4))>-1)continue;if(d==="data"||d==="start"||d==="size"||d==="creation_time"||d==="modification_time")continue;if(h.DIFF_PRIMITIVE_ARRAY_PROP_NAMES.indexOf(d)>-1)continue;if(a[d]!==c[d])return!1}return!0},h.boxEqual=function(a,c){if(!h.boxEqualFields(a,c))return!1;for(var d=0;d<h.DIFF_BOXES_PROP_NAMES.length;d++){var p=h.DIFF_BOXES_PROP_NAMES[d];if(a[p]&&c[p]&&!h.boxEqual(a[p],c[p]))return!1}return!0};var m=function(){};m.prototype.parseSample=function(a){var c={},d;c.resources=[];var p=new e(a.data.buffer);if(!a.subsamples||a.subsamples.length===0)c.documentString=p.readString(a.data.length);else if(c.documentString=p.readString(a.subsamples[0].size),a.subsamples.length>1)for(d=1;d<a.subsamples.length;d++)c.resources[d]=p.readUint8Array(a.subsamples[d].size);return typeof DOMParser<"u"&&(c.document=new DOMParser().parseFromString(c.documentString,"application/xml")),c};var g=function(){};g.prototype.parseSample=function(a){var c,d=new e(a.data.buffer);return c=d.readString(a.data.length),c},g.prototype.parseConfig=function(a){var c,d=new e(a.buffer);return d.readUint32(),c=d.readCString(),c},s.XMLSubtitlein4Parser=m,s.Textin4Parser=g;var y=function(a){this.stream=a||new o,this.boxes=[],this.mdats=[],this.moofs=[],this.isProgressive=!1,this.moovStartFound=!1,this.onMoovStart=null,this.moovStartSent=!1,this.onReady=null,this.readySent=!1,this.onSegment=null,this.onSamples=null,this.onError=null,this.sampleListBuilt=!1,this.fragmentedTracks=[],this.extractedTracks=[],this.isFragmentationInitialized=!1,this.sampleProcessingStarted=!1,this.nextMoofNumber=0,this.itemListBuilt=!1,this.onSidx=null,this.sidxSent=!1};y.prototype.setSegmentOptions=function(a,c,d){var p=this.getTrackById(a);if(p){var _={};this.fragmentedTracks.push(_),_.id=a,_.user=c,_.trak=p,p.nextSample=0,_.segmentStream=null,_.nb_samples=1e3,_.rapAlignement=!0,d&&(d.nbSamples&&(_.nb_samples=d.nbSamples),d.rapAlignement&&(_.rapAlignement=d.rapAlignement))}},y.prototype.unsetSegmentOptions=function(a){for(var c=-1,d=0;d<this.fragmentedTracks.length;d++){var p=this.fragmentedTracks[d];p.id==a&&(c=d)}c>-1&&this.fragmentedTracks.splice(c,1)},y.prototype.setExtractionOptions=function(a,c,d){var p=this.getTrackById(a);if(p){var _={};this.extractedTracks.push(_),_.id=a,_.user=c,_.trak=p,p.nextSample=0,_.nb_samples=1e3,_.samples=[],d&&d.nbSamples&&(_.nb_samples=d.nbSamples)}},y.prototype.unsetExtractionOptions=function(a){for(var c=-1,d=0;d<this.extractedTracks.length;d++){var p=this.extractedTracks[d];p.id==a&&(c=d)}c>-1&&this.extractedTracks.splice(c,1)},y.prototype.parse=function(){var a,c,d=!1;if(!(this.restoreParsePosition&&!this.restoreParsePosition()))for(;;)if(this.hasIncompleteMdat&&this.hasIncompleteMdat()){if(this.processIncompleteMdat())continue;return}else if(this.saveParsePosition&&this.saveParsePosition(),a=h.parseOneBox(this.stream,d),a.code===h.ERR_NOT_ENOUGH_DATA)if(this.processIncompleteBox){if(this.processIncompleteBox(a))continue;return}else return;else{var p;switch(c=a.box,p=c.type!=="uuid"?c.type:c.uuid,this.boxes.push(c),p){case"mdat":this.mdats.push(c);break;case"moof":this.moofs.push(c);break;case"moov":this.moovStartFound=!0,this.mdats.length===0&&(this.isProgressive=!0);default:this[p]!==void 0&&t.warn("ISOFile","Duplicate Box of type: "+p+", overriding previous occurrence"),this[p]=c;break}this.updateUsedBytes&&this.updateUsedBytes(c,a)}},y.prototype.checkBuffer=function(a){if(a==null)throw"Buffer must be defined and non empty";if(a.fileStart===void 0)throw"Buffer must have a fileStart property";return a.byteLength===0?(t.warn("ISOFile","Ignoring empty buffer (fileStart: "+a.fileStart+")"),this.stream.logBufferLevel(),!1):(t.info("ISOFile","Processing buffer (fileStart: "+a.fileStart+")"),a.usedBytes=0,this.stream.insertBuffer(a),this.stream.logBufferLevel(),this.stream.initialized()?!0:(t.warn("ISOFile","Not ready to start parsing"),!1))},y.prototype.appendBuffer=function(a,c){var d;if(this.checkBuffer(a))return this.parse(),this.moovStartFound&&!this.moovStartSent&&(this.moovStartSent=!0,this.onMoovStart&&this.onMoovStart()),this.moov?(this.sampleListBuilt||(this.buildSampleLists(),this.sampleListBuilt=!0),this.updateSampleLists(),this.onReady&&!this.readySent&&(this.readySent=!0,this.onReady(this.getInfo())),this.processSamples(c),this.nextSeekPosition?(d=this.nextSeekPosition,this.nextSeekPosition=void 0):d=this.nextParsePosition,this.stream.getEndFilePositionAfter&&(d=this.stream.getEndFilePositionAfter(d))):this.nextParsePosition?d=this.nextParsePosition:d=0,this.sidx&&this.onSidx&&!this.sidxSent&&(this.onSidx(this.sidx),this.sidxSent=!0),this.meta&&(this.flattenItemInfo&&!this.itemListBuilt&&(this.flattenItemInfo(),this.itemListBuilt=!0),this.processItems&&this.processItems(this.onItem)),this.stream.cleanBuffers&&(t.info("ISOFile","Done processing buffer (fileStart: "+a.fileStart+") - next buffer to fetch should have a fileStart position of "+d),this.stream.logBufferLevel(),this.stream.cleanBuffers(),this.stream.logBufferLevel(!0),t.info("ISOFile","Sample data size in memory: "+this.getAllocatedSampleDataSize())),d},y.prototype.getInfo=function(){var a,c,d={},p,_,b,v,w=new Date("1904-01-01T00:00:00Z").getTime();if(this.moov)for(d.hasMoov=!0,d.duration=this.moov.mvhd.duration,d.timescale=this.moov.mvhd.timescale,d.isFragmented=this.moov.mvex!=null,d.isFragmented&&this.moov.mvex.mehd&&(d.fragment_duration=this.moov.mvex.mehd.fragment_duration),d.isProgressive=this.isProgressive,d.hasIOD=this.moov.iods!=null,d.brands=[],d.brands.push(this.ftyp.major_brand),d.brands=d.brands.concat(this.ftyp.compatible_brands),d.created=new Date(w+this.moov.mvhd.creation_time*1e3),d.modified=new Date(w+this.moov.mvhd.modification_time*1e3),d.tracks=[],d.audioTracks=[],d.videoTracks=[],d.subtitleTracks=[],d.metadataTracks=[],d.hintTracks=[],d.otherTracks=[],a=0;a<this.moov.traks.length;a++){if(p=this.moov.traks[a],v=p.mdia.minf.stbl.stsd.entries[0],_={},d.tracks.push(_),_.id=p.tkhd.track_id,_.name=p.mdia.hdlr.name,_.references=[],p.tref)for(c=0;c<p.tref.boxes.length;c++)b={},_.references.push(b),b.type=p.tref.boxes[c].type,b.track_ids=p.tref.boxes[c].track_ids;p.edts&&(_.edits=p.edts.elst.entries),_.created=new Date(w+p.tkhd.creation_time*1e3),_.modified=new Date(w+p.tkhd.modification_time*1e3),_.movie_duration=p.tkhd.duration,_.movie_timescale=d.timescale,_.layer=p.tkhd.layer,_.alternate_group=p.tkhd.alternate_group,_.volume=p.tkhd.volume,_.matrix=p.tkhd.matrix,_.track_width=p.tkhd.width/65536,_.track_height=p.tkhd.height/65536,_.timescale=p.mdia.mdhd.timescale,_.cts_shift=p.mdia.minf.stbl.cslg,_.duration=p.mdia.mdhd.duration,_.samples_duration=p.samples_duration,_.codec=v.getCodec(),_.kind=p.udta&&p.udta.kinds.length?p.udta.kinds[0]:{schemeURI:"",value:""},_.language=p.mdia.elng?p.mdia.elng.extended_language:p.mdia.mdhd.languageString,_.nb_samples=p.samples.length,_.size=p.samples_size,_.bitrate=_.size*8*_.timescale/_.samples_duration,v.isAudio()?(_.type="audio",d.audioTracks.push(_),_.audio={},_.audio.sample_rate=v.getSampleRate(),_.audio.channel_count=v.getChannelCount(),_.audio.sample_size=v.getSampleSize()):v.isVideo()?(_.type="video",d.videoTracks.push(_),_.video={},_.video.width=v.getWidth(),_.video.height=v.getHeight()):v.isSubtitle()?(_.type="subtitles",d.subtitleTracks.push(_)):v.isHint()?(_.type="metadata",d.hintTracks.push(_)):v.isMetadata()?(_.type="metadata",d.metadataTracks.push(_)):(_.type="metadata",d.otherTracks.push(_))}else d.hasMoov=!1;if(d.mime="",d.hasMoov&&d.tracks){for(d.videoTracks&&d.videoTracks.length>0?d.mime+='video/mp4; codecs="':d.audioTracks&&d.audioTracks.length>0?d.mime+='audio/mp4; codecs="':d.mime+='application/mp4; codecs="',a=0;a<d.tracks.length;a++)a!==0&&(d.mime+=","),d.mime+=d.tracks[a].codec;d.mime+='"; profiles="',d.mime+=this.ftyp.compatible_brands.join(),d.mime+='"'}return d},y.prototype.setNextSeekPositionFromSample=function(a){a&&(this.nextSeekPosition?this.nextSeekPosition=Math.min(a.offset+a.alreadyRead,this.nextSeekPosition):this.nextSeekPosition=a.offset+a.alreadyRead)},y.prototype.processSamples=function(a){var c,d;if(this.sampleProcessingStarted){if(this.isFragmentationInitialized&&this.onSegment!==null)for(c=0;c<this.fragmentedTracks.length;c++){var p=this.fragmentedTracks[c];for(d=p.trak;d.nextSample<d.samples.length&&this.sampleProcessingStarted;){t.debug("ISOFile","Creating media fragment on track #"+p.id+" for sample "+d.nextSample);var _=this.createFragment(p.id,d.nextSample,p.segmentStream);if(_)p.segmentStream=_,d.nextSample++;else break;if((d.nextSample%p.nb_samples===0||a||d.nextSample>=d.samples.length)&&(t.info("ISOFile","Sending fragmented data on track #"+p.id+" for samples ["+Math.max(0,d.nextSample-p.nb_samples)+","+(d.nextSample-1)+"]"),t.info("ISOFile","Sample data size in memory: "+this.getAllocatedSampleDataSize()),this.onSegment&&this.onSegment(p.id,p.user,p.segmentStream.buffer,d.nextSample,a||d.nextSample>=d.samples.length),p.segmentStream=null,p!==this.fragmentedTracks[c]))break}}if(this.onSamples!==null)for(c=0;c<this.extractedTracks.length;c++){var b=this.extractedTracks[c];for(d=b.trak;d.nextSample<d.samples.length&&this.sampleProcessingStarted;){t.debug("ISOFile","Exporting on track #"+b.id+" sample #"+d.nextSample);var v=this.getSample(d,d.nextSample);if(v)d.nextSample++,b.samples.push(v);else{this.setNextSeekPositionFromSample(d.samples[d.nextSample]);break}if((d.nextSample%b.nb_samples===0||d.nextSample>=d.samples.length)&&(t.debug("ISOFile","Sending samples on track #"+b.id+" for sample "+d.nextSample),this.onSamples&&this.onSamples(b.id,b.user,b.samples),b.samples=[],b!==this.extractedTracks[c]))break}}}},y.prototype.getBox=function(a){var c=this.getBoxes(a,!0);return c.length?c[0]:null},y.prototype.getBoxes=function(a,c){var d=[];return y._sweep.call(this,a,d,c),d},y._sweep=function(a,c,d){this.type&&this.type==a&&c.push(this);for(var p in this.boxes){if(c.length&&d)return;y._sweep.call(this.boxes[p],a,c,d)}},y.prototype.getTrackSamplesInfo=function(a){var c=this.getTrackById(a);if(c)return c.samples},y.prototype.getTrackSample=function(a,c){var d=this.getTrackById(a),p=this.getSample(d,c);return p},y.prototype.releaseUsedSamples=function(a,c){var d=0,p=this.getTrackById(a);p.lastValidSample||(p.lastValidSample=0);for(var _=p.lastValidSample;_<c;_++)d+=this.releaseSample(p,_);t.info("ISOFile","Track #"+a+" released samples up to "+c+" (released size: "+d+", remaining: "+this.samplesDataSize+")"),p.lastValidSample=c},y.prototype.start=function(){this.sampleProcessingStarted=!0,this.processSamples(!1)},y.prototype.stop=function(){this.sampleProcessingStarted=!1},y.prototype.flush=function(){t.info("ISOFile","Flushing remaining samples"),this.updateSampleLists(),this.processSamples(!0),this.stream.cleanBuffers(),this.stream.logBufferLevel(!0)},y.prototype.seekTrack=function(a,c,d){var p,_,b=1/0,v=0,w=0,S;if(d.samples.length===0)return t.info("ISOFile","No sample in track, cannot seek! Using time "+t.getDurationString(0,1)+" and offset: 0"),{offset:0,time:0};for(p=0;p<d.samples.length;p++){if(_=d.samples[p],p===0)w=0,S=_.timescale;else if(_.cts>a*_.timescale){w=p-1;break}c&&_.is_sync&&(v=p)}for(c&&(w=v),a=d.samples[w].cts,d.nextSample=w;d.samples[w].alreadyRead===d.samples[w].size&&d.samples[w+1];)w++;return b=d.samples[w].offset+d.samples[w].alreadyRead,t.info("ISOFile","Seeking to "+(c?"RAP":"")+" sample #"+d.nextSample+" on track "+d.tkhd.track_id+", time "+t.getDurationString(a,S)+" and offset: "+b),{offset:b,time:a/S}},y.prototype.getTrackDuration=function(a){var c;return a.samples?(c=a.samples[a.samples.length-1],(c.cts+c.duration)/c.timescale):1/0},y.prototype.seek=function(a,c){var d=this.moov,p,_,b,v={offset:1/0,time:1/0};if(this.moov){for(b=0;b<d.traks.length;b++)p=d.traks[b],!(a>this.getTrackDuration(p))&&(_=this.seekTrack(a,c,p),_.offset<v.offset&&(v.offset=_.offset),_.time<v.time&&(v.time=_.time));return t.info("ISOFile","Seeking at time "+t.getDurationString(v.time,1)+" needs a buffer with a fileStart position of "+v.offset),v.offset===1/0?v={offset:this.nextParsePosition,time:0}:v.offset=this.stream.getEndFilePositionAfter(v.offset),t.info("ISOFile","Adjusted seek position (after checking data already in buffer): "+v.offset),v}else throw"Cannot seek: moov not received!"},y.prototype.equal=function(a){for(var c=0;c<this.boxes.length&&c<a.boxes.length;){var d=this.boxes[c],p=a.boxes[c];if(!h.boxEqual(d,p))return!1;c++}return!0},s.ISOFile=y,y.prototype.lastBoxStartPosition=0,y.prototype.parsingMdat=null,y.prototype.nextParsePosition=0,y.prototype.discardMdatData=!1,y.prototype.processIncompleteBox=function(a){var c,d,p;return a.type==="mdat"?(c=new h[a.type+"Box"](a.size),this.parsingMdat=c,this.boxes.push(c),this.mdats.push(c),c.start=a.start,c.hdr_size=a.hdr_size,this.stream.addUsedBytes(c.hdr_size),this.lastBoxStartPosition=c.start+c.size,p=this.stream.seek(c.start+c.size,!1,this.discardMdatData),p?(this.parsingMdat=null,!0):(this.moovStartFound?this.nextParsePosition=this.stream.findEndContiguousBuf():this.nextParsePosition=c.start+c.size,!1)):(a.type==="moov"&&(this.moovStartFound=!0,this.mdats.length===0&&(this.isProgressive=!0)),d=this.stream.mergeNextBuffer?this.stream.mergeNextBuffer():!1,d?(this.nextParsePosition=this.stream.getEndPosition(),!0):(a.type?this.moovStartFound?this.nextParsePosition=this.stream.getEndPosition():this.nextParsePosition=this.stream.getPosition()+a.size:this.nextParsePosition=this.stream.getEndPosition(),!1))},y.prototype.hasIncompleteMdat=function(){return this.parsingMdat!==null},y.prototype.processIncompleteMdat=function(){var a,c;return a=this.parsingMdat,c=this.stream.seek(a.start+a.size,!1,this.discardMdatData),c?(t.debug("ISOFile","Found 'mdat' end in buffered data"),this.parsingMdat=null,!0):(this.nextParsePosition=this.stream.findEndContiguousBuf(),!1)},y.prototype.restoreParsePosition=function(){return this.stream.seek(this.lastBoxStartPosition,!0,this.discardMdatData)},y.prototype.saveParsePosition=function(){this.lastBoxStartPosition=this.stream.getPosition()},y.prototype.updateUsedBytes=function(a,c){this.stream.addUsedBytes&&(a.type==="mdat"?(this.stream.addUsedBytes(a.hdr_size),this.discardMdatData&&this.stream.addUsedBytes(a.size-a.hdr_size)):this.stream.addUsedBytes(a.size))},y.prototype.add=h.Box.prototype.add,y.prototype.addBox=h.Box.prototype.addBox,y.prototype.init=function(a){var c=a||{};this.add("ftyp").set("major_brand",c.brands&&c.brands[0]||"iso4").set("minor_version",0).set("compatible_brands",c.brands||["iso4"]);var d=this.add("moov");return d.add("mvhd").set("timescale",c.timescale||600).set("rate",c.rate||65536).set("creation_time",0).set("modification_time",0).set("duration",c.duration||0).set("volume",c.width?0:256).set("matrix",[65536,0,0,0,65536,0,0,0,1073741824]).set("next_track_id",1),d.add("mvex"),this},y.prototype.addTrack=function(a){this.moov||this.init(a);var c=a||{};c.width=c.width||320,c.height=c.height||320,c.id=c.id||this.moov.mvhd.next_track_id,c.type=c.type||"avc1";var d=this.moov.add("trak");this.moov.mvhd.next_track_id=c.id+1,d.add("tkhd").set("flags",h.TKHD_FLAG_ENABLED|h.TKHD_FLAG_IN_MOVIE|h.TKHD_FLAG_IN_PREVIEW).set("creation_time",0).set("modification_time",0).set("track_id",c.id).set("duration",c.duration||0).set("layer",c.layer||0).set("alternate_group",0).set("volume",1).set("matrix",[65536,0,0,0,65536,0,0,0,1073741824]).set("width",c.width<<16).set("height",c.height<<16);var p=d.add("mdia");p.add("mdhd").set("creation_time",0).set("modification_time",0).set("timescale",c.timescale||1).set("duration",c.media_duration||0).set("language",c.language||"und"),p.add("hdlr").set("handler",c.hdlr||"vide").set("name",c.name||"Track created with MP4Box.js"),p.add("elng").set("extended_language",c.language||"fr-FR");var _=p.add("minf");if(h[c.type+"SampleEntry"]!==void 0){var b=new h[c.type+"SampleEntry"];b.data_reference_index=1;var v="";for(var w in h.sampleEntryCodes)for(var S=h.sampleEntryCodes[w],T=0;T<S.length;T++)if(S.indexOf(c.type)>-1){v=w;break}switch(v){case"Visual":if(_.add("vmhd").set("graphicsmode",0).set("opcolor",[0,0,0]),b.set("width",c.width).set("height",c.height).set("horizresolution",72<<16).set("vertresolution",72<<16).set("frame_count",1).set("compressorname",c.type+" Compressor").set("depth",24),c.avcDecoderConfigRecord){var E=new h.avcCBox;E.parse(new e(c.avcDecoderConfigRecord)),b.addBox(E)}else if(c.hevcDecoderConfigRecord){var P=new h.hvcCBox;P.parse(new e(c.hevcDecoderConfigRecord)),b.addBox(P)}else if(c.vpcDecoderConfigRecord){var B=new h.vpcCBox;B.parse(new e(c.vpcDecoderConfigRecord)),b.addBox(B)}break;case"Audio":_.add("smhd").set("balance",c.balance||0),b.set("channel_count",c.channel_count||2).set("samplesize",c.samplesize||16).set("samplerate",c.samplerate||65536);break;case"Hint":_.add("hmhd");break;case"Subtitle":switch(_.add("sthd"),c.type){case"stpp":b.set("namespace",c.namespace||"nonamespace").set("schema_location",c.schema_location||"").set("auxiliary_mime_types",c.auxiliary_mime_types||"");break}break;case"Metadata":_.add("nmhd");break;case"System":_.add("nmhd");break;default:_.add("nmhd");break}c.description&&b.addBox(c.description),c.description_boxes&&c.description_boxes.forEach(function(O){b.addBox(O)}),_.add("dinf").add("dref").addEntry(new h["url Box"]().set("flags",1));var A=_.add("stbl");return A.add("stsd").addEntry(b),A.add("stts").set("sample_counts",[]).set("sample_deltas",[]),A.add("stsc").set("first_chunk",[]).set("samples_per_chunk",[]).set("sample_description_index",[]),A.add("stco").set("chunk_offsets",[]),A.add("stsz").set("sample_sizes",[]),this.moov.mvex.add("trex").set("track_id",c.id).set("default_sample_description_index",c.default_sample_description_index||1).set("default_sample_duration",c.default_sample_duration||0).set("default_sample_size",c.default_sample_size||0).set("default_sample_flags",c.default_sample_flags||0),this.buildTrakSampleLists(d),c.id}},h.Box.prototype.computeSize=function(a){var c=a||new r;c.endianness=r.BIG_ENDIAN,this.write(c)},y.prototype.addSample=function(a,c,d){var p=d||{},_={},b=this.getTrackById(a);if(b!==null){_.number=b.samples.length,_.track_id=b.tkhd.track_id,_.timescale=b.mdia.mdhd.timescale,_.description_index=p.sample_description_index?p.sample_description_index-1:0,_.description=b.mdia.minf.stbl.stsd.entries[_.description_index],_.data=c,_.size=c.byteLength,_.alreadyRead=_.size,_.duration=p.duration||1,_.cts=p.cts||0,_.dts=p.dts||0,_.is_sync=p.is_sync||!1,_.is_leading=p.is_leading||0,_.depends_on=p.depends_on||0,_.is_depended_on=p.is_depended_on||0,_.has_redundancy=p.has_redundancy||0,_.degradation_priority=p.degradation_priority||0,_.offset=0,_.subsamples=p.subsamples,b.samples.push(_),b.samples_size+=_.size,b.samples_duration+=_.duration,b.first_dts===void 0&&(b.first_dts=p.dts),this.processSamples();var v=this.createSingleSampleMoof(_);return this.addBox(v),v.computeSize(),v.trafs[0].truns[0].data_offset=v.size+8,this.add("mdat").data=new Uint8Array(c),_}},y.prototype.createSingleSampleMoof=function(a){var c=0;a.is_sync?c=1<<25:c=65536;var d=new h.moofBox;d.add("mfhd").set("sequence_number",this.nextMoofNumber),this.nextMoofNumber++;var p=d.add("traf"),_=this.getTrackById(a.track_id);return p.add("tfhd").set("track_id",a.track_id).set("flags",h.TFHD_FLAG_DEFAULT_BASE_IS_MOOF),p.add("tfdt").set("baseMediaDecodeTime",a.dts-(_.first_dts||0)),p.add("trun").set("flags",h.TRUN_FLAGS_DATA_OFFSET|h.TRUN_FLAGS_DURATION|h.TRUN_FLAGS_SIZE|h.TRUN_FLAGS_FLAGS|h.TRUN_FLAGS_CTS_OFFSET).set("data_offset",0).set("first_sample_flags",0).set("sample_count",1).set("sample_duration",[a.duration]).set("sample_size",[a.size]).set("sample_flags",[c]).set("sample_composition_time_offset",[a.cts-a.dts]),d},y.prototype.lastMoofIndex=0,y.prototype.samplesDataSize=0,y.prototype.resetTables=function(){var a,c,d,p,_,b,v,w;for(this.initial_duration=this.moov.mvhd.duration,this.moov.mvhd.duration=0,a=0;a<this.moov.traks.length;a++){c=this.moov.traks[a],c.tkhd.duration=0,c.mdia.mdhd.duration=0,d=c.mdia.minf.stbl.stco||c.mdia.minf.stbl.co64,d.chunk_offsets=[],p=c.mdia.minf.stbl.stsc,p.first_chunk=[],p.samples_per_chunk=[],p.sample_description_index=[],_=c.mdia.minf.stbl.stsz||c.mdia.minf.stbl.stz2,_.sample_sizes=[],b=c.mdia.minf.stbl.stts,b.sample_counts=[],b.sample_deltas=[],v=c.mdia.minf.stbl.ctts,v&&(v.sample_counts=[],v.sample_offsets=[]),w=c.mdia.minf.stbl.stss;var S=c.mdia.minf.stbl.boxes.indexOf(w);S!=-1&&(c.mdia.minf.stbl.boxes[S]=null)}},y.initSampleGroups=function(a,c,d,p,_){var b,v,w,S;function T(E,P,B){this.grouping_type=E,this.grouping_type_parameter=P,this.sbgp=B,this.last_sample_in_run=-1,this.entry_index=-1}for(c&&(c.sample_groups_info=[]),a.sample_groups_info||(a.sample_groups_info=[]),v=0;v<d.length;v++){for(S=d[v].grouping_type+"/"+d[v].grouping_type_parameter,w=new T(d[v].grouping_type,d[v].grouping_type_parameter,d[v]),c&&(c.sample_groups_info[S]=w),a.sample_groups_info[S]||(a.sample_groups_info[S]=w),b=0;b<p.length;b++)p[b].grouping_type===d[v].grouping_type&&(w.description=p[b],w.description.used=!0);if(_)for(b=0;b<_.length;b++)_[b].grouping_type===d[v].grouping_type&&(w.fragment_description=_[b],w.fragment_description.used=!0,w.is_fragment=!0)}if(c){if(_)for(v=0;v<_.length;v++)!_[v].used&&_[v].version>=2&&(S=_[v].grouping_type+"/0",w=new T(_[v].grouping_type,0),w.is_fragment=!0,c.sample_groups_info[S]||(c.sample_groups_info[S]=w))}else for(v=0;v<p.length;v++)!p[v].used&&p[v].version>=2&&(S=p[v].grouping_type+"/0",w=new T(p[v].grouping_type,0),a.sample_groups_info[S]||(a.sample_groups_info[S]=w))},y.setSampleGroupProperties=function(a,c,d,p){var _,b;c.sample_groups=[];for(_ in p)if(c.sample_groups[_]={},c.sample_groups[_].grouping_type=p[_].grouping_type,c.sample_groups[_].grouping_type_parameter=p[_].grouping_type_parameter,d>=p[_].last_sample_in_run&&(p[_].last_sample_in_run<0&&(p[_].last_sample_in_run=0),p[_].entry_index++,p[_].entry_index<=p[_].sbgp.entries.length-1&&(p[_].last_sample_in_run+=p[_].sbgp.entries[p[_].entry_index].sample_count)),p[_].entry_index<=p[_].sbgp.entries.length-1?c.sample_groups[_].group_description_index=p[_].sbgp.entries[p[_].entry_index].group_description_index:c.sample_groups[_].group_description_index=-1,c.sample_groups[_].group_description_index!==0){var v;p[_].fragment_description?v=p[_].fragment_description:v=p[_].description,c.sample_groups[_].group_description_index>0?(c.sample_groups[_].group_description_index>65535?b=(c.sample_groups[_].group_description_index>>16)-1:b=c.sample_groups[_].group_description_index-1,v&&b>=0&&(c.sample_groups[_].description=v.entries[b])):v&&v.version>=2&&v.default_group_description_index>0&&(c.sample_groups[_].description=v.entries[v.default_group_description_index-1])}},y.process_sdtp=function(a,c,d){c&&(a?(c.is_leading=a.is_leading[d],c.depends_on=a.sample_depends_on[d],c.is_depended_on=a.sample_is_depended_on[d],c.has_redundancy=a.sample_has_redundancy[d]):(c.is_leading=0,c.depends_on=0,c.is_depended_on=0,c.has_redundancy=0))},y.prototype.buildSampleLists=function(){var a,c;for(a=0;a<this.moov.traks.length;a++)c=this.moov.traks[a],this.buildTrakSampleLists(c)},y.prototype.buildTrakSampleLists=function(a){var c,d,p,_,b,v,w,S,T,E,P,B,A,O,L,j,Ot,U,R,St,V,Gt,Tt,$t;if(a.samples=[],a.samples_duration=0,a.samples_size=0,d=a.mdia.minf.stbl.stco||a.mdia.minf.stbl.co64,p=a.mdia.minf.stbl.stsc,_=a.mdia.minf.stbl.stsz||a.mdia.minf.stbl.stz2,b=a.mdia.minf.stbl.stts,v=a.mdia.minf.stbl.ctts,w=a.mdia.minf.stbl.stss,S=a.mdia.minf.stbl.stsd,T=a.mdia.minf.stbl.subs,B=a.mdia.minf.stbl.stdp,E=a.mdia.minf.stbl.sbgps,P=a.mdia.minf.stbl.sgpds,U=-1,R=-1,St=-1,V=-1,Gt=0,Tt=0,$t=0,y.initSampleGroups(a,null,E,P),!(typeof _>"u")){for(c=0;c<_.sample_sizes.length;c++){var N={};N.number=c,N.track_id=a.tkhd.track_id,N.timescale=a.mdia.mdhd.timescale,N.alreadyRead=0,a.samples[c]=N,N.size=_.sample_sizes[c],a.samples_size+=N.size,c===0?(O=1,A=0,N.chunk_index=O,N.chunk_run_index=A,Ot=p.samples_per_chunk[A],j=0,A+1<p.first_chunk.length?L=p.first_chunk[A+1]-1:L=1/0):c<Ot?(N.chunk_index=O,N.chunk_run_index=A):(O++,N.chunk_index=O,j=0,O<=L||(A++,A+1<p.first_chunk.length?L=p.first_chunk[A+1]-1:L=1/0),N.chunk_run_index=A,Ot+=p.samples_per_chunk[A]),N.description_index=p.sample_description_index[N.chunk_run_index]-1,N.description=S.entries[N.description_index],N.offset=d.chunk_offsets[N.chunk_index-1]+j,j+=N.size,c>U&&(R++,U<0&&(U=0),U+=b.sample_counts[R]),c>0?(a.samples[c-1].duration=b.sample_deltas[R],a.samples_duration+=a.samples[c-1].duration,N.dts=a.samples[c-1].dts+a.samples[c-1].duration):N.dts=0,v?(c>=St&&(V++,St<0&&(St=0),St+=v.sample_counts[V]),N.cts=a.samples[c].dts+v.sample_offsets[V]):N.cts=N.dts,w?(c==w.sample_numbers[Gt]-1?(N.is_sync=!0,Gt++):(N.is_sync=!1,N.degradation_priority=0),T&&T.entries[Tt].sample_delta+$t==c+1&&(N.subsamples=T.entries[Tt].subsamples,$t+=T.entries[Tt].sample_delta,Tt++)):N.is_sync=!0,y.process_sdtp(a.mdia.minf.stbl.sdtp,N,N.number),B?N.degradation_priority=B.priority[c]:N.degradation_priority=0,T&&T.entries[Tt].sample_delta+$t==c&&(N.subsamples=T.entries[Tt].subsamples,$t+=T.entries[Tt].sample_delta),(E.length>0||P.length>0)&&y.setSampleGroupProperties(a,N,c,a.sample_groups_info)}c>0&&(a.samples[c-1].duration=Math.max(a.mdia.mdhd.duration-a.samples[c-1].dts,0),a.samples_duration+=a.samples[c-1].duration)}},y.prototype.updateSampleLists=function(){var a,c,d,p,_,b,v,w,S,T,E,P,B,A,O;if(this.moov!==void 0){for(;this.lastMoofIndex<this.moofs.length;)if(S=this.moofs[this.lastMoofIndex],this.lastMoofIndex++,S.type=="moof")for(T=S,a=0;a<T.trafs.length;a++){for(E=T.trafs[a],P=this.getTrackById(E.tfhd.track_id),P.samples==null&&(P.samples=[]),B=this.getTrexById(E.tfhd.track_id),E.tfhd.flags&h.TFHD_FLAG_SAMPLE_DESC?p=E.tfhd.default_sample_description_index:p=B?B.default_sample_description_index:1,E.tfhd.flags&h.TFHD_FLAG_SAMPLE_DUR?_=E.tfhd.default_sample_duration:_=B?B.default_sample_duration:0,E.tfhd.flags&h.TFHD_FLAG_SAMPLE_SIZE?b=E.tfhd.default_sample_size:b=B?B.default_sample_size:0,E.tfhd.flags&h.TFHD_FLAG_SAMPLE_FLAGS?v=E.tfhd.default_sample_flags:v=B?B.default_sample_flags:0,E.sample_number=0,E.sbgps.length>0&&y.initSampleGroups(P,E,E.sbgps,P.mdia.minf.stbl.sgpds,E.sgpds),c=0;c<E.truns.length;c++){var L=E.truns[c];for(d=0;d<L.sample_count;d++){A={},A.moof_number=this.lastMoofIndex,A.number_in_traf=E.sample_number,E.sample_number++,A.number=P.samples.length,E.first_sample_index=P.samples.length,P.samples.push(A),A.track_id=P.tkhd.track_id,A.timescale=P.mdia.mdhd.timescale,A.description_index=p-1,A.description=P.mdia.minf.stbl.stsd.entries[A.description_index],A.size=b,L.flags&h.TRUN_FLAGS_SIZE&&(A.size=L.sample_size[d]),P.samples_size+=A.size,A.duration=_,L.flags&h.TRUN_FLAGS_DURATION&&(A.duration=L.sample_duration[d]),P.samples_duration+=A.duration,P.first_traf_merged||d>0?A.dts=P.samples[P.samples.length-2].dts+P.samples[P.samples.length-2].duration:(E.tfdt?A.dts=E.tfdt.baseMediaDecodeTime:A.dts=0,P.first_traf_merged=!0),A.cts=A.dts,L.flags&h.TRUN_FLAGS_CTS_OFFSET&&(A.cts=A.dts+L.sample_composition_time_offset[d]),O=v,L.flags&h.TRUN_FLAGS_FLAGS?O=L.sample_flags[d]:d===0&&L.flags&h.TRUN_FLAGS_FIRST_FLAG&&(O=L.first_sample_flags),A.is_sync=!(O>>16&1),A.is_leading=O>>26&3,A.depends_on=O>>24&3,A.is_depended_on=O>>22&3,A.has_redundancy=O>>20&3,A.degradation_priority=O&65535;var j=!!(E.tfhd.flags&h.TFHD_FLAG_BASE_DATA_OFFSET),Ot=!!(E.tfhd.flags&h.TFHD_FLAG_DEFAULT_BASE_IS_MOOF),U=!!(L.flags&h.TRUN_FLAGS_DATA_OFFSET),R=0;j?R=E.tfhd.base_data_offset:Ot||c===0?R=T.start:R=w,c===0&&d===0?U?A.offset=R+L.data_offset:A.offset=R:A.offset=w,w=A.offset+A.size,(E.sbgps.length>0||E.sgpds.length>0||P.mdia.minf.stbl.sbgps.length>0||P.mdia.minf.stbl.sgpds.length>0)&&y.setSampleGroupProperties(P,A,A.number_in_traf,E.sample_groups_info)}}if(E.subs){P.has_fragment_subsamples=!0;var St=E.first_sample_index;for(c=0;c<E.subs.entries.length;c++)St+=E.subs.entries[c].sample_delta,A=P.samples[St-1],A.subsamples=E.subs.entries[c].subsamples}}}},y.prototype.getSample=function(a,c){var d,p=a.samples[c];if(!this.moov)return null;if(!p.data)p.data=new Uint8Array(p.size),p.alreadyRead=0,this.samplesDataSize+=p.size,t.debug("ISOFile","Allocating sample #"+c+" on track #"+a.tkhd.track_id+" of size "+p.size+" (total: "+this.samplesDataSize+")");else if(p.alreadyRead==p.size)return p;for(;;){var _=this.stream.findPosition(!0,p.offset+p.alreadyRead,!1);if(_>-1){d=this.stream.buffers[_];var b=d.byteLength-(p.offset+p.alreadyRead-d.fileStart);if(p.size-p.alreadyRead<=b)return t.debug("ISOFile","Getting sample #"+c+" data (alreadyRead: "+p.alreadyRead+" offset: "+(p.offset+p.alreadyRead-d.fileStart)+" read size: "+(p.size-p.alreadyRead)+" full size: "+p.size+")"),r.memcpy(p.data.buffer,p.alreadyRead,d,p.offset+p.alreadyRead-d.fileStart,p.size-p.alreadyRead),d.usedBytes+=p.size-p.alreadyRead,this.stream.logBufferLevel(),p.alreadyRead=p.size,p;if(b===0)return null;t.debug("ISOFile","Getting sample #"+c+" partial data (alreadyRead: "+p.alreadyRead+" offset: "+(p.offset+p.alreadyRead-d.fileStart)+" read size: "+b+" full size: "+p.size+")"),r.memcpy(p.data.buffer,p.alreadyRead,d,p.offset+p.alreadyRead-d.fileStart,b),p.alreadyRead+=b,d.usedBytes+=b,this.stream.logBufferLevel()}else return null}},y.prototype.releaseSample=function(a,c){var d=a.samples[c];return d.data?(this.samplesDataSize-=d.size,d.data=null,d.alreadyRead=0,d.size):0},y.prototype.getAllocatedSampleDataSize=function(){return this.samplesDataSize},y.prototype.getCodecs=function(){var a,c="";for(a=0;a<this.moov.traks.length;a++){var d=this.moov.traks[a];a>0&&(c+=","),c+=d.mdia.minf.stbl.stsd.entries[0].getCodec()}return c},y.prototype.getTrexById=function(a){var c;if(!this.moov||!this.moov.mvex)return null;for(c=0;c<this.moov.mvex.trexs.length;c++){var d=this.moov.mvex.trexs[c];if(d.track_id==a)return d}return null},y.prototype.getTrackById=function(a){if(this.moov===void 0)return null;for(var c=0;c<this.moov.traks.length;c++){var d=this.moov.traks[c];if(d.tkhd.track_id==a)return d}return null},y.prototype.items=[],y.prototype.entity_groups=[],y.prototype.itemsDataSize=0,y.prototype.flattenItemInfo=function(){var a=this.items,c=this.entity_groups,d,p,_,b=this.meta;if(b!=null&&b.hdlr!==void 0&&b.iinf!==void 0){for(d=0;d<b.iinf.item_infos.length;d++)_={},_.id=b.iinf.item_infos[d].item_ID,a[_.id]=_,_.ref_to=[],_.name=b.iinf.item_infos[d].item_name,b.iinf.item_infos[d].protection_index>0&&(_.protection=b.ipro.protections[b.iinf.item_infos[d].protection_index-1]),b.iinf.item_infos[d].item_type?_.type=b.iinf.item_infos[d].item_type:_.type="mime",_.content_type=b.iinf.item_infos[d].content_type,_.content_encoding=b.iinf.item_infos[d].content_encoding;if(b.grpl)for(d=0;d<b.grpl.boxes.length;d++)entity_group={},entity_group.id=b.grpl.boxes[d].group_id,entity_group.entity_ids=b.grpl.boxes[d].entity_ids,entity_group.type=b.grpl.boxes[d].type,c[entity_group.id]=entity_group;if(b.iloc)for(d=0;d<b.iloc.items.length;d++){var v=b.iloc.items[d];switch(_=a[v.item_ID],v.data_reference_index!==0&&(t.warn("Item storage with reference to other files: not supported"),_.source=b.dinf.boxes[v.data_reference_index-1]),v.construction_method){case 0:break;case 1:t.warn("Item storage with construction_method : not supported");break;case 2:t.warn("Item storage with construction_method : not supported");break}for(_.extents=[],_.size=0,p=0;p<v.extents.length;p++)_.extents[p]={},_.extents[p].offset=v.extents[p].extent_offset+v.base_offset,_.extents[p].length=v.extents[p].extent_length,_.extents[p].alreadyRead=0,_.size+=_.extents[p].length}if(b.pitm&&(a[b.pitm.item_id].primary=!0),b.iref)for(d=0;d<b.iref.references.length;d++){var w=b.iref.references[d];for(p=0;p<w.references.length;p++)a[w.from_item_ID].ref_to.push({type:w.type,id:w.references[p]})}if(b.iprp)for(var S=0;S<b.iprp.ipmas.length;S++){var T=b.iprp.ipmas[S];for(d=0;d<T.associations.length;d++){var E=T.associations[d];if(_=a[E.id],_||(_=c[E.id]),_)for(_.properties===void 0&&(_.properties={},_.properties.boxes=[]),p=0;p<E.props.length;p++){var P=E.props[p];if(P.property_index>0&&P.property_index-1<b.iprp.ipco.boxes.length){var B=b.iprp.ipco.boxes[P.property_index-1];_.properties[B.type]=B,_.properties.boxes.push(B)}}}}}},y.prototype.getItem=function(a){var c,d;if(!this.meta)return null;if(d=this.items[a],!d.data&&d.size)d.data=new Uint8Array(d.size),d.alreadyRead=0,this.itemsDataSize+=d.size,t.debug("ISOFile","Allocating item #"+a+" of size "+d.size+" (total: "+this.itemsDataSize+")");else if(d.alreadyRead===d.size)return d;for(var p=0;p<d.extents.length;p++){var _=d.extents[p];if(_.alreadyRead!==_.length){var b=this.stream.findPosition(!0,_.offset+_.alreadyRead,!1);if(b>-1){c=this.stream.buffers[b];var v=c.byteLength-(_.offset+_.alreadyRead-c.fileStart);if(_.length-_.alreadyRead<=v)t.debug("ISOFile","Getting item #"+a+" extent #"+p+" data (alreadyRead: "+_.alreadyRead+" offset: "+(_.offset+_.alreadyRead-c.fileStart)+" read size: "+(_.length-_.alreadyRead)+" full extent size: "+_.length+" full item size: "+d.size+")"),r.memcpy(d.data.buffer,d.alreadyRead,c,_.offset+_.alreadyRead-c.fileStart,_.length-_.alreadyRead),c.usedBytes+=_.length-_.alreadyRead,this.stream.logBufferLevel(),d.alreadyRead+=_.length-_.alreadyRead,_.alreadyRead=_.length;else return t.debug("ISOFile","Getting item #"+a+" extent #"+p+" partial data (alreadyRead: "+_.alreadyRead+" offset: "+(_.offset+_.alreadyRead-c.fileStart)+" read size: "+v+" full extent size: "+_.length+" full item size: "+d.size+")"),r.memcpy(d.data.buffer,d.alreadyRead,c,_.offset+_.alreadyRead-c.fileStart,v),_.alreadyRead+=v,d.alreadyRead+=v,c.usedBytes+=v,this.stream.logBufferLevel(),null}else return null}}return d.alreadyRead===d.size?d:null},y.prototype.releaseItem=function(a){var c=this.items[a];if(c.data){this.itemsDataSize-=c.size,c.data=null,c.alreadyRead=0;for(var d=0;d<c.extents.length;d++){var p=c.extents[d];p.alreadyRead=0}return c.size}else return 0},y.prototype.processItems=function(a){for(var c in this.items){var d=this.items[c];this.getItem(d.id),a&&!d.sent&&(a(d),d.sent=!0,d.data=null)}},y.prototype.hasItem=function(a){for(var c in this.items){var d=this.items[c];if(d.name===a)return d.id}return-1},y.prototype.getMetaHandler=function(){return this.meta?this.meta.hdlr.handler:null},y.prototype.getPrimaryItem=function(){return!this.meta||!this.meta.pitm?null:this.getItem(this.meta.pitm.item_id)},y.prototype.itemToFragmentedTrackFile=function(a){var c=a||{},d=null;if(c.itemId?d=this.getItem(c.itemId):d=this.getPrimaryItem(),d==null)return null;var p=new y;p.discardMdatData=!1;var _={type:d.type,description_boxes:d.properties.boxes};d.properties.ispe&&(_.width=d.properties.ispe.image_width,_.height=d.properties.ispe.image_height);var b=p.addTrack(_);return b?(p.addSample(b,d.data),p):null},y.prototype.write=function(a){for(var c=0;c<this.boxes.length;c++)this.boxes[c].write(a)},y.prototype.createFragment=function(a,c,d){var p=this.getTrackById(a),_=this.getSample(p,c);if(_==null)return this.setNextSeekPositionFromSample(p.samples[c]),null;var b=d||new r;b.endianness=r.BIG_ENDIAN;var v=this.createSingleSampleMoof(_);v.write(b),v.trafs[0].truns[0].data_offset=v.size+8,t.debug("MP4Box","Adjusting data_offset with new value "+v.trafs[0].truns[0].data_offset),b.adjustUint32(v.trafs[0].truns[0].data_offset_position,v.trafs[0].truns[0].data_offset);var w=new h.mdatBox;return w.data=_.data,w.write(b),b},y.writeInitializationSegment=function(a,c,d,p){var _;t.debug("ISOFile","Generating initialization segment");var b=new r;b.endianness=r.BIG_ENDIAN,a.write(b);var v=c.add("mvex");for(d&&v.add("mehd").set("fragment_duration",d),_=0;_<c.traks.length;_++)v.add("trex").set("track_id",c.traks[_].tkhd.track_id).set("default_sample_description_index",1).set("default_sample_duration",p).set("default_sample_size",0).set("default_sample_flags",65536);return c.write(b),b.buffer},y.prototype.save=function(a){var c=new r;c.endianness=r.BIG_ENDIAN,this.write(c),c.save(a)},y.prototype.getBuffer=function(){var a=new r;return a.endianness=r.BIG_ENDIAN,this.write(a),a.buffer},y.prototype.initializeSegmentation=function(){var a,c,d,p;for(this.onSegment===null&&t.warn("MP4Box","No segmentation callback set!"),this.isFragmentationInitialized||(this.isFragmentationInitialized=!0,this.nextMoofNumber=0,this.resetTables()),c=[],a=0;a<this.fragmentedTracks.length;a++){var _=new h.moovBox;_.mvhd=this.moov.mvhd,_.boxes.push(_.mvhd),d=this.getTrackById(this.fragmentedTracks[a].id),_.boxes.push(d),_.traks.push(d),p={},p.id=d.tkhd.track_id,p.user=this.fragmentedTracks[a].user,p.buffer=y.writeInitializationSegment(this.ftyp,_,this.moov.mvex&&this.moov.mvex.mehd?this.moov.mvex.mehd.fragment_duration:void 0,this.moov.traks[a].samples.length>0?this.moov.traks[a].samples[0].duration:0),c.push(p)}return c},h.Box.prototype.printHeader=function(a){this.size+=8,this.size>n&&(this.size+=8),this.type==="uuid"&&(this.size+=16),a.log(a.indent+"size:"+this.size),a.log(a.indent+"type:"+this.type)},h.FullBox.prototype.printHeader=function(a){this.size+=4,h.Box.prototype.printHeader.call(this,a),a.log(a.indent+"version:"+this.version),a.log(a.indent+"flags:"+this.flags)},h.Box.prototype.print=function(a){this.printHeader(a)},h.ContainerBox.prototype.print=function(a){this.printHeader(a);for(var c=0;c<this.boxes.length;c++)if(this.boxes[c]){var d=a.indent;a.indent+=" ",this.boxes[c].print(a),a.indent=d}},y.prototype.print=function(a){a.indent="";for(var c=0;c<this.boxes.length;c++)this.boxes[c]&&this.boxes[c].print(a)},h.mvhdBox.prototype.print=function(a){h.FullBox.prototype.printHeader.call(this,a),a.log(a.indent+"creation_time: "+this.creation_time),a.log(a.indent+"modification_time: "+this.modification_time),a.log(a.indent+"timescale: "+this.timescale),a.log(a.indent+"duration: "+this.duration),a.log(a.indent+"rate: "+this.rate),a.log(a.indent+"volume: "+(this.volume>>8)),a.log(a.indent+"matrix: "+this.matrix.join(", ")),a.log(a.indent+"next_track_id: "+this.next_track_id)},h.tkhdBox.prototype.print=function(a){h.FullBox.prototype.printHeader.call(this,a),a.log(a.indent+"creation_time: "+this.creation_time),a.log(a.indent+"modification_time: "+this.modification_time),a.log(a.indent+"track_id: "+this.track_id),a.log(a.indent+"duration: "+this.duration),a.log(a.indent+"volume: "+(this.volume>>8)),a.log(a.indent+"matrix: "+this.matrix.join(", ")),a.log(a.indent+"layer: "+this.layer),a.log(a.indent+"alternate_group: "+this.alternate_group),a.log(a.indent+"width: "+this.width),a.log(a.indent+"height: "+this.height)};var x={};x.createFile=function(a,c){var d=a!==void 0?a:!0,p=new y(c);return p.discardMdatData=!d,p},s.createFile=x.createFile})(Qr)),Qr}var yu=_u();const yt=ye(yu);var Eo=s=>{throw TypeError(s)},Ao=(s,t,e)=>t.has(s)||Eo("Cannot "+e),X=(s,t,e)=>(Ao(s,t,"read from private field"),e?e.call(s):t.get(s)),Mt=(s,t,e)=>t.has(s)?Eo("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(s):t.set(s,e),pt=(s,t,e,r)=>(Ao(s,t,"write to private field"),t.set(s,e),e);const Po="KGZ1bmN0aW9uKCl7InVzZSBzdHJpY3QiO2Z1bmN0aW9uIHUobil7aWYobj09PSIvIilyZXR1cm57cGFyZW50Om51bGwsbmFtZToiIn07Y29uc3QgZT1uLnNwbGl0KCIvIikuZmlsdGVyKGk9PmkubGVuZ3RoPjApO2lmKGUubGVuZ3RoPT09MCl0aHJvdyBFcnJvcigiSW52YWxpZCBwYXRoIik7Y29uc3QgYT1lW2UubGVuZ3RoLTFdLHI9Ii8iK2Uuc2xpY2UoMCwtMSkuam9pbigiLyIpO3JldHVybntuYW1lOmEscGFyZW50OnJ9fWFzeW5jIGZ1bmN0aW9uIHcobixlKXtjb25zdHtwYXJlbnQ6YSxuYW1lOnJ9PXUobik7aWYoYT09bnVsbClyZXR1cm4gYXdhaXQgbmF2aWdhdG9yLnN0b3JhZ2UuZ2V0RGlyZWN0b3J5KCk7Y29uc3QgaT1hLnNwbGl0KCIvIikuZmlsdGVyKHQ9PnQubGVuZ3RoPjApO3RyeXtsZXQgdD1hd2FpdCBuYXZpZ2F0b3Iuc3RvcmFnZS5nZXREaXJlY3RvcnkoKTtmb3IoY29uc3QgcyBvZiBpKXQ9YXdhaXQgdC5nZXREaXJlY3RvcnlIYW5kbGUocyx7Y3JlYXRlOmUuY3JlYXRlfSk7aWYoZS5pc0ZpbGUpcmV0dXJuIGF3YWl0IHQuZ2V0RmlsZUhhbmRsZShyLHtjcmVhdGU6ZS5jcmVhdGV9KX1jYXRjaCh0KXtpZih0Lm5hbWU9PT0iTm90Rm91bmRFcnJvciIpcmV0dXJuIG51bGw7dGhyb3cgdH19Y29uc3QgZj17fTtzZWxmLm9ubWVzc2FnZT1hc3luYyBuPT57dmFyIGk7Y29uc3R7ZXZ0VHlwZTplLGFyZ3M6YX09bi5kYXRhO2xldCByPWZbYS5maWxlSWRdO3RyeXtsZXQgdDtjb25zdCBzPVtdO2lmKGU9PT0icmVnaXN0ZXIiKXtjb25zdCBsPWF3YWl0IHcoYS5maWxlUGF0aCx7Y3JlYXRlOiEwLGlzRmlsZTohMH0pO2lmKGw9PW51bGwpdGhyb3cgRXJyb3IoYG5vdCBmb3VuZCBmaWxlOiAke2EuZmlsZUlkfWApO3I9YXdhaXQgbC5jcmVhdGVTeW5jQWNjZXNzSGFuZGxlKHttb2RlOmEubW9kZX0pLGZbYS5maWxlSWRdPXJ9ZWxzZSBpZihlPT09ImNsb3NlIilhd2FpdCByLmNsb3NlKCksZGVsZXRlIGZbYS5maWxlSWRdO2Vsc2UgaWYoZT09PSJ0cnVuY2F0ZSIpYXdhaXQgci50cnVuY2F0ZShhLm5ld1NpemUpO2Vsc2UgaWYoZT09PSJ3cml0ZSIpe2NvbnN0e2RhdGE6bCxvcHRzOm99PW4uZGF0YS5hcmdzO3Q9YXdhaXQgci53cml0ZShsLG8pfWVsc2UgaWYoZT09PSJyZWFkIil7Y29uc3R7b2Zmc2V0Omwsc2l6ZTpvfT1uLmRhdGEuYXJncyxnPW5ldyBVaW50OEFycmF5KG8pLGQ9YXdhaXQgci5yZWFkKGcse2F0Omx9KSxjPWcuYnVmZmVyO3Q9ZD09PW8/YzooKGk9Yy50cmFuc2Zlcik9PW51bGw/dm9pZCAwOmkuY2FsbChjLGQpKT8/Yy5zbGljZSgwLGQpLHMucHVzaCh0KX1lbHNlIGU9PT0iZ2V0U2l6ZSI/dD1hd2FpdCByLmdldFNpemUoKTplPT09ImZsdXNoIiYmYXdhaXQgci5mbHVzaCgpO3NlbGYucG9zdE1lc3NhZ2Uoe2V2dFR5cGU6ImNhbGxiYWNrIixjYklkOm4uZGF0YS5jYklkLHJldHVyblZhbDp0fSxzKX1jYXRjaCh0KXtjb25zdCBzPXQ7c2VsZi5wb3N0TWVzc2FnZSh7ZXZ0VHlwZToidGhyb3dFcnJvciIsY2JJZDpuLmRhdGEuY2JJZCxlcnJNc2c6cy5uYW1lKyI6ICIrcy5tZXNzYWdlK2AKYCtKU09OLnN0cmluZ2lmeShuLmRhdGEpfSl9fX0pKCk7Ci8vIyBzb3VyY2VNYXBwaW5nVVJMPW9wZnMtd29ya2VyLUY0UldscWNfLmpzLm1hcAo=",xu=s=>Uint8Array.from(atob(s),t=>t.charCodeAt(0)),Bo=typeof self<"u"&&self.Blob&&new Blob([xu(Po)],{type:"text/javascript;charset=utf-8"});function bu(s){let t;try{if(t=Bo&&(self.URL||self.webkitURL).createObjectURL(Bo),!t)throw"";const e=new Worker(t,{name:s?.name});return e.addEventListener("error",()=>{(self.URL||self.webkitURL).revokeObjectURL(t)}),e}catch{return new Worker("data:text/javascript;base64,"+Po,{name:s?.name})}finally{t&&(self.URL||self.webkitURL).revokeObjectURL(t)}}async function vu(s,t,e){const r=wu();return await r("register",{fileId:s,filePath:t,mode:e}),{read:async(n,o)=>await r("read",{fileId:s,offset:n,size:o}),write:async(n,o)=>await r("write",{fileId:s,data:n,opts:o},[ArrayBuffer.isView(n)?n.buffer:n]),close:async()=>await r("close",{fileId:s}),truncate:async n=>await r("truncate",{fileId:s,newSize:n}),getSize:async()=>await r("getSize",{fileId:s}),flush:async()=>await r("flush",{fileId:s})}}const Zi=[];let Jr=0;function wu(){if(Zi.length<3){const t=s();return Zi.push(t),t}else{const t=Zi[Jr];return Jr=(Jr+1)%Zi.length,t}function s(){const t=new bu;let e=0,r={};return t.onmessage=({data:n})=>{var o,l;n.evtType==="callback"?(o=r[n.cbId])==null||o.resolve(n.returnVal):n.evtType==="throwError"&&((l=r[n.cbId])==null||l.reject(Error(n.errMsg))),delete r[n.cbId]},async function(n,o,l=[]){e+=1;const h=new Promise((u,f)=>{r[e]={resolve:u,reject:f}});return t.postMessage({cbId:e,evtType:n,args:o},l),h}}}function Qi(s){if(s==="/")return{parent:null,name:""};const t=s.split("/").filter(n=>n.length>0);if(t.length===0)throw Error("Invalid path");const e=t[t.length-1],r="/"+t.slice(0,-1).join("/");return{name:e,parent:r}}async function de(s,t){const{parent:e,name:r}=Qi(s);if(e==null)return await navigator.storage.getDirectory();const n=e.split("/").filter(o=>o.length>0);try{let o=await navigator.storage.getDirectory();for(const l of n)o=await o.getDirectoryHandle(l,{create:t.create});return t.isFile?await o.getFileHandle(r,{create:t.create}):await o.getDirectoryHandle(r,{create:t.create})}catch(o){if(o.name==="NotFoundError")return null;throw o}}async function ts(s){const{parent:t,name:e}=Qi(s);if(t==null){const n=await navigator.storage.getDirectory();for await(const o of n.keys())await n.removeEntry(o,{recursive:!0});return}const r=await de(t,{create:!1,isFile:!1});if(r!=null)try{await r.removeEntry(e,{recursive:!0})}catch(n){if(n.name==="NotFoundError")return;throw n}}function es(s,t){return`${s}/${t}`.replace("//","/")}function Fe(s){return new Uo(s)}var Kt,Ji,si;const Su=class $d{constructor(t){Mt(this,Kt),Mt(this,Ji),Mt(this,si),pt(this,Kt,t);const{parent:e,name:r}=Qi(t);pt(this,Ji,r),pt(this,si,e)}get kind(){return"dir"}get name(){return X(this,Ji)}get path(){return X(this,Kt)}get parent(){return X(this,si)==null?null:Fe(X(this,si))}async create(){return await de(X(this,Kt),{create:!0,isFile:!1}),Fe(X(this,Kt))}async exists(){return await de(X(this,Kt),{create:!1,isFile:!1})instanceof FileSystemDirectoryHandle}async remove(t={}){for(const e of await this.children())try{await e.remove(t)}catch(r){console.warn(r)}try{await ts(X(this,Kt))}catch(e){console.warn(e)}}async children(){const t=await de(X(this,Kt),{create:!1,isFile:!1});if(t==null)return[];const e=[];for await(const r of t.values())e.push((r.kind==="file"?ni:Fe)(es(X(this,Kt),r.name)));return e}async copyTo(t){if(!await this.exists())throw Error(`dir ${this.path} not exists`);if(t instanceof $d){const e=await t.exists()?Fe(es(t.path,this.name)):t;return await e.create(),await Promise.all((await this.children()).map(r=>r.copyTo(e))),e}else if(t instanceof FileSystemDirectoryHandle)return await Promise.all((await this.children()).map(async e=>{e.kind==="file"?await e.copyTo(await t.getFileHandle(e.name,{create:!0})):await e.copyTo(await t.getDirectoryHandle(e.name,{create:!0}))})),null;throw Error("Illegal target type")}async moveTo(t){const e=await this.copyTo(t);return await this.remove(),e}};Kt=new WeakMap,Ji=new WeakMap,si=new WeakMap;let Uo=Su;const is=new Map;function ni(s,t="rw"){if(t==="rw"){const e=is.get(s)??new sr(s,t);return is.set(s,e),e}return new sr(s,t)}async function oi(s,t,e={overwrite:!0}){if(t instanceof sr){await oi(s,await t.stream(),e);return}const r=await(s instanceof sr?s:ni(s,"rw")).createWriter();try{if(e.overwrite&&await r.truncate(0),t instanceof ReadableStream){const n=t.getReader();for(;;){const{done:o,value:l}=await n.read();if(o)break;await r.write(l)}}else await r.write(t)}catch(n){throw n}finally{await r.close()}}let Tu=0;const Cu=()=>++Tu;var Rt,ai,tr,hi,er,Jt,ir,rr,De;const Eu=class Kd{constructor(t,e){Mt(this,Rt),Mt(this,ai),Mt(this,tr),Mt(this,hi),Mt(this,er),Mt(this,Jt,0),Mt(this,ir,async()=>{}),Mt(this,rr,(()=>{let o=null;return()=>(pt(this,Jt,X(this,Jt)+1),o!=null||(o=new Promise(async(l,h)=>{try{const u=await vu(X(this,er),X(this,Rt),X(this,hi));pt(this,ir,async()=>{o!=null&&(o=null,pt(this,Jt,0),await u.close().catch(console.error))}),l([u,async()=>{pt(this,Jt,X(this,Jt)-1),!(X(this,Jt)>0)&&(o=null,await u.close())}])}catch(u){h(u)}})),o)})()),Mt(this,De,!1),pt(this,er,Cu()),pt(this,Rt,t),pt(this,hi,{r:"read-only",rw:"readwrite","rw-unsafe":"readwrite-unsafe"}[e]);const{parent:r,name:n}=Qi(t);if(r==null)throw Error("Invalid path");pt(this,tr,n),pt(this,ai,r)}get kind(){return"file"}get path(){return X(this,Rt)}get name(){return X(this,tr)}get parent(){return X(this,ai)==null?null:Fe(X(this,ai))}async createWriter(){if(X(this,hi)==="read-only")throw Error("file is read-only");if(X(this,De))throw Error("Other writer have not been closed");pt(this,De,!0);try{const t=new TextEncoder,[e,r]=await X(this,rr).call(this);let n=await e.getSize(),o=!1;return{write:async(l,h={})=>{if(o)throw Error("Writer is closed");const u=typeof l=="string"?t.encode(l):l,f=h.at??n,m=u.byteLength;return n=f+m,await e.write(u,{at:f})},truncate:async l=>{if(o)throw Error("Writer is closed");await e.truncate(l),n>l&&(n=l)},flush:async()=>{if(o)throw Error("Writer is closed");await e.flush()},close:async()=>{if(o)throw Error("Writer is closed");o=!0,pt(this,De,!1),await r()}}}catch(t){throw pt(this,De,!1),t}}async createReader(){const[t,e]=await X(this,rr).call(this);let r=!1,n=0;return{read:async(o,l={})=>{if(r)throw Error("Reader is closed");const h=l.at??n,u=await t.read(h,o);return n=h+u.byteLength,u},getSize:async()=>{if(r)throw Error("Reader is closed");return await t.getSize()},close:async()=>{r||(r=!0,await e())}}}async text(){return new TextDecoder().decode(await this.arrayBuffer())}async arrayBuffer(){const t=await de(X(this,Rt),{create:!1,isFile:!0});return t==null?new ArrayBuffer(0):(await t.getFile()).arrayBuffer()}async stream(){const t=await this.getOriginFile();return t==null?new ReadableStream({pull:e=>{e.close()}}):t.stream()}async getOriginFile(){var t;return(t=await de(X(this,Rt),{create:!1,isFile:!0}))==null?void 0:t.getFile()}async getSize(){const t=await de(X(this,Rt),{create:!1,isFile:!0});return t==null?0:(await t.getFile()).size}async exists(){return await de(X(this,Rt),{create:!1,isFile:!0})instanceof FileSystemFileHandle}async remove(t={}){if(t.force===!0){await X(this,ir).call(this),await ts(X(this,Rt)),is.delete(X(this,Rt));return}if(X(this,Jt)>0)throw Error("exists unclosed reader/writer");await ts(X(this,Rt))}async copyTo(t){if(t instanceof Kd)return t.path===this.path?this:(await oi(t,this),t);if(t instanceof Uo){if(!await this.exists())throw Error(`file ${this.path} not exists`);return await this.copyTo(ni(es(t.path,this.name)))}else if(t instanceof FileSystemFileHandle)return await(await this.stream()).pipeTo(await t.createWritable()),null;throw Error("Illegal target type")}async moveTo(t){const e=await this.copyTo(t);return await this.remove(),e}};Rt=new WeakMap,ai=new WeakMap,tr=new WeakMap,hi=new WeakMap,er=new WeakMap,Jt=new WeakMap,ir=new WeakMap,rr=new WeakMap,De=new WeakMap;let sr=Eu;const rs="/.opfs-tools-temp-dir";async function ko(s){try{if(s.kind==="file"){if(!await s.exists())return!0;const t=await s.createWriter();await t.truncate(0),await t.close(),await s.remove()}else await s.remove();return!0}catch(t){return console.warn(t),!1}}function Au(){setInterval(async()=>{for(const s of await Fe(rs).children()){const t=/^\d+-(\d+)$/.exec(s.name);(t==null||Date.now()-Number(t[1])>2592e5)&&await ko(s)}},60*1e3)}const ss=[];let Mo=!1;async function Pu(){if(globalThis.localStorage==null)return;const s="OPFS_TOOLS_EXPIRES_TMP_FILES";Mo||(Mo=!0,globalThis.addEventListener("unload",()=>{ss.length!==0&&localStorage.setItem(s,`${localStorage.getItem(s)??""},${ss.join(",")}`)}));let t=localStorage.getItem(s)??"";for(const e of t.split(","))e.length!==0&&await ko(ni(`${rs}/${e}`))&&(t=t.replace(e,""));localStorage.setItem(s,t.replace(/,{2,}/g,","))}(async function(){var s;globalThis.__opfs_tools_tmpfile_init__!==!0&&(globalThis.__opfs_tools_tmpfile_init__=!0,!(globalThis.FileSystemDirectoryHandle==null||globalThis.FileSystemFileHandle==null||((s=globalThis.navigator)==null?void 0:s.storage.getDirectory)==null)&&(Au(),await Pu()))})();function ns(){const s=`${Math.random().toString().slice(2)}-${Date.now()}`;return ss.push(s),ni(`${rs}/${s}`)}class os{static forwardEvent(t,e,r){const n=r.map(o=>{const[l,h]=Array.isArray(o)?o:[o,o];return t.on(l,(...u)=>{e.emit(h,...u)})});return()=>{n.forEach(o=>o())}}listeners=new Map;on=(t,e)=>{const r=this.listeners.get(t)??new Set;return r.add(e),this.listeners.has(t)||this.listeners.set(t,r),()=>{r.delete(e),r.size===0&&this.listeners.delete(t)}};once=(t,e)=>{const r=this.on(t,(...n)=>{r(),e(...n)});return r};emit=(t,...e)=>{const r=this.listeners.get(t);r?.forEach(n=>n(...e))};destroy(){this.listeners.clear()}}function Bu(s){return s instanceof Error?String(s):typeof s=="object"?JSON.stringify(s,(t,e)=>e instanceof Error?String(e):e):String(s)}function Uu(){const s=new Date;return`${s.getHours()}:${s.getMinutes()}:${s.getSeconds()}.${s.getMilliseconds()}`}let Ro=1;const Io=[],Fo=["debug","info","warn","error"].reduce((s,t,e)=>Object.assign(s,{[t]:(...r)=>{Ro<=e&&(console[t](...r),Io.push({lvName:t,timeStr:Uu(),args:r}))}}),{}),li=new Map,H={setLogLevel:s=>{Ro=li.get(s)??1},...Fo,create:s=>Object.fromEntries(Object.entries(Fo).map(([t,e])=>[t,(...r)=>e(s,...r)])),async dump(){return Io.reduce((s,{lvName:t,timeStr:e,args:r})=>s+`[${t}][${e}] ${r.map(n=>Bu(n)).join(" ")}
|
|
2
|
+
`,"")}};li.set(H.debug,0),li.set(H.info,1),li.set(H.warn,2),li.set(H.error,3),(async function(){if(await Promise.resolve(),!(globalThis.navigator==null||globalThis.document==null)&&(H.info(globalThis.navigator.userAgent),document.addEventListener("visibilitychange",()=>{H.info(`visibilitychange: ${document.visibilityState}`)}),"PressureObserver"in globalThis)){let t="";new PressureObserver(r=>{const n=JSON.stringify(r.map(o=>o.state));n!==t&&(H.info(`cpu state change: ${n}`),t=n)}).observe("cpu")}})();const as=(s,t)=>{const e=new Uint8Array(8);new DataView(e.buffer).setUint32(0,t);for(let n=0;n<4;n++)e[4+n]=s.charCodeAt(n);return e},ku=()=>{const s=new TextEncoder,t=s.encode("mdta"),e=s.encode("mp4 handler"),r=32+e.byteLength+1,n=new Uint8Array(r),o=new DataView(n.buffer);return n.set(as("hdlr",r),0),o.setUint32(8,0),n.set(t,16),n.set(e,32),n},Mu=s=>{const t=new TextEncoder,e=t.encode("mdta"),r=s.map(f=>{const m=t.encode(f),g=8+m.byteLength,y=new Uint8Array(g);return new DataView(y.buffer).setUint32(0,g),y.set(e,4),y.set(m,4+e.byteLength),y}),o=16+r.reduce((f,m)=>f+m.byteLength,0),l=new Uint8Array(o),h=new DataView(l.buffer);l.set(as("keys",o),0),h.setUint32(8,0),h.setUint32(12,s.length);let u=16;for(const f of r)l.set(f,u),u+=f.byteLength;return l},Ru=s=>{const t=new TextEncoder,e=t.encode("data"),r=Object.entries(s).map(([u,f],m)=>{const g=m+1,y=t.encode(f),x=24+y.byteLength,a=new Uint8Array(x),c=new DataView(a.buffer);return c.setUint32(0,x),c.setUint32(4,g),c.setUint32(8,16+y.byteLength),a.set(e,12),c.setUint32(16,1),a.set(y,24),a}),o=8+r.reduce((u,f)=>u+f.byteLength,0),l=new Uint8Array(o);l.set(as("ilst",o),0);let h=8;for(const u of r)l.set(u,h),h+=u.byteLength;return l},Iu=s=>{const t=ku(),e=Mu(Object.keys(s)),r=Ru(s),n=t.length+e.length+r.length,o=new Uint8Array(n);return o.set(t,0),o.set(e,t.length),o.set(r,t.length+e.length),o},Fu=()=>{let s,t=16.6;self.onmessage=e=>{e.data.event==="start"&&(self.clearInterval(s),s=self.setInterval(()=>{self.postMessage({})},t)),e.data.event==="stop"&&self.clearInterval(s)}},Du=()=>{const s=new Blob([`(${Fu.toString()})()`]),t=URL.createObjectURL(s);return new Worker(t)},Oe=new Map;let hs=1,nr=null;globalThis.Worker!=null&&(nr=Du(),nr.onmessage=()=>{hs+=1;for(const[s,t]of Oe)if(hs%s===0)for(const e of t)e()});const Do=(s,t)=>{const e=Math.round(t/16.6),r=Oe.get(e)??new Set;return r.add(s),Oe.set(e,r),Oe.size===1&&r.size===1&&nr?.postMessage({event:"start"}),()=>{r.delete(s),r.size===0&&Oe.delete(e),Oe.size===0&&(hs=0,nr?.postMessage({event:"stop"}))}};function Ou(s){H.info("recodemux opts:",s);const t=yt.createFile(),e=new os,r=(u,f)=>{const g=u.add("udta").add("meta");g.data=Iu(f),g.size=g.data.byteLength};let n=!1;const o=()=>{t.moov==null||n||(n=!0,s.metaDataTags!=null&&r(t.moov,s.metaDataTags),s.duration!=null&&(t.moov.mvhd.duration=s.duration))};e.once("VideoReady",o),e.once("AudioReady",o);const l=s.video!=null?Gu(s.video,t,e):null,h=s.audio!=null?zu(s.audio,t,e):null;return s.video==null&&e.emit("VideoReady"),s.audio==null&&e.emit("AudioReady"),{encodeVideo:(u,f)=>{l?.encode(u,f),u.close()},encodeAudio:u=>{if(h!=null)try{h.encode(u),u.close()}catch(f){const m=`encode audio chunk error: ${f.message}, state: ${JSON.stringify({qSize:h.encodeQueueSize,state:h.state})}`;throw H.error(m),Error(m)}},getEncodeQueueSize:()=>l?.encodeQueueSize??h?.encodeQueueSize??0,flush:async()=>{await Promise.all([l?.flush(),h?.state==="configured"?h.flush():null])},close:()=>{e.destroy(),l?.close(),h?.state==="configured"&&h.close()},mp4file:t}}function Gu(s,t,e){const r={timescale:1e6,width:s.width,height:s.height,brands:["isom","iso2","avc1","mp42","mp41"],avcDecoderConfigRecord:null,hevcDecoderConfigRecord:null,vpcDecoderConfigRecord:null,type:"avc1",name:"Track created with WebAV"};let n=-1,o=!1;e.once("AudioReady",()=>{o=!0});const l={encoder0:[],encoder1:[]},h=(p,_,b)=>{if(n===-1&&b!=null){let v=b.decoderConfig?.description;s.codec.startsWith("avc1")?Lu(v):s.codec.startsWith("vp09")&&b.decoderConfig&&(r.type="vp09",v=Wu(b.decoderConfig));const w=[["avc1","avcDecoderConfigRecord"],["hvc1","hevcDecoderConfigRecord"],["vp09","vpcDecoderConfigRecord"]].find(([S])=>s.codec.startsWith(S))?.[1];w!=null&&v!=null&&(r[w]=v),n=t.addTrack(r),e.emit("VideoReady"),H.info("VideoEncoder, video track ready, trackId:",n)}l[p].push(ls(_))};let u="encoder1",f=0;const m=Math.floor(1e3/s.expectFPS*1e3);function g(){if(!o)return;const p=u==="encoder1"?"encoder0":"encoder1",_=l[u],b=l[p];if(_.length===0&&b.length===0)return;const v=_[0];if(v!=null&&(!v.is_sync||v.cts-f<m)){const S=y(_);S>f&&(f=S)}const w=b[0];if(w?.is_sync&&w.cts-f<m){u=p,g();return}if(v?.is_sync&&w?.is_sync)if(v.cts<=w.cts){const S=y(_);S>f&&(f=S)}else{u=p,g();return}}function y(p){let _=-1,b=0;for(;b<p.length;b++){const v=p[b];if(b>0&&v.is_sync)break;t.addSample(n,v.data,v),_=v.cts+v.duration}return p.splice(0,b),_}const x=Do(g,15),a=Oo(s,(p,_)=>h("encoder0",p,_)),c=Oo(s,(p,_)=>h("encoder1",p,_));let d=0;return{get encodeQueueSize(){return a.encodeQueueSize+c.encodeQueueSize},encode:(p,_)=>{try{_.keyFrame&&(d+=1),(d%2===0?a:c).encode(p,_)}catch(b){const v=`encode video frame error: ${b.message}, state: ${JSON.stringify({ts:p.timestamp,keyFrame:_.keyFrame,duration:p.duration,gopId:d})}`;throw H.error(v),Error(v)}},flush:async()=>{await Promise.all([a.state==="configured"?await a.flush():null,c.state==="configured"?await c.flush():null]),x(),g()},close:()=>{a.state==="configured"&&a.close(),c.state==="configured"&&c.close()}}}function Lu(s){const t=new Uint8Array(s);t[2].toString(2).slice(-2).includes("1")&&(t[2]=0)}function Oo(s,t){const e={codec:s.codec,framerate:s.expectFPS,hardwareAcceleration:s.__unsafe_hardwareAcceleration__,bitrate:s.bitrate,width:s.width,height:s.height,alpha:"discard",avc:{format:"avc"}},r=new VideoEncoder({error:n=>{const o=`VideoEncoder error: ${n.message}, config: ${JSON.stringify(e)}, state: ${JSON.stringify({qSize:r.encodeQueueSize,state:r.state})}`;throw H.error(o),Error(o)},output:t});return r.configure(e),r}function zu(s,t,e){const r={timescale:1e6,samplerate:s.sampleRate,channel_count:s.channelCount,hdlr:"soun",type:s.codec==="aac"?"mp4a":"Opus",name:"Track created with WebAV"};let n=-1,o=[],l=!1;e.once("VideoReady",()=>{l=!0,o.forEach(f=>{const m=ls(f);t.addSample(n,m.data,m)}),o=[]});const h={codec:s.codec==="aac"?"mp4a.40.2":"opus",sampleRate:s.sampleRate,numberOfChannels:s.channelCount,bitrate:128e3},u=new AudioEncoder({error:f=>{const m=`AudioEncoder error: ${f.message}, config: ${JSON.stringify(h)}, state: ${JSON.stringify({qSize:u.encodeQueueSize,state:u.state})}`;throw H.error(m),Error(m)},output:(f,m)=>{if(n===-1){const g=m?.decoderConfig?.description;n=t.addTrack({...r,description:g==null?void 0:s.codec==="aac"?Nu(g):Hu(g)}),e.emit("AudioReady"),H.info("AudioEncoder, audio track ready, trackId:",n)}if(l){const g=ls(f);t.addSample(n,g.data,g)}else o.push(f)}});return u.configure(h),u}function Nu(s){const t=s.byteLength,e=new Uint8Array([0,0,0,0,3,23+t,0,2,0,4,18+t,64,21,0,0,0,0,0,0,0,0,0,0,0,5,t,...new Uint8Array(s instanceof ArrayBuffer?s:s.buffer),6,1,2]),r=new yt.BoxParser.esdsBox(e.byteLength);return r.hdr_size=0,r.parse(new yt.DataStream(e,0,yt.DataStream.BIG_ENDIAN)),r}function Hu(s){const t=new DataView(s instanceof ArrayBuffer?s:s.buffer),e=t.getUint8(9),r=t.getUint16(10,!0),n=t.getUint32(12,!0),o=t.getInt16(16,!0),l=t.getUint8(18),h=new Uint8Array([0,e,r>>8&255,r&255,n>>24&255,n>>16&255,n>>8&255,n&255,o>>8&255,o&255,l]);return{type:"dOps",size:h.byteLength+8,hdr_size:8,start:0,data:h,write:function(f){f.writeUint32(this.size),f.writeString("dOps"),f.writeUint8Array(this.data)},parse:function(){}}}function ls(s){const t=new ArrayBuffer(s.byteLength);s.copyTo(t);const e=s.timestamp;return{duration:s.duration??0,dts:e,cts:e,is_sync:s.type==="key",data:t}}function Wu(s){const e=s.codec.split("."),r=parseInt(e[1]||"0",10),n=parseInt(e[2]||"40",10),o=parseInt(e[3]||"08",10),l={bt709:1,bt601:5,bt2020:9},h={bt709:1,srgb:13,pq:16,hlg:18},u={bt709:1,bt601:5,bt2020:9},f=l[s.colorSpace?.primaries||"bt709"]||1,m=h[s.colorSpace?.transfer||"bt709"]||1,g=u[s.colorSpace?.matrix||"bt709"]||1,y=s.colorSpace?.fullRange?1:0,x=1,a=0,c=new ArrayBuffer(12),d=new DataView(c);let p=0;return d.setUint32(p,1<<24),p+=4,d.setUint8(p++,r),d.setUint8(p++,n),d.setUint8(p++,o<<4|x<<1|y),d.setUint8(p++,f),d.setUint8(p++,m),d.setUint8(p++,g),d.setUint16(p,a),c}function Go(s,t){let e=!1;async function r(){const n=s.getReader();for(;!e;){const{value:o,done:l}=await n.read();if(l){t.onDone();return}await t.onChunk(o)}n.releaseLock(),await s.cancel()}return r().catch(console.error),()=>{e=!0}}function Lo(s,t,e){let r=0,n=0;const o=s.boxes;let l=!1;const h=()=>{if(!l)if(o.find(a=>a.type==="moof")!=null)l=!0;else return null;if(n>=o.length)return null;const y=new yt.DataStream;y.endianness=yt.DataStream.BIG_ENDIAN;let x=n;try{for(;x<o.length;)o[x].write(y),delete o[x],x+=1}catch(a){const c=o[x];throw a instanceof Error&&c!=null?Error(`${a.message} | deltaBuf( boxType: ${c.type}, boxSize: ${c.size}, boxDataLen: ${c.data?.length??-1})`):a}return Vu(s),n=o.length,new Uint8Array(y.buffer)};let u=!1,f=!1,m=null;return{stream:new ReadableStream({start(y){r=self.setInterval(()=>{const x=h();x!=null&&!f&&y.enqueue(x)},t),m=x=>{if(clearInterval(r),s.flush(),x!=null){y.error(x);return}const a=h();a!=null&&!f&&y.enqueue(a),f||y.close()},u&&m()},cancel(){f=!0,clearInterval(r),e?.()}}),stop:y=>{u||(u=!0,m?.(y))}}}function Vu(s){if(s.moov!=null){for(var t=0;t<s.moov.traks.length;t++)s.moov.traks[t].samples=[];s.mdats=[],s.moofs=[]}}class Yu{constructor(t,e,r){this.length_=t,this.scaleFactor_=(t-1)/e,this.interpolate=this.cubic,r.method==="point"?this.interpolate=this.point:r.method==="linear"?this.interpolate=this.linear:r.method==="sinc"&&(this.interpolate=this.sinc),this.tangentFactor_=1-Math.max(0,Math.min(1,r.tension||0)),this.sincFilterSize_=r.sincFilterSize||1,this.kernel_=$u(r.sincWindow||Xu)}point(t,e){return this.getClippedInput_(Math.round(this.scaleFactor_*t),e)}linear(t,e){t=this.scaleFactor_*t;let r=Math.floor(t);return t-=r,(1-t)*this.getClippedInput_(r,e)+t*this.getClippedInput_(r+1,e)}cubic(t,e){t=this.scaleFactor_*t;let r=Math.floor(t),n=[this.getTangent_(r,e),this.getTangent_(r+1,e)],o=[this.getClippedInput_(r,e),this.getClippedInput_(r+1,e)];t-=r;let l=t*t,h=t*l;return(2*h-3*l+1)*o[0]+(h-2*l+t)*n[0]+(-2*h+3*l)*o[1]+(h-l)*n[1]}sinc(t,e){t=this.scaleFactor_*t;let r=Math.floor(t),n=r-this.sincFilterSize_+1,o=r+this.sincFilterSize_,l=0;for(let h=n;h<=o;h++)l+=this.kernel_(t-h)*this.getClippedInput_(h,e);return l}getTangent_(t,e){return this.tangentFactor_*(this.getClippedInput_(t+1,e)-this.getClippedInput_(t-1,e))/2}getClippedInput_(t,e){return 0<=t&&t<this.length_?e[t]:0}}function Xu(s){return Math.exp(-s/2*s/2)}function $u(s){return function(t){return Ku(t)*s(t)}}function Ku(s){return s===0?1:Math.sin(Math.PI*s)/(Math.PI*s)}class ju{constructor(t,e,r){let n=2*Math.PI*r/e,o=0;this.filters=[];for(let l=0;l<=t;l++)l-t/2===0?this.filters[l]=n:(this.filters[l]=Math.sin(n*(l-t/2))/(l-t/2),this.filters[l]*=.54-.46*Math.cos(2*Math.PI*l/t)),o=o+this.filters[l];for(let l=0;l<=t;l++)this.filters[l]/=o;this.z=this.initZ_()}filter(t){this.z.buf[this.z.pointer]=t;let e=0;for(let r=0,n=this.z.buf.length;r<n;r++)e+=this.filters[r]*this.z.buf[(this.z.pointer+r)%this.z.buf.length];return this.z.pointer=(this.z.pointer+1)%this.z.buf.length,e}reset(){this.z=this.initZ_()}initZ_(){let t=[];for(let e=0;e<this.filters.length-1;e++)t.push(0);return{buf:t,pointer:0}}}class qu{constructor(t,e,r){let n=[];for(let o=0;o<t;o++)n.push(this.getCoeffs_({Fs:e,Fc:r,Q:.5/Math.sin(Math.PI/(t*2)*(o+.5))}));this.stages=[];for(let o=0;o<n.length;o++)this.stages[o]={b0:n[o].b[0],b1:n[o].b[1],b2:n[o].b[2],a1:n[o].a[0],a2:n[o].a[1],k:n[o].k,z:[0,0]}}filter(t){let e=t;for(let r=0,n=this.stages.length;r<n;r++)e=this.runStage_(r,e);return e}getCoeffs_(t){let e={};e.z=[0,0],e.a=[],e.b=[];let r=this.preCalc_(t,e);return e.k=1,e.b.push((1-r.cw)/(2*r.a0)),e.b.push(2*e.b[0]),e.b.push(e.b[0]),e}preCalc_(t,e){let r={},n=2*Math.PI*t.Fc/t.Fs;return r.alpha=Math.sin(n)/(2*t.Q),r.cw=Math.cos(n),r.a0=1+r.alpha,e.a0=r.a0,e.a.push(-2*r.cw/r.a0),e.k=1,e.a.push((1-r.alpha)/r.a0),r}runStage_(t,e){let r=e*this.stages[t].k-this.stages[t].a1*this.stages[t].z[0]-this.stages[t].a2*this.stages[t].z[1],n=this.stages[t].b0*r+this.stages[t].b1*this.stages[t].z[0]+this.stages[t].b2*this.stages[t].z[1];return this.stages[t].z[1]=this.stages[t].z[0],this.stages[t].z[0]=r,n}reset(){for(let t=0;t<this.stages.length;t++)this.stages[t].z=[0,0]}}const Zu={point:!1,linear:!1,cubic:!0,sinc:!0},zo={IIR:16,FIR:71},Qu={IIR:qu,FIR:ju};function Ju(s,t,e,r={}){let n=(e-t)/t+1,o=new Float64Array(s.length*n);r.method=r.method||"cubic";let l=new Yu(s.length,o.length,{method:r.method,tension:r.tension||0,sincFilterSize:r.sincFilterSize||6,sincWindow:r.sincWindow||void 0});if(r.LPF===void 0&&(r.LPF=Zu[r.method]),r.LPF){r.LPFType=r.LPFType||"IIR";const h=Qu[r.LPFType];if(e>t){let u=new h(r.LPFOrder||zo[r.LPFType],e,t/2);tf(s,o,l,u)}else{let u=new h(r.LPFOrder||zo[r.LPFType],t,e/2);ef(s,o,l,u)}}else No(s,o,l);return o}function No(s,t,e){for(let r=0,n=t.length;r<n;r++)t[r]=e.interpolate(r,s)}function tf(s,t,e,r){for(let n=0,o=t.length;n<o;n++)t[n]=r.filter(e.interpolate(n,s));r.reset();for(let n=t.length-1;n>=0;n--)t[n]=r.filter(t[n])}function ef(s,t,e,r){for(let n=0,o=s.length;n<o;n++)s[n]=r.filter(s[n]);r.reset();for(let n=s.length-1;n>=0;n--)s[n]=r.filter(s[n]);No(s,t,e)}function rf(s){const t=new Float32Array(s.map(r=>r.length).reduce((r,n)=>r+n));let e=0;for(const r of s)t.set(r,e),e+=r.length;return t}function Ho(s){const t=[];for(let e=0;e<s.length;e+=1)for(let r=0;r<s[e].length;r+=1)t[r]==null&&(t[r]=[]),t[r].push(s[e][r]);return t.map(rf)}function Wo(s){if(s.format==="f32-planar"){const t=[];for(let e=0;e<s.numberOfChannels;e+=1){const r=s.allocationSize({planeIndex:e}),n=new ArrayBuffer(r);s.copyTo(n,{planeIndex:e}),t.push(new Float32Array(n))}return t}else if(s.format==="f32"){const t=new ArrayBuffer(s.allocationSize({planeIndex:0}));return s.copyTo(t,{planeIndex:0}),nf(new Float32Array(t),s.numberOfChannels)}else if(s.format==="s16"){const t=new ArrayBuffer(s.allocationSize({planeIndex:0}));return s.copyTo(t,{planeIndex:0}),sf(new Int16Array(t),s.numberOfChannels)}throw Error("Unsupported audio data format")}function sf(s,t){const e=s.length/t,r=Array.from({length:t},()=>new Float32Array(e));for(let n=0;n<e;n++)for(let o=0;o<t;o++){const l=s[n*t+o];r[o][n]=l/32768}return r}function nf(s,t){const e=s.length/t,r=Array.from({length:t},()=>new Float32Array(e));for(let n=0;n<e;n++)for(let o=0;o<t;o++)r[o][n]=s[n*t+o];return r}function cs(s){return Array(s.numberOfChannels).fill(0).map((t,e)=>s.getChannelData(e))}function Vo(s){const t=Math.max(...s.map(r=>r[0]?.length??0)),e=new Float32Array(t*2);for(let r=0;r<t;r++){let n=0,o=0;for(let l=0;l<s.length;l++){const h=s[l][0]?.[r]??0,u=s[l][1]?.[r]??h;n+=h,o+=u}e[r]=n,e[r+t]=o}return e}async function of(s,t,e){const r=s.length,n=Array(e.chanCount).fill(0).map(()=>new Float32Array(0));if(r===0)return n;const o=Math.max(...s.map(f=>f.length));if(o===0)return n;if(globalThis.OfflineAudioContext==null)return s.map(f=>new Float32Array(Ju(f,t,e.rate,{method:"sinc",LPF:!1})));const l=new globalThis.OfflineAudioContext(e.chanCount,o*e.rate/t,e.rate),h=l.createBufferSource(),u=l.createBuffer(r,o,t);return s.forEach((f,m)=>u.copyToChannel(new Float32Array(f),m)),h.buffer=u,h.connect(l.destination),h.start(),cs(await l.startRendering())}function ds(s,t,e){const r=e-t,n=new Float32Array(r);let o=0;for(;o<r;)n[o]=s[(t+o)%s.length],o+=1;return n}function Yo(s,t){const e=Math.floor(s.length/t),r=new Float32Array(e);for(let n=0;n<e;n++){const o=n*t,l=Math.floor(o),h=o-l;l+1<s.length?r[n]=s[l]*(1-h)+s[l+1]*h:r[n]=s[l]}return r}const af=[{codec:"mp4a.40.2",codecType:"aac",sampleRate:48e3,channelCount:2},{codec:"opus",codecType:"opus",sampleRate:48e3,channelCount:2}];let Ge=null;function hf(){if(typeof navigator>"u")return"unknown";const s=navigator.userAgent.toLowerCase();return s.includes("linux")?"linux":s.includes("mac")?"macos":s.includes("win")?"windows":"unknown"}async function lf(s){if(typeof AudioEncoder>"u")return!1;try{return(await AudioEncoder.isConfigSupported({codec:s.codec,sampleRate:s.sampleRate,numberOfChannels:s.channelCount})).supported??!1}catch{return!1}}async function cf(){if(Ge!==null)return Ge;const s=hf();for(const e of af)if(await lf(e))return Ge={...e},console.log(`[AudioCodec] Selected ${e.codec} for ${s}`),Ge;const t={codec:"opus",codecType:"opus",sampleRate:48e3,channelCount:2};return console.warn("[AudioCodec] No supported codec found, falling back to Opus"),Ge=t,t}function or(){return Ge}const df=`#version 300 es
|
|
3
3
|
layout (location = 0) in vec4 a_position;
|
|
4
4
|
layout (location = 1) in vec2 a_texCoord;
|
|
5
5
|
out vec2 v_texCoord;
|
|
@@ -7,7 +7,7 @@
|
|
|
7
7
|
gl_Position = a_position;
|
|
8
8
|
v_texCoord = a_texCoord;
|
|
9
9
|
}
|
|
10
|
-
`,
|
|
10
|
+
`,uf=`#version 300 es
|
|
11
11
|
precision mediump float;
|
|
12
12
|
out vec4 FragColor;
|
|
13
13
|
in vec2 v_texCoord;
|
|
@@ -47,13 +47,13 @@ void main() {
|
|
|
47
47
|
rgba.rgb = mix(vec3(desat, desat, desat), rgba.rgb, spillVal);
|
|
48
48
|
FragColor = rgba;
|
|
49
49
|
}
|
|
50
|
-
`,
|
|
50
|
+
`,ff=[-1,1,-1,-1,1,-1,1,-1,1,1,-1,1],pf=[0,1,0,0,1,0,1,0,1,1,0,1];function mf(s,t,e){const r=Xo(s,s.VERTEX_SHADER,t),n=Xo(s,s.FRAGMENT_SHADER,e),o=s.createProgram();if(s.attachShader(o,r),s.attachShader(o,n),s.linkProgram(o),!s.getProgramParameter(o,s.LINK_STATUS))throw Error(s.getProgramInfoLog(o)??"Unable to initialize the shader program");return o}function Xo(s,t,e){const r=s.createShader(t);if(s.shaderSource(r,e),s.compileShader(r),!s.getShaderParameter(r,s.COMPILE_STATUS)){const n=s.getShaderInfoLog(r);throw s.deleteShader(r),Error(n??"An error occurred compiling the shaders")}return r}function gf(s,t,e){s.bindTexture(s.TEXTURE_2D,e),s.texImage2D(s.TEXTURE_2D,0,s.RGBA,s.RGBA,s.UNSIGNED_BYTE,t),s.drawArrays(s.TRIANGLES,0,6)}function _f(s){const t=s.createTexture();if(t==null)throw Error("Create WebGL texture error");s.bindTexture(s.TEXTURE_2D,t);const e=0,r=s.RGBA,n=1,o=1,l=0,h=s.RGBA,u=s.UNSIGNED_BYTE,f=new Uint8Array([0,0,255,255]);return s.texImage2D(s.TEXTURE_2D,e,r,n,o,l,h,u,f),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_MAG_FILTER,s.LINEAR),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_MIN_FILTER,s.LINEAR),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_WRAP_S,s.CLAMP_TO_EDGE),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_WRAP_T,s.CLAMP_TO_EDGE),t}function yf(s){const t="document"in globalThis?globalThis.document.createElement("canvas"):new OffscreenCanvas(s.width,s.height);t.width=s.width,t.height=s.height;const e=t.getContext("webgl2",{premultipliedAlpha:!1,alpha:!0});if(e==null)throw Error("Cant create gl context");const r=mf(e,df,uf);e.useProgram(r),e.uniform3fv(e.getUniformLocation(r,"keyColor"),s.keyColor.map(u=>u/255)),e.uniform1f(e.getUniformLocation(r,"similarity"),s.similarity),e.uniform1f(e.getUniformLocation(r,"smoothness"),s.smoothness),e.uniform1f(e.getUniformLocation(r,"spill"),s.spill);const n=e.createBuffer();e.bindBuffer(e.ARRAY_BUFFER,n),e.bufferData(e.ARRAY_BUFFER,new Float32Array(ff),e.STATIC_DRAW);const o=e.getAttribLocation(r,"a_position");e.vertexAttribPointer(o,2,e.FLOAT,!1,Float32Array.BYTES_PER_ELEMENT*2,0),e.enableVertexAttribArray(o);const l=e.createBuffer();e.bindBuffer(e.ARRAY_BUFFER,l),e.bufferData(e.ARRAY_BUFFER,new Float32Array(pf),e.STATIC_DRAW);const h=e.getAttribLocation(r,"a_texCoord");return e.vertexAttribPointer(h,2,e.FLOAT,!1,Float32Array.BYTES_PER_ELEMENT*2,0),e.enableVertexAttribArray(h),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,1),{canvas:t,gl:e}}function xf(s){return s instanceof VideoFrame?{width:s.codedWidth,height:s.codedHeight}:{width:s.width,height:s.height}}function bf(s){const e=new OffscreenCanvas(1,1).getContext("2d");e.drawImage(s,0,0);const{data:[r,n,o]}=e.getImageData(0,0,1,1);return[r,n,o]}const vf=s=>{let t=null,e=null,r=s.keyColor,n=null;return async o=>{if((t==null||e==null||n==null)&&(r==null&&(r=bf(o)),{canvas:t,gl:e}=yf({...xf(o),keyColor:r,...s}),n=_f(e)),gf(e,o,n),globalThis.VideoFrame!=null&&o instanceof globalThis.VideoFrame){const l=new VideoFrame(t,{alpha:"keep",timestamp:o.timestamp,duration:o.duration??void 0});return o.close(),l}return createImageBitmap(t,{imageOrientation:o instanceof ImageBitmap?"flipY":"none"})}};function us(s){return new Promise(t=>{const e=Do(()=>{e(),t()},s)})}function wf(s){return document.createElement(s)}function Sf(s){var t="",e=new Uint8Array(s),r=e.byteLength;for(let n=0;n<r;n++)t+=String.fromCharCode(e[n]);return window.btoa(t)}async function Tf(s,t,e={}){const r=wf("pre");r.style.cssText=`margin: 0; ${t}; position: fixed;`,r.textContent=s,document.body.appendChild(r),e.onCreated?.(r);const{width:n,height:o}=r.getBoundingClientRect();r.remove();const l=new Image;l.width=n,l.height=o;const h=e.font==null?"":`
|
|
51
51
|
@font-face {
|
|
52
52
|
font-family: '${e.font.name}';
|
|
53
|
-
src: url('data:font/woff2;base64,${
|
|
53
|
+
src: url('data:font/woff2;base64,${Sf(await(await fetch(e.font.url)).arrayBuffer())}') format('woff2');
|
|
54
54
|
}
|
|
55
|
-
`,
|
|
56
|
-
<svg xmlns="http://www.w3.org/2000/svg" width="${n}" height="${
|
|
55
|
+
`,u=`
|
|
56
|
+
<svg xmlns="http://www.w3.org/2000/svg" width="${n}" height="${o}">
|
|
57
57
|
<style>
|
|
58
58
|
${h}
|
|
59
59
|
</style>
|
|
@@ -61,10 +61,10 @@ void main() {
|
|
|
61
61
|
<div xmlns="http://www.w3.org/1999/xhtml">${r.outerHTML}</div>
|
|
62
62
|
</foreignObject>
|
|
63
63
|
</svg>
|
|
64
|
-
`.replace(/\t/g,"").replace(/#/g,"%23");return l.src=`data:image/svg+xml;charset=utf-8,${d}`,await new Promise(f=>{l.onload=f}),l}async function gf(s,t,e={}){const r=await mf(s,t,e),n=new OffscreenCanvas(r.width,r.height);return n.getContext("2d")?.drawImage(r,0,0,r.width,r.height),await createImageBitmap(n)}async function _f(s,t){const e={type:t,data:s},r=new ImageDecoder(e);await Promise.all([r.completed,r.tracks.ready]);const n=r.tracks.selectedTrack?.frameCount??1,a=[];for(let l=0;l<n;l+=1)a.push((await r.decode({frameIndex:l})).image);return a}class yf{display={from:0,to:0};duration=0;playbackRate=1;evtTool=new ss;on=this.evtTool.on;_left=0;get left(){return this._left}set left(t){const e=this._left!==t;this._left=t,e&&this.evtTool.emit("propsChange",{left:t})}_top=0;get top(){return this._top}set top(t){const e=this._top!==t;this._top=t,e&&this.evtTool.emit("propsChange",{top:t})}_width=0;get width(){return this._width}set width(t){const e=this._width!==t;this._width=t,e&&this.evtTool.emit("propsChange",{width:t})}_height=0;get height(){return this._height}set height(t){const e=this._height!==t;this._height=t,e&&this.evtTool.emit("propsChange",{height:t})}_angle=0;get angle(){return this._angle}set angle(t){const e=this._angle!==t;this._angle=t,e&&this.evtTool.emit("propsChange",{angle:t})}get center(){return{x:this.left+this.width/2,y:this.top+this.height/2}}_zIndex=0;get zIndex(){return this._zIndex}set zIndex(t){const e=this._zIndex!==t;this._zIndex=t,e&&this.evtTool.emit("propsChange",{zIndex:t})}opacity=1;flip=null;animatKeyFrame=null;animatOpts=null;ready=Promise.resolve();constructor(){}_render(t){const{center:e,angle:r}=this;t.setTransform(this.flip==="horizontal"?-1:1,0,0,this.flip==="vertical"?-1:1,e.x,e.y),t.rotate((this.flip==null?1:-1)*r),t.globalAlpha=this.opacity}setAnimation(t,e){this.animatKeyFrame=Object.entries(t).map(([r,n])=>{const a={from:0,to:100}[r]??Number(r.slice(0,-1));if(isNaN(a)||a>100||a<0)throw Error("keyFrame must between 0~100");return[a/100,n]}),this.animatOpts=Object.assign({},this.animatOpts,{duration:e.duration,delay:e.delay??0,iterCount:e.iterCount??1/0})}animate(t){if(this.animatKeyFrame==null||this.animatOpts==null||t<this.animatOpts.delay)return;const e=xf(t,this.animatKeyFrame,this.animatOpts);for(const r in e)switch(r){case"opacity":this.opacity=e[r];break;case"x":this.left=e[r];break;case"y":this.top=e[r];break;case"w":this.width=e[r];break;case"h":this.height=e[r];break;case"angle":this.angle=e[r];break}}copyStateTo(t){t.animatKeyFrame=this.animatKeyFrame,t.animatOpts=this.animatOpts,t.zIndex=this.zIndex,t.opacity=this.opacity,t.flip=this.flip,t.left=this.left,t.top=this.top,t.width=this.width,t.height=this.height,t.angle=this.angle,t.display={...this.display},t.duration=this.duration,t.playbackRate=this.playbackRate,"src"in this&&"src"in t&&(t.src=this.src)}destroy(){this.evtTool.destroy()}}function xf(s,t,e){const r=s-e.delay,n=r%e.duration,a=r/e.duration>=e.iterCount||r===e.duration?1:n/e.duration,l=t.findIndex(x=>x[0]>=a);if(l===-1)return{};const h=t[l-1],d=t[l],f=d[1];if(h==null)return f;const m=h[1],g={},y=(a-h[0])/(d[0]-h[0]);for(const x in f){if(!f.hasOwnProperty(x)||typeof x!="string")continue;const o=x;m[o]!=null&&(g[o]=(f[o]-m[o])*y+m[o])}return g}class li extends yf{lastVf=null;destroyed=!1;src="";constructor(){super()}async getFrame(t){const e=t*this.playbackRate,{video:r,audio:n,state:a}=await this.tick(e);let l=n??[];n!=null&&this.playbackRate!==1&&(l=n.map(d=>Na(d,this.playbackRate)));let h=null;return r!=null?(this.lastVf?.close(),r instanceof VideoFrame?(h=await createImageBitmap(r),r.close()):h=r,this.lastVf=h):this.lastVf!=null&&(h=this.lastVf),{video:h,audio:l,done:a==="done"}}async offscreenRender(t,e){const r=e*this.playbackRate;this.animate(r),super._render(t);const{width:n,height:a}=this,{video:l,audio:h,state:d}=await this.tick(r);let f=h??[];if(h!=null&&this.playbackRate!==1&&(f=h.map(g=>Na(g,this.playbackRate))),d==="done")return{audio:f,done:!0};let m=l??this.lastVf;return m!=null&&t.drawImage(m,-n/2,-a/2,n,a),l!=null&&(this.lastVf?.close(),l instanceof ImageBitmap&&(this.lastVf=l)),{audio:f,done:!1}}set(t,e=30){if(t.display&&(t.display.from!==void 0&&(this.display.from=t.display.from<1e6?t.display.from/e*1e6:t.display.from),t.display.to!==void 0&&(this.display.to=t.display.to<1e6?t.display.to/e*1e6:t.display.to)),t.x!==void 0&&(this.left=t.x),t.y!==void 0&&(this.top=t.y),t.width!==void 0&&(this.width=t.width),t.height!==void 0&&(this.height=t.height),t.duration!==void 0){const r=t.duration<1e6?t.duration/e*1e6:t.duration;this.duration=r,this.display.from!==void 0&&(this.display.to=this.display.from+r)}return this}toJSON(t=!1){const e=this.animatKeyFrame&&this.animatOpts?{keyFrames:this.animatKeyFrame.reduce((r,[n,a])=>{const l=n===0?"from":n===1?"to":`${Math.round(n*100)}%`;return r[l]=a,r},{}),opts:this.animatOpts}:void 0;return{type:this.constructor.name,src:this.src,display:{from:this.display.from,to:this.display.to},playbackRate:this.playbackRate,duration:this.duration,left:this.left,top:this.top,width:this.width,height:this.height,angle:this.angle,zIndex:this.zIndex,opacity:this.opacity,flip:this.flip,...e&&{animation:e},...t&&{main:!0}}}destroy(){this.destroyed||(this.destroyed=!0,H.info("BaseClip destroy"),super.destroy(),this.lastVf?.close(),this.lastVf=null)}}const tt={sampleRate:48e3,channelCount:2,codec:"mp4a.40.2"};class pt extends li{static ctx=null;ready;_meta={duration:0,width:0,height:0};get meta(){return{...this._meta,sampleRate:tt.sampleRate,chanCount:2}}chan0Buf=new Float32Array;chan1Buf=new Float32Array;getPCMData(){return[this.chan0Buf,this.chan1Buf]}opts;loop=!1;volume=1;static async fromUrl(t,e={}){const r=await fetch(t);if(!r.ok)throw new Error(`Failed to fetch audio from ${t}: ${r.status} ${r.statusText}`);const n=new pt(r.body,e,t);return await n.ready,n}static async fromObject(t){if(t.type!=="Audio")throw new Error(`Expected Audio, got ${t.type}`);if(!t.src||t.src.trim()==="")throw new Error("AudioClip requires a valid source URL");const e={};t.loop!==void 0&&(e.loop=t.loop),t.volume!==void 0&&(e.volume=t.volume);const r=await pt.fromUrl(t.src,e);return r.left=t.left,r.top=t.top,r.width=t.width,r.height=t.height,r.angle=t.angle,r.display.from=t.display.from,r.display.to=t.display.to,r.duration=t.duration,r.playbackRate=t.playbackRate,r.zIndex=t.zIndex,r.opacity=t.opacity,r.flip=t.flip,t.animation&&r.setAnimation(t.animation.keyFrames,t.animation.opts),r}constructor(t,e={},r){super(),this.src=r!==void 0?r:"",this.opts={loop:!1,volume:1,...e},this.loop=this.opts.loop??!1,this.volume=this.opts.volume??1,this.ready=this.init(t).then(n=>{const a={width:0,height:0,duration:e.loop?1/0:this._meta.duration};return this.width=this.width===0?a.width:this.width,this.height=this.height===0?a.height:this.height,this.duration=this.duration===0?a.duration:this.duration,this.display.to=this.display.from+this.duration,a})}async init(t){pt.ctx==null&&(pt.ctx=new AudioContext({sampleRate:tt.sampleRate}));const e=performance.now(),r=t instanceof ReadableStream?await vf(t,pt.ctx):t;H.info("Audio clip decoded complete:",performance.now()-e);const n=this.opts.volume;if(n!==1)for(const a of r)for(let l=0;l<a.length;l+=1)a[l]*=n;this._meta.duration=r[0].length/tt.sampleRate*1e6,this.chan0Buf=r[0],this.chan1Buf=r[1]??this.chan0Buf,H.info("Audio clip convert to AudioData, time:",performance.now()-e)}tickInterceptor=async(t,e)=>e;timestamp=0;frameOffset=0;async tick(t){if(!this.opts.loop&&t>=this._meta.duration)return await this.tickInterceptor(t,{audio:[],state:"done"});const e=t-this.timestamp;if(t<this.timestamp||e>3e6)return this.timestamp=t,this.frameOffset=Math.ceil(this.timestamp/1e6*tt.sampleRate),await this.tickInterceptor(t,{audio:[new Float32Array(0),new Float32Array(0)],state:"success"});this.timestamp=t;const r=Math.ceil(e/1e6*tt.sampleRate),n=this.frameOffset+r,a=this.opts.loop?[ls(this.chan0Buf,this.frameOffset,n),ls(this.chan1Buf,this.frameOffset,n)]:[this.chan0Buf.slice(this.frameOffset,n),this.chan1Buf.slice(this.frameOffset,n)];return this.frameOffset=n,await this.tickInterceptor(t,{audio:a,state:"success"})}async split(t){await this.ready;const e=Math.ceil(t/1e6*tt.sampleRate),r=new pt(this.getPCMData().map(a=>a.slice(0,e)),this.opts,this.src),n=new pt(this.getPCMData().map(a=>a.slice(e)),this.opts,this.src);return[r,n]}async clone(){await this.ready;const t=new pt(this.getPCMData(),this.opts,this.src);return await t.ready,this.copyStateTo(t),t}destroy(){this.chan0Buf=new Float32Array(0),this.chan1Buf=new Float32Array(0),H.info("---- audioclip destroy ----"),super.destroy()}toJSON(t=!1){return{...super.toJSON(t),type:"Audio",loop:this.loop,volume:this.volume}}static concatAudioClip=bf;async createPlaybackElement(){if(await this.ready,!this.src||this.src.trim()==="")throw new Error("AudioClip requires a source URL for playback");const t=this.src.startsWith("blob:")?this.src:void 0,e=document.createElement("audio");return e.crossOrigin="anonymous",e.autoplay=!1,e.preload="auto",e.loop=this.opts.loop||!1,e.src=this.src,await new Promise((r,n)=>{const a=()=>{e.removeEventListener("loadeddata",a),e.removeEventListener("error",l),e.pause(),e.currentTime=0,r()},l=()=>{e.removeEventListener("loadeddata",a),e.removeEventListener("error",l),n(new Error("Failed to load audio"))};e.addEventListener("loadeddata",a,{once:!0}),e.addEventListener("error",l,{once:!0}),e.load()}),{element:e,objectUrl:t}}async play(t,e){const r=t;if(Math.abs(r.currentTime-e)>.1&&(r.currentTime=e),r.paused)try{await r.play()}catch{try{await r.play()}catch(a){console.warn("Failed to play audio:",a)}}}pause(t){t.pause()}async seek(t,e){const r=t;return r.pause(),r.currentTime=e,new Promise(n=>{if(Math.abs(r.currentTime-e)<.01){n();return}const a=()=>{r.removeEventListener("seeked",a),n()};r.addEventListener("seeked",a,{once:!0}),setTimeout(()=>{r.removeEventListener("seeked",a),n()},500)})}syncPlayback(t,e,r){const n=t,a=this.meta.duration/1e6,l=r>=0&&r<a;e&&l?n.paused&&this.play(n,r).catch(console.warn):(n.paused||n.pause(),l&&Math.abs(n.currentTime-r)>.1&&(n.currentTime=r))}cleanupPlayback(t,e){const r=t;r.pause(),r.removeAttribute("src"),r.load(),e&&e.startsWith("blob:")&&URL.revokeObjectURL(e)}}async function bf(s,t){const e=[];for(const r of s)await r.ready,e.push(r.getPCMData());return new pt(Oa(e),t)}async function vf(s,t){const e=await new Response(s).arrayBuffer();return hs(await t.decodeAudioData(e))}var C=(s=>(s.Application="application",s.WebGLPipes="webgl-pipes",s.WebGLPipesAdaptor="webgl-pipes-adaptor",s.WebGLSystem="webgl-system",s.WebGPUPipes="webgpu-pipes",s.WebGPUPipesAdaptor="webgpu-pipes-adaptor",s.WebGPUSystem="webgpu-system",s.CanvasSystem="canvas-system",s.CanvasPipesAdaptor="canvas-pipes-adaptor",s.CanvasPipes="canvas-pipes",s.Asset="asset",s.LoadParser="load-parser",s.ResolveParser="resolve-parser",s.CacheParser="cache-parser",s.DetectionParser="detection-parser",s.MaskEffect="mask-effect",s.BlendMode="blend-mode",s.TextureSource="texture-source",s.Environment="environment",s.ShapeBuilder="shape-builder",s.Batcher="batcher",s))(C||{});const us=s=>{if(typeof s=="function"||typeof s=="object"&&s.extension){if(!s.extension)throw new Error("Extension class must have an extension object");s={...typeof s.extension!="object"?{type:s.extension}:s.extension,ref:s}}if(typeof s=="object")s={...s};else throw new Error("Invalid extension type");return typeof s.type=="string"&&(s.type=[s.type]),s},nr=(s,t)=>us(s).priority??t,D={_addHandlers:{},_removeHandlers:{},_queue:{},remove(...s){return s.map(us).forEach(t=>{t.type.forEach(e=>this._removeHandlers[e]?.(t))}),this},add(...s){return s.map(us).forEach(t=>{t.type.forEach(e=>{const r=this._addHandlers,n=this._queue;r[e]?r[e]?.(t):(n[e]=n[e]||[],n[e]?.push(t))})}),this},handle(s,t,e){const r=this._addHandlers,n=this._removeHandlers;if(r[s]||n[s])throw new Error(`Extension type ${s} already has a handler`);r[s]=t,n[s]=e;const a=this._queue;return a[s]&&(a[s]?.forEach(l=>t(l)),delete a[s]),this},handleByMap(s,t){return this.handle(s,e=>{e.name&&(t[e.name]=e.ref)},e=>{e.name&&delete t[e.name]})},handleByNamedList(s,t,e=-1){return this.handle(s,r=>{t.findIndex(a=>a.name===r.name)>=0||(t.push({name:r.name,value:r.ref}),t.sort((a,l)=>nr(l.value,e)-nr(a.value,e)))},r=>{const n=t.findIndex(a=>a.name===r.name);n!==-1&&t.splice(n,1)})},handleByList(s,t,e=-1){return this.handle(s,r=>{t.includes(r.ref)||(t.push(r.ref),t.sort((n,a)=>nr(a,e)-nr(n,e)))},r=>{const n=t.indexOf(r.ref);n!==-1&&t.splice(n,1)})},mixin(s,...t){for(const e of t)Object.defineProperties(s.prototype,Object.getOwnPropertyDescriptors(e))}},wf={extension:{type:C.Environment,name:"browser",priority:-1},test:()=>!0,load:async()=>{await Promise.resolve().then(()=>Cv)}},Sf={extension:{type:C.Environment,name:"webworker",priority:0},test:()=>typeof self<"u"&&self.WorkerGlobalScope!==void 0,load:async()=>{await Promise.resolve().then(()=>Ev)}};class ct{constructor(t,e,r){this._x=e||0,this._y=r||0,this._observer=t}clone(t){return new ct(t??this._observer,this._x,this._y)}set(t=0,e=t){return(this._x!==t||this._y!==e)&&(this._x=t,this._y=e,this._observer._onUpdate(this)),this}copyFrom(t){return(this._x!==t.x||this._y!==t.y)&&(this._x=t.x,this._y=t.y,this._observer._onUpdate(this)),this}copyTo(t){return t.set(this._x,this._y),t}equals(t){return t.x===this._x&&t.y===this._y}toString(){return`[pixi.js/math:ObservablePoint x=${this._x} y=${this._y} scope=${this._observer}]`}get x(){return this._x}set x(t){this._x!==t&&(this._x=t,this._observer._onUpdate(this))}get y(){return this._y}set y(t){this._y!==t&&(this._y=t,this._observer._onUpdate(this))}}var ds={exports:{}},Wa;function Tf(){return Wa||(Wa=1,(function(s){var t=Object.prototype.hasOwnProperty,e="~";function r(){}Object.create&&(r.prototype=Object.create(null),new r().__proto__||(e=!1));function n(d,f,m){this.fn=d,this.context=f,this.once=m||!1}function a(d,f,m,g,y){if(typeof m!="function")throw new TypeError("The listener must be a function");var x=new n(m,g||d,y),o=e?e+f:f;return d._events[o]?d._events[o].fn?d._events[o]=[d._events[o],x]:d._events[o].push(x):(d._events[o]=x,d._eventsCount++),d}function l(d,f){--d._eventsCount===0?d._events=new r:delete d._events[f]}function h(){this._events=new r,this._eventsCount=0}h.prototype.eventNames=function(){var f=[],m,g;if(this._eventsCount===0)return f;for(g in m=this._events)t.call(m,g)&&f.push(e?g.slice(1):g);return Object.getOwnPropertySymbols?f.concat(Object.getOwnPropertySymbols(m)):f},h.prototype.listeners=function(f){var m=e?e+f:f,g=this._events[m];if(!g)return[];if(g.fn)return[g.fn];for(var y=0,x=g.length,o=new Array(x);y<x;y++)o[y]=g[y].fn;return o},h.prototype.listenerCount=function(f){var m=e?e+f:f,g=this._events[m];return g?g.fn?1:g.length:0},h.prototype.emit=function(f,m,g,y,x,o){var c=e?e+f:f;if(!this._events[c])return!1;var u=this._events[c],p=arguments.length,_,b;if(u.fn){switch(u.once&&this.removeListener(f,u.fn,void 0,!0),p){case 1:return u.fn.call(u.context),!0;case 2:return u.fn.call(u.context,m),!0;case 3:return u.fn.call(u.context,m,g),!0;case 4:return u.fn.call(u.context,m,g,y),!0;case 5:return u.fn.call(u.context,m,g,y,x),!0;case 6:return u.fn.call(u.context,m,g,y,x,o),!0}for(b=1,_=new Array(p-1);b<p;b++)_[b-1]=arguments[b];u.fn.apply(u.context,_)}else{var v=u.length,w;for(b=0;b<v;b++)switch(u[b].once&&this.removeListener(f,u[b].fn,void 0,!0),p){case 1:u[b].fn.call(u[b].context);break;case 2:u[b].fn.call(u[b].context,m);break;case 3:u[b].fn.call(u[b].context,m,g);break;case 4:u[b].fn.call(u[b].context,m,g,y);break;default:if(!_)for(w=1,_=new Array(p-1);w<p;w++)_[w-1]=arguments[w];u[b].fn.apply(u[b].context,_)}}return!0},h.prototype.on=function(f,m,g){return a(this,f,m,g,!1)},h.prototype.once=function(f,m,g){return a(this,f,m,g,!0)},h.prototype.removeListener=function(f,m,g,y){var x=e?e+f:f;if(!this._events[x])return this;if(!m)return l(this,x),this;var o=this._events[x];if(o.fn)o.fn===m&&(!y||o.once)&&(!g||o.context===g)&&l(this,x);else{for(var c=0,u=[],p=o.length;c<p;c++)(o[c].fn!==m||y&&!o[c].once||g&&o[c].context!==g)&&u.push(o[c]);u.length?this._events[x]=u.length===1?u[0]:u:l(this,x)}return this},h.prototype.removeAllListeners=function(f){var m;return f?(m=e?e+f:f,this._events[m]&&l(this,m)):(this._events=new r,this._eventsCount=0),this},h.prototype.off=h.prototype.removeListener,h.prototype.addListener=h.prototype.on,h.prefixed=e,h.EventEmitter=h,s.exports=h})(ds)),ds.exports}var Cf=Tf();const Tt=_e(Cf),Ef=Math.PI*2,Af=180/Math.PI,Pf=Math.PI/180;class q{constructor(t=0,e=0){this.x=0,this.y=0,this.x=t,this.y=e}clone(){return new q(this.x,this.y)}copyFrom(t){return this.set(t.x,t.y),this}copyTo(t){return t.set(this.x,this.y),t}equals(t){return t.x===this.x&&t.y===this.y}set(t=0,e=t){return this.x=t,this.y=e,this}toString(){return`[pixi.js/math:Point x=${this.x} y=${this.y}]`}static get shared(){return fs.x=0,fs.y=0,fs}}const fs=new q;class k{constructor(t=1,e=0,r=0,n=1,a=0,l=0){this.array=null,this.a=t,this.b=e,this.c=r,this.d=n,this.tx=a,this.ty=l}fromArray(t){this.a=t[0],this.b=t[1],this.c=t[3],this.d=t[4],this.tx=t[2],this.ty=t[5]}set(t,e,r,n,a,l){return this.a=t,this.b=e,this.c=r,this.d=n,this.tx=a,this.ty=l,this}toArray(t,e){this.array||(this.array=new Float32Array(9));const r=e||this.array;return t?(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[8]=1):(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}apply(t,e){e=e||new q;const r=t.x,n=t.y;return e.x=this.a*r+this.c*n+this.tx,e.y=this.b*r+this.d*n+this.ty,e}applyInverse(t,e){e=e||new q;const r=this.a,n=this.b,a=this.c,l=this.d,h=this.tx,d=this.ty,f=1/(r*l+a*-n),m=t.x,g=t.y;return e.x=l*f*m+-a*f*g+(d*a-h*l)*f,e.y=r*f*g+-n*f*m+(-d*r+h*n)*f,e}translate(t,e){return this.tx+=t,this.ty+=e,this}scale(t,e){return this.a*=t,this.d*=e,this.c*=t,this.b*=e,this.tx*=t,this.ty*=e,this}rotate(t){const e=Math.cos(t),r=Math.sin(t),n=this.a,a=this.c,l=this.tx;return this.a=n*e-this.b*r,this.b=n*r+this.b*e,this.c=a*e-this.d*r,this.d=a*r+this.d*e,this.tx=l*e-this.ty*r,this.ty=l*r+this.ty*e,this}append(t){const e=this.a,r=this.b,n=this.c,a=this.d;return this.a=t.a*e+t.b*n,this.b=t.a*r+t.b*a,this.c=t.c*e+t.d*n,this.d=t.c*r+t.d*a,this.tx=t.tx*e+t.ty*n+this.tx,this.ty=t.tx*r+t.ty*a+this.ty,this}appendFrom(t,e){const r=t.a,n=t.b,a=t.c,l=t.d,h=t.tx,d=t.ty,f=e.a,m=e.b,g=e.c,y=e.d;return this.a=r*f+n*g,this.b=r*m+n*y,this.c=a*f+l*g,this.d=a*m+l*y,this.tx=h*f+d*g+e.tx,this.ty=h*m+d*y+e.ty,this}setTransform(t,e,r,n,a,l,h,d,f){return this.a=Math.cos(h+f)*a,this.b=Math.sin(h+f)*a,this.c=-Math.sin(h-d)*l,this.d=Math.cos(h-d)*l,this.tx=t-(r*this.a+n*this.c),this.ty=e-(r*this.b+n*this.d),this}prepend(t){const e=this.tx;if(t.a!==1||t.b!==0||t.c!==0||t.d!==1){const r=this.a,n=this.c;this.a=r*t.a+this.b*t.c,this.b=r*t.b+this.b*t.d,this.c=n*t.a+this.d*t.c,this.d=n*t.b+this.d*t.d}return this.tx=e*t.a+this.ty*t.c+t.tx,this.ty=e*t.b+this.ty*t.d+t.ty,this}decompose(t){const e=this.a,r=this.b,n=this.c,a=this.d,l=t.pivot,h=-Math.atan2(-n,a),d=Math.atan2(r,e),f=Math.abs(h+d);return f<1e-5||Math.abs(Ef-f)<1e-5?(t.rotation=d,t.skew.x=t.skew.y=0):(t.rotation=0,t.skew.x=h,t.skew.y=d),t.scale.x=Math.sqrt(e*e+r*r),t.scale.y=Math.sqrt(n*n+a*a),t.position.x=this.tx+(l.x*e+l.y*n),t.position.y=this.ty+(l.x*r+l.y*a),t}invert(){const t=this.a,e=this.b,r=this.c,n=this.d,a=this.tx,l=t*n-e*r;return this.a=n/l,this.b=-e/l,this.c=-r/l,this.d=t/l,this.tx=(r*this.ty-n*a)/l,this.ty=-(t*this.ty-e*a)/l,this}isIdentity(){return this.a===1&&this.b===0&&this.c===0&&this.d===1&&this.tx===0&&this.ty===0}identity(){return this.a=1,this.b=0,this.c=0,this.d=1,this.tx=0,this.ty=0,this}clone(){const t=new k;return t.a=this.a,t.b=this.b,t.c=this.c,t.d=this.d,t.tx=this.tx,t.ty=this.ty,t}copyTo(t){return t.a=this.a,t.b=this.b,t.c=this.c,t.d=this.d,t.tx=this.tx,t.ty=this.ty,t}copyFrom(t){return this.a=t.a,this.b=t.b,this.c=t.c,this.d=t.d,this.tx=t.tx,this.ty=t.ty,this}equals(t){return t.a===this.a&&t.b===this.b&&t.c===this.c&&t.d===this.d&&t.tx===this.tx&&t.ty===this.ty}toString(){return`[pixi.js:Matrix a=${this.a} b=${this.b} c=${this.c} d=${this.d} tx=${this.tx} ty=${this.ty}]`}static get IDENTITY(){return Uf.identity()}static get shared(){return Bf.identity()}}const Bf=new k,Uf=new k,ye=[1,1,0,-1,-1,-1,0,1,1,1,0,-1,-1,-1,0,1],xe=[0,1,1,1,0,-1,-1,-1,0,1,1,1,0,-1,-1,-1],be=[0,-1,-1,-1,0,1,1,1,0,1,1,1,0,-1,-1,-1],ve=[1,1,0,-1,-1,-1,0,1,-1,-1,0,1,1,1,0,-1],ps=[],Va=[],ar=Math.sign;function Mf(){for(let s=0;s<16;s++){const t=[];ps.push(t);for(let e=0;e<16;e++){const r=ar(ye[s]*ye[e]+be[s]*xe[e]),n=ar(xe[s]*ye[e]+ve[s]*xe[e]),a=ar(ye[s]*be[e]+be[s]*ve[e]),l=ar(xe[s]*be[e]+ve[s]*ve[e]);for(let h=0;h<16;h++)if(ye[h]===r&&xe[h]===n&&be[h]===a&&ve[h]===l){t.push(h);break}}}for(let s=0;s<16;s++){const t=new k;t.set(ye[s],xe[s],be[s],ve[s],0,0),Va.push(t)}}Mf();const Z={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:s=>ye[s],uY:s=>xe[s],vX:s=>be[s],vY:s=>ve[s],inv:s=>s&8?s&15:-s&7,add:(s,t)=>ps[s][t],sub:(s,t)=>ps[s][Z.inv(t)],rotate180:s=>s^4,isVertical:s=>(s&3)===2,byDirection:(s,t)=>Math.abs(s)*2<=Math.abs(t)?t>=0?Z.S:Z.N:Math.abs(t)*2<=Math.abs(s)?s>0?Z.E:Z.W:t>0?s>0?Z.SE:Z.SW:s>0?Z.NE:Z.NW,matrixAppendRotationInv:(s,t,e=0,r=0)=>{const n=Va[Z.inv(t)];n.tx=e,n.ty=r,s.append(n)},transformRectCoords:(s,t,e,r)=>{const{x:n,y:a,width:l,height:h}=s,{x:d,y:f,width:m,height:g}=t;return e===Z.E?(r.set(n+d,a+f,l,h),r):e===Z.S?r.set(m-a-h+d,n+f,h,l):e===Z.W?r.set(m-n-l+d,g-a-h+f,l,h):e===Z.N?r.set(a+d,g-n-l+f,h,l):r.set(n+d,a+f,l,h)}},or=[new q,new q,new q,new q];class L{constructor(t=0,e=0,r=0,n=0){this.type="rectangle",this.x=Number(t),this.y=Number(e),this.width=Number(r),this.height=Number(n)}get left(){return this.x}get right(){return this.x+this.width}get top(){return this.y}get bottom(){return this.y+this.height}isEmpty(){return this.left===this.right||this.top===this.bottom}static get EMPTY(){return new L(0,0,0,0)}clone(){return new L(this.x,this.y,this.width,this.height)}copyFromBounds(t){return this.x=t.minX,this.y=t.minY,this.width=t.maxX-t.minX,this.height=t.maxY-t.minY,this}copyFrom(t){return this.x=t.x,this.y=t.y,this.width=t.width,this.height=t.height,this}copyTo(t){return t.copyFrom(this),t}contains(t,e){return this.width<=0||this.height<=0?!1:t>=this.x&&t<this.x+this.width&&e>=this.y&&e<this.y+this.height}strokeContains(t,e,r,n=.5){const{width:a,height:l}=this;if(a<=0||l<=0)return!1;const h=this.x,d=this.y,f=r*(1-n),m=r-f,g=h-f,y=h+a+f,x=d-f,o=d+l+f,c=h+m,u=h+a-m,p=d+m,_=d+l-m;return t>=g&&t<=y&&e>=x&&e<=o&&!(t>c&&t<u&&e>p&&e<_)}intersects(t,e){if(!e){const E=this.x<t.x?t.x:this.x;if((this.right>t.right?t.right:this.right)<=E)return!1;const B=this.y<t.y?t.y:this.y;return(this.bottom>t.bottom?t.bottom:this.bottom)>B}const r=this.left,n=this.right,a=this.top,l=this.bottom;if(n<=r||l<=a)return!1;const h=or[0].set(t.left,t.top),d=or[1].set(t.left,t.bottom),f=or[2].set(t.right,t.top),m=or[3].set(t.right,t.bottom);if(f.x<=h.x||d.y<=h.y)return!1;const g=Math.sign(e.a*e.d-e.b*e.c);if(g===0||(e.apply(h,h),e.apply(d,d),e.apply(f,f),e.apply(m,m),Math.max(h.x,d.x,f.x,m.x)<=r||Math.min(h.x,d.x,f.x,m.x)>=n||Math.max(h.y,d.y,f.y,m.y)<=a||Math.min(h.y,d.y,f.y,m.y)>=l))return!1;const y=g*(d.y-h.y),x=g*(h.x-d.x),o=y*r+x*a,c=y*n+x*a,u=y*r+x*l,p=y*n+x*l;if(Math.max(o,c,u,p)<=y*h.x+x*h.y||Math.min(o,c,u,p)>=y*m.x+x*m.y)return!1;const _=g*(h.y-f.y),b=g*(f.x-h.x),v=_*r+b*a,w=_*n+b*a,S=_*r+b*l,T=_*n+b*l;return!(Math.max(v,w,S,T)<=_*h.x+b*h.y||Math.min(v,w,S,T)>=_*m.x+b*m.y)}pad(t=0,e=t){return this.x-=t,this.y-=e,this.width+=t*2,this.height+=e*2,this}fit(t){const e=Math.max(this.x,t.x),r=Math.min(this.x+this.width,t.x+t.width),n=Math.max(this.y,t.y),a=Math.min(this.y+this.height,t.y+t.height);return this.x=e,this.width=Math.max(r-e,0),this.y=n,this.height=Math.max(a-n,0),this}ceil(t=1,e=.001){const r=Math.ceil((this.x+this.width-e)*t)/t,n=Math.ceil((this.y+this.height-e)*t)/t;return this.x=Math.floor((this.x+e)*t)/t,this.y=Math.floor((this.y+e)*t)/t,this.width=r-this.x,this.height=n-this.y,this}scale(t,e=t){return this.x*=t,this.y*=e,this.width*=t,this.height*=e,this}enlarge(t){const e=Math.min(this.x,t.x),r=Math.max(this.x+this.width,t.x+t.width),n=Math.min(this.y,t.y),a=Math.max(this.y+this.height,t.y+t.height);return this.x=e,this.width=r-e,this.y=n,this.height=a-n,this}getBounds(t){return t||(t=new L),t.copyFrom(this),t}containsRect(t){if(this.width<=0||this.height<=0)return!1;const e=t.x,r=t.y,n=t.x+t.width,a=t.y+t.height;return e>=this.x&&e<this.x+this.width&&r>=this.y&&r<this.y+this.height&&n>=this.x&&n<this.x+this.width&&a>=this.y&&a<this.y+this.height}set(t,e,r,n){return this.x=t,this.y=e,this.width=r,this.height=n,this}toString(){return`[pixi.js/math:Rectangle x=${this.x} y=${this.y} width=${this.width} height=${this.height}]`}}const ms={default:-1};function et(s="default"){return ms[s]===void 0&&(ms[s]=-1),++ms[s]}const Ya=new Set,$="8.0.0",kf="8.3.4",Oe={quiet:!1,noColor:!1},z=(s,t,e=3)=>{if(Oe.quiet||Ya.has(t))return;let r=new Error().stack;const n=`${t}
|
|
65
|
-
Deprecated since v${s}`,
|
|
64
|
+
`.replace(/\t/g,"").replace(/#/g,"%23");return l.src=`data:image/svg+xml;charset=utf-8,${u}`,await new Promise(f=>{l.onload=f}),l}async function Cf(s,t,e={}){const r=await Tf(s,t,e),n=new OffscreenCanvas(r.width,r.height);return n.getContext("2d")?.drawImage(r,0,0,r.width,r.height),await createImageBitmap(n)}async function Ef(s,t){const e={type:t,data:s},r=new ImageDecoder(e);await Promise.all([r.completed,r.tracks.ready]);const n=r.tracks.selectedTrack?.frameCount??1,o=[];for(let l=0;l<n;l+=1)o.push((await r.decode({frameIndex:l})).image);return o}class Af{display={from:0,to:0};duration=0;playbackRate=1;evtTool=new os;on=this.evtTool.on;_left=0;get left(){return this._left}set left(t){const e=this._left!==t;this._left=t,e&&this.evtTool.emit("propsChange",{left:t})}_top=0;get top(){return this._top}set top(t){const e=this._top!==t;this._top=t,e&&this.evtTool.emit("propsChange",{top:t})}_width=0;get width(){return this._width}set width(t){const e=this._width!==t;this._width=t,e&&this.evtTool.emit("propsChange",{width:t})}_height=0;get height(){return this._height}set height(t){const e=this._height!==t;this._height=t,e&&this.evtTool.emit("propsChange",{height:t})}_angle=0;get angle(){return this._angle}set angle(t){const e=this._angle!==t;this._angle=t,e&&this.evtTool.emit("propsChange",{angle:t})}get center(){return{x:this.left+this.width/2,y:this.top+this.height/2}}_zIndex=0;get zIndex(){return this._zIndex}set zIndex(t){const e=this._zIndex!==t;this._zIndex=t,e&&this.evtTool.emit("propsChange",{zIndex:t})}opacity=1;flip=null;animatKeyFrame=null;animatOpts=null;ready=Promise.resolve();constructor(){}_render(t){const{center:e,angle:r}=this;t.setTransform(this.flip==="horizontal"?-1:1,0,0,this.flip==="vertical"?-1:1,e.x,e.y),t.rotate((this.flip==null?1:-1)*r),t.globalAlpha=this.opacity}setAnimation(t,e){this.animatKeyFrame=Object.entries(t).map(([r,n])=>{const o={from:0,to:100}[r]??Number(r.slice(0,-1));if(isNaN(o)||o>100||o<0)throw Error("keyFrame must between 0~100");return[o/100,n]}),this.animatOpts=Object.assign({},this.animatOpts,{duration:e.duration,delay:e.delay??0,iterCount:e.iterCount??1/0})}animate(t){if(this.animatKeyFrame==null||this.animatOpts==null||t<this.animatOpts.delay)return;const e=Pf(t,this.animatKeyFrame,this.animatOpts);for(const r in e)switch(r){case"opacity":this.opacity=e[r];break;case"x":this.left=e[r];break;case"y":this.top=e[r];break;case"w":this.width=e[r];break;case"h":this.height=e[r];break;case"angle":this.angle=e[r];break}}copyStateTo(t){t.animatKeyFrame=this.animatKeyFrame,t.animatOpts=this.animatOpts,t.zIndex=this.zIndex,t.opacity=this.opacity,t.flip=this.flip,t.left=this.left,t.top=this.top,t.width=this.width,t.height=this.height,t.angle=this.angle,t.display={...this.display},t.duration=this.duration,t.playbackRate=this.playbackRate,"src"in this&&"src"in t&&(t.src=this.src)}destroy(){this.evtTool.destroy()}}function Pf(s,t,e){const r=s-e.delay,n=r%e.duration,o=r/e.duration>=e.iterCount||r===e.duration?1:n/e.duration,l=t.findIndex(x=>x[0]>=o);if(l===-1)return{};const h=t[l-1],u=t[l],f=u[1];if(h==null)return f;const m=h[1],g={},y=(o-h[0])/(u[0]-h[0]);for(const x in f){if(!f.hasOwnProperty(x)||typeof x!="string")continue;const a=x;m[a]!=null&&(g[a]=(f[a]-m[a])*y+m[a])}return g}class ci extends Af{lastVf=null;destroyed=!1;src="";constructor(){super()}async getFrame(t){const e=t*this.playbackRate,{video:r,audio:n,state:o}=await this.tick(e);let l=n??[];n!=null&&this.playbackRate!==1&&(l=n.map(u=>Yo(u,this.playbackRate)));let h=null;return r!=null?(this.lastVf?.close(),r instanceof VideoFrame?(h=await createImageBitmap(r),r.close()):h=r,this.lastVf=h):this.lastVf!=null&&(h=this.lastVf),{video:h,audio:l,done:o==="done"}}async offscreenRender(t,e){const r=e*this.playbackRate;this.animate(r),super._render(t);const{width:n,height:o}=this,{video:l,audio:h,state:u}=await this.tick(r);let f=h??[];if(h!=null&&this.playbackRate!==1&&(f=h.map(g=>Yo(g,this.playbackRate))),u==="done")return{audio:f,done:!0};let m=l??this.lastVf;return m!=null&&t.drawImage(m,-n/2,-o/2,n,o),l!=null&&(this.lastVf?.close(),l instanceof ImageBitmap&&(this.lastVf=l)),{audio:f,done:!1}}set(t,e=30){if(t.display&&(t.display.from!==void 0&&(this.display.from=t.display.from<1e6?t.display.from/e*1e6:t.display.from),t.display.to!==void 0&&(this.display.to=t.display.to<1e6?t.display.to/e*1e6:t.display.to)),t.x!==void 0&&(this.left=t.x),t.y!==void 0&&(this.top=t.y),t.width!==void 0&&(this.width=t.width),t.height!==void 0&&(this.height=t.height),t.duration!==void 0){const r=t.duration<1e6?t.duration/e*1e6:t.duration;this.duration=r,this.display.from!==void 0&&(this.display.to=this.display.from+r)}return this}toJSON(t=!1){const e=this.animatKeyFrame&&this.animatOpts?{keyFrames:this.animatKeyFrame.reduce((r,[n,o])=>{const l=n===0?"from":n===1?"to":`${Math.round(n*100)}%`;return r[l]=o,r},{}),opts:this.animatOpts}:void 0;return{type:this.constructor.name,src:this.src,display:{from:this.display.from,to:this.display.to},playbackRate:this.playbackRate,duration:this.duration,left:this.left,top:this.top,width:this.width,height:this.height,angle:this.angle,zIndex:this.zIndex,opacity:this.opacity,flip:this.flip,...e&&{animation:e},...t&&{main:!0}}}destroy(){this.destroyed||(this.destroyed=!0,H.info("BaseClip destroy"),super.destroy(),this.lastVf?.close(),this.lastVf=null)}}let fs=null;async function $o(){return fs===null&&(fs=cf()),await fs}const tt={get codec(){return or()?.codec??"mp4a.40.2"},get codecType(){return or()?.codecType??"aac"},get sampleRate(){return or()?.sampleRate??48e3},get channelCount(){return or()?.channelCount??2}};class mt extends ci{static ctx=null;ready;_meta={duration:0,width:0,height:0};get meta(){return{...this._meta,sampleRate:tt.sampleRate,chanCount:2}}chan0Buf=new Float32Array;chan1Buf=new Float32Array;getPCMData(){return[this.chan0Buf,this.chan1Buf]}opts;loop=!1;volume=1;static async fromUrl(t,e={}){const r=await fetch(t);if(!r.ok)throw new Error(`Failed to fetch audio from ${t}: ${r.status} ${r.statusText}`);const n=new mt(r.body,e,t);return await n.ready,n}static async fromObject(t){if(t.type!=="Audio")throw new Error(`Expected Audio, got ${t.type}`);if(!t.src||t.src.trim()==="")throw new Error("AudioClip requires a valid source URL");const e={};t.loop!==void 0&&(e.loop=t.loop),t.volume!==void 0&&(e.volume=t.volume);const r=await mt.fromUrl(t.src,e);return r.left=t.left,r.top=t.top,r.width=t.width,r.height=t.height,r.angle=t.angle,r.display.from=t.display.from,r.display.to=t.display.to,r.duration=t.duration,r.playbackRate=t.playbackRate,r.zIndex=t.zIndex,r.opacity=t.opacity,r.flip=t.flip,t.animation&&r.setAnimation(t.animation.keyFrames,t.animation.opts),r}constructor(t,e={},r){super(),this.src=r!==void 0?r:"",this.opts={loop:!1,volume:1,...e},this.loop=this.opts.loop??!1,this.volume=this.opts.volume??1,this.ready=this.init(t).then(n=>{const o={width:0,height:0,duration:e.loop?1/0:this._meta.duration};return this.width=this.width===0?o.width:this.width,this.height=this.height===0?o.height:this.height,this.duration=this.duration===0?o.duration:this.duration,this.display.to=this.display.from+this.duration,o})}async init(t){mt.ctx==null&&(mt.ctx=new AudioContext({sampleRate:tt.sampleRate}));const e=performance.now(),r=t instanceof ReadableStream?await Uf(t,mt.ctx):t;H.info("Audio clip decoded complete:",performance.now()-e);const n=this.opts.volume;if(n!==1)for(const o of r)for(let l=0;l<o.length;l+=1)o[l]*=n;this._meta.duration=r[0].length/tt.sampleRate*1e6,this.chan0Buf=r[0],this.chan1Buf=r[1]??this.chan0Buf,H.info("Audio clip convert to AudioData, time:",performance.now()-e)}tickInterceptor=async(t,e)=>e;timestamp=0;frameOffset=0;async tick(t){if(!this.opts.loop&&t>=this._meta.duration)return await this.tickInterceptor(t,{audio:[],state:"done"});const e=t-this.timestamp;if(t<this.timestamp||e>3e6)return this.timestamp=t,this.frameOffset=Math.ceil(this.timestamp/1e6*tt.sampleRate),await this.tickInterceptor(t,{audio:[new Float32Array(0),new Float32Array(0)],state:"success"});this.timestamp=t;const r=Math.ceil(e/1e6*tt.sampleRate),n=this.frameOffset+r,o=this.opts.loop?[ds(this.chan0Buf,this.frameOffset,n),ds(this.chan1Buf,this.frameOffset,n)]:[this.chan0Buf.slice(this.frameOffset,n),this.chan1Buf.slice(this.frameOffset,n)];return this.frameOffset=n,await this.tickInterceptor(t,{audio:o,state:"success"})}async split(t){await this.ready;const e=Math.ceil(t/1e6*tt.sampleRate),r=new mt(this.getPCMData().map(o=>o.slice(0,e)),this.opts,this.src),n=new mt(this.getPCMData().map(o=>o.slice(e)),this.opts,this.src);return[r,n]}async clone(){await this.ready;const t=new mt(this.getPCMData(),this.opts,this.src);return await t.ready,this.copyStateTo(t),t}destroy(){this.chan0Buf=new Float32Array(0),this.chan1Buf=new Float32Array(0),H.info("---- audioclip destroy ----"),super.destroy()}toJSON(t=!1){return{...super.toJSON(t),type:"Audio",loop:this.loop,volume:this.volume}}static concatAudioClip=Bf;async createPlaybackElement(){if(await this.ready,!this.src||this.src.trim()==="")throw new Error("AudioClip requires a source URL for playback");const t=this.src.startsWith("blob:")?this.src:void 0,e=document.createElement("audio");return e.crossOrigin="anonymous",e.autoplay=!1,e.preload="auto",e.loop=this.opts.loop||!1,e.src=this.src,await new Promise((r,n)=>{const o=()=>{e.removeEventListener("loadeddata",o),e.removeEventListener("error",l),e.pause(),e.currentTime=0,r()},l=()=>{e.removeEventListener("loadeddata",o),e.removeEventListener("error",l),n(new Error("Failed to load audio"))};e.addEventListener("loadeddata",o,{once:!0}),e.addEventListener("error",l,{once:!0}),e.load()}),{element:e,objectUrl:t}}async play(t,e){const r=t;if(Math.abs(r.currentTime-e)>.1&&(r.currentTime=e),r.paused)try{await r.play()}catch{try{await r.play()}catch(o){console.warn("Failed to play audio:",o)}}}pause(t){t.pause()}async seek(t,e){const r=t;return r.pause(),r.currentTime=e,new Promise(n=>{if(Math.abs(r.currentTime-e)<.01){n();return}const o=()=>{r.removeEventListener("seeked",o),n()};r.addEventListener("seeked",o,{once:!0}),setTimeout(()=>{r.removeEventListener("seeked",o),n()},500)})}syncPlayback(t,e,r){const n=t,o=this.meta.duration/1e6,l=r>=0&&r<o;e&&l?n.paused&&this.play(n,r).catch(console.warn):(n.paused||n.pause(),l&&Math.abs(n.currentTime-r)>.1&&(n.currentTime=r))}cleanupPlayback(t,e){const r=t;r.pause(),r.removeAttribute("src"),r.load(),e&&e.startsWith("blob:")&&URL.revokeObjectURL(e)}}async function Bf(s,t){const e=[];for(const r of s)await r.ready,e.push(r.getPCMData());return new mt(Ho(e),t)}async function Uf(s,t){const e=await new Response(s).arrayBuffer();return cs(await t.decodeAudioData(e))}var C=(s=>(s.Application="application",s.WebGLPipes="webgl-pipes",s.WebGLPipesAdaptor="webgl-pipes-adaptor",s.WebGLSystem="webgl-system",s.WebGPUPipes="webgpu-pipes",s.WebGPUPipesAdaptor="webgpu-pipes-adaptor",s.WebGPUSystem="webgpu-system",s.CanvasSystem="canvas-system",s.CanvasPipesAdaptor="canvas-pipes-adaptor",s.CanvasPipes="canvas-pipes",s.Asset="asset",s.LoadParser="load-parser",s.ResolveParser="resolve-parser",s.CacheParser="cache-parser",s.DetectionParser="detection-parser",s.MaskEffect="mask-effect",s.BlendMode="blend-mode",s.TextureSource="texture-source",s.Environment="environment",s.ShapeBuilder="shape-builder",s.Batcher="batcher",s))(C||{});const ps=s=>{if(typeof s=="function"||typeof s=="object"&&s.extension){if(!s.extension)throw new Error("Extension class must have an extension object");s={...typeof s.extension!="object"?{type:s.extension}:s.extension,ref:s}}if(typeof s=="object")s={...s};else throw new Error("Invalid extension type");return typeof s.type=="string"&&(s.type=[s.type]),s},ar=(s,t)=>ps(s).priority??t,D={_addHandlers:{},_removeHandlers:{},_queue:{},remove(...s){return s.map(ps).forEach(t=>{t.type.forEach(e=>this._removeHandlers[e]?.(t))}),this},add(...s){return s.map(ps).forEach(t=>{t.type.forEach(e=>{const r=this._addHandlers,n=this._queue;r[e]?r[e]?.(t):(n[e]=n[e]||[],n[e]?.push(t))})}),this},handle(s,t,e){const r=this._addHandlers,n=this._removeHandlers;if(r[s]||n[s])throw new Error(`Extension type ${s} already has a handler`);r[s]=t,n[s]=e;const o=this._queue;return o[s]&&(o[s]?.forEach(l=>t(l)),delete o[s]),this},handleByMap(s,t){return this.handle(s,e=>{e.name&&(t[e.name]=e.ref)},e=>{e.name&&delete t[e.name]})},handleByNamedList(s,t,e=-1){return this.handle(s,r=>{t.findIndex(o=>o.name===r.name)>=0||(t.push({name:r.name,value:r.ref}),t.sort((o,l)=>ar(l.value,e)-ar(o.value,e)))},r=>{const n=t.findIndex(o=>o.name===r.name);n!==-1&&t.splice(n,1)})},handleByList(s,t,e=-1){return this.handle(s,r=>{t.includes(r.ref)||(t.push(r.ref),t.sort((n,o)=>ar(o,e)-ar(n,e)))},r=>{const n=t.indexOf(r.ref);n!==-1&&t.splice(n,1)})},mixin(s,...t){for(const e of t)Object.defineProperties(s.prototype,Object.getOwnPropertyDescriptors(e))}},kf={extension:{type:C.Environment,name:"browser",priority:-1},test:()=>!0,load:async()=>{await Promise.resolve().then(()=>Iv)}},Mf={extension:{type:C.Environment,name:"webworker",priority:0},test:()=>typeof self<"u"&&self.WorkerGlobalScope!==void 0,load:async()=>{await Promise.resolve().then(()=>Fv)}};class ct{constructor(t,e,r){this._x=e||0,this._y=r||0,this._observer=t}clone(t){return new ct(t??this._observer,this._x,this._y)}set(t=0,e=t){return(this._x!==t||this._y!==e)&&(this._x=t,this._y=e,this._observer._onUpdate(this)),this}copyFrom(t){return(this._x!==t.x||this._y!==t.y)&&(this._x=t.x,this._y=t.y,this._observer._onUpdate(this)),this}copyTo(t){return t.set(this._x,this._y),t}equals(t){return t.x===this._x&&t.y===this._y}toString(){return`[pixi.js/math:ObservablePoint x=${this._x} y=${this._y} scope=${this._observer}]`}get x(){return this._x}set x(t){this._x!==t&&(this._x=t,this._observer._onUpdate(this))}get y(){return this._y}set y(t){this._y!==t&&(this._y=t,this._observer._onUpdate(this))}}var ms={exports:{}},Ko;function Rf(){return Ko||(Ko=1,(function(s){var t=Object.prototype.hasOwnProperty,e="~";function r(){}Object.create&&(r.prototype=Object.create(null),new r().__proto__||(e=!1));function n(u,f,m){this.fn=u,this.context=f,this.once=m||!1}function o(u,f,m,g,y){if(typeof m!="function")throw new TypeError("The listener must be a function");var x=new n(m,g||u,y),a=e?e+f:f;return u._events[a]?u._events[a].fn?u._events[a]=[u._events[a],x]:u._events[a].push(x):(u._events[a]=x,u._eventsCount++),u}function l(u,f){--u._eventsCount===0?u._events=new r:delete u._events[f]}function h(){this._events=new r,this._eventsCount=0}h.prototype.eventNames=function(){var f=[],m,g;if(this._eventsCount===0)return f;for(g in m=this._events)t.call(m,g)&&f.push(e?g.slice(1):g);return Object.getOwnPropertySymbols?f.concat(Object.getOwnPropertySymbols(m)):f},h.prototype.listeners=function(f){var m=e?e+f:f,g=this._events[m];if(!g)return[];if(g.fn)return[g.fn];for(var y=0,x=g.length,a=new Array(x);y<x;y++)a[y]=g[y].fn;return a},h.prototype.listenerCount=function(f){var m=e?e+f:f,g=this._events[m];return g?g.fn?1:g.length:0},h.prototype.emit=function(f,m,g,y,x,a){var c=e?e+f:f;if(!this._events[c])return!1;var d=this._events[c],p=arguments.length,_,b;if(d.fn){switch(d.once&&this.removeListener(f,d.fn,void 0,!0),p){case 1:return d.fn.call(d.context),!0;case 2:return d.fn.call(d.context,m),!0;case 3:return d.fn.call(d.context,m,g),!0;case 4:return d.fn.call(d.context,m,g,y),!0;case 5:return d.fn.call(d.context,m,g,y,x),!0;case 6:return d.fn.call(d.context,m,g,y,x,a),!0}for(b=1,_=new Array(p-1);b<p;b++)_[b-1]=arguments[b];d.fn.apply(d.context,_)}else{var v=d.length,w;for(b=0;b<v;b++)switch(d[b].once&&this.removeListener(f,d[b].fn,void 0,!0),p){case 1:d[b].fn.call(d[b].context);break;case 2:d[b].fn.call(d[b].context,m);break;case 3:d[b].fn.call(d[b].context,m,g);break;case 4:d[b].fn.call(d[b].context,m,g,y);break;default:if(!_)for(w=1,_=new Array(p-1);w<p;w++)_[w-1]=arguments[w];d[b].fn.apply(d[b].context,_)}}return!0},h.prototype.on=function(f,m,g){return o(this,f,m,g,!1)},h.prototype.once=function(f,m,g){return o(this,f,m,g,!0)},h.prototype.removeListener=function(f,m,g,y){var x=e?e+f:f;if(!this._events[x])return this;if(!m)return l(this,x),this;var a=this._events[x];if(a.fn)a.fn===m&&(!y||a.once)&&(!g||a.context===g)&&l(this,x);else{for(var c=0,d=[],p=a.length;c<p;c++)(a[c].fn!==m||y&&!a[c].once||g&&a[c].context!==g)&&d.push(a[c]);d.length?this._events[x]=d.length===1?d[0]:d:l(this,x)}return this},h.prototype.removeAllListeners=function(f){var m;return f?(m=e?e+f:f,this._events[m]&&l(this,m)):(this._events=new r,this._eventsCount=0),this},h.prototype.off=h.prototype.removeListener,h.prototype.addListener=h.prototype.on,h.prefixed=e,h.EventEmitter=h,s.exports=h})(ms)),ms.exports}var If=Rf();const Ct=ye(If),Ff=Math.PI*2,Df=180/Math.PI,Of=Math.PI/180;class q{constructor(t=0,e=0){this.x=0,this.y=0,this.x=t,this.y=e}clone(){return new q(this.x,this.y)}copyFrom(t){return this.set(t.x,t.y),this}copyTo(t){return t.set(this.x,this.y),t}equals(t){return t.x===this.x&&t.y===this.y}set(t=0,e=t){return this.x=t,this.y=e,this}toString(){return`[pixi.js/math:Point x=${this.x} y=${this.y}]`}static get shared(){return gs.x=0,gs.y=0,gs}}const gs=new q;class M{constructor(t=1,e=0,r=0,n=1,o=0,l=0){this.array=null,this.a=t,this.b=e,this.c=r,this.d=n,this.tx=o,this.ty=l}fromArray(t){this.a=t[0],this.b=t[1],this.c=t[3],this.d=t[4],this.tx=t[2],this.ty=t[5]}set(t,e,r,n,o,l){return this.a=t,this.b=e,this.c=r,this.d=n,this.tx=o,this.ty=l,this}toArray(t,e){this.array||(this.array=new Float32Array(9));const r=e||this.array;return t?(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[8]=1):(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}apply(t,e){e=e||new q;const r=t.x,n=t.y;return e.x=this.a*r+this.c*n+this.tx,e.y=this.b*r+this.d*n+this.ty,e}applyInverse(t,e){e=e||new q;const r=this.a,n=this.b,o=this.c,l=this.d,h=this.tx,u=this.ty,f=1/(r*l+o*-n),m=t.x,g=t.y;return e.x=l*f*m+-o*f*g+(u*o-h*l)*f,e.y=r*f*g+-n*f*m+(-u*r+h*n)*f,e}translate(t,e){return this.tx+=t,this.ty+=e,this}scale(t,e){return this.a*=t,this.d*=e,this.c*=t,this.b*=e,this.tx*=t,this.ty*=e,this}rotate(t){const e=Math.cos(t),r=Math.sin(t),n=this.a,o=this.c,l=this.tx;return this.a=n*e-this.b*r,this.b=n*r+this.b*e,this.c=o*e-this.d*r,this.d=o*r+this.d*e,this.tx=l*e-this.ty*r,this.ty=l*r+this.ty*e,this}append(t){const e=this.a,r=this.b,n=this.c,o=this.d;return this.a=t.a*e+t.b*n,this.b=t.a*r+t.b*o,this.c=t.c*e+t.d*n,this.d=t.c*r+t.d*o,this.tx=t.tx*e+t.ty*n+this.tx,this.ty=t.tx*r+t.ty*o+this.ty,this}appendFrom(t,e){const r=t.a,n=t.b,o=t.c,l=t.d,h=t.tx,u=t.ty,f=e.a,m=e.b,g=e.c,y=e.d;return this.a=r*f+n*g,this.b=r*m+n*y,this.c=o*f+l*g,this.d=o*m+l*y,this.tx=h*f+u*g+e.tx,this.ty=h*m+u*y+e.ty,this}setTransform(t,e,r,n,o,l,h,u,f){return this.a=Math.cos(h+f)*o,this.b=Math.sin(h+f)*o,this.c=-Math.sin(h-u)*l,this.d=Math.cos(h-u)*l,this.tx=t-(r*this.a+n*this.c),this.ty=e-(r*this.b+n*this.d),this}prepend(t){const e=this.tx;if(t.a!==1||t.b!==0||t.c!==0||t.d!==1){const r=this.a,n=this.c;this.a=r*t.a+this.b*t.c,this.b=r*t.b+this.b*t.d,this.c=n*t.a+this.d*t.c,this.d=n*t.b+this.d*t.d}return this.tx=e*t.a+this.ty*t.c+t.tx,this.ty=e*t.b+this.ty*t.d+t.ty,this}decompose(t){const e=this.a,r=this.b,n=this.c,o=this.d,l=t.pivot,h=-Math.atan2(-n,o),u=Math.atan2(r,e),f=Math.abs(h+u);return f<1e-5||Math.abs(Ff-f)<1e-5?(t.rotation=u,t.skew.x=t.skew.y=0):(t.rotation=0,t.skew.x=h,t.skew.y=u),t.scale.x=Math.sqrt(e*e+r*r),t.scale.y=Math.sqrt(n*n+o*o),t.position.x=this.tx+(l.x*e+l.y*n),t.position.y=this.ty+(l.x*r+l.y*o),t}invert(){const t=this.a,e=this.b,r=this.c,n=this.d,o=this.tx,l=t*n-e*r;return this.a=n/l,this.b=-e/l,this.c=-r/l,this.d=t/l,this.tx=(r*this.ty-n*o)/l,this.ty=-(t*this.ty-e*o)/l,this}isIdentity(){return this.a===1&&this.b===0&&this.c===0&&this.d===1&&this.tx===0&&this.ty===0}identity(){return this.a=1,this.b=0,this.c=0,this.d=1,this.tx=0,this.ty=0,this}clone(){const t=new M;return t.a=this.a,t.b=this.b,t.c=this.c,t.d=this.d,t.tx=this.tx,t.ty=this.ty,t}copyTo(t){return t.a=this.a,t.b=this.b,t.c=this.c,t.d=this.d,t.tx=this.tx,t.ty=this.ty,t}copyFrom(t){return this.a=t.a,this.b=t.b,this.c=t.c,this.d=t.d,this.tx=t.tx,this.ty=t.ty,this}equals(t){return t.a===this.a&&t.b===this.b&&t.c===this.c&&t.d===this.d&&t.tx===this.tx&&t.ty===this.ty}toString(){return`[pixi.js:Matrix a=${this.a} b=${this.b} c=${this.c} d=${this.d} tx=${this.tx} ty=${this.ty}]`}static get IDENTITY(){return Lf.identity()}static get shared(){return Gf.identity()}}const Gf=new M,Lf=new M,xe=[1,1,0,-1,-1,-1,0,1,1,1,0,-1,-1,-1,0,1],be=[0,1,1,1,0,-1,-1,-1,0,1,1,1,0,-1,-1,-1],ve=[0,-1,-1,-1,0,1,1,1,0,1,1,1,0,-1,-1,-1],we=[1,1,0,-1,-1,-1,0,1,-1,-1,0,1,1,1,0,-1],_s=[],jo=[],hr=Math.sign;function zf(){for(let s=0;s<16;s++){const t=[];_s.push(t);for(let e=0;e<16;e++){const r=hr(xe[s]*xe[e]+ve[s]*be[e]),n=hr(be[s]*xe[e]+we[s]*be[e]),o=hr(xe[s]*ve[e]+ve[s]*we[e]),l=hr(be[s]*ve[e]+we[s]*we[e]);for(let h=0;h<16;h++)if(xe[h]===r&&be[h]===n&&ve[h]===o&&we[h]===l){t.push(h);break}}}for(let s=0;s<16;s++){const t=new M;t.set(xe[s],be[s],ve[s],we[s],0,0),jo.push(t)}}zf();const Z={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:s=>xe[s],uY:s=>be[s],vX:s=>ve[s],vY:s=>we[s],inv:s=>s&8?s&15:-s&7,add:(s,t)=>_s[s][t],sub:(s,t)=>_s[s][Z.inv(t)],rotate180:s=>s^4,isVertical:s=>(s&3)===2,byDirection:(s,t)=>Math.abs(s)*2<=Math.abs(t)?t>=0?Z.S:Z.N:Math.abs(t)*2<=Math.abs(s)?s>0?Z.E:Z.W:t>0?s>0?Z.SE:Z.SW:s>0?Z.NE:Z.NW,matrixAppendRotationInv:(s,t,e=0,r=0)=>{const n=jo[Z.inv(t)];n.tx=e,n.ty=r,s.append(n)},transformRectCoords:(s,t,e,r)=>{const{x:n,y:o,width:l,height:h}=s,{x:u,y:f,width:m,height:g}=t;return e===Z.E?(r.set(n+u,o+f,l,h),r):e===Z.S?r.set(m-o-h+u,n+f,h,l):e===Z.W?r.set(m-n-l+u,g-o-h+f,l,h):e===Z.N?r.set(o+u,g-n-l+f,h,l):r.set(n+u,o+f,l,h)}},lr=[new q,new q,new q,new q];class G{constructor(t=0,e=0,r=0,n=0){this.type="rectangle",this.x=Number(t),this.y=Number(e),this.width=Number(r),this.height=Number(n)}get left(){return this.x}get right(){return this.x+this.width}get top(){return this.y}get bottom(){return this.y+this.height}isEmpty(){return this.left===this.right||this.top===this.bottom}static get EMPTY(){return new G(0,0,0,0)}clone(){return new G(this.x,this.y,this.width,this.height)}copyFromBounds(t){return this.x=t.minX,this.y=t.minY,this.width=t.maxX-t.minX,this.height=t.maxY-t.minY,this}copyFrom(t){return this.x=t.x,this.y=t.y,this.width=t.width,this.height=t.height,this}copyTo(t){return t.copyFrom(this),t}contains(t,e){return this.width<=0||this.height<=0?!1:t>=this.x&&t<this.x+this.width&&e>=this.y&&e<this.y+this.height}strokeContains(t,e,r,n=.5){const{width:o,height:l}=this;if(o<=0||l<=0)return!1;const h=this.x,u=this.y,f=r*(1-n),m=r-f,g=h-f,y=h+o+f,x=u-f,a=u+l+f,c=h+m,d=h+o-m,p=u+m,_=u+l-m;return t>=g&&t<=y&&e>=x&&e<=a&&!(t>c&&t<d&&e>p&&e<_)}intersects(t,e){if(!e){const E=this.x<t.x?t.x:this.x;if((this.right>t.right?t.right:this.right)<=E)return!1;const B=this.y<t.y?t.y:this.y;return(this.bottom>t.bottom?t.bottom:this.bottom)>B}const r=this.left,n=this.right,o=this.top,l=this.bottom;if(n<=r||l<=o)return!1;const h=lr[0].set(t.left,t.top),u=lr[1].set(t.left,t.bottom),f=lr[2].set(t.right,t.top),m=lr[3].set(t.right,t.bottom);if(f.x<=h.x||u.y<=h.y)return!1;const g=Math.sign(e.a*e.d-e.b*e.c);if(g===0||(e.apply(h,h),e.apply(u,u),e.apply(f,f),e.apply(m,m),Math.max(h.x,u.x,f.x,m.x)<=r||Math.min(h.x,u.x,f.x,m.x)>=n||Math.max(h.y,u.y,f.y,m.y)<=o||Math.min(h.y,u.y,f.y,m.y)>=l))return!1;const y=g*(u.y-h.y),x=g*(h.x-u.x),a=y*r+x*o,c=y*n+x*o,d=y*r+x*l,p=y*n+x*l;if(Math.max(a,c,d,p)<=y*h.x+x*h.y||Math.min(a,c,d,p)>=y*m.x+x*m.y)return!1;const _=g*(h.y-f.y),b=g*(f.x-h.x),v=_*r+b*o,w=_*n+b*o,S=_*r+b*l,T=_*n+b*l;return!(Math.max(v,w,S,T)<=_*h.x+b*h.y||Math.min(v,w,S,T)>=_*m.x+b*m.y)}pad(t=0,e=t){return this.x-=t,this.y-=e,this.width+=t*2,this.height+=e*2,this}fit(t){const e=Math.max(this.x,t.x),r=Math.min(this.x+this.width,t.x+t.width),n=Math.max(this.y,t.y),o=Math.min(this.y+this.height,t.y+t.height);return this.x=e,this.width=Math.max(r-e,0),this.y=n,this.height=Math.max(o-n,0),this}ceil(t=1,e=.001){const r=Math.ceil((this.x+this.width-e)*t)/t,n=Math.ceil((this.y+this.height-e)*t)/t;return this.x=Math.floor((this.x+e)*t)/t,this.y=Math.floor((this.y+e)*t)/t,this.width=r-this.x,this.height=n-this.y,this}scale(t,e=t){return this.x*=t,this.y*=e,this.width*=t,this.height*=e,this}enlarge(t){const e=Math.min(this.x,t.x),r=Math.max(this.x+this.width,t.x+t.width),n=Math.min(this.y,t.y),o=Math.max(this.y+this.height,t.y+t.height);return this.x=e,this.width=r-e,this.y=n,this.height=o-n,this}getBounds(t){return t||(t=new G),t.copyFrom(this),t}containsRect(t){if(this.width<=0||this.height<=0)return!1;const e=t.x,r=t.y,n=t.x+t.width,o=t.y+t.height;return e>=this.x&&e<this.x+this.width&&r>=this.y&&r<this.y+this.height&&n>=this.x&&n<this.x+this.width&&o>=this.y&&o<this.y+this.height}set(t,e,r,n){return this.x=t,this.y=e,this.width=r,this.height=n,this}toString(){return`[pixi.js/math:Rectangle x=${this.x} y=${this.y} width=${this.width} height=${this.height}]`}}const ys={default:-1};function et(s="default"){return ys[s]===void 0&&(ys[s]=-1),++ys[s]}const qo=new Set,$="8.0.0",Nf="8.3.4",Le={quiet:!1,noColor:!1},z=(s,t,e=3)=>{if(Le.quiet||qo.has(t))return;let r=new Error().stack;const n=`${t}
|
|
65
|
+
Deprecated since v${s}`,o=typeof console.groupCollapsed=="function"&&!Le.noColor;typeof r>"u"?console.warn("PixiJS Deprecation Warning: ",n):(r=r.split(`
|
|
66
66
|
`).splice(e).join(`
|
|
67
|
-
`),a?(console.groupCollapsed("%cPixiJS Deprecation Warning: %c%s","color:#614108;background:#fffbe6","font-weight:normal;color:#614108;background:#fffbe6",n),console.warn(r),console.groupEnd()):(console.warn("PixiJS Deprecation Warning: ",n),console.warn(r))),Ya.add(t)};Object.defineProperties(z,{quiet:{get:()=>Oe.quiet,set:s=>{Oe.quiet=s},enumerable:!0,configurable:!1},noColor:{get:()=>Oe.noColor,set:s=>{Oe.noColor=s},enumerable:!0,configurable:!1}});const Xa=()=>{};function Le(s){return s+=s===0?1:0,--s,s|=s>>>1,s|=s>>>2,s|=s>>>4,s|=s>>>8,s|=s>>>16,s+1}function $a(s){return!(s&s-1)&&!!s}function Ka(s){const t={};for(const e in s)s[e]!==void 0&&(t[e]=s[e]);return t}const ja=Object.create(null);function Rf(s){const t=ja[s];return t===void 0&&(ja[s]=et("resource")),t}const qa=class Yu extends Tt{constructor(t={}){super(),this._resourceType="textureSampler",this._touched=0,this._maxAnisotropy=1,this.destroyed=!1,t={...Yu.defaultOptions,...t},this.addressMode=t.addressMode,this.addressModeU=t.addressModeU??this.addressModeU,this.addressModeV=t.addressModeV??this.addressModeV,this.addressModeW=t.addressModeW??this.addressModeW,this.scaleMode=t.scaleMode,this.magFilter=t.magFilter??this.magFilter,this.minFilter=t.minFilter??this.minFilter,this.mipmapFilter=t.mipmapFilter??this.mipmapFilter,this.lodMinClamp=t.lodMinClamp,this.lodMaxClamp=t.lodMaxClamp,this.compare=t.compare,this.maxAnisotropy=t.maxAnisotropy??1}set addressMode(t){this.addressModeU=t,this.addressModeV=t,this.addressModeW=t}get addressMode(){return this.addressModeU}set wrapMode(t){z($,"TextureStyle.wrapMode is now TextureStyle.addressMode"),this.addressMode=t}get wrapMode(){return this.addressMode}set scaleMode(t){this.magFilter=t,this.minFilter=t,this.mipmapFilter=t}get scaleMode(){return this.magFilter}set maxAnisotropy(t){this._maxAnisotropy=Math.min(t,16),this._maxAnisotropy>1&&(this.scaleMode="linear")}get maxAnisotropy(){return this._maxAnisotropy}get _resourceId(){return this._sharedResourceId||this._generateResourceId()}update(){this.emit("change",this),this._sharedResourceId=null}_generateResourceId(){const t=`${this.addressModeU}-${this.addressModeV}-${this.addressModeW}-${this.magFilter}-${this.minFilter}-${this.mipmapFilter}-${this.lodMinClamp}-${this.lodMaxClamp}-${this.compare}-${this._maxAnisotropy}`;return this._sharedResourceId=Rf(t),this._resourceId}destroy(){this.destroyed=!0,this.emit("destroy",this),this.emit("change",this),this.removeAllListeners()}};qa.defaultOptions={addressMode:"clamp-to-edge",scaleMode:"linear"};let Kt=qa;const Za=class Xu extends Tt{constructor(t={}){super(),this.options=t,this.uid=et("textureSource"),this._resourceType="textureSource",this._resourceId=et("resource"),this.uploadMethodId="unknown",this._resolution=1,this.pixelWidth=1,this.pixelHeight=1,this.width=1,this.height=1,this.sampleCount=1,this.mipLevelCount=1,this.autoGenerateMipmaps=!1,this.format="rgba8unorm",this.dimension="2d",this.antialias=!1,this._touched=0,this._batchTick=-1,this._textureBindLocation=-1,t={...Xu.defaultOptions,...t},this.label=t.label??"",this.resource=t.resource,this.autoGarbageCollect=t.autoGarbageCollect,this._resolution=t.resolution,t.width?this.pixelWidth=t.width*this._resolution:this.pixelWidth=this.resource?this.resourceWidth??1:1,t.height?this.pixelHeight=t.height*this._resolution:this.pixelHeight=this.resource?this.resourceHeight??1:1,this.width=this.pixelWidth/this._resolution,this.height=this.pixelHeight/this._resolution,this.format=t.format,this.dimension=t.dimensions,this.mipLevelCount=t.mipLevelCount,this.autoGenerateMipmaps=t.autoGenerateMipmaps,this.sampleCount=t.sampleCount,this.antialias=t.antialias,this.alphaMode=t.alphaMode,this.style=new Kt(Ka(t)),this.destroyed=!1,this._refreshPOT()}get source(){return this}get style(){return this._style}set style(t){this.style!==t&&(this._style?.off("change",this._onStyleChange,this),this._style=t,this._style?.on("change",this._onStyleChange,this),this._onStyleChange())}set maxAnisotropy(t){this._style.maxAnisotropy=t}get maxAnisotropy(){return this._style.maxAnisotropy}get addressMode(){return this._style.addressMode}set addressMode(t){this._style.addressMode=t}get repeatMode(){return this._style.addressMode}set repeatMode(t){this._style.addressMode=t}get magFilter(){return this._style.magFilter}set magFilter(t){this._style.magFilter=t}get minFilter(){return this._style.minFilter}set minFilter(t){this._style.minFilter=t}get mipmapFilter(){return this._style.mipmapFilter}set mipmapFilter(t){this._style.mipmapFilter=t}get lodMinClamp(){return this._style.lodMinClamp}set lodMinClamp(t){this._style.lodMinClamp=t}get lodMaxClamp(){return this._style.lodMaxClamp}set lodMaxClamp(t){this._style.lodMaxClamp=t}_onStyleChange(){this.emit("styleChange",this)}update(){if(this.resource){const t=this._resolution;if(this.resize(this.resourceWidth/t,this.resourceHeight/t))return}this.emit("update",this)}destroy(){this.destroyed=!0,this.emit("destroy",this),this.emit("change",this),this._style&&(this._style.destroy(),this._style=null),this.uploadMethodId=null,this.resource=null,this.removeAllListeners()}unload(){this._resourceId=et("resource"),this.emit("change",this),this.emit("unload",this)}get resourceWidth(){const{resource:t}=this;return t.naturalWidth||t.videoWidth||t.displayWidth||t.width}get resourceHeight(){const{resource:t}=this;return t.naturalHeight||t.videoHeight||t.displayHeight||t.height}get resolution(){return this._resolution}set resolution(t){this._resolution!==t&&(this._resolution=t,this.width=this.pixelWidth/t,this.height=this.pixelHeight/t)}resize(t,e,r){r||(r=this._resolution),t||(t=this.width),e||(e=this.height);const n=Math.round(t*r),a=Math.round(e*r);return this.width=n/r,this.height=a/r,this._resolution=r,this.pixelWidth===n&&this.pixelHeight===a?!1:(this._refreshPOT(),this.pixelWidth=n,this.pixelHeight=a,this.emit("resize",this),this._resourceId=et("resource"),this.emit("change",this),!0)}updateMipmaps(){this.autoGenerateMipmaps&&this.mipLevelCount>1&&this.emit("updateMipmaps",this)}set wrapMode(t){this._style.wrapMode=t}get wrapMode(){return this._style.wrapMode}set scaleMode(t){this._style.scaleMode=t}get scaleMode(){return this._style.scaleMode}_refreshPOT(){this.isPowerOfTwo=$a(this.pixelWidth)&&$a(this.pixelHeight)}static test(t){throw new Error("Unimplemented")}};Za.defaultOptions={resolution:1,format:"bgra8unorm",alphaMode:"premultiply-alpha-on-upload",dimensions:"2d",mipLevelCount:1,autoGenerateMipmaps:!1,sampleCount:1,antialias:!1,autoGarbageCollect:!1};let ht=Za;class gs extends ht{constructor(t){const e=t.resource||new Float32Array(t.width*t.height*4);let r=t.format;r||(e instanceof Float32Array?r="rgba32float":e instanceof Int32Array||e instanceof Uint32Array?r="rgba32uint":e instanceof Int16Array||e instanceof Uint16Array?r="rgba16uint":(e instanceof Int8Array,r="bgra8unorm")),super({...t,resource:e,format:r}),this.uploadMethodId="buffer"}static test(t){return t instanceof Int8Array||t instanceof Uint8Array||t instanceof Uint8ClampedArray||t instanceof Int16Array||t instanceof Uint16Array||t instanceof Int32Array||t instanceof Uint32Array||t instanceof Float32Array}}gs.extension=C.TextureSource;const Qa=new k;class Ja{constructor(t,e){this.mapCoord=new k,this.uClampFrame=new Float32Array(4),this.uClampOffset=new Float32Array(2),this._textureID=-1,this._updateID=0,this.clampOffset=0,typeof e>"u"?this.clampMargin=t.width<10?0:.5:this.clampMargin=e,this.isSimple=!1,this.texture=t}get texture(){return this._texture}set texture(t){this.texture!==t&&(this._texture?.removeListener("update",this.update,this),this._texture=t,this._texture.addListener("update",this.update,this),this.update())}multiplyUvs(t,e){e===void 0&&(e=t);const r=this.mapCoord;for(let n=0;n<t.length;n+=2){const a=t[n],l=t[n+1];e[n]=a*r.a+l*r.c+r.tx,e[n+1]=a*r.b+l*r.d+r.ty}return e}update(){const t=this._texture;this._updateID++;const e=t.uvs;this.mapCoord.set(e.x1-e.x0,e.y1-e.y0,e.x3-e.x0,e.y3-e.y0,e.x0,e.y0);const r=t.orig,n=t.trim;n&&(Qa.set(r.width/n.width,0,0,r.height/n.height,-n.x/n.width,-n.y/n.height),this.mapCoord.append(Qa));const a=t.source,l=this.uClampFrame,h=this.clampMargin/a._resolution,d=this.clampOffset/a._resolution;return l[0]=(t.frame.x+h+d)/a.width,l[1]=(t.frame.y+h+d)/a.height,l[2]=(t.frame.x+t.frame.width-h+d)/a.width,l[3]=(t.frame.y+t.frame.height-h+d)/a.height,this.uClampOffset[0]=this.clampOffset/a.pixelWidth,this.uClampOffset[1]=this.clampOffset/a.pixelHeight,this.isSimple=t.frame.width===a.width&&t.frame.height===a.height&&t.rotate===0,!0}}class M extends Tt{constructor({source:t,label:e,frame:r,orig:n,trim:a,defaultAnchor:l,defaultBorders:h,rotate:d,dynamic:f}={}){if(super(),this.uid=et("texture"),this.uvs={x0:0,y0:0,x1:0,y1:0,x2:0,y2:0,x3:0,y3:0},this.frame=new L,this.noFrame=!1,this.dynamic=!1,this.isTexture=!0,this.label=e,this.source=t?.source??new ht,this.noFrame=!r,r)this.frame.copyFrom(r);else{const{width:m,height:g}=this._source;this.frame.width=m,this.frame.height=g}this.orig=n||this.frame,this.trim=a,this.rotate=d??0,this.defaultAnchor=l,this.defaultBorders=h,this.destroyed=!1,this.dynamic=f||!1,this.updateUvs()}set source(t){this._source&&this._source.off("resize",this.update,this),this._source=t,t.on("resize",this.update,this),this.emit("update",this)}get source(){return this._source}get textureMatrix(){return this._textureMatrix||(this._textureMatrix=new Ja(this)),this._textureMatrix}get width(){return this.orig.width}get height(){return this.orig.height}updateUvs(){const{uvs:t,frame:e}=this,{width:r,height:n}=this._source,a=e.x/r,l=e.y/n,h=e.width/r,d=e.height/n;let f=this.rotate;if(f){const m=h/2,g=d/2,y=a+m,x=l+g;f=Z.add(f,Z.NW),t.x0=y+m*Z.uX(f),t.y0=x+g*Z.uY(f),f=Z.add(f,2),t.x1=y+m*Z.uX(f),t.y1=x+g*Z.uY(f),f=Z.add(f,2),t.x2=y+m*Z.uX(f),t.y2=x+g*Z.uY(f),f=Z.add(f,2),t.x3=y+m*Z.uX(f),t.y3=x+g*Z.uY(f)}else t.x0=a,t.y0=l,t.x1=a+h,t.y1=l,t.x2=a+h,t.y2=l+d,t.x3=a,t.y3=l+d}destroy(t=!1){this._source&&(this._source.off("resize",this.update,this),t&&(this._source.destroy(),this._source=null)),this._textureMatrix=null,this.destroyed=!0,this.emit("destroy",this),this.removeAllListeners()}update(){this.noFrame&&(this.frame.width=this._source.width,this.frame.height=this._source.height),this.updateUvs(),this.emit("update",this)}get baseTexture(){return z($,"Texture.baseTexture is now Texture.source"),this._source}}M.EMPTY=new M({label:"EMPTY",source:new ht({label:"EMPTY"})}),M.EMPTY.destroy=Xa,M.WHITE=new M({source:new gs({resource:new Uint8Array([255,255,255,255]),width:1,height:1,alphaMode:"premultiply-alpha-on-upload",label:"WHITE"}),label:"WHITE"}),M.WHITE.destroy=Xa;function to(s,t,e){const{width:r,height:n}=e.orig,a=e.trim;if(a){const l=a.width,h=a.height;s.minX=a.x-t._x*r,s.maxX=s.minX+l,s.minY=a.y-t._y*n,s.maxY=s.minY+h}else s.minX=-t._x*r,s.maxX=s.minX+r,s.minY=-t._y*n,s.maxY=s.minY+n}const eo=new k;class dt{constructor(t=1/0,e=1/0,r=-1/0,n=-1/0){this.minX=1/0,this.minY=1/0,this.maxX=-1/0,this.maxY=-1/0,this.matrix=eo,this.minX=t,this.minY=e,this.maxX=r,this.maxY=n}isEmpty(){return this.minX>this.maxX||this.minY>this.maxY}get rectangle(){this._rectangle||(this._rectangle=new L);const t=this._rectangle;return this.minX>this.maxX||this.minY>this.maxY?(t.x=0,t.y=0,t.width=0,t.height=0):t.copyFromBounds(this),t}clear(){return this.minX=1/0,this.minY=1/0,this.maxX=-1/0,this.maxY=-1/0,this.matrix=eo,this}set(t,e,r,n){this.minX=t,this.minY=e,this.maxX=r,this.maxY=n}addFrame(t,e,r,n,a){a||(a=this.matrix);const l=a.a,h=a.b,d=a.c,f=a.d,m=a.tx,g=a.ty;let y=this.minX,x=this.minY,o=this.maxX,c=this.maxY,u=l*t+d*e+m,p=h*t+f*e+g;u<y&&(y=u),p<x&&(x=p),u>o&&(o=u),p>c&&(c=p),u=l*r+d*e+m,p=h*r+f*e+g,u<y&&(y=u),p<x&&(x=p),u>o&&(o=u),p>c&&(c=p),u=l*t+d*n+m,p=h*t+f*n+g,u<y&&(y=u),p<x&&(x=p),u>o&&(o=u),p>c&&(c=p),u=l*r+d*n+m,p=h*r+f*n+g,u<y&&(y=u),p<x&&(x=p),u>o&&(o=u),p>c&&(c=p),this.minX=y,this.minY=x,this.maxX=o,this.maxY=c}addRect(t,e){this.addFrame(t.x,t.y,t.x+t.width,t.y+t.height,e)}addBounds(t,e){this.addFrame(t.minX,t.minY,t.maxX,t.maxY,e)}addBoundsMask(t){this.minX=this.minX>t.minX?this.minX:t.minX,this.minY=this.minY>t.minY?this.minY:t.minY,this.maxX=this.maxX<t.maxX?this.maxX:t.maxX,this.maxY=this.maxY<t.maxY?this.maxY:t.maxY}applyMatrix(t){const e=this.minX,r=this.minY,n=this.maxX,a=this.maxY,{a:l,b:h,c:d,d:f,tx:m,ty:g}=t;let y=l*e+d*r+m,x=h*e+f*r+g;this.minX=y,this.minY=x,this.maxX=y,this.maxY=x,y=l*n+d*r+m,x=h*n+f*r+g,this.minX=y<this.minX?y:this.minX,this.minY=x<this.minY?x:this.minY,this.maxX=y>this.maxX?y:this.maxX,this.maxY=x>this.maxY?x:this.maxY,y=l*e+d*a+m,x=h*e+f*a+g,this.minX=y<this.minX?y:this.minX,this.minY=x<this.minY?x:this.minY,this.maxX=y>this.maxX?y:this.maxX,this.maxY=x>this.maxY?x:this.maxY,y=l*n+d*a+m,x=h*n+f*a+g,this.minX=y<this.minX?y:this.minX,this.minY=x<this.minY?x:this.minY,this.maxX=y>this.maxX?y:this.maxX,this.maxY=x>this.maxY?x:this.maxY}fit(t){return this.minX<t.left&&(this.minX=t.left),this.maxX>t.right&&(this.maxX=t.right),this.minY<t.top&&(this.minY=t.top),this.maxY>t.bottom&&(this.maxY=t.bottom),this}fitBounds(t,e,r,n){return this.minX<t&&(this.minX=t),this.maxX>e&&(this.maxX=e),this.minY<r&&(this.minY=r),this.maxY>n&&(this.maxY=n),this}pad(t,e=t){return this.minX-=t,this.maxX+=t,this.minY-=e,this.maxY+=e,this}ceil(){return this.minX=Math.floor(this.minX),this.minY=Math.floor(this.minY),this.maxX=Math.ceil(this.maxX),this.maxY=Math.ceil(this.maxY),this}clone(){return new dt(this.minX,this.minY,this.maxX,this.maxY)}scale(t,e=t){return this.minX*=t,this.minY*=e,this.maxX*=t,this.maxY*=e,this}get x(){return this.minX}set x(t){const e=this.maxX-this.minX;this.minX=t,this.maxX=t+e}get y(){return this.minY}set y(t){const e=this.maxY-this.minY;this.minY=t,this.maxY=t+e}get width(){return this.maxX-this.minX}set width(t){this.maxX=this.minX+t}get height(){return this.maxY-this.minY}set height(t){this.maxY=this.minY+t}get left(){return this.minX}get right(){return this.maxX}get top(){return this.minY}get bottom(){return this.maxY}get isPositive(){return this.maxX-this.minX>0&&this.maxY-this.minY>0}get isValid(){return this.minX+this.minY!==1/0}addVertexData(t,e,r,n){let a=this.minX,l=this.minY,h=this.maxX,d=this.maxY;n||(n=this.matrix);const f=n.a,m=n.b,g=n.c,y=n.d,x=n.tx,o=n.ty;for(let c=e;c<r;c+=2){const u=t[c],p=t[c+1],_=f*u+g*p+x,b=m*u+y*p+o;a=_<a?_:a,l=b<l?b:l,h=_>h?_:h,d=b>d?b:d}this.minX=a,this.minY=l,this.maxX=h,this.maxY=d}containsPoint(t,e){return this.minX<=t&&this.minY<=e&&this.maxX>=t&&this.maxY>=e}toString(){return`[pixi.js:Bounds minX=${this.minX} minY=${this.minY} maxX=${this.maxX} maxY=${this.maxY} width=${this.width} height=${this.height}]`}copyFrom(t){return this.minX=t.minX,this.minY=t.minY,this.maxX=t.maxX,this.maxY=t.maxY,this}}var If={grad:.9,turn:360,rad:360/(2*Math.PI)},Qt=function(s){return typeof s=="string"?s.length>0:typeof s=="number"},lt=function(s,t,e){return t===void 0&&(t=0),e===void 0&&(e=Math.pow(10,t)),Math.round(e*s)/e+0},Rt=function(s,t,e){return t===void 0&&(t=0),e===void 0&&(e=1),s>e?e:s>t?s:t},io=function(s){return(s=isFinite(s)?s%360:0)>0?s:s+360},ro=function(s){return{r:Rt(s.r,0,255),g:Rt(s.g,0,255),b:Rt(s.b,0,255),a:Rt(s.a)}},_s=function(s){return{r:lt(s.r),g:lt(s.g),b:lt(s.b),a:lt(s.a,3)}},Ff=/^#([0-9a-f]{3,8})$/i,hr=function(s){var t=s.toString(16);return t.length<2?"0"+t:t},so=function(s){var t=s.r,e=s.g,r=s.b,n=s.a,a=Math.max(t,e,r),l=a-Math.min(t,e,r),h=l?a===t?(e-r)/l:a===e?2+(r-t)/l:4+(t-e)/l:0;return{h:60*(h<0?h+6:h),s:a?l/a*100:0,v:a/255*100,a:n}},no=function(s){var t=s.h,e=s.s,r=s.v,n=s.a;t=t/360*6,e/=100,r/=100;var a=Math.floor(t),l=r*(1-e),h=r*(1-(t-a)*e),d=r*(1-(1-t+a)*e),f=a%6;return{r:255*[r,h,l,l,d,r][f],g:255*[d,r,r,h,l,l][f],b:255*[l,l,d,r,r,h][f],a:n}},ao=function(s){return{h:io(s.h),s:Rt(s.s,0,100),l:Rt(s.l,0,100),a:Rt(s.a)}},oo=function(s){return{h:lt(s.h),s:lt(s.s),l:lt(s.l),a:lt(s.a,3)}},ho=function(s){return no((e=(t=s).s,{h:t.h,s:(e*=((r=t.l)<50?r:100-r)/100)>0?2*e/(r+e)*100:0,v:r+e,a:t.a}));var t,e,r},ci=function(s){return{h:(t=so(s)).h,s:(n=(200-(e=t.s))*(r=t.v)/100)>0&&n<200?e*r/100/(n<=100?n:200-n)*100:0,l:n/2,a:t.a};var t,e,r,n},Df=/^hsla?\(\s*([+-]?\d*\.?\d+)(deg|rad|grad|turn)?\s*,\s*([+-]?\d*\.?\d+)%\s*,\s*([+-]?\d*\.?\d+)%\s*(?:,\s*([+-]?\d*\.?\d+)(%)?\s*)?\)$/i,Gf=/^hsla?\(\s*([+-]?\d*\.?\d+)(deg|rad|grad|turn)?\s+([+-]?\d*\.?\d+)%\s+([+-]?\d*\.?\d+)%\s*(?:\/\s*([+-]?\d*\.?\d+)(%)?\s*)?\)$/i,Of=/^rgba?\(\s*([+-]?\d*\.?\d+)(%)?\s*,\s*([+-]?\d*\.?\d+)(%)?\s*,\s*([+-]?\d*\.?\d+)(%)?\s*(?:,\s*([+-]?\d*\.?\d+)(%)?\s*)?\)$/i,Lf=/^rgba?\(\s*([+-]?\d*\.?\d+)(%)?\s+([+-]?\d*\.?\d+)(%)?\s+([+-]?\d*\.?\d+)(%)?\s*(?:\/\s*([+-]?\d*\.?\d+)(%)?\s*)?\)$/i,ys={string:[[function(s){var t=Ff.exec(s);return t?(s=t[1]).length<=4?{r:parseInt(s[0]+s[0],16),g:parseInt(s[1]+s[1],16),b:parseInt(s[2]+s[2],16),a:s.length===4?lt(parseInt(s[3]+s[3],16)/255,2):1}:s.length===6||s.length===8?{r:parseInt(s.substr(0,2),16),g:parseInt(s.substr(2,2),16),b:parseInt(s.substr(4,2),16),a:s.length===8?lt(parseInt(s.substr(6,2),16)/255,2):1}:null:null},"hex"],[function(s){var t=Of.exec(s)||Lf.exec(s);return t?t[2]!==t[4]||t[4]!==t[6]?null:ro({r:Number(t[1])/(t[2]?100/255:1),g:Number(t[3])/(t[4]?100/255:1),b:Number(t[5])/(t[6]?100/255:1),a:t[7]===void 0?1:Number(t[7])/(t[8]?100:1)}):null},"rgb"],[function(s){var t=Df.exec(s)||Gf.exec(s);if(!t)return null;var e,r,n=ao({h:(e=t[1],r=t[2],r===void 0&&(r="deg"),Number(e)*(If[r]||1)),s:Number(t[3]),l:Number(t[4]),a:t[5]===void 0?1:Number(t[5])/(t[6]?100:1)});return ho(n)},"hsl"]],object:[[function(s){var t=s.r,e=s.g,r=s.b,n=s.a,a=n===void 0?1:n;return Qt(t)&&Qt(e)&&Qt(r)?ro({r:Number(t),g:Number(e),b:Number(r),a:Number(a)}):null},"rgb"],[function(s){var t=s.h,e=s.s,r=s.l,n=s.a,a=n===void 0?1:n;if(!Qt(t)||!Qt(e)||!Qt(r))return null;var l=ao({h:Number(t),s:Number(e),l:Number(r),a:Number(a)});return ho(l)},"hsl"],[function(s){var t=s.h,e=s.s,r=s.v,n=s.a,a=n===void 0?1:n;if(!Qt(t)||!Qt(e)||!Qt(r))return null;var l=(function(h){return{h:io(h.h),s:Rt(h.s,0,100),v:Rt(h.v,0,100),a:Rt(h.a)}})({h:Number(t),s:Number(e),v:Number(r),a:Number(a)});return no(l)},"hsv"]]},lo=function(s,t){for(var e=0;e<t.length;e++){var r=t[e][0](s);if(r)return[r,t[e][1]]}return[null,void 0]},zf=function(s){return typeof s=="string"?lo(s.trim(),ys.string):typeof s=="object"&&s!==null?lo(s,ys.object):[null,void 0]},xs=function(s,t){var e=ci(s);return{h:e.h,s:Rt(e.s+100*t,0,100),l:e.l,a:e.a}},bs=function(s){return(299*s.r+587*s.g+114*s.b)/1e3/255},co=function(s,t){var e=ci(s);return{h:e.h,s:e.s,l:Rt(e.l+100*t,0,100),a:e.a}},vs=(function(){function s(t){this.parsed=zf(t)[0],this.rgba=this.parsed||{r:0,g:0,b:0,a:1}}return s.prototype.isValid=function(){return this.parsed!==null},s.prototype.brightness=function(){return lt(bs(this.rgba),2)},s.prototype.isDark=function(){return bs(this.rgba)<.5},s.prototype.isLight=function(){return bs(this.rgba)>=.5},s.prototype.toHex=function(){return t=_s(this.rgba),e=t.r,r=t.g,n=t.b,l=(a=t.a)<1?hr(lt(255*a)):"","#"+hr(e)+hr(r)+hr(n)+l;var t,e,r,n,a,l},s.prototype.toRgb=function(){return _s(this.rgba)},s.prototype.toRgbString=function(){return t=_s(this.rgba),e=t.r,r=t.g,n=t.b,(a=t.a)<1?"rgba("+e+", "+r+", "+n+", "+a+")":"rgb("+e+", "+r+", "+n+")";var t,e,r,n,a},s.prototype.toHsl=function(){return oo(ci(this.rgba))},s.prototype.toHslString=function(){return t=oo(ci(this.rgba)),e=t.h,r=t.s,n=t.l,(a=t.a)<1?"hsla("+e+", "+r+"%, "+n+"%, "+a+")":"hsl("+e+", "+r+"%, "+n+"%)";var t,e,r,n,a},s.prototype.toHsv=function(){return t=so(this.rgba),{h:lt(t.h),s:lt(t.s),v:lt(t.v),a:lt(t.a,3)};var t},s.prototype.invert=function(){return jt({r:255-(t=this.rgba).r,g:255-t.g,b:255-t.b,a:t.a});var t},s.prototype.saturate=function(t){return t===void 0&&(t=.1),jt(xs(this.rgba,t))},s.prototype.desaturate=function(t){return t===void 0&&(t=.1),jt(xs(this.rgba,-t))},s.prototype.grayscale=function(){return jt(xs(this.rgba,-1))},s.prototype.lighten=function(t){return t===void 0&&(t=.1),jt(co(this.rgba,t))},s.prototype.darken=function(t){return t===void 0&&(t=.1),jt(co(this.rgba,-t))},s.prototype.rotate=function(t){return t===void 0&&(t=15),this.hue(this.hue()+t)},s.prototype.alpha=function(t){return typeof t=="number"?jt({r:(e=this.rgba).r,g:e.g,b:e.b,a:t}):lt(this.rgba.a,3);var e},s.prototype.hue=function(t){var e=ci(this.rgba);return typeof t=="number"?jt({h:t,s:e.s,l:e.l,a:e.a}):lt(e.h)},s.prototype.isEqual=function(t){return this.toHex()===jt(t).toHex()},s})(),jt=function(s){return s instanceof vs?s:new vs(s)},uo=[],Nf=function(s){s.forEach(function(t){uo.indexOf(t)<0&&(t(vs,ys),uo.push(t))})};function Hf(s,t){var e={white:"#ffffff",bisque:"#ffe4c4",blue:"#0000ff",cadetblue:"#5f9ea0",chartreuse:"#7fff00",chocolate:"#d2691e",coral:"#ff7f50",antiquewhite:"#faebd7",aqua:"#00ffff",azure:"#f0ffff",whitesmoke:"#f5f5f5",papayawhip:"#ffefd5",plum:"#dda0dd",blanchedalmond:"#ffebcd",black:"#000000",gold:"#ffd700",goldenrod:"#daa520",gainsboro:"#dcdcdc",cornsilk:"#fff8dc",cornflowerblue:"#6495ed",burlywood:"#deb887",aquamarine:"#7fffd4",beige:"#f5f5dc",crimson:"#dc143c",cyan:"#00ffff",darkblue:"#00008b",darkcyan:"#008b8b",darkgoldenrod:"#b8860b",darkkhaki:"#bdb76b",darkgray:"#a9a9a9",darkgreen:"#006400",darkgrey:"#a9a9a9",peachpuff:"#ffdab9",darkmagenta:"#8b008b",darkred:"#8b0000",darkorchid:"#9932cc",darkorange:"#ff8c00",darkslateblue:"#483d8b",gray:"#808080",darkslategray:"#2f4f4f",darkslategrey:"#2f4f4f",deeppink:"#ff1493",deepskyblue:"#00bfff",wheat:"#f5deb3",firebrick:"#b22222",floralwhite:"#fffaf0",ghostwhite:"#f8f8ff",darkviolet:"#9400d3",magenta:"#ff00ff",green:"#008000",dodgerblue:"#1e90ff",grey:"#808080",honeydew:"#f0fff0",hotpink:"#ff69b4",blueviolet:"#8a2be2",forestgreen:"#228b22",lawngreen:"#7cfc00",indianred:"#cd5c5c",indigo:"#4b0082",fuchsia:"#ff00ff",brown:"#a52a2a",maroon:"#800000",mediumblue:"#0000cd",lightcoral:"#f08080",darkturquoise:"#00ced1",lightcyan:"#e0ffff",ivory:"#fffff0",lightyellow:"#ffffe0",lightsalmon:"#ffa07a",lightseagreen:"#20b2aa",linen:"#faf0e6",mediumaquamarine:"#66cdaa",lemonchiffon:"#fffacd",lime:"#00ff00",khaki:"#f0e68c",mediumseagreen:"#3cb371",limegreen:"#32cd32",mediumspringgreen:"#00fa9a",lightskyblue:"#87cefa",lightblue:"#add8e6",midnightblue:"#191970",lightpink:"#ffb6c1",mistyrose:"#ffe4e1",moccasin:"#ffe4b5",mintcream:"#f5fffa",lightslategray:"#778899",lightslategrey:"#778899",navajowhite:"#ffdead",navy:"#000080",mediumvioletred:"#c71585",powderblue:"#b0e0e6",palegoldenrod:"#eee8aa",oldlace:"#fdf5e6",paleturquoise:"#afeeee",mediumturquoise:"#48d1cc",mediumorchid:"#ba55d3",rebeccapurple:"#663399",lightsteelblue:"#b0c4de",mediumslateblue:"#7b68ee",thistle:"#d8bfd8",tan:"#d2b48c",orchid:"#da70d6",mediumpurple:"#9370db",purple:"#800080",pink:"#ffc0cb",skyblue:"#87ceeb",springgreen:"#00ff7f",palegreen:"#98fb98",red:"#ff0000",yellow:"#ffff00",slateblue:"#6a5acd",lavenderblush:"#fff0f5",peru:"#cd853f",palevioletred:"#db7093",violet:"#ee82ee",teal:"#008080",slategray:"#708090",slategrey:"#708090",aliceblue:"#f0f8ff",darkseagreen:"#8fbc8f",darkolivegreen:"#556b2f",greenyellow:"#adff2f",seagreen:"#2e8b57",seashell:"#fff5ee",tomato:"#ff6347",silver:"#c0c0c0",sienna:"#a0522d",lavender:"#e6e6fa",lightgreen:"#90ee90",orange:"#ffa500",orangered:"#ff4500",steelblue:"#4682b4",royalblue:"#4169e1",turquoise:"#40e0d0",yellowgreen:"#9acd32",salmon:"#fa8072",saddlebrown:"#8b4513",sandybrown:"#f4a460",rosybrown:"#bc8f8f",darksalmon:"#e9967a",lightgoldenrodyellow:"#fafad2",snow:"#fffafa",lightgrey:"#d3d3d3",lightgray:"#d3d3d3",dimgray:"#696969",dimgrey:"#696969",olivedrab:"#6b8e23",olive:"#808000"},r={};for(var n in e)r[e[n]]=n;var a={};s.prototype.toName=function(l){if(!(this.rgba.a||this.rgba.r||this.rgba.g||this.rgba.b))return"transparent";var h,d,f=r[this.toHex()];if(f)return f;if(l?.closest){var m=this.toRgb(),g=1/0,y="black";if(!a.length)for(var x in e)a[x]=new s(e[x]).toRgb();for(var o in e){var c=(h=m,d=a[o],Math.pow(h.r-d.r,2)+Math.pow(h.g-d.g,2)+Math.pow(h.b-d.b,2));c<g&&(g=c,y=o)}return y}},t.string.push([function(l){var h=l.toLowerCase(),d=h==="transparent"?"#0000":e[h];return d?new s(d).toRgb():null},"name"])}Nf([Hf]);const ze=class Ki{constructor(t=16777215){this._value=null,this._components=new Float32Array(4),this._components.fill(1),this._int=16777215,this.value=t}get red(){return this._components[0]}get green(){return this._components[1]}get blue(){return this._components[2]}get alpha(){return this._components[3]}setValue(t){return this.value=t,this}set value(t){if(t instanceof Ki)this._value=this._cloneSource(t._value),this._int=t._int,this._components.set(t._components);else{if(t===null)throw new Error("Cannot set Color#value to null");(this._value===null||!this._isSourceEqual(this._value,t))&&(this._value=this._cloneSource(t),this._normalize(this._value))}}get value(){return this._value}_cloneSource(t){return typeof t=="string"||typeof t=="number"||t instanceof Number||t===null?t:Array.isArray(t)||ArrayBuffer.isView(t)?t.slice(0):typeof t=="object"&&t!==null?{...t}:t}_isSourceEqual(t,e){const r=typeof t;if(r!==typeof e)return!1;if(r==="number"||r==="string"||t instanceof Number)return t===e;if(Array.isArray(t)&&Array.isArray(e)||ArrayBuffer.isView(t)&&ArrayBuffer.isView(e))return t.length!==e.length?!1:t.every((a,l)=>a===e[l]);if(t!==null&&e!==null){const a=Object.keys(t),l=Object.keys(e);return a.length!==l.length?!1:a.every(h=>t[h]===e[h])}return t===e}toRgba(){const[t,e,r,n]=this._components;return{r:t,g:e,b:r,a:n}}toRgb(){const[t,e,r]=this._components;return{r:t,g:e,b:r}}toRgbaString(){const[t,e,r]=this.toUint8RgbArray();return`rgba(${t},${e},${r},${this.alpha})`}toUint8RgbArray(t){const[e,r,n]=this._components;return this._arrayRgb||(this._arrayRgb=[]),t||(t=this._arrayRgb),t[0]=Math.round(e*255),t[1]=Math.round(r*255),t[2]=Math.round(n*255),t}toArray(t){this._arrayRgba||(this._arrayRgba=[]),t||(t=this._arrayRgba);const[e,r,n,a]=this._components;return t[0]=e,t[1]=r,t[2]=n,t[3]=a,t}toRgbArray(t){this._arrayRgb||(this._arrayRgb=[]),t||(t=this._arrayRgb);const[e,r,n]=this._components;return t[0]=e,t[1]=r,t[2]=n,t}toNumber(){return this._int}toBgrNumber(){const[t,e,r]=this.toUint8RgbArray();return(r<<16)+(e<<8)+t}toLittleEndianNumber(){const t=this._int;return(t>>16)+(t&65280)+((t&255)<<16)}multiply(t){const[e,r,n,a]=Ki._temp.setValue(t)._components;return this._components[0]*=e,this._components[1]*=r,this._components[2]*=n,this._components[3]*=a,this._refreshInt(),this._value=null,this}premultiply(t,e=!0){return e&&(this._components[0]*=t,this._components[1]*=t,this._components[2]*=t),this._components[3]=t,this._refreshInt(),this._value=null,this}toPremultiplied(t,e=!0){if(t===1)return(255<<24)+this._int;if(t===0)return e?0:this._int;let r=this._int>>16&255,n=this._int>>8&255,a=this._int&255;return e&&(r=r*t+.5|0,n=n*t+.5|0,a=a*t+.5|0),(t*255<<24)+(r<<16)+(n<<8)+a}toHex(){const t=this._int.toString(16);return`#${"000000".substring(0,6-t.length)+t}`}toHexa(){const e=Math.round(this._components[3]*255).toString(16);return this.toHex()+"00".substring(0,2-e.length)+e}setAlpha(t){return this._components[3]=this._clamp(t),this}_normalize(t){let e,r,n,a;if((typeof t=="number"||t instanceof Number)&&t>=0&&t<=16777215){const l=t;e=(l>>16&255)/255,r=(l>>8&255)/255,n=(l&255)/255,a=1}else if((Array.isArray(t)||t instanceof Float32Array)&&t.length>=3&&t.length<=4)t=this._clamp(t),[e,r,n,a=1]=t;else if((t instanceof Uint8Array||t instanceof Uint8ClampedArray)&&t.length>=3&&t.length<=4)t=this._clamp(t,0,255),[e,r,n,a=255]=t,e/=255,r/=255,n/=255,a/=255;else if(typeof t=="string"||typeof t=="object"){if(typeof t=="string"){const h=Ki.HEX_PATTERN.exec(t);h&&(t=`#${h[2]}`)}const l=jt(t);l.isValid()&&({r:e,g:r,b:n,a}=l.rgba,e/=255,r/=255,n/=255)}if(e!==void 0)this._components[0]=e,this._components[1]=r,this._components[2]=n,this._components[3]=a,this._refreshInt();else throw new Error(`Unable to convert color ${t}`)}_refreshInt(){this._clamp(this._components);const[t,e,r]=this._components;this._int=(t*255<<16)+(e*255<<8)+(r*255|0)}_clamp(t,e=0,r=1){return typeof t=="number"?Math.min(Math.max(t,e),r):(t.forEach((n,a)=>{t[a]=Math.min(Math.max(n,e),r)}),t)}static isColorLike(t){return typeof t=="number"||typeof t=="string"||t instanceof Number||t instanceof Ki||Array.isArray(t)||t instanceof Uint8Array||t instanceof Uint8ClampedArray||t instanceof Float32Array||t.r!==void 0&&t.g!==void 0&&t.b!==void 0||t.r!==void 0&&t.g!==void 0&&t.b!==void 0&&t.a!==void 0||t.h!==void 0&&t.s!==void 0&&t.l!==void 0||t.h!==void 0&&t.s!==void 0&&t.l!==void 0&&t.a!==void 0||t.h!==void 0&&t.s!==void 0&&t.v!==void 0||t.h!==void 0&&t.s!==void 0&&t.v!==void 0&&t.a!==void 0}};ze.shared=new ze,ze._temp=new ze,ze.HEX_PATTERN=/^(#|0x)?(([a-f0-9]{3}){1,2}([a-f0-9]{2})?)$/i;let J=ze;const Wf={cullArea:null,cullable:!1,cullableChildren:!0};let ws=0;const fo=500;function F(...s){ws!==fo&&(ws++,ws===fo?console.warn("PixiJS Warning: too many warnings, no more warnings will be reported to the console by PixiJS."):console.warn("PixiJS Warning: ",...s))}const Ne={_registeredResources:new Set,register(s){this._registeredResources.add(s)},unregister(s){this._registeredResources.delete(s)},release(){this._registeredResources.forEach(s=>s.clear())},get registeredCount(){return this._registeredResources.size},isRegistered(s){return this._registeredResources.has(s)},reset(){this._registeredResources.clear()}};class Vf{constructor(t,e){this._pool=[],this._count=0,this._index=0,this._classType=t,e&&this.prepopulate(e)}prepopulate(t){for(let e=0;e<t;e++)this._pool[this._index++]=new this._classType;this._count+=t}get(t){let e;return this._index>0?e=this._pool[--this._index]:(e=new this._classType,this._count++),e.init?.(t),e}return(t){t.reset?.(),this._pool[this._index++]=t}get totalSize(){return this._count}get totalFree(){return this._index}get totalUsed(){return this._count-this._index}clear(){if(this._pool.length>0&&this._pool[0].destroy)for(let t=0;t<this._index;t++)this._pool[t].destroy();this._pool.length=0,this._count=0,this._index=0}}class Yf{constructor(){this._poolsByClass=new Map}prepopulate(t,e){this.getPool(t).prepopulate(e)}get(t,e){return this.getPool(t).get(e)}return(t){this.getPool(t.constructor).return(t)}getPool(t){return this._poolsByClass.has(t)||this._poolsByClass.set(t,new Vf(t)),this._poolsByClass.get(t)}stats(){const t={};return this._poolsByClass.forEach(e=>{const r=t[e._classType.name]?e._classType.name+e._classType.ID:e._classType.name;t[r]={free:e.totalFree,used:e.totalUsed,size:e.totalSize}}),t}clear(){this._poolsByClass.forEach(t=>t.clear()),this._poolsByClass.clear()}}const at=new Yf;Ne.register(at);const Xf={get isCachedAsTexture(){return!!this.renderGroup?.isCachedAsTexture},cacheAsTexture(s){typeof s=="boolean"&&s===!1?this.disableRenderGroup():(this.enableRenderGroup(),this.renderGroup.enableCacheAsTexture(s===!0?{}:s))},updateCacheTexture(){this.renderGroup?.updateCacheTexture()},get cacheAsBitmap(){return this.isCachedAsTexture},set cacheAsBitmap(s){z("v8.6.0","cacheAsBitmap is deprecated, use cacheAsTexture instead."),this.cacheAsTexture(s)}};function po(s,t,e){const r=s.length;let n;if(t>=r||e===0)return;e=t+e>r?r-t:e;const a=r-e;for(n=t;n<a;++n)s[n]=s[n+e];s.length=a}const $f={allowChildren:!0,removeChildren(s=0,t){const e=t??this.children.length,r=e-s,n=[];if(r>0&&r<=e){for(let l=e-1;l>=s;l--){const h=this.children[l];h&&(n.push(h),h.parent=null)}po(this.children,s,e);const a=this.renderGroup||this.parentRenderGroup;a&&a.removeChildren(n);for(let l=0;l<n.length;++l){const h=n[l];h.parentRenderLayer?.detach(h),this.emit("childRemoved",h,this,l),n[l].emit("removed",this)}return n.length>0&&this._didViewChangeTick++,n}else if(r===0&&this.children.length===0)return n;throw new RangeError("removeChildren: numeric values are outside the acceptable range.")},removeChildAt(s){const t=this.getChildAt(s);return this.removeChild(t)},getChildAt(s){if(s<0||s>=this.children.length)throw new Error(`getChildAt: Index (${s}) does not exist.`);return this.children[s]},setChildIndex(s,t){if(t<0||t>=this.children.length)throw new Error(`The index ${t} supplied is out of bounds ${this.children.length}`);this.getChildIndex(s),this.addChildAt(s,t)},getChildIndex(s){const t=this.children.indexOf(s);if(t===-1)throw new Error("The supplied Container must be a child of the caller");return t},addChildAt(s,t){this.allowChildren||z($,"addChildAt: Only Containers will be allowed to add children in v8.0.0");const{children:e}=this;if(t<0||t>e.length)throw new Error(`${s}addChildAt: The index ${t} supplied is out of bounds ${e.length}`);if(s.parent){const n=s.parent.children.indexOf(s);if(s.parent===this&&n===t)return s;n!==-1&&s.parent.children.splice(n,1)}t===e.length?e.push(s):e.splice(t,0,s),s.parent=this,s.didChange=!0,s._updateFlags=15;const r=this.renderGroup||this.parentRenderGroup;return r&&r.addChild(s),this.sortableChildren&&(this.sortDirty=!0),this.emit("childAdded",s,this,t),s.emit("added",this),s},swapChildren(s,t){if(s===t)return;const e=this.getChildIndex(s),r=this.getChildIndex(t);this.children[e]=t,this.children[r]=s;const n=this.renderGroup||this.parentRenderGroup;n&&(n.structureDidChange=!0),this._didContainerChangeTick++},removeFromParent(){this.parent?.removeChild(this)},reparentChild(...s){return s.length===1?this.reparentChildAt(s[0],this.children.length):(s.forEach(t=>this.reparentChildAt(t,this.children.length)),s[0])},reparentChildAt(s,t){if(s.parent===this)return this.setChildIndex(s,t),s;const e=s.worldTransform.clone();s.removeFromParent(),this.addChildAt(s,t);const r=this.worldTransform.clone();return r.invert(),e.prepend(r),s.setFromMatrix(e),s},replaceChild(s,t){s.updateLocalTransform(),this.addChildAt(t,this.getChildIndex(s)),t.setFromMatrix(s.localTransform),t.updateLocalTransform(),this.removeChild(s)}},Kf={collectRenderables(s,t,e){this.parentRenderLayer&&this.parentRenderLayer!==e||this.globalDisplayStatus<7||!this.includeInBuild||(this.sortableChildren&&this.sortChildren(),this.isSimple?this.collectRenderablesSimple(s,t,e):this.renderGroup?t.renderPipes.renderGroup.addRenderGroup(this.renderGroup,s):this.collectRenderablesWithEffects(s,t,e))},collectRenderablesSimple(s,t,e){const r=this.children,n=r.length;for(let a=0;a<n;a++)r[a].collectRenderables(s,t,e)},collectRenderablesWithEffects(s,t,e){const{renderPipes:r}=t;for(let n=0;n<this.effects.length;n++){const a=this.effects[n];r[a.pipe].push(a,this,s)}this.collectRenderablesSimple(s,t,e);for(let n=this.effects.length-1;n>=0;n--){const a=this.effects[n];r[a.pipe].pop(a,this,s)}}};class lr{constructor(){this.pipe="filter",this.priority=1}destroy(){for(let t=0;t<this.filters.length;t++)this.filters[t].destroy();this.filters=null,this.filterArea=null}}class jf{constructor(){this._effectClasses=[],this._tests=[],this._initialized=!1}init(){this._initialized||(this._initialized=!0,this._effectClasses.forEach(t=>{this.add({test:t.test,maskClass:t})}))}add(t){this._tests.push(t)}getMaskEffect(t){this._initialized||this.init();for(let e=0;e<this._tests.length;e++){const r=this._tests[e];if(r.test(t))return at.get(r.maskClass,t)}return t}returnMaskEffect(t){at.return(t)}}const Ss=new jf;D.handleByList(C.MaskEffect,Ss._effectClasses);const qf={_maskEffect:null,_maskOptions:{inverse:!1},_filterEffect:null,effects:[],_markStructureAsChanged(){const s=this.renderGroup||this.parentRenderGroup;s&&(s.structureDidChange=!0)},addEffect(s){this.effects.indexOf(s)===-1&&(this.effects.push(s),this.effects.sort((e,r)=>e.priority-r.priority),this._markStructureAsChanged(),this._updateIsSimple())},removeEffect(s){const t=this.effects.indexOf(s);t!==-1&&(this.effects.splice(t,1),this._markStructureAsChanged(),this._updateIsSimple())},set mask(s){const t=this._maskEffect;t?.mask!==s&&(t&&(this.removeEffect(t),Ss.returnMaskEffect(t),this._maskEffect=null),s!=null&&(this._maskEffect=Ss.getMaskEffect(s),this.addEffect(this._maskEffect)))},get mask(){return this._maskEffect?.mask},setMask(s){this._maskOptions={...this._maskOptions,...s},s.mask&&(this.mask=s.mask),this._markStructureAsChanged()},set filters(s){!Array.isArray(s)&&s&&(s=[s]);const t=this._filterEffect||(this._filterEffect=new lr);s=s;const e=s?.length>0,r=t.filters?.length>0,n=e!==r;s=Array.isArray(s)?s.slice(0):s,t.filters=Object.freeze(s),n&&(e?this.addEffect(t):(this.removeEffect(t),t.filters=s??null))},get filters(){return this._filterEffect?.filters},set filterArea(s){this._filterEffect||(this._filterEffect=new lr),this._filterEffect.filterArea=s},get filterArea(){return this._filterEffect?.filterArea}},Zf={label:null,get name(){return z($,"Container.name property has been removed, use Container.label instead"),this.label},set name(s){z($,"Container.name property has been removed, use Container.label instead"),this.label=s},getChildByName(s,t=!1){return this.getChildByLabel(s,t)},getChildByLabel(s,t=!1){const e=this.children;for(let r=0;r<e.length;r++){const n=e[r];if(n.label===s||s instanceof RegExp&&s.test(n.label))return n}if(t)for(let r=0;r<e.length;r++){const a=e[r].getChildByLabel(s,!0);if(a)return a}return null},getChildrenByLabel(s,t=!1,e=[]){const r=this.children;for(let n=0;n<r.length;n++){const a=r[n];(a.label===s||s instanceof RegExp&&s.test(a.label))&&e.push(a)}if(t)for(let n=0;n<r.length;n++)r[n].getChildrenByLabel(s,!0,e);return e}},mt=at.getPool(k),Jt=at.getPool(dt),Qf=new k,Jf={getFastGlobalBounds(s,t){t||(t=new dt),t.clear(),this._getGlobalBoundsRecursive(!!s,t,this.parentRenderLayer),t.isValid||t.set(0,0,0,0);const e=this.renderGroup||this.parentRenderGroup;return t.applyMatrix(e.worldTransform),t},_getGlobalBoundsRecursive(s,t,e){let r=t;if(s&&this.parentRenderLayer&&this.parentRenderLayer!==e||this.localDisplayStatus!==7||!this.measurable)return;const n=!!this.effects.length;if((this.renderGroup||n)&&(r=Jt.get().clear()),this.boundsArea)t.addRect(this.boundsArea,this.worldTransform);else{if(this.renderPipeId){const l=this.bounds;r.addFrame(l.minX,l.minY,l.maxX,l.maxY,this.groupTransform)}const a=this.children;for(let l=0;l<a.length;l++)a[l]._getGlobalBoundsRecursive(s,r,e)}if(n){let a=!1;const l=this.renderGroup||this.parentRenderGroup;for(let h=0;h<this.effects.length;h++)this.effects[h].addBounds&&(a||(a=!0,r.applyMatrix(l.worldTransform)),this.effects[h].addBounds(r,!0));a&&r.applyMatrix(l.worldTransform.copyTo(Qf).invert()),t.addBounds(r),Jt.return(r)}else this.renderGroup&&(t.addBounds(r,this.relativeGroupTransform),Jt.return(r))}};function Ts(s,t,e){e.clear();let r,n;return s.parent?t?r=s.parent.worldTransform:(n=mt.get().identity(),r=Cs(s,n)):r=k.IDENTITY,mo(s,e,r,t),n&&mt.return(n),e.isValid||e.set(0,0,0,0),e}function mo(s,t,e,r){if(!s.visible||!s.measurable)return;let n;r?n=s.worldTransform:(s.updateLocalTransform(),n=mt.get(),n.appendFrom(s.localTransform,e));const a=t,l=!!s.effects.length;if(l&&(t=Jt.get().clear()),s.boundsArea)t.addRect(s.boundsArea,n);else{const h=s.bounds;h&&!h.isEmpty()&&(t.matrix=n,t.addBounds(h));for(let d=0;d<s.children.length;d++)mo(s.children[d],t,n,r)}if(l){for(let h=0;h<s.effects.length;h++)s.effects[h].addBounds?.(t);a.addBounds(t,k.IDENTITY),Jt.return(t)}r||mt.return(n)}function Cs(s,t){const e=s.parent;return e&&(Cs(e,t),e.updateLocalTransform(),t.append(e.localTransform)),t}function go(s,t){if(s===16777215||!t)return t;if(t===16777215||!s)return s;const e=s>>16&255,r=s>>8&255,n=s&255,a=t>>16&255,l=t>>8&255,h=t&255,d=e*a/255|0,f=r*l/255|0,m=n*h/255|0;return(d<<16)+(f<<8)+m}const _o=16777215;function cr(s,t){return s===_o?t:t===_o?s:go(s,t)}function ur(s){return((s&255)<<16)+(s&65280)+(s>>16&255)}const tp={getGlobalAlpha(s){if(s)return this.renderGroup?this.renderGroup.worldAlpha:this.parentRenderGroup?this.parentRenderGroup.worldAlpha*this.alpha:this.alpha;let t=this.alpha,e=this.parent;for(;e;)t*=e.alpha,e=e.parent;return t},getGlobalTransform(s=new k,t){if(t)return s.copyFrom(this.worldTransform);this.updateLocalTransform();const e=Cs(this,mt.get().identity());return s.appendFrom(this.localTransform,e),mt.return(e),s},getGlobalTint(s){if(s)return this.renderGroup?ur(this.renderGroup.worldColor):this.parentRenderGroup?ur(cr(this.localColor,this.parentRenderGroup.worldColor)):this.tint;let t=this.localColor,e=this.parent;for(;e;)t=cr(t,e.localColor),e=e.parent;return ur(t)}};function Es(s,t,e){return t.clear(),e||(e=k.IDENTITY),yo(s,t,e,s,!0),t.isValid||t.set(0,0,0,0),t}function yo(s,t,e,r,n){let a;if(n)a=mt.get(),a=e.copyTo(a);else{if(!s.visible||!s.measurable)return;s.updateLocalTransform();const d=s.localTransform;a=mt.get(),a.appendFrom(d,e)}const l=t,h=!!s.effects.length;if(h&&(t=Jt.get().clear()),s.boundsArea)t.addRect(s.boundsArea,a);else{s.renderPipeId&&(t.matrix=a,t.addBounds(s.bounds));const d=s.children;for(let f=0;f<d.length;f++)yo(d[f],t,a,r,!1)}if(h){for(let d=0;d<s.effects.length;d++)s.effects[d].addLocalBounds?.(t,r);l.addBounds(t,k.IDENTITY),Jt.return(t)}mt.return(a)}function xo(s,t){const e=s.children;for(let r=0;r<e.length;r++){const n=e[r],a=n.uid,l=(n._didViewChangeTick&65535)<<16|n._didContainerChangeTick&65535,h=t.index;(t.data[h]!==a||t.data[h+1]!==l)&&(t.data[t.index]=a,t.data[t.index+1]=l,t.didChange=!0),t.index=h+2,n.children.length&&xo(n,t)}return t.didChange}const ep=new k,ip={_localBoundsCacheId:-1,_localBoundsCacheData:null,_setWidth(s,t){const e=Math.sign(this.scale.x)||1;t!==0?this.scale.x=s/t*e:this.scale.x=e},_setHeight(s,t){const e=Math.sign(this.scale.y)||1;t!==0?this.scale.y=s/t*e:this.scale.y=e},getLocalBounds(){this._localBoundsCacheData||(this._localBoundsCacheData={data:[],index:1,didChange:!1,localBounds:new dt});const s=this._localBoundsCacheData;return s.index=1,s.didChange=!1,s.data[0]!==this._didViewChangeTick&&(s.didChange=!0,s.data[0]=this._didViewChangeTick),xo(this,s),s.didChange&&Es(this,s.localBounds,ep),s.localBounds},getBounds(s,t){return Ts(this,s,t||new dt)}},rp={_onRender:null,set onRender(s){const t=this.renderGroup||this.parentRenderGroup;if(!s){this._onRender&&t?.removeOnRender(this),this._onRender=null;return}this._onRender||t?.addOnRender(this),this._onRender=s},get onRender(){return this._onRender}},sp={_zIndex:0,sortDirty:!1,sortableChildren:!1,get zIndex(){return this._zIndex},set zIndex(s){this._zIndex!==s&&(this._zIndex=s,this.depthOfChildModified())},depthOfChildModified(){this.parent&&(this.parent.sortableChildren=!0,this.parent.sortDirty=!0),this.parentRenderGroup&&(this.parentRenderGroup.structureDidChange=!0)},sortChildren(){this.sortDirty&&(this.sortDirty=!1,this.children.sort(np))}};function np(s,t){return s._zIndex-t._zIndex}const ap={getGlobalPosition(s=new q,t=!1){return this.parent?this.parent.toGlobal(this._position,s,t):(s.x=this._position.x,s.y=this._position.y),s},toGlobal(s,t,e=!1){const r=this.getGlobalTransform(mt.get(),e);return t=r.apply(s,t),mt.return(r),t},toLocal(s,t,e,r){t&&(s=t.toGlobal(s,e,r));const n=this.getGlobalTransform(mt.get(),r);return e=n.applyInverse(s,e),mt.return(n),e}};class bo{constructor(){this.uid=et("instructionSet"),this.instructions=[],this.instructionSize=0,this.renderables=[],this.gcTick=0}reset(){this.instructionSize=0}destroy(){this.instructions.length=0,this.renderables.length=0,this.renderPipes=null,this.gcTick=0}add(t){this.instructions[this.instructionSize++]=t}log(){this.instructions.length=this.instructionSize,console.table(this.instructions,["type","action"])}}let op=0;class hp{constructor(t){this._poolKeyHash=Object.create(null),this._texturePool={},this.textureOptions=t||{},this.enableFullScreen=!1,this.textureStyle=new Kt(this.textureOptions)}createTexture(t,e,r){const n=new ht({...this.textureOptions,width:t,height:e,resolution:1,antialias:r,autoGarbageCollect:!1});return new M({source:n,label:`texturePool_${op++}`})}getOptimalTexture(t,e,r=1,n){let a=Math.ceil(t*r-1e-6),l=Math.ceil(e*r-1e-6);a=Le(a),l=Le(l);const h=(a<<17)+(l<<1)+(n?1:0);this._texturePool[h]||(this._texturePool[h]=[]);let d=this._texturePool[h].pop();return d||(d=this.createTexture(a,l,n)),d.source._resolution=r,d.source.width=a/r,d.source.height=l/r,d.source.pixelWidth=a,d.source.pixelHeight=l,d.frame.x=0,d.frame.y=0,d.frame.width=t,d.frame.height=e,d.updateUvs(),this._poolKeyHash[d.uid]=h,d}getSameSizeTexture(t,e=!1){const r=t.source;return this.getOptimalTexture(t.width,t.height,r._resolution,e)}returnTexture(t,e=!1){const r=this._poolKeyHash[t.uid];e&&(t.source.style=this.textureStyle),this._texturePool[r].push(t)}clear(t){if(t=t!==!1,t)for(const e in this._texturePool){const r=this._texturePool[e];if(r)for(let n=0;n<r.length;n++)r[n].destroy(!0)}this._texturePool={}}}const ut=new hp;Ne.register(ut);class As{constructor(){this.renderPipeId="renderGroup",this.root=null,this.canBundle=!1,this.renderGroupParent=null,this.renderGroupChildren=[],this.worldTransform=new k,this.worldColorAlpha=4294967295,this.worldColor=16777215,this.worldAlpha=1,this.childrenToUpdate=Object.create(null),this.updateTick=0,this.gcTick=0,this.childrenRenderablesToUpdate={list:[],index:0},this.structureDidChange=!0,this.instructionSet=new bo,this._onRenderContainers=[],this.textureNeedsUpdate=!0,this.isCachedAsTexture=!1,this._matrixDirty=7}init(t){this.root=t,t._onRender&&this.addOnRender(t),t.didChange=!0;const e=t.children;for(let r=0;r<e.length;r++){const n=e[r];n._updateFlags=15,this.addChild(n)}}enableCacheAsTexture(t={}){this.textureOptions=t,this.isCachedAsTexture=!0,this.textureNeedsUpdate=!0}disableCacheAsTexture(){this.isCachedAsTexture=!1,this.texture&&(ut.returnTexture(this.texture,!0),this.texture=null)}updateCacheTexture(){this.textureNeedsUpdate=!0;const t=this._parentCacheAsTextureRenderGroup;t&&!t.textureNeedsUpdate&&t.updateCacheTexture()}reset(){this.renderGroupChildren.length=0;for(const t in this.childrenToUpdate){const e=this.childrenToUpdate[t];e.list.fill(null),e.index=0}this.childrenRenderablesToUpdate.index=0,this.childrenRenderablesToUpdate.list.fill(null),this.root=null,this.updateTick=0,this.structureDidChange=!0,this._onRenderContainers.length=0,this.renderGroupParent=null,this.disableCacheAsTexture()}get localTransform(){return this.root.localTransform}addRenderGroupChild(t){t.renderGroupParent&&t.renderGroupParent._removeRenderGroupChild(t),t.renderGroupParent=this,this.renderGroupChildren.push(t)}_removeRenderGroupChild(t){const e=this.renderGroupChildren.indexOf(t);e>-1&&this.renderGroupChildren.splice(e,1),t.renderGroupParent=null}addChild(t){if(this.structureDidChange=!0,t.parentRenderGroup=this,t.updateTick=-1,t.parent===this.root?t.relativeRenderGroupDepth=1:t.relativeRenderGroupDepth=t.parent.relativeRenderGroupDepth+1,t.didChange=!0,this.onChildUpdate(t),t.renderGroup){this.addRenderGroupChild(t.renderGroup);return}t._onRender&&this.addOnRender(t);const e=t.children;for(let r=0;r<e.length;r++)this.addChild(e[r])}removeChild(t){if(this.structureDidChange=!0,t._onRender&&(t.renderGroup||this.removeOnRender(t)),t.parentRenderGroup=null,t.renderGroup){this._removeRenderGroupChild(t.renderGroup);return}const e=t.children;for(let r=0;r<e.length;r++)this.removeChild(e[r])}removeChildren(t){for(let e=0;e<t.length;e++)this.removeChild(t[e])}onChildUpdate(t){let e=this.childrenToUpdate[t.relativeRenderGroupDepth];e||(e=this.childrenToUpdate[t.relativeRenderGroupDepth]={index:0,list:[]}),e.list[e.index++]=t}updateRenderable(t){t.globalDisplayStatus<7||(this.instructionSet.renderPipes[t.renderPipeId].updateRenderable(t),t.didViewUpdate=!1)}onChildViewUpdate(t){this.childrenRenderablesToUpdate.list[this.childrenRenderablesToUpdate.index++]=t}get isRenderable(){return this.root.localDisplayStatus===7&&this.worldAlpha>0}addOnRender(t){this._onRenderContainers.push(t)}removeOnRender(t){this._onRenderContainers.splice(this._onRenderContainers.indexOf(t),1)}runOnRender(t){for(let e=0;e<this._onRenderContainers.length;e++)this._onRenderContainers[e]._onRender(t)}destroy(){this.disableCacheAsTexture(),this.renderGroupParent=null,this.root=null,this.childrenRenderablesToUpdate=null,this.childrenToUpdate=null,this.renderGroupChildren=null,this._onRenderContainers=null,this.instructionSet=null}getChildren(t=[]){const e=this.root.children;for(let r=0;r<e.length;r++)this._getChildren(e[r],t);return t}_getChildren(t,e=[]){if(e.push(t),t.renderGroup)return e;const r=t.children;for(let n=0;n<r.length;n++)this._getChildren(r[n],e);return e}invalidateMatrices(){this._matrixDirty=7}get inverseWorldTransform(){return(this._matrixDirty&1)===0?this._inverseWorldTransform:(this._matrixDirty&=-2,this._inverseWorldTransform||(this._inverseWorldTransform=new k),this._inverseWorldTransform.copyFrom(this.worldTransform).invert())}get textureOffsetInverseTransform(){return(this._matrixDirty&2)===0?this._textureOffsetInverseTransform:(this._matrixDirty&=-3,this._textureOffsetInverseTransform||(this._textureOffsetInverseTransform=new k),this._textureOffsetInverseTransform.copyFrom(this.inverseWorldTransform).translate(-this._textureBounds.x,-this._textureBounds.y))}get inverseParentTextureTransform(){if((this._matrixDirty&4)===0)return this._inverseParentTextureTransform;this._matrixDirty&=-5;const t=this._parentCacheAsTextureRenderGroup;return t?(this._inverseParentTextureTransform||(this._inverseParentTextureTransform=new k),this._inverseParentTextureTransform.copyFrom(this.worldTransform).prepend(t.inverseWorldTransform).translate(-t._textureBounds.x,-t._textureBounds.y)):this.worldTransform}get cacheToLocalTransform(){return this.isCachedAsTexture?this.textureOffsetInverseTransform:this._parentCacheAsTextureRenderGroup?this._parentCacheAsTextureRenderGroup.textureOffsetInverseTransform:null}}function lp(s,t,e={}){for(const r in t)!e[r]&&t[r]!==void 0&&(s[r]=t[r])}const Ps=new ct(null),dr=new ct(null),Bs=new ct(null,1,1),fr=new ct(null),pr=1,Us=2,ui=4;class ot extends Tt{constructor(t={}){super(),this.uid=et("renderable"),this._updateFlags=15,this.renderGroup=null,this.parentRenderGroup=null,this.parentRenderGroupIndex=0,this.didChange=!1,this.didViewUpdate=!1,this.relativeRenderGroupDepth=0,this.children=[],this.parent=null,this.includeInBuild=!0,this.measurable=!0,this.isSimple=!0,this.parentRenderLayer=null,this.updateTick=-1,this.localTransform=new k,this.relativeGroupTransform=new k,this.groupTransform=this.relativeGroupTransform,this.destroyed=!1,this._position=new ct(this,0,0),this._scale=Bs,this._pivot=dr,this._origin=fr,this._skew=Ps,this._cx=1,this._sx=0,this._cy=0,this._sy=1,this._rotation=0,this.localColor=16777215,this.localAlpha=1,this.groupAlpha=1,this.groupColor=16777215,this.groupColorAlpha=4294967295,this.localBlendMode="inherit",this.groupBlendMode="normal",this.localDisplayStatus=7,this.globalDisplayStatus=7,this._didContainerChangeTick=0,this._didViewChangeTick=0,this._didLocalTransformChangeId=-1,this.effects=[],lp(this,t,{children:!0,parent:!0,effects:!0}),t.children?.forEach(e=>this.addChild(e)),t.parent?.addChild(this)}static mixin(t){z("8.8.0","Container.mixin is deprecated, please use extensions.mixin instead."),D.mixin(ot,t)}set _didChangeId(t){this._didViewChangeTick=t>>12&4095,this._didContainerChangeTick=t&4095}get _didChangeId(){return this._didContainerChangeTick&4095|(this._didViewChangeTick&4095)<<12}addChild(...t){if(this.allowChildren||z($,"addChild: Only Containers will be allowed to add children in v8.0.0"),t.length>1){for(let n=0;n<t.length;n++)this.addChild(t[n]);return t[0]}const e=t[0],r=this.renderGroup||this.parentRenderGroup;return e.parent===this?(this.children.splice(this.children.indexOf(e),1),this.children.push(e),r&&(r.structureDidChange=!0),e):(e.parent&&e.parent.removeChild(e),this.children.push(e),this.sortableChildren&&(this.sortDirty=!0),e.parent=this,e.didChange=!0,e._updateFlags=15,r&&r.addChild(e),this.emit("childAdded",e,this,this.children.length-1),e.emit("added",this),this._didViewChangeTick++,e._zIndex!==0&&e.depthOfChildModified(),e)}removeChild(...t){if(t.length>1){for(let n=0;n<t.length;n++)this.removeChild(t[n]);return t[0]}const e=t[0],r=this.children.indexOf(e);return r>-1&&(this._didViewChangeTick++,this.children.splice(r,1),this.renderGroup?this.renderGroup.removeChild(e):this.parentRenderGroup&&this.parentRenderGroup.removeChild(e),e.parentRenderLayer&&e.parentRenderLayer.detach(e),e.parent=null,this.emit("childRemoved",e,this,r),e.emit("removed",this)),e}_onUpdate(t){t&&t===this._skew&&this._updateSkew(),this._didContainerChangeTick++,!this.didChange&&(this.didChange=!0,this.parentRenderGroup&&this.parentRenderGroup.onChildUpdate(this))}set isRenderGroup(t){!!this.renderGroup!==t&&(t?this.enableRenderGroup():this.disableRenderGroup())}get isRenderGroup(){return!!this.renderGroup}enableRenderGroup(){if(this.renderGroup)return;const t=this.parentRenderGroup;t?.removeChild(this),this.renderGroup=at.get(As,this),this.groupTransform=k.IDENTITY,t?.addChild(this),this._updateIsSimple()}disableRenderGroup(){if(!this.renderGroup)return;const t=this.parentRenderGroup;t?.removeChild(this),at.return(this.renderGroup),this.renderGroup=null,this.groupTransform=this.relativeGroupTransform,t?.addChild(this),this._updateIsSimple()}_updateIsSimple(){this.isSimple=!this.renderGroup&&this.effects.length===0}get worldTransform(){return this._worldTransform||(this._worldTransform=new k),this.renderGroup?this._worldTransform.copyFrom(this.renderGroup.worldTransform):this.parentRenderGroup&&this._worldTransform.appendFrom(this.relativeGroupTransform,this.parentRenderGroup.worldTransform),this._worldTransform}get x(){return this._position.x}set x(t){this._position.x=t}get y(){return this._position.y}set y(t){this._position.y=t}get position(){return this._position}set position(t){this._position.copyFrom(t)}get rotation(){return this._rotation}set rotation(t){this._rotation!==t&&(this._rotation=t,this._onUpdate(this._skew))}get angle(){return this.rotation*Af}set angle(t){this.rotation=t*Pf}get pivot(){return this._pivot===dr&&(this._pivot=new ct(this,0,0)),this._pivot}set pivot(t){this._pivot===dr&&(this._pivot=new ct(this,0,0),this._origin!==fr&&F("Setting both a pivot and origin on a Container is not recommended. This can lead to unexpected behavior if not handled carefully.")),typeof t=="number"?this._pivot.set(t):this._pivot.copyFrom(t)}get skew(){return this._skew===Ps&&(this._skew=new ct(this,0,0)),this._skew}set skew(t){this._skew===Ps&&(this._skew=new ct(this,0,0)),this._skew.copyFrom(t)}get scale(){return this._scale===Bs&&(this._scale=new ct(this,1,1)),this._scale}set scale(t){this._scale===Bs&&(this._scale=new ct(this,0,0)),typeof t=="string"&&(t=parseFloat(t)),typeof t=="number"?this._scale.set(t):this._scale.copyFrom(t)}get origin(){return this._origin===fr&&(this._origin=new ct(this,0,0)),this._origin}set origin(t){this._origin===fr&&(this._origin=new ct(this,0,0),this._pivot!==dr&&F("Setting both a pivot and origin on a Container is not recommended. This can lead to unexpected behavior if not handled carefully.")),typeof t=="number"?this._origin.set(t):this._origin.copyFrom(t)}get width(){return Math.abs(this.scale.x*this.getLocalBounds().width)}set width(t){const e=this.getLocalBounds().width;this._setWidth(t,e)}get height(){return Math.abs(this.scale.y*this.getLocalBounds().height)}set height(t){const e=this.getLocalBounds().height;this._setHeight(t,e)}getSize(t){t||(t={});const e=this.getLocalBounds();return t.width=Math.abs(this.scale.x*e.width),t.height=Math.abs(this.scale.y*e.height),t}setSize(t,e){const r=this.getLocalBounds();typeof t=="object"?(e=t.height??t.width,t=t.width):e??(e=t),t!==void 0&&this._setWidth(t,r.width),e!==void 0&&this._setHeight(e,r.height)}_updateSkew(){const t=this._rotation,e=this._skew;this._cx=Math.cos(t+e._y),this._sx=Math.sin(t+e._y),this._cy=-Math.sin(t-e._x),this._sy=Math.cos(t-e._x)}updateTransform(t){return this.position.set(typeof t.x=="number"?t.x:this.position.x,typeof t.y=="number"?t.y:this.position.y),this.scale.set(typeof t.scaleX=="number"?t.scaleX||1:this.scale.x,typeof t.scaleY=="number"?t.scaleY||1:this.scale.y),this.rotation=typeof t.rotation=="number"?t.rotation:this.rotation,this.skew.set(typeof t.skewX=="number"?t.skewX:this.skew.x,typeof t.skewY=="number"?t.skewY:this.skew.y),this.pivot.set(typeof t.pivotX=="number"?t.pivotX:this.pivot.x,typeof t.pivotY=="number"?t.pivotY:this.pivot.y),this.origin.set(typeof t.originX=="number"?t.originX:this.origin.x,typeof t.originY=="number"?t.originY:this.origin.y),this}setFromMatrix(t){t.decompose(this)}updateLocalTransform(){const t=this._didContainerChangeTick;if(this._didLocalTransformChangeId===t)return;this._didLocalTransformChangeId=t;const e=this.localTransform,r=this._scale,n=this._pivot,a=this._origin,l=this._position,h=r._x,d=r._y,f=n._x,m=n._y,g=-a._x,y=-a._y;e.a=this._cx*h,e.b=this._sx*h,e.c=this._cy*d,e.d=this._sy*d,e.tx=l._x-(f*e.a+m*e.c)+(g*e.a+y*e.c)-g,e.ty=l._y-(f*e.b+m*e.d)+(g*e.b+y*e.d)-y}set alpha(t){t!==this.localAlpha&&(this.localAlpha=t,this._updateFlags|=pr,this._onUpdate())}get alpha(){return this.localAlpha}set tint(t){const r=J.shared.setValue(t??16777215).toBgrNumber();r!==this.localColor&&(this.localColor=r,this._updateFlags|=pr,this._onUpdate())}get tint(){return ur(this.localColor)}set blendMode(t){this.localBlendMode!==t&&(this.parentRenderGroup&&(this.parentRenderGroup.structureDidChange=!0),this._updateFlags|=Us,this.localBlendMode=t,this._onUpdate())}get blendMode(){return this.localBlendMode}get visible(){return!!(this.localDisplayStatus&2)}set visible(t){const e=t?2:0;(this.localDisplayStatus&2)!==e&&(this.parentRenderGroup&&(this.parentRenderGroup.structureDidChange=!0),this._updateFlags|=ui,this.localDisplayStatus^=2,this._onUpdate())}get culled(){return!(this.localDisplayStatus&4)}set culled(t){const e=t?0:4;(this.localDisplayStatus&4)!==e&&(this.parentRenderGroup&&(this.parentRenderGroup.structureDidChange=!0),this._updateFlags|=ui,this.localDisplayStatus^=4,this._onUpdate())}get renderable(){return!!(this.localDisplayStatus&1)}set renderable(t){const e=t?1:0;(this.localDisplayStatus&1)!==e&&(this._updateFlags|=ui,this.localDisplayStatus^=1,this.parentRenderGroup&&(this.parentRenderGroup.structureDidChange=!0),this._onUpdate())}get isRenderable(){return this.localDisplayStatus===7&&this.groupAlpha>0}destroy(t=!1){if(this.destroyed)return;this.destroyed=!0;let e;if(this.children.length&&(e=this.removeChildren(0,this.children.length)),this.removeFromParent(),this.parent=null,this._maskEffect=null,this._filterEffect=null,this.effects=null,this._position=null,this._scale=null,this._pivot=null,this._origin=null,this._skew=null,this.emit("destroyed",this),this.removeAllListeners(),(typeof t=="boolean"?t:t?.children)&&e)for(let n=0;n<e.length;++n)e[n].destroy(t);this.renderGroup?.destroy(),this.renderGroup=null}}D.mixin(ot,$f,Jf,ap,rp,ip,qf,Zf,sp,Wf,Xf,tp,Kf);class Ms extends ot{constructor(t){super(t),this.canBundle=!0,this.allowChildren=!1,this._roundPixels=0,this._lastUsed=-1,this._gpuData=Object.create(null),this._bounds=new dt(0,1,0,0),this._boundsDirty=!0}get bounds(){return this._boundsDirty?(this.updateBounds(),this._boundsDirty=!1,this._bounds):this._bounds}get roundPixels(){return!!this._roundPixels}set roundPixels(t){this._roundPixels=t?1:0}containsPoint(t){const e=this.bounds,{x:r,y:n}=t;return r>=e.minX&&r<=e.maxX&&n>=e.minY&&n<=e.maxY}onViewUpdate(){if(this._didViewChangeTick++,this._boundsDirty=!0,this.didViewUpdate)return;this.didViewUpdate=!0;const t=this.renderGroup||this.parentRenderGroup;t&&t.onChildViewUpdate(this)}destroy(t){super.destroy(t),this._bounds=null;for(const e in this._gpuData)this._gpuData[e].destroy?.();this._gpuData=null}collectRenderablesSimple(t,e,r){const{renderPipes:n}=e;n.blendMode.pushBlendMode(this,this.groupBlendMode,t),n[this.renderPipeId].addRenderable(this,t),this.didViewUpdate=!1;const l=this.children,h=l.length;for(let d=0;d<h;d++)l[d].collectRenderables(t,e,r);n.blendMode.popBlendMode(t)}}class te extends Ms{constructor(t=M.EMPTY){t instanceof M&&(t={texture:t});const{texture:e=M.EMPTY,anchor:r,roundPixels:n,width:a,height:l,...h}=t;super({label:"Sprite",...h}),this.renderPipeId="sprite",this.batched=!0,this._visualBounds={minX:0,maxX:1,minY:0,maxY:0},this._anchor=new ct({_onUpdate:()=>{this.onViewUpdate()}}),r?this.anchor=r:e.defaultAnchor&&(this.anchor=e.defaultAnchor),this.texture=e,this.allowChildren=!1,this.roundPixels=n??!1,a!==void 0&&(this.width=a),l!==void 0&&(this.height=l)}static from(t,e=!1){return t instanceof M?new te(t):new te(M.from(t,e))}set texture(t){t||(t=M.EMPTY);const e=this._texture;e!==t&&(e&&e.dynamic&&e.off("update",this.onViewUpdate,this),t.dynamic&&t.on("update",this.onViewUpdate,this),this._texture=t,this._width&&this._setWidth(this._width,this._texture.orig.width),this._height&&this._setHeight(this._height,this._texture.orig.height),this.onViewUpdate())}get texture(){return this._texture}get visualBounds(){return to(this._visualBounds,this._anchor,this._texture),this._visualBounds}get sourceBounds(){return z("8.6.1","Sprite.sourceBounds is deprecated, use visualBounds instead."),this.visualBounds}updateBounds(){const t=this._anchor,e=this._texture,r=this._bounds,{width:n,height:a}=e.orig;r.minX=-t._x*n,r.maxX=r.minX+n,r.minY=-t._y*a,r.maxY=r.minY+a}destroy(t=!1){if(super.destroy(t),typeof t=="boolean"?t:t?.texture){const r=typeof t=="boolean"?t:t?.textureSource;this._texture.destroy(r)}this._texture=null,this._visualBounds=null,this._bounds=null,this._anchor=null,this._gpuData=null}get anchor(){return this._anchor}set anchor(t){typeof t=="number"?this._anchor.set(t):this._anchor.copyFrom(t)}get width(){return Math.abs(this.scale.x)*this._texture.orig.width}set width(t){this._setWidth(t,this._texture.orig.width),this._width=t}get height(){return Math.abs(this.scale.y)*this._texture.orig.height}set height(t){this._setHeight(t,this._texture.orig.height),this._height=t}getSize(t){return t||(t={}),t.width=Math.abs(this.scale.x)*this._texture.orig.width,t.height=Math.abs(this.scale.y)*this._texture.orig.height,t}setSize(t,e){typeof t=="object"?(e=t.height??t.width,t=t.width):e??(e=t),t!==void 0&&this._setWidth(t,this._texture.orig.width),e!==void 0&&this._setHeight(e,this._texture.orig.height)}}const cp=new dt;function vo(s,t,e){const r=cp;s.measurable=!0,Ts(s,e,r),t.addBoundsMask(r),s.measurable=!1}function wo(s,t,e){const r=Jt.get();s.measurable=!0;const n=mt.get().identity(),a=So(s,e,n);Es(s,r,a),s.measurable=!1,t.addBoundsMask(r),mt.return(n),Jt.return(r)}function So(s,t,e){return s?(s!==t&&(So(s.parent,t,e),s.updateLocalTransform(),e.append(s.localTransform)),e):(F("Mask bounds, renderable is not inside the root container"),e)}class To{constructor(t){this.priority=0,this.inverse=!1,this.pipe="alphaMask",t?.mask&&this.init(t.mask)}init(t){this.mask=t,this.renderMaskToTexture=!(t instanceof te),this.mask.renderable=this.renderMaskToTexture,this.mask.includeInBuild=!this.renderMaskToTexture,this.mask.measurable=!1}reset(){this.mask!==null&&(this.mask.measurable=!0,this.mask=null)}addBounds(t,e){this.inverse||vo(this.mask,t,e)}addLocalBounds(t,e){wo(this.mask,t,e)}containsPoint(t,e){const r=this.mask;return e(r,t)}destroy(){this.reset()}static test(t){return t instanceof te}}To.extension=C.MaskEffect;class Co{constructor(t){this.priority=0,this.pipe="colorMask",t?.mask&&this.init(t.mask)}init(t){this.mask=t}destroy(){}static test(t){return typeof t=="number"}}Co.extension=C.MaskEffect;class Eo{constructor(t){this.priority=0,this.pipe="stencilMask",t?.mask&&this.init(t.mask)}init(t){this.mask=t,this.mask.includeInBuild=!1,this.mask.measurable=!1}reset(){this.mask!==null&&(this.mask.measurable=!0,this.mask.includeInBuild=!0,this.mask=null)}addBounds(t,e){vo(this.mask,t,e)}addLocalBounds(t,e){wo(this.mask,t,e)}containsPoint(t,e){const r=this.mask;return e(r,t)}destroy(){this.reset()}static test(t){return t instanceof ot}}Eo.extension=C.MaskEffect;let Ao={createCanvas:(s,t)=>{const e=document.createElement("canvas");return e.width=s,e.height=t,e},createImage:()=>new Image,getCanvasRenderingContext2D:()=>CanvasRenderingContext2D,getWebGLRenderingContext:()=>WebGLRenderingContext,getNavigator:()=>navigator,getBaseUrl:()=>document.baseURI??window.location.href,getFontFaceSet:()=>document.fonts,fetch:(s,t)=>fetch(s,t),parseXML:s=>new DOMParser().parseFromString(s,"text/xml")};const W={get(){return Ao},set(s){Ao=s}};class ee extends ht{constructor(t){t.resource||(t.resource=W.get().createCanvas()),t.width||(t.width=t.resource.width,t.autoDensity||(t.width/=t.resolution)),t.height||(t.height=t.resource.height,t.autoDensity||(t.height/=t.resolution)),super(t),this.uploadMethodId="image",this.autoDensity=t.autoDensity,this.resizeCanvas(),this.transparent=!!t.transparent}resizeCanvas(){this.autoDensity&&"style"in this.resource&&(this.resource.style.width=`${this.width}px`,this.resource.style.height=`${this.height}px`),(this.resource.width!==this.pixelWidth||this.resource.height!==this.pixelHeight)&&(this.resource.width=this.pixelWidth,this.resource.height=this.pixelHeight)}resize(t=this.width,e=this.height,r=this._resolution){const n=super.resize(t,e,r);return n&&this.resizeCanvas(),n}static test(t){return globalThis.HTMLCanvasElement&&t instanceof HTMLCanvasElement||globalThis.OffscreenCanvas&&t instanceof OffscreenCanvas}get context2D(){return this._context2D||(this._context2D=this.resource.getContext("2d"))}}ee.extension=C.TextureSource;class we extends ht{constructor(t){super(t),this.uploadMethodId="image",this.autoGarbageCollect=!0}static test(t){return globalThis.HTMLImageElement&&t instanceof HTMLImageElement||typeof ImageBitmap<"u"&&t instanceof ImageBitmap||globalThis.VideoFrame&&t instanceof VideoFrame}}we.extension=C.TextureSource;var He=(s=>(s[s.INTERACTION=50]="INTERACTION",s[s.HIGH=25]="HIGH",s[s.NORMAL=0]="NORMAL",s[s.LOW=-25]="LOW",s[s.UTILITY=-50]="UTILITY",s))(He||{});class ks{constructor(t,e=null,r=0,n=!1){this.next=null,this.previous=null,this._destroyed=!1,this._fn=t,this._context=e,this.priority=r,this._once=n}match(t,e=null){return this._fn===t&&this._context===e}emit(t){this._fn&&(this._context?this._fn.call(this._context,t):this._fn(t));const e=this.next;return this._once&&this.destroy(!0),this._destroyed&&(this.next=null),e}connect(t){this.previous=t,t.next&&(t.next.previous=this),this.next=t.next,t.next=this}destroy(t=!1){this._destroyed=!0,this._fn=null,this._context=null,this.previous&&(this.previous.next=this.next),this.next&&(this.next.previous=this.previous);const e=this.next;return this.next=t?null:e,this.previous=null,e}}const Po=class Ut{constructor(){this.autoStart=!1,this.deltaTime=1,this.lastTime=-1,this.speed=1,this.started=!1,this._requestId=null,this._maxElapsedMS=100,this._minElapsedMS=0,this._protected=!1,this._lastFrame=-1,this._head=new ks(null,null,1/0),this.deltaMS=1/Ut.targetFPMS,this.elapsedMS=1/Ut.targetFPMS,this._tick=t=>{this._requestId=null,this.started&&(this.update(t),this.started&&this._requestId===null&&this._head.next&&(this._requestId=requestAnimationFrame(this._tick)))}}_requestIfNeeded(){this._requestId===null&&this._head.next&&(this.lastTime=performance.now(),this._lastFrame=this.lastTime,this._requestId=requestAnimationFrame(this._tick))}_cancelIfNeeded(){this._requestId!==null&&(cancelAnimationFrame(this._requestId),this._requestId=null)}_startIfPossible(){this.started?this._requestIfNeeded():this.autoStart&&this.start()}add(t,e,r=He.NORMAL){return this._addListener(new ks(t,e,r))}addOnce(t,e,r=He.NORMAL){return this._addListener(new ks(t,e,r,!0))}_addListener(t){let e=this._head.next,r=this._head;if(!e)t.connect(r);else{for(;e;){if(t.priority>e.priority){t.connect(r);break}r=e,e=e.next}t.previous||t.connect(r)}return this._startIfPossible(),this}remove(t,e){let r=this._head.next;for(;r;)r.match(t,e)?r=r.destroy():r=r.next;return this._head.next||this._cancelIfNeeded(),this}get count(){if(!this._head)return 0;let t=0,e=this._head;for(;e=e.next;)t++;return t}start(){this.started||(this.started=!0,this._requestIfNeeded())}stop(){this.started&&(this.started=!1,this._cancelIfNeeded())}destroy(){if(!this._protected){this.stop();let t=this._head.next;for(;t;)t=t.destroy(!0);this._head.destroy(),this._head=null}}update(t=performance.now()){let e;if(t>this.lastTime){if(e=this.elapsedMS=t-this.lastTime,e>this._maxElapsedMS&&(e=this._maxElapsedMS),e*=this.speed,this._minElapsedMS){const a=t-this._lastFrame|0;if(a<this._minElapsedMS)return;this._lastFrame=t-a%this._minElapsedMS}this.deltaMS=e,this.deltaTime=this.deltaMS*Ut.targetFPMS;const r=this._head;let n=r.next;for(;n;)n=n.emit(this);r.next||this._cancelIfNeeded()}else this.deltaTime=this.deltaMS=this.elapsedMS=0;this.lastTime=t}get FPS(){return 1e3/this.elapsedMS}get minFPS(){return 1e3/this._maxElapsedMS}set minFPS(t){const e=Math.min(this.maxFPS,t),r=Math.min(Math.max(0,e)/1e3,Ut.targetFPMS);this._maxElapsedMS=1/r}get maxFPS(){return this._minElapsedMS?Math.round(1e3/this._minElapsedMS):0}set maxFPS(t){if(t===0)this._minElapsedMS=0;else{const e=Math.max(this.minFPS,t);this._minElapsedMS=1/(e/1e3)}}static get shared(){if(!Ut._shared){const t=Ut._shared=new Ut;t.autoStart=!0,t._protected=!0}return Ut._shared}static get system(){if(!Ut._system){const t=Ut._system=new Ut;t.autoStart=!0,t._protected=!0}return Ut._system}};Po.targetFPMS=.06;let Ct=Po,Rs;async function Bo(){return Rs??(Rs=(async()=>{const t=W.get().createCanvas(1,1).getContext("webgl");if(!t)return"premultiply-alpha-on-upload";const e=await new Promise(l=>{const h=document.createElement("video");h.onloadeddata=()=>l(h),h.onerror=()=>l(null),h.autoplay=!1,h.crossOrigin="anonymous",h.preload="auto",h.src="data:video/webm;base64,GkXfo59ChoEBQveBAULygQRC84EIQoKEd2VibUKHgQJChYECGFOAZwEAAAAAAAHTEU2bdLpNu4tTq4QVSalmU6yBoU27i1OrhBZUrmtTrIHGTbuMU6uEElTDZ1OsggEXTbuMU6uEHFO7a1OsggG97AEAAAAAAABZAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAVSalmoCrXsYMPQkBNgIRMYXZmV0GETGF2ZkSJiEBEAAAAAAAAFlSua8yuAQAAAAAAAEPXgQFzxYgAAAAAAAAAAZyBACK1nIN1bmSIgQCGhVZfVlA5g4EBI+ODhAJiWgDglLCBArqBApqBAlPAgQFVsIRVuYEBElTDZ9Vzc9JjwItjxYgAAAAAAAAAAWfInEWjh0VOQ09ERVJEh49MYXZjIGxpYnZweC12cDlnyKJFo4hEVVJBVElPTkSHlDAwOjAwOjAwLjA0MDAwMDAwMAAAH0O2dcfngQCgwqGggQAAAIJJg0IAABAAFgA4JBwYSgAAICAAEb///4r+AAB1oZ2mm+6BAaWWgkmDQgAAEAAWADgkHBhKAAAgIABIQBxTu2uRu4+zgQC3iveBAfGCAXHwgQM=",h.load()});if(!e)return"premultiply-alpha-on-upload";const r=t.createTexture();t.bindTexture(t.TEXTURE_2D,r);const n=t.createFramebuffer();t.bindFramebuffer(t.FRAMEBUFFER,n),t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,r,0),t.pixelStorei(t.UNPACK_PREMULTIPLY_ALPHA_WEBGL,!1),t.pixelStorei(t.UNPACK_COLORSPACE_CONVERSION_WEBGL,t.NONE),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,e);const a=new Uint8Array(4);return t.readPixels(0,0,1,1,t.RGBA,t.UNSIGNED_BYTE,a),t.deleteFramebuffer(n),t.deleteTexture(r),t.getExtension("WEBGL_lose_context")?.loseContext(),a[0]<=a[3]?"premultiplied-alpha":"premultiply-alpha-on-upload"})()),Rs}const mr=class $u extends ht{constructor(t){super(t),this.isReady=!1,this.uploadMethodId="video",t={...$u.defaultOptions,...t},this._autoUpdate=!0,this._isConnectedToTicker=!1,this._updateFPS=t.updateFPS||0,this._msToNextUpdate=0,this.autoPlay=t.autoPlay!==!1,this.alphaMode=t.alphaMode??"premultiply-alpha-on-upload",this._videoFrameRequestCallback=this._videoFrameRequestCallback.bind(this),this._videoFrameRequestCallbackHandle=null,this._load=null,this._resolve=null,this._reject=null,this._onCanPlay=this._onCanPlay.bind(this),this._onCanPlayThrough=this._onCanPlayThrough.bind(this),this._onError=this._onError.bind(this),this._onPlayStart=this._onPlayStart.bind(this),this._onPlayStop=this._onPlayStop.bind(this),this._onSeeked=this._onSeeked.bind(this),t.autoLoad!==!1&&this.load()}updateFrame(){if(!this.destroyed){if(this._updateFPS){const t=Ct.shared.elapsedMS*this.resource.playbackRate;this._msToNextUpdate=Math.floor(this._msToNextUpdate-t)}(!this._updateFPS||this._msToNextUpdate<=0)&&(this._msToNextUpdate=this._updateFPS?Math.floor(1e3/this._updateFPS):0),this.isValid&&this.update()}}_videoFrameRequestCallback(){this.updateFrame(),this.destroyed?this._videoFrameRequestCallbackHandle=null:this._videoFrameRequestCallbackHandle=this.resource.requestVideoFrameCallback(this._videoFrameRequestCallback)}get isValid(){return!!this.resource.videoWidth&&!!this.resource.videoHeight}async load(){if(this._load)return this._load;const t=this.resource,e=this.options;return(t.readyState===t.HAVE_ENOUGH_DATA||t.readyState===t.HAVE_FUTURE_DATA)&&t.width&&t.height&&(t.complete=!0),t.addEventListener("play",this._onPlayStart),t.addEventListener("pause",this._onPlayStop),t.addEventListener("seeked",this._onSeeked),this._isSourceReady()?this._mediaReady():(e.preload||t.addEventListener("canplay",this._onCanPlay),t.addEventListener("canplaythrough",this._onCanPlayThrough),t.addEventListener("error",this._onError,!0)),this.alphaMode=await Bo(),this._load=new Promise((r,n)=>{this.isValid?r(this):(this._resolve=r,this._reject=n,e.preloadTimeoutMs!==void 0&&(this._preloadTimeout=setTimeout(()=>{this._onError(new ErrorEvent(`Preload exceeded timeout of ${e.preloadTimeoutMs}ms`))})),t.load())}),this._load}_onError(t){this.resource.removeEventListener("error",this._onError,!0),this.emit("error",t),this._reject&&(this._reject(t),this._reject=null,this._resolve=null)}_isSourcePlaying(){const t=this.resource;return!t.paused&&!t.ended}_isSourceReady(){return this.resource.readyState>2}_onPlayStart(){this.isValid||this._mediaReady(),this._configureAutoUpdate()}_onPlayStop(){this._configureAutoUpdate()}_onSeeked(){this._autoUpdate&&!this._isSourcePlaying()&&(this._msToNextUpdate=0,this.updateFrame(),this._msToNextUpdate=0)}_onCanPlay(){this.resource.removeEventListener("canplay",this._onCanPlay),this._mediaReady()}_onCanPlayThrough(){this.resource.removeEventListener("canplaythrough",this._onCanPlay),this._preloadTimeout&&(clearTimeout(this._preloadTimeout),this._preloadTimeout=void 0),this._mediaReady()}_mediaReady(){const t=this.resource;this.isValid&&(this.isReady=!0,this.resize(t.videoWidth,t.videoHeight)),this._msToNextUpdate=0,this.updateFrame(),this._msToNextUpdate=0,this._resolve&&(this._resolve(this),this._resolve=null,this._reject=null),this._isSourcePlaying()?this._onPlayStart():this.autoPlay&&this.resource.play()}destroy(){this._configureAutoUpdate();const t=this.resource;t&&(t.removeEventListener("play",this._onPlayStart),t.removeEventListener("pause",this._onPlayStop),t.removeEventListener("seeked",this._onSeeked),t.removeEventListener("canplay",this._onCanPlay),t.removeEventListener("canplaythrough",this._onCanPlayThrough),t.removeEventListener("error",this._onError,!0),t.pause(),t.src="",t.load()),super.destroy()}get autoUpdate(){return this._autoUpdate}set autoUpdate(t){t!==this._autoUpdate&&(this._autoUpdate=t,this._configureAutoUpdate())}get updateFPS(){return this._updateFPS}set updateFPS(t){t!==this._updateFPS&&(this._updateFPS=t,this._configureAutoUpdate())}_configureAutoUpdate(){this._autoUpdate&&this._isSourcePlaying()?!this._updateFPS&&this.resource.requestVideoFrameCallback?(this._isConnectedToTicker&&(Ct.shared.remove(this.updateFrame,this),this._isConnectedToTicker=!1,this._msToNextUpdate=0),this._videoFrameRequestCallbackHandle===null&&(this._videoFrameRequestCallbackHandle=this.resource.requestVideoFrameCallback(this._videoFrameRequestCallback))):(this._videoFrameRequestCallbackHandle!==null&&(this.resource.cancelVideoFrameCallback(this._videoFrameRequestCallbackHandle),this._videoFrameRequestCallbackHandle=null),this._isConnectedToTicker||(Ct.shared.add(this.updateFrame,this),this._isConnectedToTicker=!0,this._msToNextUpdate=0)):(this._videoFrameRequestCallbackHandle!==null&&(this.resource.cancelVideoFrameCallback(this._videoFrameRequestCallbackHandle),this._videoFrameRequestCallbackHandle=null),this._isConnectedToTicker&&(Ct.shared.remove(this.updateFrame,this),this._isConnectedToTicker=!1,this._msToNextUpdate=0))}static test(t){return globalThis.HTMLVideoElement&&t instanceof HTMLVideoElement}};mr.extension=C.TextureSource,mr.defaultOptions={...ht.defaultOptions,autoLoad:!0,autoPlay:!0,updateFPS:0,crossorigin:!0,loop:!1,muted:!0,playsinline:!0,preload:!1},mr.MIME_TYPES={ogv:"video/ogg",mov:"video/quicktime",m4v:"video/mp4"};let di=mr;const Lt=(s,t,e=!1)=>(Array.isArray(s)||(s=[s]),t?s.map(r=>typeof r=="string"||e?t(r):r):s);class up{constructor(){this._parsers=[],this._cache=new Map,this._cacheMap=new Map}reset(){this._cacheMap.clear(),this._cache.clear()}has(t){return this._cache.has(t)}get(t){const e=this._cache.get(t);return e||F(`[Assets] Asset id ${t} was not found in the Cache`),e}set(t,e){const r=Lt(t);let n;for(let d=0;d<this.parsers.length;d++){const f=this.parsers[d];if(f.test(e)){n=f.getCacheableAssets(r,e);break}}const a=new Map(Object.entries(n||{}));n||r.forEach(d=>{a.set(d,e)});const l=[...a.keys()],h={cacheKeys:l,keys:r};r.forEach(d=>{this._cacheMap.set(d,h)}),l.forEach(d=>{const f=n?n[d]:e;this._cache.has(d)&&this._cache.get(d)!==f&&F("[Cache] already has key:",d),this._cache.set(d,a.get(d))})}remove(t){if(!this._cacheMap.has(t)){F(`[Assets] Asset id ${t} was not found in the Cache`);return}const e=this._cacheMap.get(t);e.cacheKeys.forEach(n=>{this._cache.delete(n)}),e.keys.forEach(n=>{this._cacheMap.delete(n)})}get parsers(){return this._parsers}}const Q=new up,Is=[];D.handleByList(C.TextureSource,Is);function Uo(s={}){const t=s&&s.resource,e=t?s.resource:s,r=t?s:{resource:s};for(let n=0;n<Is.length;n++){const a=Is[n];if(a.test(e))return new a(r)}throw new Error(`Could not find a source type for resource: ${r.resource}`)}function dp(s={},t=!1){const e=s&&s.resource,r=e?s.resource:s,n=e?s:{resource:s};if(!t&&Q.has(r))return Q.get(r);const a=new M({source:Uo(n)});return a.on("destroy",()=>{Q.has(r)&&Q.remove(r)}),t||Q.set(r,a),a}function fp(s,t=!1){return typeof s=="string"?Q.get(s):s instanceof ht?new M({source:s}):dp(s,t)}M.from=fp,ht.from=Uo,D.add(To,Co,Eo,di,we,ee,gs);var ce=(s=>(s[s.Low=0]="Low",s[s.Normal=1]="Normal",s[s.High=2]="High",s))(ce||{});function zt(s){if(typeof s!="string")throw new TypeError(`Path must be a string. Received ${JSON.stringify(s)}`)}function fi(s){return s.split("?")[0].split("#")[0]}function pp(s){return s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function mp(s,t,e){return s.replace(new RegExp(pp(t),"g"),e)}function gp(s,t){let e="",r=0,n=-1,a=0,l=-1;for(let h=0;h<=s.length;++h){if(h<s.length)l=s.charCodeAt(h);else{if(l===47)break;l=47}if(l===47){if(!(n===h-1||a===1))if(n!==h-1&&a===2){if(e.length<2||r!==2||e.charCodeAt(e.length-1)!==46||e.charCodeAt(e.length-2)!==46){if(e.length>2){const d=e.lastIndexOf("/");if(d!==e.length-1){d===-1?(e="",r=0):(e=e.slice(0,d),r=e.length-1-e.lastIndexOf("/")),n=h,a=0;continue}}else if(e.length===2||e.length===1){e="",r=0,n=h,a=0;continue}}}else e.length>0?e+=`/${s.slice(n+1,h)}`:e=s.slice(n+1,h),r=h-n-1;n=h,a=0}else l===46&&a!==-1?++a:a=-1}return e}const Et={toPosix(s){return mp(s,"\\","/")},isUrl(s){return/^https?:/.test(this.toPosix(s))},isDataUrl(s){return/^data:([a-z]+\/[a-z0-9-+.]+(;[a-z0-9-.!#$%*+.{}|~`]+=[a-z0-9-.!#$%*+.{}()_|~`]+)*)?(;base64)?,([a-z0-9!$&',()*+;=\-._~:@\/?%\s<>]*?)$/i.test(s)},isBlobUrl(s){return s.startsWith("blob:")},hasProtocol(s){return/^[^/:]+:/.test(this.toPosix(s))},getProtocol(s){zt(s),s=this.toPosix(s);const t=/^file:\/\/\//.exec(s);if(t)return t[0];const e=/^[^/:]+:\/{0,2}/.exec(s);return e?e[0]:""},toAbsolute(s,t,e){if(zt(s),this.isDataUrl(s)||this.isBlobUrl(s))return s;const r=fi(this.toPosix(t??W.get().getBaseUrl())),n=fi(this.toPosix(e??this.rootname(r)));return s=this.toPosix(s),s.startsWith("/")?Et.join(n,s.slice(1)):this.isAbsolute(s)?s:this.join(r,s)},normalize(s){if(zt(s),s.length===0)return".";if(this.isDataUrl(s)||this.isBlobUrl(s))return s;s=this.toPosix(s);let t="";const e=s.startsWith("/");this.hasProtocol(s)&&(t=this.rootname(s),s=s.slice(t.length));const r=s.endsWith("/");return s=gp(s),s.length>0&&r&&(s+="/"),e?`/${s}`:t+s},isAbsolute(s){return zt(s),s=this.toPosix(s),this.hasProtocol(s)?!0:s.startsWith("/")},join(...s){if(s.length===0)return".";let t;for(let e=0;e<s.length;++e){const r=s[e];if(zt(r),r.length>0)if(t===void 0)t=r;else{const n=s[e-1]??"";this.joinExtensions.includes(this.extname(n).toLowerCase())?t+=`/../${r}`:t+=`/${r}`}}return t===void 0?".":this.normalize(t)},dirname(s){if(zt(s),s.length===0)return".";s=this.toPosix(s);let t=s.charCodeAt(0);const e=t===47;let r=-1,n=!0;const a=this.getProtocol(s),l=s;s=s.slice(a.length);for(let h=s.length-1;h>=1;--h)if(t=s.charCodeAt(h),t===47){if(!n){r=h;break}}else n=!1;return r===-1?e?"/":this.isUrl(l)?a+s:a:e&&r===1?"//":a+s.slice(0,r)},rootname(s){zt(s),s=this.toPosix(s);let t="";if(s.startsWith("/")?t="/":t=this.getProtocol(s),this.isUrl(s)){const e=s.indexOf("/",t.length);e!==-1?t=s.slice(0,e):t=s,t.endsWith("/")||(t+="/")}return t},basename(s,t){zt(s),t&&zt(t),s=fi(this.toPosix(s));let e=0,r=-1,n=!0,a;if(t!==void 0&&t.length>0&&t.length<=s.length){if(t.length===s.length&&t===s)return"";let l=t.length-1,h=-1;for(a=s.length-1;a>=0;--a){const d=s.charCodeAt(a);if(d===47){if(!n){e=a+1;break}}else h===-1&&(n=!1,h=a+1),l>=0&&(d===t.charCodeAt(l)?--l===-1&&(r=a):(l=-1,r=h))}return e===r?r=h:r===-1&&(r=s.length),s.slice(e,r)}for(a=s.length-1;a>=0;--a)if(s.charCodeAt(a)===47){if(!n){e=a+1;break}}else r===-1&&(n=!1,r=a+1);return r===-1?"":s.slice(e,r)},extname(s){zt(s),s=fi(this.toPosix(s));let t=-1,e=0,r=-1,n=!0,a=0;for(let l=s.length-1;l>=0;--l){const h=s.charCodeAt(l);if(h===47){if(!n){e=l+1;break}continue}r===-1&&(n=!1,r=l+1),h===46?t===-1?t=l:a!==1&&(a=1):t!==-1&&(a=-1)}return t===-1||r===-1||a===0||a===1&&t===r-1&&t===e+1?"":s.slice(t,r)},parse(s){zt(s);const t={root:"",dir:"",base:"",ext:"",name:""};if(s.length===0)return t;s=fi(this.toPosix(s));let e=s.charCodeAt(0);const r=this.isAbsolute(s);let n;t.root=this.rootname(s),r||this.hasProtocol(s)?n=1:n=0;let a=-1,l=0,h=-1,d=!0,f=s.length-1,m=0;for(;f>=n;--f){if(e=s.charCodeAt(f),e===47){if(!d){l=f+1;break}continue}h===-1&&(d=!1,h=f+1),e===46?a===-1?a=f:m!==1&&(m=1):a!==-1&&(m=-1)}return a===-1||h===-1||m===0||m===1&&a===h-1&&a===l+1?h!==-1&&(l===0&&r?t.base=t.name=s.slice(1,h):t.base=t.name=s.slice(l,h)):(l===0&&r?(t.name=s.slice(1,a),t.base=s.slice(1,h)):(t.name=s.slice(l,a),t.base=s.slice(l,h)),t.ext=s.slice(a,h)),t.dir=this.dirname(s),t},sep:"/",delimiter:":",joinExtensions:[".html"]};function Mo(s,t,e,r,n){const a=t[e];for(let l=0;l<a.length;l++){const h=a[l];e<t.length-1?Mo(s.replace(r[e],h),t,e+1,r,n):n.push(s.replace(r[e],h))}}function _p(s){const t=/\{(.*?)\}/g,e=s.match(t),r=[];if(e){const n=[];e.forEach(a=>{const l=a.substring(1,a.length-1).split(",");n.push(l)}),Mo(s,n,0,e,r)}else r.push(s);return r}const gr=s=>!Array.isArray(s);class We{constructor(){this._defaultBundleIdentifierOptions={connector:"-",createBundleAssetId:(t,e)=>`${t}${this._bundleIdConnector}${e}`,extractAssetIdFromBundle:(t,e)=>e.replace(`${t}${this._bundleIdConnector}`,"")},this._bundleIdConnector=this._defaultBundleIdentifierOptions.connector,this._createBundleAssetId=this._defaultBundleIdentifierOptions.createBundleAssetId,this._extractAssetIdFromBundle=this._defaultBundleIdentifierOptions.extractAssetIdFromBundle,this._assetMap={},this._preferredOrder=[],this._parsers=[],this._resolverHash={},this._bundles={}}setBundleIdentifier(t){if(this._bundleIdConnector=t.connector??this._bundleIdConnector,this._createBundleAssetId=t.createBundleAssetId??this._createBundleAssetId,this._extractAssetIdFromBundle=t.extractAssetIdFromBundle??this._extractAssetIdFromBundle,this._extractAssetIdFromBundle("foo",this._createBundleAssetId("foo","bar"))!=="bar")throw new Error("[Resolver] GenerateBundleAssetId are not working correctly")}prefer(...t){t.forEach(e=>{this._preferredOrder.push(e),e.priority||(e.priority=Object.keys(e.params))}),this._resolverHash={}}set basePath(t){this._basePath=t}get basePath(){return this._basePath}set rootPath(t){this._rootPath=t}get rootPath(){return this._rootPath}get parsers(){return this._parsers}reset(){this.setBundleIdentifier(this._defaultBundleIdentifierOptions),this._assetMap={},this._preferredOrder=[],this._resolverHash={},this._rootPath=null,this._basePath=null,this._manifest=null,this._bundles={},this._defaultSearchParams=null}setDefaultSearchParams(t){if(typeof t=="string")this._defaultSearchParams=t;else{const e=t;this._defaultSearchParams=Object.keys(e).map(r=>`${encodeURIComponent(r)}=${encodeURIComponent(e[r])}`).join("&")}}getAlias(t){const{alias:e,src:r}=t;return Lt(e||r,a=>typeof a=="string"?a:Array.isArray(a)?a.map(l=>l?.src??l):a?.src?a.src:a,!0)}addManifest(t){this._manifest&&F("[Resolver] Manifest already exists, this will be overwritten"),this._manifest=t,t.bundles.forEach(e=>{this.addBundle(e.name,e.assets)})}addBundle(t,e){const r=[];let n=e;Array.isArray(e)||(n=Object.entries(e).map(([a,l])=>typeof l=="string"||Array.isArray(l)?{alias:a,src:l}:{alias:a,...l})),n.forEach(a=>{const l=a.src,h=a.alias;let d;if(typeof h=="string"){const f=this._createBundleAssetId(t,h);r.push(f),d=[h,f]}else{const f=h.map(m=>this._createBundleAssetId(t,m));r.push(...f),d=[...h,...f]}this.add({...a,alias:d,src:l})}),this._bundles[t]=r}add(t){const e=[];Array.isArray(t)?e.push(...t):e.push(t);let r;r=a=>{this.hasKey(a)&&F(`[Resolver] already has key: ${a} overwriting`)},Lt(e).forEach(a=>{const{src:l}=a;let{data:h,format:d,loadParser:f,parser:m}=a;const g=Lt(l).map(c=>typeof c=="string"?_p(c):Array.isArray(c)?c:[c]),y=this.getAlias(a);Array.isArray(y)?y.forEach(r):r(y);const x=[],o=c=>({...this._parsers.find(p=>p.test(c))?.parse(c),src:c});g.forEach(c=>{c.forEach(u=>{let p={};if(typeof u!="object"?p=o(u):(h=u.data??h,d=u.format??d,(u.loadParser||u.parser)&&(f=u.loadParser??f,m=u.parser??m),p={...o(u.src),...u}),!y)throw new Error(`[Resolver] alias is undefined for this asset: ${p.src}`);p=this._buildResolvedAsset(p,{aliases:y,data:h,format:d,loadParser:f,parser:m,progressSize:a.progressSize}),x.push(p)})}),y.forEach(c=>{this._assetMap[c]=x})})}resolveBundle(t){const e=gr(t);t=Lt(t);const r={};return t.forEach(n=>{const a=this._bundles[n];if(a){const l=this.resolve(a),h={};for(const d in l){const f=l[d];h[this._extractAssetIdFromBundle(n,d)]=f}r[n]=h}}),e?r[t[0]]:r}resolveUrl(t){const e=this.resolve(t);if(typeof t!="string"){const r={};for(const n in e)r[n]=e[n].src;return r}return e.src}resolve(t){const e=gr(t);t=Lt(t);const r={};return t.forEach(n=>{if(!this._resolverHash[n])if(this._assetMap[n]){let a=this._assetMap[n];const l=this._getPreferredOrder(a);l?.priority.forEach(h=>{l.params[h].forEach(d=>{const f=a.filter(m=>m[h]?m[h]===d:!1);f.length&&(a=f)})}),this._resolverHash[n]=a[0]}else this._resolverHash[n]=this._buildResolvedAsset({alias:[n],src:n},{});r[n]=this._resolverHash[n]}),e?r[t[0]]:r}hasKey(t){return!!this._assetMap[t]}hasBundle(t){return!!this._bundles[t]}_getPreferredOrder(t){for(let e=0;e<t.length;e++){const r=t[e],n=this._preferredOrder.find(a=>a.params.format.includes(r.format));if(n)return n}return this._preferredOrder[0]}_appendDefaultSearchParams(t){if(!this._defaultSearchParams)return t;const e=/\?/.test(t)?"&":"?";return`${t}${e}${this._defaultSearchParams}`}_buildResolvedAsset(t,e){const{aliases:r,data:n,loadParser:a,parser:l,format:h,progressSize:d}=e;return(this._basePath||this._rootPath)&&(t.src=Et.toAbsolute(t.src,this._basePath,this._rootPath)),t.alias=r??t.alias??[t.src],t.src=this._appendDefaultSearchParams(t.src),t.data={...n||{},...t.data},t.loadParser=a??t.loadParser,t.parser=l??t.parser,t.format=h??t.format??yp(t.src),d!==void 0&&(t.progressSize=d),t}}We.RETINA_PREFIX=/@([0-9\.]+)x/;function yp(s){return s.split(".").pop().split("?").shift().split("#").shift()}const Fs=(s,t)=>{const e=t.split("?")[1];return e&&(s+=`?${e}`),s},ko=class ji{constructor(t,e){this.linkedSheets=[];let r=t;t?.source instanceof ht&&(r={texture:t,data:e});const{texture:n,data:a,cachePrefix:l=""}=r;this.cachePrefix=l,this._texture=n instanceof M?n:null,this.textureSource=n.source,this.textures={},this.animations={},this.data=a;const h=parseFloat(a.meta.scale);h?(this.resolution=h,n.source.resolution=this.resolution):this.resolution=n.source._resolution,this._frames=this.data.frames,this._frameKeys=Object.keys(this._frames),this._batchIndex=0,this._callback=null}parse(){return new Promise(t=>{this._callback=t,this._batchIndex=0,this._frameKeys.length<=ji.BATCH_SIZE?(this._processFrames(0),this._processAnimations(),this._parseComplete()):this._nextBatch()})}_processFrames(t){let e=t;const r=ji.BATCH_SIZE;for(;e-t<r&&e<this._frameKeys.length;){const n=this._frameKeys[e],a=this._frames[n],l=a.frame;if(l){let h=null,d=null;const f=a.trimmed!==!1&&a.sourceSize?a.sourceSize:a.frame,m=new L(0,0,Math.floor(f.w)/this.resolution,Math.floor(f.h)/this.resolution);a.rotated?h=new L(Math.floor(l.x)/this.resolution,Math.floor(l.y)/this.resolution,Math.floor(l.h)/this.resolution,Math.floor(l.w)/this.resolution):h=new L(Math.floor(l.x)/this.resolution,Math.floor(l.y)/this.resolution,Math.floor(l.w)/this.resolution,Math.floor(l.h)/this.resolution),a.trimmed!==!1&&a.spriteSourceSize&&(d=new L(Math.floor(a.spriteSourceSize.x)/this.resolution,Math.floor(a.spriteSourceSize.y)/this.resolution,Math.floor(l.w)/this.resolution,Math.floor(l.h)/this.resolution)),this.textures[n]=new M({source:this.textureSource,frame:h,orig:m,trim:d,rotate:a.rotated?2:0,defaultAnchor:a.anchor,defaultBorders:a.borders,label:n.toString()})}e++}}_processAnimations(){const t=this.data.animations||{};for(const e in t){this.animations[e]=[];for(let r=0;r<t[e].length;r++){const n=t[e][r];this.animations[e].push(this.textures[n])}}}_parseComplete(){const t=this._callback;this._callback=null,this._batchIndex=0,t.call(this,this.textures)}_nextBatch(){this._processFrames(this._batchIndex*ji.BATCH_SIZE),this._batchIndex++,setTimeout(()=>{this._batchIndex*ji.BATCH_SIZE<this._frameKeys.length?this._nextBatch():(this._processAnimations(),this._parseComplete())},0)}destroy(t=!1){for(const e in this.textures)this.textures[e].destroy();this._frames=null,this._frameKeys=null,this.data=null,this.textures=null,t&&(this._texture?.destroy(),this.textureSource.destroy()),this._texture=null,this.textureSource=null,this.linkedSheets=[]}};ko.BATCH_SIZE=1e3;let Ro=ko;const xp=["jpg","png","jpeg","avif","webp","basis","etc2","bc7","bc6h","bc5","bc4","bc3","bc2","bc1","eac","astc"];function Io(s,t,e){const r={};if(s.forEach(n=>{r[n]=t}),Object.keys(t.textures).forEach(n=>{r[`${t.cachePrefix}${n}`]=t.textures[n]}),!e){const n=Et.dirname(s[0]);t.linkedSheets.forEach((a,l)=>{const h=Io([`${n}/${t.data.meta.related_multi_packs[l]}`],a,!0);Object.assign(r,h)})}return r}const bp={extension:C.Asset,cache:{test:s=>s instanceof Ro,getCacheableAssets:(s,t)=>Io(s,t,!1)},resolver:{extension:{type:C.ResolveParser,name:"resolveSpritesheet"},test:s=>{const e=s.split("?")[0].split("."),r=e.pop(),n=e.pop();return r==="json"&&xp.includes(n)},parse:s=>{const t=s.split(".");return{resolution:parseFloat(We.RETINA_PREFIX.exec(s)?.[1]??"1"),format:t[t.length-2],src:s}}},loader:{name:"spritesheetLoader",id:"spritesheet",extension:{type:C.LoadParser,priority:ce.Normal,name:"spritesheetLoader"},async testParse(s,t){return Et.extname(t.src).toLowerCase()===".json"&&!!s.frames},async parse(s,t,e){const{texture:r,imageFilename:n,textureOptions:a,cachePrefix:l}=t?.data??{};let h=Et.dirname(t.src);h&&h.lastIndexOf("/")!==h.length-1&&(h+="/");let d;if(r instanceof M)d=r;else{const g=Fs(h+(n??s.meta.image),t.src);d=(await e.load([{src:g,data:a}]))[g]}const f=new Ro({texture:d.source,data:s,cachePrefix:l});await f.parse();const m=s?.meta?.related_multi_packs;if(Array.isArray(m)){const g=[];for(const x of m){if(typeof x!="string")continue;let o=h+x;t.data?.ignoreMultiPack||(o=Fs(o,t.src),g.push(e.load({src:o,data:{textureOptions:a,ignoreMultiPack:!0}})))}const y=await Promise.all(g);f.linkedSheets=y,y.forEach(x=>{x.linkedSheets=[f].concat(f.linkedSheets.filter(o=>o!==x))})}return f},async unload(s,t,e){await e.unload(s.textureSource._sourceOrigin),s.destroy(!1)}}};D.add(bp);class Fo{constructor(t){this._lastTransform="",this._observer=null,this._tickerAttached=!1,this.updateTranslation=()=>{if(!this._canvas)return;const e=this._canvas.getBoundingClientRect(),r=this._canvas.width,n=this._canvas.height,a=e.width/r*this._renderer.resolution,l=e.height/n*this._renderer.resolution,h=e.left,d=e.top,f=`translate(${h}px, ${d}px) scale(${a}, ${l})`;f!==this._lastTransform&&(this._domElement.style.transform=f,this._lastTransform=f)},this._domElement=t.domElement,this._renderer=t.renderer,!(globalThis.OffscreenCanvas&&this._renderer.canvas instanceof OffscreenCanvas)&&(this._canvas=this._renderer.canvas,this._attachObserver())}get canvas(){return this._canvas}ensureAttached(){!this._domElement.parentNode&&this._canvas.parentNode&&(this._canvas.parentNode.appendChild(this._domElement),this.updateTranslation())}_attachObserver(){"ResizeObserver"in globalThis?(this._observer&&(this._observer.disconnect(),this._observer=null),this._observer=new ResizeObserver(t=>{for(const e of t){if(e.target!==this._canvas)continue;const r=this.canvas.width,n=this.canvas.height,a=e.contentRect.width/r*this._renderer.resolution,l=e.contentRect.height/n*this._renderer.resolution;(this._lastScaleX!==a||this._lastScaleY!==l)&&(this.updateTranslation(),this._lastScaleX=a,this._lastScaleY=l)}}),this._observer.observe(this._canvas)):this._tickerAttached||Ct.shared.add(this.updateTranslation,this,He.HIGH)}destroy(){this._observer?(this._observer.disconnect(),this._observer=null):this._tickerAttached&&Ct.shared.remove(this.updateTranslation),this._domElement=null,this._renderer=null,this._canvas=null,this._tickerAttached=!1,this._lastTransform="",this._lastScaleX=null,this._lastScaleY=null}}class pi{constructor(t){this.bubbles=!0,this.cancelBubble=!0,this.cancelable=!1,this.composed=!1,this.defaultPrevented=!1,this.eventPhase=pi.prototype.NONE,this.propagationStopped=!1,this.propagationImmediatelyStopped=!1,this.layer=new q,this.page=new q,this.NONE=0,this.CAPTURING_PHASE=1,this.AT_TARGET=2,this.BUBBLING_PHASE=3,this.manager=t}get layerX(){return this.layer.x}get layerY(){return this.layer.y}get pageX(){return this.page.x}get pageY(){return this.page.y}get data(){return this}composedPath(){return this.manager&&(!this.path||this.path[this.path.length-1]!==this.target)&&(this.path=this.target?this.manager.propagationPath(this.target):[]),this.path}initEvent(t,e,r){throw new Error("initEvent() is a legacy DOM API. It is not implemented in the Federated Events API.")}initUIEvent(t,e,r,n,a){throw new Error("initUIEvent() is a legacy DOM API. It is not implemented in the Federated Events API.")}preventDefault(){this.nativeEvent instanceof Event&&this.nativeEvent.cancelable&&this.nativeEvent.preventDefault(),this.defaultPrevented=!0}stopImmediatePropagation(){this.propagationImmediatelyStopped=!0}stopPropagation(){this.propagationStopped=!0}}var Ds=/iPhone/i,Do=/iPod/i,Go=/iPad/i,Oo=/\biOS-universal(?:.+)Mac\b/i,Gs=/\bAndroid(?:.+)Mobile\b/i,Lo=/Android/i,Ve=/(?:SD4930UR|\bSilk(?:.+)Mobile\b)/i,_r=/Silk/i,ie=/Windows Phone/i,zo=/\bWindows(?:.+)ARM\b/i,No=/BlackBerry/i,Ho=/BB10/i,Wo=/Opera Mini/i,Vo=/\b(CriOS|Chrome)(?:.+)Mobile/i,Yo=/Mobile(?:.+)Firefox\b/i,Xo=function(s){return typeof s<"u"&&s.platform==="MacIntel"&&typeof s.maxTouchPoints=="number"&&s.maxTouchPoints>1&&typeof MSStream>"u"};function vp(s){return function(t){return t.test(s)}}function $o(s){var t={userAgent:"",platform:"",maxTouchPoints:0};!s&&typeof navigator<"u"?t={userAgent:navigator.userAgent,platform:navigator.platform,maxTouchPoints:navigator.maxTouchPoints||0}:typeof s=="string"?t.userAgent=s:s&&s.userAgent&&(t={userAgent:s.userAgent,platform:s.platform,maxTouchPoints:s.maxTouchPoints||0});var e=t.userAgent,r=e.split("[FBAN");typeof r[1]<"u"&&(e=r[0]),r=e.split("Twitter"),typeof r[1]<"u"&&(e=r[0]);var n=vp(e),a={apple:{phone:n(Ds)&&!n(ie),ipod:n(Do),tablet:!n(Ds)&&(n(Go)||Xo(t))&&!n(ie),universal:n(Oo),device:(n(Ds)||n(Do)||n(Go)||n(Oo)||Xo(t))&&!n(ie)},amazon:{phone:n(Ve),tablet:!n(Ve)&&n(_r),device:n(Ve)||n(_r)},android:{phone:!n(ie)&&n(Ve)||!n(ie)&&n(Gs),tablet:!n(ie)&&!n(Ve)&&!n(Gs)&&(n(_r)||n(Lo)),device:!n(ie)&&(n(Ve)||n(_r)||n(Gs)||n(Lo))||n(/\bokhttp\b/i)},windows:{phone:n(ie),tablet:n(zo),device:n(ie)||n(zo)},other:{blackberry:n(No),blackberry10:n(Ho),opera:n(Wo),firefox:n(Yo),chrome:n(Vo),device:n(No)||n(Ho)||n(Wo)||n(Yo)||n(Vo)},any:!1,phone:!1,tablet:!1};return a.any=a.apple.device||a.android.device||a.windows.device||a.other.device,a.phone=a.apple.phone||a.android.phone||a.windows.phone,a.tablet=a.apple.tablet||a.android.tablet||a.windows.tablet,a}const wp=($o.default??$o)(globalThis.navigator),Sp=9,Ko=100,Tp=0,Cp=0,jo=2,qo=1,Ep=-1e3,Ap=-1e3,Pp=2,Os=class Ku{constructor(t,e=wp){this._mobileInfo=e,this.debug=!1,this._activateOnTab=!0,this._deactivateOnMouseMove=!0,this._isActive=!1,this._isMobileAccessibility=!1,this._div=null,this._pools={},this._renderId=0,this._children=[],this._androidUpdateCount=0,this._androidUpdateFrequency=500,this._isRunningTests=!1,this._boundOnKeyDown=this._onKeyDown.bind(this),this._boundOnMouseMove=this._onMouseMove.bind(this),this._hookDiv=null,(e.tablet||e.phone)&&this._createTouchHook(),this._renderer=t}get isActive(){return this._isActive}get isMobileAccessibility(){return this._isMobileAccessibility}get hookDiv(){return this._hookDiv}get div(){return this._div}_createTouchHook(){const t=document.createElement("button");t.style.width=`${qo}px`,t.style.height=`${qo}px`,t.style.position="absolute",t.style.top=`${Ep}px`,t.style.left=`${Ap}px`,t.style.zIndex=Pp.toString(),t.style.backgroundColor="#FF0000",t.title="select to enable accessibility for this content",t.addEventListener("focus",()=>{this._isMobileAccessibility=!0,this._activate(),this._destroyTouchHook()}),document.body.appendChild(t),this._hookDiv=t}_destroyTouchHook(){this._hookDiv&&(document.body.removeChild(this._hookDiv),this._hookDiv=null)}_activate(){if(this._isActive)return;this._isActive=!0,this._div||(this._div=document.createElement("div"),this._div.style.position="absolute",this._div.style.top=`${Tp}px`,this._div.style.left=`${Cp}px`,this._div.style.pointerEvents="none",this._div.style.zIndex=jo.toString(),this._canvasObserver=new Fo({domElement:this._div,renderer:this._renderer})),this._activateOnTab&&globalThis.addEventListener("keydown",this._boundOnKeyDown,!1),this._deactivateOnMouseMove&&globalThis.document.addEventListener("mousemove",this._boundOnMouseMove,!0);const t=this._renderer.view.canvas;if(t.parentNode)this._canvasObserver.ensureAttached(),this._initAccessibilitySetup();else{const e=new MutationObserver(()=>{t.parentNode&&(e.disconnect(),this._canvasObserver.ensureAttached(),this._initAccessibilitySetup())});e.observe(document.body,{childList:!0,subtree:!0})}}_initAccessibilitySetup(){this._renderer.runners.postrender.add(this),this._renderer.lastObjectRendered&&this._updateAccessibleObjects(this._renderer.lastObjectRendered)}_deactivate(){if(!(!this._isActive||this._isMobileAccessibility)){this._isActive=!1,globalThis.document.removeEventListener("mousemove",this._boundOnMouseMove,!0),this._activateOnTab&&globalThis.addEventListener("keydown",this._boundOnKeyDown,!1),this._renderer.runners.postrender.remove(this);for(const t of this._children)t._accessibleDiv?.parentNode&&(t._accessibleDiv.parentNode.removeChild(t._accessibleDiv),t._accessibleDiv=null),t._accessibleActive=!1;for(const t in this._pools)this._pools[t].forEach(r=>{r.parentNode&&r.parentNode.removeChild(r)}),delete this._pools[t];this._div?.parentNode&&this._div.parentNode.removeChild(this._div),this._pools={},this._children=[]}}_updateAccessibleObjects(t){if(!t.visible||!t.accessibleChildren)return;t.accessible&&(t._accessibleActive||this._addChild(t),t._renderId=this._renderId);const e=t.children;if(e)for(let r=0;r<e.length;r++)this._updateAccessibleObjects(e[r])}init(t){const r={accessibilityOptions:{...Ku.defaultOptions,...t?.accessibilityOptions||{}}};this.debug=r.accessibilityOptions.debug,this._activateOnTab=r.accessibilityOptions.activateOnTab,this._deactivateOnMouseMove=r.accessibilityOptions.deactivateOnMouseMove,r.accessibilityOptions.enabledByDefault&&this._activate(),this._renderer.runners.postrender.remove(this)}postrender(){const t=performance.now();if(this._mobileInfo.android.device&&t<this._androidUpdateCount||(this._androidUpdateCount=t+this._androidUpdateFrequency,(!this._renderer.renderingToScreen||!this._renderer.view.canvas)&&!this._isRunningTests))return;const e=new Set;if(this._renderer.lastObjectRendered){this._updateAccessibleObjects(this._renderer.lastObjectRendered);for(const r of this._children)r._renderId===this._renderId&&e.add(this._children.indexOf(r))}for(let r=this._children.length-1;r>=0;r--){const n=this._children[r];e.has(r)||(n._accessibleDiv&&n._accessibleDiv.parentNode&&(n._accessibleDiv.parentNode.removeChild(n._accessibleDiv),this._getPool(n.accessibleType).push(n._accessibleDiv),n._accessibleDiv=null),n._accessibleActive=!1,po(this._children,r,1))}this._renderer.renderingToScreen&&this._canvasObserver.ensureAttached();for(let r=0;r<this._children.length;r++){const n=this._children[r];if(!n._accessibleActive||!n._accessibleDiv)continue;const a=n._accessibleDiv,l=n.hitArea||n.getBounds().rectangle;if(n.hitArea){const h=n.worldTransform;a.style.left=`${h.tx+l.x*h.a}px`,a.style.top=`${h.ty+l.y*h.d}px`,a.style.width=`${l.width*h.a}px`,a.style.height=`${l.height*h.d}px`}else this._capHitArea(l),a.style.left=`${l.x}px`,a.style.top=`${l.y}px`,a.style.width=`${l.width}px`,a.style.height=`${l.height}px`}this._renderId++}_updateDebugHTML(t){t.innerHTML=`type: ${t.type}</br> title : ${t.title}</br> tabIndex: ${t.tabIndex}`}_capHitArea(t){t.x<0&&(t.width+=t.x,t.x=0),t.y<0&&(t.height+=t.y,t.y=0);const{width:e,height:r}=this._renderer;t.x+t.width>e&&(t.width=e-t.x),t.y+t.height>r&&(t.height=r-t.y)}_addChild(t){let r=this._getPool(t.accessibleType).pop();r?(r.innerHTML="",r.removeAttribute("title"),r.removeAttribute("aria-label"),r.tabIndex=0):(t.accessibleType==="button"?r=document.createElement("button"):(r=document.createElement(t.accessibleType),r.style.cssText=`
|
|
67
|
+
`),o?(console.groupCollapsed("%cPixiJS Deprecation Warning: %c%s","color:#614108;background:#fffbe6","font-weight:normal;color:#614108;background:#fffbe6",n),console.warn(r),console.groupEnd()):(console.warn("PixiJS Deprecation Warning: ",n),console.warn(r))),qo.add(t)};Object.defineProperties(z,{quiet:{get:()=>Le.quiet,set:s=>{Le.quiet=s},enumerable:!0,configurable:!1},noColor:{get:()=>Le.noColor,set:s=>{Le.noColor=s},enumerable:!0,configurable:!1}});const Zo=()=>{};function ze(s){return s+=s===0?1:0,--s,s|=s>>>1,s|=s>>>2,s|=s>>>4,s|=s>>>8,s|=s>>>16,s+1}function Qo(s){return!(s&s-1)&&!!s}function Jo(s){const t={};for(const e in s)s[e]!==void 0&&(t[e]=s[e]);return t}const ta=Object.create(null);function Hf(s){const t=ta[s];return t===void 0&&(ta[s]=et("resource")),t}const ea=class jd extends Ct{constructor(t={}){super(),this._resourceType="textureSampler",this._touched=0,this._maxAnisotropy=1,this.destroyed=!1,t={...jd.defaultOptions,...t},this.addressMode=t.addressMode,this.addressModeU=t.addressModeU??this.addressModeU,this.addressModeV=t.addressModeV??this.addressModeV,this.addressModeW=t.addressModeW??this.addressModeW,this.scaleMode=t.scaleMode,this.magFilter=t.magFilter??this.magFilter,this.minFilter=t.minFilter??this.minFilter,this.mipmapFilter=t.mipmapFilter??this.mipmapFilter,this.lodMinClamp=t.lodMinClamp,this.lodMaxClamp=t.lodMaxClamp,this.compare=t.compare,this.maxAnisotropy=t.maxAnisotropy??1}set addressMode(t){this.addressModeU=t,this.addressModeV=t,this.addressModeW=t}get addressMode(){return this.addressModeU}set wrapMode(t){z($,"TextureStyle.wrapMode is now TextureStyle.addressMode"),this.addressMode=t}get wrapMode(){return this.addressMode}set scaleMode(t){this.magFilter=t,this.minFilter=t,this.mipmapFilter=t}get scaleMode(){return this.magFilter}set maxAnisotropy(t){this._maxAnisotropy=Math.min(t,16),this._maxAnisotropy>1&&(this.scaleMode="linear")}get maxAnisotropy(){return this._maxAnisotropy}get _resourceId(){return this._sharedResourceId||this._generateResourceId()}update(){this.emit("change",this),this._sharedResourceId=null}_generateResourceId(){const t=`${this.addressModeU}-${this.addressModeV}-${this.addressModeW}-${this.magFilter}-${this.minFilter}-${this.mipmapFilter}-${this.lodMinClamp}-${this.lodMaxClamp}-${this.compare}-${this._maxAnisotropy}`;return this._sharedResourceId=Hf(t),this._resourceId}destroy(){this.destroyed=!0,this.emit("destroy",this),this.emit("change",this),this.removeAllListeners()}};ea.defaultOptions={addressMode:"clamp-to-edge",scaleMode:"linear"};let jt=ea;const ia=class qd extends Ct{constructor(t={}){super(),this.options=t,this.uid=et("textureSource"),this._resourceType="textureSource",this._resourceId=et("resource"),this.uploadMethodId="unknown",this._resolution=1,this.pixelWidth=1,this.pixelHeight=1,this.width=1,this.height=1,this.sampleCount=1,this.mipLevelCount=1,this.autoGenerateMipmaps=!1,this.format="rgba8unorm",this.dimension="2d",this.antialias=!1,this._touched=0,this._batchTick=-1,this._textureBindLocation=-1,t={...qd.defaultOptions,...t},this.label=t.label??"",this.resource=t.resource,this.autoGarbageCollect=t.autoGarbageCollect,this._resolution=t.resolution,t.width?this.pixelWidth=t.width*this._resolution:this.pixelWidth=this.resource?this.resourceWidth??1:1,t.height?this.pixelHeight=t.height*this._resolution:this.pixelHeight=this.resource?this.resourceHeight??1:1,this.width=this.pixelWidth/this._resolution,this.height=this.pixelHeight/this._resolution,this.format=t.format,this.dimension=t.dimensions,this.mipLevelCount=t.mipLevelCount,this.autoGenerateMipmaps=t.autoGenerateMipmaps,this.sampleCount=t.sampleCount,this.antialias=t.antialias,this.alphaMode=t.alphaMode,this.style=new jt(Jo(t)),this.destroyed=!1,this._refreshPOT()}get source(){return this}get style(){return this._style}set style(t){this.style!==t&&(this._style?.off("change",this._onStyleChange,this),this._style=t,this._style?.on("change",this._onStyleChange,this),this._onStyleChange())}set maxAnisotropy(t){this._style.maxAnisotropy=t}get maxAnisotropy(){return this._style.maxAnisotropy}get addressMode(){return this._style.addressMode}set addressMode(t){this._style.addressMode=t}get repeatMode(){return this._style.addressMode}set repeatMode(t){this._style.addressMode=t}get magFilter(){return this._style.magFilter}set magFilter(t){this._style.magFilter=t}get minFilter(){return this._style.minFilter}set minFilter(t){this._style.minFilter=t}get mipmapFilter(){return this._style.mipmapFilter}set mipmapFilter(t){this._style.mipmapFilter=t}get lodMinClamp(){return this._style.lodMinClamp}set lodMinClamp(t){this._style.lodMinClamp=t}get lodMaxClamp(){return this._style.lodMaxClamp}set lodMaxClamp(t){this._style.lodMaxClamp=t}_onStyleChange(){this.emit("styleChange",this)}update(){if(this.resource){const t=this._resolution;if(this.resize(this.resourceWidth/t,this.resourceHeight/t))return}this.emit("update",this)}destroy(){this.destroyed=!0,this.emit("destroy",this),this.emit("change",this),this._style&&(this._style.destroy(),this._style=null),this.uploadMethodId=null,this.resource=null,this.removeAllListeners()}unload(){this._resourceId=et("resource"),this.emit("change",this),this.emit("unload",this)}get resourceWidth(){const{resource:t}=this;return t.naturalWidth||t.videoWidth||t.displayWidth||t.width}get resourceHeight(){const{resource:t}=this;return t.naturalHeight||t.videoHeight||t.displayHeight||t.height}get resolution(){return this._resolution}set resolution(t){this._resolution!==t&&(this._resolution=t,this.width=this.pixelWidth/t,this.height=this.pixelHeight/t)}resize(t,e,r){r||(r=this._resolution),t||(t=this.width),e||(e=this.height);const n=Math.round(t*r),o=Math.round(e*r);return this.width=n/r,this.height=o/r,this._resolution=r,this.pixelWidth===n&&this.pixelHeight===o?!1:(this._refreshPOT(),this.pixelWidth=n,this.pixelHeight=o,this.emit("resize",this),this._resourceId=et("resource"),this.emit("change",this),!0)}updateMipmaps(){this.autoGenerateMipmaps&&this.mipLevelCount>1&&this.emit("updateMipmaps",this)}set wrapMode(t){this._style.wrapMode=t}get wrapMode(){return this._style.wrapMode}set scaleMode(t){this._style.scaleMode=t}get scaleMode(){return this._style.scaleMode}_refreshPOT(){this.isPowerOfTwo=Qo(this.pixelWidth)&&Qo(this.pixelHeight)}static test(t){throw new Error("Unimplemented")}};ia.defaultOptions={resolution:1,format:"bgra8unorm",alphaMode:"premultiply-alpha-on-upload",dimensions:"2d",mipLevelCount:1,autoGenerateMipmaps:!1,sampleCount:1,antialias:!1,autoGarbageCollect:!1};let ht=ia;class xs extends ht{constructor(t){const e=t.resource||new Float32Array(t.width*t.height*4);let r=t.format;r||(e instanceof Float32Array?r="rgba32float":e instanceof Int32Array||e instanceof Uint32Array?r="rgba32uint":e instanceof Int16Array||e instanceof Uint16Array?r="rgba16uint":(e instanceof Int8Array,r="bgra8unorm")),super({...t,resource:e,format:r}),this.uploadMethodId="buffer"}static test(t){return t instanceof Int8Array||t instanceof Uint8Array||t instanceof Uint8ClampedArray||t instanceof Int16Array||t instanceof Uint16Array||t instanceof Int32Array||t instanceof Uint32Array||t instanceof Float32Array}}xs.extension=C.TextureSource;const ra=new M;class sa{constructor(t,e){this.mapCoord=new M,this.uClampFrame=new Float32Array(4),this.uClampOffset=new Float32Array(2),this._textureID=-1,this._updateID=0,this.clampOffset=0,typeof e>"u"?this.clampMargin=t.width<10?0:.5:this.clampMargin=e,this.isSimple=!1,this.texture=t}get texture(){return this._texture}set texture(t){this.texture!==t&&(this._texture?.removeListener("update",this.update,this),this._texture=t,this._texture.addListener("update",this.update,this),this.update())}multiplyUvs(t,e){e===void 0&&(e=t);const r=this.mapCoord;for(let n=0;n<t.length;n+=2){const o=t[n],l=t[n+1];e[n]=o*r.a+l*r.c+r.tx,e[n+1]=o*r.b+l*r.d+r.ty}return e}update(){const t=this._texture;this._updateID++;const e=t.uvs;this.mapCoord.set(e.x1-e.x0,e.y1-e.y0,e.x3-e.x0,e.y3-e.y0,e.x0,e.y0);const r=t.orig,n=t.trim;n&&(ra.set(r.width/n.width,0,0,r.height/n.height,-n.x/n.width,-n.y/n.height),this.mapCoord.append(ra));const o=t.source,l=this.uClampFrame,h=this.clampMargin/o._resolution,u=this.clampOffset/o._resolution;return l[0]=(t.frame.x+h+u)/o.width,l[1]=(t.frame.y+h+u)/o.height,l[2]=(t.frame.x+t.frame.width-h+u)/o.width,l[3]=(t.frame.y+t.frame.height-h+u)/o.height,this.uClampOffset[0]=this.clampOffset/o.pixelWidth,this.uClampOffset[1]=this.clampOffset/o.pixelHeight,this.isSimple=t.frame.width===o.width&&t.frame.height===o.height&&t.rotate===0,!0}}class k extends Ct{constructor({source:t,label:e,frame:r,orig:n,trim:o,defaultAnchor:l,defaultBorders:h,rotate:u,dynamic:f}={}){if(super(),this.uid=et("texture"),this.uvs={x0:0,y0:0,x1:0,y1:0,x2:0,y2:0,x3:0,y3:0},this.frame=new G,this.noFrame=!1,this.dynamic=!1,this.isTexture=!0,this.label=e,this.source=t?.source??new ht,this.noFrame=!r,r)this.frame.copyFrom(r);else{const{width:m,height:g}=this._source;this.frame.width=m,this.frame.height=g}this.orig=n||this.frame,this.trim=o,this.rotate=u??0,this.defaultAnchor=l,this.defaultBorders=h,this.destroyed=!1,this.dynamic=f||!1,this.updateUvs()}set source(t){this._source&&this._source.off("resize",this.update,this),this._source=t,t.on("resize",this.update,this),this.emit("update",this)}get source(){return this._source}get textureMatrix(){return this._textureMatrix||(this._textureMatrix=new sa(this)),this._textureMatrix}get width(){return this.orig.width}get height(){return this.orig.height}updateUvs(){const{uvs:t,frame:e}=this,{width:r,height:n}=this._source,o=e.x/r,l=e.y/n,h=e.width/r,u=e.height/n;let f=this.rotate;if(f){const m=h/2,g=u/2,y=o+m,x=l+g;f=Z.add(f,Z.NW),t.x0=y+m*Z.uX(f),t.y0=x+g*Z.uY(f),f=Z.add(f,2),t.x1=y+m*Z.uX(f),t.y1=x+g*Z.uY(f),f=Z.add(f,2),t.x2=y+m*Z.uX(f),t.y2=x+g*Z.uY(f),f=Z.add(f,2),t.x3=y+m*Z.uX(f),t.y3=x+g*Z.uY(f)}else t.x0=o,t.y0=l,t.x1=o+h,t.y1=l,t.x2=o+h,t.y2=l+u,t.x3=o,t.y3=l+u}destroy(t=!1){this._source&&(this._source.off("resize",this.update,this),t&&(this._source.destroy(),this._source=null)),this._textureMatrix=null,this.destroyed=!0,this.emit("destroy",this),this.removeAllListeners()}update(){this.noFrame&&(this.frame.width=this._source.width,this.frame.height=this._source.height),this.updateUvs(),this.emit("update",this)}get baseTexture(){return z($,"Texture.baseTexture is now Texture.source"),this._source}}k.EMPTY=new k({label:"EMPTY",source:new ht({label:"EMPTY"})}),k.EMPTY.destroy=Zo,k.WHITE=new k({source:new xs({resource:new Uint8Array([255,255,255,255]),width:1,height:1,alphaMode:"premultiply-alpha-on-upload",label:"WHITE"}),label:"WHITE"}),k.WHITE.destroy=Zo;function na(s,t,e){const{width:r,height:n}=e.orig,o=e.trim;if(o){const l=o.width,h=o.height;s.minX=o.x-t._x*r,s.maxX=s.minX+l,s.minY=o.y-t._y*n,s.maxY=s.minY+h}else s.minX=-t._x*r,s.maxX=s.minX+r,s.minY=-t._y*n,s.maxY=s.minY+n}const oa=new M;class ut{constructor(t=1/0,e=1/0,r=-1/0,n=-1/0){this.minX=1/0,this.minY=1/0,this.maxX=-1/0,this.maxY=-1/0,this.matrix=oa,this.minX=t,this.minY=e,this.maxX=r,this.maxY=n}isEmpty(){return this.minX>this.maxX||this.minY>this.maxY}get rectangle(){this._rectangle||(this._rectangle=new G);const t=this._rectangle;return this.minX>this.maxX||this.minY>this.maxY?(t.x=0,t.y=0,t.width=0,t.height=0):t.copyFromBounds(this),t}clear(){return this.minX=1/0,this.minY=1/0,this.maxX=-1/0,this.maxY=-1/0,this.matrix=oa,this}set(t,e,r,n){this.minX=t,this.minY=e,this.maxX=r,this.maxY=n}addFrame(t,e,r,n,o){o||(o=this.matrix);const l=o.a,h=o.b,u=o.c,f=o.d,m=o.tx,g=o.ty;let y=this.minX,x=this.minY,a=this.maxX,c=this.maxY,d=l*t+u*e+m,p=h*t+f*e+g;d<y&&(y=d),p<x&&(x=p),d>a&&(a=d),p>c&&(c=p),d=l*r+u*e+m,p=h*r+f*e+g,d<y&&(y=d),p<x&&(x=p),d>a&&(a=d),p>c&&(c=p),d=l*t+u*n+m,p=h*t+f*n+g,d<y&&(y=d),p<x&&(x=p),d>a&&(a=d),p>c&&(c=p),d=l*r+u*n+m,p=h*r+f*n+g,d<y&&(y=d),p<x&&(x=p),d>a&&(a=d),p>c&&(c=p),this.minX=y,this.minY=x,this.maxX=a,this.maxY=c}addRect(t,e){this.addFrame(t.x,t.y,t.x+t.width,t.y+t.height,e)}addBounds(t,e){this.addFrame(t.minX,t.minY,t.maxX,t.maxY,e)}addBoundsMask(t){this.minX=this.minX>t.minX?this.minX:t.minX,this.minY=this.minY>t.minY?this.minY:t.minY,this.maxX=this.maxX<t.maxX?this.maxX:t.maxX,this.maxY=this.maxY<t.maxY?this.maxY:t.maxY}applyMatrix(t){const e=this.minX,r=this.minY,n=this.maxX,o=this.maxY,{a:l,b:h,c:u,d:f,tx:m,ty:g}=t;let y=l*e+u*r+m,x=h*e+f*r+g;this.minX=y,this.minY=x,this.maxX=y,this.maxY=x,y=l*n+u*r+m,x=h*n+f*r+g,this.minX=y<this.minX?y:this.minX,this.minY=x<this.minY?x:this.minY,this.maxX=y>this.maxX?y:this.maxX,this.maxY=x>this.maxY?x:this.maxY,y=l*e+u*o+m,x=h*e+f*o+g,this.minX=y<this.minX?y:this.minX,this.minY=x<this.minY?x:this.minY,this.maxX=y>this.maxX?y:this.maxX,this.maxY=x>this.maxY?x:this.maxY,y=l*n+u*o+m,x=h*n+f*o+g,this.minX=y<this.minX?y:this.minX,this.minY=x<this.minY?x:this.minY,this.maxX=y>this.maxX?y:this.maxX,this.maxY=x>this.maxY?x:this.maxY}fit(t){return this.minX<t.left&&(this.minX=t.left),this.maxX>t.right&&(this.maxX=t.right),this.minY<t.top&&(this.minY=t.top),this.maxY>t.bottom&&(this.maxY=t.bottom),this}fitBounds(t,e,r,n){return this.minX<t&&(this.minX=t),this.maxX>e&&(this.maxX=e),this.minY<r&&(this.minY=r),this.maxY>n&&(this.maxY=n),this}pad(t,e=t){return this.minX-=t,this.maxX+=t,this.minY-=e,this.maxY+=e,this}ceil(){return this.minX=Math.floor(this.minX),this.minY=Math.floor(this.minY),this.maxX=Math.ceil(this.maxX),this.maxY=Math.ceil(this.maxY),this}clone(){return new ut(this.minX,this.minY,this.maxX,this.maxY)}scale(t,e=t){return this.minX*=t,this.minY*=e,this.maxX*=t,this.maxY*=e,this}get x(){return this.minX}set x(t){const e=this.maxX-this.minX;this.minX=t,this.maxX=t+e}get y(){return this.minY}set y(t){const e=this.maxY-this.minY;this.minY=t,this.maxY=t+e}get width(){return this.maxX-this.minX}set width(t){this.maxX=this.minX+t}get height(){return this.maxY-this.minY}set height(t){this.maxY=this.minY+t}get left(){return this.minX}get right(){return this.maxX}get top(){return this.minY}get bottom(){return this.maxY}get isPositive(){return this.maxX-this.minX>0&&this.maxY-this.minY>0}get isValid(){return this.minX+this.minY!==1/0}addVertexData(t,e,r,n){let o=this.minX,l=this.minY,h=this.maxX,u=this.maxY;n||(n=this.matrix);const f=n.a,m=n.b,g=n.c,y=n.d,x=n.tx,a=n.ty;for(let c=e;c<r;c+=2){const d=t[c],p=t[c+1],_=f*d+g*p+x,b=m*d+y*p+a;o=_<o?_:o,l=b<l?b:l,h=_>h?_:h,u=b>u?b:u}this.minX=o,this.minY=l,this.maxX=h,this.maxY=u}containsPoint(t,e){return this.minX<=t&&this.minY<=e&&this.maxX>=t&&this.maxY>=e}toString(){return`[pixi.js:Bounds minX=${this.minX} minY=${this.minY} maxX=${this.maxX} maxY=${this.maxY} width=${this.width} height=${this.height}]`}copyFrom(t){return this.minX=t.minX,this.minY=t.minY,this.maxX=t.maxX,this.maxY=t.maxY,this}}var Wf={grad:.9,turn:360,rad:360/(2*Math.PI)},te=function(s){return typeof s=="string"?s.length>0:typeof s=="number"},lt=function(s,t,e){return t===void 0&&(t=0),e===void 0&&(e=Math.pow(10,t)),Math.round(e*s)/e+0},It=function(s,t,e){return t===void 0&&(t=0),e===void 0&&(e=1),s>e?e:s>t?s:t},aa=function(s){return(s=isFinite(s)?s%360:0)>0?s:s+360},ha=function(s){return{r:It(s.r,0,255),g:It(s.g,0,255),b:It(s.b,0,255),a:It(s.a)}},bs=function(s){return{r:lt(s.r),g:lt(s.g),b:lt(s.b),a:lt(s.a,3)}},Vf=/^#([0-9a-f]{3,8})$/i,cr=function(s){var t=s.toString(16);return t.length<2?"0"+t:t},la=function(s){var t=s.r,e=s.g,r=s.b,n=s.a,o=Math.max(t,e,r),l=o-Math.min(t,e,r),h=l?o===t?(e-r)/l:o===e?2+(r-t)/l:4+(t-e)/l:0;return{h:60*(h<0?h+6:h),s:o?l/o*100:0,v:o/255*100,a:n}},ca=function(s){var t=s.h,e=s.s,r=s.v,n=s.a;t=t/360*6,e/=100,r/=100;var o=Math.floor(t),l=r*(1-e),h=r*(1-(t-o)*e),u=r*(1-(1-t+o)*e),f=o%6;return{r:255*[r,h,l,l,u,r][f],g:255*[u,r,r,h,l,l][f],b:255*[l,l,u,r,r,h][f],a:n}},da=function(s){return{h:aa(s.h),s:It(s.s,0,100),l:It(s.l,0,100),a:It(s.a)}},ua=function(s){return{h:lt(s.h),s:lt(s.s),l:lt(s.l),a:lt(s.a,3)}},fa=function(s){return ca((e=(t=s).s,{h:t.h,s:(e*=((r=t.l)<50?r:100-r)/100)>0?2*e/(r+e)*100:0,v:r+e,a:t.a}));var t,e,r},di=function(s){return{h:(t=la(s)).h,s:(n=(200-(e=t.s))*(r=t.v)/100)>0&&n<200?e*r/100/(n<=100?n:200-n)*100:0,l:n/2,a:t.a};var t,e,r,n},Yf=/^hsla?\(\s*([+-]?\d*\.?\d+)(deg|rad|grad|turn)?\s*,\s*([+-]?\d*\.?\d+)%\s*,\s*([+-]?\d*\.?\d+)%\s*(?:,\s*([+-]?\d*\.?\d+)(%)?\s*)?\)$/i,Xf=/^hsla?\(\s*([+-]?\d*\.?\d+)(deg|rad|grad|turn)?\s+([+-]?\d*\.?\d+)%\s+([+-]?\d*\.?\d+)%\s*(?:\/\s*([+-]?\d*\.?\d+)(%)?\s*)?\)$/i,$f=/^rgba?\(\s*([+-]?\d*\.?\d+)(%)?\s*,\s*([+-]?\d*\.?\d+)(%)?\s*,\s*([+-]?\d*\.?\d+)(%)?\s*(?:,\s*([+-]?\d*\.?\d+)(%)?\s*)?\)$/i,Kf=/^rgba?\(\s*([+-]?\d*\.?\d+)(%)?\s+([+-]?\d*\.?\d+)(%)?\s+([+-]?\d*\.?\d+)(%)?\s*(?:\/\s*([+-]?\d*\.?\d+)(%)?\s*)?\)$/i,vs={string:[[function(s){var t=Vf.exec(s);return t?(s=t[1]).length<=4?{r:parseInt(s[0]+s[0],16),g:parseInt(s[1]+s[1],16),b:parseInt(s[2]+s[2],16),a:s.length===4?lt(parseInt(s[3]+s[3],16)/255,2):1}:s.length===6||s.length===8?{r:parseInt(s.substr(0,2),16),g:parseInt(s.substr(2,2),16),b:parseInt(s.substr(4,2),16),a:s.length===8?lt(parseInt(s.substr(6,2),16)/255,2):1}:null:null},"hex"],[function(s){var t=$f.exec(s)||Kf.exec(s);return t?t[2]!==t[4]||t[4]!==t[6]?null:ha({r:Number(t[1])/(t[2]?100/255:1),g:Number(t[3])/(t[4]?100/255:1),b:Number(t[5])/(t[6]?100/255:1),a:t[7]===void 0?1:Number(t[7])/(t[8]?100:1)}):null},"rgb"],[function(s){var t=Yf.exec(s)||Xf.exec(s);if(!t)return null;var e,r,n=da({h:(e=t[1],r=t[2],r===void 0&&(r="deg"),Number(e)*(Wf[r]||1)),s:Number(t[3]),l:Number(t[4]),a:t[5]===void 0?1:Number(t[5])/(t[6]?100:1)});return fa(n)},"hsl"]],object:[[function(s){var t=s.r,e=s.g,r=s.b,n=s.a,o=n===void 0?1:n;return te(t)&&te(e)&&te(r)?ha({r:Number(t),g:Number(e),b:Number(r),a:Number(o)}):null},"rgb"],[function(s){var t=s.h,e=s.s,r=s.l,n=s.a,o=n===void 0?1:n;if(!te(t)||!te(e)||!te(r))return null;var l=da({h:Number(t),s:Number(e),l:Number(r),a:Number(o)});return fa(l)},"hsl"],[function(s){var t=s.h,e=s.s,r=s.v,n=s.a,o=n===void 0?1:n;if(!te(t)||!te(e)||!te(r))return null;var l=(function(h){return{h:aa(h.h),s:It(h.s,0,100),v:It(h.v,0,100),a:It(h.a)}})({h:Number(t),s:Number(e),v:Number(r),a:Number(o)});return ca(l)},"hsv"]]},pa=function(s,t){for(var e=0;e<t.length;e++){var r=t[e][0](s);if(r)return[r,t[e][1]]}return[null,void 0]},jf=function(s){return typeof s=="string"?pa(s.trim(),vs.string):typeof s=="object"&&s!==null?pa(s,vs.object):[null,void 0]},ws=function(s,t){var e=di(s);return{h:e.h,s:It(e.s+100*t,0,100),l:e.l,a:e.a}},Ss=function(s){return(299*s.r+587*s.g+114*s.b)/1e3/255},ma=function(s,t){var e=di(s);return{h:e.h,s:e.s,l:It(e.l+100*t,0,100),a:e.a}},Ts=(function(){function s(t){this.parsed=jf(t)[0],this.rgba=this.parsed||{r:0,g:0,b:0,a:1}}return s.prototype.isValid=function(){return this.parsed!==null},s.prototype.brightness=function(){return lt(Ss(this.rgba),2)},s.prototype.isDark=function(){return Ss(this.rgba)<.5},s.prototype.isLight=function(){return Ss(this.rgba)>=.5},s.prototype.toHex=function(){return t=bs(this.rgba),e=t.r,r=t.g,n=t.b,l=(o=t.a)<1?cr(lt(255*o)):"","#"+cr(e)+cr(r)+cr(n)+l;var t,e,r,n,o,l},s.prototype.toRgb=function(){return bs(this.rgba)},s.prototype.toRgbString=function(){return t=bs(this.rgba),e=t.r,r=t.g,n=t.b,(o=t.a)<1?"rgba("+e+", "+r+", "+n+", "+o+")":"rgb("+e+", "+r+", "+n+")";var t,e,r,n,o},s.prototype.toHsl=function(){return ua(di(this.rgba))},s.prototype.toHslString=function(){return t=ua(di(this.rgba)),e=t.h,r=t.s,n=t.l,(o=t.a)<1?"hsla("+e+", "+r+"%, "+n+"%, "+o+")":"hsl("+e+", "+r+"%, "+n+"%)";var t,e,r,n,o},s.prototype.toHsv=function(){return t=la(this.rgba),{h:lt(t.h),s:lt(t.s),v:lt(t.v),a:lt(t.a,3)};var t},s.prototype.invert=function(){return qt({r:255-(t=this.rgba).r,g:255-t.g,b:255-t.b,a:t.a});var t},s.prototype.saturate=function(t){return t===void 0&&(t=.1),qt(ws(this.rgba,t))},s.prototype.desaturate=function(t){return t===void 0&&(t=.1),qt(ws(this.rgba,-t))},s.prototype.grayscale=function(){return qt(ws(this.rgba,-1))},s.prototype.lighten=function(t){return t===void 0&&(t=.1),qt(ma(this.rgba,t))},s.prototype.darken=function(t){return t===void 0&&(t=.1),qt(ma(this.rgba,-t))},s.prototype.rotate=function(t){return t===void 0&&(t=15),this.hue(this.hue()+t)},s.prototype.alpha=function(t){return typeof t=="number"?qt({r:(e=this.rgba).r,g:e.g,b:e.b,a:t}):lt(this.rgba.a,3);var e},s.prototype.hue=function(t){var e=di(this.rgba);return typeof t=="number"?qt({h:t,s:e.s,l:e.l,a:e.a}):lt(e.h)},s.prototype.isEqual=function(t){return this.toHex()===qt(t).toHex()},s})(),qt=function(s){return s instanceof Ts?s:new Ts(s)},ga=[],qf=function(s){s.forEach(function(t){ga.indexOf(t)<0&&(t(Ts,vs),ga.push(t))})};function Zf(s,t){var e={white:"#ffffff",bisque:"#ffe4c4",blue:"#0000ff",cadetblue:"#5f9ea0",chartreuse:"#7fff00",chocolate:"#d2691e",coral:"#ff7f50",antiquewhite:"#faebd7",aqua:"#00ffff",azure:"#f0ffff",whitesmoke:"#f5f5f5",papayawhip:"#ffefd5",plum:"#dda0dd",blanchedalmond:"#ffebcd",black:"#000000",gold:"#ffd700",goldenrod:"#daa520",gainsboro:"#dcdcdc",cornsilk:"#fff8dc",cornflowerblue:"#6495ed",burlywood:"#deb887",aquamarine:"#7fffd4",beige:"#f5f5dc",crimson:"#dc143c",cyan:"#00ffff",darkblue:"#00008b",darkcyan:"#008b8b",darkgoldenrod:"#b8860b",darkkhaki:"#bdb76b",darkgray:"#a9a9a9",darkgreen:"#006400",darkgrey:"#a9a9a9",peachpuff:"#ffdab9",darkmagenta:"#8b008b",darkred:"#8b0000",darkorchid:"#9932cc",darkorange:"#ff8c00",darkslateblue:"#483d8b",gray:"#808080",darkslategray:"#2f4f4f",darkslategrey:"#2f4f4f",deeppink:"#ff1493",deepskyblue:"#00bfff",wheat:"#f5deb3",firebrick:"#b22222",floralwhite:"#fffaf0",ghostwhite:"#f8f8ff",darkviolet:"#9400d3",magenta:"#ff00ff",green:"#008000",dodgerblue:"#1e90ff",grey:"#808080",honeydew:"#f0fff0",hotpink:"#ff69b4",blueviolet:"#8a2be2",forestgreen:"#228b22",lawngreen:"#7cfc00",indianred:"#cd5c5c",indigo:"#4b0082",fuchsia:"#ff00ff",brown:"#a52a2a",maroon:"#800000",mediumblue:"#0000cd",lightcoral:"#f08080",darkturquoise:"#00ced1",lightcyan:"#e0ffff",ivory:"#fffff0",lightyellow:"#ffffe0",lightsalmon:"#ffa07a",lightseagreen:"#20b2aa",linen:"#faf0e6",mediumaquamarine:"#66cdaa",lemonchiffon:"#fffacd",lime:"#00ff00",khaki:"#f0e68c",mediumseagreen:"#3cb371",limegreen:"#32cd32",mediumspringgreen:"#00fa9a",lightskyblue:"#87cefa",lightblue:"#add8e6",midnightblue:"#191970",lightpink:"#ffb6c1",mistyrose:"#ffe4e1",moccasin:"#ffe4b5",mintcream:"#f5fffa",lightslategray:"#778899",lightslategrey:"#778899",navajowhite:"#ffdead",navy:"#000080",mediumvioletred:"#c71585",powderblue:"#b0e0e6",palegoldenrod:"#eee8aa",oldlace:"#fdf5e6",paleturquoise:"#afeeee",mediumturquoise:"#48d1cc",mediumorchid:"#ba55d3",rebeccapurple:"#663399",lightsteelblue:"#b0c4de",mediumslateblue:"#7b68ee",thistle:"#d8bfd8",tan:"#d2b48c",orchid:"#da70d6",mediumpurple:"#9370db",purple:"#800080",pink:"#ffc0cb",skyblue:"#87ceeb",springgreen:"#00ff7f",palegreen:"#98fb98",red:"#ff0000",yellow:"#ffff00",slateblue:"#6a5acd",lavenderblush:"#fff0f5",peru:"#cd853f",palevioletred:"#db7093",violet:"#ee82ee",teal:"#008080",slategray:"#708090",slategrey:"#708090",aliceblue:"#f0f8ff",darkseagreen:"#8fbc8f",darkolivegreen:"#556b2f",greenyellow:"#adff2f",seagreen:"#2e8b57",seashell:"#fff5ee",tomato:"#ff6347",silver:"#c0c0c0",sienna:"#a0522d",lavender:"#e6e6fa",lightgreen:"#90ee90",orange:"#ffa500",orangered:"#ff4500",steelblue:"#4682b4",royalblue:"#4169e1",turquoise:"#40e0d0",yellowgreen:"#9acd32",salmon:"#fa8072",saddlebrown:"#8b4513",sandybrown:"#f4a460",rosybrown:"#bc8f8f",darksalmon:"#e9967a",lightgoldenrodyellow:"#fafad2",snow:"#fffafa",lightgrey:"#d3d3d3",lightgray:"#d3d3d3",dimgray:"#696969",dimgrey:"#696969",olivedrab:"#6b8e23",olive:"#808000"},r={};for(var n in e)r[e[n]]=n;var o={};s.prototype.toName=function(l){if(!(this.rgba.a||this.rgba.r||this.rgba.g||this.rgba.b))return"transparent";var h,u,f=r[this.toHex()];if(f)return f;if(l?.closest){var m=this.toRgb(),g=1/0,y="black";if(!o.length)for(var x in e)o[x]=new s(e[x]).toRgb();for(var a in e){var c=(h=m,u=o[a],Math.pow(h.r-u.r,2)+Math.pow(h.g-u.g,2)+Math.pow(h.b-u.b,2));c<g&&(g=c,y=a)}return y}},t.string.push([function(l){var h=l.toLowerCase(),u=h==="transparent"?"#0000":e[h];return u?new s(u).toRgb():null},"name"])}qf([Zf]);const Ne=class ji{constructor(t=16777215){this._value=null,this._components=new Float32Array(4),this._components.fill(1),this._int=16777215,this.value=t}get red(){return this._components[0]}get green(){return this._components[1]}get blue(){return this._components[2]}get alpha(){return this._components[3]}setValue(t){return this.value=t,this}set value(t){if(t instanceof ji)this._value=this._cloneSource(t._value),this._int=t._int,this._components.set(t._components);else{if(t===null)throw new Error("Cannot set Color#value to null");(this._value===null||!this._isSourceEqual(this._value,t))&&(this._value=this._cloneSource(t),this._normalize(this._value))}}get value(){return this._value}_cloneSource(t){return typeof t=="string"||typeof t=="number"||t instanceof Number||t===null?t:Array.isArray(t)||ArrayBuffer.isView(t)?t.slice(0):typeof t=="object"&&t!==null?{...t}:t}_isSourceEqual(t,e){const r=typeof t;if(r!==typeof e)return!1;if(r==="number"||r==="string"||t instanceof Number)return t===e;if(Array.isArray(t)&&Array.isArray(e)||ArrayBuffer.isView(t)&&ArrayBuffer.isView(e))return t.length!==e.length?!1:t.every((o,l)=>o===e[l]);if(t!==null&&e!==null){const o=Object.keys(t),l=Object.keys(e);return o.length!==l.length?!1:o.every(h=>t[h]===e[h])}return t===e}toRgba(){const[t,e,r,n]=this._components;return{r:t,g:e,b:r,a:n}}toRgb(){const[t,e,r]=this._components;return{r:t,g:e,b:r}}toRgbaString(){const[t,e,r]=this.toUint8RgbArray();return`rgba(${t},${e},${r},${this.alpha})`}toUint8RgbArray(t){const[e,r,n]=this._components;return this._arrayRgb||(this._arrayRgb=[]),t||(t=this._arrayRgb),t[0]=Math.round(e*255),t[1]=Math.round(r*255),t[2]=Math.round(n*255),t}toArray(t){this._arrayRgba||(this._arrayRgba=[]),t||(t=this._arrayRgba);const[e,r,n,o]=this._components;return t[0]=e,t[1]=r,t[2]=n,t[3]=o,t}toRgbArray(t){this._arrayRgb||(this._arrayRgb=[]),t||(t=this._arrayRgb);const[e,r,n]=this._components;return t[0]=e,t[1]=r,t[2]=n,t}toNumber(){return this._int}toBgrNumber(){const[t,e,r]=this.toUint8RgbArray();return(r<<16)+(e<<8)+t}toLittleEndianNumber(){const t=this._int;return(t>>16)+(t&65280)+((t&255)<<16)}multiply(t){const[e,r,n,o]=ji._temp.setValue(t)._components;return this._components[0]*=e,this._components[1]*=r,this._components[2]*=n,this._components[3]*=o,this._refreshInt(),this._value=null,this}premultiply(t,e=!0){return e&&(this._components[0]*=t,this._components[1]*=t,this._components[2]*=t),this._components[3]=t,this._refreshInt(),this._value=null,this}toPremultiplied(t,e=!0){if(t===1)return(255<<24)+this._int;if(t===0)return e?0:this._int;let r=this._int>>16&255,n=this._int>>8&255,o=this._int&255;return e&&(r=r*t+.5|0,n=n*t+.5|0,o=o*t+.5|0),(t*255<<24)+(r<<16)+(n<<8)+o}toHex(){const t=this._int.toString(16);return`#${"000000".substring(0,6-t.length)+t}`}toHexa(){const e=Math.round(this._components[3]*255).toString(16);return this.toHex()+"00".substring(0,2-e.length)+e}setAlpha(t){return this._components[3]=this._clamp(t),this}_normalize(t){let e,r,n,o;if((typeof t=="number"||t instanceof Number)&&t>=0&&t<=16777215){const l=t;e=(l>>16&255)/255,r=(l>>8&255)/255,n=(l&255)/255,o=1}else if((Array.isArray(t)||t instanceof Float32Array)&&t.length>=3&&t.length<=4)t=this._clamp(t),[e,r,n,o=1]=t;else if((t instanceof Uint8Array||t instanceof Uint8ClampedArray)&&t.length>=3&&t.length<=4)t=this._clamp(t,0,255),[e,r,n,o=255]=t,e/=255,r/=255,n/=255,o/=255;else if(typeof t=="string"||typeof t=="object"){if(typeof t=="string"){const h=ji.HEX_PATTERN.exec(t);h&&(t=`#${h[2]}`)}const l=qt(t);l.isValid()&&({r:e,g:r,b:n,a:o}=l.rgba,e/=255,r/=255,n/=255)}if(e!==void 0)this._components[0]=e,this._components[1]=r,this._components[2]=n,this._components[3]=o,this._refreshInt();else throw new Error(`Unable to convert color ${t}`)}_refreshInt(){this._clamp(this._components);const[t,e,r]=this._components;this._int=(t*255<<16)+(e*255<<8)+(r*255|0)}_clamp(t,e=0,r=1){return typeof t=="number"?Math.min(Math.max(t,e),r):(t.forEach((n,o)=>{t[o]=Math.min(Math.max(n,e),r)}),t)}static isColorLike(t){return typeof t=="number"||typeof t=="string"||t instanceof Number||t instanceof ji||Array.isArray(t)||t instanceof Uint8Array||t instanceof Uint8ClampedArray||t instanceof Float32Array||t.r!==void 0&&t.g!==void 0&&t.b!==void 0||t.r!==void 0&&t.g!==void 0&&t.b!==void 0&&t.a!==void 0||t.h!==void 0&&t.s!==void 0&&t.l!==void 0||t.h!==void 0&&t.s!==void 0&&t.l!==void 0&&t.a!==void 0||t.h!==void 0&&t.s!==void 0&&t.v!==void 0||t.h!==void 0&&t.s!==void 0&&t.v!==void 0&&t.a!==void 0}};Ne.shared=new Ne,Ne._temp=new Ne,Ne.HEX_PATTERN=/^(#|0x)?(([a-f0-9]{3}){1,2}([a-f0-9]{2})?)$/i;let J=Ne;const Qf={cullArea:null,cullable:!1,cullableChildren:!0};let Cs=0;const _a=500;function F(...s){Cs!==_a&&(Cs++,Cs===_a?console.warn("PixiJS Warning: too many warnings, no more warnings will be reported to the console by PixiJS."):console.warn("PixiJS Warning: ",...s))}const He={_registeredResources:new Set,register(s){this._registeredResources.add(s)},unregister(s){this._registeredResources.delete(s)},release(){this._registeredResources.forEach(s=>s.clear())},get registeredCount(){return this._registeredResources.size},isRegistered(s){return this._registeredResources.has(s)},reset(){this._registeredResources.clear()}};class Jf{constructor(t,e){this._pool=[],this._count=0,this._index=0,this._classType=t,e&&this.prepopulate(e)}prepopulate(t){for(let e=0;e<t;e++)this._pool[this._index++]=new this._classType;this._count+=t}get(t){let e;return this._index>0?e=this._pool[--this._index]:(e=new this._classType,this._count++),e.init?.(t),e}return(t){t.reset?.(),this._pool[this._index++]=t}get totalSize(){return this._count}get totalFree(){return this._index}get totalUsed(){return this._count-this._index}clear(){if(this._pool.length>0&&this._pool[0].destroy)for(let t=0;t<this._index;t++)this._pool[t].destroy();this._pool.length=0,this._count=0,this._index=0}}class tp{constructor(){this._poolsByClass=new Map}prepopulate(t,e){this.getPool(t).prepopulate(e)}get(t,e){return this.getPool(t).get(e)}return(t){this.getPool(t.constructor).return(t)}getPool(t){return this._poolsByClass.has(t)||this._poolsByClass.set(t,new Jf(t)),this._poolsByClass.get(t)}stats(){const t={};return this._poolsByClass.forEach(e=>{const r=t[e._classType.name]?e._classType.name+e._classType.ID:e._classType.name;t[r]={free:e.totalFree,used:e.totalUsed,size:e.totalSize}}),t}clear(){this._poolsByClass.forEach(t=>t.clear()),this._poolsByClass.clear()}}const at=new tp;He.register(at);const ep={get isCachedAsTexture(){return!!this.renderGroup?.isCachedAsTexture},cacheAsTexture(s){typeof s=="boolean"&&s===!1?this.disableRenderGroup():(this.enableRenderGroup(),this.renderGroup.enableCacheAsTexture(s===!0?{}:s))},updateCacheTexture(){this.renderGroup?.updateCacheTexture()},get cacheAsBitmap(){return this.isCachedAsTexture},set cacheAsBitmap(s){z("v8.6.0","cacheAsBitmap is deprecated, use cacheAsTexture instead."),this.cacheAsTexture(s)}};function ya(s,t,e){const r=s.length;let n;if(t>=r||e===0)return;e=t+e>r?r-t:e;const o=r-e;for(n=t;n<o;++n)s[n]=s[n+e];s.length=o}const ip={allowChildren:!0,removeChildren(s=0,t){const e=t??this.children.length,r=e-s,n=[];if(r>0&&r<=e){for(let l=e-1;l>=s;l--){const h=this.children[l];h&&(n.push(h),h.parent=null)}ya(this.children,s,e);const o=this.renderGroup||this.parentRenderGroup;o&&o.removeChildren(n);for(let l=0;l<n.length;++l){const h=n[l];h.parentRenderLayer?.detach(h),this.emit("childRemoved",h,this,l),n[l].emit("removed",this)}return n.length>0&&this._didViewChangeTick++,n}else if(r===0&&this.children.length===0)return n;throw new RangeError("removeChildren: numeric values are outside the acceptable range.")},removeChildAt(s){const t=this.getChildAt(s);return this.removeChild(t)},getChildAt(s){if(s<0||s>=this.children.length)throw new Error(`getChildAt: Index (${s}) does not exist.`);return this.children[s]},setChildIndex(s,t){if(t<0||t>=this.children.length)throw new Error(`The index ${t} supplied is out of bounds ${this.children.length}`);this.getChildIndex(s),this.addChildAt(s,t)},getChildIndex(s){const t=this.children.indexOf(s);if(t===-1)throw new Error("The supplied Container must be a child of the caller");return t},addChildAt(s,t){this.allowChildren||z($,"addChildAt: Only Containers will be allowed to add children in v8.0.0");const{children:e}=this;if(t<0||t>e.length)throw new Error(`${s}addChildAt: The index ${t} supplied is out of bounds ${e.length}`);if(s.parent){const n=s.parent.children.indexOf(s);if(s.parent===this&&n===t)return s;n!==-1&&s.parent.children.splice(n,1)}t===e.length?e.push(s):e.splice(t,0,s),s.parent=this,s.didChange=!0,s._updateFlags=15;const r=this.renderGroup||this.parentRenderGroup;return r&&r.addChild(s),this.sortableChildren&&(this.sortDirty=!0),this.emit("childAdded",s,this,t),s.emit("added",this),s},swapChildren(s,t){if(s===t)return;const e=this.getChildIndex(s),r=this.getChildIndex(t);this.children[e]=t,this.children[r]=s;const n=this.renderGroup||this.parentRenderGroup;n&&(n.structureDidChange=!0),this._didContainerChangeTick++},removeFromParent(){this.parent?.removeChild(this)},reparentChild(...s){return s.length===1?this.reparentChildAt(s[0],this.children.length):(s.forEach(t=>this.reparentChildAt(t,this.children.length)),s[0])},reparentChildAt(s,t){if(s.parent===this)return this.setChildIndex(s,t),s;const e=s.worldTransform.clone();s.removeFromParent(),this.addChildAt(s,t);const r=this.worldTransform.clone();return r.invert(),e.prepend(r),s.setFromMatrix(e),s},replaceChild(s,t){s.updateLocalTransform(),this.addChildAt(t,this.getChildIndex(s)),t.setFromMatrix(s.localTransform),t.updateLocalTransform(),this.removeChild(s)}},rp={collectRenderables(s,t,e){this.parentRenderLayer&&this.parentRenderLayer!==e||this.globalDisplayStatus<7||!this.includeInBuild||(this.sortableChildren&&this.sortChildren(),this.isSimple?this.collectRenderablesSimple(s,t,e):this.renderGroup?t.renderPipes.renderGroup.addRenderGroup(this.renderGroup,s):this.collectRenderablesWithEffects(s,t,e))},collectRenderablesSimple(s,t,e){const r=this.children,n=r.length;for(let o=0;o<n;o++)r[o].collectRenderables(s,t,e)},collectRenderablesWithEffects(s,t,e){const{renderPipes:r}=t;for(let n=0;n<this.effects.length;n++){const o=this.effects[n];r[o.pipe].push(o,this,s)}this.collectRenderablesSimple(s,t,e);for(let n=this.effects.length-1;n>=0;n--){const o=this.effects[n];r[o.pipe].pop(o,this,s)}}};class dr{constructor(){this.pipe="filter",this.priority=1}destroy(){for(let t=0;t<this.filters.length;t++)this.filters[t].destroy();this.filters=null,this.filterArea=null}}class sp{constructor(){this._effectClasses=[],this._tests=[],this._initialized=!1}init(){this._initialized||(this._initialized=!0,this._effectClasses.forEach(t=>{this.add({test:t.test,maskClass:t})}))}add(t){this._tests.push(t)}getMaskEffect(t){this._initialized||this.init();for(let e=0;e<this._tests.length;e++){const r=this._tests[e];if(r.test(t))return at.get(r.maskClass,t)}return t}returnMaskEffect(t){at.return(t)}}const Es=new sp;D.handleByList(C.MaskEffect,Es._effectClasses);const np={_maskEffect:null,_maskOptions:{inverse:!1},_filterEffect:null,effects:[],_markStructureAsChanged(){const s=this.renderGroup||this.parentRenderGroup;s&&(s.structureDidChange=!0)},addEffect(s){this.effects.indexOf(s)===-1&&(this.effects.push(s),this.effects.sort((e,r)=>e.priority-r.priority),this._markStructureAsChanged(),this._updateIsSimple())},removeEffect(s){const t=this.effects.indexOf(s);t!==-1&&(this.effects.splice(t,1),this._markStructureAsChanged(),this._updateIsSimple())},set mask(s){const t=this._maskEffect;t?.mask!==s&&(t&&(this.removeEffect(t),Es.returnMaskEffect(t),this._maskEffect=null),s!=null&&(this._maskEffect=Es.getMaskEffect(s),this.addEffect(this._maskEffect)))},get mask(){return this._maskEffect?.mask},setMask(s){this._maskOptions={...this._maskOptions,...s},s.mask&&(this.mask=s.mask),this._markStructureAsChanged()},set filters(s){!Array.isArray(s)&&s&&(s=[s]);const t=this._filterEffect||(this._filterEffect=new dr);s=s;const e=s?.length>0,r=t.filters?.length>0,n=e!==r;s=Array.isArray(s)?s.slice(0):s,t.filters=Object.freeze(s),n&&(e?this.addEffect(t):(this.removeEffect(t),t.filters=s??null))},get filters(){return this._filterEffect?.filters},set filterArea(s){this._filterEffect||(this._filterEffect=new dr),this._filterEffect.filterArea=s},get filterArea(){return this._filterEffect?.filterArea}},op={label:null,get name(){return z($,"Container.name property has been removed, use Container.label instead"),this.label},set name(s){z($,"Container.name property has been removed, use Container.label instead"),this.label=s},getChildByName(s,t=!1){return this.getChildByLabel(s,t)},getChildByLabel(s,t=!1){const e=this.children;for(let r=0;r<e.length;r++){const n=e[r];if(n.label===s||s instanceof RegExp&&s.test(n.label))return n}if(t)for(let r=0;r<e.length;r++){const o=e[r].getChildByLabel(s,!0);if(o)return o}return null},getChildrenByLabel(s,t=!1,e=[]){const r=this.children;for(let n=0;n<r.length;n++){const o=r[n];(o.label===s||s instanceof RegExp&&s.test(o.label))&&e.push(o)}if(t)for(let n=0;n<r.length;n++)r[n].getChildrenByLabel(s,!0,e);return e}},gt=at.getPool(M),ee=at.getPool(ut),ap=new M,hp={getFastGlobalBounds(s,t){t||(t=new ut),t.clear(),this._getGlobalBoundsRecursive(!!s,t,this.parentRenderLayer),t.isValid||t.set(0,0,0,0);const e=this.renderGroup||this.parentRenderGroup;return t.applyMatrix(e.worldTransform),t},_getGlobalBoundsRecursive(s,t,e){let r=t;if(s&&this.parentRenderLayer&&this.parentRenderLayer!==e||this.localDisplayStatus!==7||!this.measurable)return;const n=!!this.effects.length;if((this.renderGroup||n)&&(r=ee.get().clear()),this.boundsArea)t.addRect(this.boundsArea,this.worldTransform);else{if(this.renderPipeId){const l=this.bounds;r.addFrame(l.minX,l.minY,l.maxX,l.maxY,this.groupTransform)}const o=this.children;for(let l=0;l<o.length;l++)o[l]._getGlobalBoundsRecursive(s,r,e)}if(n){let o=!1;const l=this.renderGroup||this.parentRenderGroup;for(let h=0;h<this.effects.length;h++)this.effects[h].addBounds&&(o||(o=!0,r.applyMatrix(l.worldTransform)),this.effects[h].addBounds(r,!0));o&&r.applyMatrix(l.worldTransform.copyTo(ap).invert()),t.addBounds(r),ee.return(r)}else this.renderGroup&&(t.addBounds(r,this.relativeGroupTransform),ee.return(r))}};function As(s,t,e){e.clear();let r,n;return s.parent?t?r=s.parent.worldTransform:(n=gt.get().identity(),r=Ps(s,n)):r=M.IDENTITY,xa(s,e,r,t),n&>.return(n),e.isValid||e.set(0,0,0,0),e}function xa(s,t,e,r){if(!s.visible||!s.measurable)return;let n;r?n=s.worldTransform:(s.updateLocalTransform(),n=gt.get(),n.appendFrom(s.localTransform,e));const o=t,l=!!s.effects.length;if(l&&(t=ee.get().clear()),s.boundsArea)t.addRect(s.boundsArea,n);else{const h=s.bounds;h&&!h.isEmpty()&&(t.matrix=n,t.addBounds(h));for(let u=0;u<s.children.length;u++)xa(s.children[u],t,n,r)}if(l){for(let h=0;h<s.effects.length;h++)s.effects[h].addBounds?.(t);o.addBounds(t,M.IDENTITY),ee.return(t)}r||gt.return(n)}function Ps(s,t){const e=s.parent;return e&&(Ps(e,t),e.updateLocalTransform(),t.append(e.localTransform)),t}function ba(s,t){if(s===16777215||!t)return t;if(t===16777215||!s)return s;const e=s>>16&255,r=s>>8&255,n=s&255,o=t>>16&255,l=t>>8&255,h=t&255,u=e*o/255|0,f=r*l/255|0,m=n*h/255|0;return(u<<16)+(f<<8)+m}const va=16777215;function ur(s,t){return s===va?t:t===va?s:ba(s,t)}function fr(s){return((s&255)<<16)+(s&65280)+(s>>16&255)}const lp={getGlobalAlpha(s){if(s)return this.renderGroup?this.renderGroup.worldAlpha:this.parentRenderGroup?this.parentRenderGroup.worldAlpha*this.alpha:this.alpha;let t=this.alpha,e=this.parent;for(;e;)t*=e.alpha,e=e.parent;return t},getGlobalTransform(s=new M,t){if(t)return s.copyFrom(this.worldTransform);this.updateLocalTransform();const e=Ps(this,gt.get().identity());return s.appendFrom(this.localTransform,e),gt.return(e),s},getGlobalTint(s){if(s)return this.renderGroup?fr(this.renderGroup.worldColor):this.parentRenderGroup?fr(ur(this.localColor,this.parentRenderGroup.worldColor)):this.tint;let t=this.localColor,e=this.parent;for(;e;)t=ur(t,e.localColor),e=e.parent;return fr(t)}};function Bs(s,t,e){return t.clear(),e||(e=M.IDENTITY),wa(s,t,e,s,!0),t.isValid||t.set(0,0,0,0),t}function wa(s,t,e,r,n){let o;if(n)o=gt.get(),o=e.copyTo(o);else{if(!s.visible||!s.measurable)return;s.updateLocalTransform();const u=s.localTransform;o=gt.get(),o.appendFrom(u,e)}const l=t,h=!!s.effects.length;if(h&&(t=ee.get().clear()),s.boundsArea)t.addRect(s.boundsArea,o);else{s.renderPipeId&&(t.matrix=o,t.addBounds(s.bounds));const u=s.children;for(let f=0;f<u.length;f++)wa(u[f],t,o,r,!1)}if(h){for(let u=0;u<s.effects.length;u++)s.effects[u].addLocalBounds?.(t,r);l.addBounds(t,M.IDENTITY),ee.return(t)}gt.return(o)}function Sa(s,t){const e=s.children;for(let r=0;r<e.length;r++){const n=e[r],o=n.uid,l=(n._didViewChangeTick&65535)<<16|n._didContainerChangeTick&65535,h=t.index;(t.data[h]!==o||t.data[h+1]!==l)&&(t.data[t.index]=o,t.data[t.index+1]=l,t.didChange=!0),t.index=h+2,n.children.length&&Sa(n,t)}return t.didChange}const cp=new M,dp={_localBoundsCacheId:-1,_localBoundsCacheData:null,_setWidth(s,t){const e=Math.sign(this.scale.x)||1;t!==0?this.scale.x=s/t*e:this.scale.x=e},_setHeight(s,t){const e=Math.sign(this.scale.y)||1;t!==0?this.scale.y=s/t*e:this.scale.y=e},getLocalBounds(){this._localBoundsCacheData||(this._localBoundsCacheData={data:[],index:1,didChange:!1,localBounds:new ut});const s=this._localBoundsCacheData;return s.index=1,s.didChange=!1,s.data[0]!==this._didViewChangeTick&&(s.didChange=!0,s.data[0]=this._didViewChangeTick),Sa(this,s),s.didChange&&Bs(this,s.localBounds,cp),s.localBounds},getBounds(s,t){return As(this,s,t||new ut)}},up={_onRender:null,set onRender(s){const t=this.renderGroup||this.parentRenderGroup;if(!s){this._onRender&&t?.removeOnRender(this),this._onRender=null;return}this._onRender||t?.addOnRender(this),this._onRender=s},get onRender(){return this._onRender}},fp={_zIndex:0,sortDirty:!1,sortableChildren:!1,get zIndex(){return this._zIndex},set zIndex(s){this._zIndex!==s&&(this._zIndex=s,this.depthOfChildModified())},depthOfChildModified(){this.parent&&(this.parent.sortableChildren=!0,this.parent.sortDirty=!0),this.parentRenderGroup&&(this.parentRenderGroup.structureDidChange=!0)},sortChildren(){this.sortDirty&&(this.sortDirty=!1,this.children.sort(pp))}};function pp(s,t){return s._zIndex-t._zIndex}const mp={getGlobalPosition(s=new q,t=!1){return this.parent?this.parent.toGlobal(this._position,s,t):(s.x=this._position.x,s.y=this._position.y),s},toGlobal(s,t,e=!1){const r=this.getGlobalTransform(gt.get(),e);return t=r.apply(s,t),gt.return(r),t},toLocal(s,t,e,r){t&&(s=t.toGlobal(s,e,r));const n=this.getGlobalTransform(gt.get(),r);return e=n.applyInverse(s,e),gt.return(n),e}};class Ta{constructor(){this.uid=et("instructionSet"),this.instructions=[],this.instructionSize=0,this.renderables=[],this.gcTick=0}reset(){this.instructionSize=0}destroy(){this.instructions.length=0,this.renderables.length=0,this.renderPipes=null,this.gcTick=0}add(t){this.instructions[this.instructionSize++]=t}log(){this.instructions.length=this.instructionSize,console.table(this.instructions,["type","action"])}}let gp=0;class _p{constructor(t){this._poolKeyHash=Object.create(null),this._texturePool={},this.textureOptions=t||{},this.enableFullScreen=!1,this.textureStyle=new jt(this.textureOptions)}createTexture(t,e,r){const n=new ht({...this.textureOptions,width:t,height:e,resolution:1,antialias:r,autoGarbageCollect:!1});return new k({source:n,label:`texturePool_${gp++}`})}getOptimalTexture(t,e,r=1,n){let o=Math.ceil(t*r-1e-6),l=Math.ceil(e*r-1e-6);o=ze(o),l=ze(l);const h=(o<<17)+(l<<1)+(n?1:0);this._texturePool[h]||(this._texturePool[h]=[]);let u=this._texturePool[h].pop();return u||(u=this.createTexture(o,l,n)),u.source._resolution=r,u.source.width=o/r,u.source.height=l/r,u.source.pixelWidth=o,u.source.pixelHeight=l,u.frame.x=0,u.frame.y=0,u.frame.width=t,u.frame.height=e,u.updateUvs(),this._poolKeyHash[u.uid]=h,u}getSameSizeTexture(t,e=!1){const r=t.source;return this.getOptimalTexture(t.width,t.height,r._resolution,e)}returnTexture(t,e=!1){const r=this._poolKeyHash[t.uid];e&&(t.source.style=this.textureStyle),this._texturePool[r].push(t)}clear(t){if(t=t!==!1,t)for(const e in this._texturePool){const r=this._texturePool[e];if(r)for(let n=0;n<r.length;n++)r[n].destroy(!0)}this._texturePool={}}}const dt=new _p;He.register(dt);class Us{constructor(){this.renderPipeId="renderGroup",this.root=null,this.canBundle=!1,this.renderGroupParent=null,this.renderGroupChildren=[],this.worldTransform=new M,this.worldColorAlpha=4294967295,this.worldColor=16777215,this.worldAlpha=1,this.childrenToUpdate=Object.create(null),this.updateTick=0,this.gcTick=0,this.childrenRenderablesToUpdate={list:[],index:0},this.structureDidChange=!0,this.instructionSet=new Ta,this._onRenderContainers=[],this.textureNeedsUpdate=!0,this.isCachedAsTexture=!1,this._matrixDirty=7}init(t){this.root=t,t._onRender&&this.addOnRender(t),t.didChange=!0;const e=t.children;for(let r=0;r<e.length;r++){const n=e[r];n._updateFlags=15,this.addChild(n)}}enableCacheAsTexture(t={}){this.textureOptions=t,this.isCachedAsTexture=!0,this.textureNeedsUpdate=!0}disableCacheAsTexture(){this.isCachedAsTexture=!1,this.texture&&(dt.returnTexture(this.texture,!0),this.texture=null)}updateCacheTexture(){this.textureNeedsUpdate=!0;const t=this._parentCacheAsTextureRenderGroup;t&&!t.textureNeedsUpdate&&t.updateCacheTexture()}reset(){this.renderGroupChildren.length=0;for(const t in this.childrenToUpdate){const e=this.childrenToUpdate[t];e.list.fill(null),e.index=0}this.childrenRenderablesToUpdate.index=0,this.childrenRenderablesToUpdate.list.fill(null),this.root=null,this.updateTick=0,this.structureDidChange=!0,this._onRenderContainers.length=0,this.renderGroupParent=null,this.disableCacheAsTexture()}get localTransform(){return this.root.localTransform}addRenderGroupChild(t){t.renderGroupParent&&t.renderGroupParent._removeRenderGroupChild(t),t.renderGroupParent=this,this.renderGroupChildren.push(t)}_removeRenderGroupChild(t){const e=this.renderGroupChildren.indexOf(t);e>-1&&this.renderGroupChildren.splice(e,1),t.renderGroupParent=null}addChild(t){if(this.structureDidChange=!0,t.parentRenderGroup=this,t.updateTick=-1,t.parent===this.root?t.relativeRenderGroupDepth=1:t.relativeRenderGroupDepth=t.parent.relativeRenderGroupDepth+1,t.didChange=!0,this.onChildUpdate(t),t.renderGroup){this.addRenderGroupChild(t.renderGroup);return}t._onRender&&this.addOnRender(t);const e=t.children;for(let r=0;r<e.length;r++)this.addChild(e[r])}removeChild(t){if(this.structureDidChange=!0,t._onRender&&(t.renderGroup||this.removeOnRender(t)),t.parentRenderGroup=null,t.renderGroup){this._removeRenderGroupChild(t.renderGroup);return}const e=t.children;for(let r=0;r<e.length;r++)this.removeChild(e[r])}removeChildren(t){for(let e=0;e<t.length;e++)this.removeChild(t[e])}onChildUpdate(t){let e=this.childrenToUpdate[t.relativeRenderGroupDepth];e||(e=this.childrenToUpdate[t.relativeRenderGroupDepth]={index:0,list:[]}),e.list[e.index++]=t}updateRenderable(t){t.globalDisplayStatus<7||(this.instructionSet.renderPipes[t.renderPipeId].updateRenderable(t),t.didViewUpdate=!1)}onChildViewUpdate(t){this.childrenRenderablesToUpdate.list[this.childrenRenderablesToUpdate.index++]=t}get isRenderable(){return this.root.localDisplayStatus===7&&this.worldAlpha>0}addOnRender(t){this._onRenderContainers.push(t)}removeOnRender(t){this._onRenderContainers.splice(this._onRenderContainers.indexOf(t),1)}runOnRender(t){for(let e=0;e<this._onRenderContainers.length;e++)this._onRenderContainers[e]._onRender(t)}destroy(){this.disableCacheAsTexture(),this.renderGroupParent=null,this.root=null,this.childrenRenderablesToUpdate=null,this.childrenToUpdate=null,this.renderGroupChildren=null,this._onRenderContainers=null,this.instructionSet=null}getChildren(t=[]){const e=this.root.children;for(let r=0;r<e.length;r++)this._getChildren(e[r],t);return t}_getChildren(t,e=[]){if(e.push(t),t.renderGroup)return e;const r=t.children;for(let n=0;n<r.length;n++)this._getChildren(r[n],e);return e}invalidateMatrices(){this._matrixDirty=7}get inverseWorldTransform(){return(this._matrixDirty&1)===0?this._inverseWorldTransform:(this._matrixDirty&=-2,this._inverseWorldTransform||(this._inverseWorldTransform=new M),this._inverseWorldTransform.copyFrom(this.worldTransform).invert())}get textureOffsetInverseTransform(){return(this._matrixDirty&2)===0?this._textureOffsetInverseTransform:(this._matrixDirty&=-3,this._textureOffsetInverseTransform||(this._textureOffsetInverseTransform=new M),this._textureOffsetInverseTransform.copyFrom(this.inverseWorldTransform).translate(-this._textureBounds.x,-this._textureBounds.y))}get inverseParentTextureTransform(){if((this._matrixDirty&4)===0)return this._inverseParentTextureTransform;this._matrixDirty&=-5;const t=this._parentCacheAsTextureRenderGroup;return t?(this._inverseParentTextureTransform||(this._inverseParentTextureTransform=new M),this._inverseParentTextureTransform.copyFrom(this.worldTransform).prepend(t.inverseWorldTransform).translate(-t._textureBounds.x,-t._textureBounds.y)):this.worldTransform}get cacheToLocalTransform(){return this.isCachedAsTexture?this.textureOffsetInverseTransform:this._parentCacheAsTextureRenderGroup?this._parentCacheAsTextureRenderGroup.textureOffsetInverseTransform:null}}function yp(s,t,e={}){for(const r in t)!e[r]&&t[r]!==void 0&&(s[r]=t[r])}const ks=new ct(null),pr=new ct(null),Ms=new ct(null,1,1),mr=new ct(null),gr=1,Rs=2,ui=4;class st extends Ct{constructor(t={}){super(),this.uid=et("renderable"),this._updateFlags=15,this.renderGroup=null,this.parentRenderGroup=null,this.parentRenderGroupIndex=0,this.didChange=!1,this.didViewUpdate=!1,this.relativeRenderGroupDepth=0,this.children=[],this.parent=null,this.includeInBuild=!0,this.measurable=!0,this.isSimple=!0,this.parentRenderLayer=null,this.updateTick=-1,this.localTransform=new M,this.relativeGroupTransform=new M,this.groupTransform=this.relativeGroupTransform,this.destroyed=!1,this._position=new ct(this,0,0),this._scale=Ms,this._pivot=pr,this._origin=mr,this._skew=ks,this._cx=1,this._sx=0,this._cy=0,this._sy=1,this._rotation=0,this.localColor=16777215,this.localAlpha=1,this.groupAlpha=1,this.groupColor=16777215,this.groupColorAlpha=4294967295,this.localBlendMode="inherit",this.groupBlendMode="normal",this.localDisplayStatus=7,this.globalDisplayStatus=7,this._didContainerChangeTick=0,this._didViewChangeTick=0,this._didLocalTransformChangeId=-1,this.effects=[],yp(this,t,{children:!0,parent:!0,effects:!0}),t.children?.forEach(e=>this.addChild(e)),t.parent?.addChild(this)}static mixin(t){z("8.8.0","Container.mixin is deprecated, please use extensions.mixin instead."),D.mixin(st,t)}set _didChangeId(t){this._didViewChangeTick=t>>12&4095,this._didContainerChangeTick=t&4095}get _didChangeId(){return this._didContainerChangeTick&4095|(this._didViewChangeTick&4095)<<12}addChild(...t){if(this.allowChildren||z($,"addChild: Only Containers will be allowed to add children in v8.0.0"),t.length>1){for(let n=0;n<t.length;n++)this.addChild(t[n]);return t[0]}const e=t[0],r=this.renderGroup||this.parentRenderGroup;return e.parent===this?(this.children.splice(this.children.indexOf(e),1),this.children.push(e),r&&(r.structureDidChange=!0),e):(e.parent&&e.parent.removeChild(e),this.children.push(e),this.sortableChildren&&(this.sortDirty=!0),e.parent=this,e.didChange=!0,e._updateFlags=15,r&&r.addChild(e),this.emit("childAdded",e,this,this.children.length-1),e.emit("added",this),this._didViewChangeTick++,e._zIndex!==0&&e.depthOfChildModified(),e)}removeChild(...t){if(t.length>1){for(let n=0;n<t.length;n++)this.removeChild(t[n]);return t[0]}const e=t[0],r=this.children.indexOf(e);return r>-1&&(this._didViewChangeTick++,this.children.splice(r,1),this.renderGroup?this.renderGroup.removeChild(e):this.parentRenderGroup&&this.parentRenderGroup.removeChild(e),e.parentRenderLayer&&e.parentRenderLayer.detach(e),e.parent=null,this.emit("childRemoved",e,this,r),e.emit("removed",this)),e}_onUpdate(t){t&&t===this._skew&&this._updateSkew(),this._didContainerChangeTick++,!this.didChange&&(this.didChange=!0,this.parentRenderGroup&&this.parentRenderGroup.onChildUpdate(this))}set isRenderGroup(t){!!this.renderGroup!==t&&(t?this.enableRenderGroup():this.disableRenderGroup())}get isRenderGroup(){return!!this.renderGroup}enableRenderGroup(){if(this.renderGroup)return;const t=this.parentRenderGroup;t?.removeChild(this),this.renderGroup=at.get(Us,this),this.groupTransform=M.IDENTITY,t?.addChild(this),this._updateIsSimple()}disableRenderGroup(){if(!this.renderGroup)return;const t=this.parentRenderGroup;t?.removeChild(this),at.return(this.renderGroup),this.renderGroup=null,this.groupTransform=this.relativeGroupTransform,t?.addChild(this),this._updateIsSimple()}_updateIsSimple(){this.isSimple=!this.renderGroup&&this.effects.length===0}get worldTransform(){return this._worldTransform||(this._worldTransform=new M),this.renderGroup?this._worldTransform.copyFrom(this.renderGroup.worldTransform):this.parentRenderGroup&&this._worldTransform.appendFrom(this.relativeGroupTransform,this.parentRenderGroup.worldTransform),this._worldTransform}get x(){return this._position.x}set x(t){this._position.x=t}get y(){return this._position.y}set y(t){this._position.y=t}get position(){return this._position}set position(t){this._position.copyFrom(t)}get rotation(){return this._rotation}set rotation(t){this._rotation!==t&&(this._rotation=t,this._onUpdate(this._skew))}get angle(){return this.rotation*Df}set angle(t){this.rotation=t*Of}get pivot(){return this._pivot===pr&&(this._pivot=new ct(this,0,0)),this._pivot}set pivot(t){this._pivot===pr&&(this._pivot=new ct(this,0,0),this._origin!==mr&&F("Setting both a pivot and origin on a Container is not recommended. This can lead to unexpected behavior if not handled carefully.")),typeof t=="number"?this._pivot.set(t):this._pivot.copyFrom(t)}get skew(){return this._skew===ks&&(this._skew=new ct(this,0,0)),this._skew}set skew(t){this._skew===ks&&(this._skew=new ct(this,0,0)),this._skew.copyFrom(t)}get scale(){return this._scale===Ms&&(this._scale=new ct(this,1,1)),this._scale}set scale(t){this._scale===Ms&&(this._scale=new ct(this,0,0)),typeof t=="string"&&(t=parseFloat(t)),typeof t=="number"?this._scale.set(t):this._scale.copyFrom(t)}get origin(){return this._origin===mr&&(this._origin=new ct(this,0,0)),this._origin}set origin(t){this._origin===mr&&(this._origin=new ct(this,0,0),this._pivot!==pr&&F("Setting both a pivot and origin on a Container is not recommended. This can lead to unexpected behavior if not handled carefully.")),typeof t=="number"?this._origin.set(t):this._origin.copyFrom(t)}get width(){return Math.abs(this.scale.x*this.getLocalBounds().width)}set width(t){const e=this.getLocalBounds().width;this._setWidth(t,e)}get height(){return Math.abs(this.scale.y*this.getLocalBounds().height)}set height(t){const e=this.getLocalBounds().height;this._setHeight(t,e)}getSize(t){t||(t={});const e=this.getLocalBounds();return t.width=Math.abs(this.scale.x*e.width),t.height=Math.abs(this.scale.y*e.height),t}setSize(t,e){const r=this.getLocalBounds();typeof t=="object"?(e=t.height??t.width,t=t.width):e??(e=t),t!==void 0&&this._setWidth(t,r.width),e!==void 0&&this._setHeight(e,r.height)}_updateSkew(){const t=this._rotation,e=this._skew;this._cx=Math.cos(t+e._y),this._sx=Math.sin(t+e._y),this._cy=-Math.sin(t-e._x),this._sy=Math.cos(t-e._x)}updateTransform(t){return this.position.set(typeof t.x=="number"?t.x:this.position.x,typeof t.y=="number"?t.y:this.position.y),this.scale.set(typeof t.scaleX=="number"?t.scaleX||1:this.scale.x,typeof t.scaleY=="number"?t.scaleY||1:this.scale.y),this.rotation=typeof t.rotation=="number"?t.rotation:this.rotation,this.skew.set(typeof t.skewX=="number"?t.skewX:this.skew.x,typeof t.skewY=="number"?t.skewY:this.skew.y),this.pivot.set(typeof t.pivotX=="number"?t.pivotX:this.pivot.x,typeof t.pivotY=="number"?t.pivotY:this.pivot.y),this.origin.set(typeof t.originX=="number"?t.originX:this.origin.x,typeof t.originY=="number"?t.originY:this.origin.y),this}setFromMatrix(t){t.decompose(this)}updateLocalTransform(){const t=this._didContainerChangeTick;if(this._didLocalTransformChangeId===t)return;this._didLocalTransformChangeId=t;const e=this.localTransform,r=this._scale,n=this._pivot,o=this._origin,l=this._position,h=r._x,u=r._y,f=n._x,m=n._y,g=-o._x,y=-o._y;e.a=this._cx*h,e.b=this._sx*h,e.c=this._cy*u,e.d=this._sy*u,e.tx=l._x-(f*e.a+m*e.c)+(g*e.a+y*e.c)-g,e.ty=l._y-(f*e.b+m*e.d)+(g*e.b+y*e.d)-y}set alpha(t){t!==this.localAlpha&&(this.localAlpha=t,this._updateFlags|=gr,this._onUpdate())}get alpha(){return this.localAlpha}set tint(t){const r=J.shared.setValue(t??16777215).toBgrNumber();r!==this.localColor&&(this.localColor=r,this._updateFlags|=gr,this._onUpdate())}get tint(){return fr(this.localColor)}set blendMode(t){this.localBlendMode!==t&&(this.parentRenderGroup&&(this.parentRenderGroup.structureDidChange=!0),this._updateFlags|=Rs,this.localBlendMode=t,this._onUpdate())}get blendMode(){return this.localBlendMode}get visible(){return!!(this.localDisplayStatus&2)}set visible(t){const e=t?2:0;(this.localDisplayStatus&2)!==e&&(this.parentRenderGroup&&(this.parentRenderGroup.structureDidChange=!0),this._updateFlags|=ui,this.localDisplayStatus^=2,this._onUpdate())}get culled(){return!(this.localDisplayStatus&4)}set culled(t){const e=t?0:4;(this.localDisplayStatus&4)!==e&&(this.parentRenderGroup&&(this.parentRenderGroup.structureDidChange=!0),this._updateFlags|=ui,this.localDisplayStatus^=4,this._onUpdate())}get renderable(){return!!(this.localDisplayStatus&1)}set renderable(t){const e=t?1:0;(this.localDisplayStatus&1)!==e&&(this._updateFlags|=ui,this.localDisplayStatus^=1,this.parentRenderGroup&&(this.parentRenderGroup.structureDidChange=!0),this._onUpdate())}get isRenderable(){return this.localDisplayStatus===7&&this.groupAlpha>0}destroy(t=!1){if(this.destroyed)return;this.destroyed=!0;let e;if(this.children.length&&(e=this.removeChildren(0,this.children.length)),this.removeFromParent(),this.parent=null,this._maskEffect=null,this._filterEffect=null,this.effects=null,this._position=null,this._scale=null,this._pivot=null,this._origin=null,this._skew=null,this.emit("destroyed",this),this.removeAllListeners(),(typeof t=="boolean"?t:t?.children)&&e)for(let n=0;n<e.length;++n)e[n].destroy(t);this.renderGroup?.destroy(),this.renderGroup=null}}D.mixin(st,ip,hp,mp,up,dp,np,op,fp,Qf,ep,lp,rp);class Is extends st{constructor(t){super(t),this.canBundle=!0,this.allowChildren=!1,this._roundPixels=0,this._lastUsed=-1,this._gpuData=Object.create(null),this._bounds=new ut(0,1,0,0),this._boundsDirty=!0}get bounds(){return this._boundsDirty?(this.updateBounds(),this._boundsDirty=!1,this._bounds):this._bounds}get roundPixels(){return!!this._roundPixels}set roundPixels(t){this._roundPixels=t?1:0}containsPoint(t){const e=this.bounds,{x:r,y:n}=t;return r>=e.minX&&r<=e.maxX&&n>=e.minY&&n<=e.maxY}onViewUpdate(){if(this._didViewChangeTick++,this._boundsDirty=!0,this.didViewUpdate)return;this.didViewUpdate=!0;const t=this.renderGroup||this.parentRenderGroup;t&&t.onChildViewUpdate(this)}destroy(t){super.destroy(t),this._bounds=null;for(const e in this._gpuData)this._gpuData[e].destroy?.();this._gpuData=null}collectRenderablesSimple(t,e,r){const{renderPipes:n}=e;n.blendMode.pushBlendMode(this,this.groupBlendMode,t),n[this.renderPipeId].addRenderable(this,t),this.didViewUpdate=!1;const l=this.children,h=l.length;for(let u=0;u<h;u++)l[u].collectRenderables(t,e,r);n.blendMode.popBlendMode(t)}}class ie extends Is{constructor(t=k.EMPTY){t instanceof k&&(t={texture:t});const{texture:e=k.EMPTY,anchor:r,roundPixels:n,width:o,height:l,...h}=t;super({label:"Sprite",...h}),this.renderPipeId="sprite",this.batched=!0,this._visualBounds={minX:0,maxX:1,minY:0,maxY:0},this._anchor=new ct({_onUpdate:()=>{this.onViewUpdate()}}),r?this.anchor=r:e.defaultAnchor&&(this.anchor=e.defaultAnchor),this.texture=e,this.allowChildren=!1,this.roundPixels=n??!1,o!==void 0&&(this.width=o),l!==void 0&&(this.height=l)}static from(t,e=!1){return t instanceof k?new ie(t):new ie(k.from(t,e))}set texture(t){t||(t=k.EMPTY);const e=this._texture;e!==t&&(e&&e.dynamic&&e.off("update",this.onViewUpdate,this),t.dynamic&&t.on("update",this.onViewUpdate,this),this._texture=t,this._width&&this._setWidth(this._width,this._texture.orig.width),this._height&&this._setHeight(this._height,this._texture.orig.height),this.onViewUpdate())}get texture(){return this._texture}get visualBounds(){return na(this._visualBounds,this._anchor,this._texture),this._visualBounds}get sourceBounds(){return z("8.6.1","Sprite.sourceBounds is deprecated, use visualBounds instead."),this.visualBounds}updateBounds(){const t=this._anchor,e=this._texture,r=this._bounds,{width:n,height:o}=e.orig;r.minX=-t._x*n,r.maxX=r.minX+n,r.minY=-t._y*o,r.maxY=r.minY+o}destroy(t=!1){if(super.destroy(t),typeof t=="boolean"?t:t?.texture){const r=typeof t=="boolean"?t:t?.textureSource;this._texture.destroy(r)}this._texture=null,this._visualBounds=null,this._bounds=null,this._anchor=null,this._gpuData=null}get anchor(){return this._anchor}set anchor(t){typeof t=="number"?this._anchor.set(t):this._anchor.copyFrom(t)}get width(){return Math.abs(this.scale.x)*this._texture.orig.width}set width(t){this._setWidth(t,this._texture.orig.width),this._width=t}get height(){return Math.abs(this.scale.y)*this._texture.orig.height}set height(t){this._setHeight(t,this._texture.orig.height),this._height=t}getSize(t){return t||(t={}),t.width=Math.abs(this.scale.x)*this._texture.orig.width,t.height=Math.abs(this.scale.y)*this._texture.orig.height,t}setSize(t,e){typeof t=="object"?(e=t.height??t.width,t=t.width):e??(e=t),t!==void 0&&this._setWidth(t,this._texture.orig.width),e!==void 0&&this._setHeight(e,this._texture.orig.height)}}const xp=new ut;function Ca(s,t,e){const r=xp;s.measurable=!0,As(s,e,r),t.addBoundsMask(r),s.measurable=!1}function Ea(s,t,e){const r=ee.get();s.measurable=!0;const n=gt.get().identity(),o=Aa(s,e,n);Bs(s,r,o),s.measurable=!1,t.addBoundsMask(r),gt.return(n),ee.return(r)}function Aa(s,t,e){return s?(s!==t&&(Aa(s.parent,t,e),s.updateLocalTransform(),e.append(s.localTransform)),e):(F("Mask bounds, renderable is not inside the root container"),e)}class Pa{constructor(t){this.priority=0,this.inverse=!1,this.pipe="alphaMask",t?.mask&&this.init(t.mask)}init(t){this.mask=t,this.renderMaskToTexture=!(t instanceof ie),this.mask.renderable=this.renderMaskToTexture,this.mask.includeInBuild=!this.renderMaskToTexture,this.mask.measurable=!1}reset(){this.mask!==null&&(this.mask.measurable=!0,this.mask=null)}addBounds(t,e){this.inverse||Ca(this.mask,t,e)}addLocalBounds(t,e){Ea(this.mask,t,e)}containsPoint(t,e){const r=this.mask;return e(r,t)}destroy(){this.reset()}static test(t){return t instanceof ie}}Pa.extension=C.MaskEffect;class Ba{constructor(t){this.priority=0,this.pipe="colorMask",t?.mask&&this.init(t.mask)}init(t){this.mask=t}destroy(){}static test(t){return typeof t=="number"}}Ba.extension=C.MaskEffect;class Ua{constructor(t){this.priority=0,this.pipe="stencilMask",t?.mask&&this.init(t.mask)}init(t){this.mask=t,this.mask.includeInBuild=!1,this.mask.measurable=!1}reset(){this.mask!==null&&(this.mask.measurable=!0,this.mask.includeInBuild=!0,this.mask=null)}addBounds(t,e){Ca(this.mask,t,e)}addLocalBounds(t,e){Ea(this.mask,t,e)}containsPoint(t,e){const r=this.mask;return e(r,t)}destroy(){this.reset()}static test(t){return t instanceof st}}Ua.extension=C.MaskEffect;let ka={createCanvas:(s,t)=>{const e=document.createElement("canvas");return e.width=s,e.height=t,e},createImage:()=>new Image,getCanvasRenderingContext2D:()=>CanvasRenderingContext2D,getWebGLRenderingContext:()=>WebGLRenderingContext,getNavigator:()=>navigator,getBaseUrl:()=>document.baseURI??window.location.href,getFontFaceSet:()=>document.fonts,fetch:(s,t)=>fetch(s,t),parseXML:s=>new DOMParser().parseFromString(s,"text/xml")};const W={get(){return ka},set(s){ka=s}};class re extends ht{constructor(t){t.resource||(t.resource=W.get().createCanvas()),t.width||(t.width=t.resource.width,t.autoDensity||(t.width/=t.resolution)),t.height||(t.height=t.resource.height,t.autoDensity||(t.height/=t.resolution)),super(t),this.uploadMethodId="image",this.autoDensity=t.autoDensity,this.resizeCanvas(),this.transparent=!!t.transparent}resizeCanvas(){this.autoDensity&&"style"in this.resource&&(this.resource.style.width=`${this.width}px`,this.resource.style.height=`${this.height}px`),(this.resource.width!==this.pixelWidth||this.resource.height!==this.pixelHeight)&&(this.resource.width=this.pixelWidth,this.resource.height=this.pixelHeight)}resize(t=this.width,e=this.height,r=this._resolution){const n=super.resize(t,e,r);return n&&this.resizeCanvas(),n}static test(t){return globalThis.HTMLCanvasElement&&t instanceof HTMLCanvasElement||globalThis.OffscreenCanvas&&t instanceof OffscreenCanvas}get context2D(){return this._context2D||(this._context2D=this.resource.getContext("2d"))}}re.extension=C.TextureSource;class Se extends ht{constructor(t){super(t),this.uploadMethodId="image",this.autoGarbageCollect=!0}static test(t){return globalThis.HTMLImageElement&&t instanceof HTMLImageElement||typeof ImageBitmap<"u"&&t instanceof ImageBitmap||globalThis.VideoFrame&&t instanceof VideoFrame}}Se.extension=C.TextureSource;var We=(s=>(s[s.INTERACTION=50]="INTERACTION",s[s.HIGH=25]="HIGH",s[s.NORMAL=0]="NORMAL",s[s.LOW=-25]="LOW",s[s.UTILITY=-50]="UTILITY",s))(We||{});class Fs{constructor(t,e=null,r=0,n=!1){this.next=null,this.previous=null,this._destroyed=!1,this._fn=t,this._context=e,this.priority=r,this._once=n}match(t,e=null){return this._fn===t&&this._context===e}emit(t){this._fn&&(this._context?this._fn.call(this._context,t):this._fn(t));const e=this.next;return this._once&&this.destroy(!0),this._destroyed&&(this.next=null),e}connect(t){this.previous=t,t.next&&(t.next.previous=this),this.next=t.next,t.next=this}destroy(t=!1){this._destroyed=!0,this._fn=null,this._context=null,this.previous&&(this.previous.next=this.next),this.next&&(this.next.previous=this.previous);const e=this.next;return this.next=t?null:e,this.previous=null,e}}const Ma=class kt{constructor(){this.autoStart=!1,this.deltaTime=1,this.lastTime=-1,this.speed=1,this.started=!1,this._requestId=null,this._maxElapsedMS=100,this._minElapsedMS=0,this._protected=!1,this._lastFrame=-1,this._head=new Fs(null,null,1/0),this.deltaMS=1/kt.targetFPMS,this.elapsedMS=1/kt.targetFPMS,this._tick=t=>{this._requestId=null,this.started&&(this.update(t),this.started&&this._requestId===null&&this._head.next&&(this._requestId=requestAnimationFrame(this._tick)))}}_requestIfNeeded(){this._requestId===null&&this._head.next&&(this.lastTime=performance.now(),this._lastFrame=this.lastTime,this._requestId=requestAnimationFrame(this._tick))}_cancelIfNeeded(){this._requestId!==null&&(cancelAnimationFrame(this._requestId),this._requestId=null)}_startIfPossible(){this.started?this._requestIfNeeded():this.autoStart&&this.start()}add(t,e,r=We.NORMAL){return this._addListener(new Fs(t,e,r))}addOnce(t,e,r=We.NORMAL){return this._addListener(new Fs(t,e,r,!0))}_addListener(t){let e=this._head.next,r=this._head;if(!e)t.connect(r);else{for(;e;){if(t.priority>e.priority){t.connect(r);break}r=e,e=e.next}t.previous||t.connect(r)}return this._startIfPossible(),this}remove(t,e){let r=this._head.next;for(;r;)r.match(t,e)?r=r.destroy():r=r.next;return this._head.next||this._cancelIfNeeded(),this}get count(){if(!this._head)return 0;let t=0,e=this._head;for(;e=e.next;)t++;return t}start(){this.started||(this.started=!0,this._requestIfNeeded())}stop(){this.started&&(this.started=!1,this._cancelIfNeeded())}destroy(){if(!this._protected){this.stop();let t=this._head.next;for(;t;)t=t.destroy(!0);this._head.destroy(),this._head=null}}update(t=performance.now()){let e;if(t>this.lastTime){if(e=this.elapsedMS=t-this.lastTime,e>this._maxElapsedMS&&(e=this._maxElapsedMS),e*=this.speed,this._minElapsedMS){const o=t-this._lastFrame|0;if(o<this._minElapsedMS)return;this._lastFrame=t-o%this._minElapsedMS}this.deltaMS=e,this.deltaTime=this.deltaMS*kt.targetFPMS;const r=this._head;let n=r.next;for(;n;)n=n.emit(this);r.next||this._cancelIfNeeded()}else this.deltaTime=this.deltaMS=this.elapsedMS=0;this.lastTime=t}get FPS(){return 1e3/this.elapsedMS}get minFPS(){return 1e3/this._maxElapsedMS}set minFPS(t){const e=Math.min(this.maxFPS,t),r=Math.min(Math.max(0,e)/1e3,kt.targetFPMS);this._maxElapsedMS=1/r}get maxFPS(){return this._minElapsedMS?Math.round(1e3/this._minElapsedMS):0}set maxFPS(t){if(t===0)this._minElapsedMS=0;else{const e=Math.max(this.minFPS,t);this._minElapsedMS=1/(e/1e3)}}static get shared(){if(!kt._shared){const t=kt._shared=new kt;t.autoStart=!0,t._protected=!0}return kt._shared}static get system(){if(!kt._system){const t=kt._system=new kt;t.autoStart=!0,t._protected=!0}return kt._system}};Ma.targetFPMS=.06;let Et=Ma,Ds;async function Ra(){return Ds??(Ds=(async()=>{const t=W.get().createCanvas(1,1).getContext("webgl");if(!t)return"premultiply-alpha-on-upload";const e=await new Promise(l=>{const h=document.createElement("video");h.onloadeddata=()=>l(h),h.onerror=()=>l(null),h.autoplay=!1,h.crossOrigin="anonymous",h.preload="auto",h.src="data:video/webm;base64,GkXfo59ChoEBQveBAULygQRC84EIQoKEd2VibUKHgQJChYECGFOAZwEAAAAAAAHTEU2bdLpNu4tTq4QVSalmU6yBoU27i1OrhBZUrmtTrIHGTbuMU6uEElTDZ1OsggEXTbuMU6uEHFO7a1OsggG97AEAAAAAAABZAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAVSalmoCrXsYMPQkBNgIRMYXZmV0GETGF2ZkSJiEBEAAAAAAAAFlSua8yuAQAAAAAAAEPXgQFzxYgAAAAAAAAAAZyBACK1nIN1bmSIgQCGhVZfVlA5g4EBI+ODhAJiWgDglLCBArqBApqBAlPAgQFVsIRVuYEBElTDZ9Vzc9JjwItjxYgAAAAAAAAAAWfInEWjh0VOQ09ERVJEh49MYXZjIGxpYnZweC12cDlnyKJFo4hEVVJBVElPTkSHlDAwOjAwOjAwLjA0MDAwMDAwMAAAH0O2dcfngQCgwqGggQAAAIJJg0IAABAAFgA4JBwYSgAAICAAEb///4r+AAB1oZ2mm+6BAaWWgkmDQgAAEAAWADgkHBhKAAAgIABIQBxTu2uRu4+zgQC3iveBAfGCAXHwgQM=",h.load()});if(!e)return"premultiply-alpha-on-upload";const r=t.createTexture();t.bindTexture(t.TEXTURE_2D,r);const n=t.createFramebuffer();t.bindFramebuffer(t.FRAMEBUFFER,n),t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,r,0),t.pixelStorei(t.UNPACK_PREMULTIPLY_ALPHA_WEBGL,!1),t.pixelStorei(t.UNPACK_COLORSPACE_CONVERSION_WEBGL,t.NONE),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,e);const o=new Uint8Array(4);return t.readPixels(0,0,1,1,t.RGBA,t.UNSIGNED_BYTE,o),t.deleteFramebuffer(n),t.deleteTexture(r),t.getExtension("WEBGL_lose_context")?.loseContext(),o[0]<=o[3]?"premultiplied-alpha":"premultiply-alpha-on-upload"})()),Ds}const _r=class Zd extends ht{constructor(t){super(t),this.isReady=!1,this.uploadMethodId="video",t={...Zd.defaultOptions,...t},this._autoUpdate=!0,this._isConnectedToTicker=!1,this._updateFPS=t.updateFPS||0,this._msToNextUpdate=0,this.autoPlay=t.autoPlay!==!1,this.alphaMode=t.alphaMode??"premultiply-alpha-on-upload",this._videoFrameRequestCallback=this._videoFrameRequestCallback.bind(this),this._videoFrameRequestCallbackHandle=null,this._load=null,this._resolve=null,this._reject=null,this._onCanPlay=this._onCanPlay.bind(this),this._onCanPlayThrough=this._onCanPlayThrough.bind(this),this._onError=this._onError.bind(this),this._onPlayStart=this._onPlayStart.bind(this),this._onPlayStop=this._onPlayStop.bind(this),this._onSeeked=this._onSeeked.bind(this),t.autoLoad!==!1&&this.load()}updateFrame(){if(!this.destroyed){if(this._updateFPS){const t=Et.shared.elapsedMS*this.resource.playbackRate;this._msToNextUpdate=Math.floor(this._msToNextUpdate-t)}(!this._updateFPS||this._msToNextUpdate<=0)&&(this._msToNextUpdate=this._updateFPS?Math.floor(1e3/this._updateFPS):0),this.isValid&&this.update()}}_videoFrameRequestCallback(){this.updateFrame(),this.destroyed?this._videoFrameRequestCallbackHandle=null:this._videoFrameRequestCallbackHandle=this.resource.requestVideoFrameCallback(this._videoFrameRequestCallback)}get isValid(){return!!this.resource.videoWidth&&!!this.resource.videoHeight}async load(){if(this._load)return this._load;const t=this.resource,e=this.options;return(t.readyState===t.HAVE_ENOUGH_DATA||t.readyState===t.HAVE_FUTURE_DATA)&&t.width&&t.height&&(t.complete=!0),t.addEventListener("play",this._onPlayStart),t.addEventListener("pause",this._onPlayStop),t.addEventListener("seeked",this._onSeeked),this._isSourceReady()?this._mediaReady():(e.preload||t.addEventListener("canplay",this._onCanPlay),t.addEventListener("canplaythrough",this._onCanPlayThrough),t.addEventListener("error",this._onError,!0)),this.alphaMode=await Ra(),this._load=new Promise((r,n)=>{this.isValid?r(this):(this._resolve=r,this._reject=n,e.preloadTimeoutMs!==void 0&&(this._preloadTimeout=setTimeout(()=>{this._onError(new ErrorEvent(`Preload exceeded timeout of ${e.preloadTimeoutMs}ms`))})),t.load())}),this._load}_onError(t){this.resource.removeEventListener("error",this._onError,!0),this.emit("error",t),this._reject&&(this._reject(t),this._reject=null,this._resolve=null)}_isSourcePlaying(){const t=this.resource;return!t.paused&&!t.ended}_isSourceReady(){return this.resource.readyState>2}_onPlayStart(){this.isValid||this._mediaReady(),this._configureAutoUpdate()}_onPlayStop(){this._configureAutoUpdate()}_onSeeked(){this._autoUpdate&&!this._isSourcePlaying()&&(this._msToNextUpdate=0,this.updateFrame(),this._msToNextUpdate=0)}_onCanPlay(){this.resource.removeEventListener("canplay",this._onCanPlay),this._mediaReady()}_onCanPlayThrough(){this.resource.removeEventListener("canplaythrough",this._onCanPlay),this._preloadTimeout&&(clearTimeout(this._preloadTimeout),this._preloadTimeout=void 0),this._mediaReady()}_mediaReady(){const t=this.resource;this.isValid&&(this.isReady=!0,this.resize(t.videoWidth,t.videoHeight)),this._msToNextUpdate=0,this.updateFrame(),this._msToNextUpdate=0,this._resolve&&(this._resolve(this),this._resolve=null,this._reject=null),this._isSourcePlaying()?this._onPlayStart():this.autoPlay&&this.resource.play()}destroy(){this._configureAutoUpdate();const t=this.resource;t&&(t.removeEventListener("play",this._onPlayStart),t.removeEventListener("pause",this._onPlayStop),t.removeEventListener("seeked",this._onSeeked),t.removeEventListener("canplay",this._onCanPlay),t.removeEventListener("canplaythrough",this._onCanPlayThrough),t.removeEventListener("error",this._onError,!0),t.pause(),t.src="",t.load()),super.destroy()}get autoUpdate(){return this._autoUpdate}set autoUpdate(t){t!==this._autoUpdate&&(this._autoUpdate=t,this._configureAutoUpdate())}get updateFPS(){return this._updateFPS}set updateFPS(t){t!==this._updateFPS&&(this._updateFPS=t,this._configureAutoUpdate())}_configureAutoUpdate(){this._autoUpdate&&this._isSourcePlaying()?!this._updateFPS&&this.resource.requestVideoFrameCallback?(this._isConnectedToTicker&&(Et.shared.remove(this.updateFrame,this),this._isConnectedToTicker=!1,this._msToNextUpdate=0),this._videoFrameRequestCallbackHandle===null&&(this._videoFrameRequestCallbackHandle=this.resource.requestVideoFrameCallback(this._videoFrameRequestCallback))):(this._videoFrameRequestCallbackHandle!==null&&(this.resource.cancelVideoFrameCallback(this._videoFrameRequestCallbackHandle),this._videoFrameRequestCallbackHandle=null),this._isConnectedToTicker||(Et.shared.add(this.updateFrame,this),this._isConnectedToTicker=!0,this._msToNextUpdate=0)):(this._videoFrameRequestCallbackHandle!==null&&(this.resource.cancelVideoFrameCallback(this._videoFrameRequestCallbackHandle),this._videoFrameRequestCallbackHandle=null),this._isConnectedToTicker&&(Et.shared.remove(this.updateFrame,this),this._isConnectedToTicker=!1,this._msToNextUpdate=0))}static test(t){return globalThis.HTMLVideoElement&&t instanceof HTMLVideoElement}};_r.extension=C.TextureSource,_r.defaultOptions={...ht.defaultOptions,autoLoad:!0,autoPlay:!0,updateFPS:0,crossorigin:!0,loop:!1,muted:!0,playsinline:!0,preload:!1},_r.MIME_TYPES={ogv:"video/ogg",mov:"video/quicktime",m4v:"video/mp4"};let fi=_r;const Lt=(s,t,e=!1)=>(Array.isArray(s)||(s=[s]),t?s.map(r=>typeof r=="string"||e?t(r):r):s);class bp{constructor(){this._parsers=[],this._cache=new Map,this._cacheMap=new Map}reset(){this._cacheMap.clear(),this._cache.clear()}has(t){return this._cache.has(t)}get(t){const e=this._cache.get(t);return e||F(`[Assets] Asset id ${t} was not found in the Cache`),e}set(t,e){const r=Lt(t);let n;for(let u=0;u<this.parsers.length;u++){const f=this.parsers[u];if(f.test(e)){n=f.getCacheableAssets(r,e);break}}const o=new Map(Object.entries(n||{}));n||r.forEach(u=>{o.set(u,e)});const l=[...o.keys()],h={cacheKeys:l,keys:r};r.forEach(u=>{this._cacheMap.set(u,h)}),l.forEach(u=>{const f=n?n[u]:e;this._cache.has(u)&&this._cache.get(u)!==f&&F("[Cache] already has key:",u),this._cache.set(u,o.get(u))})}remove(t){if(!this._cacheMap.has(t)){F(`[Assets] Asset id ${t} was not found in the Cache`);return}const e=this._cacheMap.get(t);e.cacheKeys.forEach(n=>{this._cache.delete(n)}),e.keys.forEach(n=>{this._cacheMap.delete(n)})}get parsers(){return this._parsers}}const Q=new bp,Os=[];D.handleByList(C.TextureSource,Os);function Ia(s={}){const t=s&&s.resource,e=t?s.resource:s,r=t?s:{resource:s};for(let n=0;n<Os.length;n++){const o=Os[n];if(o.test(e))return new o(r)}throw new Error(`Could not find a source type for resource: ${r.resource}`)}function vp(s={},t=!1){const e=s&&s.resource,r=e?s.resource:s,n=e?s:{resource:s};if(!t&&Q.has(r))return Q.get(r);const o=new k({source:Ia(n)});return o.on("destroy",()=>{Q.has(r)&&Q.remove(r)}),t||Q.set(r,o),o}function wp(s,t=!1){return typeof s=="string"?Q.get(s):s instanceof ht?new k({source:s}):vp(s,t)}k.from=wp,ht.from=Ia,D.add(Pa,Ba,Ua,fi,Se,re,xs);var ue=(s=>(s[s.Low=0]="Low",s[s.Normal=1]="Normal",s[s.High=2]="High",s))(ue||{});function zt(s){if(typeof s!="string")throw new TypeError(`Path must be a string. Received ${JSON.stringify(s)}`)}function pi(s){return s.split("?")[0].split("#")[0]}function Sp(s){return s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Tp(s,t,e){return s.replace(new RegExp(Sp(t),"g"),e)}function Cp(s,t){let e="",r=0,n=-1,o=0,l=-1;for(let h=0;h<=s.length;++h){if(h<s.length)l=s.charCodeAt(h);else{if(l===47)break;l=47}if(l===47){if(!(n===h-1||o===1))if(n!==h-1&&o===2){if(e.length<2||r!==2||e.charCodeAt(e.length-1)!==46||e.charCodeAt(e.length-2)!==46){if(e.length>2){const u=e.lastIndexOf("/");if(u!==e.length-1){u===-1?(e="",r=0):(e=e.slice(0,u),r=e.length-1-e.lastIndexOf("/")),n=h,o=0;continue}}else if(e.length===2||e.length===1){e="",r=0,n=h,o=0;continue}}}else e.length>0?e+=`/${s.slice(n+1,h)}`:e=s.slice(n+1,h),r=h-n-1;n=h,o=0}else l===46&&o!==-1?++o:o=-1}return e}const At={toPosix(s){return Tp(s,"\\","/")},isUrl(s){return/^https?:/.test(this.toPosix(s))},isDataUrl(s){return/^data:([a-z]+\/[a-z0-9-+.]+(;[a-z0-9-.!#$%*+.{}|~`]+=[a-z0-9-.!#$%*+.{}()_|~`]+)*)?(;base64)?,([a-z0-9!$&',()*+;=\-._~:@\/?%\s<>]*?)$/i.test(s)},isBlobUrl(s){return s.startsWith("blob:")},hasProtocol(s){return/^[^/:]+:/.test(this.toPosix(s))},getProtocol(s){zt(s),s=this.toPosix(s);const t=/^file:\/\/\//.exec(s);if(t)return t[0];const e=/^[^/:]+:\/{0,2}/.exec(s);return e?e[0]:""},toAbsolute(s,t,e){if(zt(s),this.isDataUrl(s)||this.isBlobUrl(s))return s;const r=pi(this.toPosix(t??W.get().getBaseUrl())),n=pi(this.toPosix(e??this.rootname(r)));return s=this.toPosix(s),s.startsWith("/")?At.join(n,s.slice(1)):this.isAbsolute(s)?s:this.join(r,s)},normalize(s){if(zt(s),s.length===0)return".";if(this.isDataUrl(s)||this.isBlobUrl(s))return s;s=this.toPosix(s);let t="";const e=s.startsWith("/");this.hasProtocol(s)&&(t=this.rootname(s),s=s.slice(t.length));const r=s.endsWith("/");return s=Cp(s),s.length>0&&r&&(s+="/"),e?`/${s}`:t+s},isAbsolute(s){return zt(s),s=this.toPosix(s),this.hasProtocol(s)?!0:s.startsWith("/")},join(...s){if(s.length===0)return".";let t;for(let e=0;e<s.length;++e){const r=s[e];if(zt(r),r.length>0)if(t===void 0)t=r;else{const n=s[e-1]??"";this.joinExtensions.includes(this.extname(n).toLowerCase())?t+=`/../${r}`:t+=`/${r}`}}return t===void 0?".":this.normalize(t)},dirname(s){if(zt(s),s.length===0)return".";s=this.toPosix(s);let t=s.charCodeAt(0);const e=t===47;let r=-1,n=!0;const o=this.getProtocol(s),l=s;s=s.slice(o.length);for(let h=s.length-1;h>=1;--h)if(t=s.charCodeAt(h),t===47){if(!n){r=h;break}}else n=!1;return r===-1?e?"/":this.isUrl(l)?o+s:o:e&&r===1?"//":o+s.slice(0,r)},rootname(s){zt(s),s=this.toPosix(s);let t="";if(s.startsWith("/")?t="/":t=this.getProtocol(s),this.isUrl(s)){const e=s.indexOf("/",t.length);e!==-1?t=s.slice(0,e):t=s,t.endsWith("/")||(t+="/")}return t},basename(s,t){zt(s),t&&zt(t),s=pi(this.toPosix(s));let e=0,r=-1,n=!0,o;if(t!==void 0&&t.length>0&&t.length<=s.length){if(t.length===s.length&&t===s)return"";let l=t.length-1,h=-1;for(o=s.length-1;o>=0;--o){const u=s.charCodeAt(o);if(u===47){if(!n){e=o+1;break}}else h===-1&&(n=!1,h=o+1),l>=0&&(u===t.charCodeAt(l)?--l===-1&&(r=o):(l=-1,r=h))}return e===r?r=h:r===-1&&(r=s.length),s.slice(e,r)}for(o=s.length-1;o>=0;--o)if(s.charCodeAt(o)===47){if(!n){e=o+1;break}}else r===-1&&(n=!1,r=o+1);return r===-1?"":s.slice(e,r)},extname(s){zt(s),s=pi(this.toPosix(s));let t=-1,e=0,r=-1,n=!0,o=0;for(let l=s.length-1;l>=0;--l){const h=s.charCodeAt(l);if(h===47){if(!n){e=l+1;break}continue}r===-1&&(n=!1,r=l+1),h===46?t===-1?t=l:o!==1&&(o=1):t!==-1&&(o=-1)}return t===-1||r===-1||o===0||o===1&&t===r-1&&t===e+1?"":s.slice(t,r)},parse(s){zt(s);const t={root:"",dir:"",base:"",ext:"",name:""};if(s.length===0)return t;s=pi(this.toPosix(s));let e=s.charCodeAt(0);const r=this.isAbsolute(s);let n;t.root=this.rootname(s),r||this.hasProtocol(s)?n=1:n=0;let o=-1,l=0,h=-1,u=!0,f=s.length-1,m=0;for(;f>=n;--f){if(e=s.charCodeAt(f),e===47){if(!u){l=f+1;break}continue}h===-1&&(u=!1,h=f+1),e===46?o===-1?o=f:m!==1&&(m=1):o!==-1&&(m=-1)}return o===-1||h===-1||m===0||m===1&&o===h-1&&o===l+1?h!==-1&&(l===0&&r?t.base=t.name=s.slice(1,h):t.base=t.name=s.slice(l,h)):(l===0&&r?(t.name=s.slice(1,o),t.base=s.slice(1,h)):(t.name=s.slice(l,o),t.base=s.slice(l,h)),t.ext=s.slice(o,h)),t.dir=this.dirname(s),t},sep:"/",delimiter:":",joinExtensions:[".html"]};function Fa(s,t,e,r,n){const o=t[e];for(let l=0;l<o.length;l++){const h=o[l];e<t.length-1?Fa(s.replace(r[e],h),t,e+1,r,n):n.push(s.replace(r[e],h))}}function Ep(s){const t=/\{(.*?)\}/g,e=s.match(t),r=[];if(e){const n=[];e.forEach(o=>{const l=o.substring(1,o.length-1).split(",");n.push(l)}),Fa(s,n,0,e,r)}else r.push(s);return r}const yr=s=>!Array.isArray(s);class Ve{constructor(){this._defaultBundleIdentifierOptions={connector:"-",createBundleAssetId:(t,e)=>`${t}${this._bundleIdConnector}${e}`,extractAssetIdFromBundle:(t,e)=>e.replace(`${t}${this._bundleIdConnector}`,"")},this._bundleIdConnector=this._defaultBundleIdentifierOptions.connector,this._createBundleAssetId=this._defaultBundleIdentifierOptions.createBundleAssetId,this._extractAssetIdFromBundle=this._defaultBundleIdentifierOptions.extractAssetIdFromBundle,this._assetMap={},this._preferredOrder=[],this._parsers=[],this._resolverHash={},this._bundles={}}setBundleIdentifier(t){if(this._bundleIdConnector=t.connector??this._bundleIdConnector,this._createBundleAssetId=t.createBundleAssetId??this._createBundleAssetId,this._extractAssetIdFromBundle=t.extractAssetIdFromBundle??this._extractAssetIdFromBundle,this._extractAssetIdFromBundle("foo",this._createBundleAssetId("foo","bar"))!=="bar")throw new Error("[Resolver] GenerateBundleAssetId are not working correctly")}prefer(...t){t.forEach(e=>{this._preferredOrder.push(e),e.priority||(e.priority=Object.keys(e.params))}),this._resolverHash={}}set basePath(t){this._basePath=t}get basePath(){return this._basePath}set rootPath(t){this._rootPath=t}get rootPath(){return this._rootPath}get parsers(){return this._parsers}reset(){this.setBundleIdentifier(this._defaultBundleIdentifierOptions),this._assetMap={},this._preferredOrder=[],this._resolverHash={},this._rootPath=null,this._basePath=null,this._manifest=null,this._bundles={},this._defaultSearchParams=null}setDefaultSearchParams(t){if(typeof t=="string")this._defaultSearchParams=t;else{const e=t;this._defaultSearchParams=Object.keys(e).map(r=>`${encodeURIComponent(r)}=${encodeURIComponent(e[r])}`).join("&")}}getAlias(t){const{alias:e,src:r}=t;return Lt(e||r,o=>typeof o=="string"?o:Array.isArray(o)?o.map(l=>l?.src??l):o?.src?o.src:o,!0)}addManifest(t){this._manifest&&F("[Resolver] Manifest already exists, this will be overwritten"),this._manifest=t,t.bundles.forEach(e=>{this.addBundle(e.name,e.assets)})}addBundle(t,e){const r=[];let n=e;Array.isArray(e)||(n=Object.entries(e).map(([o,l])=>typeof l=="string"||Array.isArray(l)?{alias:o,src:l}:{alias:o,...l})),n.forEach(o=>{const l=o.src,h=o.alias;let u;if(typeof h=="string"){const f=this._createBundleAssetId(t,h);r.push(f),u=[h,f]}else{const f=h.map(m=>this._createBundleAssetId(t,m));r.push(...f),u=[...h,...f]}this.add({...o,alias:u,src:l})}),this._bundles[t]=r}add(t){const e=[];Array.isArray(t)?e.push(...t):e.push(t);let r;r=o=>{this.hasKey(o)&&F(`[Resolver] already has key: ${o} overwriting`)},Lt(e).forEach(o=>{const{src:l}=o;let{data:h,format:u,loadParser:f,parser:m}=o;const g=Lt(l).map(c=>typeof c=="string"?Ep(c):Array.isArray(c)?c:[c]),y=this.getAlias(o);Array.isArray(y)?y.forEach(r):r(y);const x=[],a=c=>({...this._parsers.find(p=>p.test(c))?.parse(c),src:c});g.forEach(c=>{c.forEach(d=>{let p={};if(typeof d!="object"?p=a(d):(h=d.data??h,u=d.format??u,(d.loadParser||d.parser)&&(f=d.loadParser??f,m=d.parser??m),p={...a(d.src),...d}),!y)throw new Error(`[Resolver] alias is undefined for this asset: ${p.src}`);p=this._buildResolvedAsset(p,{aliases:y,data:h,format:u,loadParser:f,parser:m,progressSize:o.progressSize}),x.push(p)})}),y.forEach(c=>{this._assetMap[c]=x})})}resolveBundle(t){const e=yr(t);t=Lt(t);const r={};return t.forEach(n=>{const o=this._bundles[n];if(o){const l=this.resolve(o),h={};for(const u in l){const f=l[u];h[this._extractAssetIdFromBundle(n,u)]=f}r[n]=h}}),e?r[t[0]]:r}resolveUrl(t){const e=this.resolve(t);if(typeof t!="string"){const r={};for(const n in e)r[n]=e[n].src;return r}return e.src}resolve(t){const e=yr(t);t=Lt(t);const r={};return t.forEach(n=>{if(!this._resolverHash[n])if(this._assetMap[n]){let o=this._assetMap[n];const l=this._getPreferredOrder(o);l?.priority.forEach(h=>{l.params[h].forEach(u=>{const f=o.filter(m=>m[h]?m[h]===u:!1);f.length&&(o=f)})}),this._resolverHash[n]=o[0]}else this._resolverHash[n]=this._buildResolvedAsset({alias:[n],src:n},{});r[n]=this._resolverHash[n]}),e?r[t[0]]:r}hasKey(t){return!!this._assetMap[t]}hasBundle(t){return!!this._bundles[t]}_getPreferredOrder(t){for(let e=0;e<t.length;e++){const r=t[e],n=this._preferredOrder.find(o=>o.params.format.includes(r.format));if(n)return n}return this._preferredOrder[0]}_appendDefaultSearchParams(t){if(!this._defaultSearchParams)return t;const e=/\?/.test(t)?"&":"?";return`${t}${e}${this._defaultSearchParams}`}_buildResolvedAsset(t,e){const{aliases:r,data:n,loadParser:o,parser:l,format:h,progressSize:u}=e;return(this._basePath||this._rootPath)&&(t.src=At.toAbsolute(t.src,this._basePath,this._rootPath)),t.alias=r??t.alias??[t.src],t.src=this._appendDefaultSearchParams(t.src),t.data={...n||{},...t.data},t.loadParser=o??t.loadParser,t.parser=l??t.parser,t.format=h??t.format??Ap(t.src),u!==void 0&&(t.progressSize=u),t}}Ve.RETINA_PREFIX=/@([0-9\.]+)x/;function Ap(s){return s.split(".").pop().split("?").shift().split("#").shift()}const Gs=(s,t)=>{const e=t.split("?")[1];return e&&(s+=`?${e}`),s},Da=class qi{constructor(t,e){this.linkedSheets=[];let r=t;t?.source instanceof ht&&(r={texture:t,data:e});const{texture:n,data:o,cachePrefix:l=""}=r;this.cachePrefix=l,this._texture=n instanceof k?n:null,this.textureSource=n.source,this.textures={},this.animations={},this.data=o;const h=parseFloat(o.meta.scale);h?(this.resolution=h,n.source.resolution=this.resolution):this.resolution=n.source._resolution,this._frames=this.data.frames,this._frameKeys=Object.keys(this._frames),this._batchIndex=0,this._callback=null}parse(){return new Promise(t=>{this._callback=t,this._batchIndex=0,this._frameKeys.length<=qi.BATCH_SIZE?(this._processFrames(0),this._processAnimations(),this._parseComplete()):this._nextBatch()})}_processFrames(t){let e=t;const r=qi.BATCH_SIZE;for(;e-t<r&&e<this._frameKeys.length;){const n=this._frameKeys[e],o=this._frames[n],l=o.frame;if(l){let h=null,u=null;const f=o.trimmed!==!1&&o.sourceSize?o.sourceSize:o.frame,m=new G(0,0,Math.floor(f.w)/this.resolution,Math.floor(f.h)/this.resolution);o.rotated?h=new G(Math.floor(l.x)/this.resolution,Math.floor(l.y)/this.resolution,Math.floor(l.h)/this.resolution,Math.floor(l.w)/this.resolution):h=new G(Math.floor(l.x)/this.resolution,Math.floor(l.y)/this.resolution,Math.floor(l.w)/this.resolution,Math.floor(l.h)/this.resolution),o.trimmed!==!1&&o.spriteSourceSize&&(u=new G(Math.floor(o.spriteSourceSize.x)/this.resolution,Math.floor(o.spriteSourceSize.y)/this.resolution,Math.floor(l.w)/this.resolution,Math.floor(l.h)/this.resolution)),this.textures[n]=new k({source:this.textureSource,frame:h,orig:m,trim:u,rotate:o.rotated?2:0,defaultAnchor:o.anchor,defaultBorders:o.borders,label:n.toString()})}e++}}_processAnimations(){const t=this.data.animations||{};for(const e in t){this.animations[e]=[];for(let r=0;r<t[e].length;r++){const n=t[e][r];this.animations[e].push(this.textures[n])}}}_parseComplete(){const t=this._callback;this._callback=null,this._batchIndex=0,t.call(this,this.textures)}_nextBatch(){this._processFrames(this._batchIndex*qi.BATCH_SIZE),this._batchIndex++,setTimeout(()=>{this._batchIndex*qi.BATCH_SIZE<this._frameKeys.length?this._nextBatch():(this._processAnimations(),this._parseComplete())},0)}destroy(t=!1){for(const e in this.textures)this.textures[e].destroy();this._frames=null,this._frameKeys=null,this.data=null,this.textures=null,t&&(this._texture?.destroy(),this.textureSource.destroy()),this._texture=null,this.textureSource=null,this.linkedSheets=[]}};Da.BATCH_SIZE=1e3;let Oa=Da;const Pp=["jpg","png","jpeg","avif","webp","basis","etc2","bc7","bc6h","bc5","bc4","bc3","bc2","bc1","eac","astc"];function Ga(s,t,e){const r={};if(s.forEach(n=>{r[n]=t}),Object.keys(t.textures).forEach(n=>{r[`${t.cachePrefix}${n}`]=t.textures[n]}),!e){const n=At.dirname(s[0]);t.linkedSheets.forEach((o,l)=>{const h=Ga([`${n}/${t.data.meta.related_multi_packs[l]}`],o,!0);Object.assign(r,h)})}return r}const Bp={extension:C.Asset,cache:{test:s=>s instanceof Oa,getCacheableAssets:(s,t)=>Ga(s,t,!1)},resolver:{extension:{type:C.ResolveParser,name:"resolveSpritesheet"},test:s=>{const e=s.split("?")[0].split("."),r=e.pop(),n=e.pop();return r==="json"&&Pp.includes(n)},parse:s=>{const t=s.split(".");return{resolution:parseFloat(Ve.RETINA_PREFIX.exec(s)?.[1]??"1"),format:t[t.length-2],src:s}}},loader:{name:"spritesheetLoader",id:"spritesheet",extension:{type:C.LoadParser,priority:ue.Normal,name:"spritesheetLoader"},async testParse(s,t){return At.extname(t.src).toLowerCase()===".json"&&!!s.frames},async parse(s,t,e){const{texture:r,imageFilename:n,textureOptions:o,cachePrefix:l}=t?.data??{};let h=At.dirname(t.src);h&&h.lastIndexOf("/")!==h.length-1&&(h+="/");let u;if(r instanceof k)u=r;else{const g=Gs(h+(n??s.meta.image),t.src);u=(await e.load([{src:g,data:o}]))[g]}const f=new Oa({texture:u.source,data:s,cachePrefix:l});await f.parse();const m=s?.meta?.related_multi_packs;if(Array.isArray(m)){const g=[];for(const x of m){if(typeof x!="string")continue;let a=h+x;t.data?.ignoreMultiPack||(a=Gs(a,t.src),g.push(e.load({src:a,data:{textureOptions:o,ignoreMultiPack:!0}})))}const y=await Promise.all(g);f.linkedSheets=y,y.forEach(x=>{x.linkedSheets=[f].concat(f.linkedSheets.filter(a=>a!==x))})}return f},async unload(s,t,e){await e.unload(s.textureSource._sourceOrigin),s.destroy(!1)}}};D.add(Bp);class La{constructor(t){this._lastTransform="",this._observer=null,this._tickerAttached=!1,this.updateTranslation=()=>{if(!this._canvas)return;const e=this._canvas.getBoundingClientRect(),r=this._canvas.width,n=this._canvas.height,o=e.width/r*this._renderer.resolution,l=e.height/n*this._renderer.resolution,h=e.left,u=e.top,f=`translate(${h}px, ${u}px) scale(${o}, ${l})`;f!==this._lastTransform&&(this._domElement.style.transform=f,this._lastTransform=f)},this._domElement=t.domElement,this._renderer=t.renderer,!(globalThis.OffscreenCanvas&&this._renderer.canvas instanceof OffscreenCanvas)&&(this._canvas=this._renderer.canvas,this._attachObserver())}get canvas(){return this._canvas}ensureAttached(){!this._domElement.parentNode&&this._canvas.parentNode&&(this._canvas.parentNode.appendChild(this._domElement),this.updateTranslation())}_attachObserver(){"ResizeObserver"in globalThis?(this._observer&&(this._observer.disconnect(),this._observer=null),this._observer=new ResizeObserver(t=>{for(const e of t){if(e.target!==this._canvas)continue;const r=this.canvas.width,n=this.canvas.height,o=e.contentRect.width/r*this._renderer.resolution,l=e.contentRect.height/n*this._renderer.resolution;(this._lastScaleX!==o||this._lastScaleY!==l)&&(this.updateTranslation(),this._lastScaleX=o,this._lastScaleY=l)}}),this._observer.observe(this._canvas)):this._tickerAttached||Et.shared.add(this.updateTranslation,this,We.HIGH)}destroy(){this._observer?(this._observer.disconnect(),this._observer=null):this._tickerAttached&&Et.shared.remove(this.updateTranslation),this._domElement=null,this._renderer=null,this._canvas=null,this._tickerAttached=!1,this._lastTransform="",this._lastScaleX=null,this._lastScaleY=null}}class mi{constructor(t){this.bubbles=!0,this.cancelBubble=!0,this.cancelable=!1,this.composed=!1,this.defaultPrevented=!1,this.eventPhase=mi.prototype.NONE,this.propagationStopped=!1,this.propagationImmediatelyStopped=!1,this.layer=new q,this.page=new q,this.NONE=0,this.CAPTURING_PHASE=1,this.AT_TARGET=2,this.BUBBLING_PHASE=3,this.manager=t}get layerX(){return this.layer.x}get layerY(){return this.layer.y}get pageX(){return this.page.x}get pageY(){return this.page.y}get data(){return this}composedPath(){return this.manager&&(!this.path||this.path[this.path.length-1]!==this.target)&&(this.path=this.target?this.manager.propagationPath(this.target):[]),this.path}initEvent(t,e,r){throw new Error("initEvent() is a legacy DOM API. It is not implemented in the Federated Events API.")}initUIEvent(t,e,r,n,o){throw new Error("initUIEvent() is a legacy DOM API. It is not implemented in the Federated Events API.")}preventDefault(){this.nativeEvent instanceof Event&&this.nativeEvent.cancelable&&this.nativeEvent.preventDefault(),this.defaultPrevented=!0}stopImmediatePropagation(){this.propagationImmediatelyStopped=!0}stopPropagation(){this.propagationStopped=!0}}var Ls=/iPhone/i,za=/iPod/i,Na=/iPad/i,Ha=/\biOS-universal(?:.+)Mac\b/i,zs=/\bAndroid(?:.+)Mobile\b/i,Wa=/Android/i,Ye=/(?:SD4930UR|\bSilk(?:.+)Mobile\b)/i,xr=/Silk/i,se=/Windows Phone/i,Va=/\bWindows(?:.+)ARM\b/i,Ya=/BlackBerry/i,Xa=/BB10/i,$a=/Opera Mini/i,Ka=/\b(CriOS|Chrome)(?:.+)Mobile/i,ja=/Mobile(?:.+)Firefox\b/i,qa=function(s){return typeof s<"u"&&s.platform==="MacIntel"&&typeof s.maxTouchPoints=="number"&&s.maxTouchPoints>1&&typeof MSStream>"u"};function Up(s){return function(t){return t.test(s)}}function Za(s){var t={userAgent:"",platform:"",maxTouchPoints:0};!s&&typeof navigator<"u"?t={userAgent:navigator.userAgent,platform:navigator.platform,maxTouchPoints:navigator.maxTouchPoints||0}:typeof s=="string"?t.userAgent=s:s&&s.userAgent&&(t={userAgent:s.userAgent,platform:s.platform,maxTouchPoints:s.maxTouchPoints||0});var e=t.userAgent,r=e.split("[FBAN");typeof r[1]<"u"&&(e=r[0]),r=e.split("Twitter"),typeof r[1]<"u"&&(e=r[0]);var n=Up(e),o={apple:{phone:n(Ls)&&!n(se),ipod:n(za),tablet:!n(Ls)&&(n(Na)||qa(t))&&!n(se),universal:n(Ha),device:(n(Ls)||n(za)||n(Na)||n(Ha)||qa(t))&&!n(se)},amazon:{phone:n(Ye),tablet:!n(Ye)&&n(xr),device:n(Ye)||n(xr)},android:{phone:!n(se)&&n(Ye)||!n(se)&&n(zs),tablet:!n(se)&&!n(Ye)&&!n(zs)&&(n(xr)||n(Wa)),device:!n(se)&&(n(Ye)||n(xr)||n(zs)||n(Wa))||n(/\bokhttp\b/i)},windows:{phone:n(se),tablet:n(Va),device:n(se)||n(Va)},other:{blackberry:n(Ya),blackberry10:n(Xa),opera:n($a),firefox:n(ja),chrome:n(Ka),device:n(Ya)||n(Xa)||n($a)||n(ja)||n(Ka)},any:!1,phone:!1,tablet:!1};return o.any=o.apple.device||o.android.device||o.windows.device||o.other.device,o.phone=o.apple.phone||o.android.phone||o.windows.phone,o.tablet=o.apple.tablet||o.android.tablet||o.windows.tablet,o}const kp=(Za.default??Za)(globalThis.navigator),Mp=9,Qa=100,Rp=0,Ip=0,Ja=2,th=1,Fp=-1e3,Dp=-1e3,Op=2,Ns=class Qd{constructor(t,e=kp){this._mobileInfo=e,this.debug=!1,this._activateOnTab=!0,this._deactivateOnMouseMove=!0,this._isActive=!1,this._isMobileAccessibility=!1,this._div=null,this._pools={},this._renderId=0,this._children=[],this._androidUpdateCount=0,this._androidUpdateFrequency=500,this._isRunningTests=!1,this._boundOnKeyDown=this._onKeyDown.bind(this),this._boundOnMouseMove=this._onMouseMove.bind(this),this._hookDiv=null,(e.tablet||e.phone)&&this._createTouchHook(),this._renderer=t}get isActive(){return this._isActive}get isMobileAccessibility(){return this._isMobileAccessibility}get hookDiv(){return this._hookDiv}get div(){return this._div}_createTouchHook(){const t=document.createElement("button");t.style.width=`${th}px`,t.style.height=`${th}px`,t.style.position="absolute",t.style.top=`${Fp}px`,t.style.left=`${Dp}px`,t.style.zIndex=Op.toString(),t.style.backgroundColor="#FF0000",t.title="select to enable accessibility for this content",t.addEventListener("focus",()=>{this._isMobileAccessibility=!0,this._activate(),this._destroyTouchHook()}),document.body.appendChild(t),this._hookDiv=t}_destroyTouchHook(){this._hookDiv&&(document.body.removeChild(this._hookDiv),this._hookDiv=null)}_activate(){if(this._isActive)return;this._isActive=!0,this._div||(this._div=document.createElement("div"),this._div.style.position="absolute",this._div.style.top=`${Rp}px`,this._div.style.left=`${Ip}px`,this._div.style.pointerEvents="none",this._div.style.zIndex=Ja.toString(),this._canvasObserver=new La({domElement:this._div,renderer:this._renderer})),this._activateOnTab&&globalThis.addEventListener("keydown",this._boundOnKeyDown,!1),this._deactivateOnMouseMove&&globalThis.document.addEventListener("mousemove",this._boundOnMouseMove,!0);const t=this._renderer.view.canvas;if(t.parentNode)this._canvasObserver.ensureAttached(),this._initAccessibilitySetup();else{const e=new MutationObserver(()=>{t.parentNode&&(e.disconnect(),this._canvasObserver.ensureAttached(),this._initAccessibilitySetup())});e.observe(document.body,{childList:!0,subtree:!0})}}_initAccessibilitySetup(){this._renderer.runners.postrender.add(this),this._renderer.lastObjectRendered&&this._updateAccessibleObjects(this._renderer.lastObjectRendered)}_deactivate(){if(!(!this._isActive||this._isMobileAccessibility)){this._isActive=!1,globalThis.document.removeEventListener("mousemove",this._boundOnMouseMove,!0),this._activateOnTab&&globalThis.addEventListener("keydown",this._boundOnKeyDown,!1),this._renderer.runners.postrender.remove(this);for(const t of this._children)t._accessibleDiv?.parentNode&&(t._accessibleDiv.parentNode.removeChild(t._accessibleDiv),t._accessibleDiv=null),t._accessibleActive=!1;for(const t in this._pools)this._pools[t].forEach(r=>{r.parentNode&&r.parentNode.removeChild(r)}),delete this._pools[t];this._div?.parentNode&&this._div.parentNode.removeChild(this._div),this._pools={},this._children=[]}}_updateAccessibleObjects(t){if(!t.visible||!t.accessibleChildren)return;t.accessible&&(t._accessibleActive||this._addChild(t),t._renderId=this._renderId);const e=t.children;if(e)for(let r=0;r<e.length;r++)this._updateAccessibleObjects(e[r])}init(t){const r={accessibilityOptions:{...Qd.defaultOptions,...t?.accessibilityOptions||{}}};this.debug=r.accessibilityOptions.debug,this._activateOnTab=r.accessibilityOptions.activateOnTab,this._deactivateOnMouseMove=r.accessibilityOptions.deactivateOnMouseMove,r.accessibilityOptions.enabledByDefault&&this._activate(),this._renderer.runners.postrender.remove(this)}postrender(){const t=performance.now();if(this._mobileInfo.android.device&&t<this._androidUpdateCount||(this._androidUpdateCount=t+this._androidUpdateFrequency,(!this._renderer.renderingToScreen||!this._renderer.view.canvas)&&!this._isRunningTests))return;const e=new Set;if(this._renderer.lastObjectRendered){this._updateAccessibleObjects(this._renderer.lastObjectRendered);for(const r of this._children)r._renderId===this._renderId&&e.add(this._children.indexOf(r))}for(let r=this._children.length-1;r>=0;r--){const n=this._children[r];e.has(r)||(n._accessibleDiv&&n._accessibleDiv.parentNode&&(n._accessibleDiv.parentNode.removeChild(n._accessibleDiv),this._getPool(n.accessibleType).push(n._accessibleDiv),n._accessibleDiv=null),n._accessibleActive=!1,ya(this._children,r,1))}this._renderer.renderingToScreen&&this._canvasObserver.ensureAttached();for(let r=0;r<this._children.length;r++){const n=this._children[r];if(!n._accessibleActive||!n._accessibleDiv)continue;const o=n._accessibleDiv,l=n.hitArea||n.getBounds().rectangle;if(n.hitArea){const h=n.worldTransform;o.style.left=`${h.tx+l.x*h.a}px`,o.style.top=`${h.ty+l.y*h.d}px`,o.style.width=`${l.width*h.a}px`,o.style.height=`${l.height*h.d}px`}else this._capHitArea(l),o.style.left=`${l.x}px`,o.style.top=`${l.y}px`,o.style.width=`${l.width}px`,o.style.height=`${l.height}px`}this._renderId++}_updateDebugHTML(t){t.innerHTML=`type: ${t.type}</br> title : ${t.title}</br> tabIndex: ${t.tabIndex}`}_capHitArea(t){t.x<0&&(t.width+=t.x,t.x=0),t.y<0&&(t.height+=t.y,t.y=0);const{width:e,height:r}=this._renderer;t.x+t.width>e&&(t.width=e-t.x),t.y+t.height>r&&(t.height=r-t.y)}_addChild(t){let r=this._getPool(t.accessibleType).pop();r?(r.innerHTML="",r.removeAttribute("title"),r.removeAttribute("aria-label"),r.tabIndex=0):(t.accessibleType==="button"?r=document.createElement("button"):(r=document.createElement(t.accessibleType),r.style.cssText=`
|
|
68
68
|
color: transparent;
|
|
69
69
|
pointer-events: none;
|
|
70
70
|
padding: 0;
|
|
@@ -77,7 +77,7 @@ Deprecated since v${s}`,a=typeof console.groupCollapsed=="function"&&!Oe.noColor
|
|
|
77
77
|
-webkit-user-select: none;
|
|
78
78
|
-moz-user-select: none;
|
|
79
79
|
-ms-user-select: none;
|
|
80
|
-
`,t.accessibleText&&(r.innerText=t.accessibleText)),r.style.width=`${
|
|
80
|
+
`,t.accessibleText&&(r.innerText=t.accessibleText)),r.style.width=`${Qa}px`,r.style.height=`${Qa}px`,r.style.backgroundColor=this.debug?"rgba(255,255,255,0.5)":"transparent",r.style.position="absolute",r.style.zIndex=Ja.toString(),r.style.borderStyle="none",navigator.userAgent.toLowerCase().includes("chrome")?r.setAttribute("aria-live","off"):r.setAttribute("aria-live","polite"),navigator.userAgent.match(/rv:.*Gecko\//)?r.setAttribute("aria-relevant","additions"):r.setAttribute("aria-relevant","text"),r.addEventListener("click",this._onClick.bind(this)),r.addEventListener("focus",this._onFocus.bind(this)),r.addEventListener("focusout",this._onFocusOut.bind(this))),r.style.pointerEvents=t.accessiblePointerEvents,r.type=t.accessibleType,t.accessibleTitle&&t.accessibleTitle!==null?r.title=t.accessibleTitle:(!t.accessibleHint||t.accessibleHint===null)&&(r.title=`container ${t.tabIndex}`),t.accessibleHint&&t.accessibleHint!==null&&r.setAttribute("aria-label",t.accessibleHint),t.interactive?r.tabIndex=t.tabIndex:r.tabIndex=0,this.debug&&this._updateDebugHTML(r),t._accessibleActive=!0,t._accessibleDiv=r,r.container=t,this._children.push(t),this._div.appendChild(t._accessibleDiv)}_dispatchEvent(t,e){const{container:r}=t.target,n=this._renderer.events.rootBoundary,o=Object.assign(new mi(n),{target:r});n.rootTarget=this._renderer.lastObjectRendered,e.forEach(l=>n.dispatchEvent(o,l))}_onClick(t){this._dispatchEvent(t,["click","pointertap","tap"])}_onFocus(t){t.target.getAttribute("aria-live")||t.target.setAttribute("aria-live","assertive"),this._dispatchEvent(t,["mouseover"])}_onFocusOut(t){t.target.getAttribute("aria-live")||t.target.setAttribute("aria-live","polite"),this._dispatchEvent(t,["mouseout"])}_onKeyDown(t){t.keyCode!==Mp||!this._activateOnTab||this._activate()}_onMouseMove(t){t.movementX===0&&t.movementY===0||this._deactivate()}destroy(){this._deactivate(),this._destroyTouchHook(),this._canvasObserver?.destroy(),this._canvasObserver=null,this._div=null,this._pools=null,this._children=null,this._renderer=null,this._hookDiv=null,globalThis.removeEventListener("keydown",this._boundOnKeyDown),this._boundOnKeyDown=null,globalThis.document.removeEventListener("mousemove",this._boundOnMouseMove,!0),this._boundOnMouseMove=null}setAccessibilityEnabled(t){t?this._activate():this._deactivate()}_getPool(t){return this._pools[t]||(this._pools[t]=[]),this._pools[t]}};Ns.extension={type:[C.WebGLSystem,C.WebGPUSystem],name:"accessibility"},Ns.defaultOptions={enabledByDefault:!1,debug:!1,activateOnTab:!0,deactivateOnMouseMove:!0};let Gp=Ns;const Lp={accessible:!1,accessibleTitle:null,accessibleHint:null,tabIndex:0,accessibleType:"button",accessibleText:null,accessiblePointerEvents:"auto",accessibleChildren:!0,_accessibleActive:!1,_accessibleDiv:null,_renderId:-1},Hs=Object.create(null),eh=Object.create(null);function gi(s,t){let e=eh[s];return e===void 0&&(Hs[t]===void 0&&(Hs[t]=1),eh[s]=e=Hs[t]++),e}let br;function ih(){return(!br||br?.isContextLost())&&(br=W.get().createCanvas().getContext("webgl",{})),br}let vr;function zp(){if(!vr){vr="mediump";const s=ih();s&&s.getShaderPrecisionFormat&&(vr=s.getShaderPrecisionFormat(s.FRAGMENT_SHADER,s.HIGH_FLOAT).precision?"highp":"mediump")}return vr}function Np(s,t,e){return t?s:e?(s=s.replace("out vec4 finalColor;",""),`
|
|
81
81
|
|
|
82
82
|
#ifdef GL_ES // This checks if it is WebGL1
|
|
83
83
|
#define in varying
|
|
@@ -92,32 +92,32 @@ Deprecated since v${s}`,a=typeof console.groupCollapsed=="function"&&!Oe.noColor
|
|
|
92
92
|
#define out varying
|
|
93
93
|
#endif
|
|
94
94
|
${s}
|
|
95
|
-
`}function
|
|
96
|
-
${s}`}else if(r!=="highp"&&s.substring(0,15)==="precision highp")return s.replace("precision highp","precision mediump");return s}function
|
|
97
|
-
${s}`:s}const
|
|
98
|
-
${s}`}function Op(s,t){return t?s.replace("#version 300 es",""):s}const zs={stripVersion:Op,ensurePrecision:Rp,addProgramDefines:kp,setProgramName:Gp,insertVersion:Ip},gi=Object.create(null),Jo=class pa{constructor(t){t={...pa.defaultOptions,...t};const e=t.fragment.indexOf("#version 300 es")!==-1,r={stripVersion:e,ensurePrecision:{requestedFragmentPrecision:t.preferredFragmentPrecision,requestedVertexPrecision:t.preferredVertexPrecision,maxSupportedVertexPrecision:"highp",maxSupportedFragmentPrecision:Mp()},setProgramName:{name:t.name},addProgramDefines:e,insertVersion:e};let n=t.fragment,a=t.vertex;Object.keys(zs).forEach(l=>{const h=r[l];n=zs[l](n,h,!0),a=zs[l](a,h,!1)}),this.fragment=n,this.vertex=a,this.transformFeedbackVaryings=t.transformFeedbackVaryings,this._key=mi(`${this.vertex}:${this.fragment}`,"gl-program")}destroy(){this.fragment=null,this.vertex=null,this._attributeData=null,this._uniformData=null,this._uniformBlockData=null,this.transformFeedbackVaryings=null,gi[this._cacheKey]=null}static from(t){const e=`${t.vertex}:${t.fragment}`;return gi[e]||(gi[e]=new pa(t),gi[e]._cacheKey=e),gi[e]}};Jo.defaultOptions={preferredVertexPrecision:"highp",preferredFragmentPrecision:"mediump"};let Se=Jo;const th={uint8x2:{size:2,stride:2,normalised:!1},uint8x4:{size:4,stride:4,normalised:!1},sint8x2:{size:2,stride:2,normalised:!1},sint8x4:{size:4,stride:4,normalised:!1},unorm8x2:{size:2,stride:2,normalised:!0},unorm8x4:{size:4,stride:4,normalised:!0},snorm8x2:{size:2,stride:2,normalised:!0},snorm8x4:{size:4,stride:4,normalised:!0},uint16x2:{size:2,stride:4,normalised:!1},uint16x4:{size:4,stride:8,normalised:!1},sint16x2:{size:2,stride:4,normalised:!1},sint16x4:{size:4,stride:8,normalised:!1},unorm16x2:{size:2,stride:4,normalised:!0},unorm16x4:{size:4,stride:8,normalised:!0},snorm16x2:{size:2,stride:4,normalised:!0},snorm16x4:{size:4,stride:8,normalised:!0},float16x2:{size:2,stride:4,normalised:!1},float16x4:{size:4,stride:8,normalised:!1},float32:{size:1,stride:4,normalised:!1},float32x2:{size:2,stride:8,normalised:!1},float32x3:{size:3,stride:12,normalised:!1},float32x4:{size:4,stride:16,normalised:!1},uint32:{size:1,stride:4,normalised:!1},uint32x2:{size:2,stride:8,normalised:!1},uint32x3:{size:3,stride:12,normalised:!1},uint32x4:{size:4,stride:16,normalised:!1},sint32:{size:1,stride:4,normalised:!1},sint32x2:{size:2,stride:8,normalised:!1},sint32x3:{size:3,stride:12,normalised:!1},sint32x4:{size:4,stride:16,normalised:!1}};function ue(s){return th[s]??th.float32}const Lp={f32:"float32","vec2<f32>":"float32x2","vec3<f32>":"float32x3","vec4<f32>":"float32x4",vec2f:"float32x2",vec3f:"float32x3",vec4f:"float32x4",i32:"sint32","vec2<i32>":"sint32x2","vec3<i32>":"sint32x3","vec4<i32>":"sint32x4",u32:"uint32","vec2<u32>":"uint32x2","vec3<u32>":"uint32x3","vec4<u32>":"uint32x4",bool:"uint32","vec2<bool>":"uint32x2","vec3<bool>":"uint32x3","vec4<bool>":"uint32x4"};function zp({source:s,entryPoint:t}){const e={},r=s.indexOf(`fn ${t}`);if(r!==-1){const n=s.indexOf("->",r);if(n!==-1){const a=s.substring(r,n),l=/@location\((\d+)\)\s+([a-zA-Z0-9_]+)\s*:\s*([a-zA-Z0-9_<>]+)(?:,|\s|$)/g;let h;for(;(h=l.exec(a))!==null;){const d=Lp[h[3]]??"float32";e[h[2]]={location:parseInt(h[1],10),format:d,stride:ue(d).stride,offset:0,instance:!1,start:0}}}}return e}function Ns(s){const t=/(^|[^/])@(group|binding)\(\d+\)[^;]+;/g,e=/@group\((\d+)\)/,r=/@binding\((\d+)\)/,n=/var(<[^>]+>)? (\w+)/,a=/:\s*(\w+)/,l=/struct\s+(\w+)\s*{([^}]+)}/g,h=/(\w+)\s*:\s*([\w\<\>]+)/g,d=/struct\s+(\w+)/,f=s.match(t)?.map(g=>({group:parseInt(g.match(e)[1],10),binding:parseInt(g.match(r)[1],10),name:g.match(n)[2],isUniform:g.match(n)[1]==="<uniform>",type:g.match(a)[1]}));if(!f)return{groups:[],structs:[]};const m=s.match(l)?.map(g=>{const y=g.match(d)[1],x=g.match(h).reduce((o,c)=>{const[u,p]=c.split(":");return o[u.trim()]=p.trim(),o},{});return x?{name:y,members:x}:null}).filter(({name:g})=>f.some(y=>y.type===g))??[];return{groups:f,structs:m}}var _i=(s=>(s[s.VERTEX=1]="VERTEX",s[s.FRAGMENT=2]="FRAGMENT",s[s.COMPUTE=4]="COMPUTE",s))(_i||{});function Np({groups:s}){const t=[];for(let e=0;e<s.length;e++){const r=s[e];t[r.group]||(t[r.group]=[]),r.isUniform?t[r.group].push({binding:r.binding,visibility:_i.VERTEX|_i.FRAGMENT,buffer:{type:"uniform"}}):r.type==="sampler"?t[r.group].push({binding:r.binding,visibility:_i.FRAGMENT,sampler:{type:"filtering"}}):r.type==="texture_2d"&&t[r.group].push({binding:r.binding,visibility:_i.FRAGMENT,texture:{sampleType:"float",viewDimension:"2d",multisampled:!1}})}return t}function Hp({groups:s}){const t=[];for(let e=0;e<s.length;e++){const r=s[e];t[r.group]||(t[r.group]={}),t[r.group][r.name]=r.binding}return t}function Wp(s,t){const e=new Set,r=new Set,n=[...s.structs,...t.structs].filter(l=>e.has(l.name)?!1:(e.add(l.name),!0)),a=[...s.groups,...t.groups].filter(l=>{const h=`${l.name}-${l.binding}`;return r.has(h)?!1:(r.add(h),!0)});return{structs:n,groups:a}}const yi=Object.create(null);class de{constructor(t){this._layoutKey=0,this._attributeLocationsKey=0;const{fragment:e,vertex:r,layout:n,gpuLayout:a,name:l}=t;if(this.name=l,this.fragment=e,this.vertex=r,e.source===r.source){const h=Ns(e.source);this.structsAndGroups=h}else{const h=Ns(r.source),d=Ns(e.source);this.structsAndGroups=Wp(h,d)}this.layout=n??Hp(this.structsAndGroups),this.gpuLayout=a??Np(this.structsAndGroups),this.autoAssignGlobalUniforms=this.layout[0]?.globalUniforms!==void 0,this.autoAssignLocalUniforms=this.layout[1]?.localUniforms!==void 0,this._generateProgramKey()}_generateProgramKey(){const{vertex:t,fragment:e}=this,r=t.source+e.source+t.entryPoint+e.entryPoint;this._layoutKey=mi(r,"program")}get attributeData(){return this._attributeData??(this._attributeData=zp(this.vertex)),this._attributeData}destroy(){this.gpuLayout=null,this.layout=null,this.structsAndGroups=null,this.fragment=null,this.vertex=null,yi[this._cacheKey]=null}static from(t){const e=`${t.vertex.source}:${t.fragment.source}:${t.fragment.entryPoint}:${t.vertex.entryPoint}`;return yi[e]||(yi[e]=new de(t),yi[e]._cacheKey=e),yi[e]}}const eh=["f32","i32","vec2<f32>","vec3<f32>","vec4<f32>","mat2x2<f32>","mat3x3<f32>","mat4x4<f32>","mat3x2<f32>","mat4x2<f32>","mat2x3<f32>","mat4x3<f32>","mat2x4<f32>","mat3x4<f32>","vec2<i32>","vec3<i32>","vec4<i32>"],Vp=eh.reduce((s,t)=>(s[t]=!0,s),{});function Yp(s,t){switch(s){case"f32":return 0;case"vec2<f32>":return new Float32Array(2*t);case"vec3<f32>":return new Float32Array(3*t);case"vec4<f32>":return new Float32Array(4*t);case"mat2x2<f32>":return new Float32Array([1,0,0,1]);case"mat3x3<f32>":return new Float32Array([1,0,0,0,1,0,0,0,1]);case"mat4x4<f32>":return new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1])}return null}const ih=class ju{constructor(t,e){this._touched=0,this.uid=et("uniform"),this._resourceType="uniformGroup",this._resourceId=et("resource"),this.isUniformGroup=!0,this._dirtyId=0,this.destroyed=!1,e={...ju.defaultOptions,...e},this.uniformStructures=t;const r={};for(const n in t){const a=t[n];if(a.name=n,a.size=a.size??1,!Vp[a.type]){const l=a.type.match(/^array<(\w+(?:<\w+>)?),\s*(\d+)>$/);if(l){const[,h,d]=l;throw new Error(`Uniform type ${a.type} is not supported. Use type: '${h}', size: ${d} instead.`)}throw new Error(`Uniform type ${a.type} is not supported. Supported uniform types are: ${eh.join(", ")}`)}a.value??(a.value=Yp(a.type,a.size)),r[n]=a.value}this.uniforms=r,this._dirtyId=1,this.ubo=e.ubo,this.isStatic=e.isStatic,this._signature=mi(Object.keys(r).map(n=>`${n}-${t[n].type}`).join("-"),"uniform-group")}update(){this._dirtyId++}};ih.defaultOptions={ubo:!1,isStatic:!1};let gt=ih;class re{constructor(t){this.resources=Object.create(null),this._dirty=!0;let e=0;for(const r in t){const n=t[r];this.setResource(n,e++)}this._updateKey()}_updateKey(){if(!this._dirty)return;this._dirty=!1;const t=[];let e=0;for(const r in this.resources)t[e++]=this.resources[r]._resourceId;this._key=t.join("|")}setResource(t,e){const r=this.resources[e];t!==r&&(r&&t.off?.("change",this.onResourceChange,this),t.on?.("change",this.onResourceChange,this),this.resources[e]=t,this._dirty=!0)}getResource(t){return this.resources[t]}_touch(t){const e=this.resources;for(const r in e)e[r]._touched=t}destroy(){const t=this.resources;for(const e in t)t[e]?.off?.("change",this.onResourceChange,this);this.resources=null}onResourceChange(t){if(this._dirty=!0,t.destroyed){const e=this.resources;for(const r in e)e[r]===t&&(e[r]=null)}else this._updateKey()}}var Nt=(s=>(s[s.WEBGL=1]="WEBGL",s[s.WEBGPU=2]="WEBGPU",s[s.BOTH=3]="BOTH",s))(Nt||{});class It extends Tt{constructor(t){super(),this.uid=et("shader"),this._uniformBindMap=Object.create(null),this._ownedBindGroups=[],this._destroyed=!1;let{gpuProgram:e,glProgram:r,groups:n,resources:a,compatibleRenderers:l,groupMap:h}=t;this.gpuProgram=e,this.glProgram=r,l===void 0&&(l=0,e&&(l|=Nt.WEBGPU),r&&(l|=Nt.WEBGL)),this.compatibleRenderers=l;const d={};if(!a&&!n&&(a={}),a&&n)throw new Error("[Shader] Cannot have both resources and groups");if(!e&&n&&!h)throw new Error("[Shader] No group map or WebGPU shader provided - consider using resources instead.");if(!e&&n&&h)for(const f in h)for(const m in h[f]){const g=h[f][m];d[g]={group:f,binding:m,name:g}}else if(e&&n&&!h){const f=e.structsAndGroups.groups;h={},f.forEach(m=>{h[m.group]=h[m.group]||{},h[m.group][m.binding]=m.name,d[m.name]=m})}else if(a){n={},h={},e&&e.structsAndGroups.groups.forEach(g=>{h[g.group]=h[g.group]||{},h[g.group][g.binding]=g.name,d[g.name]=g});let f=0;for(const m in a)d[m]||(n[99]||(n[99]=new re,this._ownedBindGroups.push(n[99])),d[m]={group:99,binding:f,name:m},h[99]=h[99]||{},h[99][f]=m,f++);for(const m in a){const g=m;let y=a[m];!y.source&&!y._resourceType&&(y=new gt(y));const x=d[g];x&&(n[x.group]||(n[x.group]=new re,this._ownedBindGroups.push(n[x.group])),n[x.group].setResource(y,x.binding))}}this.groups=n,this._uniformBindMap=h,this.resources=this._buildResourceAccessor(n,d)}addResource(t,e,r){var n,a;(n=this._uniformBindMap)[e]||(n[e]={}),(a=this._uniformBindMap[e])[r]||(a[r]=t),this.groups[e]||(this.groups[e]=new re,this._ownedBindGroups.push(this.groups[e]))}_buildResourceAccessor(t,e){const r={};for(const n in e){const a=e[n];Object.defineProperty(r,a.name,{get(){return t[a.group].getResource(a.binding)},set(l){t[a.group].setResource(l,a.binding)}})}return r}destroy(t=!1){this._destroyed||(this._destroyed=!0,this.emit("destroy",this),t&&(this.gpuProgram?.destroy(),this.glProgram?.destroy()),this.gpuProgram=null,this.glProgram=null,this.removeAllListeners(),this._uniformBindMap=null,this._ownedBindGroups.forEach(e=>{e.destroy()}),this._ownedBindGroups=null,this.resources=null,this.groups=null)}static from(t){const{gpu:e,gl:r,...n}=t;let a,l;return e&&(a=de.from(e)),r&&(l=Se.from(r)),new It({gpuProgram:a,glProgram:l,...n})}}const Xp={normal:0,add:1,multiply:2,screen:3,overlay:4,erase:5,"normal-npm":6,"add-npm":7,"screen-npm":8,min:9,max:10},Hs=0,Ws=1,Vs=2,Ys=3,Xs=4,$s=5,Ks=class qu{constructor(){this.data=0,this.blendMode="normal",this.polygonOffset=0,this.blend=!0,this.depthMask=!0}get blend(){return!!(this.data&1<<Hs)}set blend(t){!!(this.data&1<<Hs)!==t&&(this.data^=1<<Hs)}get offsets(){return!!(this.data&1<<Ws)}set offsets(t){!!(this.data&1<<Ws)!==t&&(this.data^=1<<Ws)}set cullMode(t){if(t==="none"){this.culling=!1;return}this.culling=!0,this.clockwiseFrontFace=t==="front"}get cullMode(){return this.culling?this.clockwiseFrontFace?"front":"back":"none"}get culling(){return!!(this.data&1<<Vs)}set culling(t){!!(this.data&1<<Vs)!==t&&(this.data^=1<<Vs)}get depthTest(){return!!(this.data&1<<Ys)}set depthTest(t){!!(this.data&1<<Ys)!==t&&(this.data^=1<<Ys)}get depthMask(){return!!(this.data&1<<$s)}set depthMask(t){!!(this.data&1<<$s)!==t&&(this.data^=1<<$s)}get clockwiseFrontFace(){return!!(this.data&1<<Xs)}set clockwiseFrontFace(t){!!(this.data&1<<Xs)!==t&&(this.data^=1<<Xs)}get blendMode(){return this._blendMode}set blendMode(t){this.blend=t!=="none",this._blendMode=t,this._blendModeId=Xp[t]||0}get polygonOffset(){return this._polygonOffset}set polygonOffset(t){this.offsets=!!t,this._polygonOffset=t}toString(){return`[pixi.js/core:State blendMode=${this.blendMode} clockwiseFrontFace=${this.clockwiseFrontFace} culling=${this.culling} depthMask=${this.depthMask} polygonOffset=${this.polygonOffset}]`}static for2d(){const t=new qu;return t.depthTest=!1,t.blend=!0,t}};Ks.default2d=Ks.for2d();let Ht=Ks;const rh=class ma extends It{constructor(t){t={...ma.defaultOptions,...t},super(t),this.enabled=!0,this._state=Ht.for2d(),this.blendMode=t.blendMode,this.padding=t.padding,typeof t.antialias=="boolean"?this.antialias=t.antialias?"on":"off":this.antialias=t.antialias,this.resolution=t.resolution,this.blendRequired=t.blendRequired,this.clipToViewport=t.clipToViewport,this.addResource("uTexture",0,1),t.blendRequired&&this.addResource("uBackTexture",0,3)}apply(t,e,r,n){t.applyFilter(this,e,r,n)}get blendMode(){return this._state.blendMode}set blendMode(t){this._state.blendMode=t}static from(t){const{gpu:e,gl:r,...n}=t;let a,l;return e&&(a=de.from(e)),r&&(l=Se.from(r)),new ma({gpuProgram:a,glProgram:l,...n})}};rh.defaultOptions={blendMode:"normal",resolution:1,padding:0,antialias:"off",blendRequired:!1,clipToViewport:!0};let sh=rh;const js=[];D.handleByNamedList(C.Environment,js);async function $p(s){if(!s)for(let t=0;t<js.length;t++){const e=js[t];if(e.value.test()){await e.value.load();return}}}let xi;function nh(){if(typeof xi=="boolean")return xi;try{xi=new Function("param1","param2","param3","return param1[param2] === param3;")({a:"b"},"a","b")===!0}catch{xi=!1}return xi}function ah(s,t,e=2){const r=t&&t.length,n=r?t[0]*e:s.length;let a=oh(s,0,n,e,!0);const l=[];if(!a||a.next===a.prev)return l;let h,d,f;if(r&&(a=Qp(s,t,a,e)),s.length>80*e){h=s[0],d=s[1];let m=h,g=d;for(let y=e;y<n;y+=e){const x=s[y],o=s[y+1];x<h&&(h=x),o<d&&(d=o),x>m&&(m=x),o>g&&(g=o)}f=Math.max(m-h,g-d),f=f!==0?32767/f:0}return bi(a,l,e,h,d,f,0),l}function oh(s,t,e,r,n){let a;if(n===lm(s,t,e,r)>0)for(let l=t;l<e;l+=r)a=uh(l/r|0,s[l],s[l+1],a);else for(let l=e-r;l>=t;l-=r)a=uh(l/r|0,s[l],s[l+1],a);return a&&Ye(a,a.next)&&(Si(a),a=a.next),a}function Te(s,t){if(!s)return s;t||(t=s);let e=s,r;do if(r=!1,!e.steiner&&(Ye(e,e.next)||it(e.prev,e,e.next)===0)){if(Si(e),e=t=e.prev,e===e.next)break;r=!0}else e=e.next;while(r||e!==t);return t}function bi(s,t,e,r,n,a,l){if(!s)return;!l&&a&&rm(s,r,n,a);let h=s;for(;s.prev!==s.next;){const d=s.prev,f=s.next;if(a?jp(s,r,n,a):Kp(s)){t.push(d.i,s.i,f.i),Si(s),s=f.next,h=f.next;continue}if(s=f,s===h){l?l===1?(s=qp(Te(s),t),bi(s,t,e,r,n,a,2)):l===2&&Zp(s,t,e,r,n,a):bi(Te(s),t,e,r,n,a,1);break}}}function Kp(s){const t=s.prev,e=s,r=s.next;if(it(t,e,r)>=0)return!1;const n=t.x,a=e.x,l=r.x,h=t.y,d=e.y,f=r.y,m=Math.min(n,a,l),g=Math.min(h,d,f),y=Math.max(n,a,l),x=Math.max(h,d,f);let o=r.next;for(;o!==t;){if(o.x>=m&&o.x<=y&&o.y>=g&&o.y<=x&&vi(n,h,a,d,l,f,o.x,o.y)&&it(o.prev,o,o.next)>=0)return!1;o=o.next}return!0}function jp(s,t,e,r){const n=s.prev,a=s,l=s.next;if(it(n,a,l)>=0)return!1;const h=n.x,d=a.x,f=l.x,m=n.y,g=a.y,y=l.y,x=Math.min(h,d,f),o=Math.min(m,g,y),c=Math.max(h,d,f),u=Math.max(m,g,y),p=qs(x,o,t,e,r),_=qs(c,u,t,e,r);let b=s.prevZ,v=s.nextZ;for(;b&&b.z>=p&&v&&v.z<=_;){if(b.x>=x&&b.x<=c&&b.y>=o&&b.y<=u&&b!==n&&b!==l&&vi(h,m,d,g,f,y,b.x,b.y)&&it(b.prev,b,b.next)>=0||(b=b.prevZ,v.x>=x&&v.x<=c&&v.y>=o&&v.y<=u&&v!==n&&v!==l&&vi(h,m,d,g,f,y,v.x,v.y)&&it(v.prev,v,v.next)>=0))return!1;v=v.nextZ}for(;b&&b.z>=p;){if(b.x>=x&&b.x<=c&&b.y>=o&&b.y<=u&&b!==n&&b!==l&&vi(h,m,d,g,f,y,b.x,b.y)&&it(b.prev,b,b.next)>=0)return!1;b=b.prevZ}for(;v&&v.z<=_;){if(v.x>=x&&v.x<=c&&v.y>=o&&v.y<=u&&v!==n&&v!==l&&vi(h,m,d,g,f,y,v.x,v.y)&&it(v.prev,v,v.next)>=0)return!1;v=v.nextZ}return!0}function qp(s,t){let e=s;do{const r=e.prev,n=e.next.next;!Ye(r,n)&&lh(r,e,e.next,n)&&wi(r,n)&&wi(n,r)&&(t.push(r.i,e.i,n.i),Si(e),Si(e.next),e=s=n),e=e.next}while(e!==s);return Te(e)}function Zp(s,t,e,r,n,a){let l=s;do{let h=l.next.next;for(;h!==l.prev;){if(l.i!==h.i&&am(l,h)){let d=ch(l,h);l=Te(l,l.next),d=Te(d,d.next),bi(l,t,e,r,n,a,0),bi(d,t,e,r,n,a,0);return}h=h.next}l=l.next}while(l!==s)}function Qp(s,t,e,r){const n=[];for(let a=0,l=t.length;a<l;a++){const h=t[a]*r,d=a<l-1?t[a+1]*r:s.length,f=oh(s,h,d,r,!1);f===f.next&&(f.steiner=!0),n.push(nm(f))}n.sort(Jp);for(let a=0;a<n.length;a++)e=tm(n[a],e);return e}function Jp(s,t){let e=s.x-t.x;if(e===0&&(e=s.y-t.y,e===0)){const r=(s.next.y-s.y)/(s.next.x-s.x),n=(t.next.y-t.y)/(t.next.x-t.x);e=r-n}return e}function tm(s,t){const e=em(s,t);if(!e)return t;const r=ch(e,s);return Te(r,r.next),Te(e,e.next)}function em(s,t){let e=t;const r=s.x,n=s.y;let a=-1/0,l;if(Ye(s,e))return e;do{if(Ye(s,e.next))return e.next;if(n<=e.y&&n>=e.next.y&&e.next.y!==e.y){const g=e.x+(n-e.y)*(e.next.x-e.x)/(e.next.y-e.y);if(g<=r&&g>a&&(a=g,l=e.x<e.next.x?e:e.next,g===r))return l}e=e.next}while(e!==t);if(!l)return null;const h=l,d=l.x,f=l.y;let m=1/0;e=l;do{if(r>=e.x&&e.x>=d&&r!==e.x&&hh(n<f?r:a,n,d,f,n<f?a:r,n,e.x,e.y)){const g=Math.abs(n-e.y)/(r-e.x);wi(e,s)&&(g<m||g===m&&(e.x>l.x||e.x===l.x&&im(l,e)))&&(l=e,m=g)}e=e.next}while(e!==h);return l}function im(s,t){return it(s.prev,s,t.prev)<0&&it(t.next,s,s.next)<0}function rm(s,t,e,r){let n=s;do n.z===0&&(n.z=qs(n.x,n.y,t,e,r)),n.prevZ=n.prev,n.nextZ=n.next,n=n.next;while(n!==s);n.prevZ.nextZ=null,n.prevZ=null,sm(n)}function sm(s){let t,e=1;do{let r=s,n;s=null;let a=null;for(t=0;r;){t++;let l=r,h=0;for(let f=0;f<e&&(h++,l=l.nextZ,!!l);f++);let d=e;for(;h>0||d>0&&l;)h!==0&&(d===0||!l||r.z<=l.z)?(n=r,r=r.nextZ,h--):(n=l,l=l.nextZ,d--),a?a.nextZ=n:s=n,n.prevZ=a,a=n;r=l}a.nextZ=null,e*=2}while(t>1);return s}function qs(s,t,e,r,n){return s=(s-e)*n|0,t=(t-r)*n|0,s=(s|s<<8)&16711935,s=(s|s<<4)&252645135,s=(s|s<<2)&858993459,s=(s|s<<1)&1431655765,t=(t|t<<8)&16711935,t=(t|t<<4)&252645135,t=(t|t<<2)&858993459,t=(t|t<<1)&1431655765,s|t<<1}function nm(s){let t=s,e=s;do(t.x<e.x||t.x===e.x&&t.y<e.y)&&(e=t),t=t.next;while(t!==s);return e}function hh(s,t,e,r,n,a,l,h){return(n-l)*(t-h)>=(s-l)*(a-h)&&(s-l)*(r-h)>=(e-l)*(t-h)&&(e-l)*(a-h)>=(n-l)*(r-h)}function vi(s,t,e,r,n,a,l,h){return!(s===l&&t===h)&&hh(s,t,e,r,n,a,l,h)}function am(s,t){return s.next.i!==t.i&&s.prev.i!==t.i&&!om(s,t)&&(wi(s,t)&&wi(t,s)&&hm(s,t)&&(it(s.prev,s,t.prev)||it(s,t.prev,t))||Ye(s,t)&&it(s.prev,s,s.next)>0&&it(t.prev,t,t.next)>0)}function it(s,t,e){return(t.y-s.y)*(e.x-t.x)-(t.x-s.x)*(e.y-t.y)}function Ye(s,t){return s.x===t.x&&s.y===t.y}function lh(s,t,e,r){const n=vr(it(s,t,e)),a=vr(it(s,t,r)),l=vr(it(e,r,s)),h=vr(it(e,r,t));return!!(n!==a&&l!==h||n===0&&br(s,e,t)||a===0&&br(s,r,t)||l===0&&br(e,s,r)||h===0&&br(e,t,r))}function br(s,t,e){return t.x<=Math.max(s.x,e.x)&&t.x>=Math.min(s.x,e.x)&&t.y<=Math.max(s.y,e.y)&&t.y>=Math.min(s.y,e.y)}function vr(s){return s>0?1:s<0?-1:0}function om(s,t){let e=s;do{if(e.i!==s.i&&e.next.i!==s.i&&e.i!==t.i&&e.next.i!==t.i&&lh(e,e.next,s,t))return!0;e=e.next}while(e!==s);return!1}function wi(s,t){return it(s.prev,s,s.next)<0?it(s,t,s.next)>=0&&it(s,s.prev,t)>=0:it(s,t,s.prev)<0||it(s,s.next,t)<0}function hm(s,t){let e=s,r=!1;const n=(s.x+t.x)/2,a=(s.y+t.y)/2;do e.y>a!=e.next.y>a&&e.next.y!==e.y&&n<(e.next.x-e.x)*(a-e.y)/(e.next.y-e.y)+e.x&&(r=!r),e=e.next;while(e!==s);return r}function ch(s,t){const e=Zs(s.i,s.x,s.y),r=Zs(t.i,t.x,t.y),n=s.next,a=t.prev;return s.next=t,t.prev=s,e.next=n,n.prev=e,r.next=e,e.prev=r,a.next=r,r.prev=a,r}function uh(s,t,e,r){const n=Zs(s,t,e);return r?(n.next=r.next,n.prev=r,r.next.prev=n,r.next=n):(n.prev=n,n.next=n),n}function Si(s){s.next.prev=s.prev,s.prev.next=s.next,s.prevZ&&(s.prevZ.nextZ=s.nextZ),s.nextZ&&(s.nextZ.prevZ=s.prevZ)}function Zs(s,t,e){return{i:s,x:t,y:e,prev:null,next:null,z:0,prevZ:null,nextZ:null,steiner:!1}}function lm(s,t,e,r){let n=0;for(let a=t,l=e-r;a<e;a+=r)n+=(s[l]-s[a])*(s[a+1]+s[l+1]),l=a;return n}const cm=ah.default||ah;var At=(s=>(s[s.NONE=0]="NONE",s[s.COLOR=16384]="COLOR",s[s.STENCIL=1024]="STENCIL",s[s.DEPTH=256]="DEPTH",s[s.COLOR_DEPTH=16640]="COLOR_DEPTH",s[s.COLOR_STENCIL=17408]="COLOR_STENCIL",s[s.DEPTH_STENCIL=1280]="DEPTH_STENCIL",s[s.ALL=17664]="ALL",s))(At||{});class dh{constructor(t){this.items=[],this._name=t}emit(t,e,r,n,a,l,h,d){const{name:f,items:m}=this;for(let g=0,y=m.length;g<y;g++)m[g][f](t,e,r,n,a,l,h,d);return this}add(t){return t[this._name]&&(this.remove(t),this.items.push(t)),this}remove(t){const e=this.items.indexOf(t);return e!==-1&&this.items.splice(e,1),this}contains(t){return this.items.indexOf(t)!==-1}removeAll(){return this.items.length=0,this}destroy(){this.removeAll(),this.items=null,this._name=null}get empty(){return this.items.length===0}get name(){return this._name}}const um=["init","destroy","contextChange","resolutionChange","resetState","renderEnd","renderStart","render","update","postrender","prerender"],fh=class Zu extends Tt{constructor(t){super(),this.uid=et("renderer"),this.runners=Object.create(null),this.renderPipes=Object.create(null),this._initOptions={},this._systemsHash=Object.create(null),this.type=t.type,this.name=t.name,this.config=t;const e=[...um,...this.config.runners??[]];this._addRunners(...e),this._unsafeEvalCheck()}async init(t={}){const e=t.skipExtensionImports===!0?!0:t.manageImports===!1;await $p(e),this._addSystems(this.config.systems),this._addPipes(this.config.renderPipes,this.config.renderPipeAdaptors);for(const r in this._systemsHash)t={...this._systemsHash[r].constructor.defaultOptions,...t};t={...Zu.defaultOptions,...t},this._roundPixels=t.roundPixels?1:0;for(let r=0;r<this.runners.init.items.length;r++)await this.runners.init.items[r].init(t);this._initOptions=t}render(t,e){let r=t;if(r instanceof ot&&(r={container:r},e&&(z($,"passing a second argument is deprecated, please use render options instead"),r.target=e.renderTexture)),r.target||(r.target=this.view.renderTarget),r.target===this.view.renderTarget&&(this._lastObjectRendered=r.container,r.clearColor??(r.clearColor=this.background.colorRgba),r.clear??(r.clear=this.background.clearBeforeRender)),r.clearColor){const n=Array.isArray(r.clearColor)&&r.clearColor.length===4;r.clearColor=n?r.clearColor:J.shared.setValue(r.clearColor).toArray()}r.transform||(r.container.updateLocalTransform(),r.transform=r.container.localTransform),r.container.visible&&(r.container.enableRenderGroup(),this.runners.prerender.emit(r),this.runners.renderStart.emit(r),this.runners.render.emit(r),this.runners.renderEnd.emit(r),this.runners.postrender.emit(r))}resize(t,e,r){const n=this.view.resolution;this.view.resize(t,e,r),this.emit("resize",this.view.screen.width,this.view.screen.height,this.view.resolution),r!==void 0&&r!==n&&this.runners.resolutionChange.emit(r)}clear(t={}){const e=this;t.target||(t.target=e.renderTarget.renderTarget),t.clearColor||(t.clearColor=this.background.colorRgba),t.clear??(t.clear=At.ALL);const{clear:r,clearColor:n,target:a}=t;J.shared.setValue(n??this.background.colorRgba),e.renderTarget.clear(a,r,J.shared.toArray())}get resolution(){return this.view.resolution}set resolution(t){this.view.resolution=t,this.runners.resolutionChange.emit(t)}get width(){return this.view.texture.frame.width}get height(){return this.view.texture.frame.height}get canvas(){return this.view.canvas}get lastObjectRendered(){return this._lastObjectRendered}get renderingToScreen(){return this.renderTarget.renderingToScreen}get screen(){return this.view.screen}_addRunners(...t){t.forEach(e=>{this.runners[e]=new dh(e)})}_addSystems(t){let e;for(e in t){const r=t[e];this._addSystem(r.value,r.name)}}_addSystem(t,e){const r=new t(this);if(this[e])throw new Error(`Whoops! The name "${e}" is already in use`);this[e]=r,this._systemsHash[e]=r;for(const n in this.runners)this.runners[n].add(r);return this}_addPipes(t,e){const r=e.reduce((n,a)=>(n[a.name]=a.value,n),{});t.forEach(n=>{const a=n.value,l=n.name,h=r[l];this.renderPipes[l]=new a(this,h?new h:null),this.runners.destroy.add(this.renderPipes[l])})}destroy(t=!1){this.runners.destroy.items.reverse(),this.runners.destroy.emit(t),(t===!0||typeof t=="object"&&t.releaseGlobalResources)&&Ne.release(),Object.values(this.runners).forEach(e=>{e.destroy()}),this._systemsHash=null,this.renderPipes=null}generateTexture(t){return this.textureGenerator.generateTexture(t)}get roundPixels(){return!!this._roundPixels}_unsafeEvalCheck(){if(!nh())throw new Error("Current environment does not allow unsafe-eval, please use pixi.js/unsafe-eval module to enable support.")}resetState(){this.runners.resetState.emit()}};fh.defaultOptions={resolution:1,failIfMajorPerformanceCaveat:!1,roundPixels:!1};let wr=fh,Sr;function dm(s){return Sr!==void 0||(Sr=(()=>{const t={stencil:!0,failIfMajorPerformanceCaveat:s??wr.defaultOptions.failIfMajorPerformanceCaveat};try{if(!W.get().getWebGLRenderingContext())return!1;let r=W.get().createCanvas().getContext("webgl",t);const n=!!r?.getContextAttributes()?.stencil;if(r){const a=r.getExtension("WEBGL_lose_context");a&&a.loseContext()}return r=null,n}catch{return!1}})()),Sr}let Tr;async function fm(s={}){return Tr!==void 0||(Tr=await(async()=>{const t=W.get().getNavigator().gpu;if(!t)return!1;try{return await(await t.requestAdapter(s)).requestDevice(),!0}catch{return!1}})()),Tr}const ph=["webgl","webgpu","canvas"];async function pm(s){let t=[];s.preference?(t.push(s.preference),ph.forEach(a=>{a!==s.preference&&t.push(a)})):t=ph.slice();let e,r={};for(let a=0;a<t.length;a++){const l=t[a];if(l==="webgpu"&&await fm()){const{WebGPURenderer:h}=await Promise.resolve().then(()=>ib);e=h,r={...s,...s.webgpu};break}else if(l==="webgl"&&dm(s.failIfMajorPerformanceCaveat??wr.defaultOptions.failIfMajorPerformanceCaveat)){const{WebGLRenderer:h}=await Promise.resolve().then(()=>Gx);e=h,r={...s,...s.webgl};break}else if(l==="canvas")throw r={...s},new Error("CanvasRenderer is not yet implemented")}if(delete r.webgpu,delete r.webgl,!e)throw new Error("No available renderer for the current environment");const n=new e;return await n.init(r),n}const Cr="8.14.3";class mh{static init(){globalThis.__PIXI_APP_INIT__?.(this,Cr)}static destroy(){}}mh.extension=C.Application;class gh{constructor(t){this._renderer=t}init(){globalThis.__PIXI_RENDERER_INIT__?.(this._renderer,Cr)}destroy(){this._renderer=null}}gh.extension={type:[C.WebGLSystem,C.WebGPUSystem],name:"initHook",priority:-10};const _h=class ga{constructor(...t){this.stage=new ot,t[0]!==void 0&&z($,"Application constructor options are deprecated, please use Application.init() instead.")}async init(t){t={...t},this.stage||(this.stage=new ot),this.renderer=await pm(t),ga._plugins.forEach(e=>{e.init.call(this,t)})}render(){this.renderer.render({container:this.stage})}get canvas(){return this.renderer.canvas}get view(){return z($,"Application.view is deprecated, please use Application.canvas instead."),this.renderer.canvas}get screen(){return this.renderer.screen}destroy(t=!1,e=!1){const r=ga._plugins.slice(0);r.reverse(),r.forEach(n=>{n.destroy.call(this)}),this.stage.destroy(e),this.stage=null,this.renderer.destroy(t),this.renderer=null}};_h._plugins=[];let Qs=_h;D.handleByList(C.Application,Qs._plugins),D.add(mh);class yh{static init(t){Object.defineProperty(this,"resizeTo",{configurable:!0,set(e){globalThis.removeEventListener("resize",this.queueResize),this._resizeTo=e,e&&(globalThis.addEventListener("resize",this.queueResize),this.resize())},get(){return this._resizeTo}}),this.queueResize=()=>{this._resizeTo&&(this._cancelResize(),this._resizeId=requestAnimationFrame(()=>this.resize()))},this._cancelResize=()=>{this._resizeId&&(cancelAnimationFrame(this._resizeId),this._resizeId=null)},this.resize=()=>{if(!this._resizeTo)return;this._cancelResize();let e,r;if(this._resizeTo===globalThis.window)e=globalThis.innerWidth,r=globalThis.innerHeight;else{const{clientWidth:n,clientHeight:a}=this._resizeTo;e=n,r=a}this.renderer.resize(e,r),this.render()},this._resizeId=null,this._resizeTo=null,this.resizeTo=t.resizeTo||null}static destroy(){globalThis.removeEventListener("resize",this.queueResize),this._cancelResize(),this._cancelResize=null,this.queueResize=null,this.resizeTo=null,this.resize=null}}yh.extension=C.Application;class xh{static init(t){t=Object.assign({autoStart:!0,sharedTicker:!1},t),Object.defineProperty(this,"ticker",{configurable:!0,set(e){this._ticker&&this._ticker.remove(this.render,this),this._ticker=e,e&&e.add(this.render,this,He.LOW)},get(){return this._ticker}}),this.stop=()=>{this._ticker.stop()},this.start=()=>{this._ticker.start()},this._ticker=null,this.ticker=t.sharedTicker?Ct.shared:new Ct,t.autoStart&&this.start()}static destroy(){if(this._ticker){const t=this._ticker;this.ticker=null,t.destroy()}}}xh.extension=C.Application;class bh extends Tt{constructor(){super(...arguments),this.chars=Object.create(null),this.lineHeight=0,this.fontFamily="",this.fontMetrics={fontSize:0,ascent:0,descent:0},this.baseLineOffset=0,this.distanceField={type:"none",range:0},this.pages=[],this.applyFillAsTint=!0,this.baseMeasurementFontSize=100,this.baseRenderedFontSize=100}get font(){return z($,"BitmapFont.font is deprecated, please use BitmapFont.fontFamily instead."),this.fontFamily}get pageTextures(){return z($,"BitmapFont.pageTextures is deprecated, please use BitmapFont.pages instead."),this.pages}get size(){return z($,"BitmapFont.size is deprecated, please use BitmapFont.fontMetrics.fontSize instead."),this.fontMetrics.fontSize}get distanceFieldRange(){return z($,"BitmapFont.distanceFieldRange is deprecated, please use BitmapFont.distanceField.range instead."),this.distanceField.range}get distanceFieldType(){return z($,"BitmapFont.distanceFieldType is deprecated, please use BitmapFont.distanceField.type instead."),this.distanceField.type}destroy(t=!1){this.emit("destroy",this),this.removeAllListeners();for(const e in this.chars)this.chars[e].texture?.destroy();this.chars=null,t&&(this.pages.forEach(e=>e.texture.destroy(!0)),this.pages=null)}}class mm{constructor(t=0,e=0,r=!1){this.first=null,this.items=Object.create(null),this.last=null,this.max=t,this.resetTtl=r,this.size=0,this.ttl=e}clear(){return this.first=null,this.items=Object.create(null),this.last=null,this.size=0,this}delete(t){if(this.has(t)){const e=this.items[t];delete this.items[t],this.size--,e.prev!==null&&(e.prev.next=e.next),e.next!==null&&(e.next.prev=e.prev),this.first===e&&(this.first=e.next),this.last===e&&(this.last=e.prev)}return this}entries(t=this.keys()){return t.map(e=>[e,this.get(e)])}evict(t=!1){if(t||this.size>0){const e=this.first;delete this.items[e.key],--this.size===0?(this.first=null,this.last=null):(this.first=e.next,this.first.prev=null)}return this}expiresAt(t){let e;return this.has(t)&&(e=this.items[t].expiry),e}get(t){const e=this.items[t];if(e!==void 0){if(this.ttl>0&&e.expiry<=Date.now()){this.delete(t);return}return this.moveToEnd(e),e.value}}has(t){return t in this.items}moveToEnd(t){this.last!==t&&(t.prev!==null&&(t.prev.next=t.next),t.next!==null&&(t.next.prev=t.prev),this.first===t&&(this.first=t.next),t.prev=this.last,t.next=null,this.last!==null&&(this.last.next=t),this.last=t,this.first===null&&(this.first=t))}keys(){const t=[];let e=this.first;for(;e!==null;)t.push(e.key),e=e.next;return t}setWithEvicted(t,e,r=this.resetTtl){let n=null;if(this.has(t))this.set(t,e,!0,r);else{this.max>0&&this.size===this.max&&(n={...this.first},this.evict(!0));let a=this.items[t]={expiry:this.ttl>0?Date.now()+this.ttl:this.ttl,key:t,prev:this.last,next:null,value:e};++this.size===1?this.first=a:this.last.next=a,this.last=a}return n}set(t,e,r=!1,n=this.resetTtl){let a=this.items[t];return r||a!==void 0?(a.value=e,r===!1&&n&&(a.expiry=this.ttl>0?Date.now()+this.ttl:this.ttl),this.moveToEnd(a)):(this.max>0&&this.size===this.max&&this.evict(!0),a=this.items[t]={expiry:this.ttl>0?Date.now()+this.ttl:this.ttl,key:t,prev:this.last,next:null,value:e},++this.size===1?this.first=a:this.last.next=a,this.last=a),this}values(t=this.keys()){return t.map(e=>this.get(e))}}function vh(s=1e3,t=0,e=!1){if(isNaN(s)||s<0)throw new TypeError("Invalid max value");if(isNaN(t)||t<0)throw new TypeError("Invalid ttl value");if(typeof e!="boolean")throw new TypeError("Invalid resetTtl value");return new mm(s,t,e)}const gm=["serif","sans-serif","monospace","cursive","fantasy","system-ui"];function Er(s){const t=typeof s.fontSize=="number"?`${s.fontSize}px`:s.fontSize;let e=s.fontFamily;Array.isArray(s.fontFamily)||(e=s.fontFamily.split(","));for(let r=e.length-1;r>=0;r--){let n=e[r].trim();!/([\"\'])[^\'\"]+\1/.test(n)&&!gm.includes(n)&&(n=`"${n}"`),e[r]=n}return`${s.fontStyle} ${s.fontVariant} ${s.fontWeight} ${t} ${e.join(",")}`}const Js={willReadFrequently:!0},Wt=class I{static get experimentalLetterSpacingSupported(){let t=I._experimentalLetterSpacingSupported;if(t===void 0){const e=W.get().getCanvasRenderingContext2D().prototype;t=I._experimentalLetterSpacingSupported="letterSpacing"in e||"textLetterSpacing"in e}return t}constructor(t,e,r,n,a,l,h,d,f){this.text=t,this.style=e,this.width=r,this.height=n,this.lines=a,this.lineWidths=l,this.lineHeight=h,this.maxLineWidth=d,this.fontProperties=f}static measureText(t=" ",e,r=I._canvas,n=e.wordWrap){const a=`${t}-${e.styleKey}-wordWrap-${n}`;if(I._measurementCache.has(a))return I._measurementCache.get(a);const l=Er(e),h=I.measureFont(l);h.fontSize===0&&(h.fontSize=e.fontSize,h.ascent=e.fontSize);const d=I.__context;d.font=l;const m=(n?I._wordWrap(t,e,r):t).split(/(?:\r\n|\r|\n)/),g=new Array(m.length);let y=0;for(let _=0;_<m.length;_++){const b=I._measureText(m[_],e.letterSpacing,d);g[_]=b,y=Math.max(y,b)}const x=e._stroke?.width||0;let o=y+x;e.dropShadow&&(o+=e.dropShadow.distance);const c=e.lineHeight||h.fontSize;let u=Math.max(c,h.fontSize+x)+(m.length-1)*(c+e.leading);e.dropShadow&&(u+=e.dropShadow.distance);const p=new I(t,e,o,u,m,g,c+e.leading,y,h);return I._measurementCache.set(a,p),p}static _measureText(t,e,r){let n=!1;I.experimentalLetterSpacingSupported&&(I.experimentalLetterSpacing?(r.letterSpacing=`${e}px`,r.textLetterSpacing=`${e}px`,n=!0):(r.letterSpacing="0px",r.textLetterSpacing="0px"));const a=r.measureText(t);let l=a.width;const h=-a.actualBoundingBoxLeft;let f=a.actualBoundingBoxRight-h;if(l>0)if(n)l-=e,f-=e;else{const m=(I.graphemeSegmenter(t).length-1)*e;l+=m,f+=m}return Math.max(l,f)}static _wordWrap(t,e,r=I._canvas){const n=r.getContext("2d",Js);let a=0,l="",h="";const d=Object.create(null),{letterSpacing:f,whiteSpace:m}=e,g=I._collapseSpaces(m),y=I._collapseNewlines(m);let x=!g;const o=e.wordWrapWidth+f,c=I._tokenize(t);for(let u=0;u<c.length;u++){let p=c[u];if(I._isNewline(p)){if(!y){h+=I._addLine(l),x=!g,l="",a=0;continue}p=" "}if(g){const b=I.isBreakingSpace(p),v=I.isBreakingSpace(l[l.length-1]);if(b&&v)continue}const _=I._getFromCache(p,f,d,n);if(_>o)if(l!==""&&(h+=I._addLine(l),l="",a=0),I.canBreakWords(p,e.breakWords)){const b=I.wordWrapSplit(p);for(let v=0;v<b.length;v++){let w=b[v],S=w,T=1;for(;b[v+T];){const P=b[v+T];if(!I.canBreakChars(S,P,p,v,e.breakWords))w+=P;else break;S=P,T++}v+=T-1;const E=I._getFromCache(w,f,d,n);E+a>o&&(h+=I._addLine(l),x=!1,l="",a=0),l+=w,a+=E}}else{l.length>0&&(h+=I._addLine(l),l="",a=0);const b=u===c.length-1;h+=I._addLine(p,!b),x=!1,l="",a=0}else _+a>o&&(x=!1,h+=I._addLine(l),l="",a=0),(l.length>0||!I.isBreakingSpace(p)||x)&&(l+=p,a+=_)}return h+=I._addLine(l,!1),h}static _addLine(t,e=!0){return t=I._trimRight(t),t=e?`${t}
|
|
99
|
-
`:t,t}static _getFromCache(t,e,r,n){let
|
|
95
|
+
`}function Hp(s,t,e){const r=e?t.maxSupportedFragmentPrecision:t.maxSupportedVertexPrecision;if(s.substring(0,9)!=="precision"){let n=e?t.requestedFragmentPrecision:t.requestedVertexPrecision;return n==="highp"&&r!=="highp"&&(n="mediump"),`precision ${n} float;
|
|
96
|
+
${s}`}else if(r!=="highp"&&s.substring(0,15)==="precision highp")return s.replace("precision highp","precision mediump");return s}function Wp(s,t){return t?`#version 300 es
|
|
97
|
+
${s}`:s}const Vp={},Yp={};function Xp(s,{name:t="pixi-program"},e=!0){t=t.replace(/\s+/g,"-"),t+=e?"-fragment":"-vertex";const r=e?Vp:Yp;return r[t]?(r[t]++,t+=`-${r[t]}`):r[t]=1,s.indexOf("#define SHADER_NAME")!==-1?s:`${`#define SHADER_NAME ${t}`}
|
|
98
|
+
${s}`}function $p(s,t){return t?s.replace("#version 300 es",""):s}const Ws={stripVersion:$p,ensurePrecision:Hp,addProgramDefines:Np,setProgramName:Xp,insertVersion:Wp},_i=Object.create(null),rh=class yo{constructor(t){t={...yo.defaultOptions,...t};const e=t.fragment.indexOf("#version 300 es")!==-1,r={stripVersion:e,ensurePrecision:{requestedFragmentPrecision:t.preferredFragmentPrecision,requestedVertexPrecision:t.preferredVertexPrecision,maxSupportedVertexPrecision:"highp",maxSupportedFragmentPrecision:zp()},setProgramName:{name:t.name},addProgramDefines:e,insertVersion:e};let n=t.fragment,o=t.vertex;Object.keys(Ws).forEach(l=>{const h=r[l];n=Ws[l](n,h,!0),o=Ws[l](o,h,!1)}),this.fragment=n,this.vertex=o,this.transformFeedbackVaryings=t.transformFeedbackVaryings,this._key=gi(`${this.vertex}:${this.fragment}`,"gl-program")}destroy(){this.fragment=null,this.vertex=null,this._attributeData=null,this._uniformData=null,this._uniformBlockData=null,this.transformFeedbackVaryings=null,_i[this._cacheKey]=null}static from(t){const e=`${t.vertex}:${t.fragment}`;return _i[e]||(_i[e]=new yo(t),_i[e]._cacheKey=e),_i[e]}};rh.defaultOptions={preferredVertexPrecision:"highp",preferredFragmentPrecision:"mediump"};let Te=rh;const sh={uint8x2:{size:2,stride:2,normalised:!1},uint8x4:{size:4,stride:4,normalised:!1},sint8x2:{size:2,stride:2,normalised:!1},sint8x4:{size:4,stride:4,normalised:!1},unorm8x2:{size:2,stride:2,normalised:!0},unorm8x4:{size:4,stride:4,normalised:!0},snorm8x2:{size:2,stride:2,normalised:!0},snorm8x4:{size:4,stride:4,normalised:!0},uint16x2:{size:2,stride:4,normalised:!1},uint16x4:{size:4,stride:8,normalised:!1},sint16x2:{size:2,stride:4,normalised:!1},sint16x4:{size:4,stride:8,normalised:!1},unorm16x2:{size:2,stride:4,normalised:!0},unorm16x4:{size:4,stride:8,normalised:!0},snorm16x2:{size:2,stride:4,normalised:!0},snorm16x4:{size:4,stride:8,normalised:!0},float16x2:{size:2,stride:4,normalised:!1},float16x4:{size:4,stride:8,normalised:!1},float32:{size:1,stride:4,normalised:!1},float32x2:{size:2,stride:8,normalised:!1},float32x3:{size:3,stride:12,normalised:!1},float32x4:{size:4,stride:16,normalised:!1},uint32:{size:1,stride:4,normalised:!1},uint32x2:{size:2,stride:8,normalised:!1},uint32x3:{size:3,stride:12,normalised:!1},uint32x4:{size:4,stride:16,normalised:!1},sint32:{size:1,stride:4,normalised:!1},sint32x2:{size:2,stride:8,normalised:!1},sint32x3:{size:3,stride:12,normalised:!1},sint32x4:{size:4,stride:16,normalised:!1}};function fe(s){return sh[s]??sh.float32}const Kp={f32:"float32","vec2<f32>":"float32x2","vec3<f32>":"float32x3","vec4<f32>":"float32x4",vec2f:"float32x2",vec3f:"float32x3",vec4f:"float32x4",i32:"sint32","vec2<i32>":"sint32x2","vec3<i32>":"sint32x3","vec4<i32>":"sint32x4",u32:"uint32","vec2<u32>":"uint32x2","vec3<u32>":"uint32x3","vec4<u32>":"uint32x4",bool:"uint32","vec2<bool>":"uint32x2","vec3<bool>":"uint32x3","vec4<bool>":"uint32x4"};function jp({source:s,entryPoint:t}){const e={},r=s.indexOf(`fn ${t}`);if(r!==-1){const n=s.indexOf("->",r);if(n!==-1){const o=s.substring(r,n),l=/@location\((\d+)\)\s+([a-zA-Z0-9_]+)\s*:\s*([a-zA-Z0-9_<>]+)(?:,|\s|$)/g;let h;for(;(h=l.exec(o))!==null;){const u=Kp[h[3]]??"float32";e[h[2]]={location:parseInt(h[1],10),format:u,stride:fe(u).stride,offset:0,instance:!1,start:0}}}}return e}function Vs(s){const t=/(^|[^/])@(group|binding)\(\d+\)[^;]+;/g,e=/@group\((\d+)\)/,r=/@binding\((\d+)\)/,n=/var(<[^>]+>)? (\w+)/,o=/:\s*(\w+)/,l=/struct\s+(\w+)\s*{([^}]+)}/g,h=/(\w+)\s*:\s*([\w\<\>]+)/g,u=/struct\s+(\w+)/,f=s.match(t)?.map(g=>({group:parseInt(g.match(e)[1],10),binding:parseInt(g.match(r)[1],10),name:g.match(n)[2],isUniform:g.match(n)[1]==="<uniform>",type:g.match(o)[1]}));if(!f)return{groups:[],structs:[]};const m=s.match(l)?.map(g=>{const y=g.match(u)[1],x=g.match(h).reduce((a,c)=>{const[d,p]=c.split(":");return a[d.trim()]=p.trim(),a},{});return x?{name:y,members:x}:null}).filter(({name:g})=>f.some(y=>y.type===g))??[];return{groups:f,structs:m}}var yi=(s=>(s[s.VERTEX=1]="VERTEX",s[s.FRAGMENT=2]="FRAGMENT",s[s.COMPUTE=4]="COMPUTE",s))(yi||{});function qp({groups:s}){const t=[];for(let e=0;e<s.length;e++){const r=s[e];t[r.group]||(t[r.group]=[]),r.isUniform?t[r.group].push({binding:r.binding,visibility:yi.VERTEX|yi.FRAGMENT,buffer:{type:"uniform"}}):r.type==="sampler"?t[r.group].push({binding:r.binding,visibility:yi.FRAGMENT,sampler:{type:"filtering"}}):r.type==="texture_2d"&&t[r.group].push({binding:r.binding,visibility:yi.FRAGMENT,texture:{sampleType:"float",viewDimension:"2d",multisampled:!1}})}return t}function Zp({groups:s}){const t=[];for(let e=0;e<s.length;e++){const r=s[e];t[r.group]||(t[r.group]={}),t[r.group][r.name]=r.binding}return t}function Qp(s,t){const e=new Set,r=new Set,n=[...s.structs,...t.structs].filter(l=>e.has(l.name)?!1:(e.add(l.name),!0)),o=[...s.groups,...t.groups].filter(l=>{const h=`${l.name}-${l.binding}`;return r.has(h)?!1:(r.add(h),!0)});return{structs:n,groups:o}}const xi=Object.create(null);class pe{constructor(t){this._layoutKey=0,this._attributeLocationsKey=0;const{fragment:e,vertex:r,layout:n,gpuLayout:o,name:l}=t;if(this.name=l,this.fragment=e,this.vertex=r,e.source===r.source){const h=Vs(e.source);this.structsAndGroups=h}else{const h=Vs(r.source),u=Vs(e.source);this.structsAndGroups=Qp(h,u)}this.layout=n??Zp(this.structsAndGroups),this.gpuLayout=o??qp(this.structsAndGroups),this.autoAssignGlobalUniforms=this.layout[0]?.globalUniforms!==void 0,this.autoAssignLocalUniforms=this.layout[1]?.localUniforms!==void 0,this._generateProgramKey()}_generateProgramKey(){const{vertex:t,fragment:e}=this,r=t.source+e.source+t.entryPoint+e.entryPoint;this._layoutKey=gi(r,"program")}get attributeData(){return this._attributeData??(this._attributeData=jp(this.vertex)),this._attributeData}destroy(){this.gpuLayout=null,this.layout=null,this.structsAndGroups=null,this.fragment=null,this.vertex=null,xi[this._cacheKey]=null}static from(t){const e=`${t.vertex.source}:${t.fragment.source}:${t.fragment.entryPoint}:${t.vertex.entryPoint}`;return xi[e]||(xi[e]=new pe(t),xi[e]._cacheKey=e),xi[e]}}const nh=["f32","i32","vec2<f32>","vec3<f32>","vec4<f32>","mat2x2<f32>","mat3x3<f32>","mat4x4<f32>","mat3x2<f32>","mat4x2<f32>","mat2x3<f32>","mat4x3<f32>","mat2x4<f32>","mat3x4<f32>","vec2<i32>","vec3<i32>","vec4<i32>"],Jp=nh.reduce((s,t)=>(s[t]=!0,s),{});function tm(s,t){switch(s){case"f32":return 0;case"vec2<f32>":return new Float32Array(2*t);case"vec3<f32>":return new Float32Array(3*t);case"vec4<f32>":return new Float32Array(4*t);case"mat2x2<f32>":return new Float32Array([1,0,0,1]);case"mat3x3<f32>":return new Float32Array([1,0,0,0,1,0,0,0,1]);case"mat4x4<f32>":return new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1])}return null}const oh=class Jd{constructor(t,e){this._touched=0,this.uid=et("uniform"),this._resourceType="uniformGroup",this._resourceId=et("resource"),this.isUniformGroup=!0,this._dirtyId=0,this.destroyed=!1,e={...Jd.defaultOptions,...e},this.uniformStructures=t;const r={};for(const n in t){const o=t[n];if(o.name=n,o.size=o.size??1,!Jp[o.type]){const l=o.type.match(/^array<(\w+(?:<\w+>)?),\s*(\d+)>$/);if(l){const[,h,u]=l;throw new Error(`Uniform type ${o.type} is not supported. Use type: '${h}', size: ${u} instead.`)}throw new Error(`Uniform type ${o.type} is not supported. Supported uniform types are: ${nh.join(", ")}`)}o.value??(o.value=tm(o.type,o.size)),r[n]=o.value}this.uniforms=r,this._dirtyId=1,this.ubo=e.ubo,this.isStatic=e.isStatic,this._signature=gi(Object.keys(r).map(n=>`${n}-${t[n].type}`).join("-"),"uniform-group")}update(){this._dirtyId++}};oh.defaultOptions={ubo:!1,isStatic:!1};let _t=oh;class ne{constructor(t){this.resources=Object.create(null),this._dirty=!0;let e=0;for(const r in t){const n=t[r];this.setResource(n,e++)}this._updateKey()}_updateKey(){if(!this._dirty)return;this._dirty=!1;const t=[];let e=0;for(const r in this.resources)t[e++]=this.resources[r]._resourceId;this._key=t.join("|")}setResource(t,e){const r=this.resources[e];t!==r&&(r&&t.off?.("change",this.onResourceChange,this),t.on?.("change",this.onResourceChange,this),this.resources[e]=t,this._dirty=!0)}getResource(t){return this.resources[t]}_touch(t){const e=this.resources;for(const r in e)e[r]._touched=t}destroy(){const t=this.resources;for(const e in t)t[e]?.off?.("change",this.onResourceChange,this);this.resources=null}onResourceChange(t){if(this._dirty=!0,t.destroyed){const e=this.resources;for(const r in e)e[r]===t&&(e[r]=null)}else this._updateKey()}}var Nt=(s=>(s[s.WEBGL=1]="WEBGL",s[s.WEBGPU=2]="WEBGPU",s[s.BOTH=3]="BOTH",s))(Nt||{});class Ft extends Ct{constructor(t){super(),this.uid=et("shader"),this._uniformBindMap=Object.create(null),this._ownedBindGroups=[],this._destroyed=!1;let{gpuProgram:e,glProgram:r,groups:n,resources:o,compatibleRenderers:l,groupMap:h}=t;this.gpuProgram=e,this.glProgram=r,l===void 0&&(l=0,e&&(l|=Nt.WEBGPU),r&&(l|=Nt.WEBGL)),this.compatibleRenderers=l;const u={};if(!o&&!n&&(o={}),o&&n)throw new Error("[Shader] Cannot have both resources and groups");if(!e&&n&&!h)throw new Error("[Shader] No group map or WebGPU shader provided - consider using resources instead.");if(!e&&n&&h)for(const f in h)for(const m in h[f]){const g=h[f][m];u[g]={group:f,binding:m,name:g}}else if(e&&n&&!h){const f=e.structsAndGroups.groups;h={},f.forEach(m=>{h[m.group]=h[m.group]||{},h[m.group][m.binding]=m.name,u[m.name]=m})}else if(o){n={},h={},e&&e.structsAndGroups.groups.forEach(g=>{h[g.group]=h[g.group]||{},h[g.group][g.binding]=g.name,u[g.name]=g});let f=0;for(const m in o)u[m]||(n[99]||(n[99]=new ne,this._ownedBindGroups.push(n[99])),u[m]={group:99,binding:f,name:m},h[99]=h[99]||{},h[99][f]=m,f++);for(const m in o){const g=m;let y=o[m];!y.source&&!y._resourceType&&(y=new _t(y));const x=u[g];x&&(n[x.group]||(n[x.group]=new ne,this._ownedBindGroups.push(n[x.group])),n[x.group].setResource(y,x.binding))}}this.groups=n,this._uniformBindMap=h,this.resources=this._buildResourceAccessor(n,u)}addResource(t,e,r){var n,o;(n=this._uniformBindMap)[e]||(n[e]={}),(o=this._uniformBindMap[e])[r]||(o[r]=t),this.groups[e]||(this.groups[e]=new ne,this._ownedBindGroups.push(this.groups[e]))}_buildResourceAccessor(t,e){const r={};for(const n in e){const o=e[n];Object.defineProperty(r,o.name,{get(){return t[o.group].getResource(o.binding)},set(l){t[o.group].setResource(l,o.binding)}})}return r}destroy(t=!1){this._destroyed||(this._destroyed=!0,this.emit("destroy",this),t&&(this.gpuProgram?.destroy(),this.glProgram?.destroy()),this.gpuProgram=null,this.glProgram=null,this.removeAllListeners(),this._uniformBindMap=null,this._ownedBindGroups.forEach(e=>{e.destroy()}),this._ownedBindGroups=null,this.resources=null,this.groups=null)}static from(t){const{gpu:e,gl:r,...n}=t;let o,l;return e&&(o=pe.from(e)),r&&(l=Te.from(r)),new Ft({gpuProgram:o,glProgram:l,...n})}}const em={normal:0,add:1,multiply:2,screen:3,overlay:4,erase:5,"normal-npm":6,"add-npm":7,"screen-npm":8,min:9,max:10},Ys=0,Xs=1,$s=2,Ks=3,js=4,qs=5,Zs=class tu{constructor(){this.data=0,this.blendMode="normal",this.polygonOffset=0,this.blend=!0,this.depthMask=!0}get blend(){return!!(this.data&1<<Ys)}set blend(t){!!(this.data&1<<Ys)!==t&&(this.data^=1<<Ys)}get offsets(){return!!(this.data&1<<Xs)}set offsets(t){!!(this.data&1<<Xs)!==t&&(this.data^=1<<Xs)}set cullMode(t){if(t==="none"){this.culling=!1;return}this.culling=!0,this.clockwiseFrontFace=t==="front"}get cullMode(){return this.culling?this.clockwiseFrontFace?"front":"back":"none"}get culling(){return!!(this.data&1<<$s)}set culling(t){!!(this.data&1<<$s)!==t&&(this.data^=1<<$s)}get depthTest(){return!!(this.data&1<<Ks)}set depthTest(t){!!(this.data&1<<Ks)!==t&&(this.data^=1<<Ks)}get depthMask(){return!!(this.data&1<<qs)}set depthMask(t){!!(this.data&1<<qs)!==t&&(this.data^=1<<qs)}get clockwiseFrontFace(){return!!(this.data&1<<js)}set clockwiseFrontFace(t){!!(this.data&1<<js)!==t&&(this.data^=1<<js)}get blendMode(){return this._blendMode}set blendMode(t){this.blend=t!=="none",this._blendMode=t,this._blendModeId=em[t]||0}get polygonOffset(){return this._polygonOffset}set polygonOffset(t){this.offsets=!!t,this._polygonOffset=t}toString(){return`[pixi.js/core:State blendMode=${this.blendMode} clockwiseFrontFace=${this.clockwiseFrontFace} culling=${this.culling} depthMask=${this.depthMask} polygonOffset=${this.polygonOffset}]`}static for2d(){const t=new tu;return t.depthTest=!1,t.blend=!0,t}};Zs.default2d=Zs.for2d();let Ht=Zs;const ah=class xo extends Ft{constructor(t){t={...xo.defaultOptions,...t},super(t),this.enabled=!0,this._state=Ht.for2d(),this.blendMode=t.blendMode,this.padding=t.padding,typeof t.antialias=="boolean"?this.antialias=t.antialias?"on":"off":this.antialias=t.antialias,this.resolution=t.resolution,this.blendRequired=t.blendRequired,this.clipToViewport=t.clipToViewport,this.addResource("uTexture",0,1),t.blendRequired&&this.addResource("uBackTexture",0,3)}apply(t,e,r,n){t.applyFilter(this,e,r,n)}get blendMode(){return this._state.blendMode}set blendMode(t){this._state.blendMode=t}static from(t){const{gpu:e,gl:r,...n}=t;let o,l;return e&&(o=pe.from(e)),r&&(l=Te.from(r)),new xo({gpuProgram:o,glProgram:l,...n})}};ah.defaultOptions={blendMode:"normal",resolution:1,padding:0,antialias:"off",blendRequired:!1,clipToViewport:!0};let hh=ah;const Qs=[];D.handleByNamedList(C.Environment,Qs);async function im(s){if(!s)for(let t=0;t<Qs.length;t++){const e=Qs[t];if(e.value.test()){await e.value.load();return}}}let bi;function lh(){if(typeof bi=="boolean")return bi;try{bi=new Function("param1","param2","param3","return param1[param2] === param3;")({a:"b"},"a","b")===!0}catch{bi=!1}return bi}function ch(s,t,e=2){const r=t&&t.length,n=r?t[0]*e:s.length;let o=dh(s,0,n,e,!0);const l=[];if(!o||o.next===o.prev)return l;let h,u,f;if(r&&(o=am(s,t,o,e)),s.length>80*e){h=s[0],u=s[1];let m=h,g=u;for(let y=e;y<n;y+=e){const x=s[y],a=s[y+1];x<h&&(h=x),a<u&&(u=a),x>m&&(m=x),a>g&&(g=a)}f=Math.max(m-h,g-u),f=f!==0?32767/f:0}return vi(o,l,e,h,u,f,0),l}function dh(s,t,e,r,n){let o;if(n===ym(s,t,e,r)>0)for(let l=t;l<e;l+=r)o=mh(l/r|0,s[l],s[l+1],o);else for(let l=e-r;l>=t;l-=r)o=mh(l/r|0,s[l],s[l+1],o);return o&&Xe(o,o.next)&&(Ti(o),o=o.next),o}function Ce(s,t){if(!s)return s;t||(t=s);let e=s,r;do if(r=!1,!e.steiner&&(Xe(e,e.next)||it(e.prev,e,e.next)===0)){if(Ti(e),e=t=e.prev,e===e.next)break;r=!0}else e=e.next;while(r||e!==t);return t}function vi(s,t,e,r,n,o,l){if(!s)return;!l&&o&&um(s,r,n,o);let h=s;for(;s.prev!==s.next;){const u=s.prev,f=s.next;if(o?sm(s,r,n,o):rm(s)){t.push(u.i,s.i,f.i),Ti(s),s=f.next,h=f.next;continue}if(s=f,s===h){l?l===1?(s=nm(Ce(s),t),vi(s,t,e,r,n,o,2)):l===2&&om(s,t,e,r,n,o):vi(Ce(s),t,e,r,n,o,1);break}}}function rm(s){const t=s.prev,e=s,r=s.next;if(it(t,e,r)>=0)return!1;const n=t.x,o=e.x,l=r.x,h=t.y,u=e.y,f=r.y,m=Math.min(n,o,l),g=Math.min(h,u,f),y=Math.max(n,o,l),x=Math.max(h,u,f);let a=r.next;for(;a!==t;){if(a.x>=m&&a.x<=y&&a.y>=g&&a.y<=x&&wi(n,h,o,u,l,f,a.x,a.y)&&it(a.prev,a,a.next)>=0)return!1;a=a.next}return!0}function sm(s,t,e,r){const n=s.prev,o=s,l=s.next;if(it(n,o,l)>=0)return!1;const h=n.x,u=o.x,f=l.x,m=n.y,g=o.y,y=l.y,x=Math.min(h,u,f),a=Math.min(m,g,y),c=Math.max(h,u,f),d=Math.max(m,g,y),p=Js(x,a,t,e,r),_=Js(c,d,t,e,r);let b=s.prevZ,v=s.nextZ;for(;b&&b.z>=p&&v&&v.z<=_;){if(b.x>=x&&b.x<=c&&b.y>=a&&b.y<=d&&b!==n&&b!==l&&wi(h,m,u,g,f,y,b.x,b.y)&&it(b.prev,b,b.next)>=0||(b=b.prevZ,v.x>=x&&v.x<=c&&v.y>=a&&v.y<=d&&v!==n&&v!==l&&wi(h,m,u,g,f,y,v.x,v.y)&&it(v.prev,v,v.next)>=0))return!1;v=v.nextZ}for(;b&&b.z>=p;){if(b.x>=x&&b.x<=c&&b.y>=a&&b.y<=d&&b!==n&&b!==l&&wi(h,m,u,g,f,y,b.x,b.y)&&it(b.prev,b,b.next)>=0)return!1;b=b.prevZ}for(;v&&v.z<=_;){if(v.x>=x&&v.x<=c&&v.y>=a&&v.y<=d&&v!==n&&v!==l&&wi(h,m,u,g,f,y,v.x,v.y)&&it(v.prev,v,v.next)>=0)return!1;v=v.nextZ}return!0}function nm(s,t){let e=s;do{const r=e.prev,n=e.next.next;!Xe(r,n)&&fh(r,e,e.next,n)&&Si(r,n)&&Si(n,r)&&(t.push(r.i,e.i,n.i),Ti(e),Ti(e.next),e=s=n),e=e.next}while(e!==s);return Ce(e)}function om(s,t,e,r,n,o){let l=s;do{let h=l.next.next;for(;h!==l.prev;){if(l.i!==h.i&&mm(l,h)){let u=ph(l,h);l=Ce(l,l.next),u=Ce(u,u.next),vi(l,t,e,r,n,o,0),vi(u,t,e,r,n,o,0);return}h=h.next}l=l.next}while(l!==s)}function am(s,t,e,r){const n=[];for(let o=0,l=t.length;o<l;o++){const h=t[o]*r,u=o<l-1?t[o+1]*r:s.length,f=dh(s,h,u,r,!1);f===f.next&&(f.steiner=!0),n.push(pm(f))}n.sort(hm);for(let o=0;o<n.length;o++)e=lm(n[o],e);return e}function hm(s,t){let e=s.x-t.x;if(e===0&&(e=s.y-t.y,e===0)){const r=(s.next.y-s.y)/(s.next.x-s.x),n=(t.next.y-t.y)/(t.next.x-t.x);e=r-n}return e}function lm(s,t){const e=cm(s,t);if(!e)return t;const r=ph(e,s);return Ce(r,r.next),Ce(e,e.next)}function cm(s,t){let e=t;const r=s.x,n=s.y;let o=-1/0,l;if(Xe(s,e))return e;do{if(Xe(s,e.next))return e.next;if(n<=e.y&&n>=e.next.y&&e.next.y!==e.y){const g=e.x+(n-e.y)*(e.next.x-e.x)/(e.next.y-e.y);if(g<=r&&g>o&&(o=g,l=e.x<e.next.x?e:e.next,g===r))return l}e=e.next}while(e!==t);if(!l)return null;const h=l,u=l.x,f=l.y;let m=1/0;e=l;do{if(r>=e.x&&e.x>=u&&r!==e.x&&uh(n<f?r:o,n,u,f,n<f?o:r,n,e.x,e.y)){const g=Math.abs(n-e.y)/(r-e.x);Si(e,s)&&(g<m||g===m&&(e.x>l.x||e.x===l.x&&dm(l,e)))&&(l=e,m=g)}e=e.next}while(e!==h);return l}function dm(s,t){return it(s.prev,s,t.prev)<0&&it(t.next,s,s.next)<0}function um(s,t,e,r){let n=s;do n.z===0&&(n.z=Js(n.x,n.y,t,e,r)),n.prevZ=n.prev,n.nextZ=n.next,n=n.next;while(n!==s);n.prevZ.nextZ=null,n.prevZ=null,fm(n)}function fm(s){let t,e=1;do{let r=s,n;s=null;let o=null;for(t=0;r;){t++;let l=r,h=0;for(let f=0;f<e&&(h++,l=l.nextZ,!!l);f++);let u=e;for(;h>0||u>0&&l;)h!==0&&(u===0||!l||r.z<=l.z)?(n=r,r=r.nextZ,h--):(n=l,l=l.nextZ,u--),o?o.nextZ=n:s=n,n.prevZ=o,o=n;r=l}o.nextZ=null,e*=2}while(t>1);return s}function Js(s,t,e,r,n){return s=(s-e)*n|0,t=(t-r)*n|0,s=(s|s<<8)&16711935,s=(s|s<<4)&252645135,s=(s|s<<2)&858993459,s=(s|s<<1)&1431655765,t=(t|t<<8)&16711935,t=(t|t<<4)&252645135,t=(t|t<<2)&858993459,t=(t|t<<1)&1431655765,s|t<<1}function pm(s){let t=s,e=s;do(t.x<e.x||t.x===e.x&&t.y<e.y)&&(e=t),t=t.next;while(t!==s);return e}function uh(s,t,e,r,n,o,l,h){return(n-l)*(t-h)>=(s-l)*(o-h)&&(s-l)*(r-h)>=(e-l)*(t-h)&&(e-l)*(o-h)>=(n-l)*(r-h)}function wi(s,t,e,r,n,o,l,h){return!(s===l&&t===h)&&uh(s,t,e,r,n,o,l,h)}function mm(s,t){return s.next.i!==t.i&&s.prev.i!==t.i&&!gm(s,t)&&(Si(s,t)&&Si(t,s)&&_m(s,t)&&(it(s.prev,s,t.prev)||it(s,t.prev,t))||Xe(s,t)&&it(s.prev,s,s.next)>0&&it(t.prev,t,t.next)>0)}function it(s,t,e){return(t.y-s.y)*(e.x-t.x)-(t.x-s.x)*(e.y-t.y)}function Xe(s,t){return s.x===t.x&&s.y===t.y}function fh(s,t,e,r){const n=Sr(it(s,t,e)),o=Sr(it(s,t,r)),l=Sr(it(e,r,s)),h=Sr(it(e,r,t));return!!(n!==o&&l!==h||n===0&&wr(s,e,t)||o===0&&wr(s,r,t)||l===0&&wr(e,s,r)||h===0&&wr(e,t,r))}function wr(s,t,e){return t.x<=Math.max(s.x,e.x)&&t.x>=Math.min(s.x,e.x)&&t.y<=Math.max(s.y,e.y)&&t.y>=Math.min(s.y,e.y)}function Sr(s){return s>0?1:s<0?-1:0}function gm(s,t){let e=s;do{if(e.i!==s.i&&e.next.i!==s.i&&e.i!==t.i&&e.next.i!==t.i&&fh(e,e.next,s,t))return!0;e=e.next}while(e!==s);return!1}function Si(s,t){return it(s.prev,s,s.next)<0?it(s,t,s.next)>=0&&it(s,s.prev,t)>=0:it(s,t,s.prev)<0||it(s,s.next,t)<0}function _m(s,t){let e=s,r=!1;const n=(s.x+t.x)/2,o=(s.y+t.y)/2;do e.y>o!=e.next.y>o&&e.next.y!==e.y&&n<(e.next.x-e.x)*(o-e.y)/(e.next.y-e.y)+e.x&&(r=!r),e=e.next;while(e!==s);return r}function ph(s,t){const e=tn(s.i,s.x,s.y),r=tn(t.i,t.x,t.y),n=s.next,o=t.prev;return s.next=t,t.prev=s,e.next=n,n.prev=e,r.next=e,e.prev=r,o.next=r,r.prev=o,r}function mh(s,t,e,r){const n=tn(s,t,e);return r?(n.next=r.next,n.prev=r,r.next.prev=n,r.next=n):(n.prev=n,n.next=n),n}function Ti(s){s.next.prev=s.prev,s.prev.next=s.next,s.prevZ&&(s.prevZ.nextZ=s.nextZ),s.nextZ&&(s.nextZ.prevZ=s.prevZ)}function tn(s,t,e){return{i:s,x:t,y:e,prev:null,next:null,z:0,prevZ:null,nextZ:null,steiner:!1}}function ym(s,t,e,r){let n=0;for(let o=t,l=e-r;o<e;o+=r)n+=(s[l]-s[o])*(s[o+1]+s[l+1]),l=o;return n}const xm=ch.default||ch;var Pt=(s=>(s[s.NONE=0]="NONE",s[s.COLOR=16384]="COLOR",s[s.STENCIL=1024]="STENCIL",s[s.DEPTH=256]="DEPTH",s[s.COLOR_DEPTH=16640]="COLOR_DEPTH",s[s.COLOR_STENCIL=17408]="COLOR_STENCIL",s[s.DEPTH_STENCIL=1280]="DEPTH_STENCIL",s[s.ALL=17664]="ALL",s))(Pt||{});class gh{constructor(t){this.items=[],this._name=t}emit(t,e,r,n,o,l,h,u){const{name:f,items:m}=this;for(let g=0,y=m.length;g<y;g++)m[g][f](t,e,r,n,o,l,h,u);return this}add(t){return t[this._name]&&(this.remove(t),this.items.push(t)),this}remove(t){const e=this.items.indexOf(t);return e!==-1&&this.items.splice(e,1),this}contains(t){return this.items.indexOf(t)!==-1}removeAll(){return this.items.length=0,this}destroy(){this.removeAll(),this.items=null,this._name=null}get empty(){return this.items.length===0}get name(){return this._name}}const bm=["init","destroy","contextChange","resolutionChange","resetState","renderEnd","renderStart","render","update","postrender","prerender"],_h=class eu extends Ct{constructor(t){super(),this.uid=et("renderer"),this.runners=Object.create(null),this.renderPipes=Object.create(null),this._initOptions={},this._systemsHash=Object.create(null),this.type=t.type,this.name=t.name,this.config=t;const e=[...bm,...this.config.runners??[]];this._addRunners(...e),this._unsafeEvalCheck()}async init(t={}){const e=t.skipExtensionImports===!0?!0:t.manageImports===!1;await im(e),this._addSystems(this.config.systems),this._addPipes(this.config.renderPipes,this.config.renderPipeAdaptors);for(const r in this._systemsHash)t={...this._systemsHash[r].constructor.defaultOptions,...t};t={...eu.defaultOptions,...t},this._roundPixels=t.roundPixels?1:0;for(let r=0;r<this.runners.init.items.length;r++)await this.runners.init.items[r].init(t);this._initOptions=t}render(t,e){let r=t;if(r instanceof st&&(r={container:r},e&&(z($,"passing a second argument is deprecated, please use render options instead"),r.target=e.renderTexture)),r.target||(r.target=this.view.renderTarget),r.target===this.view.renderTarget&&(this._lastObjectRendered=r.container,r.clearColor??(r.clearColor=this.background.colorRgba),r.clear??(r.clear=this.background.clearBeforeRender)),r.clearColor){const n=Array.isArray(r.clearColor)&&r.clearColor.length===4;r.clearColor=n?r.clearColor:J.shared.setValue(r.clearColor).toArray()}r.transform||(r.container.updateLocalTransform(),r.transform=r.container.localTransform),r.container.visible&&(r.container.enableRenderGroup(),this.runners.prerender.emit(r),this.runners.renderStart.emit(r),this.runners.render.emit(r),this.runners.renderEnd.emit(r),this.runners.postrender.emit(r))}resize(t,e,r){const n=this.view.resolution;this.view.resize(t,e,r),this.emit("resize",this.view.screen.width,this.view.screen.height,this.view.resolution),r!==void 0&&r!==n&&this.runners.resolutionChange.emit(r)}clear(t={}){const e=this;t.target||(t.target=e.renderTarget.renderTarget),t.clearColor||(t.clearColor=this.background.colorRgba),t.clear??(t.clear=Pt.ALL);const{clear:r,clearColor:n,target:o}=t;J.shared.setValue(n??this.background.colorRgba),e.renderTarget.clear(o,r,J.shared.toArray())}get resolution(){return this.view.resolution}set resolution(t){this.view.resolution=t,this.runners.resolutionChange.emit(t)}get width(){return this.view.texture.frame.width}get height(){return this.view.texture.frame.height}get canvas(){return this.view.canvas}get lastObjectRendered(){return this._lastObjectRendered}get renderingToScreen(){return this.renderTarget.renderingToScreen}get screen(){return this.view.screen}_addRunners(...t){t.forEach(e=>{this.runners[e]=new gh(e)})}_addSystems(t){let e;for(e in t){const r=t[e];this._addSystem(r.value,r.name)}}_addSystem(t,e){const r=new t(this);if(this[e])throw new Error(`Whoops! The name "${e}" is already in use`);this[e]=r,this._systemsHash[e]=r;for(const n in this.runners)this.runners[n].add(r);return this}_addPipes(t,e){const r=e.reduce((n,o)=>(n[o.name]=o.value,n),{});t.forEach(n=>{const o=n.value,l=n.name,h=r[l];this.renderPipes[l]=new o(this,h?new h:null),this.runners.destroy.add(this.renderPipes[l])})}destroy(t=!1){this.runners.destroy.items.reverse(),this.runners.destroy.emit(t),(t===!0||typeof t=="object"&&t.releaseGlobalResources)&&He.release(),Object.values(this.runners).forEach(e=>{e.destroy()}),this._systemsHash=null,this.renderPipes=null}generateTexture(t){return this.textureGenerator.generateTexture(t)}get roundPixels(){return!!this._roundPixels}_unsafeEvalCheck(){if(!lh())throw new Error("Current environment does not allow unsafe-eval, please use pixi.js/unsafe-eval module to enable support.")}resetState(){this.runners.resetState.emit()}};_h.defaultOptions={resolution:1,failIfMajorPerformanceCaveat:!1,roundPixels:!1};let Tr=_h,Cr;function vm(s){return Cr!==void 0||(Cr=(()=>{const t={stencil:!0,failIfMajorPerformanceCaveat:s??Tr.defaultOptions.failIfMajorPerformanceCaveat};try{if(!W.get().getWebGLRenderingContext())return!1;let r=W.get().createCanvas().getContext("webgl",t);const n=!!r?.getContextAttributes()?.stencil;if(r){const o=r.getExtension("WEBGL_lose_context");o&&o.loseContext()}return r=null,n}catch{return!1}})()),Cr}let Er;async function wm(s={}){return Er!==void 0||(Er=await(async()=>{const t=W.get().getNavigator().gpu;if(!t)return!1;try{return await(await t.requestAdapter(s)).requestDevice(),!0}catch{return!1}})()),Er}const yh=["webgl","webgpu","canvas"];async function Sm(s){let t=[];s.preference?(t.push(s.preference),yh.forEach(o=>{o!==s.preference&&t.push(o)})):t=yh.slice();let e,r={};for(let o=0;o<t.length;o++){const l=t[o];if(l==="webgpu"&&await wm()){const{WebGPURenderer:h}=await Promise.resolve().then(()=>db);e=h,r={...s,...s.webgpu};break}else if(l==="webgl"&&vm(s.failIfMajorPerformanceCaveat??Tr.defaultOptions.failIfMajorPerformanceCaveat)){const{WebGLRenderer:h}=await Promise.resolve().then(()=>Xx);e=h,r={...s,...s.webgl};break}else if(l==="canvas")throw r={...s},new Error("CanvasRenderer is not yet implemented")}if(delete r.webgpu,delete r.webgl,!e)throw new Error("No available renderer for the current environment");const n=new e;return await n.init(r),n}const Ar="8.14.3";class xh{static init(){globalThis.__PIXI_APP_INIT__?.(this,Ar)}static destroy(){}}xh.extension=C.Application;class bh{constructor(t){this._renderer=t}init(){globalThis.__PIXI_RENDERER_INIT__?.(this._renderer,Ar)}destroy(){this._renderer=null}}bh.extension={type:[C.WebGLSystem,C.WebGPUSystem],name:"initHook",priority:-10};const vh=class bo{constructor(...t){this.stage=new st,t[0]!==void 0&&z($,"Application constructor options are deprecated, please use Application.init() instead.")}async init(t){t={...t},this.stage||(this.stage=new st),this.renderer=await Sm(t),bo._plugins.forEach(e=>{e.init.call(this,t)})}render(){this.renderer.render({container:this.stage})}get canvas(){return this.renderer.canvas}get view(){return z($,"Application.view is deprecated, please use Application.canvas instead."),this.renderer.canvas}get screen(){return this.renderer.screen}destroy(t=!1,e=!1){const r=bo._plugins.slice(0);r.reverse(),r.forEach(n=>{n.destroy.call(this)}),this.stage.destroy(e),this.stage=null,this.renderer.destroy(t),this.renderer=null}};vh._plugins=[];let en=vh;D.handleByList(C.Application,en._plugins),D.add(xh);class wh{static init(t){Object.defineProperty(this,"resizeTo",{configurable:!0,set(e){globalThis.removeEventListener("resize",this.queueResize),this._resizeTo=e,e&&(globalThis.addEventListener("resize",this.queueResize),this.resize())},get(){return this._resizeTo}}),this.queueResize=()=>{this._resizeTo&&(this._cancelResize(),this._resizeId=requestAnimationFrame(()=>this.resize()))},this._cancelResize=()=>{this._resizeId&&(cancelAnimationFrame(this._resizeId),this._resizeId=null)},this.resize=()=>{if(!this._resizeTo)return;this._cancelResize();let e,r;if(this._resizeTo===globalThis.window)e=globalThis.innerWidth,r=globalThis.innerHeight;else{const{clientWidth:n,clientHeight:o}=this._resizeTo;e=n,r=o}this.renderer.resize(e,r),this.render()},this._resizeId=null,this._resizeTo=null,this.resizeTo=t.resizeTo||null}static destroy(){globalThis.removeEventListener("resize",this.queueResize),this._cancelResize(),this._cancelResize=null,this.queueResize=null,this.resizeTo=null,this.resize=null}}wh.extension=C.Application;class Sh{static init(t){t=Object.assign({autoStart:!0,sharedTicker:!1},t),Object.defineProperty(this,"ticker",{configurable:!0,set(e){this._ticker&&this._ticker.remove(this.render,this),this._ticker=e,e&&e.add(this.render,this,We.LOW)},get(){return this._ticker}}),this.stop=()=>{this._ticker.stop()},this.start=()=>{this._ticker.start()},this._ticker=null,this.ticker=t.sharedTicker?Et.shared:new Et,t.autoStart&&this.start()}static destroy(){if(this._ticker){const t=this._ticker;this.ticker=null,t.destroy()}}}Sh.extension=C.Application;class Th extends Ct{constructor(){super(...arguments),this.chars=Object.create(null),this.lineHeight=0,this.fontFamily="",this.fontMetrics={fontSize:0,ascent:0,descent:0},this.baseLineOffset=0,this.distanceField={type:"none",range:0},this.pages=[],this.applyFillAsTint=!0,this.baseMeasurementFontSize=100,this.baseRenderedFontSize=100}get font(){return z($,"BitmapFont.font is deprecated, please use BitmapFont.fontFamily instead."),this.fontFamily}get pageTextures(){return z($,"BitmapFont.pageTextures is deprecated, please use BitmapFont.pages instead."),this.pages}get size(){return z($,"BitmapFont.size is deprecated, please use BitmapFont.fontMetrics.fontSize instead."),this.fontMetrics.fontSize}get distanceFieldRange(){return z($,"BitmapFont.distanceFieldRange is deprecated, please use BitmapFont.distanceField.range instead."),this.distanceField.range}get distanceFieldType(){return z($,"BitmapFont.distanceFieldType is deprecated, please use BitmapFont.distanceField.type instead."),this.distanceField.type}destroy(t=!1){this.emit("destroy",this),this.removeAllListeners();for(const e in this.chars)this.chars[e].texture?.destroy();this.chars=null,t&&(this.pages.forEach(e=>e.texture.destroy(!0)),this.pages=null)}}class Tm{constructor(t=0,e=0,r=!1){this.first=null,this.items=Object.create(null),this.last=null,this.max=t,this.resetTtl=r,this.size=0,this.ttl=e}clear(){return this.first=null,this.items=Object.create(null),this.last=null,this.size=0,this}delete(t){if(this.has(t)){const e=this.items[t];delete this.items[t],this.size--,e.prev!==null&&(e.prev.next=e.next),e.next!==null&&(e.next.prev=e.prev),this.first===e&&(this.first=e.next),this.last===e&&(this.last=e.prev)}return this}entries(t=this.keys()){return t.map(e=>[e,this.get(e)])}evict(t=!1){if(t||this.size>0){const e=this.first;delete this.items[e.key],--this.size===0?(this.first=null,this.last=null):(this.first=e.next,this.first.prev=null)}return this}expiresAt(t){let e;return this.has(t)&&(e=this.items[t].expiry),e}get(t){const e=this.items[t];if(e!==void 0){if(this.ttl>0&&e.expiry<=Date.now()){this.delete(t);return}return this.moveToEnd(e),e.value}}has(t){return t in this.items}moveToEnd(t){this.last!==t&&(t.prev!==null&&(t.prev.next=t.next),t.next!==null&&(t.next.prev=t.prev),this.first===t&&(this.first=t.next),t.prev=this.last,t.next=null,this.last!==null&&(this.last.next=t),this.last=t,this.first===null&&(this.first=t))}keys(){const t=[];let e=this.first;for(;e!==null;)t.push(e.key),e=e.next;return t}setWithEvicted(t,e,r=this.resetTtl){let n=null;if(this.has(t))this.set(t,e,!0,r);else{this.max>0&&this.size===this.max&&(n={...this.first},this.evict(!0));let o=this.items[t]={expiry:this.ttl>0?Date.now()+this.ttl:this.ttl,key:t,prev:this.last,next:null,value:e};++this.size===1?this.first=o:this.last.next=o,this.last=o}return n}set(t,e,r=!1,n=this.resetTtl){let o=this.items[t];return r||o!==void 0?(o.value=e,r===!1&&n&&(o.expiry=this.ttl>0?Date.now()+this.ttl:this.ttl),this.moveToEnd(o)):(this.max>0&&this.size===this.max&&this.evict(!0),o=this.items[t]={expiry:this.ttl>0?Date.now()+this.ttl:this.ttl,key:t,prev:this.last,next:null,value:e},++this.size===1?this.first=o:this.last.next=o,this.last=o),this}values(t=this.keys()){return t.map(e=>this.get(e))}}function Ch(s=1e3,t=0,e=!1){if(isNaN(s)||s<0)throw new TypeError("Invalid max value");if(isNaN(t)||t<0)throw new TypeError("Invalid ttl value");if(typeof e!="boolean")throw new TypeError("Invalid resetTtl value");return new Tm(s,t,e)}const Cm=["serif","sans-serif","monospace","cursive","fantasy","system-ui"];function Pr(s){const t=typeof s.fontSize=="number"?`${s.fontSize}px`:s.fontSize;let e=s.fontFamily;Array.isArray(s.fontFamily)||(e=s.fontFamily.split(","));for(let r=e.length-1;r>=0;r--){let n=e[r].trim();!/([\"\'])[^\'\"]+\1/.test(n)&&!Cm.includes(n)&&(n=`"${n}"`),e[r]=n}return`${s.fontStyle} ${s.fontVariant} ${s.fontWeight} ${t} ${e.join(",")}`}const rn={willReadFrequently:!0},Wt=class I{static get experimentalLetterSpacingSupported(){let t=I._experimentalLetterSpacingSupported;if(t===void 0){const e=W.get().getCanvasRenderingContext2D().prototype;t=I._experimentalLetterSpacingSupported="letterSpacing"in e||"textLetterSpacing"in e}return t}constructor(t,e,r,n,o,l,h,u,f){this.text=t,this.style=e,this.width=r,this.height=n,this.lines=o,this.lineWidths=l,this.lineHeight=h,this.maxLineWidth=u,this.fontProperties=f}static measureText(t=" ",e,r=I._canvas,n=e.wordWrap){const o=`${t}-${e.styleKey}-wordWrap-${n}`;if(I._measurementCache.has(o))return I._measurementCache.get(o);const l=Pr(e),h=I.measureFont(l);h.fontSize===0&&(h.fontSize=e.fontSize,h.ascent=e.fontSize);const u=I.__context;u.font=l;const m=(n?I._wordWrap(t,e,r):t).split(/(?:\r\n|\r|\n)/),g=new Array(m.length);let y=0;for(let _=0;_<m.length;_++){const b=I._measureText(m[_],e.letterSpacing,u);g[_]=b,y=Math.max(y,b)}const x=e._stroke?.width||0;let a=y+x;e.dropShadow&&(a+=e.dropShadow.distance);const c=e.lineHeight||h.fontSize;let d=Math.max(c,h.fontSize+x)+(m.length-1)*(c+e.leading);e.dropShadow&&(d+=e.dropShadow.distance);const p=new I(t,e,a,d,m,g,c+e.leading,y,h);return I._measurementCache.set(o,p),p}static _measureText(t,e,r){let n=!1;I.experimentalLetterSpacingSupported&&(I.experimentalLetterSpacing?(r.letterSpacing=`${e}px`,r.textLetterSpacing=`${e}px`,n=!0):(r.letterSpacing="0px",r.textLetterSpacing="0px"));const o=r.measureText(t);let l=o.width;const h=-o.actualBoundingBoxLeft;let f=o.actualBoundingBoxRight-h;if(l>0)if(n)l-=e,f-=e;else{const m=(I.graphemeSegmenter(t).length-1)*e;l+=m,f+=m}return Math.max(l,f)}static _wordWrap(t,e,r=I._canvas){const n=r.getContext("2d",rn);let o=0,l="",h="";const u=Object.create(null),{letterSpacing:f,whiteSpace:m}=e,g=I._collapseSpaces(m),y=I._collapseNewlines(m);let x=!g;const a=e.wordWrapWidth+f,c=I._tokenize(t);for(let d=0;d<c.length;d++){let p=c[d];if(I._isNewline(p)){if(!y){h+=I._addLine(l),x=!g,l="",o=0;continue}p=" "}if(g){const b=I.isBreakingSpace(p),v=I.isBreakingSpace(l[l.length-1]);if(b&&v)continue}const _=I._getFromCache(p,f,u,n);if(_>a)if(l!==""&&(h+=I._addLine(l),l="",o=0),I.canBreakWords(p,e.breakWords)){const b=I.wordWrapSplit(p);for(let v=0;v<b.length;v++){let w=b[v],S=w,T=1;for(;b[v+T];){const P=b[v+T];if(!I.canBreakChars(S,P,p,v,e.breakWords))w+=P;else break;S=P,T++}v+=T-1;const E=I._getFromCache(w,f,u,n);E+o>a&&(h+=I._addLine(l),x=!1,l="",o=0),l+=w,o+=E}}else{l.length>0&&(h+=I._addLine(l),l="",o=0);const b=d===c.length-1;h+=I._addLine(p,!b),x=!1,l="",o=0}else _+o>a&&(x=!1,h+=I._addLine(l),l="",o=0),(l.length>0||!I.isBreakingSpace(p)||x)&&(l+=p,o+=_)}return h+=I._addLine(l,!1),h}static _addLine(t,e=!0){return t=I._trimRight(t),t=e?`${t}
|
|
99
|
+
`:t,t}static _getFromCache(t,e,r,n){let o=r[t];return typeof o!="number"&&(o=I._measureText(t,e,n)+e,r[t]=o),o}static _collapseSpaces(t){return t==="normal"||t==="pre-line"}static _collapseNewlines(t){return t==="normal"}static _trimRight(t){if(typeof t!="string")return"";for(let e=t.length-1;e>=0;e--){const r=t[e];if(!I.isBreakingSpace(r))break;t=t.slice(0,-1)}return t}static _isNewline(t){return typeof t!="string"?!1:I._newlines.includes(t.charCodeAt(0))}static isBreakingSpace(t,e){return typeof t!="string"?!1:I._breakingSpaces.includes(t.charCodeAt(0))}static _tokenize(t){const e=[];let r="";if(typeof t!="string")return e;for(let n=0;n<t.length;n++){const o=t[n],l=t[n+1];if(I.isBreakingSpace(o,l)||I._isNewline(o)){r!==""&&(e.push(r),r=""),o==="\r"&&l===`
|
|
100
100
|
`?(e.push(`\r
|
|
101
|
-
`),n++):e.push(a);continue}r+=a}return r!==""&&e.push(r),e}static canBreakWords(t,e){return e}static canBreakChars(t,e,r,n,a){return!0}static wordWrapSplit(t){return I.graphemeSegmenter(t)}static measureFont(t){if(I._fonts[t])return I._fonts[t];const e=I._context;e.font=t;const r=e.measureText(I.METRICS_STRING+I.BASELINE_SYMBOL),n={ascent:r.actualBoundingBoxAscent,descent:r.actualBoundingBoxDescent,fontSize:r.actualBoundingBoxAscent+r.actualBoundingBoxDescent};return I._fonts[t]=n,n}static clearMetrics(t=""){t?delete I._fonts[t]:I._fonts={}}static get _canvas(){if(!I.__canvas){let t;try{const e=new OffscreenCanvas(0,0);if(e.getContext("2d",Js)?.measureText)return I.__canvas=e,e;t=W.get().createCanvas()}catch{t=W.get().createCanvas()}t.width=t.height=10,I.__canvas=t}return I.__canvas}static get _context(){return I.__context||(I.__context=I._canvas.getContext("2d",Js)),I.__context}};Wt.METRICS_STRING="|ÉqÅ",Wt.BASELINE_SYMBOL="M",Wt.BASELINE_MULTIPLIER=1.4,Wt.HEIGHT_MULTIPLIER=2,Wt.graphemeSegmenter=(()=>{if(typeof Intl?.Segmenter=="function"){const s=new Intl.Segmenter;return t=>{const e=s.segment(t),r=[];let n=0;for(const a of e)r[n++]=a.segment;return r}}return s=>[...s]})(),Wt.experimentalLetterSpacing=!1,Wt._fonts={},Wt._newlines=[10,13],Wt._breakingSpaces=[9,32,8192,8193,8194,8195,8196,8197,8198,8200,8201,8202,8287,12288],Wt._measurementCache=vh(1e3);let xt=Wt;const wh=[{offset:0,color:"white"},{offset:1,color:"black"}],tn=class _a{constructor(...t){this.uid=et("fillGradient"),this._tick=0,this.type="linear",this.colorStops=[];let e=_m(t);e={...e.type==="radial"?_a.defaultRadialOptions:_a.defaultLinearOptions,...Ka(e)},this._textureSize=e.textureSize,this._wrapMode=e.wrapMode,e.type==="radial"?(this.center=e.center,this.outerCenter=e.outerCenter??this.center,this.innerRadius=e.innerRadius,this.outerRadius=e.outerRadius,this.scale=e.scale,this.rotation=e.rotation):(this.start=e.start,this.end=e.end),this.textureSpace=e.textureSpace,this.type=e.type,e.colorStops.forEach(n=>{this.addColorStop(n.offset,n.color)})}addColorStop(t,e){return this.colorStops.push({offset:t,color:J.shared.setValue(e).toHexa()}),this}buildLinearGradient(){if(this.texture)return;let{x:t,y:e}=this.start,{x:r,y:n}=this.end,a=r-t,l=n-e;const h=a<0||l<0;if(this._wrapMode==="clamp-to-edge"){if(a<0){const u=t;t=r,r=u,a*=-1}if(l<0){const u=e;e=n,n=u,l*=-1}}const d=this.colorStops.length?this.colorStops:wh,f=this._textureSize,{canvas:m,context:g}=Th(f,1),y=h?g.createLinearGradient(this._textureSize,0,0,0):g.createLinearGradient(0,0,this._textureSize,0);Sh(y,d),g.fillStyle=y,g.fillRect(0,0,f,1),this.texture=new M({source:new we({resource:m,addressMode:this._wrapMode})});const x=Math.sqrt(a*a+l*l),o=Math.atan2(l,a),c=new k;c.scale(x/f,1),c.rotate(o),c.translate(t,e),this.textureSpace==="local"&&c.scale(f,f),this.transform=c}buildGradient(){this.texture||this._tick++,this.type==="linear"?this.buildLinearGradient():this.buildRadialGradient()}buildRadialGradient(){if(this.texture)return;const t=this.colorStops.length?this.colorStops:wh,e=this._textureSize,{canvas:r,context:n}=Th(e,e),{x:a,y:l}=this.center,{x:h,y:d}=this.outerCenter,f=this.innerRadius,m=this.outerRadius,g=h-m,y=d-m,x=e/(m*2),o=(a-g)*x,c=(l-y)*x,u=n.createRadialGradient(o,c,f*x,(h-g)*x,(d-y)*x,m*x);Sh(u,t),n.fillStyle=t[t.length-1].color,n.fillRect(0,0,e,e),n.fillStyle=u,n.translate(o,c),n.rotate(this.rotation),n.scale(1,this.scale),n.translate(-o,-c),n.fillRect(0,0,e,e),this.texture=new M({source:new we({resource:r,addressMode:this._wrapMode})});const p=new k;p.scale(1/x,1/x),p.translate(g,y),this.textureSpace==="local"&&p.scale(e,e),this.transform=p}destroy(){this.texture?.destroy(!0),this.texture=null,this.transform=null,this.colorStops=[],this.start=null,this.end=null,this.center=null,this.outerCenter=null}get styleKey(){return`fill-gradient-${this.uid}-${this._tick}`}};tn.defaultLinearOptions={start:{x:0,y:0},end:{x:0,y:1},colorStops:[],textureSpace:"local",type:"linear",textureSize:256,wrapMode:"clamp-to-edge"},tn.defaultRadialOptions={center:{x:.5,y:.5},innerRadius:0,outerRadius:.5,colorStops:[],scale:1,textureSpace:"local",type:"radial",textureSize:256,wrapMode:"clamp-to-edge"};let Vt=tn;function Sh(s,t){for(let e=0;e<t.length;e++){const r=t[e];s.addColorStop(r.offset,r.color)}}function Th(s,t){const e=W.get().createCanvas(s,t),r=e.getContext("2d");return{canvas:e,context:r}}function _m(s){let t=s[0]??{};return(typeof t=="number"||s[1])&&(z("8.5.2","use options object instead"),t={type:"linear",start:{x:s[0],y:s[1]},end:{x:s[2],y:s[3]},textureSpace:s[4],textureSize:s[5]??Vt.defaultLinearOptions.textureSize}),t}const Ch={repeat:{addressModeU:"repeat",addressModeV:"repeat"},"repeat-x":{addressModeU:"repeat",addressModeV:"clamp-to-edge"},"repeat-y":{addressModeU:"clamp-to-edge",addressModeV:"repeat"},"no-repeat":{addressModeU:"clamp-to-edge",addressModeV:"clamp-to-edge"}};class Ar{constructor(t,e){this.uid=et("fillPattern"),this._tick=0,this.transform=new k,this.texture=t,this.transform.scale(1/t.frame.width,1/t.frame.height),e&&(t.source.style.addressModeU=Ch[e].addressModeU,t.source.style.addressModeV=Ch[e].addressModeV)}setTransform(t){const e=this.texture;this.transform.copyFrom(t),this.transform.invert(),this.transform.scale(1/e.frame.width,1/e.frame.height),this._tick++}get texture(){return this._texture}set texture(t){this._texture!==t&&(this._texture=t,this._tick++)}get styleKey(){return`fill-pattern-${this.uid}-${this._tick}`}destroy(){this.texture.destroy(!0),this.texture=null}}var en,Eh;function ym(){if(Eh)return en;Eh=1,en=e;var s={a:7,c:6,h:1,l:2,m:2,q:4,s:4,t:2,v:1,z:0},t=/([astvzqmhlc])([^astvzqmhlc]*)/ig;function e(a){var l=[];return a.replace(t,function(h,d,f){var m=d.toLowerCase();for(f=n(f),m=="m"&&f.length>2&&(l.push([d].concat(f.splice(0,2))),m="l",d=d=="m"?"l":"L");;){if(f.length==s[m])return f.unshift(d),l.push(f);if(f.length<s[m])throw new Error("malformed path data");l.push([d].concat(f.splice(0,s[m])))}}),l}var r=/-?[0-9]*\.?[0-9]+(?:e[-+]?\d+)?/ig;function n(a){var l=a.match(r);return l?l.map(Number):[]}return en}var xm=ym();const bm=_e(xm);function vm(s,t){const e=bm(s),r=[];let n=null,a=0,l=0;for(let h=0;h<e.length;h++){const d=e[h],f=d[0],m=d;switch(f){case"M":a=m[1],l=m[2],t.moveTo(a,l);break;case"m":a+=m[1],l+=m[2],t.moveTo(a,l);break;case"H":a=m[1],t.lineTo(a,l);break;case"h":a+=m[1],t.lineTo(a,l);break;case"V":l=m[1],t.lineTo(a,l);break;case"v":l+=m[1],t.lineTo(a,l);break;case"L":a=m[1],l=m[2],t.lineTo(a,l);break;case"l":a+=m[1],l+=m[2],t.lineTo(a,l);break;case"C":a=m[5],l=m[6],t.bezierCurveTo(m[1],m[2],m[3],m[4],a,l);break;case"c":t.bezierCurveTo(a+m[1],l+m[2],a+m[3],l+m[4],a+m[5],l+m[6]),a+=m[5],l+=m[6];break;case"S":a=m[3],l=m[4],t.bezierCurveToShort(m[1],m[2],a,l);break;case"s":t.bezierCurveToShort(a+m[1],l+m[2],a+m[3],l+m[4]),a+=m[3],l+=m[4];break;case"Q":a=m[3],l=m[4],t.quadraticCurveTo(m[1],m[2],a,l);break;case"q":t.quadraticCurveTo(a+m[1],l+m[2],a+m[3],l+m[4]),a+=m[3],l+=m[4];break;case"T":a=m[1],l=m[2],t.quadraticCurveToShort(a,l);break;case"t":a+=m[1],l+=m[2],t.quadraticCurveToShort(a,l);break;case"A":a=m[6],l=m[7],t.arcToSvg(m[1],m[2],m[3],m[4],m[5],a,l);break;case"a":a+=m[6],l+=m[7],t.arcToSvg(m[1],m[2],m[3],m[4],m[5],a,l);break;case"Z":case"z":t.closePath(),r.length>0&&(n=r.pop(),n?(a=n.startX,l=n.startY):(a=0,l=0)),n=null;break;default:F(`Unknown SVG path command: ${f}`)}f!=="Z"&&f!=="z"&&n===null&&(n={startX:a,startY:l},r.push(n))}return t}class Pr{constructor(t=0,e=0,r=0){this.type="circle",this.x=t,this.y=e,this.radius=r}clone(){return new Pr(this.x,this.y,this.radius)}contains(t,e){if(this.radius<=0)return!1;const r=this.radius*this.radius;let n=this.x-t,a=this.y-e;return n*=n,a*=a,n+a<=r}strokeContains(t,e,r,n=.5){if(this.radius===0)return!1;const a=this.x-t,l=this.y-e,h=this.radius,d=(1-n)*r,f=Math.sqrt(a*a+l*l);return f<=h+d&&f>h-(r-d)}getBounds(t){return t||(t=new L),t.x=this.x-this.radius,t.y=this.y-this.radius,t.width=this.radius*2,t.height=this.radius*2,t}copyFrom(t){return this.x=t.x,this.y=t.y,this.radius=t.radius,this}copyTo(t){return t.copyFrom(this),t}toString(){return`[pixi.js/math:Circle x=${this.x} y=${this.y} radius=${this.radius}]`}}class rn{constructor(t=0,e=0,r=0,n=0){this.type="ellipse",this.x=t,this.y=e,this.halfWidth=r,this.halfHeight=n}clone(){return new rn(this.x,this.y,this.halfWidth,this.halfHeight)}contains(t,e){if(this.halfWidth<=0||this.halfHeight<=0)return!1;let r=(t-this.x)/this.halfWidth,n=(e-this.y)/this.halfHeight;return r*=r,n*=n,r+n<=1}strokeContains(t,e,r,n=.5){const{halfWidth:a,halfHeight:l}=this;if(a<=0||l<=0)return!1;const h=r*(1-n),d=r-h,f=a-d,m=l-d,g=a+h,y=l+h,x=t-this.x,o=e-this.y,c=x*x/(f*f)+o*o/(m*m),u=x*x/(g*g)+o*o/(y*y);return c>1&&u<=1}getBounds(t){return t||(t=new L),t.x=this.x-this.halfWidth,t.y=this.y-this.halfHeight,t.width=this.halfWidth*2,t.height=this.halfHeight*2,t}copyFrom(t){return this.x=t.x,this.y=t.y,this.halfWidth=t.halfWidth,this.halfHeight=t.halfHeight,this}copyTo(t){return t.copyFrom(this),t}toString(){return`[pixi.js/math:Ellipse x=${this.x} y=${this.y} halfWidth=${this.halfWidth} halfHeight=${this.halfHeight}]`}}function wm(s,t,e,r,n,a){const l=s-e,h=t-r,d=n-e,f=a-r,m=l*d+h*f,g=d*d+f*f;let y=-1;g!==0&&(y=m/g);let x,o;y<0?(x=e,o=r):y>1?(x=n,o=a):(x=e+y*d,o=r+y*f);const c=s-x,u=t-o;return c*c+u*u}let Sm,Tm;class Ti{constructor(...t){this.type="polygon";let e=Array.isArray(t[0])?t[0]:t;if(typeof e[0]!="number"){const r=[];for(let n=0,a=e.length;n<a;n++)r.push(e[n].x,e[n].y);e=r}this.points=e,this.closePath=!0}isClockwise(){let t=0;const e=this.points,r=e.length;for(let n=0;n<r;n+=2){const a=e[n],l=e[n+1],h=e[(n+2)%r],d=e[(n+3)%r];t+=(h-a)*(d+l)}return t<0}containsPolygon(t){const e=this.getBounds(Sm),r=t.getBounds(Tm);if(!e.containsRect(r))return!1;const n=t.points;for(let a=0;a<n.length;a+=2){const l=n[a],h=n[a+1];if(!this.contains(l,h))return!1}return!0}clone(){const t=this.points.slice(),e=new Ti(t);return e.closePath=this.closePath,e}contains(t,e){let r=!1;const n=this.points.length/2;for(let a=0,l=n-1;a<n;l=a++){const h=this.points[a*2],d=this.points[a*2+1],f=this.points[l*2],m=this.points[l*2+1];d>e!=m>e&&t<(f-h)*((e-d)/(m-d))+h&&(r=!r)}return r}strokeContains(t,e,r,n=.5){const a=r*r,l=a*(1-n),h=a-l,{points:d}=this,f=d.length-(this.closePath?0:2);for(let m=0;m<f;m+=2){const g=d[m],y=d[m+1],x=d[(m+2)%d.length],o=d[(m+3)%d.length],c=wm(t,e,g,y,x,o),u=Math.sign((x-g)*(e-y)-(o-y)*(t-g));if(c<=(u<0?h:l))return!0}return!1}getBounds(t){t||(t=new L);const e=this.points;let r=1/0,n=-1/0,a=1/0,l=-1/0;for(let h=0,d=e.length;h<d;h+=2){const f=e[h],m=e[h+1];r=f<r?f:r,n=f>n?f:n,a=m<a?m:a,l=m>l?m:l}return t.x=r,t.width=n-r,t.y=a,t.height=l-a,t}copyFrom(t){return this.points=t.points.slice(),this.closePath=t.closePath,this}copyTo(t){return t.copyFrom(this),t}toString(){return`[pixi.js/math:PolygoncloseStroke=${this.closePath}points=${this.points.reduce((t,e)=>`${t}, ${e}`,"")}]`}get lastX(){return this.points[this.points.length-2]}get lastY(){return this.points[this.points.length-1]}get x(){return z("8.11.0","Polygon.lastX is deprecated, please use Polygon.lastX instead."),this.points[this.points.length-2]}get y(){return z("8.11.0","Polygon.y is deprecated, please use Polygon.lastY instead."),this.points[this.points.length-1]}get startX(){return this.points[0]}get startY(){return this.points[1]}}const Br=(s,t,e,r,n,a,l)=>{const h=s-e,d=t-r,f=Math.sqrt(h*h+d*d);return f>=n-a&&f<=n+l};class sn{constructor(t=0,e=0,r=0,n=0,a=20){this.type="roundedRectangle",this.x=t,this.y=e,this.width=r,this.height=n,this.radius=a}getBounds(t){return t||(t=new L),t.x=this.x,t.y=this.y,t.width=this.width,t.height=this.height,t}clone(){return new sn(this.x,this.y,this.width,this.height,this.radius)}copyFrom(t){return this.x=t.x,this.y=t.y,this.width=t.width,this.height=t.height,this}copyTo(t){return t.copyFrom(this),t}contains(t,e){if(this.width<=0||this.height<=0)return!1;if(t>=this.x&&t<=this.x+this.width&&e>=this.y&&e<=this.y+this.height){const r=Math.max(0,Math.min(this.radius,Math.min(this.width,this.height)/2));if(e>=this.y+r&&e<=this.y+this.height-r||t>=this.x+r&&t<=this.x+this.width-r)return!0;let n=t-(this.x+r),a=e-(this.y+r);const l=r*r;if(n*n+a*a<=l||(n=t-(this.x+this.width-r),n*n+a*a<=l)||(a=e-(this.y+this.height-r),n*n+a*a<=l)||(n=t-(this.x+r),n*n+a*a<=l))return!0}return!1}strokeContains(t,e,r,n=.5){const{x:a,y:l,width:h,height:d,radius:f}=this,m=r*(1-n),g=r-m,y=a+f,x=l+f,o=h-f*2,c=d-f*2,u=a+h,p=l+d;return(t>=a-m&&t<=a+g||t>=u-g&&t<=u+m)&&e>=x&&e<=x+c||(e>=l-m&&e<=l+g||e>=p-g&&e<=p+m)&&t>=y&&t<=y+o?!0:t<y&&e<x&&Br(t,e,y,x,f,g,m)||t>u-f&&e<x&&Br(t,e,u-f,x,f,g,m)||t>u-f&&e>p-f&&Br(t,e,u-f,p-f,f,g,m)||t<y&&e>p-f&&Br(t,e,y,p-f,f,g,m)}toString(){return`[pixi.js/math:RoundedRectangle x=${this.x} y=${this.y}width=${this.width} height=${this.height} radius=${this.radius}]`}}const Ah={};function nn(s,t,e){let r=2166136261;for(let n=0;n<t;n++)r^=s[n].uid,r=Math.imul(r,16777619),r>>>=0;return Ah[r]||Cm(s,t,r,e)}function Cm(s,t,e,r){const n={};let a=0;for(let h=0;h<r;h++){const d=h<t?s[h]:M.EMPTY.source;n[a++]=d.source,n[a++]=d.style}const l=new re(n);return Ah[e]=l,l}class Xe{constructor(t){typeof t=="number"?this.rawBinaryData=new ArrayBuffer(t):t instanceof Uint8Array?this.rawBinaryData=t.buffer:this.rawBinaryData=t,this.uint32View=new Uint32Array(this.rawBinaryData),this.float32View=new Float32Array(this.rawBinaryData),this.size=this.rawBinaryData.byteLength}get int8View(){return this._int8View||(this._int8View=new Int8Array(this.rawBinaryData)),this._int8View}get uint8View(){return this._uint8View||(this._uint8View=new Uint8Array(this.rawBinaryData)),this._uint8View}get int16View(){return this._int16View||(this._int16View=new Int16Array(this.rawBinaryData)),this._int16View}get int32View(){return this._int32View||(this._int32View=new Int32Array(this.rawBinaryData)),this._int32View}get float64View(){return this._float64Array||(this._float64Array=new Float64Array(this.rawBinaryData)),this._float64Array}get bigUint64View(){return this._bigUint64Array||(this._bigUint64Array=new BigUint64Array(this.rawBinaryData)),this._bigUint64Array}view(t){return this[`${t}View`]}destroy(){this.rawBinaryData=null,this.uint32View=null,this.float32View=null,this.uint16View=null,this._int8View=null,this._uint8View=null,this._int16View=null,this._int32View=null,this._float64Array=null,this._bigUint64Array=null}static sizeOf(t){switch(t){case"int8":case"uint8":return 1;case"int16":case"uint16":return 2;case"int32":case"uint32":case"float32":return 4;default:throw new Error(`${t} isn't a valid view type`)}}}function an(s,t){const e=s.byteLength/8|0,r=new Float64Array(s,0,e);new Float64Array(t,0,e).set(r);const a=s.byteLength-e*8;if(a>0){const l=new Uint8Array(s,e*8,a);new Uint8Array(t,e*8,a).set(l)}}const Em={normal:"normal-npm",add:"add-npm",screen:"screen-npm"};var nt=(s=>(s[s.DISABLED=0]="DISABLED",s[s.RENDERING_MASK_ADD=1]="RENDERING_MASK_ADD",s[s.MASK_ACTIVE=2]="MASK_ACTIVE",s[s.INVERSE_MASK_ACTIVE=3]="INVERSE_MASK_ACTIVE",s[s.RENDERING_MASK_REMOVE=4]="RENDERING_MASK_REMOVE",s[s.NONE=5]="NONE",s))(nt||{});function Ci(s,t){return t.alphaMode==="no-premultiply-alpha"&&Em[s]||s}const Am=["precision mediump float;","void main(void){","float test = 0.1;","%forloop%","gl_FragColor = vec4(0.0);","}"].join(`
|
|
102
|
-
`);function
|
|
103
|
-
else `),e<s-1&&(t+=`if(test == ${e}.0){}`);return t}function Ph(s,t){if(s===0)throw new Error("Invalid value of `0` passed to `checkMaxIfStatementsInShader`");const e=t.createShader(t.FRAGMENT_SHADER);try{for(;;){const r=Am.replace(/%forloop%/gi,Pm(s));if(t.shaderSource(e,r),t.compileShader(e),!t.getShaderParameter(e,t.COMPILE_STATUS))s=s/2|0;else break}}finally{t.deleteShader(e)}return s}let $e=null;function Bm(){if($e)return $e;const s=Qo();return $e=s.getParameter(s.MAX_TEXTURE_IMAGE_UNITS),$e=Ph($e,s),s.getExtension("WEBGL_lose_context")?.loseContext(),$e}class Um{constructor(){this.ids=Object.create(null),this.textures=[],this.count=0}clear(){for(let t=0;t<this.count;t++){const e=this.textures[t];this.textures[t]=null,this.ids[e.uid]=null}this.count=0}}class Mm{constructor(){this.renderPipeId="batch",this.action="startBatch",this.start=0,this.size=0,this.textures=new Um,this.blendMode="normal",this.topology="triangle-strip",this.canBundle=!0}destroy(){this.textures=null,this.gpuBindGroup=null,this.bindGroup=null,this.batcher=null}}const Ei=[];let Ur=0;Ne.register({clear:()=>{if(Ei.length>0)for(const s of Ei)s&&s.destroy();Ei.length=0,Ur=0}});function Bh(){return Ur>0?Ei[--Ur]:new Mm}function Uh(s){Ei[Ur++]=s}let Ai=0;const Mh=class Qu{constructor(t){this.uid=et("batcher"),this.dirty=!0,this.batchIndex=0,this.batches=[],this._elements=[],t={...Qu.defaultOptions,...t},t.maxTextures||(z("v8.8.0","maxTextures is a required option for Batcher now, please pass it in the options"),t.maxTextures=Bm());const{maxTextures:e,attributesInitialSize:r,indicesInitialSize:n}=t;this.attributeBuffer=new Xe(r*4),this.indexBuffer=new Uint16Array(n),this.maxTextures=e}begin(){this.elementSize=0,this.elementStart=0,this.indexSize=0,this.attributeSize=0;for(let t=0;t<this.batchIndex;t++)Uh(this.batches[t]);this.batchIndex=0,this._batchIndexStart=0,this._batchIndexSize=0,this.dirty=!0}add(t){this._elements[this.elementSize++]=t,t._indexStart=this.indexSize,t._attributeStart=this.attributeSize,t._batcher=this,this.indexSize+=t.indexSize,this.attributeSize+=t.attributeSize*this.vertexSize}checkAndUpdateTexture(t,e){const r=t._batch.textures.ids[e._source.uid];return!r&&r!==0?!1:(t._textureId=r,t.texture=e,!0)}updateElement(t){this.dirty=!0;const e=this.attributeBuffer;t.packAsQuad?this.packQuadAttributes(t,e.float32View,e.uint32View,t._attributeStart,t._textureId):this.packAttributes(t,e.float32View,e.uint32View,t._attributeStart,t._textureId)}break(t){const e=this._elements;if(!e[this.elementStart])return;let r=Bh(),n=r.textures;n.clear();const a=e[this.elementStart];let l=Ci(a.blendMode,a.texture._source),h=a.topology;this.attributeSize*4>this.attributeBuffer.size&&this._resizeAttributeBuffer(this.attributeSize*4),this.indexSize>this.indexBuffer.length&&this._resizeIndexBuffer(this.indexSize);const d=this.attributeBuffer.float32View,f=this.attributeBuffer.uint32View,m=this.indexBuffer;let g=this._batchIndexSize,y=this._batchIndexStart,x="startBatch";const o=this.maxTextures;for(let c=this.elementStart;c<this.elementSize;++c){const u=e[c];e[c]=null;const _=u.texture._source,b=Ci(u.blendMode,_),v=l!==b||h!==u.topology;if(_._batchTick===Ai&&!v){u._textureId=_._textureBindLocation,g+=u.indexSize,u.packAsQuad?(this.packQuadAttributes(u,d,f,u._attributeStart,u._textureId),this.packQuadIndex(m,u._indexStart,u._attributeStart/this.vertexSize)):(this.packAttributes(u,d,f,u._attributeStart,u._textureId),this.packIndex(u,m,u._indexStart,u._attributeStart/this.vertexSize)),u._batch=r;continue}_._batchTick=Ai,(n.count>=o||v)&&(this._finishBatch(r,y,g-y,n,l,h,t,x),x="renderBatch",y=g,l=b,h=u.topology,r=Bh(),n=r.textures,n.clear(),++Ai),u._textureId=_._textureBindLocation=n.count,n.ids[_.uid]=n.count,n.textures[n.count++]=_,u._batch=r,g+=u.indexSize,u.packAsQuad?(this.packQuadAttributes(u,d,f,u._attributeStart,u._textureId),this.packQuadIndex(m,u._indexStart,u._attributeStart/this.vertexSize)):(this.packAttributes(u,d,f,u._attributeStart,u._textureId),this.packIndex(u,m,u._indexStart,u._attributeStart/this.vertexSize))}n.count>0&&(this._finishBatch(r,y,g-y,n,l,h,t,x),y=g,++Ai),this.elementStart=this.elementSize,this._batchIndexStart=y,this._batchIndexSize=g}_finishBatch(t,e,r,n,a,l,h,d){t.gpuBindGroup=null,t.bindGroup=null,t.action=d,t.batcher=this,t.textures=n,t.blendMode=a,t.topology=l,t.start=e,t.size=r,++Ai,this.batches[this.batchIndex++]=t,h.add(t)}finish(t){this.break(t)}ensureAttributeBuffer(t){t*4<=this.attributeBuffer.size||this._resizeAttributeBuffer(t*4)}ensureIndexBuffer(t){t<=this.indexBuffer.length||this._resizeIndexBuffer(t)}_resizeAttributeBuffer(t){const e=Math.max(t,this.attributeBuffer.size*2),r=new Xe(e);an(this.attributeBuffer.rawBinaryData,r.rawBinaryData),this.attributeBuffer=r}_resizeIndexBuffer(t){const e=this.indexBuffer;let r=Math.max(t,e.length*1.5);r+=r%2;const n=r>65535?new Uint32Array(r):new Uint16Array(r);if(n.BYTES_PER_ELEMENT!==e.BYTES_PER_ELEMENT)for(let a=0;a<e.length;a++)n[a]=e[a];else an(e.buffer,n.buffer);this.indexBuffer=n}packQuadIndex(t,e,r){t[e]=r+0,t[e+1]=r+1,t[e+2]=r+2,t[e+3]=r+0,t[e+4]=r+2,t[e+5]=r+3}packIndex(t,e,r,n){const a=t.indices,l=t.indexSize,h=t.indexOffset,d=t.attributeOffset;for(let f=0;f<l;f++)e[r++]=n+a[f+h]-d}destroy(t={}){if(this.batches!==null){for(let e=0;e<this.batches.length;e++)Uh(this.batches[e]);this.batches=null,this.geometry.destroy(!0),this.geometry=null,t.shader&&(this.shader?.destroy(),this.shader=null);for(let e=0;e<this._elements.length;e++)this._elements[e]&&(this._elements[e]._batch=null);this._elements=null,this.indexBuffer=null,this.attributeBuffer.destroy(),this.attributeBuffer=null}}};Mh.defaultOptions={maxTextures:null,attributesInitialSize:4,indicesInitialSize:6};let km=Mh;var Y=(s=>(s[s.MAP_READ=1]="MAP_READ",s[s.MAP_WRITE=2]="MAP_WRITE",s[s.COPY_SRC=4]="COPY_SRC",s[s.COPY_DST=8]="COPY_DST",s[s.INDEX=16]="INDEX",s[s.VERTEX=32]="VERTEX",s[s.UNIFORM=64]="UNIFORM",s[s.STORAGE=128]="STORAGE",s[s.INDIRECT=256]="INDIRECT",s[s.QUERY_RESOLVE=512]="QUERY_RESOLVE",s[s.STATIC=1024]="STATIC",s))(Y||{});class Pt extends Tt{constructor(t){let{data:e,size:r}=t;const{usage:n,label:a,shrinkToFit:l}=t;super(),this.uid=et("buffer"),this._resourceType="buffer",this._resourceId=et("resource"),this._touched=0,this._updateID=1,this._dataInt32=null,this.shrinkToFit=!0,this.destroyed=!1,e instanceof Array&&(e=new Float32Array(e)),this._data=e,r??(r=e?.byteLength);const h=!!e;this.descriptor={size:r,usage:n,mappedAtCreation:h,label:a},this.shrinkToFit=l??!0}get data(){return this._data}set data(t){this.setDataWithSize(t,t.length,!0)}get dataInt32(){return this._dataInt32||(this._dataInt32=new Int32Array(this.data.buffer)),this._dataInt32}get static(){return!!(this.descriptor.usage&Y.STATIC)}set static(t){t?this.descriptor.usage|=Y.STATIC:this.descriptor.usage&=~Y.STATIC}setDataWithSize(t,e,r){if(this._updateID++,this._updateSize=e*t.BYTES_PER_ELEMENT,this._data===t){r&&this.emit("update",this);return}const n=this._data;if(this._data=t,this._dataInt32=null,!n||n.length!==t.length){!this.shrinkToFit&&n&&t.byteLength<n.byteLength?r&&this.emit("update",this):(this.descriptor.size=t.byteLength,this._resourceId=et("resource"),this.emit("change",this));return}r&&this.emit("update",this)}update(t){this._updateSize=t??this._updateSize,this._updateID++,this.emit("update",this)}destroy(){this.destroyed=!0,this.emit("destroy",this),this.emit("change",this),this._data=null,this.descriptor=null,this.removeAllListeners()}}function kh(s,t){if(!(s instanceof Pt)){let e=t?Y.INDEX:Y.VERTEX;s instanceof Array&&(t?(s=new Uint32Array(s),e=Y.INDEX|Y.COPY_DST):(s=new Float32Array(s),e=Y.VERTEX|Y.COPY_DST)),s=new Pt({data:s,label:t?"index-mesh-buffer":"vertex-mesh-buffer",usage:e})}return s}function Rm(s,t,e){const r=s.getAttribute(t);if(!r)return e.minX=0,e.minY=0,e.maxX=0,e.maxY=0,e;const n=r.buffer.data;let a=1/0,l=1/0,h=-1/0,d=-1/0;const f=n.BYTES_PER_ELEMENT,m=(r.offset||0)/f,g=(r.stride||8)/f;for(let y=m;y<n.length;y+=g){const x=n[y],o=n[y+1];x>h&&(h=x),o>d&&(d=o),x<a&&(a=x),o<l&&(l=o)}return e.minX=a,e.minY=l,e.maxX=h,e.maxY=d,e}function Im(s){return(s instanceof Pt||Array.isArray(s)||s.BYTES_PER_ELEMENT)&&(s={buffer:s}),s.buffer=kh(s.buffer,!1),s}class Pi extends Tt{constructor(t={}){super(),this.uid=et("geometry"),this._layoutKey=0,this.instanceCount=1,this._bounds=new dt,this._boundsDirty=!0;const{attributes:e,indexBuffer:r,topology:n}=t;if(this.buffers=[],this.attributes={},e)for(const a in e)this.addAttribute(a,e[a]);this.instanceCount=t.instanceCount??1,r&&this.addIndex(r),this.topology=n||"triangle-list"}onBufferUpdate(){this._boundsDirty=!0,this.emit("update",this)}getAttribute(t){return this.attributes[t]}getIndex(){return this.indexBuffer}getBuffer(t){return this.getAttribute(t).buffer}getSize(){for(const t in this.attributes){const e=this.attributes[t];return e.buffer.data.length/(e.stride/4||e.size)}return 0}addAttribute(t,e){const r=Im(e);this.buffers.indexOf(r.buffer)===-1&&(this.buffers.push(r.buffer),r.buffer.on("update",this.onBufferUpdate,this),r.buffer.on("change",this.onBufferUpdate,this)),this.attributes[t]=r}addIndex(t){this.indexBuffer=kh(t,!0),this.buffers.push(this.indexBuffer)}get bounds(){return this._boundsDirty?(this._boundsDirty=!1,Rm(this,"aPosition",this._bounds)):this._bounds}destroy(t=!1){this.emit("destroy",this),this.removeAllListeners(),t&&this.buffers.forEach(e=>e.destroy()),this.indexBuffer?.destroy(),this.attributes=null,this.buffers=null,this.indexBuffer=null,this._bounds=null}}const Fm=new Float32Array(1),Dm=new Uint32Array(1);class Gm extends Pi{constructor(){const e=new Pt({data:Fm,label:"attribute-batch-buffer",usage:Y.VERTEX|Y.COPY_DST,shrinkToFit:!1}),r=new Pt({data:Dm,label:"index-batch-buffer",usage:Y.INDEX|Y.COPY_DST,shrinkToFit:!1}),n=24;super({attributes:{aPosition:{buffer:e,format:"float32x2",stride:n,offset:0},aUV:{buffer:e,format:"float32x2",stride:n,offset:8},aColor:{buffer:e,format:"unorm8x4",stride:n,offset:16},aTextureIdAndRound:{buffer:e,format:"uint16x2",stride:n,offset:20}},indexBuffer:r})}}function Rh(s,t,e){if(s)for(const r in s){const n=r.toLocaleLowerCase(),a=t[n];if(a){let l=s[r];r==="header"&&(l=l.replace(/@in\s+[^;]+;\s*/g,"").replace(/@out\s+[^;]+;\s*/g,"")),e&&a.push(`//----${e}----//`),a.push(l)}else F(`${r} placement hook does not exist in shader`)}}const Om=/\{\{(.*?)\}\}/g;function Ih(s){const t={};return(s.match(Om)?.map(r=>r.replace(/[{()}]/g,""))??[]).forEach(r=>{t[r]=[]}),t}function Fh(s,t){let e;const r=/@in\s+([^;]+);/g;for(;(e=r.exec(s))!==null;)t.push(e[1])}function Dh(s,t,e=!1){const r=[];Fh(t,r),s.forEach(h=>{h.header&&Fh(h.header,r)});const n=r;e&&n.sort();const a=n.map((h,d)=>` @location(${d}) ${h},`).join(`
|
|
101
|
+
`),n++):e.push(o);continue}r+=o}return r!==""&&e.push(r),e}static canBreakWords(t,e){return e}static canBreakChars(t,e,r,n,o){return!0}static wordWrapSplit(t){return I.graphemeSegmenter(t)}static measureFont(t){if(I._fonts[t])return I._fonts[t];const e=I._context;e.font=t;const r=e.measureText(I.METRICS_STRING+I.BASELINE_SYMBOL),n={ascent:r.actualBoundingBoxAscent,descent:r.actualBoundingBoxDescent,fontSize:r.actualBoundingBoxAscent+r.actualBoundingBoxDescent};return I._fonts[t]=n,n}static clearMetrics(t=""){t?delete I._fonts[t]:I._fonts={}}static get _canvas(){if(!I.__canvas){let t;try{const e=new OffscreenCanvas(0,0);if(e.getContext("2d",rn)?.measureText)return I.__canvas=e,e;t=W.get().createCanvas()}catch{t=W.get().createCanvas()}t.width=t.height=10,I.__canvas=t}return I.__canvas}static get _context(){return I.__context||(I.__context=I._canvas.getContext("2d",rn)),I.__context}};Wt.METRICS_STRING="|ÉqÅ",Wt.BASELINE_SYMBOL="M",Wt.BASELINE_MULTIPLIER=1.4,Wt.HEIGHT_MULTIPLIER=2,Wt.graphemeSegmenter=(()=>{if(typeof Intl?.Segmenter=="function"){const s=new Intl.Segmenter;return t=>{const e=s.segment(t),r=[];let n=0;for(const o of e)r[n++]=o.segment;return r}}return s=>[...s]})(),Wt.experimentalLetterSpacing=!1,Wt._fonts={},Wt._newlines=[10,13],Wt._breakingSpaces=[9,32,8192,8193,8194,8195,8196,8197,8198,8200,8201,8202,8287,12288],Wt._measurementCache=Ch(1e3);let xt=Wt;const Eh=[{offset:0,color:"white"},{offset:1,color:"black"}],sn=class vo{constructor(...t){this.uid=et("fillGradient"),this._tick=0,this.type="linear",this.colorStops=[];let e=Em(t);e={...e.type==="radial"?vo.defaultRadialOptions:vo.defaultLinearOptions,...Jo(e)},this._textureSize=e.textureSize,this._wrapMode=e.wrapMode,e.type==="radial"?(this.center=e.center,this.outerCenter=e.outerCenter??this.center,this.innerRadius=e.innerRadius,this.outerRadius=e.outerRadius,this.scale=e.scale,this.rotation=e.rotation):(this.start=e.start,this.end=e.end),this.textureSpace=e.textureSpace,this.type=e.type,e.colorStops.forEach(n=>{this.addColorStop(n.offset,n.color)})}addColorStop(t,e){return this.colorStops.push({offset:t,color:J.shared.setValue(e).toHexa()}),this}buildLinearGradient(){if(this.texture)return;let{x:t,y:e}=this.start,{x:r,y:n}=this.end,o=r-t,l=n-e;const h=o<0||l<0;if(this._wrapMode==="clamp-to-edge"){if(o<0){const d=t;t=r,r=d,o*=-1}if(l<0){const d=e;e=n,n=d,l*=-1}}const u=this.colorStops.length?this.colorStops:Eh,f=this._textureSize,{canvas:m,context:g}=Ph(f,1),y=h?g.createLinearGradient(this._textureSize,0,0,0):g.createLinearGradient(0,0,this._textureSize,0);Ah(y,u),g.fillStyle=y,g.fillRect(0,0,f,1),this.texture=new k({source:new Se({resource:m,addressMode:this._wrapMode})});const x=Math.sqrt(o*o+l*l),a=Math.atan2(l,o),c=new M;c.scale(x/f,1),c.rotate(a),c.translate(t,e),this.textureSpace==="local"&&c.scale(f,f),this.transform=c}buildGradient(){this.texture||this._tick++,this.type==="linear"?this.buildLinearGradient():this.buildRadialGradient()}buildRadialGradient(){if(this.texture)return;const t=this.colorStops.length?this.colorStops:Eh,e=this._textureSize,{canvas:r,context:n}=Ph(e,e),{x:o,y:l}=this.center,{x:h,y:u}=this.outerCenter,f=this.innerRadius,m=this.outerRadius,g=h-m,y=u-m,x=e/(m*2),a=(o-g)*x,c=(l-y)*x,d=n.createRadialGradient(a,c,f*x,(h-g)*x,(u-y)*x,m*x);Ah(d,t),n.fillStyle=t[t.length-1].color,n.fillRect(0,0,e,e),n.fillStyle=d,n.translate(a,c),n.rotate(this.rotation),n.scale(1,this.scale),n.translate(-a,-c),n.fillRect(0,0,e,e),this.texture=new k({source:new Se({resource:r,addressMode:this._wrapMode})});const p=new M;p.scale(1/x,1/x),p.translate(g,y),this.textureSpace==="local"&&p.scale(e,e),this.transform=p}destroy(){this.texture?.destroy(!0),this.texture=null,this.transform=null,this.colorStops=[],this.start=null,this.end=null,this.center=null,this.outerCenter=null}get styleKey(){return`fill-gradient-${this.uid}-${this._tick}`}};sn.defaultLinearOptions={start:{x:0,y:0},end:{x:0,y:1},colorStops:[],textureSpace:"local",type:"linear",textureSize:256,wrapMode:"clamp-to-edge"},sn.defaultRadialOptions={center:{x:.5,y:.5},innerRadius:0,outerRadius:.5,colorStops:[],scale:1,textureSpace:"local",type:"radial",textureSize:256,wrapMode:"clamp-to-edge"};let Vt=sn;function Ah(s,t){for(let e=0;e<t.length;e++){const r=t[e];s.addColorStop(r.offset,r.color)}}function Ph(s,t){const e=W.get().createCanvas(s,t),r=e.getContext("2d");return{canvas:e,context:r}}function Em(s){let t=s[0]??{};return(typeof t=="number"||s[1])&&(z("8.5.2","use options object instead"),t={type:"linear",start:{x:s[0],y:s[1]},end:{x:s[2],y:s[3]},textureSpace:s[4],textureSize:s[5]??Vt.defaultLinearOptions.textureSize}),t}const Bh={repeat:{addressModeU:"repeat",addressModeV:"repeat"},"repeat-x":{addressModeU:"repeat",addressModeV:"clamp-to-edge"},"repeat-y":{addressModeU:"clamp-to-edge",addressModeV:"repeat"},"no-repeat":{addressModeU:"clamp-to-edge",addressModeV:"clamp-to-edge"}};class Br{constructor(t,e){this.uid=et("fillPattern"),this._tick=0,this.transform=new M,this.texture=t,this.transform.scale(1/t.frame.width,1/t.frame.height),e&&(t.source.style.addressModeU=Bh[e].addressModeU,t.source.style.addressModeV=Bh[e].addressModeV)}setTransform(t){const e=this.texture;this.transform.copyFrom(t),this.transform.invert(),this.transform.scale(1/e.frame.width,1/e.frame.height),this._tick++}get texture(){return this._texture}set texture(t){this._texture!==t&&(this._texture=t,this._tick++)}get styleKey(){return`fill-pattern-${this.uid}-${this._tick}`}destroy(){this.texture.destroy(!0),this.texture=null}}var nn,Uh;function Am(){if(Uh)return nn;Uh=1,nn=e;var s={a:7,c:6,h:1,l:2,m:2,q:4,s:4,t:2,v:1,z:0},t=/([astvzqmhlc])([^astvzqmhlc]*)/ig;function e(o){var l=[];return o.replace(t,function(h,u,f){var m=u.toLowerCase();for(f=n(f),m=="m"&&f.length>2&&(l.push([u].concat(f.splice(0,2))),m="l",u=u=="m"?"l":"L");;){if(f.length==s[m])return f.unshift(u),l.push(f);if(f.length<s[m])throw new Error("malformed path data");l.push([u].concat(f.splice(0,s[m])))}}),l}var r=/-?[0-9]*\.?[0-9]+(?:e[-+]?\d+)?/ig;function n(o){var l=o.match(r);return l?l.map(Number):[]}return nn}var Pm=Am();const Bm=ye(Pm);function Um(s,t){const e=Bm(s),r=[];let n=null,o=0,l=0;for(let h=0;h<e.length;h++){const u=e[h],f=u[0],m=u;switch(f){case"M":o=m[1],l=m[2],t.moveTo(o,l);break;case"m":o+=m[1],l+=m[2],t.moveTo(o,l);break;case"H":o=m[1],t.lineTo(o,l);break;case"h":o+=m[1],t.lineTo(o,l);break;case"V":l=m[1],t.lineTo(o,l);break;case"v":l+=m[1],t.lineTo(o,l);break;case"L":o=m[1],l=m[2],t.lineTo(o,l);break;case"l":o+=m[1],l+=m[2],t.lineTo(o,l);break;case"C":o=m[5],l=m[6],t.bezierCurveTo(m[1],m[2],m[3],m[4],o,l);break;case"c":t.bezierCurveTo(o+m[1],l+m[2],o+m[3],l+m[4],o+m[5],l+m[6]),o+=m[5],l+=m[6];break;case"S":o=m[3],l=m[4],t.bezierCurveToShort(m[1],m[2],o,l);break;case"s":t.bezierCurveToShort(o+m[1],l+m[2],o+m[3],l+m[4]),o+=m[3],l+=m[4];break;case"Q":o=m[3],l=m[4],t.quadraticCurveTo(m[1],m[2],o,l);break;case"q":t.quadraticCurveTo(o+m[1],l+m[2],o+m[3],l+m[4]),o+=m[3],l+=m[4];break;case"T":o=m[1],l=m[2],t.quadraticCurveToShort(o,l);break;case"t":o+=m[1],l+=m[2],t.quadraticCurveToShort(o,l);break;case"A":o=m[6],l=m[7],t.arcToSvg(m[1],m[2],m[3],m[4],m[5],o,l);break;case"a":o+=m[6],l+=m[7],t.arcToSvg(m[1],m[2],m[3],m[4],m[5],o,l);break;case"Z":case"z":t.closePath(),r.length>0&&(n=r.pop(),n?(o=n.startX,l=n.startY):(o=0,l=0)),n=null;break;default:F(`Unknown SVG path command: ${f}`)}f!=="Z"&&f!=="z"&&n===null&&(n={startX:o,startY:l},r.push(n))}return t}class Ur{constructor(t=0,e=0,r=0){this.type="circle",this.x=t,this.y=e,this.radius=r}clone(){return new Ur(this.x,this.y,this.radius)}contains(t,e){if(this.radius<=0)return!1;const r=this.radius*this.radius;let n=this.x-t,o=this.y-e;return n*=n,o*=o,n+o<=r}strokeContains(t,e,r,n=.5){if(this.radius===0)return!1;const o=this.x-t,l=this.y-e,h=this.radius,u=(1-n)*r,f=Math.sqrt(o*o+l*l);return f<=h+u&&f>h-(r-u)}getBounds(t){return t||(t=new G),t.x=this.x-this.radius,t.y=this.y-this.radius,t.width=this.radius*2,t.height=this.radius*2,t}copyFrom(t){return this.x=t.x,this.y=t.y,this.radius=t.radius,this}copyTo(t){return t.copyFrom(this),t}toString(){return`[pixi.js/math:Circle x=${this.x} y=${this.y} radius=${this.radius}]`}}class on{constructor(t=0,e=0,r=0,n=0){this.type="ellipse",this.x=t,this.y=e,this.halfWidth=r,this.halfHeight=n}clone(){return new on(this.x,this.y,this.halfWidth,this.halfHeight)}contains(t,e){if(this.halfWidth<=0||this.halfHeight<=0)return!1;let r=(t-this.x)/this.halfWidth,n=(e-this.y)/this.halfHeight;return r*=r,n*=n,r+n<=1}strokeContains(t,e,r,n=.5){const{halfWidth:o,halfHeight:l}=this;if(o<=0||l<=0)return!1;const h=r*(1-n),u=r-h,f=o-u,m=l-u,g=o+h,y=l+h,x=t-this.x,a=e-this.y,c=x*x/(f*f)+a*a/(m*m),d=x*x/(g*g)+a*a/(y*y);return c>1&&d<=1}getBounds(t){return t||(t=new G),t.x=this.x-this.halfWidth,t.y=this.y-this.halfHeight,t.width=this.halfWidth*2,t.height=this.halfHeight*2,t}copyFrom(t){return this.x=t.x,this.y=t.y,this.halfWidth=t.halfWidth,this.halfHeight=t.halfHeight,this}copyTo(t){return t.copyFrom(this),t}toString(){return`[pixi.js/math:Ellipse x=${this.x} y=${this.y} halfWidth=${this.halfWidth} halfHeight=${this.halfHeight}]`}}function km(s,t,e,r,n,o){const l=s-e,h=t-r,u=n-e,f=o-r,m=l*u+h*f,g=u*u+f*f;let y=-1;g!==0&&(y=m/g);let x,a;y<0?(x=e,a=r):y>1?(x=n,a=o):(x=e+y*u,a=r+y*f);const c=s-x,d=t-a;return c*c+d*d}let Mm,Rm;class Ci{constructor(...t){this.type="polygon";let e=Array.isArray(t[0])?t[0]:t;if(typeof e[0]!="number"){const r=[];for(let n=0,o=e.length;n<o;n++)r.push(e[n].x,e[n].y);e=r}this.points=e,this.closePath=!0}isClockwise(){let t=0;const e=this.points,r=e.length;for(let n=0;n<r;n+=2){const o=e[n],l=e[n+1],h=e[(n+2)%r],u=e[(n+3)%r];t+=(h-o)*(u+l)}return t<0}containsPolygon(t){const e=this.getBounds(Mm),r=t.getBounds(Rm);if(!e.containsRect(r))return!1;const n=t.points;for(let o=0;o<n.length;o+=2){const l=n[o],h=n[o+1];if(!this.contains(l,h))return!1}return!0}clone(){const t=this.points.slice(),e=new Ci(t);return e.closePath=this.closePath,e}contains(t,e){let r=!1;const n=this.points.length/2;for(let o=0,l=n-1;o<n;l=o++){const h=this.points[o*2],u=this.points[o*2+1],f=this.points[l*2],m=this.points[l*2+1];u>e!=m>e&&t<(f-h)*((e-u)/(m-u))+h&&(r=!r)}return r}strokeContains(t,e,r,n=.5){const o=r*r,l=o*(1-n),h=o-l,{points:u}=this,f=u.length-(this.closePath?0:2);for(let m=0;m<f;m+=2){const g=u[m],y=u[m+1],x=u[(m+2)%u.length],a=u[(m+3)%u.length],c=km(t,e,g,y,x,a),d=Math.sign((x-g)*(e-y)-(a-y)*(t-g));if(c<=(d<0?h:l))return!0}return!1}getBounds(t){t||(t=new G);const e=this.points;let r=1/0,n=-1/0,o=1/0,l=-1/0;for(let h=0,u=e.length;h<u;h+=2){const f=e[h],m=e[h+1];r=f<r?f:r,n=f>n?f:n,o=m<o?m:o,l=m>l?m:l}return t.x=r,t.width=n-r,t.y=o,t.height=l-o,t}copyFrom(t){return this.points=t.points.slice(),this.closePath=t.closePath,this}copyTo(t){return t.copyFrom(this),t}toString(){return`[pixi.js/math:PolygoncloseStroke=${this.closePath}points=${this.points.reduce((t,e)=>`${t}, ${e}`,"")}]`}get lastX(){return this.points[this.points.length-2]}get lastY(){return this.points[this.points.length-1]}get x(){return z("8.11.0","Polygon.lastX is deprecated, please use Polygon.lastX instead."),this.points[this.points.length-2]}get y(){return z("8.11.0","Polygon.y is deprecated, please use Polygon.lastY instead."),this.points[this.points.length-1]}get startX(){return this.points[0]}get startY(){return this.points[1]}}const kr=(s,t,e,r,n,o,l)=>{const h=s-e,u=t-r,f=Math.sqrt(h*h+u*u);return f>=n-o&&f<=n+l};class an{constructor(t=0,e=0,r=0,n=0,o=20){this.type="roundedRectangle",this.x=t,this.y=e,this.width=r,this.height=n,this.radius=o}getBounds(t){return t||(t=new G),t.x=this.x,t.y=this.y,t.width=this.width,t.height=this.height,t}clone(){return new an(this.x,this.y,this.width,this.height,this.radius)}copyFrom(t){return this.x=t.x,this.y=t.y,this.width=t.width,this.height=t.height,this}copyTo(t){return t.copyFrom(this),t}contains(t,e){if(this.width<=0||this.height<=0)return!1;if(t>=this.x&&t<=this.x+this.width&&e>=this.y&&e<=this.y+this.height){const r=Math.max(0,Math.min(this.radius,Math.min(this.width,this.height)/2));if(e>=this.y+r&&e<=this.y+this.height-r||t>=this.x+r&&t<=this.x+this.width-r)return!0;let n=t-(this.x+r),o=e-(this.y+r);const l=r*r;if(n*n+o*o<=l||(n=t-(this.x+this.width-r),n*n+o*o<=l)||(o=e-(this.y+this.height-r),n*n+o*o<=l)||(n=t-(this.x+r),n*n+o*o<=l))return!0}return!1}strokeContains(t,e,r,n=.5){const{x:o,y:l,width:h,height:u,radius:f}=this,m=r*(1-n),g=r-m,y=o+f,x=l+f,a=h-f*2,c=u-f*2,d=o+h,p=l+u;return(t>=o-m&&t<=o+g||t>=d-g&&t<=d+m)&&e>=x&&e<=x+c||(e>=l-m&&e<=l+g||e>=p-g&&e<=p+m)&&t>=y&&t<=y+a?!0:t<y&&e<x&&kr(t,e,y,x,f,g,m)||t>d-f&&e<x&&kr(t,e,d-f,x,f,g,m)||t>d-f&&e>p-f&&kr(t,e,d-f,p-f,f,g,m)||t<y&&e>p-f&&kr(t,e,y,p-f,f,g,m)}toString(){return`[pixi.js/math:RoundedRectangle x=${this.x} y=${this.y}width=${this.width} height=${this.height} radius=${this.radius}]`}}const kh={};function hn(s,t,e){let r=2166136261;for(let n=0;n<t;n++)r^=s[n].uid,r=Math.imul(r,16777619),r>>>=0;return kh[r]||Im(s,t,r,e)}function Im(s,t,e,r){const n={};let o=0;for(let h=0;h<r;h++){const u=h<t?s[h]:k.EMPTY.source;n[o++]=u.source,n[o++]=u.style}const l=new ne(n);return kh[e]=l,l}class $e{constructor(t){typeof t=="number"?this.rawBinaryData=new ArrayBuffer(t):t instanceof Uint8Array?this.rawBinaryData=t.buffer:this.rawBinaryData=t,this.uint32View=new Uint32Array(this.rawBinaryData),this.float32View=new Float32Array(this.rawBinaryData),this.size=this.rawBinaryData.byteLength}get int8View(){return this._int8View||(this._int8View=new Int8Array(this.rawBinaryData)),this._int8View}get uint8View(){return this._uint8View||(this._uint8View=new Uint8Array(this.rawBinaryData)),this._uint8View}get int16View(){return this._int16View||(this._int16View=new Int16Array(this.rawBinaryData)),this._int16View}get int32View(){return this._int32View||(this._int32View=new Int32Array(this.rawBinaryData)),this._int32View}get float64View(){return this._float64Array||(this._float64Array=new Float64Array(this.rawBinaryData)),this._float64Array}get bigUint64View(){return this._bigUint64Array||(this._bigUint64Array=new BigUint64Array(this.rawBinaryData)),this._bigUint64Array}view(t){return this[`${t}View`]}destroy(){this.rawBinaryData=null,this.uint32View=null,this.float32View=null,this.uint16View=null,this._int8View=null,this._uint8View=null,this._int16View=null,this._int32View=null,this._float64Array=null,this._bigUint64Array=null}static sizeOf(t){switch(t){case"int8":case"uint8":return 1;case"int16":case"uint16":return 2;case"int32":case"uint32":case"float32":return 4;default:throw new Error(`${t} isn't a valid view type`)}}}function ln(s,t){const e=s.byteLength/8|0,r=new Float64Array(s,0,e);new Float64Array(t,0,e).set(r);const o=s.byteLength-e*8;if(o>0){const l=new Uint8Array(s,e*8,o);new Uint8Array(t,e*8,o).set(l)}}const Fm={normal:"normal-npm",add:"add-npm",screen:"screen-npm"};var ot=(s=>(s[s.DISABLED=0]="DISABLED",s[s.RENDERING_MASK_ADD=1]="RENDERING_MASK_ADD",s[s.MASK_ACTIVE=2]="MASK_ACTIVE",s[s.INVERSE_MASK_ACTIVE=3]="INVERSE_MASK_ACTIVE",s[s.RENDERING_MASK_REMOVE=4]="RENDERING_MASK_REMOVE",s[s.NONE=5]="NONE",s))(ot||{});function Ei(s,t){return t.alphaMode==="no-premultiply-alpha"&&Fm[s]||s}const Dm=["precision mediump float;","void main(void){","float test = 0.1;","%forloop%","gl_FragColor = vec4(0.0);","}"].join(`
|
|
102
|
+
`);function Om(s){let t="";for(let e=0;e<s;++e)e>0&&(t+=`
|
|
103
|
+
else `),e<s-1&&(t+=`if(test == ${e}.0){}`);return t}function Mh(s,t){if(s===0)throw new Error("Invalid value of `0` passed to `checkMaxIfStatementsInShader`");const e=t.createShader(t.FRAGMENT_SHADER);try{for(;;){const r=Dm.replace(/%forloop%/gi,Om(s));if(t.shaderSource(e,r),t.compileShader(e),!t.getShaderParameter(e,t.COMPILE_STATUS))s=s/2|0;else break}}finally{t.deleteShader(e)}return s}let Ke=null;function Gm(){if(Ke)return Ke;const s=ih();return Ke=s.getParameter(s.MAX_TEXTURE_IMAGE_UNITS),Ke=Mh(Ke,s),s.getExtension("WEBGL_lose_context")?.loseContext(),Ke}class Lm{constructor(){this.ids=Object.create(null),this.textures=[],this.count=0}clear(){for(let t=0;t<this.count;t++){const e=this.textures[t];this.textures[t]=null,this.ids[e.uid]=null}this.count=0}}class zm{constructor(){this.renderPipeId="batch",this.action="startBatch",this.start=0,this.size=0,this.textures=new Lm,this.blendMode="normal",this.topology="triangle-strip",this.canBundle=!0}destroy(){this.textures=null,this.gpuBindGroup=null,this.bindGroup=null,this.batcher=null}}const Ai=[];let Mr=0;He.register({clear:()=>{if(Ai.length>0)for(const s of Ai)s&&s.destroy();Ai.length=0,Mr=0}});function Rh(){return Mr>0?Ai[--Mr]:new zm}function Ih(s){Ai[Mr++]=s}let Pi=0;const Fh=class iu{constructor(t){this.uid=et("batcher"),this.dirty=!0,this.batchIndex=0,this.batches=[],this._elements=[],t={...iu.defaultOptions,...t},t.maxTextures||(z("v8.8.0","maxTextures is a required option for Batcher now, please pass it in the options"),t.maxTextures=Gm());const{maxTextures:e,attributesInitialSize:r,indicesInitialSize:n}=t;this.attributeBuffer=new $e(r*4),this.indexBuffer=new Uint16Array(n),this.maxTextures=e}begin(){this.elementSize=0,this.elementStart=0,this.indexSize=0,this.attributeSize=0;for(let t=0;t<this.batchIndex;t++)Ih(this.batches[t]);this.batchIndex=0,this._batchIndexStart=0,this._batchIndexSize=0,this.dirty=!0}add(t){this._elements[this.elementSize++]=t,t._indexStart=this.indexSize,t._attributeStart=this.attributeSize,t._batcher=this,this.indexSize+=t.indexSize,this.attributeSize+=t.attributeSize*this.vertexSize}checkAndUpdateTexture(t,e){const r=t._batch.textures.ids[e._source.uid];return!r&&r!==0?!1:(t._textureId=r,t.texture=e,!0)}updateElement(t){this.dirty=!0;const e=this.attributeBuffer;t.packAsQuad?this.packQuadAttributes(t,e.float32View,e.uint32View,t._attributeStart,t._textureId):this.packAttributes(t,e.float32View,e.uint32View,t._attributeStart,t._textureId)}break(t){const e=this._elements;if(!e[this.elementStart])return;let r=Rh(),n=r.textures;n.clear();const o=e[this.elementStart];let l=Ei(o.blendMode,o.texture._source),h=o.topology;this.attributeSize*4>this.attributeBuffer.size&&this._resizeAttributeBuffer(this.attributeSize*4),this.indexSize>this.indexBuffer.length&&this._resizeIndexBuffer(this.indexSize);const u=this.attributeBuffer.float32View,f=this.attributeBuffer.uint32View,m=this.indexBuffer;let g=this._batchIndexSize,y=this._batchIndexStart,x="startBatch";const a=this.maxTextures;for(let c=this.elementStart;c<this.elementSize;++c){const d=e[c];e[c]=null;const _=d.texture._source,b=Ei(d.blendMode,_),v=l!==b||h!==d.topology;if(_._batchTick===Pi&&!v){d._textureId=_._textureBindLocation,g+=d.indexSize,d.packAsQuad?(this.packQuadAttributes(d,u,f,d._attributeStart,d._textureId),this.packQuadIndex(m,d._indexStart,d._attributeStart/this.vertexSize)):(this.packAttributes(d,u,f,d._attributeStart,d._textureId),this.packIndex(d,m,d._indexStart,d._attributeStart/this.vertexSize)),d._batch=r;continue}_._batchTick=Pi,(n.count>=a||v)&&(this._finishBatch(r,y,g-y,n,l,h,t,x),x="renderBatch",y=g,l=b,h=d.topology,r=Rh(),n=r.textures,n.clear(),++Pi),d._textureId=_._textureBindLocation=n.count,n.ids[_.uid]=n.count,n.textures[n.count++]=_,d._batch=r,g+=d.indexSize,d.packAsQuad?(this.packQuadAttributes(d,u,f,d._attributeStart,d._textureId),this.packQuadIndex(m,d._indexStart,d._attributeStart/this.vertexSize)):(this.packAttributes(d,u,f,d._attributeStart,d._textureId),this.packIndex(d,m,d._indexStart,d._attributeStart/this.vertexSize))}n.count>0&&(this._finishBatch(r,y,g-y,n,l,h,t,x),y=g,++Pi),this.elementStart=this.elementSize,this._batchIndexStart=y,this._batchIndexSize=g}_finishBatch(t,e,r,n,o,l,h,u){t.gpuBindGroup=null,t.bindGroup=null,t.action=u,t.batcher=this,t.textures=n,t.blendMode=o,t.topology=l,t.start=e,t.size=r,++Pi,this.batches[this.batchIndex++]=t,h.add(t)}finish(t){this.break(t)}ensureAttributeBuffer(t){t*4<=this.attributeBuffer.size||this._resizeAttributeBuffer(t*4)}ensureIndexBuffer(t){t<=this.indexBuffer.length||this._resizeIndexBuffer(t)}_resizeAttributeBuffer(t){const e=Math.max(t,this.attributeBuffer.size*2),r=new $e(e);ln(this.attributeBuffer.rawBinaryData,r.rawBinaryData),this.attributeBuffer=r}_resizeIndexBuffer(t){const e=this.indexBuffer;let r=Math.max(t,e.length*1.5);r+=r%2;const n=r>65535?new Uint32Array(r):new Uint16Array(r);if(n.BYTES_PER_ELEMENT!==e.BYTES_PER_ELEMENT)for(let o=0;o<e.length;o++)n[o]=e[o];else ln(e.buffer,n.buffer);this.indexBuffer=n}packQuadIndex(t,e,r){t[e]=r+0,t[e+1]=r+1,t[e+2]=r+2,t[e+3]=r+0,t[e+4]=r+2,t[e+5]=r+3}packIndex(t,e,r,n){const o=t.indices,l=t.indexSize,h=t.indexOffset,u=t.attributeOffset;for(let f=0;f<l;f++)e[r++]=n+o[f+h]-u}destroy(t={}){if(this.batches!==null){for(let e=0;e<this.batches.length;e++)Ih(this.batches[e]);this.batches=null,this.geometry.destroy(!0),this.geometry=null,t.shader&&(this.shader?.destroy(),this.shader=null);for(let e=0;e<this._elements.length;e++)this._elements[e]&&(this._elements[e]._batch=null);this._elements=null,this.indexBuffer=null,this.attributeBuffer.destroy(),this.attributeBuffer=null}}};Fh.defaultOptions={maxTextures:null,attributesInitialSize:4,indicesInitialSize:6};let Nm=Fh;var Y=(s=>(s[s.MAP_READ=1]="MAP_READ",s[s.MAP_WRITE=2]="MAP_WRITE",s[s.COPY_SRC=4]="COPY_SRC",s[s.COPY_DST=8]="COPY_DST",s[s.INDEX=16]="INDEX",s[s.VERTEX=32]="VERTEX",s[s.UNIFORM=64]="UNIFORM",s[s.STORAGE=128]="STORAGE",s[s.INDIRECT=256]="INDIRECT",s[s.QUERY_RESOLVE=512]="QUERY_RESOLVE",s[s.STATIC=1024]="STATIC",s))(Y||{});class Bt extends Ct{constructor(t){let{data:e,size:r}=t;const{usage:n,label:o,shrinkToFit:l}=t;super(),this.uid=et("buffer"),this._resourceType="buffer",this._resourceId=et("resource"),this._touched=0,this._updateID=1,this._dataInt32=null,this.shrinkToFit=!0,this.destroyed=!1,e instanceof Array&&(e=new Float32Array(e)),this._data=e,r??(r=e?.byteLength);const h=!!e;this.descriptor={size:r,usage:n,mappedAtCreation:h,label:o},this.shrinkToFit=l??!0}get data(){return this._data}set data(t){this.setDataWithSize(t,t.length,!0)}get dataInt32(){return this._dataInt32||(this._dataInt32=new Int32Array(this.data.buffer)),this._dataInt32}get static(){return!!(this.descriptor.usage&Y.STATIC)}set static(t){t?this.descriptor.usage|=Y.STATIC:this.descriptor.usage&=~Y.STATIC}setDataWithSize(t,e,r){if(this._updateID++,this._updateSize=e*t.BYTES_PER_ELEMENT,this._data===t){r&&this.emit("update",this);return}const n=this._data;if(this._data=t,this._dataInt32=null,!n||n.length!==t.length){!this.shrinkToFit&&n&&t.byteLength<n.byteLength?r&&this.emit("update",this):(this.descriptor.size=t.byteLength,this._resourceId=et("resource"),this.emit("change",this));return}r&&this.emit("update",this)}update(t){this._updateSize=t??this._updateSize,this._updateID++,this.emit("update",this)}destroy(){this.destroyed=!0,this.emit("destroy",this),this.emit("change",this),this._data=null,this.descriptor=null,this.removeAllListeners()}}function Dh(s,t){if(!(s instanceof Bt)){let e=t?Y.INDEX:Y.VERTEX;s instanceof Array&&(t?(s=new Uint32Array(s),e=Y.INDEX|Y.COPY_DST):(s=new Float32Array(s),e=Y.VERTEX|Y.COPY_DST)),s=new Bt({data:s,label:t?"index-mesh-buffer":"vertex-mesh-buffer",usage:e})}return s}function Hm(s,t,e){const r=s.getAttribute(t);if(!r)return e.minX=0,e.minY=0,e.maxX=0,e.maxY=0,e;const n=r.buffer.data;let o=1/0,l=1/0,h=-1/0,u=-1/0;const f=n.BYTES_PER_ELEMENT,m=(r.offset||0)/f,g=(r.stride||8)/f;for(let y=m;y<n.length;y+=g){const x=n[y],a=n[y+1];x>h&&(h=x),a>u&&(u=a),x<o&&(o=x),a<l&&(l=a)}return e.minX=o,e.minY=l,e.maxX=h,e.maxY=u,e}function Wm(s){return(s instanceof Bt||Array.isArray(s)||s.BYTES_PER_ELEMENT)&&(s={buffer:s}),s.buffer=Dh(s.buffer,!1),s}class Bi extends Ct{constructor(t={}){super(),this.uid=et("geometry"),this._layoutKey=0,this.instanceCount=1,this._bounds=new ut,this._boundsDirty=!0;const{attributes:e,indexBuffer:r,topology:n}=t;if(this.buffers=[],this.attributes={},e)for(const o in e)this.addAttribute(o,e[o]);this.instanceCount=t.instanceCount??1,r&&this.addIndex(r),this.topology=n||"triangle-list"}onBufferUpdate(){this._boundsDirty=!0,this.emit("update",this)}getAttribute(t){return this.attributes[t]}getIndex(){return this.indexBuffer}getBuffer(t){return this.getAttribute(t).buffer}getSize(){for(const t in this.attributes){const e=this.attributes[t];return e.buffer.data.length/(e.stride/4||e.size)}return 0}addAttribute(t,e){const r=Wm(e);this.buffers.indexOf(r.buffer)===-1&&(this.buffers.push(r.buffer),r.buffer.on("update",this.onBufferUpdate,this),r.buffer.on("change",this.onBufferUpdate,this)),this.attributes[t]=r}addIndex(t){this.indexBuffer=Dh(t,!0),this.buffers.push(this.indexBuffer)}get bounds(){return this._boundsDirty?(this._boundsDirty=!1,Hm(this,"aPosition",this._bounds)):this._bounds}destroy(t=!1){this.emit("destroy",this),this.removeAllListeners(),t&&this.buffers.forEach(e=>e.destroy()),this.indexBuffer?.destroy(),this.attributes=null,this.buffers=null,this.indexBuffer=null,this._bounds=null}}const Vm=new Float32Array(1),Ym=new Uint32Array(1);class Xm extends Bi{constructor(){const e=new Bt({data:Vm,label:"attribute-batch-buffer",usage:Y.VERTEX|Y.COPY_DST,shrinkToFit:!1}),r=new Bt({data:Ym,label:"index-batch-buffer",usage:Y.INDEX|Y.COPY_DST,shrinkToFit:!1}),n=24;super({attributes:{aPosition:{buffer:e,format:"float32x2",stride:n,offset:0},aUV:{buffer:e,format:"float32x2",stride:n,offset:8},aColor:{buffer:e,format:"unorm8x4",stride:n,offset:16},aTextureIdAndRound:{buffer:e,format:"uint16x2",stride:n,offset:20}},indexBuffer:r})}}function Oh(s,t,e){if(s)for(const r in s){const n=r.toLocaleLowerCase(),o=t[n];if(o){let l=s[r];r==="header"&&(l=l.replace(/@in\s+[^;]+;\s*/g,"").replace(/@out\s+[^;]+;\s*/g,"")),e&&o.push(`//----${e}----//`),o.push(l)}else F(`${r} placement hook does not exist in shader`)}}const $m=/\{\{(.*?)\}\}/g;function Gh(s){const t={};return(s.match($m)?.map(r=>r.replace(/[{()}]/g,""))??[]).forEach(r=>{t[r]=[]}),t}function Lh(s,t){let e;const r=/@in\s+([^;]+);/g;for(;(e=r.exec(s))!==null;)t.push(e[1])}function zh(s,t,e=!1){const r=[];Lh(t,r),s.forEach(h=>{h.header&&Lh(h.header,r)});const n=r;e&&n.sort();const o=n.map((h,u)=>` @location(${u}) ${h},`).join(`
|
|
104
104
|
`);let l=t.replace(/@in\s+[^;]+;\s*/g,"");return l=l.replace("{{in}}",`
|
|
105
|
-
${
|
|
106
|
-
`),l}function
|
|
107
|
-
`),
|
|
105
|
+
${o}
|
|
106
|
+
`),l}function Nh(s,t){let e;const r=/@out\s+([^;]+);/g;for(;(e=r.exec(s))!==null;)t.push(e[1])}function Km(s){const e=/\b(\w+)\s*:/g.exec(s);return e?e[1]:""}function jm(s){const t=/@.*?\s+/g;return s.replace(t,"")}function qm(s,t){const e=[];Nh(t,e),s.forEach(u=>{u.header&&Nh(u.header,e)});let r=0;const n=e.sort().map(u=>u.indexOf("builtin")>-1?u:`@location(${r++}) ${u}`).join(`,
|
|
107
|
+
`),o=e.sort().map(u=>` var ${jm(u)};`).join(`
|
|
108
108
|
`),l=`return VSOutput(
|
|
109
|
-
${e.sort().map(
|
|
109
|
+
${e.sort().map(u=>` ${Km(u)}`).join(`,
|
|
110
110
|
`)});`;let h=t.replace(/@out\s+[^;]+;\s*/g,"");return h=h.replace("{{struct}}",`
|
|
111
111
|
${n}
|
|
112
112
|
`),h=h.replace("{{start}}",`
|
|
113
|
-
${
|
|
113
|
+
${o}
|
|
114
114
|
`),h=h.replace("{{return}}",`
|
|
115
115
|
${l}
|
|
116
|
-
`),h}function
|
|
116
|
+
`),h}function Hh(s,t){let e=s;for(const r in t){const n=t[r];n.join(`
|
|
117
117
|
`).length?e=e.replace(`{{${r}}}`,`//-----${r} START-----//
|
|
118
118
|
${n.join(`
|
|
119
119
|
`)}
|
|
120
|
-
//----${r} FINISH----//`):e=e.replace(`{{${r}}}`,"")}return e}const
|
|
120
|
+
//----${r} FINISH----//`):e=e.replace(`{{${r}}}`,"")}return e}const me=Object.create(null),cn=new Map;let Zm=0;function Qm({template:s,bits:t}){const e=Wh(s,t);if(me[e])return me[e];const{vertex:r,fragment:n}=tg(s,t);return me[e]=Vh(r,n,t),me[e]}function Jm({template:s,bits:t}){const e=Wh(s,t);return me[e]||(me[e]=Vh(s.vertex,s.fragment,t)),me[e]}function tg(s,t){const e=t.map(l=>l.vertex).filter(l=>!!l),r=t.map(l=>l.fragment).filter(l=>!!l);let n=zh(e,s.vertex,!0);n=qm(e,n);const o=zh(r,s.fragment,!0);return{vertex:n,fragment:o}}function Wh(s,t){return t.map(e=>(cn.has(e)||cn.set(e,Zm++),cn.get(e))).sort((e,r)=>e-r).join("-")+s.vertex+s.fragment}function Vh(s,t,e){const r=Gh(s),n=Gh(t);return e.forEach(o=>{Oh(o.vertex,r,o.name),Oh(o.fragment,n,o.name)}),{vertex:Hh(s,r),fragment:Hh(t,n)}}const eg=`
|
|
121
121
|
@in aPosition: vec2<f32>;
|
|
122
122
|
@in aUV: vec2<f32>;
|
|
123
123
|
|
|
@@ -161,7 +161,7 @@ ${n.join(`
|
|
|
161
161
|
|
|
162
162
|
{{return}}
|
|
163
163
|
};
|
|
164
|
-
|
|
164
|
+
`,ig=`
|
|
165
165
|
@in vUV : vec2<f32>;
|
|
166
166
|
@in vColor : vec4<f32>;
|
|
167
167
|
|
|
@@ -184,7 +184,7 @@ ${n.join(`
|
|
|
184
184
|
|
|
185
185
|
return finalColor;
|
|
186
186
|
};
|
|
187
|
-
`,
|
|
187
|
+
`,rg=`
|
|
188
188
|
in vec2 aPosition;
|
|
189
189
|
in vec2 aUV;
|
|
190
190
|
|
|
@@ -220,7 +220,7 @@ ${n.join(`
|
|
|
220
220
|
|
|
221
221
|
{{end}}
|
|
222
222
|
}
|
|
223
|
-
`,
|
|
223
|
+
`,sg=`
|
|
224
224
|
|
|
225
225
|
in vec4 vColor;
|
|
226
226
|
in vec2 vUV;
|
|
@@ -241,7 +241,7 @@ ${n.join(`
|
|
|
241
241
|
|
|
242
242
|
{{end}}
|
|
243
243
|
}
|
|
244
|
-
`,
|
|
244
|
+
`,ng={name:"global-uniforms-bit",vertex:{header:`
|
|
245
245
|
struct GlobalUniforms {
|
|
246
246
|
uProjectionMatrix:mat3x3<f32>,
|
|
247
247
|
uWorldTransformMatrix:mat3x3<f32>,
|
|
@@ -250,22 +250,22 @@ ${n.join(`
|
|
|
250
250
|
}
|
|
251
251
|
|
|
252
252
|
@group(0) @binding(0) var<uniform> globalUniforms : GlobalUniforms;
|
|
253
|
-
`}},
|
|
253
|
+
`}},og={name:"global-uniforms-bit",vertex:{header:`
|
|
254
254
|
uniform mat3 uProjectionMatrix;
|
|
255
255
|
uniform mat3 uWorldTransformMatrix;
|
|
256
256
|
uniform vec4 uWorldColorAlpha;
|
|
257
257
|
uniform vec2 uResolution;
|
|
258
|
-
`}};function
|
|
258
|
+
`}};function Ui({bits:s,name:t}){const e=Qm({template:{fragment:ig,vertex:eg},bits:[ng,...s]});return pe.from({name:t,vertex:{source:e.vertex,entryPoint:"main"},fragment:{source:e.fragment,entryPoint:"main"}})}function ki({bits:s,name:t}){return new Te({name:t,...Jm({template:{vertex:rg,fragment:sg},bits:[og,...s]})})}const dn={name:"color-bit",vertex:{header:`
|
|
259
259
|
@in aColor: vec4<f32>;
|
|
260
260
|
`,main:`
|
|
261
261
|
vColor *= vec4<f32>(aColor.rgb * aColor.a, aColor.a);
|
|
262
|
-
`}},
|
|
262
|
+
`}},un={name:"color-bit",vertex:{header:`
|
|
263
263
|
in vec4 aColor;
|
|
264
264
|
`,main:`
|
|
265
265
|
vColor *= vec4(aColor.rgb * aColor.a, aColor.a);
|
|
266
|
-
`}},
|
|
267
|
-
`)}function
|
|
268
|
-
`)}function
|
|
266
|
+
`}},fn={};function ag(s){const t=[];if(s===1)t.push("@group(1) @binding(0) var textureSource1: texture_2d<f32>;"),t.push("@group(1) @binding(1) var textureSampler1: sampler;");else{let e=0;for(let r=0;r<s;r++)t.push(`@group(1) @binding(${e++}) var textureSource${r+1}: texture_2d<f32>;`),t.push(`@group(1) @binding(${e++}) var textureSampler${r+1}: sampler;`)}return t.join(`
|
|
267
|
+
`)}function hg(s){const t=[];if(s===1)t.push("outColor = textureSampleGrad(textureSource1, textureSampler1, vUV, uvDx, uvDy);");else{t.push("switch vTextureId {");for(let e=0;e<s;e++)e===s-1?t.push(" default:{"):t.push(` case ${e}:{`),t.push(` outColor = textureSampleGrad(textureSource${e+1}, textureSampler${e+1}, vUV, uvDx, uvDy);`),t.push(" break;}");t.push("}")}return t.join(`
|
|
268
|
+
`)}function pn(s){return fn[s]||(fn[s]={name:"texture-batch-bit",vertex:{header:`
|
|
269
269
|
@in aTextureIdAndRound: vec2<u32>;
|
|
270
270
|
@out @interpolate(flat) vTextureId : u32;
|
|
271
271
|
`,main:`
|
|
@@ -278,14 +278,14 @@ ${n.join(`
|
|
|
278
278
|
`},fragment:{header:`
|
|
279
279
|
@in @interpolate(flat) vTextureId: u32;
|
|
280
280
|
|
|
281
|
-
${
|
|
281
|
+
${ag(s)}
|
|
282
282
|
`,main:`
|
|
283
283
|
var uvDx = dpdx(vUV);
|
|
284
284
|
var uvDy = dpdy(vUV);
|
|
285
285
|
|
|
286
|
-
${
|
|
287
|
-
`}}),
|
|
288
|
-
`)}function
|
|
286
|
+
${hg(s)}
|
|
287
|
+
`}}),fn[s]}const mn={};function lg(s){const t=[];for(let e=0;e<s;e++)e>0&&t.push("else"),e<s-1&&t.push(`if(vTextureId < ${e}.5)`),t.push("{"),t.push(` outColor = texture(uTextures[${e}], vUV);`),t.push("}");return t.join(`
|
|
288
|
+
`)}function gn(s){return mn[s]||(mn[s]={name:"texture-batch-bit",vertex:{header:`
|
|
289
289
|
in vec2 aTextureIdAndRound;
|
|
290
290
|
out float vTextureId;
|
|
291
291
|
|
|
@@ -303,22 +303,22 @@ ${n.join(`
|
|
|
303
303
|
|
|
304
304
|
`,main:`
|
|
305
305
|
|
|
306
|
-
${
|
|
307
|
-
`}}),
|
|
306
|
+
${lg(s)}
|
|
307
|
+
`}}),mn[s]}const Mi={name:"round-pixels-bit",vertex:{header:`
|
|
308
308
|
fn roundPixels(position: vec2<f32>, targetSize: vec2<f32>) -> vec2<f32>
|
|
309
309
|
{
|
|
310
310
|
return (floor(((position * 0.5 + 0.5) * targetSize) + 0.5) / targetSize) * 2.0 - 1.0;
|
|
311
311
|
}
|
|
312
|
-
`}},
|
|
312
|
+
`}},Ri={name:"round-pixels-bit",vertex:{header:`
|
|
313
313
|
vec2 roundPixels(vec2 position, vec2 targetSize)
|
|
314
314
|
{
|
|
315
315
|
return (floor(((position * 0.5 + 0.5) * targetSize) + 0.5) / targetSize) * 2.0 - 1.0;
|
|
316
316
|
}
|
|
317
|
-
`}},Nh={};function pn(s){let t=Nh[s];if(t)return t;const e=new Int32Array(s);for(let r=0;r<s;r++)e[r]=r;return t=Nh[s]=new gt({uTextures:{value:e,type:"i32",size:s}},{isStatic:!0}),t}class Hh extends It{constructor(t){const e=Ui({name:"batch",bits:[ln,fn(t),ki]}),r=Bi({name:"batch",bits:[hn,un(t),Mi]});super({glProgram:e,gpuProgram:r,resources:{batchSamplers:pn(t)}}),this.maxTextures=t}}let Ri=null;const Wh=class Ju extends km{constructor(t){super(t),this.geometry=new Gm,this.name=Ju.extension.name,this.vertexSize=6,Ri??(Ri=new Hh(t.maxTextures)),this.shader=Ri}packAttributes(t,e,r,n,a){const l=a<<16|t.roundPixels&65535,h=t.transform,d=h.a,f=h.b,m=h.c,g=h.d,y=h.tx,x=h.ty,{positions:o,uvs:c}=t,u=t.color,p=t.attributeOffset,_=p+t.attributeSize;for(let b=p;b<_;b++){const v=b*2,w=o[v],S=o[v+1];e[n++]=d*w+m*S+y,e[n++]=g*S+f*w+x,e[n++]=c[v],e[n++]=c[v+1],r[n++]=u,r[n++]=l}}packQuadAttributes(t,e,r,n,a){const l=t.texture,h=t.transform,d=h.a,f=h.b,m=h.c,g=h.d,y=h.tx,x=h.ty,o=t.bounds,c=o.maxX,u=o.minX,p=o.maxY,_=o.minY,b=l.uvs,v=t.color,w=a<<16|t.roundPixels&65535;e[n+0]=d*u+m*_+y,e[n+1]=g*_+f*u+x,e[n+2]=b.x0,e[n+3]=b.y0,r[n+4]=v,r[n+5]=w,e[n+6]=d*c+m*_+y,e[n+7]=g*_+f*c+x,e[n+8]=b.x1,e[n+9]=b.y1,r[n+10]=v,r[n+11]=w,e[n+12]=d*c+m*p+y,e[n+13]=g*p+f*c+x,e[n+14]=b.x2,e[n+15]=b.y2,r[n+16]=v,r[n+17]=w,e[n+18]=d*u+m*p+y,e[n+19]=g*p+f*u+x,e[n+20]=b.x3,e[n+21]=b.y3,r[n+22]=v,r[n+23]=w}_updateMaxTextures(t){this.shader.maxTextures!==t&&(Ri=new Hh(t),this.shader=Ri)}destroy(){this.shader=null,super.destroy()}};Wh.extension={type:[C.Batcher],name:"default"};let mn=Wh;function eg(s,t,e,r,n,a,l,h=null){let d=0;e*=t,n*=a;const f=h.a,m=h.b,g=h.c,y=h.d,x=h.tx,o=h.ty;for(;d<l;){const c=s[e],u=s[e+1];r[n]=f*c+g*u+x,r[n+1]=m*c+y*u+o,n+=a,e+=t,d++}}function ig(s,t,e,r){let n=0;for(t*=e;n<r;)s[t]=0,s[t+1]=0,t+=e,n++}function Vh(s,t,e,r,n){const a=t.a,l=t.b,h=t.c,d=t.d,f=t.tx,m=t.ty;e||(e=0),r||(r=2),n||(n=s.length/r-e);let g=e*r;for(let y=0;y<n;y++){const x=s[g],o=s[g+1];s[g]=a*x+h*o+f,s[g+1]=l*x+d*o+m,g+=r}}const rg=new k;class gn{constructor(){this.packAsQuad=!1,this.batcherName="default",this.topology="triangle-list",this.applyTransform=!0,this.roundPixels=0,this._batcher=null,this._batch=null}get uvs(){return this.geometryData.uvs}get positions(){return this.geometryData.vertices}get indices(){return this.geometryData.indices}get blendMode(){return this.renderable&&this.applyTransform?this.renderable.groupBlendMode:"normal"}get color(){const t=this.baseColor,e=t>>16|t&65280|(t&255)<<16,r=this.renderable;return r?go(e,r.groupColor)+(this.alpha*r.groupAlpha*255<<24):e+(this.alpha*255<<24)}get transform(){return this.renderable?.groupTransform||rg}copyTo(t){t.indexOffset=this.indexOffset,t.indexSize=this.indexSize,t.attributeOffset=this.attributeOffset,t.attributeSize=this.attributeSize,t.baseColor=this.baseColor,t.alpha=this.alpha,t.texture=this.texture,t.geometryData=this.geometryData,t.topology=this.topology}reset(){this.applyTransform=!0,this.renderable=null,this.topology="triangle-list"}destroy(){this.renderable=null,this.texture=null,this.geometryData=null,this._batcher=null,this._batch=null}}const Ii={extension:{type:C.ShapeBuilder,name:"circle"},build(s,t){let e,r,n,a,l,h;if(s.type==="circle"){const v=s;if(l=h=v.radius,l<=0)return!1;e=v.x,r=v.y,n=a=0}else if(s.type==="ellipse"){const v=s;if(l=v.halfWidth,h=v.halfHeight,l<=0||h<=0)return!1;e=v.x,r=v.y,n=a=0}else{const v=s,w=v.width/2,S=v.height/2;e=v.x+w,r=v.y+S,l=h=Math.max(0,Math.min(v.radius,Math.min(w,S))),n=w-l,a=S-h}if(n<0||a<0)return!1;const d=Math.ceil(2.3*Math.sqrt(l+h)),f=d*8+(n?4:0)+(a?4:0);if(f===0)return!1;if(d===0)return t[0]=t[6]=e+n,t[1]=t[3]=r+a,t[2]=t[4]=e-n,t[5]=t[7]=r-a,!0;let m=0,g=d*4+(n?2:0)+2,y=g,x=f,o=n+l,c=a,u=e+o,p=e-o,_=r+c;if(t[m++]=u,t[m++]=_,t[--g]=_,t[--g]=p,a){const v=r-c;t[y++]=p,t[y++]=v,t[--x]=v,t[--x]=u}for(let v=1;v<d;v++){const w=Math.PI/2*(v/d),S=n+Math.cos(w)*l,T=a+Math.sin(w)*h,E=e+S,P=e-S,B=r+T,A=r-T;t[m++]=E,t[m++]=B,t[--g]=B,t[--g]=P,t[y++]=P,t[y++]=A,t[--x]=A,t[--x]=E}o=n,c=a+h,u=e+o,p=e-o,_=r+c;const b=r-c;return t[m++]=u,t[m++]=_,t[--x]=b,t[--x]=u,n&&(t[m++]=p,t[m++]=_,t[--x]=b,t[--x]=p),!0},triangulate(s,t,e,r,n,a){if(s.length===0)return;let l=0,h=0;for(let m=0;m<s.length;m+=2)l+=s[m],h+=s[m+1];l/=s.length/2,h/=s.length/2;let d=r;t[d*e]=l,t[d*e+1]=h;const f=d++;for(let m=0;m<s.length;m+=2)t[d*e]=s[m],t[d*e+1]=s[m+1],m>0&&(n[a++]=d,n[a++]=f,n[a++]=d-1),d++;n[a++]=f+1,n[a++]=f,n[a++]=d-1}},sg={...Ii,extension:{...Ii.extension,name:"ellipse"}},ng={...Ii,extension:{...Ii.extension,name:"roundedRectangle"}},Yh=1e-4,Xh=1e-4;function ag(s){const t=s.length;if(t<6)return 1;let e=0;for(let r=0,n=s[t-2],a=s[t-1];r<t;r+=2){const l=s[r],h=s[r+1];e+=(l-n)*(h+a),n=l,a=h}return e<0?-1:1}function $h(s,t,e,r,n,a,l,h){const d=s-e*n,f=t-r*n,m=s+e*a,g=t+r*a;let y,x;l?(y=r,x=-e):(y=-r,x=e);const o=d+y,c=f+x,u=m+y,p=g+x;return h.push(o,c),h.push(u,p),2}function Ce(s,t,e,r,n,a,l,h){const d=e-s,f=r-t;let m=Math.atan2(d,f),g=Math.atan2(n-s,a-t);h&&m<g?m+=Math.PI*2:!h&&m>g&&(g+=Math.PI*2);let y=m;const x=g-m,o=Math.abs(x),c=Math.sqrt(d*d+f*f),u=(15*o*Math.sqrt(c)/Math.PI>>0)+1,p=x/u;if(y+=p,h){l.push(s,t),l.push(e,r);for(let _=1,b=y;_<u;_++,b+=p)l.push(s,t),l.push(s+Math.sin(b)*c,t+Math.cos(b)*c);l.push(s,t),l.push(n,a)}else{l.push(e,r),l.push(s,t);for(let _=1,b=y;_<u;_++,b+=p)l.push(s+Math.sin(b)*c,t+Math.cos(b)*c),l.push(s,t);l.push(n,a),l.push(s,t)}return u*2}function og(s,t,e,r,n,a){const l=Yh;if(s.length===0)return;const h=t;let d=h.alignment;if(t.alignment!==.5){let V=ag(s);d=(d-.5)*V+.5}const f=new q(s[0],s[1]),m=new q(s[s.length-2],s[s.length-1]),g=r,y=Math.abs(f.x-m.x)<l&&Math.abs(f.y-m.y)<l;if(g){s=s.slice(),y&&(s.pop(),s.pop(),m.set(s[s.length-2],s[s.length-1]));const V=(f.x+m.x)*.5,Ot=(m.y+f.y)*.5;s.unshift(V,Ot),s.push(V,Ot)}const x=n,o=s.length/2;let c=s.length;const u=x.length/2,p=h.width/2,_=p*p,b=h.miterLimit*h.miterLimit;let v=s[0],w=s[1],S=s[2],T=s[3],E=0,P=0,B=-(w-T),A=v-S,G=0,O=0,j=Math.sqrt(B*B+A*A);B/=j,A/=j,B*=p,A*=p;const Gt=d,U=(1-Gt)*2,R=Gt*2;g||(h.cap==="round"?c+=Ce(v-B*(U-R)*.5,w-A*(U-R)*.5,v-B*U,w-A*U,v+B*R,w+A*R,x,!0)+2:h.cap==="square"&&(c+=$h(v,w,B,A,U,R,!0,x))),x.push(v-B*U,w-A*U),x.push(v+B*R,w+A*R);for(let V=1;V<o-1;++V){v=s[(V-1)*2],w=s[(V-1)*2+1],S=s[V*2],T=s[V*2+1],E=s[(V+1)*2],P=s[(V+1)*2+1],B=-(w-T),A=v-S,j=Math.sqrt(B*B+A*A),B/=j,A/=j,B*=p,A*=p,G=-(T-P),O=S-E,j=Math.sqrt(G*G+O*O),G/=j,O/=j,G*=p,O*=p;const Ot=S-v,St=w-T,Xt=S-E,N=P-T,Lu=Ot*Xt+St*N,Yr=St*Xt-N*Ot,$i=Yr<0;if(Math.abs(Yr)<.001*Math.abs(Lu)){x.push(S-B*U,T-A*U),x.push(S+B*R,T+A*R),Lu>=0&&(h.join==="round"?c+=Ce(S,T,S-B*U,T-A*U,S-G*U,T-O*U,x,!1)+4:c+=2,x.push(S-G*R,T-O*R),x.push(S+G*U,T+O*U));continue}const zu=(-B+v)*(-A+T)-(-B+S)*(-A+w),Nu=(-G+E)*(-O+T)-(-G+S)*(-O+P),Xr=(Ot*Nu-Xt*zu)/Yr,$r=(N*zu-St*Nu)/Yr,fa=(Xr-S)*(Xr-S)+($r-T)*($r-T),Me=S+(Xr-S)*U,ke=T+($r-T)*U,Re=S-(Xr-S)*R,Ie=T-($r-T)*R,Av=Math.min(Ot*Ot+St*St,Xt*Xt+N*N),Hu=$i?U:R,Pv=Av+Hu*Hu*_;fa<=Pv?h.join==="bevel"||fa/_>b?($i?(x.push(Me,ke),x.push(S+B*R,T+A*R),x.push(Me,ke),x.push(S+G*R,T+O*R)):(x.push(S-B*U,T-A*U),x.push(Re,Ie),x.push(S-G*U,T-O*U),x.push(Re,Ie)),c+=2):h.join==="round"?$i?(x.push(Me,ke),x.push(S+B*R,T+A*R),c+=Ce(S,T,S+B*R,T+A*R,S+G*R,T+O*R,x,!0)+4,x.push(Me,ke),x.push(S+G*R,T+O*R)):(x.push(S-B*U,T-A*U),x.push(Re,Ie),c+=Ce(S,T,S-B*U,T-A*U,S-G*U,T-O*U,x,!1)+4,x.push(S-G*U,T-O*U),x.push(Re,Ie)):(x.push(Me,ke),x.push(Re,Ie)):(x.push(S-B*U,T-A*U),x.push(S+B*R,T+A*R),h.join==="round"?$i?c+=Ce(S,T,S+B*R,T+A*R,S+G*R,T+O*R,x,!0)+2:c+=Ce(S,T,S-B*U,T-A*U,S-G*U,T-O*U,x,!1)+2:h.join==="miter"&&fa/_<=b&&($i?(x.push(Re,Ie),x.push(Re,Ie)):(x.push(Me,ke),x.push(Me,ke)),c+=2),x.push(S-G*U,T-O*U),x.push(S+G*R,T+O*R),c+=2)}v=s[(o-2)*2],w=s[(o-2)*2+1],S=s[(o-1)*2],T=s[(o-1)*2+1],B=-(w-T),A=v-S,j=Math.sqrt(B*B+A*A),B/=j,A/=j,B*=p,A*=p,x.push(S-B*U,T-A*U),x.push(S+B*R,T+A*R),g||(h.cap==="round"?c+=Ce(S-B*(U-R)*.5,T-A*(U-R)*.5,S-B*U,T-A*U,S+B*R,T+A*R,x,!1)+2:h.cap==="square"&&(c+=$h(S,T,B,A,U,R,!1,x)));const wt=Xh*Xh;for(let V=u;V<c+u-2;++V)v=x[V*2],w=x[V*2+1],S=x[(V+1)*2],T=x[(V+1)*2+1],E=x[(V+2)*2],P=x[(V+2)*2+1],!(Math.abs(v*(T-P)+S*(P-w)+E*(w-T))<wt)&&a.push(V,V+1,V+2)}function hg(s,t,e,r){const n=Yh;if(s.length===0)return;const a=s[0],l=s[1],h=s[s.length-2],d=s[s.length-1],f=t||Math.abs(a-h)<n&&Math.abs(l-d)<n,m=e,g=s.length/2,y=m.length/2;for(let x=0;x<g;x++)m.push(s[x*2]),m.push(s[x*2+1]);for(let x=0;x<g-1;x++)r.push(y+x,y+x+1);f&&r.push(y+g-1,y)}function Kh(s,t,e,r,n,a,l){const h=cm(s,t,2);if(!h)return;for(let f=0;f<h.length;f+=3)a[l++]=h[f]+n,a[l++]=h[f+1]+n,a[l++]=h[f+2]+n;let d=n*r;for(let f=0;f<s.length;f+=2)e[d]=s[f],e[d+1]=s[f+1],d+=r}const lg=[],cg={extension:{type:C.ShapeBuilder,name:"polygon"},build(s,t){for(let e=0;e<s.points.length;e++)t[e]=s.points[e];return!0},triangulate(s,t,e,r,n,a){Kh(s,lg,t,e,r,n,a)}},ug={extension:{type:C.ShapeBuilder,name:"rectangle"},build(s,t){const e=s,r=e.x,n=e.y,a=e.width,l=e.height;return a>0&&l>0?(t[0]=r,t[1]=n,t[2]=r+a,t[3]=n,t[4]=r+a,t[5]=n+l,t[6]=r,t[7]=n+l,!0):!1},triangulate(s,t,e,r,n,a){let l=0;r*=e,t[r+l]=s[0],t[r+l+1]=s[1],l+=e,t[r+l]=s[2],t[r+l+1]=s[3],l+=e,t[r+l]=s[6],t[r+l+1]=s[7],l+=e,t[r+l]=s[4],t[r+l+1]=s[5],l+=e;const h=r/e;n[a++]=h,n[a++]=h+1,n[a++]=h+2,n[a++]=h+1,n[a++]=h+3,n[a++]=h+2}},dg={extension:{type:C.ShapeBuilder,name:"triangle"},build(s,t){return t[0]=s.x,t[1]=s.y,t[2]=s.x2,t[3]=s.y2,t[4]=s.x3,t[5]=s.y3,!0},triangulate(s,t,e,r,n,a){let l=0;r*=e,t[r+l]=s[0],t[r+l+1]=s[1],l+=e,t[r+l]=s[2],t[r+l+1]=s[3],l+=e,t[r+l]=s[4],t[r+l+1]=s[5];const h=r/e;n[a++]=h,n[a++]=h+1,n[a++]=h+2}},fg=new k,pg=new L;function mg(s,t,e,r){const n=t.matrix?s.copyFrom(t.matrix).invert():s.identity();if(t.textureSpace==="local"){const l=e.getBounds(pg);t.width&&l.pad(t.width);const{x:h,y:d}=l,f=1/l.width,m=1/l.height,g=-h*f,y=-d*m,x=n.a,o=n.b,c=n.c,u=n.d;n.a*=f,n.b*=f,n.c*=m,n.d*=m,n.tx=g*x+y*c+n.tx,n.ty=g*o+y*u+n.ty}else n.translate(t.texture.frame.x,t.texture.frame.y),n.scale(1/t.texture.source.width,1/t.texture.source.height);const a=t.texture.source.style;return!(t.fill instanceof Vt)&&a.addressMode==="clamp-to-edge"&&(a.addressMode="repeat",a.update()),r&&n.append(fg.copyFrom(r).invert()),n}const Mr={};D.handleByMap(C.ShapeBuilder,Mr),D.add(ug,cg,dg,Ii,sg,ng);const gg=new L,_g=new k;function yg(s,t){const{geometryData:e,batches:r}=t;r.length=0,e.indices.length=0,e.vertices.length=0,e.uvs.length=0;for(let n=0;n<s.instructions.length;n++){const a=s.instructions[n];if(a.action==="texture")xg(a.data,r,e);else if(a.action==="fill"||a.action==="stroke"){const l=a.action==="stroke",h=a.data.path.shapePath,d=a.data.style,f=a.data.hole;l&&f&&jh(f.shapePath,d,!0,r,e),f&&(h.shapePrimitives[h.shapePrimitives.length-1].holes=f.shapePath.shapePrimitives),jh(h,d,l,r,e)}}}function xg(s,t,e){const r=[],n=Mr.rectangle,a=gg;a.x=s.dx,a.y=s.dy,a.width=s.dw,a.height=s.dh;const l=s.transform;if(!n.build(a,r))return;const{vertices:h,uvs:d,indices:f}=e,m=f.length,g=h.length/2;l&&Vh(r,l),n.triangulate(r,h,2,g,f,m);const y=s.image,x=y.uvs;d.push(x.x0,x.y0,x.x1,x.y1,x.x3,x.y3,x.x2,x.y2);const o=at.get(gn);o.indexOffset=m,o.indexSize=f.length-m,o.attributeOffset=g,o.attributeSize=h.length/2-g,o.baseColor=s.style,o.alpha=s.alpha,o.texture=y,o.geometryData=e,t.push(o)}function jh(s,t,e,r,n){const{vertices:a,uvs:l,indices:h}=n;s.shapePrimitives.forEach(({shape:d,transform:f,holes:m})=>{const g=[],y=Mr[d.type];if(!y.build(d,g))return;const x=h.length,o=a.length/2;let c="triangle-list";if(f&&Vh(g,f),e){const b=d.closePath??!0,v=t;v.pixelLine?(hg(g,b,a,h),c="line-list"):og(g,v,!1,b,a,h)}else if(m){const b=[],v=g.slice();bg(m).forEach(S=>{b.push(v.length/2),v.push(...S)}),Kh(v,b,a,2,o,h,x)}else y.triangulate(g,a,2,o,h,x);const u=l.length/2,p=t.texture;if(p!==M.WHITE){const b=mg(_g,t,d,f);eg(a,2,o,l,u,2,a.length/2-o,b)}else ig(l,u,2,a.length/2-o);const _=at.get(gn);_.indexOffset=x,_.indexSize=h.length-x,_.attributeOffset=o,_.attributeSize=a.length/2-o,_.baseColor=t.color,_.alpha=t.alpha,_.texture=p,_.geometryData=n,_.topology=c,r.push(_)})}function bg(s){const t=[];for(let e=0;e<s.length;e++){const r=s[e].shape,n=[];Mr[r.type].build(r,n)&&t.push(n)}return t}class vg{constructor(){this.batches=[],this.geometryData={vertices:[],uvs:[],indices:[]}}}class wg{constructor(){this.instructions=new bo}init(t){const e=t.maxTextures;this.batcher?this.batcher._updateMaxTextures(e):this.batcher=new mn({maxTextures:e}),this.instructions.reset()}get geometry(){return z(kf,"GraphicsContextRenderData#geometry is deprecated, please use batcher.geometry instead."),this.batcher.geometry}destroy(){this.batcher.destroy(),this.instructions.destroy(),this.batcher=null,this.instructions=null}}const _n=class ya{constructor(t){this._gpuContextHash={},this._graphicsDataContextHash=Object.create(null),this._renderer=t,t.renderableGC.addManagedHash(this,"_gpuContextHash"),t.renderableGC.addManagedHash(this,"_graphicsDataContextHash")}init(t){ya.defaultOptions.bezierSmoothness=t?.bezierSmoothness??ya.defaultOptions.bezierSmoothness}getContextRenderData(t){return this._graphicsDataContextHash[t.uid]||this._initContextRenderData(t)}updateGpuContext(t){let e=this._gpuContextHash[t.uid]||this._initContext(t);if(t.dirty){e?this._cleanGraphicsContextData(t):e=this._initContext(t),yg(t,e);const r=t.batchMode;t.customShader||r==="no-batch"?e.isBatchable=!1:r==="auto"?e.isBatchable=e.geometryData.vertices.length<400:e.isBatchable=!0,t.dirty=!1}return e}getGpuContext(t){return this._gpuContextHash[t.uid]||this._initContext(t)}_initContextRenderData(t){const e=at.get(wg,{maxTextures:this._renderer.limits.maxBatchableTextures}),{batches:r,geometryData:n}=this._gpuContextHash[t.uid],a=n.vertices.length,l=n.indices.length;for(let m=0;m<r.length;m++)r[m].applyTransform=!1;const h=e.batcher;h.ensureAttributeBuffer(a),h.ensureIndexBuffer(l),h.begin();for(let m=0;m<r.length;m++){const g=r[m];h.add(g)}h.finish(e.instructions);const d=h.geometry;d.indexBuffer.setDataWithSize(h.indexBuffer,h.indexSize,!0),d.buffers[0].setDataWithSize(h.attributeBuffer.float32View,h.attributeSize,!0);const f=h.batches;for(let m=0;m<f.length;m++){const g=f[m];g.bindGroup=nn(g.textures.textures,g.textures.count,this._renderer.limits.maxBatchableTextures)}return this._graphicsDataContextHash[t.uid]=e,e}_initContext(t){const e=new vg;return e.context=t,this._gpuContextHash[t.uid]=e,t.on("destroy",this.onGraphicsContextDestroy,this),this._gpuContextHash[t.uid]}onGraphicsContextDestroy(t){this._cleanGraphicsContextData(t),t.off("destroy",this.onGraphicsContextDestroy,this),this._gpuContextHash[t.uid]=null}_cleanGraphicsContextData(t){const e=this._gpuContextHash[t.uid];e.isBatchable||this._graphicsDataContextHash[t.uid]&&(at.return(this.getContextRenderData(t)),this._graphicsDataContextHash[t.uid]=null),e.batches&&e.batches.forEach(r=>{at.return(r)})}destroy(){for(const t in this._gpuContextHash)this._gpuContextHash[t]&&this.onGraphicsContextDestroy(this._gpuContextHash[t].context);this._gpuContextHash={},this._graphicsDataContextHash={},this._renderer=null}};_n.extension={type:[C.WebGLSystem,C.WebGPUSystem,C.CanvasSystem],name:"graphicsContext"},_n.defaultOptions={bezierSmoothness:.5};let yn=_n;const Sg=8,kr=11920929e-14,Tg=1;function qh(s,t,e,r,n,a,l,h,d,f){const g=Math.min(.99,Math.max(0,f??yn.defaultOptions.bezierSmoothness));let y=(Tg-g)/1;return y*=y,Cg(t,e,r,n,a,l,h,d,s,y),s}function Cg(s,t,e,r,n,a,l,h,d,f){xn(s,t,e,r,n,a,l,h,d,f,0),d.push(l,h)}function xn(s,t,e,r,n,a,l,h,d,f,m){if(m>Sg)return;const g=(s+e)/2,y=(t+r)/2,x=(e+n)/2,o=(r+a)/2,c=(n+l)/2,u=(a+h)/2,p=(g+x)/2,_=(y+o)/2,b=(x+c)/2,v=(o+u)/2,w=(p+b)/2,S=(_+v)/2;if(m>0){let T=l-s,E=h-t;const P=Math.abs((e-l)*E-(r-h)*T),B=Math.abs((n-l)*E-(a-h)*T);if(P>kr&&B>kr){if((P+B)*(P+B)<=f*(T*T+E*E)){d.push(w,S);return}}else if(P>kr){if(P*P<=f*(T*T+E*E)){d.push(w,S);return}}else if(B>kr){if(B*B<=f*(T*T+E*E)){d.push(w,S);return}}else if(T=w-(s+l)/2,E=S-(t+h)/2,T*T+E*E<=f){d.push(w,S);return}}xn(s,t,g,y,p,_,w,S,d,f,m+1),xn(w,S,b,v,c,u,l,h,d,f,m+1)}const Eg=8,Ag=11920929e-14,Pg=1;function Bg(s,t,e,r,n,a,l,h){const f=Math.min(.99,Math.max(0,h??yn.defaultOptions.bezierSmoothness));let m=(Pg-f)/1;return m*=m,Ug(t,e,r,n,a,l,s,m),s}function Ug(s,t,e,r,n,a,l,h){bn(l,s,t,e,r,n,a,h,0),l.push(n,a)}function bn(s,t,e,r,n,a,l,h,d){if(d>Eg)return;const f=(t+r)/2,m=(e+n)/2,g=(r+a)/2,y=(n+l)/2,x=(f+g)/2,o=(m+y)/2;let c=a-t,u=l-e;const p=Math.abs((r-a)*u-(n-l)*c);if(p>Ag){if(p*p<=h*(c*c+u*u)){s.push(x,o);return}}else if(c=x-(t+a)/2,u=o-(e+l)/2,c*c+u*u<=h){s.push(x,o);return}bn(s,t,e,f,m,x,o,h,d+1),bn(s,x,o,g,y,a,l,h,d+1)}function Zh(s,t,e,r,n,a,l,h){let d=Math.abs(n-a);(!l&&n>a||l&&a>n)&&(d=2*Math.PI-d),h||(h=Math.max(6,Math.floor(6*Math.pow(r,1/3)*(d/Math.PI)))),h=Math.max(h,3);let f=d/h,m=n;f*=l?-1:1;for(let g=0;g<h+1;g++){const y=Math.cos(m),x=Math.sin(m),o=t+y*r,c=e+x*r;s.push(o,c),m+=f}}function Mg(s,t,e,r,n,a){const l=s[s.length-2],d=s[s.length-1]-e,f=l-t,m=n-e,g=r-t,y=Math.abs(d*g-f*m);if(y<1e-8||a===0){(s[s.length-2]!==t||s[s.length-1]!==e)&&s.push(t,e);return}const x=d*d+f*f,o=m*m+g*g,c=d*m+f*g,u=a*Math.sqrt(x)/y,p=a*Math.sqrt(o)/y,_=u*c/x,b=p*c/o,v=u*g+p*f,w=u*m+p*d,S=f*(p+_),T=d*(p+_),E=g*(u+b),P=m*(u+b),B=Math.atan2(T-w,S-v),A=Math.atan2(P-w,E-v);Zh(s,v+t,w+e,a,B,A,f*m>g*d)}const Fi=Math.PI*2,vn={centerX:0,centerY:0,ang1:0,ang2:0},wn=({x:s,y:t},e,r,n,a,l,h,d)=>{s*=e,t*=r;const f=n*s-a*t,m=a*s+n*t;return d.x=f+l,d.y=m+h,d};function kg(s,t){const e=t===-1.5707963267948966?-.551915024494:1.3333333333333333*Math.tan(t/4),r=t===1.5707963267948966?.551915024494:e,n=Math.cos(s),a=Math.sin(s),l=Math.cos(s+t),h=Math.sin(s+t);return[{x:n-a*r,y:a+n*r},{x:l+h*r,y:h-l*r},{x:l,y:h}]}const Qh=(s,t,e,r)=>{const n=s*r-t*e<0?-1:1;let a=s*e+t*r;return a>1&&(a=1),a<-1&&(a=-1),n*Math.acos(a)},Rg=(s,t,e,r,n,a,l,h,d,f,m,g,y)=>{const x=Math.pow(n,2),o=Math.pow(a,2),c=Math.pow(m,2),u=Math.pow(g,2);let p=x*o-x*u-o*c;p<0&&(p=0),p/=x*u+o*c,p=Math.sqrt(p)*(l===h?-1:1);const _=p*n/a*g,b=p*-a/n*m,v=f*_-d*b+(s+e)/2,w=d*_+f*b+(t+r)/2,S=(m-_)/n,T=(g-b)/a,E=(-m-_)/n,P=(-g-b)/a,B=Qh(1,0,S,T);let A=Qh(S,T,E,P);h===0&&A>0&&(A-=Fi),h===1&&A<0&&(A+=Fi),y.centerX=v,y.centerY=w,y.ang1=B,y.ang2=A};function Ig(s,t,e,r,n,a,l,h=0,d=0,f=0){if(a===0||l===0)return;const m=Math.sin(h*Fi/360),g=Math.cos(h*Fi/360),y=g*(t-r)/2+m*(e-n)/2,x=-m*(t-r)/2+g*(e-n)/2;if(y===0&&x===0)return;a=Math.abs(a),l=Math.abs(l);const o=Math.pow(y,2)/Math.pow(a,2)+Math.pow(x,2)/Math.pow(l,2);o>1&&(a*=Math.sqrt(o),l*=Math.sqrt(o)),Rg(t,e,r,n,a,l,d,f,m,g,y,x,vn);let{ang1:c,ang2:u}=vn;const{centerX:p,centerY:_}=vn;let b=Math.abs(u)/(Fi/4);Math.abs(1-b)<1e-7&&(b=1);const v=Math.max(Math.ceil(b),1);u/=v;let w=s[s.length-2],S=s[s.length-1];const T={x:0,y:0};for(let E=0;E<v;E++){const P=kg(c,u),{x:B,y:A}=wn(P[0],a,l,g,m,p,_,T),{x:G,y:O}=wn(P[1],a,l,g,m,p,_,T),{x:j,y:Gt}=wn(P[2],a,l,g,m,p,_,T);qh(s,w,S,B,A,G,O,j,Gt),w=j,S=Gt,c+=u}}function Fg(s,t,e){const r=(l,h)=>{const d=h.x-l.x,f=h.y-l.y,m=Math.sqrt(d*d+f*f),g=d/m,y=f/m;return{len:m,nx:g,ny:y}},n=(l,h)=>{l===0?s.moveTo(h.x,h.y):s.lineTo(h.x,h.y)};let a=t[t.length-1];for(let l=0;l<t.length;l++){const h=t[l%t.length],d=h.radius??e;if(d<=0){n(l,h),a=h;continue}const f=t[(l+1)%t.length],m=r(h,a),g=r(h,f);if(m.len<1e-4||g.len<1e-4){n(l,h),a=h;continue}let y=Math.asin(m.nx*g.ny-m.ny*g.nx),x=1,o=!1;m.nx*g.nx-m.ny*-g.ny<0?y<0?y=Math.PI+y:(y=Math.PI-y,x=-1,o=!0):y>0&&(x=-1,o=!0);const c=y/2;let u,p=Math.abs(Math.cos(c)*d/Math.sin(c));p>Math.min(m.len/2,g.len/2)?(p=Math.min(m.len/2,g.len/2),u=Math.abs(p*Math.sin(c)/Math.cos(c))):u=d;const _=h.x+g.nx*p+-g.ny*u*x,b=h.y+g.ny*p+g.nx*u*x,v=Math.atan2(m.ny,m.nx)+Math.PI/2*x,w=Math.atan2(g.ny,g.nx)-Math.PI/2*x;l===0&&s.moveTo(_+Math.cos(v)*u,b+Math.sin(v)*u),s.arc(_,b,u,v,w,o),a=h}}function Dg(s,t,e,r){const n=(h,d)=>Math.sqrt((h.x-d.x)**2+(h.y-d.y)**2),a=(h,d,f)=>({x:h.x+(d.x-h.x)*f,y:h.y+(d.y-h.y)*f}),l=t.length;for(let h=0;h<l;h++){const d=t[(h+1)%l],f=d.radius??e;if(f<=0){h===0?s.moveTo(d.x,d.y):s.lineTo(d.x,d.y);continue}const m=t[h],g=t[(h+2)%l],y=n(m,d);let x;if(y<1e-4)x=d;else{const u=Math.min(y/2,f);x=a(d,m,u/y)}const o=n(g,d);let c;if(o<1e-4)c=d;else{const u=Math.min(o/2,f);c=a(d,g,u/o)}h===0?s.moveTo(x.x,x.y):s.lineTo(x.x,x.y),s.quadraticCurveTo(d.x,d.y,c.x,c.y,r)}}const Gg=new L;class Og{constructor(t){this.shapePrimitives=[],this._currentPoly=null,this._bounds=new dt,this._graphicsPath2D=t,this.signed=t.checkForHoles}moveTo(t,e){return this.startPoly(t,e),this}lineTo(t,e){this._ensurePoly();const r=this._currentPoly.points,n=r[r.length-2],a=r[r.length-1];return(n!==t||a!==e)&&r.push(t,e),this}arc(t,e,r,n,a,l){this._ensurePoly(!1);const h=this._currentPoly.points;return Zh(h,t,e,r,n,a,l),this}arcTo(t,e,r,n,a){this._ensurePoly();const l=this._currentPoly.points;return Mg(l,t,e,r,n,a),this}arcToSvg(t,e,r,n,a,l,h){const d=this._currentPoly.points;return Ig(d,this._currentPoly.lastX,this._currentPoly.lastY,l,h,t,e,r,n,a),this}bezierCurveTo(t,e,r,n,a,l,h){this._ensurePoly();const d=this._currentPoly;return qh(this._currentPoly.points,d.lastX,d.lastY,t,e,r,n,a,l,h),this}quadraticCurveTo(t,e,r,n,a){this._ensurePoly();const l=this._currentPoly;return Bg(this._currentPoly.points,l.lastX,l.lastY,t,e,r,n,a),this}closePath(){return this.endPoly(!0),this}addPath(t,e){this.endPoly(),e&&!e.isIdentity()&&(t=t.clone(!0),t.transform(e));const r=this.shapePrimitives,n=r.length;for(let a=0;a<t.instructions.length;a++){const l=t.instructions[a];this[l.action](...l.data)}if(t.checkForHoles&&r.length-n>1){let a=null;for(let l=n;l<r.length;l++){const h=r[l];if(h.shape.type==="polygon"){const d=h.shape,f=a?.shape;f&&f.containsPolygon(d)?(a.holes||(a.holes=[]),a.holes.push(h),r.copyWithin(l,l+1),r.length--,l--):a=h}}}return this}finish(t=!1){this.endPoly(t)}rect(t,e,r,n,a){return this.drawShape(new L(t,e,r,n),a),this}circle(t,e,r,n){return this.drawShape(new Pr(t,e,r),n),this}poly(t,e,r){const n=new Ti(t);return n.closePath=e,this.drawShape(n,r),this}regularPoly(t,e,r,n,a=0,l){n=Math.max(n|0,3);const h=-1*Math.PI/2+a,d=Math.PI*2/n,f=[];for(let m=0;m<n;m++){const g=h-m*d;f.push(t+r*Math.cos(g),e+r*Math.sin(g))}return this.poly(f,!0,l),this}roundPoly(t,e,r,n,a,l=0,h){if(n=Math.max(n|0,3),a<=0)return this.regularPoly(t,e,r,n,l);const d=r*Math.sin(Math.PI/n)-.001;a=Math.min(a,d);const f=-1*Math.PI/2+l,m=Math.PI*2/n,g=(n-2)*Math.PI/n/2;for(let y=0;y<n;y++){const x=y*m+f,o=t+r*Math.cos(x),c=e+r*Math.sin(x),u=x+Math.PI+g,p=x-Math.PI-g,_=o+a*Math.cos(u),b=c+a*Math.sin(u),v=o+a*Math.cos(p),w=c+a*Math.sin(p);y===0?this.moveTo(_,b):this.lineTo(_,b),this.quadraticCurveTo(o,c,v,w,h)}return this.closePath()}roundShape(t,e,r=!1,n){return t.length<3?this:(r?Dg(this,t,e,n):Fg(this,t,e),this.closePath())}filletRect(t,e,r,n,a){if(a===0)return this.rect(t,e,r,n);const l=Math.min(r,n)/2,h=Math.min(l,Math.max(-l,a)),d=t+r,f=e+n,m=h<0?-h:0,g=Math.abs(h);return this.moveTo(t,e+g).arcTo(t+m,e+m,t+g,e,g).lineTo(d-g,e).arcTo(d-m,e+m,d,e+g,g).lineTo(d,f-g).arcTo(d-m,f-m,t+r-g,f,g).lineTo(t+g,f).arcTo(t+m,f-m,t,f-g,g).closePath()}chamferRect(t,e,r,n,a,l){if(a<=0)return this.rect(t,e,r,n);const h=Math.min(a,Math.min(r,n)/2),d=t+r,f=e+n,m=[t+h,e,d-h,e,d,e+h,d,f-h,d-h,f,t+h,f,t,f-h,t,e+h];for(let g=m.length-1;g>=2;g-=2)m[g]===m[g-2]&&m[g-1]===m[g-3]&&m.splice(g-1,2);return this.poly(m,!0,l)}ellipse(t,e,r,n,a){return this.drawShape(new rn(t,e,r,n),a),this}roundRect(t,e,r,n,a,l){return this.drawShape(new sn(t,e,r,n,a),l),this}drawShape(t,e){return this.endPoly(),this.shapePrimitives.push({shape:t,transform:e}),this}startPoly(t,e){let r=this._currentPoly;return r&&this.endPoly(),r=new Ti,r.points.push(t,e),this._currentPoly=r,this}endPoly(t=!1){const e=this._currentPoly;return e&&e.points.length>2&&(e.closePath=t,this.shapePrimitives.push({shape:e})),this._currentPoly=null,this}_ensurePoly(t=!0){if(!this._currentPoly&&(this._currentPoly=new Ti,t)){const e=this.shapePrimitives[this.shapePrimitives.length-1];if(e){let r=e.shape.x,n=e.shape.y;if(e.transform&&!e.transform.isIdentity()){const a=e.transform,l=r;r=a.a*r+a.c*n+a.tx,n=a.b*l+a.d*n+a.ty}this._currentPoly.points.push(r,n)}else this._currentPoly.points.push(0,0)}}buildPath(){const t=this._graphicsPath2D;this.shapePrimitives.length=0,this._currentPoly=null;for(let e=0;e<t.instructions.length;e++){const r=t.instructions[e];this[r.action](...r.data)}this.finish()}get bounds(){const t=this._bounds;t.clear();const e=this.shapePrimitives;for(let r=0;r<e.length;r++){const n=e[r],a=n.shape.getBounds(Gg);n.transform?t.addRect(a,n.transform):t.addRect(a)}return t}}class se{constructor(t,e=!1){this.instructions=[],this.uid=et("graphicsPath"),this._dirty=!0,this.checkForHoles=e,typeof t=="string"?vm(t,this):this.instructions=t?.slice()??[]}get shapePath(){return this._shapePath||(this._shapePath=new Og(this)),this._dirty&&(this._dirty=!1,this._shapePath.buildPath()),this._shapePath}addPath(t,e){return t=t.clone(),this.instructions.push({action:"addPath",data:[t,e]}),this._dirty=!0,this}arc(...t){return this.instructions.push({action:"arc",data:t}),this._dirty=!0,this}arcTo(...t){return this.instructions.push({action:"arcTo",data:t}),this._dirty=!0,this}arcToSvg(...t){return this.instructions.push({action:"arcToSvg",data:t}),this._dirty=!0,this}bezierCurveTo(...t){return this.instructions.push({action:"bezierCurveTo",data:t}),this._dirty=!0,this}bezierCurveToShort(t,e,r,n,a){const l=this.instructions[this.instructions.length-1],h=this.getLastPoint(q.shared);let d=0,f=0;if(!l||l.action!=="bezierCurveTo")d=h.x,f=h.y;else{d=l.data[2],f=l.data[3];const m=h.x,g=h.y;d=m+(m-d),f=g+(g-f)}return this.instructions.push({action:"bezierCurveTo",data:[d,f,t,e,r,n,a]}),this._dirty=!0,this}closePath(){return this.instructions.push({action:"closePath",data:[]}),this._dirty=!0,this}ellipse(...t){return this.instructions.push({action:"ellipse",data:t}),this._dirty=!0,this}lineTo(...t){return this.instructions.push({action:"lineTo",data:t}),this._dirty=!0,this}moveTo(...t){return this.instructions.push({action:"moveTo",data:t}),this}quadraticCurveTo(...t){return this.instructions.push({action:"quadraticCurveTo",data:t}),this._dirty=!0,this}quadraticCurveToShort(t,e,r){const n=this.instructions[this.instructions.length-1],a=this.getLastPoint(q.shared);let l=0,h=0;if(!n||n.action!=="quadraticCurveTo")l=a.x,h=a.y;else{l=n.data[0],h=n.data[1];const d=a.x,f=a.y;l=d+(d-l),h=f+(f-h)}return this.instructions.push({action:"quadraticCurveTo",data:[l,h,t,e,r]}),this._dirty=!0,this}rect(t,e,r,n,a){return this.instructions.push({action:"rect",data:[t,e,r,n,a]}),this._dirty=!0,this}circle(t,e,r,n){return this.instructions.push({action:"circle",data:[t,e,r,n]}),this._dirty=!0,this}roundRect(...t){return this.instructions.push({action:"roundRect",data:t}),this._dirty=!0,this}poly(...t){return this.instructions.push({action:"poly",data:t}),this._dirty=!0,this}regularPoly(...t){return this.instructions.push({action:"regularPoly",data:t}),this._dirty=!0,this}roundPoly(...t){return this.instructions.push({action:"roundPoly",data:t}),this._dirty=!0,this}roundShape(...t){return this.instructions.push({action:"roundShape",data:t}),this._dirty=!0,this}filletRect(...t){return this.instructions.push({action:"filletRect",data:t}),this._dirty=!0,this}chamferRect(...t){return this.instructions.push({action:"chamferRect",data:t}),this._dirty=!0,this}star(t,e,r,n,a,l,h){a||(a=n/2);const d=-1*Math.PI/2+l,f=r*2,m=Math.PI*2/f,g=[];for(let y=0;y<f;y++){const x=y%2?a:n,o=y*m+d;g.push(t+x*Math.cos(o),e+x*Math.sin(o))}return this.poly(g,!0,h),this}clone(t=!1){const e=new se;if(e.checkForHoles=this.checkForHoles,!t)e.instructions=this.instructions.slice();else for(let r=0;r<this.instructions.length;r++){const n=this.instructions[r];e.instructions.push({action:n.action,data:n.data.slice()})}return e}clear(){return this.instructions.length=0,this._dirty=!0,this}transform(t){if(t.isIdentity())return this;const e=t.a,r=t.b,n=t.c,a=t.d,l=t.tx,h=t.ty;let d=0,f=0,m=0,g=0,y=0,x=0,o=0,c=0;for(let u=0;u<this.instructions.length;u++){const p=this.instructions[u],_=p.data;switch(p.action){case"moveTo":case"lineTo":d=_[0],f=_[1],_[0]=e*d+n*f+l,_[1]=r*d+a*f+h;break;case"bezierCurveTo":m=_[0],g=_[1],y=_[2],x=_[3],d=_[4],f=_[5],_[0]=e*m+n*g+l,_[1]=r*m+a*g+h,_[2]=e*y+n*x+l,_[3]=r*y+a*x+h,_[4]=e*d+n*f+l,_[5]=r*d+a*f+h;break;case"quadraticCurveTo":m=_[0],g=_[1],d=_[2],f=_[3],_[0]=e*m+n*g+l,_[1]=r*m+a*g+h,_[2]=e*d+n*f+l,_[3]=r*d+a*f+h;break;case"arcToSvg":d=_[5],f=_[6],o=_[0],c=_[1],_[0]=e*o+n*c,_[1]=r*o+a*c,_[5]=e*d+n*f+l,_[6]=r*d+a*f+h;break;case"circle":_[4]=Di(_[3],t);break;case"rect":_[4]=Di(_[4],t);break;case"ellipse":_[8]=Di(_[8],t);break;case"roundRect":_[5]=Di(_[5],t);break;case"addPath":_[0].transform(t);break;case"poly":_[2]=Di(_[2],t);break;default:F("unknown transform action",p.action);break}}return this._dirty=!0,this}get bounds(){return this.shapePath.bounds}getLastPoint(t){let e=this.instructions.length-1,r=this.instructions[e];if(!r)return t.x=0,t.y=0,t;for(;r.action==="closePath";){if(e--,e<0)return t.x=0,t.y=0,t;r=this.instructions[e]}switch(r.action){case"moveTo":case"lineTo":t.x=r.data[0],t.y=r.data[1];break;case"quadraticCurveTo":t.x=r.data[2],t.y=r.data[3];break;case"bezierCurveTo":t.x=r.data[4],t.y=r.data[5];break;case"arc":case"arcToSvg":t.x=r.data[5],t.y=r.data[6];break;case"addPath":r.data[0].getLastPoint(t);break}return t}}function Di(s,t){return s?s.prepend(t):t.clone()}function st(s,t,e){const r=s.getAttribute(t);return r?Number(r):e}function Lg(s,t){const e=s.querySelectorAll("defs");for(let r=0;r<e.length;r++){const n=e[r];for(let a=0;a<n.children.length;a++){const l=n.children[a];switch(l.nodeName.toLowerCase()){case"lineargradient":t.defs[l.id]=zg(l);break;case"radialgradient":t.defs[l.id]=Ng();break}}}}function zg(s){const t=st(s,"x1",0),e=st(s,"y1",0),r=st(s,"x2",1),n=st(s,"y2",0),a=s.getAttribute("gradientUnits")||"objectBoundingBox",l=new Vt(t,e,r,n,a==="objectBoundingBox"?"local":"global");for(let h=0;h<s.children.length;h++){const d=s.children[h],f=st(d,"offset",0),m=J.shared.setValue(d.getAttribute("stop-color")).toNumber();l.addColorStop(f,m)}return l}function Ng(s){return F("[SVG Parser] Radial gradients are not yet supported"),new Vt(0,0,1,0)}function Jh(s){const t=s.match(/url\s*\(\s*['"]?\s*#([^'"\s)]+)\s*['"]?\s*\)/i);return t?t[1]:""}const tl={fill:{type:"paint",default:0},"fill-opacity":{type:"number",default:1},stroke:{type:"paint",default:0},"stroke-width":{type:"number",default:1},"stroke-opacity":{type:"number",default:1},"stroke-linecap":{type:"string",default:"butt"},"stroke-linejoin":{type:"string",default:"miter"},"stroke-miterlimit":{type:"number",default:10},"stroke-dasharray":{type:"string",default:"none"},"stroke-dashoffset":{type:"number",default:0},opacity:{type:"number",default:1}};function el(s,t){const e=s.getAttribute("style"),r={},n={},a={strokeStyle:r,fillStyle:n,useFill:!1,useStroke:!1};for(const l in tl){const h=s.getAttribute(l);h&&il(t,a,l,h.trim())}if(e){const l=e.split(";");for(let h=0;h<l.length;h++){const d=l[h].trim(),[f,m]=d.split(":");tl[f]&&il(t,a,f,m.trim())}}return{strokeStyle:a.useStroke?r:null,fillStyle:a.useFill?n:null,useFill:a.useFill,useStroke:a.useStroke}}function il(s,t,e,r){switch(e){case"stroke":if(r!=="none"){if(r.startsWith("url(")){const n=Jh(r);t.strokeStyle.fill=s.defs[n]}else t.strokeStyle.color=J.shared.setValue(r).toNumber();t.useStroke=!0}break;case"stroke-width":t.strokeStyle.width=Number(r);break;case"fill":if(r!=="none"){if(r.startsWith("url(")){const n=Jh(r);t.fillStyle.fill=s.defs[n]}else t.fillStyle.color=J.shared.setValue(r).toNumber();t.useFill=!0}break;case"fill-opacity":t.fillStyle.alpha=Number(r);break;case"stroke-opacity":t.strokeStyle.alpha=Number(r);break;case"opacity":t.fillStyle.alpha=Number(r),t.strokeStyle.alpha=Number(r);break}}function Hg(s){if(s.length<=2)return!0;const t=s.map(h=>h.area).sort((h,d)=>d-h),[e,r]=t,n=t[t.length-1],a=e/r,l=r/n;return!(a>3&&l<2)}function Wg(s){return s.split(/(?=[Mm])/).filter(r=>r.trim().length>0)}function Vg(s){const t=s.match(/[-+]?[0-9]*\.?[0-9]+/g);if(!t||t.length<4)return 0;const e=t.map(Number),r=[],n=[];for(let m=0;m<e.length;m+=2)m+1<e.length&&(r.push(e[m]),n.push(e[m+1]));if(r.length===0||n.length===0)return 0;const a=Math.min(...r),l=Math.max(...r),h=Math.min(...n),d=Math.max(...n);return(l-a)*(d-h)}function rl(s,t){const e=new se(s,!1);for(const r of e.instructions)t.instructions.push(r)}function Yg(s,t){if(typeof s=="string"){const l=document.createElement("div");l.innerHTML=s.trim(),s=l.querySelector("svg")}const e={context:t,defs:{},path:new se};Lg(s,e);const r=s.children,{fillStyle:n,strokeStyle:a}=el(s,e);for(let l=0;l<r.length;l++){const h=r[l];h.nodeName.toLowerCase()!=="defs"&&sl(h,e,n,a)}return t}function sl(s,t,e,r){const n=s.children,{fillStyle:a,strokeStyle:l}=el(s,t);a&&e?e={...e,...a}:a&&(e=a),l&&r?r={...r,...l}:l&&(r=l);const h=!e&&!r;h&&(e={color:0});let d,f,m,g,y,x,o,c,u,p,_,b,v,w,S,T,E;switch(s.nodeName.toLowerCase()){case"path":{w=s.getAttribute("d");const P=s.getAttribute("fill-rule"),B=Wg(w),A=P==="evenodd",G=B.length>1;if(A&&G){const j=B.map(U=>({path:U,area:Vg(U)}));if(j.sort((U,R)=>R.area-U.area),B.length>3||!Hg(j))for(let U=0;U<j.length;U++){const R=j[U],wt=U===0;t.context.beginPath();const V=new se(void 0,!0);rl(R.path,V),t.context.path(V),wt?(e&&t.context.fill(e),r&&t.context.stroke(r)):t.context.cut()}else for(let U=0;U<j.length;U++){const R=j[U],wt=U%2===1;t.context.beginPath();const V=new se(void 0,!0);rl(R.path,V),t.context.path(V),wt?t.context.cut():(e&&t.context.fill(e),r&&t.context.stroke(r))}}else{const j=P?P==="evenodd":!0;S=new se(w,j),t.context.path(S),e&&t.context.fill(e),r&&t.context.stroke(r)}break}case"circle":o=st(s,"cx",0),c=st(s,"cy",0),u=st(s,"r",0),t.context.ellipse(o,c,u,u),e&&t.context.fill(e),r&&t.context.stroke(r);break;case"rect":d=st(s,"x",0),f=st(s,"y",0),T=st(s,"width",0),E=st(s,"height",0),p=st(s,"rx",0),_=st(s,"ry",0),p||_?t.context.roundRect(d,f,T,E,p||_):t.context.rect(d,f,T,E),e&&t.context.fill(e),r&&t.context.stroke(r);break;case"ellipse":o=st(s,"cx",0),c=st(s,"cy",0),p=st(s,"rx",0),_=st(s,"ry",0),t.context.beginPath(),t.context.ellipse(o,c,p,_),e&&t.context.fill(e),r&&t.context.stroke(r);break;case"line":m=st(s,"x1",0),g=st(s,"y1",0),y=st(s,"x2",0),x=st(s,"y2",0),t.context.beginPath(),t.context.moveTo(m,g),t.context.lineTo(y,x),r&&t.context.stroke(r);break;case"polygon":v=s.getAttribute("points"),b=v.match(/\d+/g).map(P=>parseInt(P,10)),t.context.poly(b,!0),e&&t.context.fill(e),r&&t.context.stroke(r);break;case"polyline":v=s.getAttribute("points"),b=v.match(/\d+/g).map(P=>parseInt(P,10)),t.context.poly(b,!1),r&&t.context.stroke(r);break;case"g":case"svg":break;default:{F(`[SVG parser] <${s.nodeName}> elements unsupported`);break}}h&&(e=null);for(let P=0;P<n.length;P++)sl(n[P],t,e,r)}function Xg(s){return J.isColorLike(s)}function nl(s){return s instanceof Ar}function al(s){return s instanceof Vt}function $g(s){return s instanceof M}function Kg(s,t,e){const r=J.shared.setValue(t??0);return s.color=r.toNumber(),s.alpha=r.alpha===1?e.alpha:r.alpha,s.texture=M.WHITE,{...e,...s}}function jg(s,t,e){return s.texture=t,{...e,...s}}function ol(s,t,e){return s.fill=t,s.color=16777215,s.texture=t.texture,s.matrix=t.transform,{...e,...s}}function hl(s,t,e){return t.buildGradient(),s.fill=t,s.color=16777215,s.texture=t.texture,s.matrix=t.transform,s.textureSpace=t.textureSpace,{...e,...s}}function qg(s,t){const e={...t,...s},r=J.shared.setValue(e.color);return e.alpha*=r.alpha,e.color=r.toNumber(),e}function Ee(s,t){if(s==null)return null;const e={},r=s;return Xg(s)?Kg(e,s,t):$g(s)?jg(e,s,t):nl(s)?ol(e,s,t):al(s)?hl(e,s,t):r.fill&&nl(r.fill)?ol(r,r.fill,t):r.fill&&al(r.fill)?hl(r,r.fill,t):qg(r,t)}function Rr(s,t){const{width:e,alignment:r,miterLimit:n,cap:a,join:l,pixelLine:h,...d}=t,f=Ee(s,d);return f?{width:e,alignment:r,miterLimit:n,cap:a,join:l,pixelLine:h,...f}:null}const Zg=new q,ll=new k,Sn=class qt extends Tt{constructor(){super(...arguments),this.uid=et("graphicsContext"),this.dirty=!0,this.batchMode="auto",this.instructions=[],this._activePath=new se,this._transform=new k,this._fillStyle={...qt.defaultFillStyle},this._strokeStyle={...qt.defaultStrokeStyle},this._stateStack=[],this._tick=0,this._bounds=new dt,this._boundsDirty=!0}clone(){const t=new qt;return t.batchMode=this.batchMode,t.instructions=this.instructions.slice(),t._activePath=this._activePath.clone(),t._transform=this._transform.clone(),t._fillStyle={...this._fillStyle},t._strokeStyle={...this._strokeStyle},t._stateStack=this._stateStack.slice(),t._bounds=this._bounds.clone(),t._boundsDirty=!0,t}get fillStyle(){return this._fillStyle}set fillStyle(t){this._fillStyle=Ee(t,qt.defaultFillStyle)}get strokeStyle(){return this._strokeStyle}set strokeStyle(t){this._strokeStyle=Rr(t,qt.defaultStrokeStyle)}setFillStyle(t){return this._fillStyle=Ee(t,qt.defaultFillStyle),this}setStrokeStyle(t){return this._strokeStyle=Ee(t,qt.defaultStrokeStyle),this}texture(t,e,r,n,a,l){return this.instructions.push({action:"texture",data:{image:t,dx:r||0,dy:n||0,dw:a||t.frame.width,dh:l||t.frame.height,transform:this._transform.clone(),alpha:this._fillStyle.alpha,style:e?J.shared.setValue(e).toNumber():16777215}}),this.onUpdate(),this}beginPath(){return this._activePath=new se,this}fill(t,e){let r;const n=this.instructions[this.instructions.length-1];return this._tick===0&&n?.action==="stroke"?r=n.data.path:r=this._activePath.clone(),r?(t!=null&&(e!==void 0&&typeof t=="number"&&(z($,"GraphicsContext.fill(color, alpha) is deprecated, use GraphicsContext.fill({ color, alpha }) instead"),t={color:t,alpha:e}),this._fillStyle=Ee(t,qt.defaultFillStyle)),this.instructions.push({action:"fill",data:{style:this.fillStyle,path:r}}),this.onUpdate(),this._initNextPathLocation(),this._tick=0,this):this}_initNextPathLocation(){const{x:t,y:e}=this._activePath.getLastPoint(q.shared);this._activePath.clear(),this._activePath.moveTo(t,e)}stroke(t){let e;const r=this.instructions[this.instructions.length-1];return this._tick===0&&r?.action==="fill"?e=r.data.path:e=this._activePath.clone(),e?(t!=null&&(this._strokeStyle=Rr(t,qt.defaultStrokeStyle)),this.instructions.push({action:"stroke",data:{style:this.strokeStyle,path:e}}),this.onUpdate(),this._initNextPathLocation(),this._tick=0,this):this}cut(){for(let t=0;t<2;t++){const e=this.instructions[this.instructions.length-1-t],r=this._activePath.clone();if(e&&(e.action==="stroke"||e.action==="fill"))if(e.data.hole)e.data.hole.addPath(r);else{e.data.hole=r;break}}return this._initNextPathLocation(),this}arc(t,e,r,n,a,l){this._tick++;const h=this._transform;return this._activePath.arc(h.a*t+h.c*e+h.tx,h.b*t+h.d*e+h.ty,r,n,a,l),this}arcTo(t,e,r,n,a){this._tick++;const l=this._transform;return this._activePath.arcTo(l.a*t+l.c*e+l.tx,l.b*t+l.d*e+l.ty,l.a*r+l.c*n+l.tx,l.b*r+l.d*n+l.ty,a),this}arcToSvg(t,e,r,n,a,l,h){this._tick++;const d=this._transform;return this._activePath.arcToSvg(t,e,r,n,a,d.a*l+d.c*h+d.tx,d.b*l+d.d*h+d.ty),this}bezierCurveTo(t,e,r,n,a,l,h){this._tick++;const d=this._transform;return this._activePath.bezierCurveTo(d.a*t+d.c*e+d.tx,d.b*t+d.d*e+d.ty,d.a*r+d.c*n+d.tx,d.b*r+d.d*n+d.ty,d.a*a+d.c*l+d.tx,d.b*a+d.d*l+d.ty,h),this}closePath(){return this._tick++,this._activePath?.closePath(),this}ellipse(t,e,r,n){return this._tick++,this._activePath.ellipse(t,e,r,n,this._transform.clone()),this}circle(t,e,r){return this._tick++,this._activePath.circle(t,e,r,this._transform.clone()),this}path(t){return this._tick++,this._activePath.addPath(t,this._transform.clone()),this}lineTo(t,e){this._tick++;const r=this._transform;return this._activePath.lineTo(r.a*t+r.c*e+r.tx,r.b*t+r.d*e+r.ty),this}moveTo(t,e){this._tick++;const r=this._transform,n=this._activePath.instructions,a=r.a*t+r.c*e+r.tx,l=r.b*t+r.d*e+r.ty;return n.length===1&&n[0].action==="moveTo"?(n[0].data[0]=a,n[0].data[1]=l,this):(this._activePath.moveTo(a,l),this)}quadraticCurveTo(t,e,r,n,a){this._tick++;const l=this._transform;return this._activePath.quadraticCurveTo(l.a*t+l.c*e+l.tx,l.b*t+l.d*e+l.ty,l.a*r+l.c*n+l.tx,l.b*r+l.d*n+l.ty,a),this}rect(t,e,r,n){return this._tick++,this._activePath.rect(t,e,r,n,this._transform.clone()),this}roundRect(t,e,r,n,a){return this._tick++,this._activePath.roundRect(t,e,r,n,a,this._transform.clone()),this}poly(t,e){return this._tick++,this._activePath.poly(t,e,this._transform.clone()),this}regularPoly(t,e,r,n,a=0,l){return this._tick++,this._activePath.regularPoly(t,e,r,n,a,l),this}roundPoly(t,e,r,n,a,l){return this._tick++,this._activePath.roundPoly(t,e,r,n,a,l),this}roundShape(t,e,r,n){return this._tick++,this._activePath.roundShape(t,e,r,n),this}filletRect(t,e,r,n,a){return this._tick++,this._activePath.filletRect(t,e,r,n,a),this}chamferRect(t,e,r,n,a,l){return this._tick++,this._activePath.chamferRect(t,e,r,n,a,l),this}star(t,e,r,n,a=0,l=0){return this._tick++,this._activePath.star(t,e,r,n,a,l,this._transform.clone()),this}svg(t){return this._tick++,Yg(t,this),this}restore(){const t=this._stateStack.pop();return t&&(this._transform=t.transform,this._fillStyle=t.fillStyle,this._strokeStyle=t.strokeStyle),this}save(){return this._stateStack.push({transform:this._transform.clone(),fillStyle:{...this._fillStyle},strokeStyle:{...this._strokeStyle}}),this}getTransform(){return this._transform}resetTransform(){return this._transform.identity(),this}rotate(t){return this._transform.rotate(t),this}scale(t,e=t){return this._transform.scale(t,e),this}setTransform(t,e,r,n,a,l){return t instanceof k?(this._transform.set(t.a,t.b,t.c,t.d,t.tx,t.ty),this):(this._transform.set(t,e,r,n,a,l),this)}transform(t,e,r,n,a,l){return t instanceof k?(this._transform.append(t),this):(ll.set(t,e,r,n,a,l),this._transform.append(ll),this)}translate(t,e=t){return this._transform.translate(t,e),this}clear(){return this._activePath.clear(),this.instructions.length=0,this.resetTransform(),this.onUpdate(),this}onUpdate(){this._boundsDirty=!0,!this.dirty&&(this.emit("update",this,16),this.dirty=!0)}get bounds(){if(!this._boundsDirty)return this._bounds;this._boundsDirty=!1;const t=this._bounds;t.clear();for(let e=0;e<this.instructions.length;e++){const r=this.instructions[e],n=r.action;if(n==="fill"){const a=r.data;t.addBounds(a.path.bounds)}else if(n==="texture"){const a=r.data;t.addFrame(a.dx,a.dy,a.dx+a.dw,a.dy+a.dh,a.transform)}if(n==="stroke"){const a=r.data,l=a.style.alignment,h=a.style.width*(1-l),d=a.path.bounds;t.addFrame(d.minX-h,d.minY-h,d.maxX+h,d.maxY+h)}}return t}containsPoint(t){if(!this.bounds.containsPoint(t.x,t.y))return!1;const e=this.instructions;let r=!1;for(let n=0;n<e.length;n++){const a=e[n],l=a.data,h=l.path;if(!a.action||!h)continue;const d=l.style,f=h.shapePath.shapePrimitives;for(let m=0;m<f.length;m++){const g=f[m].shape;if(!d||!g)continue;const y=f[m].transform,x=y?y.applyInverse(t,Zg):t;if(a.action==="fill")r=g.contains(x.x,x.y);else{const c=d;r=g.strokeContains(x.x,x.y,c.width,c.alignment)}const o=l.hole;if(o){const c=o.shapePath?.shapePrimitives;if(c)for(let u=0;u<c.length;u++)c[u].shape.contains(x.x,x.y)&&(r=!1)}if(r)return!0}}return r}destroy(t=!1){if(this._stateStack.length=0,this._transform=null,this.emit("destroy",this),this.removeAllListeners(),typeof t=="boolean"?t:t?.texture){const r=typeof t=="boolean"?t:t?.textureSource;this._fillStyle.texture&&(this._fillStyle.fill&&"uid"in this._fillStyle.fill?this._fillStyle.fill.destroy():this._fillStyle.texture.destroy(r)),this._strokeStyle.texture&&(this._strokeStyle.fill&&"uid"in this._strokeStyle.fill?this._strokeStyle.fill.destroy():this._strokeStyle.texture.destroy(r))}this._fillStyle=null,this._strokeStyle=null,this.instructions=null,this._activePath=null,this._bounds=null,this._stateStack=null,this.customShader=null,this._transform=null}};Sn.defaultFillStyle={color:16777215,alpha:1,texture:M.WHITE,matrix:null,fill:null,textureSpace:"local"},Sn.defaultStrokeStyle={width:1,color:16777215,alpha:1,alignment:.5,miterLimit:10,cap:"butt",join:"miter",texture:M.WHITE,matrix:null,fill:null,textureSpace:"local",pixelLine:!1};let Ft=Sn;const Tn=class ii extends Tt{constructor(t={}){super(),this.uid=et("textStyle"),this._tick=0,Qg(t);const e={...ii.defaultTextStyle,...t};for(const r in e){const n=r;this[n]=e[r]}this.update(),this._tick=0}get align(){return this._align}set align(t){this._align!==t&&(this._align=t,this.update())}get breakWords(){return this._breakWords}set breakWords(t){this._breakWords!==t&&(this._breakWords=t,this.update())}get dropShadow(){return this._dropShadow}set dropShadow(t){this._dropShadow!==t&&(t!==null&&typeof t=="object"?this._dropShadow=this._createProxy({...ii.defaultDropShadow,...t}):this._dropShadow=t?this._createProxy({...ii.defaultDropShadow}):null,this.update())}get fontFamily(){return this._fontFamily}set fontFamily(t){this._fontFamily!==t&&(this._fontFamily=t,this.update())}get fontSize(){return this._fontSize}set fontSize(t){this._fontSize!==t&&(typeof t=="string"?this._fontSize=parseInt(t,10):this._fontSize=t,this.update())}get fontStyle(){return this._fontStyle}set fontStyle(t){this._fontStyle!==t&&(this._fontStyle=t.toLowerCase(),this.update())}get fontVariant(){return this._fontVariant}set fontVariant(t){this._fontVariant!==t&&(this._fontVariant=t,this.update())}get fontWeight(){return this._fontWeight}set fontWeight(t){this._fontWeight!==t&&(this._fontWeight=t,this.update())}get leading(){return this._leading}set leading(t){this._leading!==t&&(this._leading=t,this.update())}get letterSpacing(){return this._letterSpacing}set letterSpacing(t){this._letterSpacing!==t&&(this._letterSpacing=t,this.update())}get lineHeight(){return this._lineHeight}set lineHeight(t){this._lineHeight!==t&&(this._lineHeight=t,this.update())}get padding(){return this._padding}set padding(t){this._padding!==t&&(this._padding=t,this.update())}get filters(){return this._filters}set filters(t){this._filters!==t&&(this._filters=Object.freeze(t),this.update())}get trim(){return this._trim}set trim(t){this._trim!==t&&(this._trim=t,this.update())}get textBaseline(){return this._textBaseline}set textBaseline(t){this._textBaseline!==t&&(this._textBaseline=t,this.update())}get whiteSpace(){return this._whiteSpace}set whiteSpace(t){this._whiteSpace!==t&&(this._whiteSpace=t,this.update())}get wordWrap(){return this._wordWrap}set wordWrap(t){this._wordWrap!==t&&(this._wordWrap=t,this.update())}get wordWrapWidth(){return this._wordWrapWidth}set wordWrapWidth(t){this._wordWrapWidth!==t&&(this._wordWrapWidth=t,this.update())}get fill(){return this._originalFill}set fill(t){t!==this._originalFill&&(this._originalFill=t,this._isFillStyle(t)&&(this._originalFill=this._createProxy({...Ft.defaultFillStyle,...t},()=>{this._fill=Ee({...this._originalFill},Ft.defaultFillStyle)})),this._fill=Ee(t===0?"black":t,Ft.defaultFillStyle),this.update())}get stroke(){return this._originalStroke}set stroke(t){t!==this._originalStroke&&(this._originalStroke=t,this._isFillStyle(t)&&(this._originalStroke=this._createProxy({...Ft.defaultStrokeStyle,...t},()=>{this._stroke=Rr({...this._originalStroke},Ft.defaultStrokeStyle)})),this._stroke=Rr(t,Ft.defaultStrokeStyle),this.update())}update(){this._tick++,this.emit("update",this)}reset(){const t=ii.defaultTextStyle;for(const e in t)this[e]=t[e]}get styleKey(){return`${this.uid}-${this._tick}`}clone(){return new ii({align:this.align,breakWords:this.breakWords,dropShadow:this._dropShadow?{...this._dropShadow}:null,fill:this._fill,fontFamily:this.fontFamily,fontSize:this.fontSize,fontStyle:this.fontStyle,fontVariant:this.fontVariant,fontWeight:this.fontWeight,leading:this.leading,letterSpacing:this.letterSpacing,lineHeight:this.lineHeight,padding:this.padding,stroke:this._stroke,textBaseline:this.textBaseline,whiteSpace:this.whiteSpace,wordWrap:this.wordWrap,wordWrapWidth:this.wordWrapWidth,filters:this._filters?[...this._filters]:void 0})}_getFinalPadding(){let t=0;if(this._filters)for(let e=0;e<this._filters.length;e++)t+=this._filters[e].padding;return Math.max(this._padding,t)}destroy(t=!1){if(this.removeAllListeners(),typeof t=="boolean"?t:t?.texture){const r=typeof t=="boolean"?t:t?.textureSource;this._fill?.texture&&this._fill.texture.destroy(r),this._originalFill?.texture&&this._originalFill.texture.destroy(r),this._stroke?.texture&&this._stroke.texture.destroy(r),this._originalStroke?.texture&&this._originalStroke.texture.destroy(r)}this._fill=null,this._stroke=null,this.dropShadow=null,this._originalStroke=null,this._originalFill=null}_createProxy(t,e){return new Proxy(t,{set:(r,n,a)=>(r[n]===a||(r[n]=a,e?.(n,a),this.update()),!0)})}_isFillStyle(t){return(t??null)!==null&&!(J.isColorLike(t)||t instanceof Vt||t instanceof Ar)}};Tn.defaultDropShadow={alpha:1,angle:Math.PI/6,blur:0,color:"black",distance:5},Tn.defaultTextStyle={align:"left",breakWords:!1,dropShadow:null,fill:"black",fontFamily:"Arial",fontSize:26,fontStyle:"normal",fontVariant:"normal",fontWeight:"normal",leading:0,letterSpacing:0,lineHeight:0,padding:0,stroke:null,textBaseline:"alphabetic",trim:!1,whiteSpace:"pre",wordWrap:!1,wordWrapWidth:100};let Bt=Tn;function Qg(s){const t=s;if(typeof t.dropShadow=="boolean"&&t.dropShadow){const e=Bt.defaultDropShadow;s.dropShadow={alpha:t.dropShadowAlpha??e.alpha,angle:t.dropShadowAngle??e.angle,blur:t.dropShadowBlur??e.blur,color:t.dropShadowColor??e.color,distance:t.dropShadowDistance??e.distance}}if(t.strokeThickness!==void 0){z($,"strokeThickness is now a part of stroke");const e=t.stroke;let r={};if(J.isColorLike(e))r.color=e;else if(e instanceof Vt||e instanceof Ar)r.fill=e;else if(Object.hasOwnProperty.call(e,"color")||Object.hasOwnProperty.call(e,"fill"))r=e;else throw new Error("Invalid stroke value.");s.stroke={...r,width:t.strokeThickness}}if(Array.isArray(t.fillGradientStops)){if(z($,"gradient fill is now a fill pattern: `new FillGradient(...)`"),!Array.isArray(t.fill)||t.fill.length===0)throw new Error("Invalid fill value. Expected an array of colors for gradient fill.");t.fill.length!==t.fillGradientStops.length&&F("The number of fill colors must match the number of fill gradient stops.");const e=new Vt({start:{x:0,y:0},end:{x:0,y:1},textureSpace:"local"}),r=t.fillGradientStops.slice(),n=t.fill.map(a=>J.shared.setValue(a).toNumber());r.forEach((a,l)=>{e.addColorStop(a,n[l])}),s.fill={fill:e}}}class Jg{constructor(t){this._canvasPool=Object.create(null),this.canvasOptions=t||{},this.enableFullScreen=!1}_createCanvasAndContext(t,e){const r=W.get().createCanvas();r.width=t,r.height=e;const n=r.getContext("2d");return{canvas:r,context:n}}getOptimalCanvasAndContext(t,e,r=1){t=Math.ceil(t*r-1e-6),e=Math.ceil(e*r-1e-6),t=Le(t),e=Le(e);const n=(t<<17)+(e<<1);this._canvasPool[n]||(this._canvasPool[n]=[]);let a=this._canvasPool[n].pop();return a||(a=this._createCanvasAndContext(t,e)),a}returnCanvasAndContext(t){const e=t.canvas,{width:r,height:n}=e,a=(r<<17)+(n<<1);t.context.resetTransform(),t.context.clearRect(0,0,r,n),this._canvasPool[a].push(t)}clear(){this._canvasPool={}}}const ne=new Jg;Ne.register(ne);const cl=1e5;function Ir(s,t,e,r=0){if(s.texture===M.WHITE&&!s.fill)return J.shared.setValue(s.color).setAlpha(s.alpha??1).toHexa();if(s.fill){if(s.fill instanceof Ar){const n=s.fill,a=t.createPattern(n.texture.source.resource,"repeat"),l=n.transform.copyTo(k.shared);return l.scale(n.texture.frame.width,n.texture.frame.height),a.setTransform(l),a}else if(s.fill instanceof Vt){const n=s.fill,a=n.type==="linear",l=n.textureSpace==="local";let h=1,d=1;l&&e&&(h=e.width+r,d=e.height+r);let f,m=!1;if(a){const{start:g,end:y}=n;f=t.createLinearGradient(g.x*h,g.y*d,y.x*h,y.y*d),m=Math.abs(y.x-g.x)<Math.abs((y.y-g.y)*.1)}else{const{center:g,innerRadius:y,outerCenter:x,outerRadius:o}=n;f=t.createRadialGradient(g.x*h,g.y*d,y*h,x.x*h,x.y*d,o*h)}if(m&&l&&e){const g=e.lineHeight/d;for(let y=0;y<e.lines.length;y++){const x=(y*e.lineHeight+r/2)/d;n.colorStops.forEach(o=>{const c=x+o.offset*g;f.addColorStop(Math.floor(c*cl)/cl,J.shared.setValue(o.color).toHex())})}}else n.colorStops.forEach(g=>{f.addColorStop(g.offset,J.shared.setValue(g.color).toHex())});return f}}else{const n=t.createPattern(s.texture.source.resource,"repeat"),a=s.matrix.copyTo(k.shared);return a.scale(s.texture.frame.width,s.texture.frame.height),n.setTransform(a),n}return F("FillStyle not recognised",s),"red"}const ul=class td extends bh{constructor(t){super(),this.resolution=1,this.pages=[],this._padding=0,this._measureCache=Object.create(null),this._currentChars=[],this._currentX=0,this._currentY=0,this._currentMaxCharHeight=0,this._currentPageIndex=-1,this._skipKerning=!1;const e={...td.defaultOptions,...t};this._textureSize=e.textureSize,this._mipmap=e.mipmap;const r=e.style.clone();e.overrideFill&&(r._fill.color=16777215,r._fill.alpha=1,r._fill.texture=M.WHITE,r._fill.fill=null),this.applyFillAsTint=e.overrideFill;const n=r.fontSize;r.fontSize=this.baseMeasurementFontSize;const a=Er(r);e.overrideSize?r._stroke&&(r._stroke.width*=this.baseRenderedFontSize/n):r.fontSize=this.baseRenderedFontSize=n,this._style=r,this._skipKerning=e.skipKerning??!1,this.resolution=e.resolution??1,this._padding=e.padding??4,e.textureStyle&&(this._textureStyle=e.textureStyle instanceof Kt?e.textureStyle:new Kt(e.textureStyle)),this.fontMetrics=xt.measureFont(a),this.lineHeight=r.lineHeight||this.fontMetrics.fontSize||r.fontSize}ensureCharacters(t){const e=xt.graphemeSegmenter(t).filter(u=>!this._currentChars.includes(u)).filter((u,p,_)=>_.indexOf(u)===p);if(!e.length)return;this._currentChars=[...this._currentChars,...e];let r;this._currentPageIndex===-1?r=this._nextPage():r=this.pages[this._currentPageIndex];let{canvas:n,context:a}=r.canvasAndContext,l=r.texture.source;const h=this._style;let d=this._currentX,f=this._currentY,m=this._currentMaxCharHeight;const g=this.baseRenderedFontSize/this.baseMeasurementFontSize,y=this._padding*g;let x=!1;const o=n.width/this.resolution,c=n.height/this.resolution;for(let u=0;u<e.length;u++){const p=e[u],_=xt.measureText(p,h,n,!1);_.lineHeight=_.height;const b=_.width*g,v=Math.ceil((h.fontStyle==="italic"?2:1)*b),w=_.height*g,S=v+y*2,T=w+y*2;if(x=!1,p!==`
|
|
318
|
-
`&&p!=="\r"&&p!==" "&&p!==" "&&(x=!0,m=Math.ceil(Math.max(T,m))),
|
|
319
|
-
`||b){if(!h&&t.wordWrap&&
|
|
320
|
-
`)c();else if(!b){const E=v.xAdvance+(v.kerning[l]||0)+m;a.width+=E,a.spaceWidth=E,a.spacesIndex.push(a.charPositions.length),a.chars.push(_)}}else{const T=v.kerning[l]||0,E=v.xAdvance+T+m;x&&u(a.width+d.width+E)&&(o(d),c()),d.positions[d.index++]=d.width+T,d.chars.push(_),d.width+=E}l=_}return c(),t.align==="center"?t_(n):t.align==="right"?e_(n):t.align==="justify"&&i_(n),n}function t_(s){for(let t=0;t<s.lines.length;t++){const e=s.lines[t],r=s.width/2-e.width/2;for(let n=0;n<e.charPositions.length;n++)e.charPositions[n]+=r}}function e_(s){for(let t=0;t<s.lines.length;t++){const e=s.lines[t],r=s.width-e.width;for(let n=0;n<e.charPositions.length;n++)e.charPositions[n]+=r}}function i_(s){const t=s.width;for(let e=0;e<s.lines.length;e++){const r=s.lines[e];let n=0,a=r.spacesIndex[n++],l=0;const h=r.spacesIndex.length,f=(t-r.width)/h;for(let m=0;m<r.charPositions.length;m++)m===a&&(a=r.spacesIndex[n++],l+=f),r.charPositions[m]+=l}}function r_(s){if(s==="")return[];typeof s=="string"&&(s=[s]);const t=[];for(let e=0,r=s.length;e<r;e++){const n=s[e];if(Array.isArray(n)){if(n.length!==2)throw new Error(`[BitmapFont]: Invalid character range length, expecting 2 got ${n.length}.`);if(n[0].length===0||n[1].length===0)throw new Error("[BitmapFont]: Invalid character delimiter.");const a=n[0].charCodeAt(0),l=n[1].charCodeAt(0);if(l<a)throw new Error("[BitmapFont]: Invalid character range.");for(let h=a,d=l;h<=d;h++)t.push(String.fromCharCode(h))}else t.push(...Array.from(n))}if(t.length===0)throw new Error("[BitmapFont]: Empty set when resolving characters.");return t}let Fr=0;class s_{constructor(){this.ALPHA=[["a","z"],["A","Z"]," "],this.NUMERIC=[["0","9"]],this.ALPHANUMERIC=[["a","z"],["A","Z"],["0","9"]," "],this.ASCII=[[" ","~"]],this.defaultOptions={chars:this.ALPHANUMERIC,resolution:1,padding:4,skipKerning:!1,textureStyle:null},this.measureCache=vh(1e3)}getFont(t,e){let r=`${e.fontFamily}-bitmap`,n=!0;if(e._fill.fill&&!e._stroke?(r+=e._fill.fill.styleKey,n=!1):(e._stroke||e.dropShadow)&&(r=`${e.styleKey}-bitmap`,n=!1),!Q.has(r)){const l=Object.create(e);l.lineHeight=0;const h=new dl({style:l,overrideFill:n,overrideSize:!0,...this.defaultOptions});Fr++,Fr>50&&F("BitmapText",`You have dynamically created ${Fr} bitmap fonts, this can be inefficient. Try pre installing your font styles using \`BitmapFont.install({name:"style1", style})\``),h.once("destroy",()=>{Fr--,Q.remove(r)}),Q.set(r,h)}const a=Q.get(r);return a.ensureCharacters?.(t),a}getLayout(t,e,r=!0){const n=this.getFont(t,e),a=`${t}-${e.styleKey}-${r}`;if(this.measureCache.has(a))return this.measureCache.get(a);const l=xt.graphemeSegmenter(t),h=Cn(l,e,n,r);return this.measureCache.set(a,h),h}measureText(t,e,r=!0){return this.getLayout(t,e,r)}install(...t){let e=t[0];typeof e=="string"&&(e={name:e,style:t[1],chars:t[2]?.chars,resolution:t[2]?.resolution,padding:t[2]?.padding,skipKerning:t[2]?.skipKerning},z($,"BitmapFontManager.install(name, style, options) is deprecated, use BitmapFontManager.install({name, style, ...options})"));const r=e?.name;if(!r)throw new Error("[BitmapFontManager] Property `name` is required.");e={...this.defaultOptions,...e};const n=e.style,a=n instanceof Bt?n:new Bt(n),l=e.dynamicFill??this._canUseTintForStyle(a),h=new dl({style:a,overrideFill:l,skipKerning:e.skipKerning,padding:e.padding,resolution:e.resolution,overrideSize:!1,textureStyle:e.textureStyle}),d=r_(e.chars);return h.ensureCharacters(d.join("")),Q.set(`${r}-bitmap`,h),h.once("destroy",()=>Q.remove(`${r}-bitmap`)),h}uninstall(t){const e=`${t}-bitmap`,r=Q.get(e);r&&r.destroy()}_canUseTintForStyle(t){return!t._stroke&&(!t.dropShadow||t.dropShadow.color===0)&&!t._fill.fill&&t._fill.color===16777215}}const Gi=new s_;class fl extends bh{constructor(t,e){super();const{textures:r,data:n}=t;Object.keys(n.pages).forEach(a=>{const l=n.pages[parseInt(a,10)],h=r[l.id];this.pages.push({texture:h})}),Object.keys(n.chars).forEach(a=>{const l=n.chars[a],{frame:h,source:d,rotate:f}=r[l.page],m=Z.transformRectCoords(l,h,f,new L),g=new M({frame:m,orig:new L(0,0,l.width,l.height),source:d,rotate:f});this.chars[a]={id:a.codePointAt(0),xOffset:l.xOffset,yOffset:l.yOffset,xAdvance:l.xAdvance,kerning:l.kerning??{},texture:g}}),this.baseRenderedFontSize=n.fontSize,this.baseMeasurementFontSize=n.fontSize,this.fontMetrics={ascent:0,descent:0,fontSize:n.fontSize},this.baseLineOffset=n.baseLineOffset,this.lineHeight=n.lineHeight,this.fontFamily=n.fontFamily,this.distanceField=n.distanceField??{type:"none",range:0},this.url=e}destroy(){super.destroy();for(let t=0;t<this.pages.length;t++){const{texture:e}=this.pages[t];e.destroy(!0)}this.pages=null}static install(t){Gi.install(t)}static uninstall(t){Gi.uninstall(t)}}const En={test(s){return typeof s=="string"&&s.startsWith("info face=")},parse(s){const t=s.match(/^[a-z]+\s+.+$/gm),e={info:[],common:[],page:[],char:[],chars:[],kerning:[],kernings:[],distanceField:[]};for(const g in t){const y=t[g].match(/^[a-z]+/gm)[0],x=t[g].match(/[a-zA-Z]+=([^\s"']+|"([^"]*)")/gm),o={};for(const c in x){const u=x[c].split("="),p=u[0],_=u[1].replace(/"/gm,""),b=parseFloat(_),v=isNaN(b)?_:b;o[p]=v}e[y].push(o)}const r={chars:{},pages:[],lineHeight:0,fontSize:0,fontFamily:"",distanceField:null,baseLineOffset:0},[n]=e.info,[a]=e.common,[l]=e.distanceField??[];l&&(r.distanceField={range:parseInt(l.distanceRange,10),type:l.fieldType}),r.fontSize=parseInt(n.size,10),r.fontFamily=n.face,r.lineHeight=parseInt(a.lineHeight,10);const h=e.page;for(let g=0;g<h.length;g++)r.pages.push({id:parseInt(h[g].id,10)||0,file:h[g].file});const d={};r.baseLineOffset=r.lineHeight-parseInt(a.base,10);const f=e.char;for(let g=0;g<f.length;g++){const y=f[g],x=parseInt(y.id,10);let o=y.letter??y.char??String.fromCharCode(x);o==="space"&&(o=" "),d[x]=o,r.chars[o]={id:x,page:parseInt(y.page,10)||0,x:parseInt(y.x,10),y:parseInt(y.y,10),width:parseInt(y.width,10),height:parseInt(y.height,10),xOffset:parseInt(y.xoffset,10),yOffset:parseInt(y.yoffset,10),xAdvance:parseInt(y.xadvance,10),kerning:{}}}const m=e.kerning||[];for(let g=0;g<m.length;g++){const y=parseInt(m[g].first,10),x=parseInt(m[g].second,10),o=parseInt(m[g].amount,10);r.chars[d[x]].kerning[d[y]]=o}return r}},pl={test(s){const t=s;return typeof t!="string"&&"getElementsByTagName"in t&&t.getElementsByTagName("page").length&&t.getElementsByTagName("info")[0].getAttribute("face")!==null},parse(s){const t={chars:{},pages:[],lineHeight:0,fontSize:0,fontFamily:"",distanceField:null,baseLineOffset:0},e=s.getElementsByTagName("info")[0],r=s.getElementsByTagName("common")[0],n=s.getElementsByTagName("distanceField")[0];n&&(t.distanceField={type:n.getAttribute("fieldType"),range:parseInt(n.getAttribute("distanceRange"),10)});const a=s.getElementsByTagName("page"),l=s.getElementsByTagName("char"),h=s.getElementsByTagName("kerning");t.fontSize=parseInt(e.getAttribute("size"),10),t.fontFamily=e.getAttribute("face"),t.lineHeight=parseInt(r.getAttribute("lineHeight"),10);for(let f=0;f<a.length;f++)t.pages.push({id:parseInt(a[f].getAttribute("id"),10)||0,file:a[f].getAttribute("file")});const d={};t.baseLineOffset=t.lineHeight-parseInt(r.getAttribute("base"),10);for(let f=0;f<l.length;f++){const m=l[f],g=parseInt(m.getAttribute("id"),10);let y=m.getAttribute("letter")??m.getAttribute("char")??String.fromCharCode(g);y==="space"&&(y=" "),d[g]=y,t.chars[y]={id:g,page:parseInt(m.getAttribute("page"),10)||0,x:parseInt(m.getAttribute("x"),10),y:parseInt(m.getAttribute("y"),10),width:parseInt(m.getAttribute("width"),10),height:parseInt(m.getAttribute("height"),10),xOffset:parseInt(m.getAttribute("xoffset"),10),yOffset:parseInt(m.getAttribute("yoffset"),10),xAdvance:parseInt(m.getAttribute("xadvance"),10),kerning:{}}}for(let f=0;f<h.length;f++){const m=parseInt(h[f].getAttribute("first"),10),g=parseInt(h[f].getAttribute("second"),10),y=parseInt(h[f].getAttribute("amount"),10);t.chars[d[g]].kerning[d[m]]=y}return t}},ml={test(s){return typeof s=="string"&&s.match(/<font(\s|>)/)?pl.test(W.get().parseXML(s)):!1},parse(s){return pl.parse(W.get().parseXML(s))}},n_=[".xml",".fnt"],a_={extension:{type:C.CacheParser,name:"cacheBitmapFont"},test:s=>s instanceof fl,getCacheableAssets(s,t){const e={};return s.forEach(r=>{e[r]=t,e[`${r}-bitmap`]=t}),e[`${t.fontFamily}-bitmap`]=t,e}},o_={extension:{type:C.LoadParser,priority:ce.Normal},name:"loadBitmapFont",id:"bitmap-font",test(s){return n_.includes(Et.extname(s).toLowerCase())},async testParse(s){return En.test(s)||ml.test(s)},async parse(s,t,e){const r=En.test(s)?En.parse(s):ml.parse(s),{src:n}=t,{pages:a}=r,l=[],h=r.distanceField?{scaleMode:"linear",alphaMode:"premultiply-alpha-on-upload",autoGenerateMipmaps:!1,resolution:1}:{};for(let g=0;g<a.length;++g){const y=a[g].file;let x=Et.join(Et.dirname(n),y);x=Fs(x,n),l.push({src:x,data:h})}const d=await e.load(l),f=l.map(g=>d[g.src]);return new fl({data:r,textures:f},n)},async load(s,t){return await(await W.get().fetch(s)).text()},async unload(s,t,e){await Promise.all(s.pages.map(r=>e.unload(r.texture.source._sourceOrigin))),s.destroy()}};class h_{constructor(t,e=!1){this._loader=t,this._assetList=[],this._isLoading=!1,this._maxConcurrent=1,this.verbose=e}add(t){t.forEach(e=>{this._assetList.push(e)}),this.verbose&&console.log("[BackgroundLoader] assets: ",this._assetList),this._isActive&&!this._isLoading&&this._next()}async _next(){if(this._assetList.length&&this._isActive){this._isLoading=!0;const t=[],e=Math.min(this._assetList.length,this._maxConcurrent);for(let r=0;r<e;r++)t.push(this._assetList.pop());await this._loader.load(t),this._isLoading=!1,this._next()}}get active(){return this._isActive}set active(t){this._isActive!==t&&(this._isActive=t,t&&!this._isLoading&&this._next())}}const l_={extension:{type:C.CacheParser,name:"cacheTextureArray"},test:s=>Array.isArray(s)&&s.every(t=>t instanceof M),getCacheableAssets:(s,t)=>{const e={};return s.forEach(r=>{t.forEach((n,a)=>{e[r+(a===0?"":a+1)]=n})}),e}};async function gl(s){if("Image"in globalThis)return new Promise(t=>{const e=new Image;e.onload=()=>{t(!0)},e.onerror=()=>{t(!1)},e.src=s});if("createImageBitmap"in globalThis&&"fetch"in globalThis){try{const t=await(await fetch(s)).blob();await createImageBitmap(t)}catch{return!1}return!0}return!1}const c_={extension:{type:C.DetectionParser,priority:1},test:async()=>gl("data:image/avif;base64,AAAAIGZ0eXBhdmlmAAAAAGF2aWZtaWYxbWlhZk1BMUIAAADybWV0YQAAAAAAAAAoaGRscgAAAAAAAAAAcGljdAAAAAAAAAAAAAAAAGxpYmF2aWYAAAAADnBpdG0AAAAAAAEAAAAeaWxvYwAAAABEAAABAAEAAAABAAABGgAAAB0AAAAoaWluZgAAAAAAAQAAABppbmZlAgAAAAABAABhdjAxQ29sb3IAAAAAamlwcnAAAABLaXBjbwAAABRpc3BlAAAAAAAAAAIAAAACAAAAEHBpeGkAAAAAAwgICAAAAAxhdjFDgQ0MAAAAABNjb2xybmNseAACAAIAAYAAAAAXaXBtYQAAAAAAAAABAAEEAQKDBAAAACVtZGF0EgAKCBgANogQEAwgMg8f8D///8WfhwB8+ErK42A="),add:async s=>[...s,"avif"],remove:async s=>s.filter(t=>t!=="avif")},_l=["png","jpg","jpeg"],u_={extension:{type:C.DetectionParser,priority:-1},test:()=>Promise.resolve(!0),add:async s=>[...s,..._l],remove:async s=>s.filter(t=>!_l.includes(t))},d_="WorkerGlobalScope"in globalThis&&globalThis instanceof globalThis.WorkerGlobalScope;function Dr(s){return d_?!1:document.createElement("video").canPlayType(s)!==""}const f_={extension:{type:C.DetectionParser,priority:0},test:async()=>Dr("video/mp4"),add:async s=>[...s,"mp4","m4v"],remove:async s=>s.filter(t=>t!=="mp4"&&t!=="m4v")},p_={extension:{type:C.DetectionParser,priority:0},test:async()=>Dr("video/ogg"),add:async s=>[...s,"ogv"],remove:async s=>s.filter(t=>t!=="ogv")},m_={extension:{type:C.DetectionParser,priority:0},test:async()=>Dr("video/webm"),add:async s=>[...s,"webm"],remove:async s=>s.filter(t=>t!=="webm")},g_={extension:{type:C.DetectionParser,priority:0},test:async()=>gl("data:image/webp;base64,UklGRh4AAABXRUJQVlA4TBEAAAAvAAAAAAfQ//73v/+BiOh/AAA="),add:async s=>[...s,"webp"],remove:async s=>s.filter(t=>t!=="webp")},yl=class Kr{constructor(){this.loadOptions={...Kr.defaultOptions},this._parsers=[],this._parsersValidated=!1,this.parsers=new Proxy(this._parsers,{set:(t,e,r)=>(this._parsersValidated=!1,t[e]=r,!0)}),this.promiseCache={}}reset(){this._parsersValidated=!1,this.promiseCache={}}_getLoadPromiseAndParser(t,e){const r={promise:null,parser:null};return r.promise=(async()=>{let n=null,a=null;if((e.parser||e.loadParser)&&(a=this._parserHash[e.parser||e.loadParser],e.loadParser&&F(`[Assets] "loadParser" is deprecated, use "parser" instead for ${t}`),a||F(`[Assets] specified load parser "${e.parser||e.loadParser}" not found while loading ${t}`)),!a){for(let l=0;l<this.parsers.length;l++){const h=this.parsers[l];if(h.load&&h.test?.(t,e,this)){a=h;break}}if(!a)return F(`[Assets] ${t} could not be loaded as we don't know how to parse it, ensure the correct parser has been added`),null}n=await a.load(t,e,this),r.parser=a;for(let l=0;l<this.parsers.length;l++){const h=this.parsers[l];h.parse&&h.parse&&await h.testParse?.(n,e,this)&&(n=await h.parse(n,e,this)||n,r.parser=h)}return n})(),r}async load(t,e){this._parsersValidated||this._validateParsers();const r=typeof e=="function"?{...Kr.defaultOptions,...this.loadOptions,onProgress:e}:{...Kr.defaultOptions,...this.loadOptions,...e||{}},{onProgress:n,onError:a,strategy:l,retryCount:h,retryDelay:d}=r;let f=0;const m={},g=gr(t),y=Lt(t,c=>({alias:[c],src:c,data:{}})),x=y.reduce((c,u)=>c+(u.progressSize||1),0),o=y.map(async c=>{const u=Et.toAbsolute(c.src);m[c.src]||(await this._loadAssetWithRetry(u,c,{onProgress:n,onError:a,strategy:l,retryCount:h,retryDelay:d},m),f+=c.progressSize||1,n&&n(f/x))});return await Promise.all(o),g?m[y[0].src]:m}async unload(t){const r=Lt(t,n=>({alias:[n],src:n})).map(async n=>{const a=Et.toAbsolute(n.src),l=this.promiseCache[a];if(l){const h=await l.promise;delete this.promiseCache[a],await l.parser?.unload?.(h,n,this)}});await Promise.all(r)}_validateParsers(){this._parsersValidated=!0,this._parserHash=this._parsers.filter(t=>t.name||t.id).reduce((t,e)=>(!e.name&&!e.id?F("[Assets] parser should have an id"):(t[e.name]||t[e.id])&&F(`[Assets] parser id conflict "${e.id}"`),t[e.name]=e,e.id&&(t[e.id]=e),t),{})}async _loadAssetWithRetry(t,e,r,n){let a=0;const{onError:l,strategy:h,retryCount:d,retryDelay:f}=r,m=g=>new Promise(y=>setTimeout(y,g));for(;;)try{this.promiseCache[t]||(this.promiseCache[t]=this._getLoadPromiseAndParser(t,e)),n[e.src]=await this.promiseCache[t].promise;return}catch(g){delete this.promiseCache[t],delete n[e.src],a++;const y=h!=="retry"||a>d;if(h==="retry"&&!y){l&&l(g,e),await m(f);continue}if(h==="skip"){l&&l(g,e);return}throw l&&l(g,e),new Error(`[Loader.load] Failed to load ${t}.
|
|
321
|
-
${g}`)}}};
|
|
317
|
+
`}},Yh={};function _n(s){let t=Yh[s];if(t)return t;const e=new Int32Array(s);for(let r=0;r<s;r++)e[r]=r;return t=Yh[s]=new _t({uTextures:{value:e,type:"i32",size:s}},{isStatic:!0}),t}class Xh extends Ft{constructor(t){const e=ki({name:"batch",bits:[un,gn(t),Ri]}),r=Ui({name:"batch",bits:[dn,pn(t),Mi]});super({glProgram:e,gpuProgram:r,resources:{batchSamplers:_n(t)}}),this.maxTextures=t}}let Ii=null;const $h=class ru extends Nm{constructor(t){super(t),this.geometry=new Xm,this.name=ru.extension.name,this.vertexSize=6,Ii??(Ii=new Xh(t.maxTextures)),this.shader=Ii}packAttributes(t,e,r,n,o){const l=o<<16|t.roundPixels&65535,h=t.transform,u=h.a,f=h.b,m=h.c,g=h.d,y=h.tx,x=h.ty,{positions:a,uvs:c}=t,d=t.color,p=t.attributeOffset,_=p+t.attributeSize;for(let b=p;b<_;b++){const v=b*2,w=a[v],S=a[v+1];e[n++]=u*w+m*S+y,e[n++]=g*S+f*w+x,e[n++]=c[v],e[n++]=c[v+1],r[n++]=d,r[n++]=l}}packQuadAttributes(t,e,r,n,o){const l=t.texture,h=t.transform,u=h.a,f=h.b,m=h.c,g=h.d,y=h.tx,x=h.ty,a=t.bounds,c=a.maxX,d=a.minX,p=a.maxY,_=a.minY,b=l.uvs,v=t.color,w=o<<16|t.roundPixels&65535;e[n+0]=u*d+m*_+y,e[n+1]=g*_+f*d+x,e[n+2]=b.x0,e[n+3]=b.y0,r[n+4]=v,r[n+5]=w,e[n+6]=u*c+m*_+y,e[n+7]=g*_+f*c+x,e[n+8]=b.x1,e[n+9]=b.y1,r[n+10]=v,r[n+11]=w,e[n+12]=u*c+m*p+y,e[n+13]=g*p+f*c+x,e[n+14]=b.x2,e[n+15]=b.y2,r[n+16]=v,r[n+17]=w,e[n+18]=u*d+m*p+y,e[n+19]=g*p+f*d+x,e[n+20]=b.x3,e[n+21]=b.y3,r[n+22]=v,r[n+23]=w}_updateMaxTextures(t){this.shader.maxTextures!==t&&(Ii=new Xh(t),this.shader=Ii)}destroy(){this.shader=null,super.destroy()}};$h.extension={type:[C.Batcher],name:"default"};let yn=$h;function cg(s,t,e,r,n,o,l,h=null){let u=0;e*=t,n*=o;const f=h.a,m=h.b,g=h.c,y=h.d,x=h.tx,a=h.ty;for(;u<l;){const c=s[e],d=s[e+1];r[n]=f*c+g*d+x,r[n+1]=m*c+y*d+a,n+=o,e+=t,u++}}function dg(s,t,e,r){let n=0;for(t*=e;n<r;)s[t]=0,s[t+1]=0,t+=e,n++}function Kh(s,t,e,r,n){const o=t.a,l=t.b,h=t.c,u=t.d,f=t.tx,m=t.ty;e||(e=0),r||(r=2),n||(n=s.length/r-e);let g=e*r;for(let y=0;y<n;y++){const x=s[g],a=s[g+1];s[g]=o*x+h*a+f,s[g+1]=l*x+u*a+m,g+=r}}const ug=new M;class xn{constructor(){this.packAsQuad=!1,this.batcherName="default",this.topology="triangle-list",this.applyTransform=!0,this.roundPixels=0,this._batcher=null,this._batch=null}get uvs(){return this.geometryData.uvs}get positions(){return this.geometryData.vertices}get indices(){return this.geometryData.indices}get blendMode(){return this.renderable&&this.applyTransform?this.renderable.groupBlendMode:"normal"}get color(){const t=this.baseColor,e=t>>16|t&65280|(t&255)<<16,r=this.renderable;return r?ba(e,r.groupColor)+(this.alpha*r.groupAlpha*255<<24):e+(this.alpha*255<<24)}get transform(){return this.renderable?.groupTransform||ug}copyTo(t){t.indexOffset=this.indexOffset,t.indexSize=this.indexSize,t.attributeOffset=this.attributeOffset,t.attributeSize=this.attributeSize,t.baseColor=this.baseColor,t.alpha=this.alpha,t.texture=this.texture,t.geometryData=this.geometryData,t.topology=this.topology}reset(){this.applyTransform=!0,this.renderable=null,this.topology="triangle-list"}destroy(){this.renderable=null,this.texture=null,this.geometryData=null,this._batcher=null,this._batch=null}}const Fi={extension:{type:C.ShapeBuilder,name:"circle"},build(s,t){let e,r,n,o,l,h;if(s.type==="circle"){const v=s;if(l=h=v.radius,l<=0)return!1;e=v.x,r=v.y,n=o=0}else if(s.type==="ellipse"){const v=s;if(l=v.halfWidth,h=v.halfHeight,l<=0||h<=0)return!1;e=v.x,r=v.y,n=o=0}else{const v=s,w=v.width/2,S=v.height/2;e=v.x+w,r=v.y+S,l=h=Math.max(0,Math.min(v.radius,Math.min(w,S))),n=w-l,o=S-h}if(n<0||o<0)return!1;const u=Math.ceil(2.3*Math.sqrt(l+h)),f=u*8+(n?4:0)+(o?4:0);if(f===0)return!1;if(u===0)return t[0]=t[6]=e+n,t[1]=t[3]=r+o,t[2]=t[4]=e-n,t[5]=t[7]=r-o,!0;let m=0,g=u*4+(n?2:0)+2,y=g,x=f,a=n+l,c=o,d=e+a,p=e-a,_=r+c;if(t[m++]=d,t[m++]=_,t[--g]=_,t[--g]=p,o){const v=r-c;t[y++]=p,t[y++]=v,t[--x]=v,t[--x]=d}for(let v=1;v<u;v++){const w=Math.PI/2*(v/u),S=n+Math.cos(w)*l,T=o+Math.sin(w)*h,E=e+S,P=e-S,B=r+T,A=r-T;t[m++]=E,t[m++]=B,t[--g]=B,t[--g]=P,t[y++]=P,t[y++]=A,t[--x]=A,t[--x]=E}a=n,c=o+h,d=e+a,p=e-a,_=r+c;const b=r-c;return t[m++]=d,t[m++]=_,t[--x]=b,t[--x]=d,n&&(t[m++]=p,t[m++]=_,t[--x]=b,t[--x]=p),!0},triangulate(s,t,e,r,n,o){if(s.length===0)return;let l=0,h=0;for(let m=0;m<s.length;m+=2)l+=s[m],h+=s[m+1];l/=s.length/2,h/=s.length/2;let u=r;t[u*e]=l,t[u*e+1]=h;const f=u++;for(let m=0;m<s.length;m+=2)t[u*e]=s[m],t[u*e+1]=s[m+1],m>0&&(n[o++]=u,n[o++]=f,n[o++]=u-1),u++;n[o++]=f+1,n[o++]=f,n[o++]=u-1}},fg={...Fi,extension:{...Fi.extension,name:"ellipse"}},pg={...Fi,extension:{...Fi.extension,name:"roundedRectangle"}},jh=1e-4,qh=1e-4;function mg(s){const t=s.length;if(t<6)return 1;let e=0;for(let r=0,n=s[t-2],o=s[t-1];r<t;r+=2){const l=s[r],h=s[r+1];e+=(l-n)*(h+o),n=l,o=h}return e<0?-1:1}function Zh(s,t,e,r,n,o,l,h){const u=s-e*n,f=t-r*n,m=s+e*o,g=t+r*o;let y,x;l?(y=r,x=-e):(y=-r,x=e);const a=u+y,c=f+x,d=m+y,p=g+x;return h.push(a,c),h.push(d,p),2}function Ee(s,t,e,r,n,o,l,h){const u=e-s,f=r-t;let m=Math.atan2(u,f),g=Math.atan2(n-s,o-t);h&&m<g?m+=Math.PI*2:!h&&m>g&&(g+=Math.PI*2);let y=m;const x=g-m,a=Math.abs(x),c=Math.sqrt(u*u+f*f),d=(15*a*Math.sqrt(c)/Math.PI>>0)+1,p=x/d;if(y+=p,h){l.push(s,t),l.push(e,r);for(let _=1,b=y;_<d;_++,b+=p)l.push(s,t),l.push(s+Math.sin(b)*c,t+Math.cos(b)*c);l.push(s,t),l.push(n,o)}else{l.push(e,r),l.push(s,t);for(let _=1,b=y;_<d;_++,b+=p)l.push(s+Math.sin(b)*c,t+Math.cos(b)*c),l.push(s,t);l.push(n,o),l.push(s,t)}return d*2}function gg(s,t,e,r,n,o){const l=jh;if(s.length===0)return;const h=t;let u=h.alignment;if(t.alignment!==.5){let V=mg(s);u=(u-.5)*V+.5}const f=new q(s[0],s[1]),m=new q(s[s.length-2],s[s.length-1]),g=r,y=Math.abs(f.x-m.x)<l&&Math.abs(f.y-m.y)<l;if(g){s=s.slice(),y&&(s.pop(),s.pop(),m.set(s[s.length-2],s[s.length-1]));const V=(f.x+m.x)*.5,Gt=(m.y+f.y)*.5;s.unshift(V,Gt),s.push(V,Gt)}const x=n,a=s.length/2;let c=s.length;const d=x.length/2,p=h.width/2,_=p*p,b=h.miterLimit*h.miterLimit;let v=s[0],w=s[1],S=s[2],T=s[3],E=0,P=0,B=-(w-T),A=v-S,O=0,L=0,j=Math.sqrt(B*B+A*A);B/=j,A/=j,B*=p,A*=p;const Ot=u,U=(1-Ot)*2,R=Ot*2;g||(h.cap==="round"?c+=Ee(v-B*(U-R)*.5,w-A*(U-R)*.5,v-B*U,w-A*U,v+B*R,w+A*R,x,!0)+2:h.cap==="square"&&(c+=Zh(v,w,B,A,U,R,!0,x))),x.push(v-B*U,w-A*U),x.push(v+B*R,w+A*R);for(let V=1;V<a-1;++V){v=s[(V-1)*2],w=s[(V-1)*2+1],S=s[V*2],T=s[V*2+1],E=s[(V+1)*2],P=s[(V+1)*2+1],B=-(w-T),A=v-S,j=Math.sqrt(B*B+A*A),B/=j,A/=j,B*=p,A*=p,O=-(T-P),L=S-E,j=Math.sqrt(O*O+L*L),O/=j,L/=j,O*=p,L*=p;const Gt=S-v,Tt=w-T,$t=S-E,N=P-T,Wd=Gt*$t+Tt*N,$r=Tt*$t-N*Gt,Ki=$r<0;if(Math.abs($r)<.001*Math.abs(Wd)){x.push(S-B*U,T-A*U),x.push(S+B*R,T+A*R),Wd>=0&&(h.join==="round"?c+=Ee(S,T,S-B*U,T-A*U,S-O*U,T-L*U,x,!1)+4:c+=2,x.push(S-O*R,T-L*R),x.push(S+O*U,T+L*U));continue}const Vd=(-B+v)*(-A+T)-(-B+S)*(-A+w),Yd=(-O+E)*(-L+T)-(-O+S)*(-L+P),Kr=(Gt*Yd-$t*Vd)/$r,jr=(N*Vd-Tt*Yd)/$r,_o=(Kr-S)*(Kr-S)+(jr-T)*(jr-T),ke=S+(Kr-S)*U,Me=T+(jr-T)*U,Re=S-(Kr-S)*R,Ie=T-(jr-T)*R,Dv=Math.min(Gt*Gt+Tt*Tt,$t*$t+N*N),Xd=Ki?U:R,Ov=Dv+Xd*Xd*_;_o<=Ov?h.join==="bevel"||_o/_>b?(Ki?(x.push(ke,Me),x.push(S+B*R,T+A*R),x.push(ke,Me),x.push(S+O*R,T+L*R)):(x.push(S-B*U,T-A*U),x.push(Re,Ie),x.push(S-O*U,T-L*U),x.push(Re,Ie)),c+=2):h.join==="round"?Ki?(x.push(ke,Me),x.push(S+B*R,T+A*R),c+=Ee(S,T,S+B*R,T+A*R,S+O*R,T+L*R,x,!0)+4,x.push(ke,Me),x.push(S+O*R,T+L*R)):(x.push(S-B*U,T-A*U),x.push(Re,Ie),c+=Ee(S,T,S-B*U,T-A*U,S-O*U,T-L*U,x,!1)+4,x.push(S-O*U,T-L*U),x.push(Re,Ie)):(x.push(ke,Me),x.push(Re,Ie)):(x.push(S-B*U,T-A*U),x.push(S+B*R,T+A*R),h.join==="round"?Ki?c+=Ee(S,T,S+B*R,T+A*R,S+O*R,T+L*R,x,!0)+2:c+=Ee(S,T,S-B*U,T-A*U,S-O*U,T-L*U,x,!1)+2:h.join==="miter"&&_o/_<=b&&(Ki?(x.push(Re,Ie),x.push(Re,Ie)):(x.push(ke,Me),x.push(ke,Me)),c+=2),x.push(S-O*U,T-L*U),x.push(S+O*R,T+L*R),c+=2)}v=s[(a-2)*2],w=s[(a-2)*2+1],S=s[(a-1)*2],T=s[(a-1)*2+1],B=-(w-T),A=v-S,j=Math.sqrt(B*B+A*A),B/=j,A/=j,B*=p,A*=p,x.push(S-B*U,T-A*U),x.push(S+B*R,T+A*R),g||(h.cap==="round"?c+=Ee(S-B*(U-R)*.5,T-A*(U-R)*.5,S-B*U,T-A*U,S+B*R,T+A*R,x,!1)+2:h.cap==="square"&&(c+=Zh(S,T,B,A,U,R,!1,x)));const St=qh*qh;for(let V=d;V<c+d-2;++V)v=x[V*2],w=x[V*2+1],S=x[(V+1)*2],T=x[(V+1)*2+1],E=x[(V+2)*2],P=x[(V+2)*2+1],!(Math.abs(v*(T-P)+S*(P-w)+E*(w-T))<St)&&o.push(V,V+1,V+2)}function _g(s,t,e,r){const n=jh;if(s.length===0)return;const o=s[0],l=s[1],h=s[s.length-2],u=s[s.length-1],f=t||Math.abs(o-h)<n&&Math.abs(l-u)<n,m=e,g=s.length/2,y=m.length/2;for(let x=0;x<g;x++)m.push(s[x*2]),m.push(s[x*2+1]);for(let x=0;x<g-1;x++)r.push(y+x,y+x+1);f&&r.push(y+g-1,y)}function Qh(s,t,e,r,n,o,l){const h=xm(s,t,2);if(!h)return;for(let f=0;f<h.length;f+=3)o[l++]=h[f]+n,o[l++]=h[f+1]+n,o[l++]=h[f+2]+n;let u=n*r;for(let f=0;f<s.length;f+=2)e[u]=s[f],e[u+1]=s[f+1],u+=r}const yg=[],xg={extension:{type:C.ShapeBuilder,name:"polygon"},build(s,t){for(let e=0;e<s.points.length;e++)t[e]=s.points[e];return!0},triangulate(s,t,e,r,n,o){Qh(s,yg,t,e,r,n,o)}},bg={extension:{type:C.ShapeBuilder,name:"rectangle"},build(s,t){const e=s,r=e.x,n=e.y,o=e.width,l=e.height;return o>0&&l>0?(t[0]=r,t[1]=n,t[2]=r+o,t[3]=n,t[4]=r+o,t[5]=n+l,t[6]=r,t[7]=n+l,!0):!1},triangulate(s,t,e,r,n,o){let l=0;r*=e,t[r+l]=s[0],t[r+l+1]=s[1],l+=e,t[r+l]=s[2],t[r+l+1]=s[3],l+=e,t[r+l]=s[6],t[r+l+1]=s[7],l+=e,t[r+l]=s[4],t[r+l+1]=s[5],l+=e;const h=r/e;n[o++]=h,n[o++]=h+1,n[o++]=h+2,n[o++]=h+1,n[o++]=h+3,n[o++]=h+2}},vg={extension:{type:C.ShapeBuilder,name:"triangle"},build(s,t){return t[0]=s.x,t[1]=s.y,t[2]=s.x2,t[3]=s.y2,t[4]=s.x3,t[5]=s.y3,!0},triangulate(s,t,e,r,n,o){let l=0;r*=e,t[r+l]=s[0],t[r+l+1]=s[1],l+=e,t[r+l]=s[2],t[r+l+1]=s[3],l+=e,t[r+l]=s[4],t[r+l+1]=s[5];const h=r/e;n[o++]=h,n[o++]=h+1,n[o++]=h+2}},wg=new M,Sg=new G;function Tg(s,t,e,r){const n=t.matrix?s.copyFrom(t.matrix).invert():s.identity();if(t.textureSpace==="local"){const l=e.getBounds(Sg);t.width&&l.pad(t.width);const{x:h,y:u}=l,f=1/l.width,m=1/l.height,g=-h*f,y=-u*m,x=n.a,a=n.b,c=n.c,d=n.d;n.a*=f,n.b*=f,n.c*=m,n.d*=m,n.tx=g*x+y*c+n.tx,n.ty=g*a+y*d+n.ty}else n.translate(t.texture.frame.x,t.texture.frame.y),n.scale(1/t.texture.source.width,1/t.texture.source.height);const o=t.texture.source.style;return!(t.fill instanceof Vt)&&o.addressMode==="clamp-to-edge"&&(o.addressMode="repeat",o.update()),r&&n.append(wg.copyFrom(r).invert()),n}const Rr={};D.handleByMap(C.ShapeBuilder,Rr),D.add(bg,xg,vg,Fi,fg,pg);const Cg=new G,Eg=new M;function Ag(s,t){const{geometryData:e,batches:r}=t;r.length=0,e.indices.length=0,e.vertices.length=0,e.uvs.length=0;for(let n=0;n<s.instructions.length;n++){const o=s.instructions[n];if(o.action==="texture")Pg(o.data,r,e);else if(o.action==="fill"||o.action==="stroke"){const l=o.action==="stroke",h=o.data.path.shapePath,u=o.data.style,f=o.data.hole;l&&f&&Jh(f.shapePath,u,!0,r,e),f&&(h.shapePrimitives[h.shapePrimitives.length-1].holes=f.shapePath.shapePrimitives),Jh(h,u,l,r,e)}}}function Pg(s,t,e){const r=[],n=Rr.rectangle,o=Cg;o.x=s.dx,o.y=s.dy,o.width=s.dw,o.height=s.dh;const l=s.transform;if(!n.build(o,r))return;const{vertices:h,uvs:u,indices:f}=e,m=f.length,g=h.length/2;l&&Kh(r,l),n.triangulate(r,h,2,g,f,m);const y=s.image,x=y.uvs;u.push(x.x0,x.y0,x.x1,x.y1,x.x3,x.y3,x.x2,x.y2);const a=at.get(xn);a.indexOffset=m,a.indexSize=f.length-m,a.attributeOffset=g,a.attributeSize=h.length/2-g,a.baseColor=s.style,a.alpha=s.alpha,a.texture=y,a.geometryData=e,t.push(a)}function Jh(s,t,e,r,n){const{vertices:o,uvs:l,indices:h}=n;s.shapePrimitives.forEach(({shape:u,transform:f,holes:m})=>{const g=[],y=Rr[u.type];if(!y.build(u,g))return;const x=h.length,a=o.length/2;let c="triangle-list";if(f&&Kh(g,f),e){const b=u.closePath??!0,v=t;v.pixelLine?(_g(g,b,o,h),c="line-list"):gg(g,v,!1,b,o,h)}else if(m){const b=[],v=g.slice();Bg(m).forEach(S=>{b.push(v.length/2),v.push(...S)}),Qh(v,b,o,2,a,h,x)}else y.triangulate(g,o,2,a,h,x);const d=l.length/2,p=t.texture;if(p!==k.WHITE){const b=Tg(Eg,t,u,f);cg(o,2,a,l,d,2,o.length/2-a,b)}else dg(l,d,2,o.length/2-a);const _=at.get(xn);_.indexOffset=x,_.indexSize=h.length-x,_.attributeOffset=a,_.attributeSize=o.length/2-a,_.baseColor=t.color,_.alpha=t.alpha,_.texture=p,_.geometryData=n,_.topology=c,r.push(_)})}function Bg(s){const t=[];for(let e=0;e<s.length;e++){const r=s[e].shape,n=[];Rr[r.type].build(r,n)&&t.push(n)}return t}class Ug{constructor(){this.batches=[],this.geometryData={vertices:[],uvs:[],indices:[]}}}class kg{constructor(){this.instructions=new Ta}init(t){const e=t.maxTextures;this.batcher?this.batcher._updateMaxTextures(e):this.batcher=new yn({maxTextures:e}),this.instructions.reset()}get geometry(){return z(Nf,"GraphicsContextRenderData#geometry is deprecated, please use batcher.geometry instead."),this.batcher.geometry}destroy(){this.batcher.destroy(),this.instructions.destroy(),this.batcher=null,this.instructions=null}}const bn=class wo{constructor(t){this._gpuContextHash={},this._graphicsDataContextHash=Object.create(null),this._renderer=t,t.renderableGC.addManagedHash(this,"_gpuContextHash"),t.renderableGC.addManagedHash(this,"_graphicsDataContextHash")}init(t){wo.defaultOptions.bezierSmoothness=t?.bezierSmoothness??wo.defaultOptions.bezierSmoothness}getContextRenderData(t){return this._graphicsDataContextHash[t.uid]||this._initContextRenderData(t)}updateGpuContext(t){let e=this._gpuContextHash[t.uid]||this._initContext(t);if(t.dirty){e?this._cleanGraphicsContextData(t):e=this._initContext(t),Ag(t,e);const r=t.batchMode;t.customShader||r==="no-batch"?e.isBatchable=!1:r==="auto"?e.isBatchable=e.geometryData.vertices.length<400:e.isBatchable=!0,t.dirty=!1}return e}getGpuContext(t){return this._gpuContextHash[t.uid]||this._initContext(t)}_initContextRenderData(t){const e=at.get(kg,{maxTextures:this._renderer.limits.maxBatchableTextures}),{batches:r,geometryData:n}=this._gpuContextHash[t.uid],o=n.vertices.length,l=n.indices.length;for(let m=0;m<r.length;m++)r[m].applyTransform=!1;const h=e.batcher;h.ensureAttributeBuffer(o),h.ensureIndexBuffer(l),h.begin();for(let m=0;m<r.length;m++){const g=r[m];h.add(g)}h.finish(e.instructions);const u=h.geometry;u.indexBuffer.setDataWithSize(h.indexBuffer,h.indexSize,!0),u.buffers[0].setDataWithSize(h.attributeBuffer.float32View,h.attributeSize,!0);const f=h.batches;for(let m=0;m<f.length;m++){const g=f[m];g.bindGroup=hn(g.textures.textures,g.textures.count,this._renderer.limits.maxBatchableTextures)}return this._graphicsDataContextHash[t.uid]=e,e}_initContext(t){const e=new Ug;return e.context=t,this._gpuContextHash[t.uid]=e,t.on("destroy",this.onGraphicsContextDestroy,this),this._gpuContextHash[t.uid]}onGraphicsContextDestroy(t){this._cleanGraphicsContextData(t),t.off("destroy",this.onGraphicsContextDestroy,this),this._gpuContextHash[t.uid]=null}_cleanGraphicsContextData(t){const e=this._gpuContextHash[t.uid];e.isBatchable||this._graphicsDataContextHash[t.uid]&&(at.return(this.getContextRenderData(t)),this._graphicsDataContextHash[t.uid]=null),e.batches&&e.batches.forEach(r=>{at.return(r)})}destroy(){for(const t in this._gpuContextHash)this._gpuContextHash[t]&&this.onGraphicsContextDestroy(this._gpuContextHash[t].context);this._gpuContextHash={},this._graphicsDataContextHash={},this._renderer=null}};bn.extension={type:[C.WebGLSystem,C.WebGPUSystem,C.CanvasSystem],name:"graphicsContext"},bn.defaultOptions={bezierSmoothness:.5};let vn=bn;const Mg=8,Ir=11920929e-14,Rg=1;function tl(s,t,e,r,n,o,l,h,u,f){const g=Math.min(.99,Math.max(0,f??vn.defaultOptions.bezierSmoothness));let y=(Rg-g)/1;return y*=y,Ig(t,e,r,n,o,l,h,u,s,y),s}function Ig(s,t,e,r,n,o,l,h,u,f){wn(s,t,e,r,n,o,l,h,u,f,0),u.push(l,h)}function wn(s,t,e,r,n,o,l,h,u,f,m){if(m>Mg)return;const g=(s+e)/2,y=(t+r)/2,x=(e+n)/2,a=(r+o)/2,c=(n+l)/2,d=(o+h)/2,p=(g+x)/2,_=(y+a)/2,b=(x+c)/2,v=(a+d)/2,w=(p+b)/2,S=(_+v)/2;if(m>0){let T=l-s,E=h-t;const P=Math.abs((e-l)*E-(r-h)*T),B=Math.abs((n-l)*E-(o-h)*T);if(P>Ir&&B>Ir){if((P+B)*(P+B)<=f*(T*T+E*E)){u.push(w,S);return}}else if(P>Ir){if(P*P<=f*(T*T+E*E)){u.push(w,S);return}}else if(B>Ir){if(B*B<=f*(T*T+E*E)){u.push(w,S);return}}else if(T=w-(s+l)/2,E=S-(t+h)/2,T*T+E*E<=f){u.push(w,S);return}}wn(s,t,g,y,p,_,w,S,u,f,m+1),wn(w,S,b,v,c,d,l,h,u,f,m+1)}const Fg=8,Dg=11920929e-14,Og=1;function Gg(s,t,e,r,n,o,l,h){const f=Math.min(.99,Math.max(0,h??vn.defaultOptions.bezierSmoothness));let m=(Og-f)/1;return m*=m,Lg(t,e,r,n,o,l,s,m),s}function Lg(s,t,e,r,n,o,l,h){Sn(l,s,t,e,r,n,o,h,0),l.push(n,o)}function Sn(s,t,e,r,n,o,l,h,u){if(u>Fg)return;const f=(t+r)/2,m=(e+n)/2,g=(r+o)/2,y=(n+l)/2,x=(f+g)/2,a=(m+y)/2;let c=o-t,d=l-e;const p=Math.abs((r-o)*d-(n-l)*c);if(p>Dg){if(p*p<=h*(c*c+d*d)){s.push(x,a);return}}else if(c=x-(t+o)/2,d=a-(e+l)/2,c*c+d*d<=h){s.push(x,a);return}Sn(s,t,e,f,m,x,a,h,u+1),Sn(s,x,a,g,y,o,l,h,u+1)}function el(s,t,e,r,n,o,l,h){let u=Math.abs(n-o);(!l&&n>o||l&&o>n)&&(u=2*Math.PI-u),h||(h=Math.max(6,Math.floor(6*Math.pow(r,1/3)*(u/Math.PI)))),h=Math.max(h,3);let f=u/h,m=n;f*=l?-1:1;for(let g=0;g<h+1;g++){const y=Math.cos(m),x=Math.sin(m),a=t+y*r,c=e+x*r;s.push(a,c),m+=f}}function zg(s,t,e,r,n,o){const l=s[s.length-2],u=s[s.length-1]-e,f=l-t,m=n-e,g=r-t,y=Math.abs(u*g-f*m);if(y<1e-8||o===0){(s[s.length-2]!==t||s[s.length-1]!==e)&&s.push(t,e);return}const x=u*u+f*f,a=m*m+g*g,c=u*m+f*g,d=o*Math.sqrt(x)/y,p=o*Math.sqrt(a)/y,_=d*c/x,b=p*c/a,v=d*g+p*f,w=d*m+p*u,S=f*(p+_),T=u*(p+_),E=g*(d+b),P=m*(d+b),B=Math.atan2(T-w,S-v),A=Math.atan2(P-w,E-v);el(s,v+t,w+e,o,B,A,f*m>g*u)}const Di=Math.PI*2,Tn={centerX:0,centerY:0,ang1:0,ang2:0},Cn=({x:s,y:t},e,r,n,o,l,h,u)=>{s*=e,t*=r;const f=n*s-o*t,m=o*s+n*t;return u.x=f+l,u.y=m+h,u};function Ng(s,t){const e=t===-1.5707963267948966?-.551915024494:1.3333333333333333*Math.tan(t/4),r=t===1.5707963267948966?.551915024494:e,n=Math.cos(s),o=Math.sin(s),l=Math.cos(s+t),h=Math.sin(s+t);return[{x:n-o*r,y:o+n*r},{x:l+h*r,y:h-l*r},{x:l,y:h}]}const il=(s,t,e,r)=>{const n=s*r-t*e<0?-1:1;let o=s*e+t*r;return o>1&&(o=1),o<-1&&(o=-1),n*Math.acos(o)},Hg=(s,t,e,r,n,o,l,h,u,f,m,g,y)=>{const x=Math.pow(n,2),a=Math.pow(o,2),c=Math.pow(m,2),d=Math.pow(g,2);let p=x*a-x*d-a*c;p<0&&(p=0),p/=x*d+a*c,p=Math.sqrt(p)*(l===h?-1:1);const _=p*n/o*g,b=p*-o/n*m,v=f*_-u*b+(s+e)/2,w=u*_+f*b+(t+r)/2,S=(m-_)/n,T=(g-b)/o,E=(-m-_)/n,P=(-g-b)/o,B=il(1,0,S,T);let A=il(S,T,E,P);h===0&&A>0&&(A-=Di),h===1&&A<0&&(A+=Di),y.centerX=v,y.centerY=w,y.ang1=B,y.ang2=A};function Wg(s,t,e,r,n,o,l,h=0,u=0,f=0){if(o===0||l===0)return;const m=Math.sin(h*Di/360),g=Math.cos(h*Di/360),y=g*(t-r)/2+m*(e-n)/2,x=-m*(t-r)/2+g*(e-n)/2;if(y===0&&x===0)return;o=Math.abs(o),l=Math.abs(l);const a=Math.pow(y,2)/Math.pow(o,2)+Math.pow(x,2)/Math.pow(l,2);a>1&&(o*=Math.sqrt(a),l*=Math.sqrt(a)),Hg(t,e,r,n,o,l,u,f,m,g,y,x,Tn);let{ang1:c,ang2:d}=Tn;const{centerX:p,centerY:_}=Tn;let b=Math.abs(d)/(Di/4);Math.abs(1-b)<1e-7&&(b=1);const v=Math.max(Math.ceil(b),1);d/=v;let w=s[s.length-2],S=s[s.length-1];const T={x:0,y:0};for(let E=0;E<v;E++){const P=Ng(c,d),{x:B,y:A}=Cn(P[0],o,l,g,m,p,_,T),{x:O,y:L}=Cn(P[1],o,l,g,m,p,_,T),{x:j,y:Ot}=Cn(P[2],o,l,g,m,p,_,T);tl(s,w,S,B,A,O,L,j,Ot),w=j,S=Ot,c+=d}}function Vg(s,t,e){const r=(l,h)=>{const u=h.x-l.x,f=h.y-l.y,m=Math.sqrt(u*u+f*f),g=u/m,y=f/m;return{len:m,nx:g,ny:y}},n=(l,h)=>{l===0?s.moveTo(h.x,h.y):s.lineTo(h.x,h.y)};let o=t[t.length-1];for(let l=0;l<t.length;l++){const h=t[l%t.length],u=h.radius??e;if(u<=0){n(l,h),o=h;continue}const f=t[(l+1)%t.length],m=r(h,o),g=r(h,f);if(m.len<1e-4||g.len<1e-4){n(l,h),o=h;continue}let y=Math.asin(m.nx*g.ny-m.ny*g.nx),x=1,a=!1;m.nx*g.nx-m.ny*-g.ny<0?y<0?y=Math.PI+y:(y=Math.PI-y,x=-1,a=!0):y>0&&(x=-1,a=!0);const c=y/2;let d,p=Math.abs(Math.cos(c)*u/Math.sin(c));p>Math.min(m.len/2,g.len/2)?(p=Math.min(m.len/2,g.len/2),d=Math.abs(p*Math.sin(c)/Math.cos(c))):d=u;const _=h.x+g.nx*p+-g.ny*d*x,b=h.y+g.ny*p+g.nx*d*x,v=Math.atan2(m.ny,m.nx)+Math.PI/2*x,w=Math.atan2(g.ny,g.nx)-Math.PI/2*x;l===0&&s.moveTo(_+Math.cos(v)*d,b+Math.sin(v)*d),s.arc(_,b,d,v,w,a),o=h}}function Yg(s,t,e,r){const n=(h,u)=>Math.sqrt((h.x-u.x)**2+(h.y-u.y)**2),o=(h,u,f)=>({x:h.x+(u.x-h.x)*f,y:h.y+(u.y-h.y)*f}),l=t.length;for(let h=0;h<l;h++){const u=t[(h+1)%l],f=u.radius??e;if(f<=0){h===0?s.moveTo(u.x,u.y):s.lineTo(u.x,u.y);continue}const m=t[h],g=t[(h+2)%l],y=n(m,u);let x;if(y<1e-4)x=u;else{const d=Math.min(y/2,f);x=o(u,m,d/y)}const a=n(g,u);let c;if(a<1e-4)c=u;else{const d=Math.min(a/2,f);c=o(u,g,d/a)}h===0?s.moveTo(x.x,x.y):s.lineTo(x.x,x.y),s.quadraticCurveTo(u.x,u.y,c.x,c.y,r)}}const Xg=new G;class $g{constructor(t){this.shapePrimitives=[],this._currentPoly=null,this._bounds=new ut,this._graphicsPath2D=t,this.signed=t.checkForHoles}moveTo(t,e){return this.startPoly(t,e),this}lineTo(t,e){this._ensurePoly();const r=this._currentPoly.points,n=r[r.length-2],o=r[r.length-1];return(n!==t||o!==e)&&r.push(t,e),this}arc(t,e,r,n,o,l){this._ensurePoly(!1);const h=this._currentPoly.points;return el(h,t,e,r,n,o,l),this}arcTo(t,e,r,n,o){this._ensurePoly();const l=this._currentPoly.points;return zg(l,t,e,r,n,o),this}arcToSvg(t,e,r,n,o,l,h){const u=this._currentPoly.points;return Wg(u,this._currentPoly.lastX,this._currentPoly.lastY,l,h,t,e,r,n,o),this}bezierCurveTo(t,e,r,n,o,l,h){this._ensurePoly();const u=this._currentPoly;return tl(this._currentPoly.points,u.lastX,u.lastY,t,e,r,n,o,l,h),this}quadraticCurveTo(t,e,r,n,o){this._ensurePoly();const l=this._currentPoly;return Gg(this._currentPoly.points,l.lastX,l.lastY,t,e,r,n,o),this}closePath(){return this.endPoly(!0),this}addPath(t,e){this.endPoly(),e&&!e.isIdentity()&&(t=t.clone(!0),t.transform(e));const r=this.shapePrimitives,n=r.length;for(let o=0;o<t.instructions.length;o++){const l=t.instructions[o];this[l.action](...l.data)}if(t.checkForHoles&&r.length-n>1){let o=null;for(let l=n;l<r.length;l++){const h=r[l];if(h.shape.type==="polygon"){const u=h.shape,f=o?.shape;f&&f.containsPolygon(u)?(o.holes||(o.holes=[]),o.holes.push(h),r.copyWithin(l,l+1),r.length--,l--):o=h}}}return this}finish(t=!1){this.endPoly(t)}rect(t,e,r,n,o){return this.drawShape(new G(t,e,r,n),o),this}circle(t,e,r,n){return this.drawShape(new Ur(t,e,r),n),this}poly(t,e,r){const n=new Ci(t);return n.closePath=e,this.drawShape(n,r),this}regularPoly(t,e,r,n,o=0,l){n=Math.max(n|0,3);const h=-1*Math.PI/2+o,u=Math.PI*2/n,f=[];for(let m=0;m<n;m++){const g=h-m*u;f.push(t+r*Math.cos(g),e+r*Math.sin(g))}return this.poly(f,!0,l),this}roundPoly(t,e,r,n,o,l=0,h){if(n=Math.max(n|0,3),o<=0)return this.regularPoly(t,e,r,n,l);const u=r*Math.sin(Math.PI/n)-.001;o=Math.min(o,u);const f=-1*Math.PI/2+l,m=Math.PI*2/n,g=(n-2)*Math.PI/n/2;for(let y=0;y<n;y++){const x=y*m+f,a=t+r*Math.cos(x),c=e+r*Math.sin(x),d=x+Math.PI+g,p=x-Math.PI-g,_=a+o*Math.cos(d),b=c+o*Math.sin(d),v=a+o*Math.cos(p),w=c+o*Math.sin(p);y===0?this.moveTo(_,b):this.lineTo(_,b),this.quadraticCurveTo(a,c,v,w,h)}return this.closePath()}roundShape(t,e,r=!1,n){return t.length<3?this:(r?Yg(this,t,e,n):Vg(this,t,e),this.closePath())}filletRect(t,e,r,n,o){if(o===0)return this.rect(t,e,r,n);const l=Math.min(r,n)/2,h=Math.min(l,Math.max(-l,o)),u=t+r,f=e+n,m=h<0?-h:0,g=Math.abs(h);return this.moveTo(t,e+g).arcTo(t+m,e+m,t+g,e,g).lineTo(u-g,e).arcTo(u-m,e+m,u,e+g,g).lineTo(u,f-g).arcTo(u-m,f-m,t+r-g,f,g).lineTo(t+g,f).arcTo(t+m,f-m,t,f-g,g).closePath()}chamferRect(t,e,r,n,o,l){if(o<=0)return this.rect(t,e,r,n);const h=Math.min(o,Math.min(r,n)/2),u=t+r,f=e+n,m=[t+h,e,u-h,e,u,e+h,u,f-h,u-h,f,t+h,f,t,f-h,t,e+h];for(let g=m.length-1;g>=2;g-=2)m[g]===m[g-2]&&m[g-1]===m[g-3]&&m.splice(g-1,2);return this.poly(m,!0,l)}ellipse(t,e,r,n,o){return this.drawShape(new on(t,e,r,n),o),this}roundRect(t,e,r,n,o,l){return this.drawShape(new an(t,e,r,n,o),l),this}drawShape(t,e){return this.endPoly(),this.shapePrimitives.push({shape:t,transform:e}),this}startPoly(t,e){let r=this._currentPoly;return r&&this.endPoly(),r=new Ci,r.points.push(t,e),this._currentPoly=r,this}endPoly(t=!1){const e=this._currentPoly;return e&&e.points.length>2&&(e.closePath=t,this.shapePrimitives.push({shape:e})),this._currentPoly=null,this}_ensurePoly(t=!0){if(!this._currentPoly&&(this._currentPoly=new Ci,t)){const e=this.shapePrimitives[this.shapePrimitives.length-1];if(e){let r=e.shape.x,n=e.shape.y;if(e.transform&&!e.transform.isIdentity()){const o=e.transform,l=r;r=o.a*r+o.c*n+o.tx,n=o.b*l+o.d*n+o.ty}this._currentPoly.points.push(r,n)}else this._currentPoly.points.push(0,0)}}buildPath(){const t=this._graphicsPath2D;this.shapePrimitives.length=0,this._currentPoly=null;for(let e=0;e<t.instructions.length;e++){const r=t.instructions[e];this[r.action](...r.data)}this.finish()}get bounds(){const t=this._bounds;t.clear();const e=this.shapePrimitives;for(let r=0;r<e.length;r++){const n=e[r],o=n.shape.getBounds(Xg);n.transform?t.addRect(o,n.transform):t.addRect(o)}return t}}class oe{constructor(t,e=!1){this.instructions=[],this.uid=et("graphicsPath"),this._dirty=!0,this.checkForHoles=e,typeof t=="string"?Um(t,this):this.instructions=t?.slice()??[]}get shapePath(){return this._shapePath||(this._shapePath=new $g(this)),this._dirty&&(this._dirty=!1,this._shapePath.buildPath()),this._shapePath}addPath(t,e){return t=t.clone(),this.instructions.push({action:"addPath",data:[t,e]}),this._dirty=!0,this}arc(...t){return this.instructions.push({action:"arc",data:t}),this._dirty=!0,this}arcTo(...t){return this.instructions.push({action:"arcTo",data:t}),this._dirty=!0,this}arcToSvg(...t){return this.instructions.push({action:"arcToSvg",data:t}),this._dirty=!0,this}bezierCurveTo(...t){return this.instructions.push({action:"bezierCurveTo",data:t}),this._dirty=!0,this}bezierCurveToShort(t,e,r,n,o){const l=this.instructions[this.instructions.length-1],h=this.getLastPoint(q.shared);let u=0,f=0;if(!l||l.action!=="bezierCurveTo")u=h.x,f=h.y;else{u=l.data[2],f=l.data[3];const m=h.x,g=h.y;u=m+(m-u),f=g+(g-f)}return this.instructions.push({action:"bezierCurveTo",data:[u,f,t,e,r,n,o]}),this._dirty=!0,this}closePath(){return this.instructions.push({action:"closePath",data:[]}),this._dirty=!0,this}ellipse(...t){return this.instructions.push({action:"ellipse",data:t}),this._dirty=!0,this}lineTo(...t){return this.instructions.push({action:"lineTo",data:t}),this._dirty=!0,this}moveTo(...t){return this.instructions.push({action:"moveTo",data:t}),this}quadraticCurveTo(...t){return this.instructions.push({action:"quadraticCurveTo",data:t}),this._dirty=!0,this}quadraticCurveToShort(t,e,r){const n=this.instructions[this.instructions.length-1],o=this.getLastPoint(q.shared);let l=0,h=0;if(!n||n.action!=="quadraticCurveTo")l=o.x,h=o.y;else{l=n.data[0],h=n.data[1];const u=o.x,f=o.y;l=u+(u-l),h=f+(f-h)}return this.instructions.push({action:"quadraticCurveTo",data:[l,h,t,e,r]}),this._dirty=!0,this}rect(t,e,r,n,o){return this.instructions.push({action:"rect",data:[t,e,r,n,o]}),this._dirty=!0,this}circle(t,e,r,n){return this.instructions.push({action:"circle",data:[t,e,r,n]}),this._dirty=!0,this}roundRect(...t){return this.instructions.push({action:"roundRect",data:t}),this._dirty=!0,this}poly(...t){return this.instructions.push({action:"poly",data:t}),this._dirty=!0,this}regularPoly(...t){return this.instructions.push({action:"regularPoly",data:t}),this._dirty=!0,this}roundPoly(...t){return this.instructions.push({action:"roundPoly",data:t}),this._dirty=!0,this}roundShape(...t){return this.instructions.push({action:"roundShape",data:t}),this._dirty=!0,this}filletRect(...t){return this.instructions.push({action:"filletRect",data:t}),this._dirty=!0,this}chamferRect(...t){return this.instructions.push({action:"chamferRect",data:t}),this._dirty=!0,this}star(t,e,r,n,o,l,h){o||(o=n/2);const u=-1*Math.PI/2+l,f=r*2,m=Math.PI*2/f,g=[];for(let y=0;y<f;y++){const x=y%2?o:n,a=y*m+u;g.push(t+x*Math.cos(a),e+x*Math.sin(a))}return this.poly(g,!0,h),this}clone(t=!1){const e=new oe;if(e.checkForHoles=this.checkForHoles,!t)e.instructions=this.instructions.slice();else for(let r=0;r<this.instructions.length;r++){const n=this.instructions[r];e.instructions.push({action:n.action,data:n.data.slice()})}return e}clear(){return this.instructions.length=0,this._dirty=!0,this}transform(t){if(t.isIdentity())return this;const e=t.a,r=t.b,n=t.c,o=t.d,l=t.tx,h=t.ty;let u=0,f=0,m=0,g=0,y=0,x=0,a=0,c=0;for(let d=0;d<this.instructions.length;d++){const p=this.instructions[d],_=p.data;switch(p.action){case"moveTo":case"lineTo":u=_[0],f=_[1],_[0]=e*u+n*f+l,_[1]=r*u+o*f+h;break;case"bezierCurveTo":m=_[0],g=_[1],y=_[2],x=_[3],u=_[4],f=_[5],_[0]=e*m+n*g+l,_[1]=r*m+o*g+h,_[2]=e*y+n*x+l,_[3]=r*y+o*x+h,_[4]=e*u+n*f+l,_[5]=r*u+o*f+h;break;case"quadraticCurveTo":m=_[0],g=_[1],u=_[2],f=_[3],_[0]=e*m+n*g+l,_[1]=r*m+o*g+h,_[2]=e*u+n*f+l,_[3]=r*u+o*f+h;break;case"arcToSvg":u=_[5],f=_[6],a=_[0],c=_[1],_[0]=e*a+n*c,_[1]=r*a+o*c,_[5]=e*u+n*f+l,_[6]=r*u+o*f+h;break;case"circle":_[4]=Oi(_[3],t);break;case"rect":_[4]=Oi(_[4],t);break;case"ellipse":_[8]=Oi(_[8],t);break;case"roundRect":_[5]=Oi(_[5],t);break;case"addPath":_[0].transform(t);break;case"poly":_[2]=Oi(_[2],t);break;default:F("unknown transform action",p.action);break}}return this._dirty=!0,this}get bounds(){return this.shapePath.bounds}getLastPoint(t){let e=this.instructions.length-1,r=this.instructions[e];if(!r)return t.x=0,t.y=0,t;for(;r.action==="closePath";){if(e--,e<0)return t.x=0,t.y=0,t;r=this.instructions[e]}switch(r.action){case"moveTo":case"lineTo":t.x=r.data[0],t.y=r.data[1];break;case"quadraticCurveTo":t.x=r.data[2],t.y=r.data[3];break;case"bezierCurveTo":t.x=r.data[4],t.y=r.data[5];break;case"arc":case"arcToSvg":t.x=r.data[5],t.y=r.data[6];break;case"addPath":r.data[0].getLastPoint(t);break}return t}}function Oi(s,t){return s?s.prepend(t):t.clone()}function nt(s,t,e){const r=s.getAttribute(t);return r?Number(r):e}function Kg(s,t){const e=s.querySelectorAll("defs");for(let r=0;r<e.length;r++){const n=e[r];for(let o=0;o<n.children.length;o++){const l=n.children[o];switch(l.nodeName.toLowerCase()){case"lineargradient":t.defs[l.id]=jg(l);break;case"radialgradient":t.defs[l.id]=qg();break}}}}function jg(s){const t=nt(s,"x1",0),e=nt(s,"y1",0),r=nt(s,"x2",1),n=nt(s,"y2",0),o=s.getAttribute("gradientUnits")||"objectBoundingBox",l=new Vt(t,e,r,n,o==="objectBoundingBox"?"local":"global");for(let h=0;h<s.children.length;h++){const u=s.children[h],f=nt(u,"offset",0),m=J.shared.setValue(u.getAttribute("stop-color")).toNumber();l.addColorStop(f,m)}return l}function qg(s){return F("[SVG Parser] Radial gradients are not yet supported"),new Vt(0,0,1,0)}function rl(s){const t=s.match(/url\s*\(\s*['"]?\s*#([^'"\s)]+)\s*['"]?\s*\)/i);return t?t[1]:""}const sl={fill:{type:"paint",default:0},"fill-opacity":{type:"number",default:1},stroke:{type:"paint",default:0},"stroke-width":{type:"number",default:1},"stroke-opacity":{type:"number",default:1},"stroke-linecap":{type:"string",default:"butt"},"stroke-linejoin":{type:"string",default:"miter"},"stroke-miterlimit":{type:"number",default:10},"stroke-dasharray":{type:"string",default:"none"},"stroke-dashoffset":{type:"number",default:0},opacity:{type:"number",default:1}};function nl(s,t){const e=s.getAttribute("style"),r={},n={},o={strokeStyle:r,fillStyle:n,useFill:!1,useStroke:!1};for(const l in sl){const h=s.getAttribute(l);h&&ol(t,o,l,h.trim())}if(e){const l=e.split(";");for(let h=0;h<l.length;h++){const u=l[h].trim(),[f,m]=u.split(":");sl[f]&&ol(t,o,f,m.trim())}}return{strokeStyle:o.useStroke?r:null,fillStyle:o.useFill?n:null,useFill:o.useFill,useStroke:o.useStroke}}function ol(s,t,e,r){switch(e){case"stroke":if(r!=="none"){if(r.startsWith("url(")){const n=rl(r);t.strokeStyle.fill=s.defs[n]}else t.strokeStyle.color=J.shared.setValue(r).toNumber();t.useStroke=!0}break;case"stroke-width":t.strokeStyle.width=Number(r);break;case"fill":if(r!=="none"){if(r.startsWith("url(")){const n=rl(r);t.fillStyle.fill=s.defs[n]}else t.fillStyle.color=J.shared.setValue(r).toNumber();t.useFill=!0}break;case"fill-opacity":t.fillStyle.alpha=Number(r);break;case"stroke-opacity":t.strokeStyle.alpha=Number(r);break;case"opacity":t.fillStyle.alpha=Number(r),t.strokeStyle.alpha=Number(r);break}}function Zg(s){if(s.length<=2)return!0;const t=s.map(h=>h.area).sort((h,u)=>u-h),[e,r]=t,n=t[t.length-1],o=e/r,l=r/n;return!(o>3&&l<2)}function Qg(s){return s.split(/(?=[Mm])/).filter(r=>r.trim().length>0)}function Jg(s){const t=s.match(/[-+]?[0-9]*\.?[0-9]+/g);if(!t||t.length<4)return 0;const e=t.map(Number),r=[],n=[];for(let m=0;m<e.length;m+=2)m+1<e.length&&(r.push(e[m]),n.push(e[m+1]));if(r.length===0||n.length===0)return 0;const o=Math.min(...r),l=Math.max(...r),h=Math.min(...n),u=Math.max(...n);return(l-o)*(u-h)}function al(s,t){const e=new oe(s,!1);for(const r of e.instructions)t.instructions.push(r)}function t_(s,t){if(typeof s=="string"){const l=document.createElement("div");l.innerHTML=s.trim(),s=l.querySelector("svg")}const e={context:t,defs:{},path:new oe};Kg(s,e);const r=s.children,{fillStyle:n,strokeStyle:o}=nl(s,e);for(let l=0;l<r.length;l++){const h=r[l];h.nodeName.toLowerCase()!=="defs"&&hl(h,e,n,o)}return t}function hl(s,t,e,r){const n=s.children,{fillStyle:o,strokeStyle:l}=nl(s,t);o&&e?e={...e,...o}:o&&(e=o),l&&r?r={...r,...l}:l&&(r=l);const h=!e&&!r;h&&(e={color:0});let u,f,m,g,y,x,a,c,d,p,_,b,v,w,S,T,E;switch(s.nodeName.toLowerCase()){case"path":{w=s.getAttribute("d");const P=s.getAttribute("fill-rule"),B=Qg(w),A=P==="evenodd",O=B.length>1;if(A&&O){const j=B.map(U=>({path:U,area:Jg(U)}));if(j.sort((U,R)=>R.area-U.area),B.length>3||!Zg(j))for(let U=0;U<j.length;U++){const R=j[U],St=U===0;t.context.beginPath();const V=new oe(void 0,!0);al(R.path,V),t.context.path(V),St?(e&&t.context.fill(e),r&&t.context.stroke(r)):t.context.cut()}else for(let U=0;U<j.length;U++){const R=j[U],St=U%2===1;t.context.beginPath();const V=new oe(void 0,!0);al(R.path,V),t.context.path(V),St?t.context.cut():(e&&t.context.fill(e),r&&t.context.stroke(r))}}else{const j=P?P==="evenodd":!0;S=new oe(w,j),t.context.path(S),e&&t.context.fill(e),r&&t.context.stroke(r)}break}case"circle":a=nt(s,"cx",0),c=nt(s,"cy",0),d=nt(s,"r",0),t.context.ellipse(a,c,d,d),e&&t.context.fill(e),r&&t.context.stroke(r);break;case"rect":u=nt(s,"x",0),f=nt(s,"y",0),T=nt(s,"width",0),E=nt(s,"height",0),p=nt(s,"rx",0),_=nt(s,"ry",0),p||_?t.context.roundRect(u,f,T,E,p||_):t.context.rect(u,f,T,E),e&&t.context.fill(e),r&&t.context.stroke(r);break;case"ellipse":a=nt(s,"cx",0),c=nt(s,"cy",0),p=nt(s,"rx",0),_=nt(s,"ry",0),t.context.beginPath(),t.context.ellipse(a,c,p,_),e&&t.context.fill(e),r&&t.context.stroke(r);break;case"line":m=nt(s,"x1",0),g=nt(s,"y1",0),y=nt(s,"x2",0),x=nt(s,"y2",0),t.context.beginPath(),t.context.moveTo(m,g),t.context.lineTo(y,x),r&&t.context.stroke(r);break;case"polygon":v=s.getAttribute("points"),b=v.match(/\d+/g).map(P=>parseInt(P,10)),t.context.poly(b,!0),e&&t.context.fill(e),r&&t.context.stroke(r);break;case"polyline":v=s.getAttribute("points"),b=v.match(/\d+/g).map(P=>parseInt(P,10)),t.context.poly(b,!1),r&&t.context.stroke(r);break;case"g":case"svg":break;default:{F(`[SVG parser] <${s.nodeName}> elements unsupported`);break}}h&&(e=null);for(let P=0;P<n.length;P++)hl(n[P],t,e,r)}function e_(s){return J.isColorLike(s)}function ll(s){return s instanceof Br}function cl(s){return s instanceof Vt}function i_(s){return s instanceof k}function r_(s,t,e){const r=J.shared.setValue(t??0);return s.color=r.toNumber(),s.alpha=r.alpha===1?e.alpha:r.alpha,s.texture=k.WHITE,{...e,...s}}function s_(s,t,e){return s.texture=t,{...e,...s}}function dl(s,t,e){return s.fill=t,s.color=16777215,s.texture=t.texture,s.matrix=t.transform,{...e,...s}}function ul(s,t,e){return t.buildGradient(),s.fill=t,s.color=16777215,s.texture=t.texture,s.matrix=t.transform,s.textureSpace=t.textureSpace,{...e,...s}}function n_(s,t){const e={...t,...s},r=J.shared.setValue(e.color);return e.alpha*=r.alpha,e.color=r.toNumber(),e}function Ae(s,t){if(s==null)return null;const e={},r=s;return e_(s)?r_(e,s,t):i_(s)?s_(e,s,t):ll(s)?dl(e,s,t):cl(s)?ul(e,s,t):r.fill&&ll(r.fill)?dl(r,r.fill,t):r.fill&&cl(r.fill)?ul(r,r.fill,t):n_(r,t)}function Fr(s,t){const{width:e,alignment:r,miterLimit:n,cap:o,join:l,pixelLine:h,...u}=t,f=Ae(s,u);return f?{width:e,alignment:r,miterLimit:n,cap:o,join:l,pixelLine:h,...f}:null}const o_=new q,fl=new M,En=class Qt extends Ct{constructor(){super(...arguments),this.uid=et("graphicsContext"),this.dirty=!0,this.batchMode="auto",this.instructions=[],this._activePath=new oe,this._transform=new M,this._fillStyle={...Qt.defaultFillStyle},this._strokeStyle={...Qt.defaultStrokeStyle},this._stateStack=[],this._tick=0,this._bounds=new ut,this._boundsDirty=!0}clone(){const t=new Qt;return t.batchMode=this.batchMode,t.instructions=this.instructions.slice(),t._activePath=this._activePath.clone(),t._transform=this._transform.clone(),t._fillStyle={...this._fillStyle},t._strokeStyle={...this._strokeStyle},t._stateStack=this._stateStack.slice(),t._bounds=this._bounds.clone(),t._boundsDirty=!0,t}get fillStyle(){return this._fillStyle}set fillStyle(t){this._fillStyle=Ae(t,Qt.defaultFillStyle)}get strokeStyle(){return this._strokeStyle}set strokeStyle(t){this._strokeStyle=Fr(t,Qt.defaultStrokeStyle)}setFillStyle(t){return this._fillStyle=Ae(t,Qt.defaultFillStyle),this}setStrokeStyle(t){return this._strokeStyle=Ae(t,Qt.defaultStrokeStyle),this}texture(t,e,r,n,o,l){return this.instructions.push({action:"texture",data:{image:t,dx:r||0,dy:n||0,dw:o||t.frame.width,dh:l||t.frame.height,transform:this._transform.clone(),alpha:this._fillStyle.alpha,style:e?J.shared.setValue(e).toNumber():16777215}}),this.onUpdate(),this}beginPath(){return this._activePath=new oe,this}fill(t,e){let r;const n=this.instructions[this.instructions.length-1];return this._tick===0&&n?.action==="stroke"?r=n.data.path:r=this._activePath.clone(),r?(t!=null&&(e!==void 0&&typeof t=="number"&&(z($,"GraphicsContext.fill(color, alpha) is deprecated, use GraphicsContext.fill({ color, alpha }) instead"),t={color:t,alpha:e}),this._fillStyle=Ae(t,Qt.defaultFillStyle)),this.instructions.push({action:"fill",data:{style:this.fillStyle,path:r}}),this.onUpdate(),this._initNextPathLocation(),this._tick=0,this):this}_initNextPathLocation(){const{x:t,y:e}=this._activePath.getLastPoint(q.shared);this._activePath.clear(),this._activePath.moveTo(t,e)}stroke(t){let e;const r=this.instructions[this.instructions.length-1];return this._tick===0&&r?.action==="fill"?e=r.data.path:e=this._activePath.clone(),e?(t!=null&&(this._strokeStyle=Fr(t,Qt.defaultStrokeStyle)),this.instructions.push({action:"stroke",data:{style:this.strokeStyle,path:e}}),this.onUpdate(),this._initNextPathLocation(),this._tick=0,this):this}cut(){for(let t=0;t<2;t++){const e=this.instructions[this.instructions.length-1-t],r=this._activePath.clone();if(e&&(e.action==="stroke"||e.action==="fill"))if(e.data.hole)e.data.hole.addPath(r);else{e.data.hole=r;break}}return this._initNextPathLocation(),this}arc(t,e,r,n,o,l){this._tick++;const h=this._transform;return this._activePath.arc(h.a*t+h.c*e+h.tx,h.b*t+h.d*e+h.ty,r,n,o,l),this}arcTo(t,e,r,n,o){this._tick++;const l=this._transform;return this._activePath.arcTo(l.a*t+l.c*e+l.tx,l.b*t+l.d*e+l.ty,l.a*r+l.c*n+l.tx,l.b*r+l.d*n+l.ty,o),this}arcToSvg(t,e,r,n,o,l,h){this._tick++;const u=this._transform;return this._activePath.arcToSvg(t,e,r,n,o,u.a*l+u.c*h+u.tx,u.b*l+u.d*h+u.ty),this}bezierCurveTo(t,e,r,n,o,l,h){this._tick++;const u=this._transform;return this._activePath.bezierCurveTo(u.a*t+u.c*e+u.tx,u.b*t+u.d*e+u.ty,u.a*r+u.c*n+u.tx,u.b*r+u.d*n+u.ty,u.a*o+u.c*l+u.tx,u.b*o+u.d*l+u.ty,h),this}closePath(){return this._tick++,this._activePath?.closePath(),this}ellipse(t,e,r,n){return this._tick++,this._activePath.ellipse(t,e,r,n,this._transform.clone()),this}circle(t,e,r){return this._tick++,this._activePath.circle(t,e,r,this._transform.clone()),this}path(t){return this._tick++,this._activePath.addPath(t,this._transform.clone()),this}lineTo(t,e){this._tick++;const r=this._transform;return this._activePath.lineTo(r.a*t+r.c*e+r.tx,r.b*t+r.d*e+r.ty),this}moveTo(t,e){this._tick++;const r=this._transform,n=this._activePath.instructions,o=r.a*t+r.c*e+r.tx,l=r.b*t+r.d*e+r.ty;return n.length===1&&n[0].action==="moveTo"?(n[0].data[0]=o,n[0].data[1]=l,this):(this._activePath.moveTo(o,l),this)}quadraticCurveTo(t,e,r,n,o){this._tick++;const l=this._transform;return this._activePath.quadraticCurveTo(l.a*t+l.c*e+l.tx,l.b*t+l.d*e+l.ty,l.a*r+l.c*n+l.tx,l.b*r+l.d*n+l.ty,o),this}rect(t,e,r,n){return this._tick++,this._activePath.rect(t,e,r,n,this._transform.clone()),this}roundRect(t,e,r,n,o){return this._tick++,this._activePath.roundRect(t,e,r,n,o,this._transform.clone()),this}poly(t,e){return this._tick++,this._activePath.poly(t,e,this._transform.clone()),this}regularPoly(t,e,r,n,o=0,l){return this._tick++,this._activePath.regularPoly(t,e,r,n,o,l),this}roundPoly(t,e,r,n,o,l){return this._tick++,this._activePath.roundPoly(t,e,r,n,o,l),this}roundShape(t,e,r,n){return this._tick++,this._activePath.roundShape(t,e,r,n),this}filletRect(t,e,r,n,o){return this._tick++,this._activePath.filletRect(t,e,r,n,o),this}chamferRect(t,e,r,n,o,l){return this._tick++,this._activePath.chamferRect(t,e,r,n,o,l),this}star(t,e,r,n,o=0,l=0){return this._tick++,this._activePath.star(t,e,r,n,o,l,this._transform.clone()),this}svg(t){return this._tick++,t_(t,this),this}restore(){const t=this._stateStack.pop();return t&&(this._transform=t.transform,this._fillStyle=t.fillStyle,this._strokeStyle=t.strokeStyle),this}save(){return this._stateStack.push({transform:this._transform.clone(),fillStyle:{...this._fillStyle},strokeStyle:{...this._strokeStyle}}),this}getTransform(){return this._transform}resetTransform(){return this._transform.identity(),this}rotate(t){return this._transform.rotate(t),this}scale(t,e=t){return this._transform.scale(t,e),this}setTransform(t,e,r,n,o,l){return t instanceof M?(this._transform.set(t.a,t.b,t.c,t.d,t.tx,t.ty),this):(this._transform.set(t,e,r,n,o,l),this)}transform(t,e,r,n,o,l){return t instanceof M?(this._transform.append(t),this):(fl.set(t,e,r,n,o,l),this._transform.append(fl),this)}translate(t,e=t){return this._transform.translate(t,e),this}clear(){return this._activePath.clear(),this.instructions.length=0,this.resetTransform(),this.onUpdate(),this}onUpdate(){this._boundsDirty=!0,!this.dirty&&(this.emit("update",this,16),this.dirty=!0)}get bounds(){if(!this._boundsDirty)return this._bounds;this._boundsDirty=!1;const t=this._bounds;t.clear();for(let e=0;e<this.instructions.length;e++){const r=this.instructions[e],n=r.action;if(n==="fill"){const o=r.data;t.addBounds(o.path.bounds)}else if(n==="texture"){const o=r.data;t.addFrame(o.dx,o.dy,o.dx+o.dw,o.dy+o.dh,o.transform)}if(n==="stroke"){const o=r.data,l=o.style.alignment,h=o.style.width*(1-l),u=o.path.bounds;t.addFrame(u.minX-h,u.minY-h,u.maxX+h,u.maxY+h)}}return t}containsPoint(t){if(!this.bounds.containsPoint(t.x,t.y))return!1;const e=this.instructions;let r=!1;for(let n=0;n<e.length;n++){const o=e[n],l=o.data,h=l.path;if(!o.action||!h)continue;const u=l.style,f=h.shapePath.shapePrimitives;for(let m=0;m<f.length;m++){const g=f[m].shape;if(!u||!g)continue;const y=f[m].transform,x=y?y.applyInverse(t,o_):t;if(o.action==="fill")r=g.contains(x.x,x.y);else{const c=u;r=g.strokeContains(x.x,x.y,c.width,c.alignment)}const a=l.hole;if(a){const c=a.shapePath?.shapePrimitives;if(c)for(let d=0;d<c.length;d++)c[d].shape.contains(x.x,x.y)&&(r=!1)}if(r)return!0}}return r}destroy(t=!1){if(this._stateStack.length=0,this._transform=null,this.emit("destroy",this),this.removeAllListeners(),typeof t=="boolean"?t:t?.texture){const r=typeof t=="boolean"?t:t?.textureSource;this._fillStyle.texture&&(this._fillStyle.fill&&"uid"in this._fillStyle.fill?this._fillStyle.fill.destroy():this._fillStyle.texture.destroy(r)),this._strokeStyle.texture&&(this._strokeStyle.fill&&"uid"in this._strokeStyle.fill?this._strokeStyle.fill.destroy():this._strokeStyle.texture.destroy(r))}this._fillStyle=null,this._strokeStyle=null,this.instructions=null,this._activePath=null,this._bounds=null,this._stateStack=null,this.customShader=null,this._transform=null}};En.defaultFillStyle={color:16777215,alpha:1,texture:k.WHITE,matrix:null,fill:null,textureSpace:"local"},En.defaultStrokeStyle={width:1,color:16777215,alpha:1,alignment:.5,miterLimit:10,cap:"butt",join:"miter",texture:k.WHITE,matrix:null,fill:null,textureSpace:"local",pixelLine:!1};let Dt=En;const An=class ri extends Ct{constructor(t={}){super(),this.uid=et("textStyle"),this._tick=0,a_(t);const e={...ri.defaultTextStyle,...t};for(const r in e){const n=r;this[n]=e[r]}this.update(),this._tick=0}get align(){return this._align}set align(t){this._align!==t&&(this._align=t,this.update())}get breakWords(){return this._breakWords}set breakWords(t){this._breakWords!==t&&(this._breakWords=t,this.update())}get dropShadow(){return this._dropShadow}set dropShadow(t){this._dropShadow!==t&&(t!==null&&typeof t=="object"?this._dropShadow=this._createProxy({...ri.defaultDropShadow,...t}):this._dropShadow=t?this._createProxy({...ri.defaultDropShadow}):null,this.update())}get fontFamily(){return this._fontFamily}set fontFamily(t){this._fontFamily!==t&&(this._fontFamily=t,this.update())}get fontSize(){return this._fontSize}set fontSize(t){this._fontSize!==t&&(typeof t=="string"?this._fontSize=parseInt(t,10):this._fontSize=t,this.update())}get fontStyle(){return this._fontStyle}set fontStyle(t){this._fontStyle!==t&&(this._fontStyle=t.toLowerCase(),this.update())}get fontVariant(){return this._fontVariant}set fontVariant(t){this._fontVariant!==t&&(this._fontVariant=t,this.update())}get fontWeight(){return this._fontWeight}set fontWeight(t){this._fontWeight!==t&&(this._fontWeight=t,this.update())}get leading(){return this._leading}set leading(t){this._leading!==t&&(this._leading=t,this.update())}get letterSpacing(){return this._letterSpacing}set letterSpacing(t){this._letterSpacing!==t&&(this._letterSpacing=t,this.update())}get lineHeight(){return this._lineHeight}set lineHeight(t){this._lineHeight!==t&&(this._lineHeight=t,this.update())}get padding(){return this._padding}set padding(t){this._padding!==t&&(this._padding=t,this.update())}get filters(){return this._filters}set filters(t){this._filters!==t&&(this._filters=Object.freeze(t),this.update())}get trim(){return this._trim}set trim(t){this._trim!==t&&(this._trim=t,this.update())}get textBaseline(){return this._textBaseline}set textBaseline(t){this._textBaseline!==t&&(this._textBaseline=t,this.update())}get whiteSpace(){return this._whiteSpace}set whiteSpace(t){this._whiteSpace!==t&&(this._whiteSpace=t,this.update())}get wordWrap(){return this._wordWrap}set wordWrap(t){this._wordWrap!==t&&(this._wordWrap=t,this.update())}get wordWrapWidth(){return this._wordWrapWidth}set wordWrapWidth(t){this._wordWrapWidth!==t&&(this._wordWrapWidth=t,this.update())}get fill(){return this._originalFill}set fill(t){t!==this._originalFill&&(this._originalFill=t,this._isFillStyle(t)&&(this._originalFill=this._createProxy({...Dt.defaultFillStyle,...t},()=>{this._fill=Ae({...this._originalFill},Dt.defaultFillStyle)})),this._fill=Ae(t===0?"black":t,Dt.defaultFillStyle),this.update())}get stroke(){return this._originalStroke}set stroke(t){t!==this._originalStroke&&(this._originalStroke=t,this._isFillStyle(t)&&(this._originalStroke=this._createProxy({...Dt.defaultStrokeStyle,...t},()=>{this._stroke=Fr({...this._originalStroke},Dt.defaultStrokeStyle)})),this._stroke=Fr(t,Dt.defaultStrokeStyle),this.update())}update(){this._tick++,this.emit("update",this)}reset(){const t=ri.defaultTextStyle;for(const e in t)this[e]=t[e]}get styleKey(){return`${this.uid}-${this._tick}`}clone(){return new ri({align:this.align,breakWords:this.breakWords,dropShadow:this._dropShadow?{...this._dropShadow}:null,fill:this._fill,fontFamily:this.fontFamily,fontSize:this.fontSize,fontStyle:this.fontStyle,fontVariant:this.fontVariant,fontWeight:this.fontWeight,leading:this.leading,letterSpacing:this.letterSpacing,lineHeight:this.lineHeight,padding:this.padding,stroke:this._stroke,textBaseline:this.textBaseline,whiteSpace:this.whiteSpace,wordWrap:this.wordWrap,wordWrapWidth:this.wordWrapWidth,filters:this._filters?[...this._filters]:void 0})}_getFinalPadding(){let t=0;if(this._filters)for(let e=0;e<this._filters.length;e++)t+=this._filters[e].padding;return Math.max(this._padding,t)}destroy(t=!1){if(this.removeAllListeners(),typeof t=="boolean"?t:t?.texture){const r=typeof t=="boolean"?t:t?.textureSource;this._fill?.texture&&this._fill.texture.destroy(r),this._originalFill?.texture&&this._originalFill.texture.destroy(r),this._stroke?.texture&&this._stroke.texture.destroy(r),this._originalStroke?.texture&&this._originalStroke.texture.destroy(r)}this._fill=null,this._stroke=null,this.dropShadow=null,this._originalStroke=null,this._originalFill=null}_createProxy(t,e){return new Proxy(t,{set:(r,n,o)=>(r[n]===o||(r[n]=o,e?.(n,o),this.update()),!0)})}_isFillStyle(t){return(t??null)!==null&&!(J.isColorLike(t)||t instanceof Vt||t instanceof Br)}};An.defaultDropShadow={alpha:1,angle:Math.PI/6,blur:0,color:"black",distance:5},An.defaultTextStyle={align:"left",breakWords:!1,dropShadow:null,fill:"black",fontFamily:"Arial",fontSize:26,fontStyle:"normal",fontVariant:"normal",fontWeight:"normal",leading:0,letterSpacing:0,lineHeight:0,padding:0,stroke:null,textBaseline:"alphabetic",trim:!1,whiteSpace:"pre",wordWrap:!1,wordWrapWidth:100};let bt=An;function a_(s){const t=s;if(typeof t.dropShadow=="boolean"&&t.dropShadow){const e=bt.defaultDropShadow;s.dropShadow={alpha:t.dropShadowAlpha??e.alpha,angle:t.dropShadowAngle??e.angle,blur:t.dropShadowBlur??e.blur,color:t.dropShadowColor??e.color,distance:t.dropShadowDistance??e.distance}}if(t.strokeThickness!==void 0){z($,"strokeThickness is now a part of stroke");const e=t.stroke;let r={};if(J.isColorLike(e))r.color=e;else if(e instanceof Vt||e instanceof Br)r.fill=e;else if(Object.hasOwnProperty.call(e,"color")||Object.hasOwnProperty.call(e,"fill"))r=e;else throw new Error("Invalid stroke value.");s.stroke={...r,width:t.strokeThickness}}if(Array.isArray(t.fillGradientStops)){if(z($,"gradient fill is now a fill pattern: `new FillGradient(...)`"),!Array.isArray(t.fill)||t.fill.length===0)throw new Error("Invalid fill value. Expected an array of colors for gradient fill.");t.fill.length!==t.fillGradientStops.length&&F("The number of fill colors must match the number of fill gradient stops.");const e=new Vt({start:{x:0,y:0},end:{x:0,y:1},textureSpace:"local"}),r=t.fillGradientStops.slice(),n=t.fill.map(o=>J.shared.setValue(o).toNumber());r.forEach((o,l)=>{e.addColorStop(o,n[l])}),s.fill={fill:e}}}class h_{constructor(t){this._canvasPool=Object.create(null),this.canvasOptions=t||{},this.enableFullScreen=!1}_createCanvasAndContext(t,e){const r=W.get().createCanvas();r.width=t,r.height=e;const n=r.getContext("2d");return{canvas:r,context:n}}getOptimalCanvasAndContext(t,e,r=1){t=Math.ceil(t*r-1e-6),e=Math.ceil(e*r-1e-6),t=ze(t),e=ze(e);const n=(t<<17)+(e<<1);this._canvasPool[n]||(this._canvasPool[n]=[]);let o=this._canvasPool[n].pop();return o||(o=this._createCanvasAndContext(t,e)),o}returnCanvasAndContext(t){const e=t.canvas,{width:r,height:n}=e,o=(r<<17)+(n<<1);t.context.resetTransform(),t.context.clearRect(0,0,r,n),this._canvasPool[o].push(t)}clear(){this._canvasPool={}}}const ae=new h_;He.register(ae);const pl=1e5;function Dr(s,t,e,r=0){if(s.texture===k.WHITE&&!s.fill)return J.shared.setValue(s.color).setAlpha(s.alpha??1).toHexa();if(s.fill){if(s.fill instanceof Br){const n=s.fill,o=t.createPattern(n.texture.source.resource,"repeat"),l=n.transform.copyTo(M.shared);return l.scale(n.texture.frame.width,n.texture.frame.height),o.setTransform(l),o}else if(s.fill instanceof Vt){const n=s.fill,o=n.type==="linear",l=n.textureSpace==="local";let h=1,u=1;l&&e&&(h=e.width+r,u=e.height+r);let f,m=!1;if(o){const{start:g,end:y}=n;f=t.createLinearGradient(g.x*h,g.y*u,y.x*h,y.y*u),m=Math.abs(y.x-g.x)<Math.abs((y.y-g.y)*.1)}else{const{center:g,innerRadius:y,outerCenter:x,outerRadius:a}=n;f=t.createRadialGradient(g.x*h,g.y*u,y*h,x.x*h,x.y*u,a*h)}if(m&&l&&e){const g=e.lineHeight/u;for(let y=0;y<e.lines.length;y++){const x=(y*e.lineHeight+r/2)/u;n.colorStops.forEach(a=>{const c=x+a.offset*g;f.addColorStop(Math.floor(c*pl)/pl,J.shared.setValue(a.color).toHex())})}}else n.colorStops.forEach(g=>{f.addColorStop(g.offset,J.shared.setValue(g.color).toHex())});return f}}else{const n=t.createPattern(s.texture.source.resource,"repeat"),o=s.matrix.copyTo(M.shared);return o.scale(s.texture.frame.width,s.texture.frame.height),n.setTransform(o),n}return F("FillStyle not recognised",s),"red"}const ml=class su extends Th{constructor(t){super(),this.resolution=1,this.pages=[],this._padding=0,this._measureCache=Object.create(null),this._currentChars=[],this._currentX=0,this._currentY=0,this._currentMaxCharHeight=0,this._currentPageIndex=-1,this._skipKerning=!1;const e={...su.defaultOptions,...t};this._textureSize=e.textureSize,this._mipmap=e.mipmap;const r=e.style.clone();e.overrideFill&&(r._fill.color=16777215,r._fill.alpha=1,r._fill.texture=k.WHITE,r._fill.fill=null),this.applyFillAsTint=e.overrideFill;const n=r.fontSize;r.fontSize=this.baseMeasurementFontSize;const o=Pr(r);e.overrideSize?r._stroke&&(r._stroke.width*=this.baseRenderedFontSize/n):r.fontSize=this.baseRenderedFontSize=n,this._style=r,this._skipKerning=e.skipKerning??!1,this.resolution=e.resolution??1,this._padding=e.padding??4,e.textureStyle&&(this._textureStyle=e.textureStyle instanceof jt?e.textureStyle:new jt(e.textureStyle)),this.fontMetrics=xt.measureFont(o),this.lineHeight=r.lineHeight||this.fontMetrics.fontSize||r.fontSize}ensureCharacters(t){const e=xt.graphemeSegmenter(t).filter(d=>!this._currentChars.includes(d)).filter((d,p,_)=>_.indexOf(d)===p);if(!e.length)return;this._currentChars=[...this._currentChars,...e];let r;this._currentPageIndex===-1?r=this._nextPage():r=this.pages[this._currentPageIndex];let{canvas:n,context:o}=r.canvasAndContext,l=r.texture.source;const h=this._style;let u=this._currentX,f=this._currentY,m=this._currentMaxCharHeight;const g=this.baseRenderedFontSize/this.baseMeasurementFontSize,y=this._padding*g;let x=!1;const a=n.width/this.resolution,c=n.height/this.resolution;for(let d=0;d<e.length;d++){const p=e[d],_=xt.measureText(p,h,n,!1);_.lineHeight=_.height;const b=_.width*g,v=Math.ceil((h.fontStyle==="italic"?2:1)*b),w=_.height*g,S=v+y*2,T=w+y*2;if(x=!1,p!==`
|
|
318
|
+
`&&p!=="\r"&&p!==" "&&p!==" "&&(x=!0,m=Math.ceil(Math.max(T,m))),u+S>a&&(f+=m,m=T,u=0,f+m>c)){l.update();const P=this._nextPage();n=P.canvasAndContext.canvas,o=P.canvasAndContext.context,l=P.texture.source,u=0,f=0,m=0}const E=b/g-(h.dropShadow?.distance??0)-(h._stroke?.width??0);if(this.chars[p]={id:p.codePointAt(0),xOffset:-this._padding,yOffset:-this._padding,xAdvance:E,kerning:{}},x){this._drawGlyph(o,_,u+y,f+y,g,h);const P=l.width*g,B=l.height*g,A=new G(u/P*l.width,f/B*l.height,S/P*l.width,T/B*l.height);this.chars[p].texture=new k({source:l,frame:A}),u+=Math.ceil(S)}}l.update(),this._currentX=u,this._currentY=f,this._currentMaxCharHeight=m,this._skipKerning&&this._applyKerning(e,o)}get pageTextures(){return z($,"BitmapFont.pageTextures is deprecated, please use BitmapFont.pages instead."),this.pages}_applyKerning(t,e){const r=this._measureCache;for(let n=0;n<t.length;n++){const o=t[n];for(let l=0;l<this._currentChars.length;l++){const h=this._currentChars[l];let u=r[o];u||(u=r[o]=e.measureText(o).width);let f=r[h];f||(f=r[h]=e.measureText(h).width);let m=e.measureText(o+h).width,g=m-(u+f);g&&(this.chars[o].kerning[h]=g),m=e.measureText(o+h).width,g=m-(u+f),g&&(this.chars[h].kerning[o]=g)}}}_nextPage(){this._currentPageIndex++;const t=this.resolution,e=ae.getOptimalCanvasAndContext(this._textureSize,this._textureSize,t);this._setupContext(e.context,this._style,t);const r=t*(this.baseRenderedFontSize/this.baseMeasurementFontSize),n=new k({source:new Se({resource:e.canvas,resolution:r,alphaMode:"premultiply-alpha-on-upload",autoGenerateMipmaps:this._mipmap})});this._textureStyle&&(n.source.style=this._textureStyle);const o={canvasAndContext:e,texture:n};return this.pages[this._currentPageIndex]=o,o}_setupContext(t,e,r){e.fontSize=this.baseRenderedFontSize,t.scale(r,r),t.font=Pr(e),e.fontSize=this.baseMeasurementFontSize,t.textBaseline=e.textBaseline;const n=e._stroke,o=n?.width??0;if(n&&(t.lineWidth=o,t.lineJoin=n.join,t.miterLimit=n.miterLimit,t.strokeStyle=Dr(n,t)),e._fill&&(t.fillStyle=Dr(e._fill,t)),e.dropShadow){const l=e.dropShadow,h=J.shared.setValue(l.color).toArray(),u=l.blur*r,f=l.distance*r;t.shadowColor=`rgba(${h[0]*255},${h[1]*255},${h[2]*255},${l.alpha})`,t.shadowBlur=u,t.shadowOffsetX=Math.cos(l.angle)*f,t.shadowOffsetY=Math.sin(l.angle)*f}else t.shadowColor="black",t.shadowBlur=0,t.shadowOffsetX=0,t.shadowOffsetY=0}_drawGlyph(t,e,r,n,o,l){const h=e.text,u=e.fontProperties,m=(l._stroke?.width??0)*o,g=r+m/2,y=n-m/2,x=u.descent*o,a=e.lineHeight*o;let c=!1;l.stroke&&m&&(c=!0,t.strokeText(h,g,y+a-x));const{shadowBlur:d,shadowOffsetX:p,shadowOffsetY:_}=t;l._fill&&(c&&(t.shadowBlur=0,t.shadowOffsetX=0,t.shadowOffsetY=0),t.fillText(h,g,y+a-x)),c&&(t.shadowBlur=d,t.shadowOffsetX=p,t.shadowOffsetY=_)}destroy(){super.destroy();for(let t=0;t<this.pages.length;t++){const{canvasAndContext:e,texture:r}=this.pages[t];ae.returnCanvasAndContext(e),r.destroy(!0)}this.pages=null}};ml.defaultOptions={textureSize:512,style:new bt,mipmap:!0};let gl=ml;function Pn(s,t,e,r){const n={width:0,height:0,offsetY:0,scale:t.fontSize/e.baseMeasurementFontSize,lines:[{width:0,charPositions:[],spaceWidth:0,spacesIndex:[],chars:[]}]};n.offsetY=e.baseLineOffset;let o=n.lines[0],l=null,h=!0;const u={width:0,start:0,index:0,positions:[],chars:[]},f=e.baseMeasurementFontSize/t.fontSize,m=t.letterSpacing*f,g=t.wordWrapWidth*f,y=t.lineHeight?t.lineHeight*f:e.lineHeight,x=t.wordWrap&&t.breakWords,a=p=>{const _=o.width;for(let b=0;b<u.index;b++){const v=p.positions[b];o.chars.push(p.chars[b]),o.charPositions.push(v+_)}o.width+=p.width,h=!1,u.width=0,u.index=0,u.chars.length=0},c=()=>{let p=o.chars.length-1;if(r){let _=o.chars[p];for(;_===" ";)o.width-=e.chars[_].xAdvance,_=o.chars[--p]}n.width=Math.max(n.width,o.width),o={width:0,charPositions:[],chars:[],spaceWidth:0,spacesIndex:[]},h=!0,n.lines.push(o),n.height+=y},d=p=>p-m>g;for(let p=0;p<s.length+1;p++){let _;const b=p===s.length;b||(_=s[p]);const v=e.chars[_]||e.chars[" "];if(/(?:\s)/.test(_)||_==="\r"||_===`
|
|
319
|
+
`||b){if(!h&&t.wordWrap&&d(o.width+u.width)?(c(),a(u),b||o.charPositions.push(0)):(u.start=o.width,a(u),b||o.charPositions.push(0)),_==="\r"||_===`
|
|
320
|
+
`)c();else if(!b){const E=v.xAdvance+(v.kerning[l]||0)+m;o.width+=E,o.spaceWidth=E,o.spacesIndex.push(o.charPositions.length),o.chars.push(_)}}else{const T=v.kerning[l]||0,E=v.xAdvance+T+m;x&&d(o.width+u.width+E)&&(a(u),c()),u.positions[u.index++]=u.width+T,u.chars.push(_),u.width+=E}l=_}return c(),t.align==="center"?l_(n):t.align==="right"?c_(n):t.align==="justify"&&d_(n),n}function l_(s){for(let t=0;t<s.lines.length;t++){const e=s.lines[t],r=s.width/2-e.width/2;for(let n=0;n<e.charPositions.length;n++)e.charPositions[n]+=r}}function c_(s){for(let t=0;t<s.lines.length;t++){const e=s.lines[t],r=s.width-e.width;for(let n=0;n<e.charPositions.length;n++)e.charPositions[n]+=r}}function d_(s){const t=s.width;for(let e=0;e<s.lines.length;e++){const r=s.lines[e];let n=0,o=r.spacesIndex[n++],l=0;const h=r.spacesIndex.length,f=(t-r.width)/h;for(let m=0;m<r.charPositions.length;m++)m===o&&(o=r.spacesIndex[n++],l+=f),r.charPositions[m]+=l}}function u_(s){if(s==="")return[];typeof s=="string"&&(s=[s]);const t=[];for(let e=0,r=s.length;e<r;e++){const n=s[e];if(Array.isArray(n)){if(n.length!==2)throw new Error(`[BitmapFont]: Invalid character range length, expecting 2 got ${n.length}.`);if(n[0].length===0||n[1].length===0)throw new Error("[BitmapFont]: Invalid character delimiter.");const o=n[0].charCodeAt(0),l=n[1].charCodeAt(0);if(l<o)throw new Error("[BitmapFont]: Invalid character range.");for(let h=o,u=l;h<=u;h++)t.push(String.fromCharCode(h))}else t.push(...Array.from(n))}if(t.length===0)throw new Error("[BitmapFont]: Empty set when resolving characters.");return t}let Or=0;class f_{constructor(){this.ALPHA=[["a","z"],["A","Z"]," "],this.NUMERIC=[["0","9"]],this.ALPHANUMERIC=[["a","z"],["A","Z"],["0","9"]," "],this.ASCII=[[" ","~"]],this.defaultOptions={chars:this.ALPHANUMERIC,resolution:1,padding:4,skipKerning:!1,textureStyle:null},this.measureCache=Ch(1e3)}getFont(t,e){let r=`${e.fontFamily}-bitmap`,n=!0;if(e._fill.fill&&!e._stroke?(r+=e._fill.fill.styleKey,n=!1):(e._stroke||e.dropShadow)&&(r=`${e.styleKey}-bitmap`,n=!1),!Q.has(r)){const l=Object.create(e);l.lineHeight=0;const h=new gl({style:l,overrideFill:n,overrideSize:!0,...this.defaultOptions});Or++,Or>50&&F("BitmapText",`You have dynamically created ${Or} bitmap fonts, this can be inefficient. Try pre installing your font styles using \`BitmapFont.install({name:"style1", style})\``),h.once("destroy",()=>{Or--,Q.remove(r)}),Q.set(r,h)}const o=Q.get(r);return o.ensureCharacters?.(t),o}getLayout(t,e,r=!0){const n=this.getFont(t,e),o=`${t}-${e.styleKey}-${r}`;if(this.measureCache.has(o))return this.measureCache.get(o);const l=xt.graphemeSegmenter(t),h=Pn(l,e,n,r);return this.measureCache.set(o,h),h}measureText(t,e,r=!0){return this.getLayout(t,e,r)}install(...t){let e=t[0];typeof e=="string"&&(e={name:e,style:t[1],chars:t[2]?.chars,resolution:t[2]?.resolution,padding:t[2]?.padding,skipKerning:t[2]?.skipKerning},z($,"BitmapFontManager.install(name, style, options) is deprecated, use BitmapFontManager.install({name, style, ...options})"));const r=e?.name;if(!r)throw new Error("[BitmapFontManager] Property `name` is required.");e={...this.defaultOptions,...e};const n=e.style,o=n instanceof bt?n:new bt(n),l=e.dynamicFill??this._canUseTintForStyle(o),h=new gl({style:o,overrideFill:l,skipKerning:e.skipKerning,padding:e.padding,resolution:e.resolution,overrideSize:!1,textureStyle:e.textureStyle}),u=u_(e.chars);return h.ensureCharacters(u.join("")),Q.set(`${r}-bitmap`,h),h.once("destroy",()=>Q.remove(`${r}-bitmap`)),h}uninstall(t){const e=`${t}-bitmap`,r=Q.get(e);r&&r.destroy()}_canUseTintForStyle(t){return!t._stroke&&(!t.dropShadow||t.dropShadow.color===0)&&!t._fill.fill&&t._fill.color===16777215}}const Gi=new f_;class _l extends Th{constructor(t,e){super();const{textures:r,data:n}=t;Object.keys(n.pages).forEach(o=>{const l=n.pages[parseInt(o,10)],h=r[l.id];this.pages.push({texture:h})}),Object.keys(n.chars).forEach(o=>{const l=n.chars[o],{frame:h,source:u,rotate:f}=r[l.page],m=Z.transformRectCoords(l,h,f,new G),g=new k({frame:m,orig:new G(0,0,l.width,l.height),source:u,rotate:f});this.chars[o]={id:o.codePointAt(0),xOffset:l.xOffset,yOffset:l.yOffset,xAdvance:l.xAdvance,kerning:l.kerning??{},texture:g}}),this.baseRenderedFontSize=n.fontSize,this.baseMeasurementFontSize=n.fontSize,this.fontMetrics={ascent:0,descent:0,fontSize:n.fontSize},this.baseLineOffset=n.baseLineOffset,this.lineHeight=n.lineHeight,this.fontFamily=n.fontFamily,this.distanceField=n.distanceField??{type:"none",range:0},this.url=e}destroy(){super.destroy();for(let t=0;t<this.pages.length;t++){const{texture:e}=this.pages[t];e.destroy(!0)}this.pages=null}static install(t){Gi.install(t)}static uninstall(t){Gi.uninstall(t)}}const Bn={test(s){return typeof s=="string"&&s.startsWith("info face=")},parse(s){const t=s.match(/^[a-z]+\s+.+$/gm),e={info:[],common:[],page:[],char:[],chars:[],kerning:[],kernings:[],distanceField:[]};for(const g in t){const y=t[g].match(/^[a-z]+/gm)[0],x=t[g].match(/[a-zA-Z]+=([^\s"']+|"([^"]*)")/gm),a={};for(const c in x){const d=x[c].split("="),p=d[0],_=d[1].replace(/"/gm,""),b=parseFloat(_),v=isNaN(b)?_:b;a[p]=v}e[y].push(a)}const r={chars:{},pages:[],lineHeight:0,fontSize:0,fontFamily:"",distanceField:null,baseLineOffset:0},[n]=e.info,[o]=e.common,[l]=e.distanceField??[];l&&(r.distanceField={range:parseInt(l.distanceRange,10),type:l.fieldType}),r.fontSize=parseInt(n.size,10),r.fontFamily=n.face,r.lineHeight=parseInt(o.lineHeight,10);const h=e.page;for(let g=0;g<h.length;g++)r.pages.push({id:parseInt(h[g].id,10)||0,file:h[g].file});const u={};r.baseLineOffset=r.lineHeight-parseInt(o.base,10);const f=e.char;for(let g=0;g<f.length;g++){const y=f[g],x=parseInt(y.id,10);let a=y.letter??y.char??String.fromCharCode(x);a==="space"&&(a=" "),u[x]=a,r.chars[a]={id:x,page:parseInt(y.page,10)||0,x:parseInt(y.x,10),y:parseInt(y.y,10),width:parseInt(y.width,10),height:parseInt(y.height,10),xOffset:parseInt(y.xoffset,10),yOffset:parseInt(y.yoffset,10),xAdvance:parseInt(y.xadvance,10),kerning:{}}}const m=e.kerning||[];for(let g=0;g<m.length;g++){const y=parseInt(m[g].first,10),x=parseInt(m[g].second,10),a=parseInt(m[g].amount,10);r.chars[u[x]].kerning[u[y]]=a}return r}},yl={test(s){const t=s;return typeof t!="string"&&"getElementsByTagName"in t&&t.getElementsByTagName("page").length&&t.getElementsByTagName("info")[0].getAttribute("face")!==null},parse(s){const t={chars:{},pages:[],lineHeight:0,fontSize:0,fontFamily:"",distanceField:null,baseLineOffset:0},e=s.getElementsByTagName("info")[0],r=s.getElementsByTagName("common")[0],n=s.getElementsByTagName("distanceField")[0];n&&(t.distanceField={type:n.getAttribute("fieldType"),range:parseInt(n.getAttribute("distanceRange"),10)});const o=s.getElementsByTagName("page"),l=s.getElementsByTagName("char"),h=s.getElementsByTagName("kerning");t.fontSize=parseInt(e.getAttribute("size"),10),t.fontFamily=e.getAttribute("face"),t.lineHeight=parseInt(r.getAttribute("lineHeight"),10);for(let f=0;f<o.length;f++)t.pages.push({id:parseInt(o[f].getAttribute("id"),10)||0,file:o[f].getAttribute("file")});const u={};t.baseLineOffset=t.lineHeight-parseInt(r.getAttribute("base"),10);for(let f=0;f<l.length;f++){const m=l[f],g=parseInt(m.getAttribute("id"),10);let y=m.getAttribute("letter")??m.getAttribute("char")??String.fromCharCode(g);y==="space"&&(y=" "),u[g]=y,t.chars[y]={id:g,page:parseInt(m.getAttribute("page"),10)||0,x:parseInt(m.getAttribute("x"),10),y:parseInt(m.getAttribute("y"),10),width:parseInt(m.getAttribute("width"),10),height:parseInt(m.getAttribute("height"),10),xOffset:parseInt(m.getAttribute("xoffset"),10),yOffset:parseInt(m.getAttribute("yoffset"),10),xAdvance:parseInt(m.getAttribute("xadvance"),10),kerning:{}}}for(let f=0;f<h.length;f++){const m=parseInt(h[f].getAttribute("first"),10),g=parseInt(h[f].getAttribute("second"),10),y=parseInt(h[f].getAttribute("amount"),10);t.chars[u[g]].kerning[u[m]]=y}return t}},xl={test(s){return typeof s=="string"&&s.match(/<font(\s|>)/)?yl.test(W.get().parseXML(s)):!1},parse(s){return yl.parse(W.get().parseXML(s))}},p_=[".xml",".fnt"],m_={extension:{type:C.CacheParser,name:"cacheBitmapFont"},test:s=>s instanceof _l,getCacheableAssets(s,t){const e={};return s.forEach(r=>{e[r]=t,e[`${r}-bitmap`]=t}),e[`${t.fontFamily}-bitmap`]=t,e}},g_={extension:{type:C.LoadParser,priority:ue.Normal},name:"loadBitmapFont",id:"bitmap-font",test(s){return p_.includes(At.extname(s).toLowerCase())},async testParse(s){return Bn.test(s)||xl.test(s)},async parse(s,t,e){const r=Bn.test(s)?Bn.parse(s):xl.parse(s),{src:n}=t,{pages:o}=r,l=[],h=r.distanceField?{scaleMode:"linear",alphaMode:"premultiply-alpha-on-upload",autoGenerateMipmaps:!1,resolution:1}:{};for(let g=0;g<o.length;++g){const y=o[g].file;let x=At.join(At.dirname(n),y);x=Gs(x,n),l.push({src:x,data:h})}const u=await e.load(l),f=l.map(g=>u[g.src]);return new _l({data:r,textures:f},n)},async load(s,t){return await(await W.get().fetch(s)).text()},async unload(s,t,e){await Promise.all(s.pages.map(r=>e.unload(r.texture.source._sourceOrigin))),s.destroy()}};class __{constructor(t,e=!1){this._loader=t,this._assetList=[],this._isLoading=!1,this._maxConcurrent=1,this.verbose=e}add(t){t.forEach(e=>{this._assetList.push(e)}),this.verbose&&console.log("[BackgroundLoader] assets: ",this._assetList),this._isActive&&!this._isLoading&&this._next()}async _next(){if(this._assetList.length&&this._isActive){this._isLoading=!0;const t=[],e=Math.min(this._assetList.length,this._maxConcurrent);for(let r=0;r<e;r++)t.push(this._assetList.pop());await this._loader.load(t),this._isLoading=!1,this._next()}}get active(){return this._isActive}set active(t){this._isActive!==t&&(this._isActive=t,t&&!this._isLoading&&this._next())}}const y_={extension:{type:C.CacheParser,name:"cacheTextureArray"},test:s=>Array.isArray(s)&&s.every(t=>t instanceof k),getCacheableAssets:(s,t)=>{const e={};return s.forEach(r=>{t.forEach((n,o)=>{e[r+(o===0?"":o+1)]=n})}),e}};async function bl(s){if("Image"in globalThis)return new Promise(t=>{const e=new Image;e.onload=()=>{t(!0)},e.onerror=()=>{t(!1)},e.src=s});if("createImageBitmap"in globalThis&&"fetch"in globalThis){try{const t=await(await fetch(s)).blob();await createImageBitmap(t)}catch{return!1}return!0}return!1}const x_={extension:{type:C.DetectionParser,priority:1},test:async()=>bl("data:image/avif;base64,AAAAIGZ0eXBhdmlmAAAAAGF2aWZtaWYxbWlhZk1BMUIAAADybWV0YQAAAAAAAAAoaGRscgAAAAAAAAAAcGljdAAAAAAAAAAAAAAAAGxpYmF2aWYAAAAADnBpdG0AAAAAAAEAAAAeaWxvYwAAAABEAAABAAEAAAABAAABGgAAAB0AAAAoaWluZgAAAAAAAQAAABppbmZlAgAAAAABAABhdjAxQ29sb3IAAAAAamlwcnAAAABLaXBjbwAAABRpc3BlAAAAAAAAAAIAAAACAAAAEHBpeGkAAAAAAwgICAAAAAxhdjFDgQ0MAAAAABNjb2xybmNseAACAAIAAYAAAAAXaXBtYQAAAAAAAAABAAEEAQKDBAAAACVtZGF0EgAKCBgANogQEAwgMg8f8D///8WfhwB8+ErK42A="),add:async s=>[...s,"avif"],remove:async s=>s.filter(t=>t!=="avif")},vl=["png","jpg","jpeg"],b_={extension:{type:C.DetectionParser,priority:-1},test:()=>Promise.resolve(!0),add:async s=>[...s,...vl],remove:async s=>s.filter(t=>!vl.includes(t))},v_="WorkerGlobalScope"in globalThis&&globalThis instanceof globalThis.WorkerGlobalScope;function Gr(s){return v_?!1:document.createElement("video").canPlayType(s)!==""}const w_={extension:{type:C.DetectionParser,priority:0},test:async()=>Gr("video/mp4"),add:async s=>[...s,"mp4","m4v"],remove:async s=>s.filter(t=>t!=="mp4"&&t!=="m4v")},S_={extension:{type:C.DetectionParser,priority:0},test:async()=>Gr("video/ogg"),add:async s=>[...s,"ogv"],remove:async s=>s.filter(t=>t!=="ogv")},T_={extension:{type:C.DetectionParser,priority:0},test:async()=>Gr("video/webm"),add:async s=>[...s,"webm"],remove:async s=>s.filter(t=>t!=="webm")},C_={extension:{type:C.DetectionParser,priority:0},test:async()=>bl("data:image/webp;base64,UklGRh4AAABXRUJQVlA4TBEAAAAvAAAAAAfQ//73v/+BiOh/AAA="),add:async s=>[...s,"webp"],remove:async s=>s.filter(t=>t!=="webp")},wl=class qr{constructor(){this.loadOptions={...qr.defaultOptions},this._parsers=[],this._parsersValidated=!1,this.parsers=new Proxy(this._parsers,{set:(t,e,r)=>(this._parsersValidated=!1,t[e]=r,!0)}),this.promiseCache={}}reset(){this._parsersValidated=!1,this.promiseCache={}}_getLoadPromiseAndParser(t,e){const r={promise:null,parser:null};return r.promise=(async()=>{let n=null,o=null;if((e.parser||e.loadParser)&&(o=this._parserHash[e.parser||e.loadParser],e.loadParser&&F(`[Assets] "loadParser" is deprecated, use "parser" instead for ${t}`),o||F(`[Assets] specified load parser "${e.parser||e.loadParser}" not found while loading ${t}`)),!o){for(let l=0;l<this.parsers.length;l++){const h=this.parsers[l];if(h.load&&h.test?.(t,e,this)){o=h;break}}if(!o)return F(`[Assets] ${t} could not be loaded as we don't know how to parse it, ensure the correct parser has been added`),null}n=await o.load(t,e,this),r.parser=o;for(let l=0;l<this.parsers.length;l++){const h=this.parsers[l];h.parse&&h.parse&&await h.testParse?.(n,e,this)&&(n=await h.parse(n,e,this)||n,r.parser=h)}return n})(),r}async load(t,e){this._parsersValidated||this._validateParsers();const r=typeof e=="function"?{...qr.defaultOptions,...this.loadOptions,onProgress:e}:{...qr.defaultOptions,...this.loadOptions,...e||{}},{onProgress:n,onError:o,strategy:l,retryCount:h,retryDelay:u}=r;let f=0;const m={},g=yr(t),y=Lt(t,c=>({alias:[c],src:c,data:{}})),x=y.reduce((c,d)=>c+(d.progressSize||1),0),a=y.map(async c=>{const d=At.toAbsolute(c.src);m[c.src]||(await this._loadAssetWithRetry(d,c,{onProgress:n,onError:o,strategy:l,retryCount:h,retryDelay:u},m),f+=c.progressSize||1,n&&n(f/x))});return await Promise.all(a),g?m[y[0].src]:m}async unload(t){const r=Lt(t,n=>({alias:[n],src:n})).map(async n=>{const o=At.toAbsolute(n.src),l=this.promiseCache[o];if(l){const h=await l.promise;delete this.promiseCache[o],await l.parser?.unload?.(h,n,this)}});await Promise.all(r)}_validateParsers(){this._parsersValidated=!0,this._parserHash=this._parsers.filter(t=>t.name||t.id).reduce((t,e)=>(!e.name&&!e.id?F("[Assets] parser should have an id"):(t[e.name]||t[e.id])&&F(`[Assets] parser id conflict "${e.id}"`),t[e.name]=e,e.id&&(t[e.id]=e),t),{})}async _loadAssetWithRetry(t,e,r,n){let o=0;const{onError:l,strategy:h,retryCount:u,retryDelay:f}=r,m=g=>new Promise(y=>setTimeout(y,g));for(;;)try{this.promiseCache[t]||(this.promiseCache[t]=this._getLoadPromiseAndParser(t,e)),n[e.src]=await this.promiseCache[t].promise;return}catch(g){delete this.promiseCache[t],delete n[e.src],o++;const y=h!=="retry"||o>u;if(h==="retry"&&!y){l&&l(g,e),await m(f);continue}if(h==="skip"){l&&l(g,e);return}throw l&&l(g,e),new Error(`[Loader.load] Failed to load ${t}.
|
|
321
|
+
${g}`)}}};wl.defaultOptions={onProgress:void 0,onError:void 0,strategy:"throw",retryCount:3,retryDelay:250};let E_=wl;function je(s,t){if(Array.isArray(t)){for(const e of t)if(s.startsWith(`data:${e}`))return!0;return!1}return s.startsWith(`data:${t}`)}function qe(s,t){const e=s.split("?")[0],r=At.extname(e).toLowerCase();return Array.isArray(t)?t.includes(r):r===t}const A_=".json",P_="application/json",B_={extension:{type:C.LoadParser,priority:ue.Low},name:"loadJson",id:"json",test(s){return je(s,P_)||qe(s,A_)},async load(s){return await(await W.get().fetch(s)).json()}},U_=".txt",k_="text/plain",M_={name:"loadTxt",id:"text",extension:{type:C.LoadParser,priority:ue.Low,name:"loadTxt"},test(s){return je(s,k_)||qe(s,U_)},async load(s){return await(await W.get().fetch(s)).text()}},R_=["normal","bold","100","200","300","400","500","600","700","800","900"],I_=[".ttf",".otf",".woff",".woff2"],F_=["font/ttf","font/otf","font/woff","font/woff2"],D_=/^(--|-?[A-Z_])[0-9A-Z_-]*$/i;function O_(s){const t=At.extname(s),n=At.basename(s,t).replace(/(-|_)/g," ").toLowerCase().split(" ").map(h=>h.charAt(0).toUpperCase()+h.slice(1));let o=n.length>0;for(const h of n)if(!h.match(D_)){o=!1;break}let l=n.join(" ");return o||(l=`"${l.replace(/[\\"]/g,"\\$&")}"`),l}const G_=/^[0-9A-Za-z%:/?#\[\]@!\$&'()\*\+,;=\-._~]*$/;function L_(s){return G_.test(s)?s:encodeURI(s)}const z_={extension:{type:C.LoadParser,priority:ue.Low},name:"loadWebFont",id:"web-font",test(s){return je(s,F_)||qe(s,I_)},async load(s,t){const e=W.get().getFontFaceSet();if(e){const r=[],n=t.data?.family??O_(s),o=t.data?.weights?.filter(h=>R_.includes(h))??["normal"],l=t.data??{};for(let h=0;h<o.length;h++){const u=o[h],f=new FontFace(n,`url(${L_(s)})`,{...l,weight:u});await f.load(),e.add(f),r.push(f)}return Q.has(`${n}-and-url`)?Q.get(`${n}-and-url`).entries.push({url:s,faces:r}):Q.set(`${n}-and-url`,{entries:[{url:s,faces:r}]}),r.length===1?r[0]:r}return F("[loadWebFont] FontFace API is not supported. Skipping loading font"),null},unload(s){const t=Array.isArray(s)?s:[s],e=t[0].family,r=Q.get(`${e}-and-url`),n=r.entries.find(o=>o.faces.some(l=>t.indexOf(l)!==-1));n.faces=n.faces.filter(o=>t.indexOf(o)===-1),n.faces.length===0&&(r.entries=r.entries.filter(o=>o!==n)),t.forEach(o=>{W.get().getFontFaceSet().delete(o)}),r.entries.length===0&&Q.remove(`${e}-and-url`)}};function Un(s,t=1){const e=Ve.RETINA_PREFIX?.exec(s);return e?parseFloat(e[1]):t}function kn(s,t,e){s.label=e,s._sourceOrigin=e;const r=new k({source:s,label:e}),n=()=>{delete t.promiseCache[e],Q.has(e)&&Q.remove(e)};return r.source.once("destroy",()=>{t.promiseCache[e]&&(F("[Assets] A TextureSource managed by Assets was destroyed instead of unloaded! Use Assets.unload() instead of destroying the TextureSource."),n())}),r.once("destroy",()=>{s.destroyed||(F("[Assets] A Texture managed by Assets was destroyed instead of unloaded! Use Assets.unload() instead of destroying the Texture."),n())}),r}const N_=".svg",H_="image/svg+xml",W_={extension:{type:C.LoadParser,priority:ue.Low,name:"loadSVG"},name:"loadSVG",id:"svg",config:{crossOrigin:"anonymous",parseAsGraphicsContext:!1},test(s){return je(s,H_)||qe(s,N_)},async load(s,t,e){return t.data?.parseAsGraphicsContext??this.config.parseAsGraphicsContext?Y_(s):V_(s,t,e,this.config.crossOrigin)},unload(s){s.destroy(!0)}};async function V_(s,t,e,r){const n=await W.get().fetch(s),o=W.get().createImage();o.src=`data:image/svg+xml;charset=utf-8,${encodeURIComponent(await n.text())}`,o.crossOrigin=r,await o.decode();const l=t.data?.width??o.width,h=t.data?.height??o.height,u=t.data?.resolution||Un(s),f=Math.ceil(l*u),m=Math.ceil(h*u),g=W.get().createCanvas(f,m),y=g.getContext("2d");y.imageSmoothingEnabled=!0,y.imageSmoothingQuality="high",y.drawImage(o,0,0,l*u,h*u);const{parseAsGraphicsContext:x,...a}=t.data??{},c=new Se({resource:g,alphaMode:"premultiply-alpha-on-upload",resolution:u,...a});return kn(c,e,s)}async function Y_(s){const e=await(await W.get().fetch(s)).text(),r=new Dt;return r.svg(e),r}const X_=`(function () {
|
|
322
322
|
'use strict';
|
|
323
323
|
|
|
324
324
|
const WHITE_PNG = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+ip1sAAAAASUVORK5CYII=";
|
|
@@ -339,7 +339,7 @@ ${g}`)}}};yl.defaultOptions={onProgress:void 0,onError:void 0,strategy:"throw",r
|
|
|
339
339
|
});
|
|
340
340
|
|
|
341
341
|
})();
|
|
342
|
-
`;let
|
|
342
|
+
`;let Ze=null,Mn=class{constructor(){Ze||(Ze=URL.createObjectURL(new Blob([X_],{type:"application/javascript"}))),this.worker=new Worker(Ze)}};Mn.revokeObjectURL=function(){Ze&&(URL.revokeObjectURL(Ze),Ze=null)};const $_=`(function () {
|
|
343
343
|
'use strict';
|
|
344
344
|
|
|
345
345
|
async function loadImageBitmap(url, alphaMode) {
|
|
@@ -368,7 +368,7 @@ ${g}`)}}};yl.defaultOptions={onProgress:void 0,onError:void 0,strategy:"throw",r
|
|
|
368
368
|
};
|
|
369
369
|
|
|
370
370
|
})();
|
|
371
|
-
`;let Ze=null;class xl{constructor(){Ze||(Ze=URL.createObjectURL(new Blob([O_],{type:"application/javascript"}))),this.worker=new Worker(Ze)}}xl.revokeObjectURL=function(){Ze&&(URL.revokeObjectURL(Ze),Ze=null)};let bl=0,Un;class L_{constructor(){this._initialized=!1,this._createdWorkers=0,this._workerPool=[],this._queue=[],this._resolveHash={}}isImageBitmapSupported(){return this._isImageBitmapSupported!==void 0?this._isImageBitmapSupported:(this._isImageBitmapSupported=new Promise(t=>{const{worker:e}=new Bn;e.addEventListener("message",r=>{e.terminate(),Bn.revokeObjectURL(),t(r.data)})}),this._isImageBitmapSupported)}loadImageBitmap(t,e){return this._run("loadImageBitmap",[t,e?.data?.alphaMode])}async _initWorkers(){this._initialized||(this._initialized=!0)}_getWorker(){Un===void 0&&(Un=navigator.hardwareConcurrency||4);let t=this._workerPool.pop();return!t&&this._createdWorkers<Un&&(this._createdWorkers++,t=new xl().worker,t.addEventListener("message",e=>{this._complete(e.data),this._returnWorker(e.target),this._next()})),t}_returnWorker(t){this._workerPool.push(t)}_complete(t){this._resolveHash[t.uuid]&&(t.error!==void 0?this._resolveHash[t.uuid].reject(t.error):this._resolveHash[t.uuid].resolve(t.data),delete this._resolveHash[t.uuid])}async _run(t,e){await this._initWorkers();const r=new Promise((n,a)=>{this._queue.push({id:t,arguments:e,resolve:n,reject:a})});return this._next(),r}_next(){if(!this._queue.length)return;const t=this._getWorker();if(!t)return;const e=this._queue.pop(),r=e.id;this._resolveHash[bl]={resolve:e.resolve,reject:e.reject},t.postMessage({data:e.arguments,uuid:bl++,id:r})}reset(){this._workerPool.forEach(t=>t.terminate()),this._workerPool.length=0,Object.values(this._resolveHash).forEach(({reject:t})=>{t?.(new Error("WorkerManager has been reset before completion"))}),this._resolveHash={},this._queue.length=0,this._initialized=!1,this._createdWorkers=0}}const vl=new L_,z_=[".jpeg",".jpg",".png",".webp",".avif"],N_=["image/jpeg","image/png","image/webp","image/avif"];async function H_(s,t){const e=await W.get().fetch(s);if(!e.ok)throw new Error(`[loadImageBitmap] Failed to fetch ${s}: ${e.status} ${e.statusText}`);const r=await e.blob();return t?.data?.alphaMode==="premultiplied-alpha"?createImageBitmap(r,{premultiplyAlpha:"none"}):createImageBitmap(r)}const wl={name:"loadTextures",id:"texture",extension:{type:C.LoadParser,priority:ce.High,name:"loadTextures"},config:{preferWorkers:!0,preferCreateImageBitmap:!0,crossOrigin:"anonymous"},test(s){return Ke(s,N_)||je(s,z_)},async load(s,t,e){let r=null;globalThis.createImageBitmap&&this.config.preferCreateImageBitmap?this.config.preferWorkers&&await vl.isImageBitmapSupported()?r=await vl.loadImageBitmap(s,t):r=await H_(s,t):r=await new Promise((a,l)=>{r=W.get().createImage(),r.crossOrigin=this.config.crossOrigin,r.src=s,r.complete?a(r):(r.onload=()=>{a(r)},r.onerror=l)});const n=new we({resource:r,alphaMode:"premultiply-alpha-on-upload",resolution:t.data?.resolution||An(s),...t.data});return Pn(n,e,s)},unload(s){s.destroy(!0)}},W_=[".mp4",".m4v",".webm",".ogg",".ogv",".h264",".avi",".mov"];let Mn,kn;function V_(s,t,e){e===void 0&&!t.startsWith("data:")?s.crossOrigin=X_(t):e!==!1&&(s.crossOrigin=typeof e=="string"?e:"anonymous")}function Y_(s){return new Promise((t,e)=>{s.addEventListener("canplaythrough",r),s.addEventListener("error",n),s.load();function r(){a(),t()}function n(l){a(),e(l)}function a(){s.removeEventListener("canplaythrough",r),s.removeEventListener("error",n)}})}function X_(s,t=globalThis.location){if(s.startsWith("data:"))return"";t||(t=globalThis.location);const e=new URL(s,document.baseURI);return e.hostname!==t.hostname||e.port!==t.port||e.protocol!==t.protocol?"anonymous":""}function $_(){const s=[],t=[];for(const e of W_){const r=di.MIME_TYPES[e.substring(1)]||`video/${e.substring(1)}`;Dr(r)&&(s.push(e),t.includes(r)||t.push(r))}return{validVideoExtensions:s,validVideoMime:t}}const K_={name:"loadVideo",id:"video",extension:{type:C.LoadParser,name:"loadVideo"},test(s){if(!Mn||!kn){const{validVideoExtensions:r,validVideoMime:n}=$_();Mn=r,kn=n}const t=Ke(s,kn),e=je(s,Mn);return t||e},async load(s,t,e){const r={...di.defaultOptions,resolution:t.data?.resolution||An(s),alphaMode:t.data?.alphaMode||await Bo(),...t.data},n=document.createElement("video"),a={preload:r.autoLoad!==!1?"auto":void 0,"webkit-playsinline":r.playsinline!==!1?"":void 0,playsinline:r.playsinline!==!1?"":void 0,muted:r.muted===!0?"":void 0,loop:r.loop===!0?"":void 0,autoplay:r.autoPlay!==!1?"":void 0};Object.keys(a).forEach(d=>{const f=a[d];f!==void 0&&n.setAttribute(d,f)}),r.muted===!0&&(n.muted=!0),V_(n,s,r.crossorigin);const l=document.createElement("source");let h;if(r.mime)h=r.mime;else if(s.startsWith("data:"))h=s.slice(5,s.indexOf(";"));else if(!s.startsWith("blob:")){const d=s.split("?")[0].slice(s.lastIndexOf(".")+1).toLowerCase();h=di.MIME_TYPES[d]||`video/${d}`}return l.src=s,h&&(l.type=h),new Promise(d=>{const f=async()=>{const m=new di({...r,resource:n});n.removeEventListener("canplay",f),t.data.preload&&await Y_(n),d(Pn(m,e,s))};r.preload&&!r.autoPlay&&n.load(),n.addEventListener("canplay",f),n.appendChild(l)})},unload(s){s.destroy(!0)}},Sl={extension:{type:C.ResolveParser,name:"resolveTexture"},test:wl.test,parse:s=>({resolution:parseFloat(We.RETINA_PREFIX.exec(s)?.[1]??"1"),format:s.split(".").pop(),src:s})},j_={extension:{type:C.ResolveParser,priority:-2,name:"resolveJson"},test:s=>We.RETINA_PREFIX.test(s)&&s.endsWith(".json"),parse:Sl.parse};class q_{constructor(){this._detections=[],this._initialized=!1,this.resolver=new We,this.loader=new __,this.cache=Q,this._backgroundLoader=new h_(this.loader),this._backgroundLoader.active=!0,this.reset()}async init(t={}){if(this._initialized){F("[Assets]AssetManager already initialized, did you load before calling this Assets.init()?");return}if(this._initialized=!0,t.defaultSearchParams&&this.resolver.setDefaultSearchParams(t.defaultSearchParams),t.basePath&&(this.resolver.basePath=t.basePath),t.bundleIdentifier&&this.resolver.setBundleIdentifier(t.bundleIdentifier),t.manifest){let a=t.manifest;typeof a=="string"&&(a=await this.load(a)),this.resolver.addManifest(a)}const e=t.texturePreference?.resolution??1,r=typeof e=="number"?[e]:e,n=await this._detectFormats({preferredFormats:t.texturePreference?.format,skipDetections:t.skipDetections,detections:this._detections});this.resolver.prefer({params:{format:n,resolution:r}}),t.preferences&&this.setPreferences(t.preferences),t.loadOptions&&(this.loader.loadOptions={...this.loader.loadOptions,...t.loadOptions})}add(t){this.resolver.add(t)}async load(t,e){this._initialized||await this.init();const r=gr(t),n=Lt(t).map(h=>{if(typeof h!="string"){const d=this.resolver.getAlias(h);return d.some(f=>!this.resolver.hasKey(f))&&this.add(h),Array.isArray(d)?d[0]:d}return this.resolver.hasKey(h)||this.add({alias:h,src:h}),h}),a=this.resolver.resolve(n),l=await this._mapLoadToResolve(a,e);return r?l[n[0]]:l}addBundle(t,e){this.resolver.addBundle(t,e)}async loadBundle(t,e){this._initialized||await this.init();let r=!1;typeof t=="string"&&(r=!0,t=[t]);const n=this.resolver.resolveBundle(t),a={},l=Object.keys(n);let h=0;const d=[],f=()=>{e?.(d.reduce((g,y)=>g+y,0)/h)},m=l.map((g,y)=>{const x=n[g],o=Object.values(x),u=[...new Set(o.flat())].reduce((p,_)=>p+(_.progressSize||1),0);return d.push(0),h+=u,this._mapLoadToResolve(x,p=>{d[y]=p*u,f()}).then(p=>{a[g]=p})});return await Promise.all(m),r?a[t[0]]:a}async backgroundLoad(t){this._initialized||await this.init(),typeof t=="string"&&(t=[t]);const e=this.resolver.resolve(t);this._backgroundLoader.add(Object.values(e))}async backgroundLoadBundle(t){this._initialized||await this.init(),typeof t=="string"&&(t=[t]);const e=this.resolver.resolveBundle(t);Object.values(e).forEach(r=>{this._backgroundLoader.add(Object.values(r))})}reset(){this.resolver.reset(),this.loader.reset(),this.cache.reset(),this._initialized=!1}get(t){if(typeof t=="string")return Q.get(t);const e={};for(let r=0;r<t.length;r++)e[r]=Q.get(t[r]);return e}async _mapLoadToResolve(t,e){const r=[...new Set(Object.values(t))];this._backgroundLoader.active=!1;const n=await this.loader.load(r,e);this._backgroundLoader.active=!0;const a={};return r.forEach(l=>{const h=n[l.src],d=[l.src];l.alias&&d.push(...l.alias),d.forEach(f=>{a[f]=h}),Q.set(d,h)}),a}async unload(t){this._initialized||await this.init();const e=Lt(t).map(n=>typeof n!="string"?n.src:n),r=this.resolver.resolve(e);await this._unloadFromResolved(r)}async unloadBundle(t){this._initialized||await this.init(),t=Lt(t);const e=this.resolver.resolveBundle(t),r=Object.keys(e).map(n=>this._unloadFromResolved(e[n]));await Promise.all(r)}async _unloadFromResolved(t){const e=Object.values(t);e.forEach(r=>{Q.remove(r.src)}),await this.loader.unload(e)}async _detectFormats(t){let e=[];t.preferredFormats&&(e=Array.isArray(t.preferredFormats)?t.preferredFormats:[t.preferredFormats]);for(const r of t.detections)t.skipDetections||await r.test()?e=await r.add(e):t.skipDetections||(e=await r.remove(e));return e=e.filter((r,n)=>e.indexOf(r)===n),e}get detections(){return this._detections}setPreferences(t){this.loader.parsers.forEach(e=>{e.config&&Object.keys(e.config).filter(r=>r in t).forEach(r=>{e.config[r]=t[r]})})}}const Oi=new q_;D.handleByList(C.LoadParser,Oi.loader.parsers).handleByList(C.ResolveParser,Oi.resolver.parsers).handleByList(C.CacheParser,Oi.cache.parsers).handleByList(C.DetectionParser,Oi.detections),D.add(l_,u_,c_,g_,f_,p_,m_,b_,S_,M_,I_,wl,K_,o_,a_,Sl,j_);const Tl={loader:C.LoadParser,resolver:C.ResolveParser,cache:C.CacheParser,detection:C.DetectionParser};D.handle(C.Asset,s=>{const t=s.ref;Object.entries(Tl).filter(([e])=>!!t[e]).forEach(([e,r])=>D.add(Object.assign(t[e],{extension:t[e].extension??r})))},s=>{const t=s.ref;Object.keys(Tl).filter(e=>!!t[e]).forEach(e=>D.remove(t[e]))});class Cl{constructor(t){this._attachedDomElements=[],this._renderer=t,this._renderer.runners.postrender.add(this),this._renderer.runners.init.add(this),this._domElement=document.createElement("div"),this._domElement.style.position="absolute",this._domElement.style.top="0",this._domElement.style.left="0",this._domElement.style.pointerEvents="none",this._domElement.style.zIndex="1000"}init(){this._canvasObserver=new Fo({domElement:this._domElement,renderer:this._renderer})}addRenderable(t,e){this._attachedDomElements.includes(t)||this._attachedDomElements.push(t)}updateRenderable(t){}validateRenderable(t){return!0}postrender(){const t=this._attachedDomElements;if(t.length===0){this._domElement.remove();return}this._canvasObserver.ensureAttached();for(let e=0;e<t.length;e++){const r=t[e],n=r.element;if(!r.parent||r.globalDisplayStatus<7)n?.remove(),t.splice(e,1),e--;else{this._domElement.contains(n)||(n.style.position="absolute",n.style.pointerEvents="auto",this._domElement.appendChild(n));const a=r.worldTransform,l=r._anchor,h=r.width*l.x,d=r.height*l.y;n.style.transformOrigin=`${h}px ${d}px`,n.style.transform=`matrix(${a.a}, ${a.b}, ${a.c}, ${a.d}, ${a.tx-h}, ${a.ty-d})`,n.style.opacity=r.groupAlpha.toString()}}}destroy(){this._renderer.runners.postrender.remove(this);for(let t=0;t<this._attachedDomElements.length;t++)this._attachedDomElements[t].element?.remove();this._attachedDomElements.length=0,this._domElement.remove(),this._canvasObserver.destroy(),this._renderer=null}}Cl.extension={type:[C.WebGLPipes,C.WebGPUPipes,C.CanvasPipes],name:"dom"};class Z_{constructor(){this.interactionFrequency=10,this._deltaTime=0,this._didMove=!1,this._tickerAdded=!1,this._pauseUpdate=!0}init(t){this.removeTickerListener(),this.events=t,this.interactionFrequency=10,this._deltaTime=0,this._didMove=!1,this._tickerAdded=!1,this._pauseUpdate=!0}get pauseUpdate(){return this._pauseUpdate}set pauseUpdate(t){this._pauseUpdate=t}addTickerListener(){this._tickerAdded||!this.domElement||(Ct.system.add(this._tickerUpdate,this,He.INTERACTION),this._tickerAdded=!0)}removeTickerListener(){this._tickerAdded&&(Ct.system.remove(this._tickerUpdate,this),this._tickerAdded=!1)}pointerMoved(){this._didMove=!0}_update(){if(!this.domElement||this._pauseUpdate)return;if(this._didMove){this._didMove=!1;return}const t=this.events._rootPointerEvent;this.events.supportsTouchEvents&&t.pointerType==="touch"||globalThis.document.dispatchEvent(this.events.supportsPointerEvents?new PointerEvent("pointermove",{clientX:t.clientX,clientY:t.clientY,pointerType:t.pointerType,pointerId:t.pointerId}):new MouseEvent("mousemove",{clientX:t.clientX,clientY:t.clientY}))}_tickerUpdate(t){this._deltaTime+=t.deltaTime,!(this._deltaTime<this.interactionFrequency)&&(this._deltaTime=0,this._update())}destroy(){this.removeTickerListener(),this.events=null,this.domElement=null,this._deltaTime=0,this._didMove=!1,this._tickerAdded=!1,this._pauseUpdate=!0}}const ae=new Z_;class Gr extends pi{constructor(){super(...arguments),this.client=new q,this.movement=new q,this.offset=new q,this.global=new q,this.screen=new q}get clientX(){return this.client.x}get clientY(){return this.client.y}get x(){return this.clientX}get y(){return this.clientY}get movementX(){return this.movement.x}get movementY(){return this.movement.y}get offsetX(){return this.offset.x}get offsetY(){return this.offset.y}get globalX(){return this.global.x}get globalY(){return this.global.y}get screenX(){return this.screen.x}get screenY(){return this.screen.y}getLocalPosition(t,e,r){return t.worldTransform.applyInverse(r||this.global,e)}getModifierState(t){return"getModifierState"in this.nativeEvent&&this.nativeEvent.getModifierState(t)}initMouseEvent(t,e,r,n,a,l,h,d,f,m,g,y,x,o,c){throw new Error("Method not implemented.")}}class Yt extends Gr{constructor(){super(...arguments),this.width=0,this.height=0,this.isPrimary=!1}getCoalescedEvents(){return this.type==="pointermove"||this.type==="mousemove"||this.type==="touchmove"?[this]:[]}getPredictedEvents(){throw new Error("getPredictedEvents is not supported!")}}class Qe extends Gr{constructor(){super(...arguments),this.DOM_DELTA_PIXEL=0,this.DOM_DELTA_LINE=1,this.DOM_DELTA_PAGE=2}}Qe.DOM_DELTA_PIXEL=0,Qe.DOM_DELTA_LINE=1,Qe.DOM_DELTA_PAGE=2;const Q_=2048,J_=new q,Li=new q;class ty{constructor(t){this.dispatch=new Tt,this.moveOnAll=!1,this.enableGlobalMoveEvents=!0,this.mappingState={trackingData:{}},this.eventPool=new Map,this._allInteractiveElements=[],this._hitElements=[],this._isPointerMoveEvent=!1,this.rootTarget=t,this.hitPruneFn=this.hitPruneFn.bind(this),this.hitTestFn=this.hitTestFn.bind(this),this.mapPointerDown=this.mapPointerDown.bind(this),this.mapPointerMove=this.mapPointerMove.bind(this),this.mapPointerOut=this.mapPointerOut.bind(this),this.mapPointerOver=this.mapPointerOver.bind(this),this.mapPointerUp=this.mapPointerUp.bind(this),this.mapPointerUpOutside=this.mapPointerUpOutside.bind(this),this.mapWheel=this.mapWheel.bind(this),this.mappingTable={},this.addEventMapping("pointerdown",this.mapPointerDown),this.addEventMapping("pointermove",this.mapPointerMove),this.addEventMapping("pointerout",this.mapPointerOut),this.addEventMapping("pointerleave",this.mapPointerOut),this.addEventMapping("pointerover",this.mapPointerOver),this.addEventMapping("pointerup",this.mapPointerUp),this.addEventMapping("pointerupoutside",this.mapPointerUpOutside),this.addEventMapping("wheel",this.mapWheel)}addEventMapping(t,e){this.mappingTable[t]||(this.mappingTable[t]=[]),this.mappingTable[t].push({fn:e,priority:0}),this.mappingTable[t].sort((r,n)=>r.priority-n.priority)}dispatchEvent(t,e){t.propagationStopped=!1,t.propagationImmediatelyStopped=!1,this.propagate(t,e),this.dispatch.emit(e||t.type,t)}mapEvent(t){if(!this.rootTarget)return;const e=this.mappingTable[t.type];if(e)for(let r=0,n=e.length;r<n;r++)e[r].fn(t);else F(`[EventBoundary]: Event mapping not defined for ${t.type}`)}hitTest(t,e){ae.pauseUpdate=!0;const n=this._isPointerMoveEvent&&this.enableGlobalMoveEvents?"hitTestMoveRecursive":"hitTestRecursive",a=this[n](this.rootTarget,this.rootTarget.eventMode,J_.set(t,e),this.hitTestFn,this.hitPruneFn);return a&&a[0]}propagate(t,e){if(!t.target)return;const r=t.composedPath();t.eventPhase=t.CAPTURING_PHASE;for(let n=0,a=r.length-1;n<a;n++)if(t.currentTarget=r[n],this.notifyTarget(t,e),t.propagationStopped||t.propagationImmediatelyStopped)return;if(t.eventPhase=t.AT_TARGET,t.currentTarget=t.target,this.notifyTarget(t,e),!(t.propagationStopped||t.propagationImmediatelyStopped)){t.eventPhase=t.BUBBLING_PHASE;for(let n=r.length-2;n>=0;n--)if(t.currentTarget=r[n],this.notifyTarget(t,e),t.propagationStopped||t.propagationImmediatelyStopped)return}}all(t,e,r=this._allInteractiveElements){if(r.length===0)return;t.eventPhase=t.BUBBLING_PHASE;const n=Array.isArray(e)?e:[e];for(let a=r.length-1;a>=0;a--)n.forEach(l=>{t.currentTarget=r[a],this.notifyTarget(t,l)})}propagationPath(t){const e=[t];for(let r=0;r<Q_&&t!==this.rootTarget&&t.parent;r++){if(!t.parent)throw new Error("Cannot find propagation path to disconnected target");e.push(t.parent),t=t.parent}return e.reverse(),e}hitTestMoveRecursive(t,e,r,n,a,l=!1){let h=!1;if(this._interactivePrune(t))return null;if((t.eventMode==="dynamic"||e==="dynamic")&&(ae.pauseUpdate=!1),t.interactiveChildren&&t.children){const m=t.children;for(let g=m.length-1;g>=0;g--){const y=m[g],x=this.hitTestMoveRecursive(y,this._isInteractive(e)?e:y.eventMode,r,n,a,l||a(t,r));if(x){if(x.length>0&&!x[x.length-1].parent)continue;const o=t.isInteractive();(x.length>0||o)&&(o&&this._allInteractiveElements.push(t),x.push(t)),this._hitElements.length===0&&(this._hitElements=x),h=!0}}}const d=this._isInteractive(e),f=t.isInteractive();return f&&f&&this._allInteractiveElements.push(t),l||this._hitElements.length>0?null:h?this._hitElements:d&&!a(t,r)&&n(t,r)?f?[t]:[]:null}hitTestRecursive(t,e,r,n,a){if(this._interactivePrune(t)||a(t,r))return null;if((t.eventMode==="dynamic"||e==="dynamic")&&(ae.pauseUpdate=!1),t.interactiveChildren&&t.children){const d=t.children,f=r;for(let m=d.length-1;m>=0;m--){const g=d[m],y=this.hitTestRecursive(g,this._isInteractive(e)?e:g.eventMode,f,n,a);if(y){if(y.length>0&&!y[y.length-1].parent)continue;const x=t.isInteractive();return(y.length>0||x)&&y.push(t),y}}}const l=this._isInteractive(e),h=t.isInteractive();return l&&n(t,r)?h?[t]:[]:null}_isInteractive(t){return t==="static"||t==="dynamic"}_interactivePrune(t){return!t||!t.visible||!t.renderable||!t.measurable||t.eventMode==="none"||t.eventMode==="passive"&&!t.interactiveChildren}hitPruneFn(t,e){if(t.hitArea&&(t.worldTransform.applyInverse(e,Li),!t.hitArea.contains(Li.x,Li.y)))return!0;if(t.effects&&t.effects.length)for(let r=0;r<t.effects.length;r++){const n=t.effects[r];if(n.containsPoint&&!n.containsPoint(e,this.hitTestFn))return!0}return!1}hitTestFn(t,e){return t.hitArea?!0:t?.containsPoint?(t.worldTransform.applyInverse(e,Li),t.containsPoint(Li)):!1}notifyTarget(t,e){if(!t.currentTarget.isInteractive())return;e??(e=t.type);const r=`on${e}`;t.currentTarget[r]?.(t);const n=t.eventPhase===t.CAPTURING_PHASE||t.eventPhase===t.AT_TARGET?`${e}capture`:e;this._notifyListeners(t,n),t.eventPhase===t.AT_TARGET&&this._notifyListeners(t,e)}mapPointerDown(t){if(!(t instanceof Yt)){F("EventBoundary cannot map a non-pointer event as a pointer event");return}const e=this.createPointerEvent(t);if(this.dispatchEvent(e,"pointerdown"),e.pointerType==="touch")this.dispatchEvent(e,"touchstart");else if(e.pointerType==="mouse"||e.pointerType==="pen"){const n=e.button===2;this.dispatchEvent(e,n?"rightdown":"mousedown")}const r=this.trackingData(t.pointerId);r.pressTargetsByButton[t.button]=e.composedPath(),this.freeEvent(e)}mapPointerMove(t){if(!(t instanceof Yt)){F("EventBoundary cannot map a non-pointer event as a pointer event");return}this._allInteractiveElements.length=0,this._hitElements.length=0,this._isPointerMoveEvent=!0;const e=this.createPointerEvent(t);this._isPointerMoveEvent=!1;const r=e.pointerType==="mouse"||e.pointerType==="pen",n=this.trackingData(t.pointerId),a=this.findMountedTarget(n.overTargets);if(n.overTargets?.length>0&&a!==e.target){const d=t.type==="mousemove"?"mouseout":"pointerout",f=this.createPointerEvent(t,d,a);if(this.dispatchEvent(f,"pointerout"),r&&this.dispatchEvent(f,"mouseout"),!e.composedPath().includes(a)){const m=this.createPointerEvent(t,"pointerleave",a);for(m.eventPhase=m.AT_TARGET;m.target&&!e.composedPath().includes(m.target);)m.currentTarget=m.target,this.notifyTarget(m),r&&this.notifyTarget(m,"mouseleave"),m.target=m.target.parent;this.freeEvent(m)}this.freeEvent(f)}if(a!==e.target){const d=t.type==="mousemove"?"mouseover":"pointerover",f=this.clonePointerEvent(e,d);this.dispatchEvent(f,"pointerover"),r&&this.dispatchEvent(f,"mouseover");let m=a?.parent;for(;m&&m!==this.rootTarget.parent&&m!==e.target;)m=m.parent;if(!m||m===this.rootTarget.parent){const y=this.clonePointerEvent(e,"pointerenter");for(y.eventPhase=y.AT_TARGET;y.target&&y.target!==a&&y.target!==this.rootTarget.parent;)y.currentTarget=y.target,this.notifyTarget(y),r&&this.notifyTarget(y,"mouseenter"),y.target=y.target.parent;this.freeEvent(y)}this.freeEvent(f)}const l=[],h=this.enableGlobalMoveEvents??!0;this.moveOnAll?l.push("pointermove"):this.dispatchEvent(e,"pointermove"),h&&l.push("globalpointermove"),e.pointerType==="touch"&&(this.moveOnAll?l.splice(1,0,"touchmove"):this.dispatchEvent(e,"touchmove"),h&&l.push("globaltouchmove")),r&&(this.moveOnAll?l.splice(1,0,"mousemove"):this.dispatchEvent(e,"mousemove"),h&&l.push("globalmousemove"),this.cursor=e.target?.cursor),l.length>0&&this.all(e,l),this._allInteractiveElements.length=0,this._hitElements.length=0,n.overTargets=e.composedPath(),this.freeEvent(e)}mapPointerOver(t){if(!(t instanceof Yt)){F("EventBoundary cannot map a non-pointer event as a pointer event");return}const e=this.trackingData(t.pointerId),r=this.createPointerEvent(t),n=r.pointerType==="mouse"||r.pointerType==="pen";this.dispatchEvent(r,"pointerover"),n&&this.dispatchEvent(r,"mouseover"),r.pointerType==="mouse"&&(this.cursor=r.target?.cursor);const a=this.clonePointerEvent(r,"pointerenter");for(a.eventPhase=a.AT_TARGET;a.target&&a.target!==this.rootTarget.parent;)a.currentTarget=a.target,this.notifyTarget(a),n&&this.notifyTarget(a,"mouseenter"),a.target=a.target.parent;e.overTargets=r.composedPath(),this.freeEvent(r),this.freeEvent(a)}mapPointerOut(t){if(!(t instanceof Yt)){F("EventBoundary cannot map a non-pointer event as a pointer event");return}const e=this.trackingData(t.pointerId);if(e.overTargets){const r=t.pointerType==="mouse"||t.pointerType==="pen",n=this.findMountedTarget(e.overTargets),a=this.createPointerEvent(t,"pointerout",n);this.dispatchEvent(a),r&&this.dispatchEvent(a,"mouseout");const l=this.createPointerEvent(t,"pointerleave",n);for(l.eventPhase=l.AT_TARGET;l.target&&l.target!==this.rootTarget.parent;)l.currentTarget=l.target,this.notifyTarget(l),r&&this.notifyTarget(l,"mouseleave"),l.target=l.target.parent;e.overTargets=null,this.freeEvent(a),this.freeEvent(l)}this.cursor=null}mapPointerUp(t){if(!(t instanceof Yt)){F("EventBoundary cannot map a non-pointer event as a pointer event");return}const e=performance.now(),r=this.createPointerEvent(t);if(this.dispatchEvent(r,"pointerup"),r.pointerType==="touch")this.dispatchEvent(r,"touchend");else if(r.pointerType==="mouse"||r.pointerType==="pen"){const h=r.button===2;this.dispatchEvent(r,h?"rightup":"mouseup")}const n=this.trackingData(t.pointerId),a=this.findMountedTarget(n.pressTargetsByButton[t.button]);let l=a;if(a&&!r.composedPath().includes(a)){let h=a;for(;h&&!r.composedPath().includes(h);){if(r.currentTarget=h,this.notifyTarget(r,"pointerupoutside"),r.pointerType==="touch")this.notifyTarget(r,"touchendoutside");else if(r.pointerType==="mouse"||r.pointerType==="pen"){const d=r.button===2;this.notifyTarget(r,d?"rightupoutside":"mouseupoutside")}h=h.parent}delete n.pressTargetsByButton[t.button],l=h}if(l){const h=this.clonePointerEvent(r,"click");h.target=l,h.path=null,n.clicksByButton[t.button]||(n.clicksByButton[t.button]={clickCount:0,target:h.target,timeStamp:e});const d=n.clicksByButton[t.button];if(d.target===h.target&&e-d.timeStamp<200?++d.clickCount:d.clickCount=1,d.target=h.target,d.timeStamp=e,h.detail=d.clickCount,h.pointerType==="mouse"){const f=h.button===2;this.dispatchEvent(h,f?"rightclick":"click")}else h.pointerType==="touch"&&this.dispatchEvent(h,"tap");this.dispatchEvent(h,"pointertap"),this.freeEvent(h)}this.freeEvent(r)}mapPointerUpOutside(t){if(!(t instanceof Yt)){F("EventBoundary cannot map a non-pointer event as a pointer event");return}const e=this.trackingData(t.pointerId),r=this.findMountedTarget(e.pressTargetsByButton[t.button]),n=this.createPointerEvent(t);if(r){let a=r;for(;a;)n.currentTarget=a,this.notifyTarget(n,"pointerupoutside"),n.pointerType==="touch"?this.notifyTarget(n,"touchendoutside"):(n.pointerType==="mouse"||n.pointerType==="pen")&&this.notifyTarget(n,n.button===2?"rightupoutside":"mouseupoutside"),a=a.parent;delete e.pressTargetsByButton[t.button]}this.freeEvent(n)}mapWheel(t){if(!(t instanceof Qe)){F("EventBoundary cannot map a non-wheel event as a wheel event");return}const e=this.createWheelEvent(t);this.dispatchEvent(e),this.freeEvent(e)}findMountedTarget(t){if(!t)return null;let e=t[0];for(let r=1;r<t.length&&t[r].parent===e;r++)e=t[r];return e}createPointerEvent(t,e,r){const n=this.allocateEvent(Yt);return this.copyPointerData(t,n),this.copyMouseData(t,n),this.copyData(t,n),n.nativeEvent=t.nativeEvent,n.originalEvent=t,n.target=r??this.hitTest(n.global.x,n.global.y)??this._hitElements[0],typeof e=="string"&&(n.type=e),n}createWheelEvent(t){const e=this.allocateEvent(Qe);return this.copyWheelData(t,e),this.copyMouseData(t,e),this.copyData(t,e),e.nativeEvent=t.nativeEvent,e.originalEvent=t,e.target=this.hitTest(e.global.x,e.global.y),e}clonePointerEvent(t,e){const r=this.allocateEvent(Yt);return r.nativeEvent=t.nativeEvent,r.originalEvent=t.originalEvent,this.copyPointerData(t,r),this.copyMouseData(t,r),this.copyData(t,r),r.target=t.target,r.path=t.composedPath().slice(),r.type=e??r.type,r}copyWheelData(t,e){e.deltaMode=t.deltaMode,e.deltaX=t.deltaX,e.deltaY=t.deltaY,e.deltaZ=t.deltaZ}copyPointerData(t,e){t instanceof Yt&&e instanceof Yt&&(e.pointerId=t.pointerId,e.width=t.width,e.height=t.height,e.isPrimary=t.isPrimary,e.pointerType=t.pointerType,e.pressure=t.pressure,e.tangentialPressure=t.tangentialPressure,e.tiltX=t.tiltX,e.tiltY=t.tiltY,e.twist=t.twist)}copyMouseData(t,e){t instanceof Gr&&e instanceof Gr&&(e.altKey=t.altKey,e.button=t.button,e.buttons=t.buttons,e.client.copyFrom(t.client),e.ctrlKey=t.ctrlKey,e.metaKey=t.metaKey,e.movement.copyFrom(t.movement),e.screen.copyFrom(t.screen),e.shiftKey=t.shiftKey,e.global.copyFrom(t.global))}copyData(t,e){e.isTrusted=t.isTrusted,e.srcElement=t.srcElement,e.timeStamp=performance.now(),e.type=t.type,e.detail=t.detail,e.view=t.view,e.which=t.which,e.layer.copyFrom(t.layer),e.page.copyFrom(t.page)}trackingData(t){return this.mappingState.trackingData[t]||(this.mappingState.trackingData[t]={pressTargetsByButton:{},clicksByButton:{},overTarget:null}),this.mappingState.trackingData[t]}allocateEvent(t){this.eventPool.has(t)||this.eventPool.set(t,[]);const e=this.eventPool.get(t).pop()||new t(this);return e.eventPhase=e.NONE,e.currentTarget=null,e.defaultPrevented=!1,e.path=null,e.target=null,e}freeEvent(t){if(t.manager!==this)throw new Error("It is illegal to free an event not managed by this EventBoundary!");const e=t.constructor;this.eventPool.has(e)||this.eventPool.set(e,[]),this.eventPool.get(e).push(t)}_notifyListeners(t,e){const r=t.currentTarget._events[e];if(r)if("fn"in r)r.once&&t.currentTarget.removeListener(e,r.fn,void 0,!0),r.fn.call(r.context,t);else for(let n=0,a=r.length;n<a&&!t.propagationImmediatelyStopped;n++)r[n].once&&t.currentTarget.removeListener(e,r[n].fn,void 0,!0),r[n].fn.call(r[n].context,t)}}const ey=1,iy={touchstart:"pointerdown",touchend:"pointerup",touchendoutside:"pointerupoutside",touchmove:"pointermove",touchcancel:"pointercancel"},Rn=class xa{constructor(t){this.supportsTouchEvents="ontouchstart"in globalThis,this.supportsPointerEvents=!!globalThis.PointerEvent,this.domElement=null,this.resolution=1,this.renderer=t,this.rootBoundary=new ty(null),ae.init(this),this.autoPreventDefault=!0,this._eventsAdded=!1,this._rootPointerEvent=new Yt(null),this._rootWheelEvent=new Qe(null),this.cursorStyles={default:"inherit",pointer:"pointer"},this.features=new Proxy({...xa.defaultEventFeatures},{set:(e,r,n)=>(r==="globalMove"&&(this.rootBoundary.enableGlobalMoveEvents=n),e[r]=n,!0)}),this._onPointerDown=this._onPointerDown.bind(this),this._onPointerMove=this._onPointerMove.bind(this),this._onPointerUp=this._onPointerUp.bind(this),this._onPointerOverOut=this._onPointerOverOut.bind(this),this.onWheel=this.onWheel.bind(this)}static get defaultEventMode(){return this._defaultEventMode}init(t){const{canvas:e,resolution:r}=this.renderer;this.setTargetElement(e),this.resolution=r,xa._defaultEventMode=t.eventMode??"passive",Object.assign(this.features,t.eventFeatures??{}),this.rootBoundary.enableGlobalMoveEvents=this.features.globalMove}resolutionChange(t){this.resolution=t}destroy(){ae.destroy(),this.setTargetElement(null),this.renderer=null,this._currentCursor=null}setCursor(t){t||(t="default");let e=!0;if(globalThis.OffscreenCanvas&&this.domElement instanceof OffscreenCanvas&&(e=!1),this._currentCursor===t)return;this._currentCursor=t;const r=this.cursorStyles[t];if(r)switch(typeof r){case"string":e&&(this.domElement.style.cursor=r);break;case"function":r(t);break;case"object":e&&Object.assign(this.domElement.style,r);break}else e&&typeof t=="string"&&!Object.prototype.hasOwnProperty.call(this.cursorStyles,t)&&(this.domElement.style.cursor=t)}get pointer(){return this._rootPointerEvent}_onPointerDown(t){if(!this.features.click)return;this.rootBoundary.rootTarget=this.renderer.lastObjectRendered;const e=this._normalizeToPointerData(t);this.autoPreventDefault&&e[0].isNormalized&&(t.cancelable||!("cancelable"in t))&&t.preventDefault();for(let r=0,n=e.length;r<n;r++){const a=e[r],l=this._bootstrapEvent(this._rootPointerEvent,a);this.rootBoundary.mapEvent(l)}this.setCursor(this.rootBoundary.cursor)}_onPointerMove(t){if(!this.features.move)return;this.rootBoundary.rootTarget=this.renderer.lastObjectRendered,ae.pointerMoved();const e=this._normalizeToPointerData(t);for(let r=0,n=e.length;r<n;r++){const a=this._bootstrapEvent(this._rootPointerEvent,e[r]);this.rootBoundary.mapEvent(a)}this.setCursor(this.rootBoundary.cursor)}_onPointerUp(t){if(!this.features.click)return;this.rootBoundary.rootTarget=this.renderer.lastObjectRendered;let e=t.target;t.composedPath&&t.composedPath().length>0&&(e=t.composedPath()[0]);const r=e!==this.domElement?"outside":"",n=this._normalizeToPointerData(t);for(let a=0,l=n.length;a<l;a++){const h=this._bootstrapEvent(this._rootPointerEvent,n[a]);h.type+=r,this.rootBoundary.mapEvent(h)}this.setCursor(this.rootBoundary.cursor)}_onPointerOverOut(t){if(!this.features.click)return;this.rootBoundary.rootTarget=this.renderer.lastObjectRendered;const e=this._normalizeToPointerData(t);for(let r=0,n=e.length;r<n;r++){const a=this._bootstrapEvent(this._rootPointerEvent,e[r]);this.rootBoundary.mapEvent(a)}this.setCursor(this.rootBoundary.cursor)}onWheel(t){if(!this.features.wheel)return;const e=this.normalizeWheelEvent(t);this.rootBoundary.rootTarget=this.renderer.lastObjectRendered,this.rootBoundary.mapEvent(e)}setTargetElement(t){this._removeEvents(),this.domElement=t,ae.domElement=t,this._addEvents()}_addEvents(){if(this._eventsAdded||!this.domElement)return;ae.addTickerListener();const t=this.domElement.style;t&&(globalThis.navigator.msPointerEnabled?(t.msContentZooming="none",t.msTouchAction="none"):this.supportsPointerEvents&&(t.touchAction="none")),this.supportsPointerEvents?(globalThis.document.addEventListener("pointermove",this._onPointerMove,!0),this.domElement.addEventListener("pointerdown",this._onPointerDown,!0),this.domElement.addEventListener("pointerleave",this._onPointerOverOut,!0),this.domElement.addEventListener("pointerover",this._onPointerOverOut,!0),globalThis.addEventListener("pointerup",this._onPointerUp,!0)):(globalThis.document.addEventListener("mousemove",this._onPointerMove,!0),this.domElement.addEventListener("mousedown",this._onPointerDown,!0),this.domElement.addEventListener("mouseout",this._onPointerOverOut,!0),this.domElement.addEventListener("mouseover",this._onPointerOverOut,!0),globalThis.addEventListener("mouseup",this._onPointerUp,!0),this.supportsTouchEvents&&(this.domElement.addEventListener("touchstart",this._onPointerDown,!0),this.domElement.addEventListener("touchend",this._onPointerUp,!0),this.domElement.addEventListener("touchmove",this._onPointerMove,!0))),this.domElement.addEventListener("wheel",this.onWheel,{passive:!0,capture:!0}),this._eventsAdded=!0}_removeEvents(){if(!this._eventsAdded||!this.domElement)return;ae.removeTickerListener();const t=this.domElement.style;t&&(globalThis.navigator.msPointerEnabled?(t.msContentZooming="",t.msTouchAction=""):this.supportsPointerEvents&&(t.touchAction="")),this.supportsPointerEvents?(globalThis.document.removeEventListener("pointermove",this._onPointerMove,!0),this.domElement.removeEventListener("pointerdown",this._onPointerDown,!0),this.domElement.removeEventListener("pointerleave",this._onPointerOverOut,!0),this.domElement.removeEventListener("pointerover",this._onPointerOverOut,!0),globalThis.removeEventListener("pointerup",this._onPointerUp,!0)):(globalThis.document.removeEventListener("mousemove",this._onPointerMove,!0),this.domElement.removeEventListener("mousedown",this._onPointerDown,!0),this.domElement.removeEventListener("mouseout",this._onPointerOverOut,!0),this.domElement.removeEventListener("mouseover",this._onPointerOverOut,!0),globalThis.removeEventListener("mouseup",this._onPointerUp,!0),this.supportsTouchEvents&&(this.domElement.removeEventListener("touchstart",this._onPointerDown,!0),this.domElement.removeEventListener("touchend",this._onPointerUp,!0),this.domElement.removeEventListener("touchmove",this._onPointerMove,!0))),this.domElement.removeEventListener("wheel",this.onWheel,!0),this.domElement=null,this._eventsAdded=!1}mapPositionToPoint(t,e,r){const n=this.domElement.isConnected?this.domElement.getBoundingClientRect():{width:this.domElement.width,height:this.domElement.height,left:0,top:0},a=1/this.resolution;t.x=(e-n.left)*(this.domElement.width/n.width)*a,t.y=(r-n.top)*(this.domElement.height/n.height)*a}_normalizeToPointerData(t){const e=[];if(this.supportsTouchEvents&&t instanceof TouchEvent)for(let r=0,n=t.changedTouches.length;r<n;r++){const a=t.changedTouches[r];typeof a.button>"u"&&(a.button=0),typeof a.buttons>"u"&&(a.buttons=1),typeof a.isPrimary>"u"&&(a.isPrimary=t.touches.length===1&&t.type==="touchstart"),typeof a.width>"u"&&(a.width=a.radiusX||1),typeof a.height>"u"&&(a.height=a.radiusY||1),typeof a.tiltX>"u"&&(a.tiltX=0),typeof a.tiltY>"u"&&(a.tiltY=0),typeof a.pointerType>"u"&&(a.pointerType="touch"),typeof a.pointerId>"u"&&(a.pointerId=a.identifier||0),typeof a.pressure>"u"&&(a.pressure=a.force||.5),typeof a.twist>"u"&&(a.twist=0),typeof a.tangentialPressure>"u"&&(a.tangentialPressure=0),typeof a.layerX>"u"&&(a.layerX=a.offsetX=a.clientX),typeof a.layerY>"u"&&(a.layerY=a.offsetY=a.clientY),a.isNormalized=!0,a.type=t.type,e.push(a)}else if(!globalThis.MouseEvent||t instanceof MouseEvent&&(!this.supportsPointerEvents||!(t instanceof globalThis.PointerEvent))){const r=t;typeof r.isPrimary>"u"&&(r.isPrimary=!0),typeof r.width>"u"&&(r.width=1),typeof r.height>"u"&&(r.height=1),typeof r.tiltX>"u"&&(r.tiltX=0),typeof r.tiltY>"u"&&(r.tiltY=0),typeof r.pointerType>"u"&&(r.pointerType="mouse"),typeof r.pointerId>"u"&&(r.pointerId=ey),typeof r.pressure>"u"&&(r.pressure=.5),typeof r.twist>"u"&&(r.twist=0),typeof r.tangentialPressure>"u"&&(r.tangentialPressure=0),r.isNormalized=!0,e.push(r)}else e.push(t);return e}normalizeWheelEvent(t){const e=this._rootWheelEvent;return this._transferMouseData(e,t),e.deltaX=t.deltaX,e.deltaY=t.deltaY,e.deltaZ=t.deltaZ,e.deltaMode=t.deltaMode,this.mapPositionToPoint(e.screen,t.clientX,t.clientY),e.global.copyFrom(e.screen),e.offset.copyFrom(e.screen),e.nativeEvent=t,e.type=t.type,e}_bootstrapEvent(t,e){return t.originalEvent=null,t.nativeEvent=e,t.pointerId=e.pointerId,t.width=e.width,t.height=e.height,t.isPrimary=e.isPrimary,t.pointerType=e.pointerType,t.pressure=e.pressure,t.tangentialPressure=e.tangentialPressure,t.tiltX=e.tiltX,t.tiltY=e.tiltY,t.twist=e.twist,this._transferMouseData(t,e),this.mapPositionToPoint(t.screen,e.clientX,e.clientY),t.global.copyFrom(t.screen),t.offset.copyFrom(t.screen),t.isTrusted=e.isTrusted,t.type==="pointerleave"&&(t.type="pointerout"),t.type.startsWith("mouse")&&(t.type=t.type.replace("mouse","pointer")),t.type.startsWith("touch")&&(t.type=iy[t.type]||t.type),t}_transferMouseData(t,e){t.isTrusted=e.isTrusted,t.srcElement=e.srcElement,t.timeStamp=performance.now(),t.type=e.type,t.altKey=e.altKey,t.button=e.button,t.buttons=e.buttons,t.client.x=e.clientX,t.client.y=e.clientY,t.ctrlKey=e.ctrlKey,t.metaKey=e.metaKey,t.movement.x=e.movementX,t.movement.y=e.movementY,t.page.x=e.pageX,t.page.y=e.pageY,t.relatedTarget=null,t.shiftKey=e.shiftKey}};Rn.extension={name:"events",type:[C.WebGLSystem,C.CanvasSystem,C.WebGPUSystem],priority:-1},Rn.defaultEventFeatures={move:!0,globalMove:!0,click:!0,wheel:!0};let El=Rn;const ry={onclick:null,onmousedown:null,onmouseenter:null,onmouseleave:null,onmousemove:null,onglobalmousemove:null,onmouseout:null,onmouseover:null,onmouseup:null,onmouseupoutside:null,onpointercancel:null,onpointerdown:null,onpointerenter:null,onpointerleave:null,onpointermove:null,onglobalpointermove:null,onpointerout:null,onpointerover:null,onpointertap:null,onpointerup:null,onpointerupoutside:null,onrightclick:null,onrightdown:null,onrightup:null,onrightupoutside:null,ontap:null,ontouchcancel:null,ontouchend:null,ontouchendoutside:null,ontouchmove:null,onglobaltouchmove:null,ontouchstart:null,onwheel:null,get interactive(){return this.eventMode==="dynamic"||this.eventMode==="static"},set interactive(s){this.eventMode=s?"static":"passive"},_internalEventMode:void 0,get eventMode(){return this._internalEventMode??El.defaultEventMode},set eventMode(s){this._internalEventMode=s},isInteractive(){return this.eventMode==="static"||this.eventMode==="dynamic"},interactiveChildren:!0,hitArea:null,addEventListener(s,t,e){const r=typeof e=="boolean"&&e||typeof e=="object"&&e.capture,n=typeof e=="object"?e.signal:void 0,a=typeof e=="object"?e.once===!0:!1,l=typeof t=="function"?void 0:t;s=r?`${s}capture`:s;const h=typeof t=="function"?t:t.handleEvent,d=this;n&&n.addEventListener("abort",()=>{d.off(s,h,l)}),a?d.once(s,h,l):d.on(s,h,l)},removeEventListener(s,t,e){const r=typeof e=="boolean"&&e||typeof e=="object"&&e.capture,n=typeof t=="function"?void 0:t;s=r?`${s}capture`:s,t=typeof t=="function"?t:t.handleEvent,this.off(s,t,n)},dispatchEvent(s){if(!(s instanceof pi))throw new Error("Container cannot propagate events outside of the Federated Events API");return s.defaultPrevented=!1,s.path=null,s.target=this,s.manager.dispatchEvent(s),!s.defaultPrevented}};var sy=`in vec2 aPosition;
|
|
371
|
+
`;let Qe=null;class Sl{constructor(){Qe||(Qe=URL.createObjectURL(new Blob([$_],{type:"application/javascript"}))),this.worker=new Worker(Qe)}}Sl.revokeObjectURL=function(){Qe&&(URL.revokeObjectURL(Qe),Qe=null)};let Tl=0,Rn;class K_{constructor(){this._initialized=!1,this._createdWorkers=0,this._workerPool=[],this._queue=[],this._resolveHash={}}isImageBitmapSupported(){return this._isImageBitmapSupported!==void 0?this._isImageBitmapSupported:(this._isImageBitmapSupported=new Promise(t=>{const{worker:e}=new Mn;e.addEventListener("message",r=>{e.terminate(),Mn.revokeObjectURL(),t(r.data)})}),this._isImageBitmapSupported)}loadImageBitmap(t,e){return this._run("loadImageBitmap",[t,e?.data?.alphaMode])}async _initWorkers(){this._initialized||(this._initialized=!0)}_getWorker(){Rn===void 0&&(Rn=navigator.hardwareConcurrency||4);let t=this._workerPool.pop();return!t&&this._createdWorkers<Rn&&(this._createdWorkers++,t=new Sl().worker,t.addEventListener("message",e=>{this._complete(e.data),this._returnWorker(e.target),this._next()})),t}_returnWorker(t){this._workerPool.push(t)}_complete(t){this._resolveHash[t.uuid]&&(t.error!==void 0?this._resolveHash[t.uuid].reject(t.error):this._resolveHash[t.uuid].resolve(t.data),delete this._resolveHash[t.uuid])}async _run(t,e){await this._initWorkers();const r=new Promise((n,o)=>{this._queue.push({id:t,arguments:e,resolve:n,reject:o})});return this._next(),r}_next(){if(!this._queue.length)return;const t=this._getWorker();if(!t)return;const e=this._queue.pop(),r=e.id;this._resolveHash[Tl]={resolve:e.resolve,reject:e.reject},t.postMessage({data:e.arguments,uuid:Tl++,id:r})}reset(){this._workerPool.forEach(t=>t.terminate()),this._workerPool.length=0,Object.values(this._resolveHash).forEach(({reject:t})=>{t?.(new Error("WorkerManager has been reset before completion"))}),this._resolveHash={},this._queue.length=0,this._initialized=!1,this._createdWorkers=0}}const Cl=new K_,j_=[".jpeg",".jpg",".png",".webp",".avif"],q_=["image/jpeg","image/png","image/webp","image/avif"];async function Z_(s,t){const e=await W.get().fetch(s);if(!e.ok)throw new Error(`[loadImageBitmap] Failed to fetch ${s}: ${e.status} ${e.statusText}`);const r=await e.blob();return t?.data?.alphaMode==="premultiplied-alpha"?createImageBitmap(r,{premultiplyAlpha:"none"}):createImageBitmap(r)}const El={name:"loadTextures",id:"texture",extension:{type:C.LoadParser,priority:ue.High,name:"loadTextures"},config:{preferWorkers:!0,preferCreateImageBitmap:!0,crossOrigin:"anonymous"},test(s){return je(s,q_)||qe(s,j_)},async load(s,t,e){let r=null;globalThis.createImageBitmap&&this.config.preferCreateImageBitmap?this.config.preferWorkers&&await Cl.isImageBitmapSupported()?r=await Cl.loadImageBitmap(s,t):r=await Z_(s,t):r=await new Promise((o,l)=>{r=W.get().createImage(),r.crossOrigin=this.config.crossOrigin,r.src=s,r.complete?o(r):(r.onload=()=>{o(r)},r.onerror=l)});const n=new Se({resource:r,alphaMode:"premultiply-alpha-on-upload",resolution:t.data?.resolution||Un(s),...t.data});return kn(n,e,s)},unload(s){s.destroy(!0)}},Q_=[".mp4",".m4v",".webm",".ogg",".ogv",".h264",".avi",".mov"];let In,Fn;function J_(s,t,e){e===void 0&&!t.startsWith("data:")?s.crossOrigin=ey(t):e!==!1&&(s.crossOrigin=typeof e=="string"?e:"anonymous")}function ty(s){return new Promise((t,e)=>{s.addEventListener("canplaythrough",r),s.addEventListener("error",n),s.load();function r(){o(),t()}function n(l){o(),e(l)}function o(){s.removeEventListener("canplaythrough",r),s.removeEventListener("error",n)}})}function ey(s,t=globalThis.location){if(s.startsWith("data:"))return"";t||(t=globalThis.location);const e=new URL(s,document.baseURI);return e.hostname!==t.hostname||e.port!==t.port||e.protocol!==t.protocol?"anonymous":""}function iy(){const s=[],t=[];for(const e of Q_){const r=fi.MIME_TYPES[e.substring(1)]||`video/${e.substring(1)}`;Gr(r)&&(s.push(e),t.includes(r)||t.push(r))}return{validVideoExtensions:s,validVideoMime:t}}const ry={name:"loadVideo",id:"video",extension:{type:C.LoadParser,name:"loadVideo"},test(s){if(!In||!Fn){const{validVideoExtensions:r,validVideoMime:n}=iy();In=r,Fn=n}const t=je(s,Fn),e=qe(s,In);return t||e},async load(s,t,e){const r={...fi.defaultOptions,resolution:t.data?.resolution||Un(s),alphaMode:t.data?.alphaMode||await Ra(),...t.data},n=document.createElement("video"),o={preload:r.autoLoad!==!1?"auto":void 0,"webkit-playsinline":r.playsinline!==!1?"":void 0,playsinline:r.playsinline!==!1?"":void 0,muted:r.muted===!0?"":void 0,loop:r.loop===!0?"":void 0,autoplay:r.autoPlay!==!1?"":void 0};Object.keys(o).forEach(u=>{const f=o[u];f!==void 0&&n.setAttribute(u,f)}),r.muted===!0&&(n.muted=!0),J_(n,s,r.crossorigin);const l=document.createElement("source");let h;if(r.mime)h=r.mime;else if(s.startsWith("data:"))h=s.slice(5,s.indexOf(";"));else if(!s.startsWith("blob:")){const u=s.split("?")[0].slice(s.lastIndexOf(".")+1).toLowerCase();h=fi.MIME_TYPES[u]||`video/${u}`}return l.src=s,h&&(l.type=h),new Promise(u=>{const f=async()=>{const m=new fi({...r,resource:n});n.removeEventListener("canplay",f),t.data.preload&&await ty(n),u(kn(m,e,s))};r.preload&&!r.autoPlay&&n.load(),n.addEventListener("canplay",f),n.appendChild(l)})},unload(s){s.destroy(!0)}},Al={extension:{type:C.ResolveParser,name:"resolveTexture"},test:El.test,parse:s=>({resolution:parseFloat(Ve.RETINA_PREFIX.exec(s)?.[1]??"1"),format:s.split(".").pop(),src:s})},sy={extension:{type:C.ResolveParser,priority:-2,name:"resolveJson"},test:s=>Ve.RETINA_PREFIX.test(s)&&s.endsWith(".json"),parse:Al.parse};class ny{constructor(){this._detections=[],this._initialized=!1,this.resolver=new Ve,this.loader=new E_,this.cache=Q,this._backgroundLoader=new __(this.loader),this._backgroundLoader.active=!0,this.reset()}async init(t={}){if(this._initialized){F("[Assets]AssetManager already initialized, did you load before calling this Assets.init()?");return}if(this._initialized=!0,t.defaultSearchParams&&this.resolver.setDefaultSearchParams(t.defaultSearchParams),t.basePath&&(this.resolver.basePath=t.basePath),t.bundleIdentifier&&this.resolver.setBundleIdentifier(t.bundleIdentifier),t.manifest){let o=t.manifest;typeof o=="string"&&(o=await this.load(o)),this.resolver.addManifest(o)}const e=t.texturePreference?.resolution??1,r=typeof e=="number"?[e]:e,n=await this._detectFormats({preferredFormats:t.texturePreference?.format,skipDetections:t.skipDetections,detections:this._detections});this.resolver.prefer({params:{format:n,resolution:r}}),t.preferences&&this.setPreferences(t.preferences),t.loadOptions&&(this.loader.loadOptions={...this.loader.loadOptions,...t.loadOptions})}add(t){this.resolver.add(t)}async load(t,e){this._initialized||await this.init();const r=yr(t),n=Lt(t).map(h=>{if(typeof h!="string"){const u=this.resolver.getAlias(h);return u.some(f=>!this.resolver.hasKey(f))&&this.add(h),Array.isArray(u)?u[0]:u}return this.resolver.hasKey(h)||this.add({alias:h,src:h}),h}),o=this.resolver.resolve(n),l=await this._mapLoadToResolve(o,e);return r?l[n[0]]:l}addBundle(t,e){this.resolver.addBundle(t,e)}async loadBundle(t,e){this._initialized||await this.init();let r=!1;typeof t=="string"&&(r=!0,t=[t]);const n=this.resolver.resolveBundle(t),o={},l=Object.keys(n);let h=0;const u=[],f=()=>{e?.(u.reduce((g,y)=>g+y,0)/h)},m=l.map((g,y)=>{const x=n[g],a=Object.values(x),d=[...new Set(a.flat())].reduce((p,_)=>p+(_.progressSize||1),0);return u.push(0),h+=d,this._mapLoadToResolve(x,p=>{u[y]=p*d,f()}).then(p=>{o[g]=p})});return await Promise.all(m),r?o[t[0]]:o}async backgroundLoad(t){this._initialized||await this.init(),typeof t=="string"&&(t=[t]);const e=this.resolver.resolve(t);this._backgroundLoader.add(Object.values(e))}async backgroundLoadBundle(t){this._initialized||await this.init(),typeof t=="string"&&(t=[t]);const e=this.resolver.resolveBundle(t);Object.values(e).forEach(r=>{this._backgroundLoader.add(Object.values(r))})}reset(){this.resolver.reset(),this.loader.reset(),this.cache.reset(),this._initialized=!1}get(t){if(typeof t=="string")return Q.get(t);const e={};for(let r=0;r<t.length;r++)e[r]=Q.get(t[r]);return e}async _mapLoadToResolve(t,e){const r=[...new Set(Object.values(t))];this._backgroundLoader.active=!1;const n=await this.loader.load(r,e);this._backgroundLoader.active=!0;const o={};return r.forEach(l=>{const h=n[l.src],u=[l.src];l.alias&&u.push(...l.alias),u.forEach(f=>{o[f]=h}),Q.set(u,h)}),o}async unload(t){this._initialized||await this.init();const e=Lt(t).map(n=>typeof n!="string"?n.src:n),r=this.resolver.resolve(e);await this._unloadFromResolved(r)}async unloadBundle(t){this._initialized||await this.init(),t=Lt(t);const e=this.resolver.resolveBundle(t),r=Object.keys(e).map(n=>this._unloadFromResolved(e[n]));await Promise.all(r)}async _unloadFromResolved(t){const e=Object.values(t);e.forEach(r=>{Q.remove(r.src)}),await this.loader.unload(e)}async _detectFormats(t){let e=[];t.preferredFormats&&(e=Array.isArray(t.preferredFormats)?t.preferredFormats:[t.preferredFormats]);for(const r of t.detections)t.skipDetections||await r.test()?e=await r.add(e):t.skipDetections||(e=await r.remove(e));return e=e.filter((r,n)=>e.indexOf(r)===n),e}get detections(){return this._detections}setPreferences(t){this.loader.parsers.forEach(e=>{e.config&&Object.keys(e.config).filter(r=>r in t).forEach(r=>{e.config[r]=t[r]})})}}const Li=new ny;D.handleByList(C.LoadParser,Li.loader.parsers).handleByList(C.ResolveParser,Li.resolver.parsers).handleByList(C.CacheParser,Li.cache.parsers).handleByList(C.DetectionParser,Li.detections),D.add(y_,b_,x_,C_,w_,S_,T_,B_,M_,z_,W_,El,ry,g_,m_,Al,sy);const Pl={loader:C.LoadParser,resolver:C.ResolveParser,cache:C.CacheParser,detection:C.DetectionParser};D.handle(C.Asset,s=>{const t=s.ref;Object.entries(Pl).filter(([e])=>!!t[e]).forEach(([e,r])=>D.add(Object.assign(t[e],{extension:t[e].extension??r})))},s=>{const t=s.ref;Object.keys(Pl).filter(e=>!!t[e]).forEach(e=>D.remove(t[e]))});class Bl{constructor(t){this._attachedDomElements=[],this._renderer=t,this._renderer.runners.postrender.add(this),this._renderer.runners.init.add(this),this._domElement=document.createElement("div"),this._domElement.style.position="absolute",this._domElement.style.top="0",this._domElement.style.left="0",this._domElement.style.pointerEvents="none",this._domElement.style.zIndex="1000"}init(){this._canvasObserver=new La({domElement:this._domElement,renderer:this._renderer})}addRenderable(t,e){this._attachedDomElements.includes(t)||this._attachedDomElements.push(t)}updateRenderable(t){}validateRenderable(t){return!0}postrender(){const t=this._attachedDomElements;if(t.length===0){this._domElement.remove();return}this._canvasObserver.ensureAttached();for(let e=0;e<t.length;e++){const r=t[e],n=r.element;if(!r.parent||r.globalDisplayStatus<7)n?.remove(),t.splice(e,1),e--;else{this._domElement.contains(n)||(n.style.position="absolute",n.style.pointerEvents="auto",this._domElement.appendChild(n));const o=r.worldTransform,l=r._anchor,h=r.width*l.x,u=r.height*l.y;n.style.transformOrigin=`${h}px ${u}px`,n.style.transform=`matrix(${o.a}, ${o.b}, ${o.c}, ${o.d}, ${o.tx-h}, ${o.ty-u})`,n.style.opacity=r.groupAlpha.toString()}}}destroy(){this._renderer.runners.postrender.remove(this);for(let t=0;t<this._attachedDomElements.length;t++)this._attachedDomElements[t].element?.remove();this._attachedDomElements.length=0,this._domElement.remove(),this._canvasObserver.destroy(),this._renderer=null}}Bl.extension={type:[C.WebGLPipes,C.WebGPUPipes,C.CanvasPipes],name:"dom"};class oy{constructor(){this.interactionFrequency=10,this._deltaTime=0,this._didMove=!1,this._tickerAdded=!1,this._pauseUpdate=!0}init(t){this.removeTickerListener(),this.events=t,this.interactionFrequency=10,this._deltaTime=0,this._didMove=!1,this._tickerAdded=!1,this._pauseUpdate=!0}get pauseUpdate(){return this._pauseUpdate}set pauseUpdate(t){this._pauseUpdate=t}addTickerListener(){this._tickerAdded||!this.domElement||(Et.system.add(this._tickerUpdate,this,We.INTERACTION),this._tickerAdded=!0)}removeTickerListener(){this._tickerAdded&&(Et.system.remove(this._tickerUpdate,this),this._tickerAdded=!1)}pointerMoved(){this._didMove=!0}_update(){if(!this.domElement||this._pauseUpdate)return;if(this._didMove){this._didMove=!1;return}const t=this.events._rootPointerEvent;this.events.supportsTouchEvents&&t.pointerType==="touch"||globalThis.document.dispatchEvent(this.events.supportsPointerEvents?new PointerEvent("pointermove",{clientX:t.clientX,clientY:t.clientY,pointerType:t.pointerType,pointerId:t.pointerId}):new MouseEvent("mousemove",{clientX:t.clientX,clientY:t.clientY}))}_tickerUpdate(t){this._deltaTime+=t.deltaTime,!(this._deltaTime<this.interactionFrequency)&&(this._deltaTime=0,this._update())}destroy(){this.removeTickerListener(),this.events=null,this.domElement=null,this._deltaTime=0,this._didMove=!1,this._tickerAdded=!1,this._pauseUpdate=!0}}const he=new oy;class Lr extends mi{constructor(){super(...arguments),this.client=new q,this.movement=new q,this.offset=new q,this.global=new q,this.screen=new q}get clientX(){return this.client.x}get clientY(){return this.client.y}get x(){return this.clientX}get y(){return this.clientY}get movementX(){return this.movement.x}get movementY(){return this.movement.y}get offsetX(){return this.offset.x}get offsetY(){return this.offset.y}get globalX(){return this.global.x}get globalY(){return this.global.y}get screenX(){return this.screen.x}get screenY(){return this.screen.y}getLocalPosition(t,e,r){return t.worldTransform.applyInverse(r||this.global,e)}getModifierState(t){return"getModifierState"in this.nativeEvent&&this.nativeEvent.getModifierState(t)}initMouseEvent(t,e,r,n,o,l,h,u,f,m,g,y,x,a,c){throw new Error("Method not implemented.")}}class Yt extends Lr{constructor(){super(...arguments),this.width=0,this.height=0,this.isPrimary=!1}getCoalescedEvents(){return this.type==="pointermove"||this.type==="mousemove"||this.type==="touchmove"?[this]:[]}getPredictedEvents(){throw new Error("getPredictedEvents is not supported!")}}class Je extends Lr{constructor(){super(...arguments),this.DOM_DELTA_PIXEL=0,this.DOM_DELTA_LINE=1,this.DOM_DELTA_PAGE=2}}Je.DOM_DELTA_PIXEL=0,Je.DOM_DELTA_LINE=1,Je.DOM_DELTA_PAGE=2;const ay=2048,hy=new q,zi=new q;class ly{constructor(t){this.dispatch=new Ct,this.moveOnAll=!1,this.enableGlobalMoveEvents=!0,this.mappingState={trackingData:{}},this.eventPool=new Map,this._allInteractiveElements=[],this._hitElements=[],this._isPointerMoveEvent=!1,this.rootTarget=t,this.hitPruneFn=this.hitPruneFn.bind(this),this.hitTestFn=this.hitTestFn.bind(this),this.mapPointerDown=this.mapPointerDown.bind(this),this.mapPointerMove=this.mapPointerMove.bind(this),this.mapPointerOut=this.mapPointerOut.bind(this),this.mapPointerOver=this.mapPointerOver.bind(this),this.mapPointerUp=this.mapPointerUp.bind(this),this.mapPointerUpOutside=this.mapPointerUpOutside.bind(this),this.mapWheel=this.mapWheel.bind(this),this.mappingTable={},this.addEventMapping("pointerdown",this.mapPointerDown),this.addEventMapping("pointermove",this.mapPointerMove),this.addEventMapping("pointerout",this.mapPointerOut),this.addEventMapping("pointerleave",this.mapPointerOut),this.addEventMapping("pointerover",this.mapPointerOver),this.addEventMapping("pointerup",this.mapPointerUp),this.addEventMapping("pointerupoutside",this.mapPointerUpOutside),this.addEventMapping("wheel",this.mapWheel)}addEventMapping(t,e){this.mappingTable[t]||(this.mappingTable[t]=[]),this.mappingTable[t].push({fn:e,priority:0}),this.mappingTable[t].sort((r,n)=>r.priority-n.priority)}dispatchEvent(t,e){t.propagationStopped=!1,t.propagationImmediatelyStopped=!1,this.propagate(t,e),this.dispatch.emit(e||t.type,t)}mapEvent(t){if(!this.rootTarget)return;const e=this.mappingTable[t.type];if(e)for(let r=0,n=e.length;r<n;r++)e[r].fn(t);else F(`[EventBoundary]: Event mapping not defined for ${t.type}`)}hitTest(t,e){he.pauseUpdate=!0;const n=this._isPointerMoveEvent&&this.enableGlobalMoveEvents?"hitTestMoveRecursive":"hitTestRecursive",o=this[n](this.rootTarget,this.rootTarget.eventMode,hy.set(t,e),this.hitTestFn,this.hitPruneFn);return o&&o[0]}propagate(t,e){if(!t.target)return;const r=t.composedPath();t.eventPhase=t.CAPTURING_PHASE;for(let n=0,o=r.length-1;n<o;n++)if(t.currentTarget=r[n],this.notifyTarget(t,e),t.propagationStopped||t.propagationImmediatelyStopped)return;if(t.eventPhase=t.AT_TARGET,t.currentTarget=t.target,this.notifyTarget(t,e),!(t.propagationStopped||t.propagationImmediatelyStopped)){t.eventPhase=t.BUBBLING_PHASE;for(let n=r.length-2;n>=0;n--)if(t.currentTarget=r[n],this.notifyTarget(t,e),t.propagationStopped||t.propagationImmediatelyStopped)return}}all(t,e,r=this._allInteractiveElements){if(r.length===0)return;t.eventPhase=t.BUBBLING_PHASE;const n=Array.isArray(e)?e:[e];for(let o=r.length-1;o>=0;o--)n.forEach(l=>{t.currentTarget=r[o],this.notifyTarget(t,l)})}propagationPath(t){const e=[t];for(let r=0;r<ay&&t!==this.rootTarget&&t.parent;r++){if(!t.parent)throw new Error("Cannot find propagation path to disconnected target");e.push(t.parent),t=t.parent}return e.reverse(),e}hitTestMoveRecursive(t,e,r,n,o,l=!1){let h=!1;if(this._interactivePrune(t))return null;if((t.eventMode==="dynamic"||e==="dynamic")&&(he.pauseUpdate=!1),t.interactiveChildren&&t.children){const m=t.children;for(let g=m.length-1;g>=0;g--){const y=m[g],x=this.hitTestMoveRecursive(y,this._isInteractive(e)?e:y.eventMode,r,n,o,l||o(t,r));if(x){if(x.length>0&&!x[x.length-1].parent)continue;const a=t.isInteractive();(x.length>0||a)&&(a&&this._allInteractiveElements.push(t),x.push(t)),this._hitElements.length===0&&(this._hitElements=x),h=!0}}}const u=this._isInteractive(e),f=t.isInteractive();return f&&f&&this._allInteractiveElements.push(t),l||this._hitElements.length>0?null:h?this._hitElements:u&&!o(t,r)&&n(t,r)?f?[t]:[]:null}hitTestRecursive(t,e,r,n,o){if(this._interactivePrune(t)||o(t,r))return null;if((t.eventMode==="dynamic"||e==="dynamic")&&(he.pauseUpdate=!1),t.interactiveChildren&&t.children){const u=t.children,f=r;for(let m=u.length-1;m>=0;m--){const g=u[m],y=this.hitTestRecursive(g,this._isInteractive(e)?e:g.eventMode,f,n,o);if(y){if(y.length>0&&!y[y.length-1].parent)continue;const x=t.isInteractive();return(y.length>0||x)&&y.push(t),y}}}const l=this._isInteractive(e),h=t.isInteractive();return l&&n(t,r)?h?[t]:[]:null}_isInteractive(t){return t==="static"||t==="dynamic"}_interactivePrune(t){return!t||!t.visible||!t.renderable||!t.measurable||t.eventMode==="none"||t.eventMode==="passive"&&!t.interactiveChildren}hitPruneFn(t,e){if(t.hitArea&&(t.worldTransform.applyInverse(e,zi),!t.hitArea.contains(zi.x,zi.y)))return!0;if(t.effects&&t.effects.length)for(let r=0;r<t.effects.length;r++){const n=t.effects[r];if(n.containsPoint&&!n.containsPoint(e,this.hitTestFn))return!0}return!1}hitTestFn(t,e){return t.hitArea?!0:t?.containsPoint?(t.worldTransform.applyInverse(e,zi),t.containsPoint(zi)):!1}notifyTarget(t,e){if(!t.currentTarget.isInteractive())return;e??(e=t.type);const r=`on${e}`;t.currentTarget[r]?.(t);const n=t.eventPhase===t.CAPTURING_PHASE||t.eventPhase===t.AT_TARGET?`${e}capture`:e;this._notifyListeners(t,n),t.eventPhase===t.AT_TARGET&&this._notifyListeners(t,e)}mapPointerDown(t){if(!(t instanceof Yt)){F("EventBoundary cannot map a non-pointer event as a pointer event");return}const e=this.createPointerEvent(t);if(this.dispatchEvent(e,"pointerdown"),e.pointerType==="touch")this.dispatchEvent(e,"touchstart");else if(e.pointerType==="mouse"||e.pointerType==="pen"){const n=e.button===2;this.dispatchEvent(e,n?"rightdown":"mousedown")}const r=this.trackingData(t.pointerId);r.pressTargetsByButton[t.button]=e.composedPath(),this.freeEvent(e)}mapPointerMove(t){if(!(t instanceof Yt)){F("EventBoundary cannot map a non-pointer event as a pointer event");return}this._allInteractiveElements.length=0,this._hitElements.length=0,this._isPointerMoveEvent=!0;const e=this.createPointerEvent(t);this._isPointerMoveEvent=!1;const r=e.pointerType==="mouse"||e.pointerType==="pen",n=this.trackingData(t.pointerId),o=this.findMountedTarget(n.overTargets);if(n.overTargets?.length>0&&o!==e.target){const u=t.type==="mousemove"?"mouseout":"pointerout",f=this.createPointerEvent(t,u,o);if(this.dispatchEvent(f,"pointerout"),r&&this.dispatchEvent(f,"mouseout"),!e.composedPath().includes(o)){const m=this.createPointerEvent(t,"pointerleave",o);for(m.eventPhase=m.AT_TARGET;m.target&&!e.composedPath().includes(m.target);)m.currentTarget=m.target,this.notifyTarget(m),r&&this.notifyTarget(m,"mouseleave"),m.target=m.target.parent;this.freeEvent(m)}this.freeEvent(f)}if(o!==e.target){const u=t.type==="mousemove"?"mouseover":"pointerover",f=this.clonePointerEvent(e,u);this.dispatchEvent(f,"pointerover"),r&&this.dispatchEvent(f,"mouseover");let m=o?.parent;for(;m&&m!==this.rootTarget.parent&&m!==e.target;)m=m.parent;if(!m||m===this.rootTarget.parent){const y=this.clonePointerEvent(e,"pointerenter");for(y.eventPhase=y.AT_TARGET;y.target&&y.target!==o&&y.target!==this.rootTarget.parent;)y.currentTarget=y.target,this.notifyTarget(y),r&&this.notifyTarget(y,"mouseenter"),y.target=y.target.parent;this.freeEvent(y)}this.freeEvent(f)}const l=[],h=this.enableGlobalMoveEvents??!0;this.moveOnAll?l.push("pointermove"):this.dispatchEvent(e,"pointermove"),h&&l.push("globalpointermove"),e.pointerType==="touch"&&(this.moveOnAll?l.splice(1,0,"touchmove"):this.dispatchEvent(e,"touchmove"),h&&l.push("globaltouchmove")),r&&(this.moveOnAll?l.splice(1,0,"mousemove"):this.dispatchEvent(e,"mousemove"),h&&l.push("globalmousemove"),this.cursor=e.target?.cursor),l.length>0&&this.all(e,l),this._allInteractiveElements.length=0,this._hitElements.length=0,n.overTargets=e.composedPath(),this.freeEvent(e)}mapPointerOver(t){if(!(t instanceof Yt)){F("EventBoundary cannot map a non-pointer event as a pointer event");return}const e=this.trackingData(t.pointerId),r=this.createPointerEvent(t),n=r.pointerType==="mouse"||r.pointerType==="pen";this.dispatchEvent(r,"pointerover"),n&&this.dispatchEvent(r,"mouseover"),r.pointerType==="mouse"&&(this.cursor=r.target?.cursor);const o=this.clonePointerEvent(r,"pointerenter");for(o.eventPhase=o.AT_TARGET;o.target&&o.target!==this.rootTarget.parent;)o.currentTarget=o.target,this.notifyTarget(o),n&&this.notifyTarget(o,"mouseenter"),o.target=o.target.parent;e.overTargets=r.composedPath(),this.freeEvent(r),this.freeEvent(o)}mapPointerOut(t){if(!(t instanceof Yt)){F("EventBoundary cannot map a non-pointer event as a pointer event");return}const e=this.trackingData(t.pointerId);if(e.overTargets){const r=t.pointerType==="mouse"||t.pointerType==="pen",n=this.findMountedTarget(e.overTargets),o=this.createPointerEvent(t,"pointerout",n);this.dispatchEvent(o),r&&this.dispatchEvent(o,"mouseout");const l=this.createPointerEvent(t,"pointerleave",n);for(l.eventPhase=l.AT_TARGET;l.target&&l.target!==this.rootTarget.parent;)l.currentTarget=l.target,this.notifyTarget(l),r&&this.notifyTarget(l,"mouseleave"),l.target=l.target.parent;e.overTargets=null,this.freeEvent(o),this.freeEvent(l)}this.cursor=null}mapPointerUp(t){if(!(t instanceof Yt)){F("EventBoundary cannot map a non-pointer event as a pointer event");return}const e=performance.now(),r=this.createPointerEvent(t);if(this.dispatchEvent(r,"pointerup"),r.pointerType==="touch")this.dispatchEvent(r,"touchend");else if(r.pointerType==="mouse"||r.pointerType==="pen"){const h=r.button===2;this.dispatchEvent(r,h?"rightup":"mouseup")}const n=this.trackingData(t.pointerId),o=this.findMountedTarget(n.pressTargetsByButton[t.button]);let l=o;if(o&&!r.composedPath().includes(o)){let h=o;for(;h&&!r.composedPath().includes(h);){if(r.currentTarget=h,this.notifyTarget(r,"pointerupoutside"),r.pointerType==="touch")this.notifyTarget(r,"touchendoutside");else if(r.pointerType==="mouse"||r.pointerType==="pen"){const u=r.button===2;this.notifyTarget(r,u?"rightupoutside":"mouseupoutside")}h=h.parent}delete n.pressTargetsByButton[t.button],l=h}if(l){const h=this.clonePointerEvent(r,"click");h.target=l,h.path=null,n.clicksByButton[t.button]||(n.clicksByButton[t.button]={clickCount:0,target:h.target,timeStamp:e});const u=n.clicksByButton[t.button];if(u.target===h.target&&e-u.timeStamp<200?++u.clickCount:u.clickCount=1,u.target=h.target,u.timeStamp=e,h.detail=u.clickCount,h.pointerType==="mouse"){const f=h.button===2;this.dispatchEvent(h,f?"rightclick":"click")}else h.pointerType==="touch"&&this.dispatchEvent(h,"tap");this.dispatchEvent(h,"pointertap"),this.freeEvent(h)}this.freeEvent(r)}mapPointerUpOutside(t){if(!(t instanceof Yt)){F("EventBoundary cannot map a non-pointer event as a pointer event");return}const e=this.trackingData(t.pointerId),r=this.findMountedTarget(e.pressTargetsByButton[t.button]),n=this.createPointerEvent(t);if(r){let o=r;for(;o;)n.currentTarget=o,this.notifyTarget(n,"pointerupoutside"),n.pointerType==="touch"?this.notifyTarget(n,"touchendoutside"):(n.pointerType==="mouse"||n.pointerType==="pen")&&this.notifyTarget(n,n.button===2?"rightupoutside":"mouseupoutside"),o=o.parent;delete e.pressTargetsByButton[t.button]}this.freeEvent(n)}mapWheel(t){if(!(t instanceof Je)){F("EventBoundary cannot map a non-wheel event as a wheel event");return}const e=this.createWheelEvent(t);this.dispatchEvent(e),this.freeEvent(e)}findMountedTarget(t){if(!t)return null;let e=t[0];for(let r=1;r<t.length&&t[r].parent===e;r++)e=t[r];return e}createPointerEvent(t,e,r){const n=this.allocateEvent(Yt);return this.copyPointerData(t,n),this.copyMouseData(t,n),this.copyData(t,n),n.nativeEvent=t.nativeEvent,n.originalEvent=t,n.target=r??this.hitTest(n.global.x,n.global.y)??this._hitElements[0],typeof e=="string"&&(n.type=e),n}createWheelEvent(t){const e=this.allocateEvent(Je);return this.copyWheelData(t,e),this.copyMouseData(t,e),this.copyData(t,e),e.nativeEvent=t.nativeEvent,e.originalEvent=t,e.target=this.hitTest(e.global.x,e.global.y),e}clonePointerEvent(t,e){const r=this.allocateEvent(Yt);return r.nativeEvent=t.nativeEvent,r.originalEvent=t.originalEvent,this.copyPointerData(t,r),this.copyMouseData(t,r),this.copyData(t,r),r.target=t.target,r.path=t.composedPath().slice(),r.type=e??r.type,r}copyWheelData(t,e){e.deltaMode=t.deltaMode,e.deltaX=t.deltaX,e.deltaY=t.deltaY,e.deltaZ=t.deltaZ}copyPointerData(t,e){t instanceof Yt&&e instanceof Yt&&(e.pointerId=t.pointerId,e.width=t.width,e.height=t.height,e.isPrimary=t.isPrimary,e.pointerType=t.pointerType,e.pressure=t.pressure,e.tangentialPressure=t.tangentialPressure,e.tiltX=t.tiltX,e.tiltY=t.tiltY,e.twist=t.twist)}copyMouseData(t,e){t instanceof Lr&&e instanceof Lr&&(e.altKey=t.altKey,e.button=t.button,e.buttons=t.buttons,e.client.copyFrom(t.client),e.ctrlKey=t.ctrlKey,e.metaKey=t.metaKey,e.movement.copyFrom(t.movement),e.screen.copyFrom(t.screen),e.shiftKey=t.shiftKey,e.global.copyFrom(t.global))}copyData(t,e){e.isTrusted=t.isTrusted,e.srcElement=t.srcElement,e.timeStamp=performance.now(),e.type=t.type,e.detail=t.detail,e.view=t.view,e.which=t.which,e.layer.copyFrom(t.layer),e.page.copyFrom(t.page)}trackingData(t){return this.mappingState.trackingData[t]||(this.mappingState.trackingData[t]={pressTargetsByButton:{},clicksByButton:{},overTarget:null}),this.mappingState.trackingData[t]}allocateEvent(t){this.eventPool.has(t)||this.eventPool.set(t,[]);const e=this.eventPool.get(t).pop()||new t(this);return e.eventPhase=e.NONE,e.currentTarget=null,e.defaultPrevented=!1,e.path=null,e.target=null,e}freeEvent(t){if(t.manager!==this)throw new Error("It is illegal to free an event not managed by this EventBoundary!");const e=t.constructor;this.eventPool.has(e)||this.eventPool.set(e,[]),this.eventPool.get(e).push(t)}_notifyListeners(t,e){const r=t.currentTarget._events[e];if(r)if("fn"in r)r.once&&t.currentTarget.removeListener(e,r.fn,void 0,!0),r.fn.call(r.context,t);else for(let n=0,o=r.length;n<o&&!t.propagationImmediatelyStopped;n++)r[n].once&&t.currentTarget.removeListener(e,r[n].fn,void 0,!0),r[n].fn.call(r[n].context,t)}}const cy=1,dy={touchstart:"pointerdown",touchend:"pointerup",touchendoutside:"pointerupoutside",touchmove:"pointermove",touchcancel:"pointercancel"},Dn=class So{constructor(t){this.supportsTouchEvents="ontouchstart"in globalThis,this.supportsPointerEvents=!!globalThis.PointerEvent,this.domElement=null,this.resolution=1,this.renderer=t,this.rootBoundary=new ly(null),he.init(this),this.autoPreventDefault=!0,this._eventsAdded=!1,this._rootPointerEvent=new Yt(null),this._rootWheelEvent=new Je(null),this.cursorStyles={default:"inherit",pointer:"pointer"},this.features=new Proxy({...So.defaultEventFeatures},{set:(e,r,n)=>(r==="globalMove"&&(this.rootBoundary.enableGlobalMoveEvents=n),e[r]=n,!0)}),this._onPointerDown=this._onPointerDown.bind(this),this._onPointerMove=this._onPointerMove.bind(this),this._onPointerUp=this._onPointerUp.bind(this),this._onPointerOverOut=this._onPointerOverOut.bind(this),this.onWheel=this.onWheel.bind(this)}static get defaultEventMode(){return this._defaultEventMode}init(t){const{canvas:e,resolution:r}=this.renderer;this.setTargetElement(e),this.resolution=r,So._defaultEventMode=t.eventMode??"passive",Object.assign(this.features,t.eventFeatures??{}),this.rootBoundary.enableGlobalMoveEvents=this.features.globalMove}resolutionChange(t){this.resolution=t}destroy(){he.destroy(),this.setTargetElement(null),this.renderer=null,this._currentCursor=null}setCursor(t){t||(t="default");let e=!0;if(globalThis.OffscreenCanvas&&this.domElement instanceof OffscreenCanvas&&(e=!1),this._currentCursor===t)return;this._currentCursor=t;const r=this.cursorStyles[t];if(r)switch(typeof r){case"string":e&&(this.domElement.style.cursor=r);break;case"function":r(t);break;case"object":e&&Object.assign(this.domElement.style,r);break}else e&&typeof t=="string"&&!Object.prototype.hasOwnProperty.call(this.cursorStyles,t)&&(this.domElement.style.cursor=t)}get pointer(){return this._rootPointerEvent}_onPointerDown(t){if(!this.features.click)return;this.rootBoundary.rootTarget=this.renderer.lastObjectRendered;const e=this._normalizeToPointerData(t);this.autoPreventDefault&&e[0].isNormalized&&(t.cancelable||!("cancelable"in t))&&t.preventDefault();for(let r=0,n=e.length;r<n;r++){const o=e[r],l=this._bootstrapEvent(this._rootPointerEvent,o);this.rootBoundary.mapEvent(l)}this.setCursor(this.rootBoundary.cursor)}_onPointerMove(t){if(!this.features.move)return;this.rootBoundary.rootTarget=this.renderer.lastObjectRendered,he.pointerMoved();const e=this._normalizeToPointerData(t);for(let r=0,n=e.length;r<n;r++){const o=this._bootstrapEvent(this._rootPointerEvent,e[r]);this.rootBoundary.mapEvent(o)}this.setCursor(this.rootBoundary.cursor)}_onPointerUp(t){if(!this.features.click)return;this.rootBoundary.rootTarget=this.renderer.lastObjectRendered;let e=t.target;t.composedPath&&t.composedPath().length>0&&(e=t.composedPath()[0]);const r=e!==this.domElement?"outside":"",n=this._normalizeToPointerData(t);for(let o=0,l=n.length;o<l;o++){const h=this._bootstrapEvent(this._rootPointerEvent,n[o]);h.type+=r,this.rootBoundary.mapEvent(h)}this.setCursor(this.rootBoundary.cursor)}_onPointerOverOut(t){if(!this.features.click)return;this.rootBoundary.rootTarget=this.renderer.lastObjectRendered;const e=this._normalizeToPointerData(t);for(let r=0,n=e.length;r<n;r++){const o=this._bootstrapEvent(this._rootPointerEvent,e[r]);this.rootBoundary.mapEvent(o)}this.setCursor(this.rootBoundary.cursor)}onWheel(t){if(!this.features.wheel)return;const e=this.normalizeWheelEvent(t);this.rootBoundary.rootTarget=this.renderer.lastObjectRendered,this.rootBoundary.mapEvent(e)}setTargetElement(t){this._removeEvents(),this.domElement=t,he.domElement=t,this._addEvents()}_addEvents(){if(this._eventsAdded||!this.domElement)return;he.addTickerListener();const t=this.domElement.style;t&&(globalThis.navigator.msPointerEnabled?(t.msContentZooming="none",t.msTouchAction="none"):this.supportsPointerEvents&&(t.touchAction="none")),this.supportsPointerEvents?(globalThis.document.addEventListener("pointermove",this._onPointerMove,!0),this.domElement.addEventListener("pointerdown",this._onPointerDown,!0),this.domElement.addEventListener("pointerleave",this._onPointerOverOut,!0),this.domElement.addEventListener("pointerover",this._onPointerOverOut,!0),globalThis.addEventListener("pointerup",this._onPointerUp,!0)):(globalThis.document.addEventListener("mousemove",this._onPointerMove,!0),this.domElement.addEventListener("mousedown",this._onPointerDown,!0),this.domElement.addEventListener("mouseout",this._onPointerOverOut,!0),this.domElement.addEventListener("mouseover",this._onPointerOverOut,!0),globalThis.addEventListener("mouseup",this._onPointerUp,!0),this.supportsTouchEvents&&(this.domElement.addEventListener("touchstart",this._onPointerDown,!0),this.domElement.addEventListener("touchend",this._onPointerUp,!0),this.domElement.addEventListener("touchmove",this._onPointerMove,!0))),this.domElement.addEventListener("wheel",this.onWheel,{passive:!0,capture:!0}),this._eventsAdded=!0}_removeEvents(){if(!this._eventsAdded||!this.domElement)return;he.removeTickerListener();const t=this.domElement.style;t&&(globalThis.navigator.msPointerEnabled?(t.msContentZooming="",t.msTouchAction=""):this.supportsPointerEvents&&(t.touchAction="")),this.supportsPointerEvents?(globalThis.document.removeEventListener("pointermove",this._onPointerMove,!0),this.domElement.removeEventListener("pointerdown",this._onPointerDown,!0),this.domElement.removeEventListener("pointerleave",this._onPointerOverOut,!0),this.domElement.removeEventListener("pointerover",this._onPointerOverOut,!0),globalThis.removeEventListener("pointerup",this._onPointerUp,!0)):(globalThis.document.removeEventListener("mousemove",this._onPointerMove,!0),this.domElement.removeEventListener("mousedown",this._onPointerDown,!0),this.domElement.removeEventListener("mouseout",this._onPointerOverOut,!0),this.domElement.removeEventListener("mouseover",this._onPointerOverOut,!0),globalThis.removeEventListener("mouseup",this._onPointerUp,!0),this.supportsTouchEvents&&(this.domElement.removeEventListener("touchstart",this._onPointerDown,!0),this.domElement.removeEventListener("touchend",this._onPointerUp,!0),this.domElement.removeEventListener("touchmove",this._onPointerMove,!0))),this.domElement.removeEventListener("wheel",this.onWheel,!0),this.domElement=null,this._eventsAdded=!1}mapPositionToPoint(t,e,r){const n=this.domElement.isConnected?this.domElement.getBoundingClientRect():{width:this.domElement.width,height:this.domElement.height,left:0,top:0},o=1/this.resolution;t.x=(e-n.left)*(this.domElement.width/n.width)*o,t.y=(r-n.top)*(this.domElement.height/n.height)*o}_normalizeToPointerData(t){const e=[];if(this.supportsTouchEvents&&t instanceof TouchEvent)for(let r=0,n=t.changedTouches.length;r<n;r++){const o=t.changedTouches[r];typeof o.button>"u"&&(o.button=0),typeof o.buttons>"u"&&(o.buttons=1),typeof o.isPrimary>"u"&&(o.isPrimary=t.touches.length===1&&t.type==="touchstart"),typeof o.width>"u"&&(o.width=o.radiusX||1),typeof o.height>"u"&&(o.height=o.radiusY||1),typeof o.tiltX>"u"&&(o.tiltX=0),typeof o.tiltY>"u"&&(o.tiltY=0),typeof o.pointerType>"u"&&(o.pointerType="touch"),typeof o.pointerId>"u"&&(o.pointerId=o.identifier||0),typeof o.pressure>"u"&&(o.pressure=o.force||.5),typeof o.twist>"u"&&(o.twist=0),typeof o.tangentialPressure>"u"&&(o.tangentialPressure=0),typeof o.layerX>"u"&&(o.layerX=o.offsetX=o.clientX),typeof o.layerY>"u"&&(o.layerY=o.offsetY=o.clientY),o.isNormalized=!0,o.type=t.type,e.push(o)}else if(!globalThis.MouseEvent||t instanceof MouseEvent&&(!this.supportsPointerEvents||!(t instanceof globalThis.PointerEvent))){const r=t;typeof r.isPrimary>"u"&&(r.isPrimary=!0),typeof r.width>"u"&&(r.width=1),typeof r.height>"u"&&(r.height=1),typeof r.tiltX>"u"&&(r.tiltX=0),typeof r.tiltY>"u"&&(r.tiltY=0),typeof r.pointerType>"u"&&(r.pointerType="mouse"),typeof r.pointerId>"u"&&(r.pointerId=cy),typeof r.pressure>"u"&&(r.pressure=.5),typeof r.twist>"u"&&(r.twist=0),typeof r.tangentialPressure>"u"&&(r.tangentialPressure=0),r.isNormalized=!0,e.push(r)}else e.push(t);return e}normalizeWheelEvent(t){const e=this._rootWheelEvent;return this._transferMouseData(e,t),e.deltaX=t.deltaX,e.deltaY=t.deltaY,e.deltaZ=t.deltaZ,e.deltaMode=t.deltaMode,this.mapPositionToPoint(e.screen,t.clientX,t.clientY),e.global.copyFrom(e.screen),e.offset.copyFrom(e.screen),e.nativeEvent=t,e.type=t.type,e}_bootstrapEvent(t,e){return t.originalEvent=null,t.nativeEvent=e,t.pointerId=e.pointerId,t.width=e.width,t.height=e.height,t.isPrimary=e.isPrimary,t.pointerType=e.pointerType,t.pressure=e.pressure,t.tangentialPressure=e.tangentialPressure,t.tiltX=e.tiltX,t.tiltY=e.tiltY,t.twist=e.twist,this._transferMouseData(t,e),this.mapPositionToPoint(t.screen,e.clientX,e.clientY),t.global.copyFrom(t.screen),t.offset.copyFrom(t.screen),t.isTrusted=e.isTrusted,t.type==="pointerleave"&&(t.type="pointerout"),t.type.startsWith("mouse")&&(t.type=t.type.replace("mouse","pointer")),t.type.startsWith("touch")&&(t.type=dy[t.type]||t.type),t}_transferMouseData(t,e){t.isTrusted=e.isTrusted,t.srcElement=e.srcElement,t.timeStamp=performance.now(),t.type=e.type,t.altKey=e.altKey,t.button=e.button,t.buttons=e.buttons,t.client.x=e.clientX,t.client.y=e.clientY,t.ctrlKey=e.ctrlKey,t.metaKey=e.metaKey,t.movement.x=e.movementX,t.movement.y=e.movementY,t.page.x=e.pageX,t.page.y=e.pageY,t.relatedTarget=null,t.shiftKey=e.shiftKey}};Dn.extension={name:"events",type:[C.WebGLSystem,C.CanvasSystem,C.WebGPUSystem],priority:-1},Dn.defaultEventFeatures={move:!0,globalMove:!0,click:!0,wheel:!0};let Ul=Dn;const uy={onclick:null,onmousedown:null,onmouseenter:null,onmouseleave:null,onmousemove:null,onglobalmousemove:null,onmouseout:null,onmouseover:null,onmouseup:null,onmouseupoutside:null,onpointercancel:null,onpointerdown:null,onpointerenter:null,onpointerleave:null,onpointermove:null,onglobalpointermove:null,onpointerout:null,onpointerover:null,onpointertap:null,onpointerup:null,onpointerupoutside:null,onrightclick:null,onrightdown:null,onrightup:null,onrightupoutside:null,ontap:null,ontouchcancel:null,ontouchend:null,ontouchendoutside:null,ontouchmove:null,onglobaltouchmove:null,ontouchstart:null,onwheel:null,get interactive(){return this.eventMode==="dynamic"||this.eventMode==="static"},set interactive(s){this.eventMode=s?"static":"passive"},_internalEventMode:void 0,get eventMode(){return this._internalEventMode??Ul.defaultEventMode},set eventMode(s){this._internalEventMode=s},isInteractive(){return this.eventMode==="static"||this.eventMode==="dynamic"},interactiveChildren:!0,hitArea:null,addEventListener(s,t,e){const r=typeof e=="boolean"&&e||typeof e=="object"&&e.capture,n=typeof e=="object"?e.signal:void 0,o=typeof e=="object"?e.once===!0:!1,l=typeof t=="function"?void 0:t;s=r?`${s}capture`:s;const h=typeof t=="function"?t:t.handleEvent,u=this;n&&n.addEventListener("abort",()=>{u.off(s,h,l)}),o?u.once(s,h,l):u.on(s,h,l)},removeEventListener(s,t,e){const r=typeof e=="boolean"&&e||typeof e=="object"&&e.capture,n=typeof t=="function"?void 0:t;s=r?`${s}capture`:s,t=typeof t=="function"?t:t.handleEvent,this.off(s,t,n)},dispatchEvent(s){if(!(s instanceof mi))throw new Error("Container cannot propagate events outside of the Federated Events API");return s.defaultPrevented=!1,s.path=null,s.target=this,s.manager.dispatchEvent(s),!s.defaultPrevented}};var fy=`in vec2 aPosition;
|
|
372
372
|
out vec2 vTextureCoord;
|
|
373
373
|
|
|
374
374
|
uniform vec4 uInputSize;
|
|
@@ -395,13 +395,13 @@ void main(void)
|
|
|
395
395
|
gl_Position = filterVertexPosition();
|
|
396
396
|
vTextureCoord = filterTextureCoord();
|
|
397
397
|
}
|
|
398
|
-
`,
|
|
398
|
+
`,py=`in vec2 vTextureCoord;
|
|
399
399
|
out vec4 finalColor;
|
|
400
400
|
uniform sampler2D uTexture;
|
|
401
401
|
void main() {
|
|
402
402
|
finalColor = texture(uTexture, vTextureCoord);
|
|
403
403
|
}
|
|
404
|
-
`,
|
|
404
|
+
`,kl=`struct GlobalFilterUniforms {
|
|
405
405
|
uInputSize: vec4<f32>,
|
|
406
406
|
uInputPixel: vec4<f32>,
|
|
407
407
|
uInputClamp: vec4<f32>,
|
|
@@ -450,7 +450,7 @@ fn mainFragment(
|
|
|
450
450
|
) -> @location(0) vec4<f32> {
|
|
451
451
|
return textureSample(uTexture, uSampler, uv);
|
|
452
452
|
}
|
|
453
|
-
`;class
|
|
453
|
+
`;class my extends hh{constructor(){const t=pe.from({vertex:{source:kl,entryPoint:"mainVertex"},fragment:{source:kl,entryPoint:"mainFragment"},name:"passthrough-filter"}),e=Te.from({vertex:fy,fragment:py,name:"passthrough-filter"});super({gpuProgram:t,glProgram:e})}}class Ml{constructor(t){this._renderer=t}push(t,e,r){this._renderer.renderPipes.batch.break(r),r.add({renderPipeId:"filter",canBundle:!1,action:"pushFilter",container:e,filterEffect:t})}pop(t,e,r){this._renderer.renderPipes.batch.break(r),r.add({renderPipeId:"filter",action:"popFilter",canBundle:!1})}execute(t){t.action==="pushFilter"?this._renderer.filter.push(t):t.action==="popFilter"&&this._renderer.filter.pop()}destroy(){this._renderer=null}}Ml.extension={type:[C.WebGLPipes,C.WebGPUPipes,C.CanvasPipes],name:"filter"};const Rl=new M;function gy(s,t){t.clear();const e=t.matrix;for(let r=0;r<s.length;r++){const n=s[r];if(n.globalDisplayStatus<7)continue;const o=n.renderGroup??n.parentRenderGroup;o?.isCachedAsTexture?t.matrix=Rl.copyFrom(o.textureOffsetInverseTransform).append(n.worldTransform):o?._parentCacheAsTextureRenderGroup?t.matrix=Rl.copyFrom(o._parentCacheAsTextureRenderGroup.inverseWorldTransform).append(n.groupTransform):t.matrix=n.worldTransform,t.addBounds(n.bounds)}return t.matrix=e,t}const _y=new Bi({attributes:{aPosition:{buffer:new Float32Array([0,0,1,0,1,1,0,1]),format:"float32x2",stride:8,offset:0}},indexBuffer:new Uint32Array([0,1,2,0,2,3])});class yy{constructor(){this.skip=!1,this.inputTexture=null,this.backTexture=null,this.filters=null,this.bounds=new ut,this.container=null,this.blendRequired=!1,this.outputRenderSurface=null,this.globalFrame={x:0,y:0,width:0,height:0},this.firstEnabledIndex=-1,this.lastEnabledIndex=-1}}class Il{constructor(t){this._filterStackIndex=0,this._filterStack=[],this._filterGlobalUniforms=new _t({uInputSize:{value:new Float32Array(4),type:"vec4<f32>"},uInputPixel:{value:new Float32Array(4),type:"vec4<f32>"},uInputClamp:{value:new Float32Array(4),type:"vec4<f32>"},uOutputFrame:{value:new Float32Array(4),type:"vec4<f32>"},uGlobalFrame:{value:new Float32Array(4),type:"vec4<f32>"},uOutputTexture:{value:new Float32Array(4),type:"vec4<f32>"}}),this._globalFilterBindGroup=new ne({}),this.renderer=t}get activeBackTexture(){return this._activeFilterData?.backTexture}push(t){const e=this.renderer,r=t.filterEffect.filters,n=this._pushFilterData();n.skip=!1,n.filters=r,n.container=t.container,n.outputRenderSurface=e.renderTarget.renderSurface;const o=e.renderTarget.renderTarget.colorTexture.source,l=o.resolution,h=o.antialias;if(r.every(x=>!x.enabled)){n.skip=!0;return}const u=n.bounds;if(this._calculateFilterArea(t,u),this._calculateFilterBounds(n,e.renderTarget.rootViewPort,h,l,1),n.skip)return;const f=this._getPreviousFilterData(),m=this._findFilterResolution(l);let g=0,y=0;f&&(g=f.bounds.minX,y=f.bounds.minY),this._calculateGlobalFrame(n,g,y,m,o.width,o.height),this._setupFilterTextures(n,u,e,f)}generateFilteredTexture({texture:t,filters:e}){const r=this._pushFilterData();this._activeFilterData=r,r.skip=!1,r.filters=e;const n=t.source,o=n.resolution,l=n.antialias;if(e.every(x=>!x.enabled))return r.skip=!0,t;const h=r.bounds;if(h.addRect(t.frame),this._calculateFilterBounds(r,h.rectangle,l,o,0),r.skip)return t;const u=o;this._calculateGlobalFrame(r,0,0,u,n.width,n.height),r.outputRenderSurface=dt.getOptimalTexture(h.width,h.height,r.resolution,r.antialias),r.backTexture=k.EMPTY,r.inputTexture=t,this.renderer.renderTarget.finishRenderPass(),this._applyFiltersToTexture(r,!0);const y=r.outputRenderSurface;return y.source.alphaMode="premultiplied-alpha",y}pop(){const t=this.renderer,e=this._popFilterData();e.skip||(t.globalUniforms.pop(),t.renderTarget.finishRenderPass(),this._activeFilterData=e,this._applyFiltersToTexture(e,!1),e.blendRequired&&dt.returnTexture(e.backTexture),dt.returnTexture(e.inputTexture))}getBackTexture(t,e,r){const n=t.colorTexture.source._resolution,o=dt.getOptimalTexture(e.width,e.height,n,!1);let l=e.minX,h=e.minY;r&&(l-=r.minX,h-=r.minY),l=Math.floor(l*n),h=Math.floor(h*n);const u=Math.ceil(e.width*n),f=Math.ceil(e.height*n);return this.renderer.renderTarget.copyToTexture(t,o,{x:l,y:h},{width:u,height:f},{x:0,y:0}),o}applyFilter(t,e,r,n){const o=this.renderer,l=this._activeFilterData,u=l.outputRenderSurface===r,f=o.renderTarget.rootRenderTarget.colorTexture.source._resolution,m=this._findFilterResolution(f);let g=0,y=0;if(u){const a=this._findPreviousFilterOffset();g=a.x,y=a.y}this._updateFilterUniforms(e,r,l,g,y,m,u,n);const x=t.enabled?t:this._getPassthroughFilter();this._setupBindGroupsAndRender(x,e,o)}calculateSpriteMatrix(t,e){const r=this._activeFilterData,n=t.set(r.inputTexture._source.width,0,0,r.inputTexture._source.height,r.bounds.minX,r.bounds.minY),o=e.worldTransform.copyTo(M.shared),l=e.renderGroup||e.parentRenderGroup;return l&&l.cacheToLocalTransform&&o.prepend(l.cacheToLocalTransform),o.invert(),n.prepend(o),n.scale(1/e.texture.orig.width,1/e.texture.orig.height),n.translate(e.anchor.x,e.anchor.y),n}destroy(){this._passthroughFilter?.destroy(!0),this._passthroughFilter=null}_getPassthroughFilter(){return this._passthroughFilter??(this._passthroughFilter=new my),this._passthroughFilter}_setupBindGroupsAndRender(t,e,r){if(r.renderPipes.uniformBatch){const n=r.renderPipes.uniformBatch.getUboResource(this._filterGlobalUniforms);this._globalFilterBindGroup.setResource(n,0)}else this._globalFilterBindGroup.setResource(this._filterGlobalUniforms,0);this._globalFilterBindGroup.setResource(e.source,1),this._globalFilterBindGroup.setResource(e.source.style,2),t.groups[0]=this._globalFilterBindGroup,r.encoder.draw({geometry:_y,shader:t,state:t._state,topology:"triangle-list"}),r.type===Nt.WEBGL&&r.renderTarget.finishRenderPass()}_setupFilterTextures(t,e,r,n){if(t.backTexture=k.EMPTY,t.inputTexture=dt.getOptimalTexture(e.width,e.height,t.resolution,t.antialias),t.blendRequired){r.renderTarget.finishRenderPass();const o=r.renderTarget.getRenderTarget(t.outputRenderSurface);t.backTexture=this.getBackTexture(o,e,n?.bounds)}r.renderTarget.bind(t.inputTexture,!0),r.globalUniforms.push({offset:e})}_calculateGlobalFrame(t,e,r,n,o,l){const h=t.globalFrame;h.x=e*n,h.y=r*n,h.width=o*n,h.height=l*n}_updateFilterUniforms(t,e,r,n,o,l,h,u){const f=this._filterGlobalUniforms.uniforms,m=f.uOutputFrame,g=f.uInputSize,y=f.uInputPixel,x=f.uInputClamp,a=f.uGlobalFrame,c=f.uOutputTexture;h?(m[0]=r.bounds.minX-n,m[1]=r.bounds.minY-o):(m[0]=0,m[1]=0),m[2]=t.frame.width,m[3]=t.frame.height,g[0]=t.source.width,g[1]=t.source.height,g[2]=1/g[0],g[3]=1/g[1],y[0]=t.source.pixelWidth,y[1]=t.source.pixelHeight,y[2]=1/y[0],y[3]=1/y[1],x[0]=.5*y[2],x[1]=.5*y[3],x[2]=t.frame.width*g[2]-.5*y[2],x[3]=t.frame.height*g[3]-.5*y[3];const d=this.renderer.renderTarget.rootRenderTarget.colorTexture;a[0]=n*l,a[1]=o*l,a[2]=d.source.width*l,a[3]=d.source.height*l,e instanceof k&&(e.source.resource=null);const p=this.renderer.renderTarget.getRenderTarget(e);this.renderer.renderTarget.bind(e,!!u),e instanceof k?(c[0]=e.frame.width,c[1]=e.frame.height):(c[0]=p.width,c[1]=p.height),c[2]=p.isRoot?-1:1,this._filterGlobalUniforms.update()}_findFilterResolution(t){let e=this._filterStackIndex-1;for(;e>0&&this._filterStack[e].skip;)--e;return e>0&&this._filterStack[e].inputTexture?this._filterStack[e].inputTexture.source._resolution:t}_findPreviousFilterOffset(){let t=0,e=0,r=this._filterStackIndex;for(;r>0;){r--;const n=this._filterStack[r];if(!n.skip){t=n.bounds.minX,e=n.bounds.minY;break}}return{x:t,y:e}}_calculateFilterArea(t,e){if(t.renderables?gy(t.renderables,e):t.filterEffect.filterArea?(e.clear(),e.addRect(t.filterEffect.filterArea),e.applyMatrix(t.container.worldTransform)):t.container.getFastGlobalBounds(!0,e),t.container){const n=(t.container.renderGroup||t.container.parentRenderGroup).cacheToLocalTransform;n&&e.applyMatrix(n)}}_applyFiltersToTexture(t,e){const r=t.inputTexture,n=t.bounds,o=t.filters,l=t.firstEnabledIndex,h=t.lastEnabledIndex;if(this._globalFilterBindGroup.setResource(r.source.style,2),this._globalFilterBindGroup.setResource(t.backTexture.source,3),l===h)o[l].apply(this,r,t.outputRenderSurface,e);else{let u=t.inputTexture;const f=dt.getOptimalTexture(n.width,n.height,u.source._resolution,!1);let m=f;for(let g=l;g<h;g++){const y=o[g];if(!y.enabled)continue;y.apply(this,u,m,!0);const x=u;u=m,m=x}o[h].apply(this,u,t.outputRenderSurface,e),dt.returnTexture(f)}}_calculateFilterBounds(t,e,r,n,o){const l=this.renderer,h=t.bounds,u=t.filters;let f=1/0,m=0,g=!0,y=!1,x=!1,a=!0,c=-1,d=-1;for(let p=0;p<u.length;p++){const _=u[p];if(!_.enabled)continue;if(c===-1&&(c=p),d=p,f=Math.min(f,_.resolution==="inherit"?n:_.resolution),m+=_.padding,_.antialias==="off"?g=!1:_.antialias==="inherit"&&g&&(g=r),_.clipToViewport||(a=!1),!!!(_.compatibleRenderers&l.type)){x=!1;break}if(_.blendRequired&&!(l.backBuffer?.useBackBuffer??!0)){F("Blend filter requires backBuffer on WebGL renderer to be enabled. Set `useBackBuffer: true` in the renderer options."),x=!1;break}x=!0,y||(y=_.blendRequired)}if(!x){t.skip=!0;return}if(a&&h.fitBounds(0,e.width/n,0,e.height/n),h.scale(f).ceil().scale(1/f).pad((m|0)*o),!h.isPositive){t.skip=!0;return}t.antialias=g,t.resolution=f,t.blendRequired=y,t.firstEnabledIndex=c,t.lastEnabledIndex=d}_popFilterData(){return this._filterStackIndex--,this._filterStack[this._filterStackIndex]}_getPreviousFilterData(){let t,e=this._filterStackIndex-1;for(;e>0&&(e--,t=this._filterStack[e],!!t.skip););return t}_pushFilterData(){let t=this._filterStack[this._filterStackIndex];return t||(t=this._filterStack[this._filterStackIndex]=new yy),this._filterStackIndex++,t}}Il.extension={type:[C.WebGLSystem,C.WebGPUSystem],name:"filter"};var xy=`in vec2 vMaskCoord;
|
|
454
454
|
in vec2 vTextureCoord;
|
|
455
455
|
|
|
456
456
|
uniform sampler2D uTexture;
|
|
@@ -484,7 +484,7 @@ void main(void)
|
|
|
484
484
|
|
|
485
485
|
finalColor = original * a;
|
|
486
486
|
}
|
|
487
|
-
`,
|
|
487
|
+
`,by=`in vec2 aPosition;
|
|
488
488
|
|
|
489
489
|
out vec2 vTextureCoord;
|
|
490
490
|
out vec2 vMaskCoord;
|
|
@@ -521,7 +521,7 @@ void main(void)
|
|
|
521
521
|
vTextureCoord = filterTextureCoord(aPosition);
|
|
522
522
|
vMaskCoord = getFilterCoord(aPosition);
|
|
523
523
|
}
|
|
524
|
-
`,
|
|
524
|
+
`,Fl=`struct GlobalFilterUniforms {
|
|
525
525
|
uInputSize:vec4<f32>,
|
|
526
526
|
uInputPixel:vec4<f32>,
|
|
527
527
|
uInputClamp:vec4<f32>,
|
|
@@ -619,7 +619,7 @@ fn mainFragment(
|
|
|
619
619
|
|
|
620
620
|
return source * a;
|
|
621
621
|
}
|
|
622
|
-
`;class dy extends sh{constructor(t){const{sprite:e,...r}=t,n=new Ja(e.texture),a=new gt({uFilterMatrix:{value:new k,type:"mat3x3<f32>"},uMaskClamp:{value:n.uClampFrame,type:"vec4<f32>"},uAlpha:{value:1,type:"f32"},uInverse:{value:t.inverse?1:0,type:"f32"}}),l=de.from({vertex:{source:Ml,entryPoint:"mainVertex"},fragment:{source:Ml,entryPoint:"mainFragment"}}),h=Se.from({vertex:uy,fragment:cy,name:"mask-filter"});super({...r,gpuProgram:l,glProgram:h,clipToViewport:!1,resources:{filterUniforms:a,uMaskTexture:e.texture.source}}),this.sprite=e,this._textureMatrix=n}set inverse(t){this.resources.filterUniforms.uniforms.uInverse=t?1:0}get inverse(){return this.resources.filterUniforms.uniforms.uInverse===1}apply(t,e,r,n){this._textureMatrix.texture=this.sprite.texture,t.calculateSpriteMatrix(this.resources.filterUniforms.uniforms.uFilterMatrix,this.sprite).prepend(this._textureMatrix.mapCoord),this.resources.uMaskTexture=this.sprite.texture.source,t.applyFilter(this,e,r,n)}}class pe extends Ms{constructor(t){t instanceof Ft&&(t={context:t});const{context:e,roundPixels:r,...n}=t||{};super({label:"Graphics",...n}),this.renderPipeId="graphics",e?this._context=e:this._context=this._ownedContext=new Ft,this._context.on("update",this.onViewUpdate,this),this.didViewUpdate=!0,this.allowChildren=!1,this.roundPixels=r??!1}set context(t){t!==this._context&&(this._context.off("update",this.onViewUpdate,this),this._context=t,this._context.on("update",this.onViewUpdate,this),this.onViewUpdate())}get context(){return this._context}get bounds(){return this._context.bounds}updateBounds(){}containsPoint(t){return this._context.containsPoint(t)}destroy(t){this._ownedContext&&!t?this._ownedContext.destroy(t):(t===!0||t?.context===!0)&&this._context.destroy(t),this._ownedContext=null,this._context=null,super.destroy(t)}_callContextMethod(t,e){return this.context[t](...e),this}setFillStyle(...t){return this._callContextMethod("setFillStyle",t)}setStrokeStyle(...t){return this._callContextMethod("setStrokeStyle",t)}fill(...t){return this._callContextMethod("fill",t)}stroke(...t){return this._callContextMethod("stroke",t)}texture(...t){return this._callContextMethod("texture",t)}beginPath(){return this._callContextMethod("beginPath",[])}cut(){return this._callContextMethod("cut",[])}arc(...t){return this._callContextMethod("arc",t)}arcTo(...t){return this._callContextMethod("arcTo",t)}arcToSvg(...t){return this._callContextMethod("arcToSvg",t)}bezierCurveTo(...t){return this._callContextMethod("bezierCurveTo",t)}closePath(){return this._callContextMethod("closePath",[])}ellipse(...t){return this._callContextMethod("ellipse",t)}circle(...t){return this._callContextMethod("circle",t)}path(...t){return this._callContextMethod("path",t)}lineTo(...t){return this._callContextMethod("lineTo",t)}moveTo(...t){return this._callContextMethod("moveTo",t)}quadraticCurveTo(...t){return this._callContextMethod("quadraticCurveTo",t)}rect(...t){return this._callContextMethod("rect",t)}roundRect(...t){return this._callContextMethod("roundRect",t)}poly(...t){return this._callContextMethod("poly",t)}regularPoly(...t){return this._callContextMethod("regularPoly",t)}roundPoly(...t){return this._callContextMethod("roundPoly",t)}roundShape(...t){return this._callContextMethod("roundShape",t)}filletRect(...t){return this._callContextMethod("filletRect",t)}chamferRect(...t){return this._callContextMethod("chamferRect",t)}star(...t){return this._callContextMethod("star",t)}svg(...t){return this._callContextMethod("svg",t)}restore(...t){return this._callContextMethod("restore",t)}save(){return this._callContextMethod("save",[])}getTransform(){return this.context.getTransform()}resetTransform(){return this._callContextMethod("resetTransform",[])}rotateTransform(...t){return this._callContextMethod("rotate",t)}scaleTransform(...t){return this._callContextMethod("scale",t)}setTransform(...t){return this._callContextMethod("setTransform",t)}transform(...t){return this._callContextMethod("transform",t)}translateTransform(...t){return this._callContextMethod("translate",t)}clear(){return this._callContextMethod("clear",[])}get fillStyle(){return this._context.fillStyle}set fillStyle(t){this._context.fillStyle=t}get strokeStyle(){return this._context.strokeStyle}set strokeStyle(t){this._context.strokeStyle=t}clone(t=!1){return t?new pe(this._context.clone()):(this._ownedContext=null,new pe(this._context))}lineStyle(t,e,r){z($,"Graphics#lineStyle is no longer needed. Use Graphics#setStrokeStyle to set the stroke style.");const n={};return t&&(n.width=t),e&&(n.color=e),r&&(n.alpha=r),this.context.strokeStyle=n,this}beginFill(t,e){z($,"Graphics#beginFill is no longer needed. Use Graphics#fill to fill the shape with the desired style.");const r={};return t!==void 0&&(r.color=t),e!==void 0&&(r.alpha=e),this.context.fillStyle=r,this}endFill(){z($,"Graphics#endFill is no longer needed. Use Graphics#fill to fill the shape with the desired style."),this.context.fill();const t=this.context.strokeStyle;return(t.width!==Ft.defaultStrokeStyle.width||t.color!==Ft.defaultStrokeStyle.color||t.alpha!==Ft.defaultStrokeStyle.alpha)&&this.context.stroke(),this}drawCircle(...t){return z($,"Graphics#drawCircle has been renamed to Graphics#circle"),this._callContextMethod("circle",t)}drawEllipse(...t){return z($,"Graphics#drawEllipse has been renamed to Graphics#ellipse"),this._callContextMethod("ellipse",t)}drawPolygon(...t){return z($,"Graphics#drawPolygon has been renamed to Graphics#poly"),this._callContextMethod("poly",t)}drawRect(...t){return z($,"Graphics#drawRect has been renamed to Graphics#rect"),this._callContextMethod("rect",t)}drawRoundedRect(...t){return z($,"Graphics#drawRoundedRect has been renamed to Graphics#roundRect"),this._callContextMethod("roundRect",t)}drawStar(...t){return z($,"Graphics#drawStar has been renamed to Graphics#star"),this._callContextMethod("star",t)}}const kl=class ed extends Pi{constructor(...t){let e=t[0]??{};e instanceof Float32Array&&(z($,"use new MeshGeometry({ positions, uvs, indices }) instead"),e={positions:e,uvs:t[1],indices:t[2]}),e={...ed.defaultOptions,...e};const r=e.positions||new Float32Array([0,0,1,0,1,1,0,1]);let n=e.uvs;n||(e.positions?n=new Float32Array(r.length):n=new Float32Array([0,0,1,0,1,1,0,1]));const a=e.indices||new Uint32Array([0,1,2,0,2,3]),l=e.shrinkBuffersToFit,h=new Pt({data:r,label:"attribute-mesh-positions",shrinkToFit:l,usage:Y.VERTEX|Y.COPY_DST}),d=new Pt({data:n,label:"attribute-mesh-uvs",shrinkToFit:l,usage:Y.VERTEX|Y.COPY_DST}),f=new Pt({data:a,label:"index-mesh-buffer",shrinkToFit:l,usage:Y.INDEX|Y.COPY_DST});super({attributes:{aPosition:{buffer:h,format:"float32x2",stride:8,offset:0},aUV:{buffer:d,format:"float32x2",stride:8,offset:0}},indexBuffer:f,topology:e.topology}),this.batchMode="auto"}get positions(){return this.attributes.aPosition.buffer.data}set positions(t){this.attributes.aPosition.buffer.data=t}get uvs(){return this.attributes.aUV.buffer.data}set uvs(t){this.attributes.aUV.buffer.data=t}get indices(){return this.indexBuffer.data}set indices(t){this.indexBuffer.data=t}};kl.defaultOptions={topology:"triangle-list",shrinkBuffersToFit:!1};let In=kl;class Rl extends Ms{constructor(t,e){const{text:r,resolution:n,style:a,anchor:l,width:h,height:d,roundPixels:f,...m}=t;super({...m}),this.batched=!0,this._resolution=null,this._autoResolution=!0,this._didTextUpdate=!0,this._styleClass=e,this.text=r??"",this.style=a,this.resolution=n??null,this.allowChildren=!1,this._anchor=new ct({_onUpdate:()=>{this.onViewUpdate()}}),l&&(this.anchor=l),this.roundPixels=f??!1,h!==void 0&&(this.width=h),d!==void 0&&(this.height=d)}get anchor(){return this._anchor}set anchor(t){typeof t=="number"?this._anchor.set(t):this._anchor.copyFrom(t)}set text(t){t=t.toString(),this._text!==t&&(this._text=t,this.onViewUpdate())}get text(){return this._text}set resolution(t){this._autoResolution=t===null,this._resolution=t,this.onViewUpdate()}get resolution(){return this._resolution}get style(){return this._style}set style(t){t||(t={}),this._style?.off("update",this.onViewUpdate,this),t instanceof this._styleClass?this._style=t:this._style=new this._styleClass(t),this._style.on("update",this.onViewUpdate,this),this.onViewUpdate()}get width(){return Math.abs(this.scale.x)*this.bounds.width}set width(t){this._setWidth(t,this.bounds.width)}get height(){return Math.abs(this.scale.y)*this.bounds.height}set height(t){this._setHeight(t,this.bounds.height)}getSize(t){return t||(t={}),t.width=Math.abs(this.scale.x)*this.bounds.width,t.height=Math.abs(this.scale.y)*this.bounds.height,t}setSize(t,e){typeof t=="object"?(e=t.height??t.width,t=t.width):e??(e=t),t!==void 0&&this._setWidth(t,this.bounds.width),e!==void 0&&this._setHeight(e,this.bounds.height)}containsPoint(t){const e=this.bounds.width,r=this.bounds.height,n=-e*this.anchor.x;let a=0;return t.x>=n&&t.x<=n+e&&(a=-r*this.anchor.y,t.y>=a&&t.y<=a+r)}onViewUpdate(){this.didViewUpdate||(this._didTextUpdate=!0),super.onViewUpdate()}destroy(t=!1){super.destroy(t),this.owner=null,this._bounds=null,this._anchor=null,(typeof t=="boolean"?t:t?.style)&&this._style.destroy(t),this._style=null,this._text=null}get styleKey(){return`${this._text}:${this._style.styleKey}:${this._resolution}`}}function Il(s,t){let e=s[0]??{};return(typeof e=="string"||s[1])&&(z($,`use new ${t}({ text: "hi!", style }) instead`),e={text:e,style:s[1]}),e}let Ae=null,oe=null;function fy(s,t){Ae||(Ae=W.get().createCanvas(256,128),oe=Ae.getContext("2d",{willReadFrequently:!0}),oe.globalCompositeOperation="copy",oe.globalAlpha=1),(Ae.width<s||Ae.height<t)&&(Ae.width=Le(s),Ae.height=Le(t))}function Fl(s,t,e){for(let r=0,n=4*e*t;r<t;++r,n+=4)if(s[n+3]!==0)return!1;return!0}function Dl(s,t,e,r,n){const a=4*t;for(let l=r,h=r*a+4*e;l<=n;++l,h+=a)if(s[h+3]!==0)return!1;return!0}function py(...s){let t=s[0];t.canvas||(t={canvas:s[0],resolution:s[1]});const{canvas:e}=t,r=Math.min(t.resolution??1,1),n=t.width??e.width,a=t.height??e.height;let l=t.output;if(fy(n,a),!oe)throw new TypeError("Failed to get canvas 2D context");oe.drawImage(e,0,0,n,a,0,0,n*r,a*r);const d=oe.getImageData(0,0,n,a).data;let f=0,m=0,g=n-1,y=a-1;for(;m<a&&Fl(d,n,m);)++m;if(m===a)return L.EMPTY;for(;Fl(d,n,y);)--y;for(;Dl(d,n,f,m,y);)++f;for(;Dl(d,n,g,m,y);)--g;return++g,++y,oe.globalCompositeOperation="source-over",oe.strokeRect(f,m,g-f,y-m),oe.globalCompositeOperation="copy",l??(l=new L),l.set(f/r,m/r,(g-f)/r,(y-m)/r),l}const Gl=new L;class my{getCanvasAndContext(t){const{text:e,style:r,resolution:n=1}=t,a=r._getFinalPadding(),l=xt.measureText(e||" ",r),h=Math.ceil(Math.ceil(Math.max(1,l.width)+a*2)*n),d=Math.ceil(Math.ceil(Math.max(1,l.height)+a*2)*n),f=ne.getOptimalCanvasAndContext(h,d);this._renderTextToCanvas(e,r,a,n,f);const m=r.trim?py({canvas:f.canvas,width:h,height:d,resolution:1,output:Gl}):Gl.set(0,0,h,d);return{canvasAndContext:f,frame:m}}returnCanvasAndContext(t){ne.returnCanvasAndContext(t)}_renderTextToCanvas(t,e,r,n,a){const{canvas:l,context:h}=a,d=Er(e),f=xt.measureText(t||" ",e),m=f.lines,g=f.lineHeight,y=f.lineWidths,x=f.maxLineWidth,o=f.fontProperties,c=l.height;if(h.resetTransform(),h.scale(n,n),h.textBaseline=e.textBaseline,e._stroke?.width){const b=e._stroke;h.lineWidth=b.width,h.miterLimit=b.miterLimit,h.lineJoin=b.join,h.lineCap=b.cap}h.font=d;let u,p;const _=e.dropShadow?2:1;for(let b=0;b<_;++b){const v=e.dropShadow&&b===0,w=v?Math.ceil(Math.max(1,c)+r*2):0,S=w*n;if(v){h.fillStyle="black",h.strokeStyle="black";const P=e.dropShadow,B=P.color,A=P.alpha;h.shadowColor=J.shared.setValue(B).setAlpha(A).toRgbaString();const G=P.blur*n,O=P.distance*n;h.shadowBlur=G,h.shadowOffsetX=Math.cos(P.angle)*O,h.shadowOffsetY=Math.sin(P.angle)*O+S}else{if(h.fillStyle=e._fill?Ir(e._fill,h,f,r*2):null,e._stroke?.width){const P=e._stroke.width*.5+r*2;h.strokeStyle=Ir(e._stroke,h,f,P)}h.shadowColor="black"}let T=(g-o.fontSize)/2;g-o.fontSize<0&&(T=0);const E=e._stroke?.width??0;for(let P=0;P<m.length;P++)u=E/2,p=E/2+P*g+o.ascent+T,e.align==="right"?u+=x-y[P]:e.align==="center"&&(u+=(x-y[P])/2),e._stroke?.width&&this._drawLetterSpacing(m[P],e,a,u+r,p+r-w,!0),e._fill!==void 0&&this._drawLetterSpacing(m[P],e,a,u+r,p+r-w)}}_drawLetterSpacing(t,e,r,n,a,l=!1){const{context:h}=r,d=e.letterSpacing;let f=!1;if(xt.experimentalLetterSpacingSupported&&(xt.experimentalLetterSpacing?(h.letterSpacing=`${d}px`,h.textLetterSpacing=`${d}px`,f=!0):(h.letterSpacing="0px",h.textLetterSpacing="0px")),d===0||f){l?h.strokeText(t,n,a):h.fillText(t,n,a);return}let m=n;const g=xt.graphemeSegmenter(t);let y=h.measureText(t).width,x=0;for(let o=0;o<g.length;++o){const c=g[o];l?h.strokeText(c,m,a):h.fillText(c,m,a);let u="";for(let p=o+1;p<g.length;++p)u+=g[p];x=h.measureText(u).width,m+=y-x+d,y=x}}}const zi=new my;class gy extends Rl{constructor(...t){const e=Il(t,"Text");super(e,Bt),this.renderPipeId="text",e.textureStyle&&(this.textureStyle=e.textureStyle instanceof Kt?e.textureStyle:new Kt(e.textureStyle))}updateBounds(){const t=this._bounds,e=this._anchor;let r=0,n=0;if(this._style.trim){const{frame:a,canvasAndContext:l}=zi.getCanvasAndContext({text:this.text,style:this._style,resolution:1});zi.returnCanvasAndContext(l),r=a.width,n=a.height}else{const a=xt.measureText(this._text,this._style);r=a.width,n=a.height}t.minX=-e._x*r,t.maxX=t.minX+r,t.minY=-e._y*n,t.maxY=t.minY+n}}class _y extends Rl{constructor(...t){var e;const r=Il(t,"BitmapText");r.style??(r.style=r.style||{}),(e=r.style).fill??(e.fill=16777215),super(r,Bt),this.renderPipeId="bitmapText"}updateBounds(){const t=this._bounds,e=this._anchor,r=Gi.measureText(this.text,this._style),n=r.scale,a=r.offsetY*n;let l=r.width*n,h=r.height*n;const d=this._style._stroke;d&&(l+=d.width,h+=d.width),t.minX=-e._x*l,t.maxX=t.minX+l,t.minY=-e._y*(h+a),t.maxY=t.minY+h}set resolution(t){t!==null&&F("[BitmapText] dynamically updating the resolution is not supported. Resolution should be managed by the BitmapFont.")}get resolution(){return this._resolution}}const Ol="http://www.w3.org/2000/svg",Ll="http://www.w3.org/1999/xhtml";class zl{constructor(){this.svgRoot=document.createElementNS(Ol,"svg"),this.foreignObject=document.createElementNS(Ol,"foreignObject"),this.domElement=document.createElementNS(Ll,"div"),this.styleElement=document.createElementNS(Ll,"style");const{foreignObject:t,svgRoot:e,styleElement:r,domElement:n}=this;t.setAttribute("width","10000"),t.setAttribute("height","10000"),t.style.overflow="hidden",e.appendChild(t),t.appendChild(r),t.appendChild(n),this.image=W.get().createImage()}destroy(){this.svgRoot.remove(),this.foreignObject.remove(),this.styleElement.remove(),this.domElement.remove(),this.image.src="",this.image.remove(),this.svgRoot=null,this.foreignObject=null,this.styleElement=null,this.domElement=null,this.image=null,this.canvasAndContext=null}}let Nl;function yy(s,t,e,r){r||(r=Nl||(Nl=new zl));const{domElement:n,styleElement:a,svgRoot:l}=r;n.innerHTML=`<style>${t.cssStyle};</style><div style='padding:0'>${s}</div>`,n.setAttribute("style","transform-origin: top left; display: inline-block"),e&&(a.textContent=e),document.body.appendChild(l);const h=n.getBoundingClientRect();l.remove();const d=t.padding*2;return{width:h.width-d,height:h.height-d}}class Hl{constructor(){this._tempState=Ht.for2d(),this._didUploadHash={}}init(t){t.renderer.runners.contextChange.add(this)}contextChange(){this._didUploadHash={}}start(t,e,r){const n=t.renderer,a=this._didUploadHash[r.uid];n.shader.bind(r,a),a||(this._didUploadHash[r.uid]=!0),n.shader.updateUniformGroup(n.globalUniforms.uniformGroup),n.geometry.bind(e,r.glProgram)}execute(t,e){const r=t.renderer;this._tempState.blendMode=e.blendMode,r.state.set(this._tempState);const n=e.textures.textures;for(let a=0;a<e.textures.count;a++)r.texture.bind(n[a],a);r.geometry.draw(e.topology,e.size,e.start)}}Hl.extension={type:[C.WebGLPipesAdaptor],name:"batch"};const Or=Ht.for2d();class Wl{start(t,e,r){const n=t.renderer,a=n.encoder,l=r.gpuProgram;this._shader=r,this._geometry=e,a.setGeometry(e,l),Or.blendMode="normal",n.pipeline.getPipeline(e,l,Or);const h=n.globalUniforms.bindGroup;a.resetBindGroup(1),a.setBindGroup(0,h,l)}execute(t,e){const r=this._shader.gpuProgram,n=t.renderer,a=n.encoder;if(!e.bindGroup){const d=e.textures;e.bindGroup=nn(d.textures,d.count,n.limits.maxBatchableTextures)}Or.blendMode=e.blendMode;const l=n.bindGroup.getBindGroup(e.bindGroup,r,1),h=n.pipeline.getPipeline(this._geometry,r,Or,e.topology);e.bindGroup._touch(n.textureGC.count),a.setPipeline(h),a.renderPassEncoder.setBindGroup(1,l),a.renderPassEncoder.drawIndexed(e.size,1,e.start)}}Wl.extension={type:[C.WebGPUPipesAdaptor],name:"batch"};const Fn=class id{constructor(t,e){this.state=Ht.for2d(),this._batchersByInstructionSet=Object.create(null),this._activeBatches=Object.create(null),this.renderer=t,this._adaptor=e,this._adaptor.init?.(this)}static getBatcher(t){return new this._availableBatchers[t]}buildStart(t){let e=this._batchersByInstructionSet[t.uid];e||(e=this._batchersByInstructionSet[t.uid]=Object.create(null),e.default||(e.default=new mn({maxTextures:this.renderer.limits.maxBatchableTextures}))),this._activeBatches=e,this._activeBatch=this._activeBatches.default;for(const r in this._activeBatches)this._activeBatches[r].begin()}addToBatch(t,e){if(this._activeBatch.name!==t.batcherName){this._activeBatch.break(e);let r=this._activeBatches[t.batcherName];r||(r=this._activeBatches[t.batcherName]=id.getBatcher(t.batcherName),r.begin()),this._activeBatch=r}this._activeBatch.add(t)}break(t){this._activeBatch.break(t)}buildEnd(t){this._activeBatch.break(t);const e=this._activeBatches;for(const r in e){const n=e[r],a=n.geometry;a.indexBuffer.setDataWithSize(n.indexBuffer,n.indexSize,!0),a.buffers[0].setDataWithSize(n.attributeBuffer.float32View,n.attributeSize,!1)}}upload(t){const e=this._batchersByInstructionSet[t.uid];for(const r in e){const n=e[r],a=n.geometry;n.dirty&&(n.dirty=!1,a.buffers[0].update(n.attributeSize*4))}}execute(t){if(t.action==="startBatch"){const e=t.batcher,r=e.geometry,n=e.shader;this._adaptor.start(this,r,n)}this._adaptor.execute(this,t)}destroy(){this.state=null,this.renderer=null,this._adaptor=null;for(const t in this._activeBatches)this._activeBatches[t].destroy();this._activeBatches=null}};Fn.extension={type:[C.WebGLPipes,C.WebGPUPipes,C.CanvasPipes],name:"batch"},Fn._availableBatchers=Object.create(null);let Vl=Fn;D.handleByMap(C.Batcher,Vl._availableBatchers),D.add(mn);const Ni={name:"local-uniform-bit",vertex:{header:`
|
|
622
|
+
`;class vy extends hh{constructor(t){const{sprite:e,...r}=t,n=new sa(e.texture),o=new _t({uFilterMatrix:{value:new M,type:"mat3x3<f32>"},uMaskClamp:{value:n.uClampFrame,type:"vec4<f32>"},uAlpha:{value:1,type:"f32"},uInverse:{value:t.inverse?1:0,type:"f32"}}),l=pe.from({vertex:{source:Fl,entryPoint:"mainVertex"},fragment:{source:Fl,entryPoint:"mainFragment"}}),h=Te.from({vertex:by,fragment:xy,name:"mask-filter"});super({...r,gpuProgram:l,glProgram:h,clipToViewport:!1,resources:{filterUniforms:o,uMaskTexture:e.texture.source}}),this.sprite=e,this._textureMatrix=n}set inverse(t){this.resources.filterUniforms.uniforms.uInverse=t?1:0}get inverse(){return this.resources.filterUniforms.uniforms.uInverse===1}apply(t,e,r,n){this._textureMatrix.texture=this.sprite.texture,t.calculateSpriteMatrix(this.resources.filterUniforms.uniforms.uFilterMatrix,this.sprite).prepend(this._textureMatrix.mapCoord),this.resources.uMaskTexture=this.sprite.texture.source,t.applyFilter(this,e,r,n)}}class Zt extends Is{constructor(t){t instanceof Dt&&(t={context:t});const{context:e,roundPixels:r,...n}=t||{};super({label:"Graphics",...n}),this.renderPipeId="graphics",e?this._context=e:this._context=this._ownedContext=new Dt,this._context.on("update",this.onViewUpdate,this),this.didViewUpdate=!0,this.allowChildren=!1,this.roundPixels=r??!1}set context(t){t!==this._context&&(this._context.off("update",this.onViewUpdate,this),this._context=t,this._context.on("update",this.onViewUpdate,this),this.onViewUpdate())}get context(){return this._context}get bounds(){return this._context.bounds}updateBounds(){}containsPoint(t){return this._context.containsPoint(t)}destroy(t){this._ownedContext&&!t?this._ownedContext.destroy(t):(t===!0||t?.context===!0)&&this._context.destroy(t),this._ownedContext=null,this._context=null,super.destroy(t)}_callContextMethod(t,e){return this.context[t](...e),this}setFillStyle(...t){return this._callContextMethod("setFillStyle",t)}setStrokeStyle(...t){return this._callContextMethod("setStrokeStyle",t)}fill(...t){return this._callContextMethod("fill",t)}stroke(...t){return this._callContextMethod("stroke",t)}texture(...t){return this._callContextMethod("texture",t)}beginPath(){return this._callContextMethod("beginPath",[])}cut(){return this._callContextMethod("cut",[])}arc(...t){return this._callContextMethod("arc",t)}arcTo(...t){return this._callContextMethod("arcTo",t)}arcToSvg(...t){return this._callContextMethod("arcToSvg",t)}bezierCurveTo(...t){return this._callContextMethod("bezierCurveTo",t)}closePath(){return this._callContextMethod("closePath",[])}ellipse(...t){return this._callContextMethod("ellipse",t)}circle(...t){return this._callContextMethod("circle",t)}path(...t){return this._callContextMethod("path",t)}lineTo(...t){return this._callContextMethod("lineTo",t)}moveTo(...t){return this._callContextMethod("moveTo",t)}quadraticCurveTo(...t){return this._callContextMethod("quadraticCurveTo",t)}rect(...t){return this._callContextMethod("rect",t)}roundRect(...t){return this._callContextMethod("roundRect",t)}poly(...t){return this._callContextMethod("poly",t)}regularPoly(...t){return this._callContextMethod("regularPoly",t)}roundPoly(...t){return this._callContextMethod("roundPoly",t)}roundShape(...t){return this._callContextMethod("roundShape",t)}filletRect(...t){return this._callContextMethod("filletRect",t)}chamferRect(...t){return this._callContextMethod("chamferRect",t)}star(...t){return this._callContextMethod("star",t)}svg(...t){return this._callContextMethod("svg",t)}restore(...t){return this._callContextMethod("restore",t)}save(){return this._callContextMethod("save",[])}getTransform(){return this.context.getTransform()}resetTransform(){return this._callContextMethod("resetTransform",[])}rotateTransform(...t){return this._callContextMethod("rotate",t)}scaleTransform(...t){return this._callContextMethod("scale",t)}setTransform(...t){return this._callContextMethod("setTransform",t)}transform(...t){return this._callContextMethod("transform",t)}translateTransform(...t){return this._callContextMethod("translate",t)}clear(){return this._callContextMethod("clear",[])}get fillStyle(){return this._context.fillStyle}set fillStyle(t){this._context.fillStyle=t}get strokeStyle(){return this._context.strokeStyle}set strokeStyle(t){this._context.strokeStyle=t}clone(t=!1){return t?new Zt(this._context.clone()):(this._ownedContext=null,new Zt(this._context))}lineStyle(t,e,r){z($,"Graphics#lineStyle is no longer needed. Use Graphics#setStrokeStyle to set the stroke style.");const n={};return t&&(n.width=t),e&&(n.color=e),r&&(n.alpha=r),this.context.strokeStyle=n,this}beginFill(t,e){z($,"Graphics#beginFill is no longer needed. Use Graphics#fill to fill the shape with the desired style.");const r={};return t!==void 0&&(r.color=t),e!==void 0&&(r.alpha=e),this.context.fillStyle=r,this}endFill(){z($,"Graphics#endFill is no longer needed. Use Graphics#fill to fill the shape with the desired style."),this.context.fill();const t=this.context.strokeStyle;return(t.width!==Dt.defaultStrokeStyle.width||t.color!==Dt.defaultStrokeStyle.color||t.alpha!==Dt.defaultStrokeStyle.alpha)&&this.context.stroke(),this}drawCircle(...t){return z($,"Graphics#drawCircle has been renamed to Graphics#circle"),this._callContextMethod("circle",t)}drawEllipse(...t){return z($,"Graphics#drawEllipse has been renamed to Graphics#ellipse"),this._callContextMethod("ellipse",t)}drawPolygon(...t){return z($,"Graphics#drawPolygon has been renamed to Graphics#poly"),this._callContextMethod("poly",t)}drawRect(...t){return z($,"Graphics#drawRect has been renamed to Graphics#rect"),this._callContextMethod("rect",t)}drawRoundedRect(...t){return z($,"Graphics#drawRoundedRect has been renamed to Graphics#roundRect"),this._callContextMethod("roundRect",t)}drawStar(...t){return z($,"Graphics#drawStar has been renamed to Graphics#star"),this._callContextMethod("star",t)}}const Dl=class nu extends Bi{constructor(...t){let e=t[0]??{};e instanceof Float32Array&&(z($,"use new MeshGeometry({ positions, uvs, indices }) instead"),e={positions:e,uvs:t[1],indices:t[2]}),e={...nu.defaultOptions,...e};const r=e.positions||new Float32Array([0,0,1,0,1,1,0,1]);let n=e.uvs;n||(e.positions?n=new Float32Array(r.length):n=new Float32Array([0,0,1,0,1,1,0,1]));const o=e.indices||new Uint32Array([0,1,2,0,2,3]),l=e.shrinkBuffersToFit,h=new Bt({data:r,label:"attribute-mesh-positions",shrinkToFit:l,usage:Y.VERTEX|Y.COPY_DST}),u=new Bt({data:n,label:"attribute-mesh-uvs",shrinkToFit:l,usage:Y.VERTEX|Y.COPY_DST}),f=new Bt({data:o,label:"index-mesh-buffer",shrinkToFit:l,usage:Y.INDEX|Y.COPY_DST});super({attributes:{aPosition:{buffer:h,format:"float32x2",stride:8,offset:0},aUV:{buffer:u,format:"float32x2",stride:8,offset:0}},indexBuffer:f,topology:e.topology}),this.batchMode="auto"}get positions(){return this.attributes.aPosition.buffer.data}set positions(t){this.attributes.aPosition.buffer.data=t}get uvs(){return this.attributes.aUV.buffer.data}set uvs(t){this.attributes.aUV.buffer.data=t}get indices(){return this.indexBuffer.data}set indices(t){this.indexBuffer.data=t}};Dl.defaultOptions={topology:"triangle-list",shrinkBuffersToFit:!1};let On=Dl;class Ol extends Is{constructor(t,e){const{text:r,resolution:n,style:o,anchor:l,width:h,height:u,roundPixels:f,...m}=t;super({...m}),this.batched=!0,this._resolution=null,this._autoResolution=!0,this._didTextUpdate=!0,this._styleClass=e,this.text=r??"",this.style=o,this.resolution=n??null,this.allowChildren=!1,this._anchor=new ct({_onUpdate:()=>{this.onViewUpdate()}}),l&&(this.anchor=l),this.roundPixels=f??!1,h!==void 0&&(this.width=h),u!==void 0&&(this.height=u)}get anchor(){return this._anchor}set anchor(t){typeof t=="number"?this._anchor.set(t):this._anchor.copyFrom(t)}set text(t){t=t.toString(),this._text!==t&&(this._text=t,this.onViewUpdate())}get text(){return this._text}set resolution(t){this._autoResolution=t===null,this._resolution=t,this.onViewUpdate()}get resolution(){return this._resolution}get style(){return this._style}set style(t){t||(t={}),this._style?.off("update",this.onViewUpdate,this),t instanceof this._styleClass?this._style=t:this._style=new this._styleClass(t),this._style.on("update",this.onViewUpdate,this),this.onViewUpdate()}get width(){return Math.abs(this.scale.x)*this.bounds.width}set width(t){this._setWidth(t,this.bounds.width)}get height(){return Math.abs(this.scale.y)*this.bounds.height}set height(t){this._setHeight(t,this.bounds.height)}getSize(t){return t||(t={}),t.width=Math.abs(this.scale.x)*this.bounds.width,t.height=Math.abs(this.scale.y)*this.bounds.height,t}setSize(t,e){typeof t=="object"?(e=t.height??t.width,t=t.width):e??(e=t),t!==void 0&&this._setWidth(t,this.bounds.width),e!==void 0&&this._setHeight(e,this.bounds.height)}containsPoint(t){const e=this.bounds.width,r=this.bounds.height,n=-e*this.anchor.x;let o=0;return t.x>=n&&t.x<=n+e&&(o=-r*this.anchor.y,t.y>=o&&t.y<=o+r)}onViewUpdate(){this.didViewUpdate||(this._didTextUpdate=!0),super.onViewUpdate()}destroy(t=!1){super.destroy(t),this.owner=null,this._bounds=null,this._anchor=null,(typeof t=="boolean"?t:t?.style)&&this._style.destroy(t),this._style=null,this._text=null}get styleKey(){return`${this._text}:${this._style.styleKey}:${this._resolution}`}}function Gl(s,t){let e=s[0]??{};return(typeof e=="string"||s[1])&&(z($,`use new ${t}({ text: "hi!", style }) instead`),e={text:e,style:s[1]}),e}let Pe=null,le=null;function wy(s,t){Pe||(Pe=W.get().createCanvas(256,128),le=Pe.getContext("2d",{willReadFrequently:!0}),le.globalCompositeOperation="copy",le.globalAlpha=1),(Pe.width<s||Pe.height<t)&&(Pe.width=ze(s),Pe.height=ze(t))}function Ll(s,t,e){for(let r=0,n=4*e*t;r<t;++r,n+=4)if(s[n+3]!==0)return!1;return!0}function zl(s,t,e,r,n){const o=4*t;for(let l=r,h=r*o+4*e;l<=n;++l,h+=o)if(s[h+3]!==0)return!1;return!0}function Sy(...s){let t=s[0];t.canvas||(t={canvas:s[0],resolution:s[1]});const{canvas:e}=t,r=Math.min(t.resolution??1,1),n=t.width??e.width,o=t.height??e.height;let l=t.output;if(wy(n,o),!le)throw new TypeError("Failed to get canvas 2D context");le.drawImage(e,0,0,n,o,0,0,n*r,o*r);const u=le.getImageData(0,0,n,o).data;let f=0,m=0,g=n-1,y=o-1;for(;m<o&&Ll(u,n,m);)++m;if(m===o)return G.EMPTY;for(;Ll(u,n,y);)--y;for(;zl(u,n,f,m,y);)++f;for(;zl(u,n,g,m,y);)--g;return++g,++y,le.globalCompositeOperation="source-over",le.strokeRect(f,m,g-f,y-m),le.globalCompositeOperation="copy",l??(l=new G),l.set(f/r,m/r,(g-f)/r,(y-m)/r),l}const Nl=new G;class Ty{getCanvasAndContext(t){const{text:e,style:r,resolution:n=1}=t,o=r._getFinalPadding(),l=xt.measureText(e||" ",r),h=Math.ceil(Math.ceil(Math.max(1,l.width)+o*2)*n),u=Math.ceil(Math.ceil(Math.max(1,l.height)+o*2)*n),f=ae.getOptimalCanvasAndContext(h,u);this._renderTextToCanvas(e,r,o,n,f);const m=r.trim?Sy({canvas:f.canvas,width:h,height:u,resolution:1,output:Nl}):Nl.set(0,0,h,u);return{canvasAndContext:f,frame:m}}returnCanvasAndContext(t){ae.returnCanvasAndContext(t)}_renderTextToCanvas(t,e,r,n,o){const{canvas:l,context:h}=o,u=Pr(e),f=xt.measureText(t||" ",e),m=f.lines,g=f.lineHeight,y=f.lineWidths,x=f.maxLineWidth,a=f.fontProperties,c=l.height;if(h.resetTransform(),h.scale(n,n),h.textBaseline=e.textBaseline,e._stroke?.width){const b=e._stroke;h.lineWidth=b.width,h.miterLimit=b.miterLimit,h.lineJoin=b.join,h.lineCap=b.cap}h.font=u;let d,p;const _=e.dropShadow?2:1;for(let b=0;b<_;++b){const v=e.dropShadow&&b===0,w=v?Math.ceil(Math.max(1,c)+r*2):0,S=w*n;if(v){h.fillStyle="black",h.strokeStyle="black";const P=e.dropShadow,B=P.color,A=P.alpha;h.shadowColor=J.shared.setValue(B).setAlpha(A).toRgbaString();const O=P.blur*n,L=P.distance*n;h.shadowBlur=O,h.shadowOffsetX=Math.cos(P.angle)*L,h.shadowOffsetY=Math.sin(P.angle)*L+S}else{if(h.fillStyle=e._fill?Dr(e._fill,h,f,r*2):null,e._stroke?.width){const P=e._stroke.width*.5+r*2;h.strokeStyle=Dr(e._stroke,h,f,P)}h.shadowColor="black"}let T=(g-a.fontSize)/2;g-a.fontSize<0&&(T=0);const E=e._stroke?.width??0;for(let P=0;P<m.length;P++)d=E/2,p=E/2+P*g+a.ascent+T,e.align==="right"?d+=x-y[P]:e.align==="center"&&(d+=(x-y[P])/2),e._stroke?.width&&this._drawLetterSpacing(m[P],e,o,d+r,p+r-w,!0),e._fill!==void 0&&this._drawLetterSpacing(m[P],e,o,d+r,p+r-w)}}_drawLetterSpacing(t,e,r,n,o,l=!1){const{context:h}=r,u=e.letterSpacing;let f=!1;if(xt.experimentalLetterSpacingSupported&&(xt.experimentalLetterSpacing?(h.letterSpacing=`${u}px`,h.textLetterSpacing=`${u}px`,f=!0):(h.letterSpacing="0px",h.textLetterSpacing="0px")),u===0||f){l?h.strokeText(t,n,o):h.fillText(t,n,o);return}let m=n;const g=xt.graphemeSegmenter(t);let y=h.measureText(t).width,x=0;for(let a=0;a<g.length;++a){const c=g[a];l?h.strokeText(c,m,o):h.fillText(c,m,o);let d="";for(let p=a+1;p<g.length;++p)d+=g[p];x=h.measureText(d).width,m+=y-x+u,y=x}}}const Ni=new Ty;class Cy extends Ol{constructor(...t){const e=Gl(t,"Text");super(e,bt),this.renderPipeId="text",e.textureStyle&&(this.textureStyle=e.textureStyle instanceof jt?e.textureStyle:new jt(e.textureStyle))}updateBounds(){const t=this._bounds,e=this._anchor;let r=0,n=0;if(this._style.trim){const{frame:o,canvasAndContext:l}=Ni.getCanvasAndContext({text:this.text,style:this._style,resolution:1});Ni.returnCanvasAndContext(l),r=o.width,n=o.height}else{const o=xt.measureText(this._text,this._style);r=o.width,n=o.height}t.minX=-e._x*r,t.maxX=t.minX+r,t.minY=-e._y*n,t.maxY=t.minY+n}}class Ey extends Ol{constructor(...t){var e;const r=Gl(t,"BitmapText");r.style??(r.style=r.style||{}),(e=r.style).fill??(e.fill=16777215),super(r,bt),this.renderPipeId="bitmapText"}updateBounds(){const t=this._bounds,e=this._anchor,r=Gi.measureText(this.text,this._style),n=r.scale,o=r.offsetY*n;let l=r.width*n,h=r.height*n;const u=this._style._stroke;u&&(l+=u.width,h+=u.width),t.minX=-e._x*l,t.maxX=t.minX+l,t.minY=-e._y*(h+o),t.maxY=t.minY+h}set resolution(t){t!==null&&F("[BitmapText] dynamically updating the resolution is not supported. Resolution should be managed by the BitmapFont.")}get resolution(){return this._resolution}}const Hl="http://www.w3.org/2000/svg",Wl="http://www.w3.org/1999/xhtml";class Vl{constructor(){this.svgRoot=document.createElementNS(Hl,"svg"),this.foreignObject=document.createElementNS(Hl,"foreignObject"),this.domElement=document.createElementNS(Wl,"div"),this.styleElement=document.createElementNS(Wl,"style");const{foreignObject:t,svgRoot:e,styleElement:r,domElement:n}=this;t.setAttribute("width","10000"),t.setAttribute("height","10000"),t.style.overflow="hidden",e.appendChild(t),t.appendChild(r),t.appendChild(n),this.image=W.get().createImage()}destroy(){this.svgRoot.remove(),this.foreignObject.remove(),this.styleElement.remove(),this.domElement.remove(),this.image.src="",this.image.remove(),this.svgRoot=null,this.foreignObject=null,this.styleElement=null,this.domElement=null,this.image=null,this.canvasAndContext=null}}let Yl;function Ay(s,t,e,r){r||(r=Yl||(Yl=new Vl));const{domElement:n,styleElement:o,svgRoot:l}=r;n.innerHTML=`<style>${t.cssStyle};</style><div style='padding:0'>${s}</div>`,n.setAttribute("style","transform-origin: top left; display: inline-block"),e&&(o.textContent=e),document.body.appendChild(l);const h=n.getBoundingClientRect();l.remove();const u=t.padding*2;return{width:h.width-u,height:h.height-u}}class Xl{constructor(){this._tempState=Ht.for2d(),this._didUploadHash={}}init(t){t.renderer.runners.contextChange.add(this)}contextChange(){this._didUploadHash={}}start(t,e,r){const n=t.renderer,o=this._didUploadHash[r.uid];n.shader.bind(r,o),o||(this._didUploadHash[r.uid]=!0),n.shader.updateUniformGroup(n.globalUniforms.uniformGroup),n.geometry.bind(e,r.glProgram)}execute(t,e){const r=t.renderer;this._tempState.blendMode=e.blendMode,r.state.set(this._tempState);const n=e.textures.textures;for(let o=0;o<e.textures.count;o++)r.texture.bind(n[o],o);r.geometry.draw(e.topology,e.size,e.start)}}Xl.extension={type:[C.WebGLPipesAdaptor],name:"batch"};const zr=Ht.for2d();class $l{start(t,e,r){const n=t.renderer,o=n.encoder,l=r.gpuProgram;this._shader=r,this._geometry=e,o.setGeometry(e,l),zr.blendMode="normal",n.pipeline.getPipeline(e,l,zr);const h=n.globalUniforms.bindGroup;o.resetBindGroup(1),o.setBindGroup(0,h,l)}execute(t,e){const r=this._shader.gpuProgram,n=t.renderer,o=n.encoder;if(!e.bindGroup){const u=e.textures;e.bindGroup=hn(u.textures,u.count,n.limits.maxBatchableTextures)}zr.blendMode=e.blendMode;const l=n.bindGroup.getBindGroup(e.bindGroup,r,1),h=n.pipeline.getPipeline(this._geometry,r,zr,e.topology);e.bindGroup._touch(n.textureGC.count),o.setPipeline(h),o.renderPassEncoder.setBindGroup(1,l),o.renderPassEncoder.drawIndexed(e.size,1,e.start)}}$l.extension={type:[C.WebGPUPipesAdaptor],name:"batch"};const Gn=class ou{constructor(t,e){this.state=Ht.for2d(),this._batchersByInstructionSet=Object.create(null),this._activeBatches=Object.create(null),this.renderer=t,this._adaptor=e,this._adaptor.init?.(this)}static getBatcher(t){return new this._availableBatchers[t]}buildStart(t){let e=this._batchersByInstructionSet[t.uid];e||(e=this._batchersByInstructionSet[t.uid]=Object.create(null),e.default||(e.default=new yn({maxTextures:this.renderer.limits.maxBatchableTextures}))),this._activeBatches=e,this._activeBatch=this._activeBatches.default;for(const r in this._activeBatches)this._activeBatches[r].begin()}addToBatch(t,e){if(this._activeBatch.name!==t.batcherName){this._activeBatch.break(e);let r=this._activeBatches[t.batcherName];r||(r=this._activeBatches[t.batcherName]=ou.getBatcher(t.batcherName),r.begin()),this._activeBatch=r}this._activeBatch.add(t)}break(t){this._activeBatch.break(t)}buildEnd(t){this._activeBatch.break(t);const e=this._activeBatches;for(const r in e){const n=e[r],o=n.geometry;o.indexBuffer.setDataWithSize(n.indexBuffer,n.indexSize,!0),o.buffers[0].setDataWithSize(n.attributeBuffer.float32View,n.attributeSize,!1)}}upload(t){const e=this._batchersByInstructionSet[t.uid];for(const r in e){const n=e[r],o=n.geometry;n.dirty&&(n.dirty=!1,o.buffers[0].update(n.attributeSize*4))}}execute(t){if(t.action==="startBatch"){const e=t.batcher,r=e.geometry,n=e.shader;this._adaptor.start(this,r,n)}this._adaptor.execute(this,t)}destroy(){this.state=null,this.renderer=null,this._adaptor=null;for(const t in this._activeBatches)this._activeBatches[t].destroy();this._activeBatches=null}};Gn.extension={type:[C.WebGLPipes,C.WebGPUPipes,C.CanvasPipes],name:"batch"},Gn._availableBatchers=Object.create(null);let Kl=Gn;D.handleByMap(C.Batcher,Kl._availableBatchers),D.add(yn);const Hi={name:"local-uniform-bit",vertex:{header:`
|
|
623
623
|
|
|
624
624
|
struct LocalUniforms {
|
|
625
625
|
uTransformMatrix:mat3x3<f32>,
|
|
@@ -636,7 +636,7 @@ fn mainFragment(
|
|
|
636
636
|
{
|
|
637
637
|
vPosition = vec4(roundPixels(vPosition.xy, globalUniforms.uResolution), vPosition.zw);
|
|
638
638
|
}
|
|
639
|
-
`}},
|
|
639
|
+
`}},Py={...Hi,vertex:{...Hi.vertex,header:Hi.vertex.header.replace("group(1)","group(2)")}},Ln={name:"local-uniform-bit",vertex:{header:`
|
|
640
640
|
|
|
641
641
|
uniform mat3 uTransformMatrix;
|
|
642
642
|
uniform vec4 uColor;
|
|
@@ -649,7 +649,7 @@ fn mainFragment(
|
|
|
649
649
|
{
|
|
650
650
|
gl_Position.xy = roundPixels(gl_Position.xy, uResolution);
|
|
651
651
|
}
|
|
652
|
-
`}},
|
|
652
|
+
`}},By={name:"texture-bit",vertex:{header:`
|
|
653
653
|
|
|
654
654
|
struct TextureUniforms {
|
|
655
655
|
uTextureMatrix:mat3x3<f32>,
|
|
@@ -665,7 +665,7 @@ fn mainFragment(
|
|
|
665
665
|
|
|
666
666
|
`,main:`
|
|
667
667
|
outColor = textureSample(uTexture, uSampler, vUV);
|
|
668
|
-
`}},
|
|
668
|
+
`}},Uy={name:"texture-bit",vertex:{header:`
|
|
669
669
|
uniform mat3 uTextureMatrix;
|
|
670
670
|
`,main:`
|
|
671
671
|
uv = (uTextureMatrix * vec3(uv, 1.0)).xy;
|
|
@@ -675,7 +675,7 @@ fn mainFragment(
|
|
|
675
675
|
|
|
676
676
|
`,main:`
|
|
677
677
|
outColor = texture(uTexture, vUV);
|
|
678
|
-
`}},wy=new dt;class Sy extends lr{constructor(){super(),this.filters=[new dy({sprite:new te(M.EMPTY),inverse:!1,resolution:"inherit",antialias:"inherit"})]}get sprite(){return this.filters[0].sprite}set sprite(t){this.filters[0].sprite=t}get inverse(){return this.filters[0].inverse}set inverse(t){this.filters[0].inverse=t}}class Yl{constructor(t){this._activeMaskStage=[],this._renderer=t}push(t,e,r){const n=this._renderer;if(n.renderPipes.batch.break(r),r.add({renderPipeId:"alphaMask",action:"pushMaskBegin",mask:t,inverse:e._maskOptions.inverse,canBundle:!1,maskedContainer:e}),t.inverse=e._maskOptions.inverse,t.renderMaskToTexture){const a=t.mask;a.includeInBuild=!0,a.collectRenderables(r,n,null),a.includeInBuild=!1}n.renderPipes.batch.break(r),r.add({renderPipeId:"alphaMask",action:"pushMaskEnd",mask:t,maskedContainer:e,inverse:e._maskOptions.inverse,canBundle:!1})}pop(t,e,r){this._renderer.renderPipes.batch.break(r),r.add({renderPipeId:"alphaMask",action:"popMaskEnd",mask:t,inverse:e._maskOptions.inverse,canBundle:!1})}execute(t){const e=this._renderer,r=t.mask.renderMaskToTexture;if(t.action==="pushMaskBegin"){const n=at.get(Sy);if(n.inverse=t.inverse,r){t.mask.mask.measurable=!0;const a=Ts(t.mask.mask,!0,wy);t.mask.mask.measurable=!1,a.ceil();const l=e.renderTarget.renderTarget.colorTexture.source,h=ut.getOptimalTexture(a.width,a.height,l._resolution,l.antialias);e.renderTarget.push(h,!0),e.globalUniforms.push({offset:a,worldColor:4294967295});const d=n.sprite;d.texture=h,d.worldTransform.tx=a.minX,d.worldTransform.ty=a.minY,this._activeMaskStage.push({filterEffect:n,maskedContainer:t.maskedContainer,filterTexture:h})}else n.sprite=t.mask.mask,this._activeMaskStage.push({filterEffect:n,maskedContainer:t.maskedContainer})}else if(t.action==="pushMaskEnd"){const n=this._activeMaskStage[this._activeMaskStage.length-1];r&&(e.type===Nt.WEBGL&&e.renderTarget.finishRenderPass(),e.renderTarget.pop(),e.globalUniforms.pop()),e.filter.push({renderPipeId:"filter",action:"pushFilter",container:n.maskedContainer,filterEffect:n.filterEffect,canBundle:!1})}else if(t.action==="popMaskEnd"){e.filter.pop();const n=this._activeMaskStage.pop();r&&ut.returnTexture(n.filterTexture),at.return(n.filterEffect)}}destroy(){this._renderer=null,this._activeMaskStage=null}}Yl.extension={type:[C.WebGLPipes,C.WebGPUPipes,C.CanvasPipes],name:"alphaMask"};class Xl{constructor(t){this._colorStack=[],this._colorStackIndex=0,this._currentColor=0,this._renderer=t}buildStart(){this._colorStack[0]=15,this._colorStackIndex=1,this._currentColor=15}push(t,e,r){this._renderer.renderPipes.batch.break(r);const a=this._colorStack;a[this._colorStackIndex]=a[this._colorStackIndex-1]&t.mask;const l=this._colorStack[this._colorStackIndex];l!==this._currentColor&&(this._currentColor=l,r.add({renderPipeId:"colorMask",colorMask:l,canBundle:!1})),this._colorStackIndex++}pop(t,e,r){this._renderer.renderPipes.batch.break(r);const a=this._colorStack;this._colorStackIndex--;const l=a[this._colorStackIndex-1];l!==this._currentColor&&(this._currentColor=l,r.add({renderPipeId:"colorMask",colorMask:l,canBundle:!1}))}execute(t){this._renderer.colorMask.setMask(t.colorMask)}destroy(){this._renderer=null,this._colorStack=null}}Xl.extension={type:[C.WebGLPipes,C.WebGPUPipes,C.CanvasPipes],name:"colorMask"};class $l{constructor(t){this._maskStackHash={},this._maskHash=new WeakMap,this._renderer=t}push(t,e,r){var n;const a=t,l=this._renderer;l.renderPipes.batch.break(r),l.renderPipes.blendMode.setBlendMode(a.mask,"none",r),r.add({renderPipeId:"stencilMask",action:"pushMaskBegin",mask:t,inverse:e._maskOptions.inverse,canBundle:!1});const h=a.mask;h.includeInBuild=!0,this._maskHash.has(a)||this._maskHash.set(a,{instructionsStart:0,instructionsLength:0});const d=this._maskHash.get(a);d.instructionsStart=r.instructionSize,h.collectRenderables(r,l,null),h.includeInBuild=!1,l.renderPipes.batch.break(r),r.add({renderPipeId:"stencilMask",action:"pushMaskEnd",mask:t,inverse:e._maskOptions.inverse,canBundle:!1});const f=r.instructionSize-d.instructionsStart-1;d.instructionsLength=f;const m=l.renderTarget.renderTarget.uid;(n=this._maskStackHash)[m]??(n[m]=0)}pop(t,e,r){const n=t,a=this._renderer;a.renderPipes.batch.break(r),a.renderPipes.blendMode.setBlendMode(n.mask,"none",r),r.add({renderPipeId:"stencilMask",action:"popMaskBegin",inverse:e._maskOptions.inverse,canBundle:!1});const l=this._maskHash.get(t);for(let h=0;h<l.instructionsLength;h++)r.instructions[r.instructionSize++]=r.instructions[l.instructionsStart++];r.add({renderPipeId:"stencilMask",action:"popMaskEnd",canBundle:!1})}execute(t){var e;const r=this._renderer,n=r.renderTarget.renderTarget.uid;let a=(e=this._maskStackHash)[n]??(e[n]=0);t.action==="pushMaskBegin"?(r.renderTarget.ensureDepthStencil(),r.stencil.setStencilMode(nt.RENDERING_MASK_ADD,a),a++,r.colorMask.setMask(0)):t.action==="pushMaskEnd"?(t.inverse?r.stencil.setStencilMode(nt.INVERSE_MASK_ACTIVE,a):r.stencil.setStencilMode(nt.MASK_ACTIVE,a),r.colorMask.setMask(15)):t.action==="popMaskBegin"?(r.colorMask.setMask(0),a!==0?r.stencil.setStencilMode(nt.RENDERING_MASK_REMOVE,a):(r.renderTarget.clear(null,At.STENCIL),r.stencil.setStencilMode(nt.DISABLED,a)),a--):t.action==="popMaskEnd"&&(t.inverse?r.stencil.setStencilMode(nt.INVERSE_MASK_ACTIVE,a):r.stencil.setStencilMode(nt.MASK_ACTIVE,a),r.colorMask.setMask(15)),this._maskStackHash[n]=a}destroy(){this._renderer=null,this._maskStackHash=null,this._maskHash=null}}$l.extension={type:[C.WebGLPipes,C.WebGPUPipes,C.CanvasPipes],name:"stencilMask"};var Lr=(s=>(s[s.ELEMENT_ARRAY_BUFFER=34963]="ELEMENT_ARRAY_BUFFER",s[s.ARRAY_BUFFER=34962]="ARRAY_BUFFER",s[s.UNIFORM_BUFFER=35345]="UNIFORM_BUFFER",s))(Lr||{});class Ty{constructor(t,e){this._lastBindBaseLocation=-1,this._lastBindCallId=-1,this.buffer=t||null,this.updateID=-1,this.byteLength=-1,this.type=e}}class Kl{constructor(t){this._gpuBuffers=Object.create(null),this._boundBufferBases=Object.create(null),this._minBaseLocation=0,this._nextBindBaseIndex=this._minBaseLocation,this._bindCallId=0,this._renderer=t,this._renderer.renderableGC.addManagedHash(this,"_gpuBuffers")}destroy(){this.destroyAll(),this._renderer=null,this._gl=null,this._gpuBuffers={},this._boundBufferBases={}}contextChange(){this._gl=this._renderer.gl,this._gpuBuffers=Object.create(null),this._maxBindings=this._renderer.limits.maxUniformBindings}getGlBuffer(t){return this._gpuBuffers[t.uid]||this.createGLBuffer(t)}bind(t){const{_gl:e}=this,r=this.getGlBuffer(t);e.bindBuffer(r.type,r.buffer)}bindBufferBase(t,e){const{_gl:r}=this;this._boundBufferBases[e]!==t&&(this._boundBufferBases[e]=t,t._lastBindBaseLocation=e,r.bindBufferBase(r.UNIFORM_BUFFER,e,t.buffer))}nextBindBase(t){this._bindCallId++,this._minBaseLocation=0,t&&(this._boundBufferBases[0]=null,this._minBaseLocation=1,this._nextBindBaseIndex<1&&(this._nextBindBaseIndex=1))}freeLocationForBufferBase(t){let e=this.getLastBindBaseLocation(t);if(e>=this._minBaseLocation)return t._lastBindCallId=this._bindCallId,e;let r=0,n=this._nextBindBaseIndex;for(;r<2;){n>=this._maxBindings&&(n=this._minBaseLocation,r++);const a=this._boundBufferBases[n];if(a&&a._lastBindCallId===this._bindCallId){n++;continue}break}return e=n,this._nextBindBaseIndex=n+1,r>=2?-1:(t._lastBindCallId=this._bindCallId,this._boundBufferBases[e]=null,e)}getLastBindBaseLocation(t){const e=t._lastBindBaseLocation;return this._boundBufferBases[e]===t?e:-1}bindBufferRange(t,e,r,n){const{_gl:a}=this;r||(r=0),e||(e=0),this._boundBufferBases[e]=null,a.bindBufferRange(a.UNIFORM_BUFFER,e||0,t.buffer,r*256,n||256)}updateBuffer(t){const{_gl:e}=this,r=this.getGlBuffer(t);if(t._updateID===r.updateID)return r;r.updateID=t._updateID,e.bindBuffer(r.type,r.buffer);const n=t.data,a=t.descriptor.usage&Y.STATIC?e.STATIC_DRAW:e.DYNAMIC_DRAW;return n?r.byteLength>=n.byteLength?e.bufferSubData(r.type,0,n,0,t._updateSize/n.BYTES_PER_ELEMENT):(r.byteLength=n.byteLength,e.bufferData(r.type,n,a)):(r.byteLength=t.descriptor.size,e.bufferData(r.type,r.byteLength,a)),r}destroyAll(){const t=this._gl;for(const e in this._gpuBuffers)this._gpuBuffers[e]&&t.deleteBuffer(this._gpuBuffers[e].buffer);this._gpuBuffers=Object.create(null)}onBufferDestroy(t,e){if(!this._gpuBuffers[t.uid])return;const r=this._gpuBuffers[t.uid],n=this._gl;e||n.deleteBuffer(r.buffer),t.off("destroy",this.onBufferDestroy,this),this._gpuBuffers[t.uid]=null}createGLBuffer(t){const{_gl:e}=this;let r=Lr.ARRAY_BUFFER;t.descriptor.usage&Y.INDEX?r=Lr.ELEMENT_ARRAY_BUFFER:t.descriptor.usage&Y.UNIFORM&&(r=Lr.UNIFORM_BUFFER);const n=new Ty(e.createBuffer(),r);return this._gpuBuffers[t.uid]=n,t.on("destroy",this.onBufferDestroy,this),n}resetState(){this._boundBufferBases=Object.create(null)}}Kl.extension={type:[C.WebGLSystem],name:"buffer"};const Gn=class rd{constructor(t){this.supports={uint32Indices:!0,uniformBufferObject:!0,vertexArrayObject:!0,srgbTextures:!0,nonPowOf2wrapping:!0,msaa:!0,nonPowOf2mipmaps:!0},this._renderer=t,this.extensions=Object.create(null),this.handleContextLost=this.handleContextLost.bind(this),this.handleContextRestored=this.handleContextRestored.bind(this)}get isLost(){return!this.gl||this.gl.isContextLost()}contextChange(t){this.gl=t,this._renderer.gl=t}init(t){t={...rd.defaultOptions,...t};let e=this.multiView=t.multiView;if(t.context&&e&&(F("Renderer created with both a context and multiview enabled. Disabling multiView as both cannot work together."),e=!1),e?this.canvas=W.get().createCanvas(this._renderer.canvas.width,this._renderer.canvas.height):this.canvas=this._renderer.view.canvas,t.context)this.initFromContext(t.context);else{const r=this._renderer.background.alpha<1,n=t.premultipliedAlpha??!0,a=t.antialias&&!this._renderer.backBuffer.useBackBuffer;this.createContext(t.preferWebGLVersion,{alpha:r,premultipliedAlpha:n,antialias:a,stencil:!0,preserveDrawingBuffer:t.preserveDrawingBuffer,powerPreference:t.powerPreference??"default"})}}ensureCanvasSize(t){if(!this.multiView){t!==this.canvas&&F("multiView is disabled, but targetCanvas is not the main canvas");return}const{canvas:e}=this;(e.width<t.width||e.height<t.height)&&(e.width=Math.max(t.width,t.width),e.height=Math.max(t.height,t.height))}initFromContext(t){this.gl=t,this.webGLVersion=t instanceof W.get().getWebGLRenderingContext()?1:2,this.getExtensions(),this.validateContext(t),this._renderer.runners.contextChange.emit(t);const e=this._renderer.view.canvas;e.addEventListener("webglcontextlost",this.handleContextLost,!1),e.addEventListener("webglcontextrestored",this.handleContextRestored,!1)}createContext(t,e){let r;const n=this.canvas;if(t===2&&(r=n.getContext("webgl2",e)),!r&&(r=n.getContext("webgl",e),!r))throw new Error("This browser does not support WebGL. Try using the canvas renderer");this.gl=r,this.initFromContext(this.gl)}getExtensions(){const{gl:t}=this,e={anisotropicFiltering:t.getExtension("EXT_texture_filter_anisotropic"),floatTextureLinear:t.getExtension("OES_texture_float_linear"),s3tc:t.getExtension("WEBGL_compressed_texture_s3tc"),s3tc_sRGB:t.getExtension("WEBGL_compressed_texture_s3tc_srgb"),etc:t.getExtension("WEBGL_compressed_texture_etc"),etc1:t.getExtension("WEBGL_compressed_texture_etc1"),pvrtc:t.getExtension("WEBGL_compressed_texture_pvrtc")||t.getExtension("WEBKIT_WEBGL_compressed_texture_pvrtc"),atc:t.getExtension("WEBGL_compressed_texture_atc"),astc:t.getExtension("WEBGL_compressed_texture_astc"),bptc:t.getExtension("EXT_texture_compression_bptc"),rgtc:t.getExtension("EXT_texture_compression_rgtc"),loseContext:t.getExtension("WEBGL_lose_context")};if(this.webGLVersion===1)this.extensions={...e,drawBuffers:t.getExtension("WEBGL_draw_buffers"),depthTexture:t.getExtension("WEBGL_depth_texture"),vertexArrayObject:t.getExtension("OES_vertex_array_object")||t.getExtension("MOZ_OES_vertex_array_object")||t.getExtension("WEBKIT_OES_vertex_array_object"),uint32ElementIndex:t.getExtension("OES_element_index_uint"),floatTexture:t.getExtension("OES_texture_float"),floatTextureLinear:t.getExtension("OES_texture_float_linear"),textureHalfFloat:t.getExtension("OES_texture_half_float"),textureHalfFloatLinear:t.getExtension("OES_texture_half_float_linear"),vertexAttribDivisorANGLE:t.getExtension("ANGLE_instanced_arrays"),srgb:t.getExtension("EXT_sRGB")};else{this.extensions={...e,colorBufferFloat:t.getExtension("EXT_color_buffer_float")};const r=t.getExtension("WEBGL_provoking_vertex");r&&r.provokingVertexWEBGL(r.FIRST_VERTEX_CONVENTION_WEBGL)}}handleContextLost(t){t.preventDefault(),this._contextLossForced&&(this._contextLossForced=!1,setTimeout(()=>{this.gl.isContextLost()&&this.extensions.loseContext?.restoreContext()},0))}handleContextRestored(){this.getExtensions(),this._renderer.runners.contextChange.emit(this.gl)}destroy(){const t=this._renderer.view.canvas;this._renderer=null,t.removeEventListener("webglcontextlost",this.handleContextLost),t.removeEventListener("webglcontextrestored",this.handleContextRestored),this.gl.useProgram(null),this.extensions.loseContext?.loseContext()}forceContextLoss(){this.extensions.loseContext?.loseContext(),this._contextLossForced=!0}validateContext(t){const e=t.getContextAttributes();e&&!e.stencil&&F("Provided WebGL context does not have a stencil buffer, masks may not render correctly");const r=this.supports,n=this.webGLVersion===2,a=this.extensions;r.uint32Indices=n||!!a.uint32ElementIndex,r.uniformBufferObject=n,r.vertexArrayObject=n||!!a.vertexArrayObject,r.srgbTextures=n||!!a.srgb,r.nonPowOf2wrapping=n,r.nonPowOf2mipmaps=n,r.msaa=n,r.uint32Indices||F("Provided WebGL context does not support 32 index buffer, large scenes may not render correctly")}};Gn.extension={type:[C.WebGLSystem],name:"context"},Gn.defaultOptions={context:null,premultipliedAlpha:!0,preserveDrawingBuffer:!1,powerPreference:void 0,preferWebGLVersion:2,multiView:!1};let Cy=Gn;function jl(s,t){for(const e in s.attributes){const r=s.attributes[e],n=t[e];n?(r.format??(r.format=n.format),r.offset??(r.offset=n.offset),r.instance??(r.instance=n.instance)):F(`Attribute ${e} is not present in the shader, but is present in the geometry. Unable to infer attribute details.`)}Ey(s)}function Ey(s){const{buffers:t,attributes:e}=s,r={},n={};for(const a in t){const l=t[a];r[l.uid]=0,n[l.uid]=0}for(const a in e){const l=e[a];r[l.buffer.uid]+=ue(l.format).stride}for(const a in e){const l=e[a];l.stride??(l.stride=r[l.buffer.uid]),l.start??(l.start=n[l.buffer.uid]),n[l.buffer.uid]+=ue(l.format).stride}}var On=(s=>(s[s.RGBA=6408]="RGBA",s[s.RGB=6407]="RGB",s[s.RG=33319]="RG",s[s.RED=6403]="RED",s[s.RGBA_INTEGER=36249]="RGBA_INTEGER",s[s.RGB_INTEGER=36248]="RGB_INTEGER",s[s.RG_INTEGER=33320]="RG_INTEGER",s[s.RED_INTEGER=36244]="RED_INTEGER",s[s.ALPHA=6406]="ALPHA",s[s.LUMINANCE=6409]="LUMINANCE",s[s.LUMINANCE_ALPHA=6410]="LUMINANCE_ALPHA",s[s.DEPTH_COMPONENT=6402]="DEPTH_COMPONENT",s[s.DEPTH_STENCIL=34041]="DEPTH_STENCIL",s))(On||{}),ql=(s=>(s[s.TEXTURE_2D=3553]="TEXTURE_2D",s[s.TEXTURE_CUBE_MAP=34067]="TEXTURE_CUBE_MAP",s[s.TEXTURE_2D_ARRAY=35866]="TEXTURE_2D_ARRAY",s[s.TEXTURE_CUBE_MAP_POSITIVE_X=34069]="TEXTURE_CUBE_MAP_POSITIVE_X",s[s.TEXTURE_CUBE_MAP_NEGATIVE_X=34070]="TEXTURE_CUBE_MAP_NEGATIVE_X",s[s.TEXTURE_CUBE_MAP_POSITIVE_Y=34071]="TEXTURE_CUBE_MAP_POSITIVE_Y",s[s.TEXTURE_CUBE_MAP_NEGATIVE_Y=34072]="TEXTURE_CUBE_MAP_NEGATIVE_Y",s[s.TEXTURE_CUBE_MAP_POSITIVE_Z=34073]="TEXTURE_CUBE_MAP_POSITIVE_Z",s[s.TEXTURE_CUBE_MAP_NEGATIVE_Z=34074]="TEXTURE_CUBE_MAP_NEGATIVE_Z",s))(ql||{}),K=(s=>(s[s.UNSIGNED_BYTE=5121]="UNSIGNED_BYTE",s[s.UNSIGNED_SHORT=5123]="UNSIGNED_SHORT",s[s.UNSIGNED_SHORT_5_6_5=33635]="UNSIGNED_SHORT_5_6_5",s[s.UNSIGNED_SHORT_4_4_4_4=32819]="UNSIGNED_SHORT_4_4_4_4",s[s.UNSIGNED_SHORT_5_5_5_1=32820]="UNSIGNED_SHORT_5_5_5_1",s[s.UNSIGNED_INT=5125]="UNSIGNED_INT",s[s.UNSIGNED_INT_10F_11F_11F_REV=35899]="UNSIGNED_INT_10F_11F_11F_REV",s[s.UNSIGNED_INT_2_10_10_10_REV=33640]="UNSIGNED_INT_2_10_10_10_REV",s[s.UNSIGNED_INT_24_8=34042]="UNSIGNED_INT_24_8",s[s.UNSIGNED_INT_5_9_9_9_REV=35902]="UNSIGNED_INT_5_9_9_9_REV",s[s.BYTE=5120]="BYTE",s[s.SHORT=5122]="SHORT",s[s.INT=5124]="INT",s[s.FLOAT=5126]="FLOAT",s[s.FLOAT_32_UNSIGNED_INT_24_8_REV=36269]="FLOAT_32_UNSIGNED_INT_24_8_REV",s[s.HALF_FLOAT=36193]="HALF_FLOAT",s))(K||{});const Zl={uint8x2:K.UNSIGNED_BYTE,uint8x4:K.UNSIGNED_BYTE,sint8x2:K.BYTE,sint8x4:K.BYTE,unorm8x2:K.UNSIGNED_BYTE,unorm8x4:K.UNSIGNED_BYTE,snorm8x2:K.BYTE,snorm8x4:K.BYTE,uint16x2:K.UNSIGNED_SHORT,uint16x4:K.UNSIGNED_SHORT,sint16x2:K.SHORT,sint16x4:K.SHORT,unorm16x2:K.UNSIGNED_SHORT,unorm16x4:K.UNSIGNED_SHORT,snorm16x2:K.SHORT,snorm16x4:K.SHORT,float16x2:K.HALF_FLOAT,float16x4:K.HALF_FLOAT,float32:K.FLOAT,float32x2:K.FLOAT,float32x3:K.FLOAT,float32x4:K.FLOAT,uint32:K.UNSIGNED_INT,uint32x2:K.UNSIGNED_INT,uint32x3:K.UNSIGNED_INT,uint32x4:K.UNSIGNED_INT,sint32:K.INT,sint32x2:K.INT,sint32x3:K.INT,sint32x4:K.INT};function Ay(s){return Zl[s]??Zl.float32}const Py={"point-list":0,"line-list":1,"line-strip":3,"triangle-list":4,"triangle-strip":5};class Ql{constructor(t){this._geometryVaoHash=Object.create(null),this._renderer=t,this._activeGeometry=null,this._activeVao=null,this.hasVao=!0,this.hasInstance=!0,this._renderer.renderableGC.addManagedHash(this,"_geometryVaoHash")}contextChange(){const t=this.gl=this._renderer.gl;if(!this._renderer.context.supports.vertexArrayObject)throw new Error("[PixiJS] Vertex Array Objects are not supported on this device");const e=this._renderer.context.extensions.vertexArrayObject;e&&(t.createVertexArray=()=>e.createVertexArrayOES(),t.bindVertexArray=n=>e.bindVertexArrayOES(n),t.deleteVertexArray=n=>e.deleteVertexArrayOES(n));const r=this._renderer.context.extensions.vertexAttribDivisorANGLE;r&&(t.drawArraysInstanced=(n,a,l,h)=>{r.drawArraysInstancedANGLE(n,a,l,h)},t.drawElementsInstanced=(n,a,l,h,d)=>{r.drawElementsInstancedANGLE(n,a,l,h,d)},t.vertexAttribDivisor=(n,a)=>r.vertexAttribDivisorANGLE(n,a)),this._activeGeometry=null,this._activeVao=null,this._geometryVaoHash=Object.create(null)}bind(t,e){const r=this.gl;this._activeGeometry=t;const n=this.getVao(t,e);this._activeVao!==n&&(this._activeVao=n,r.bindVertexArray(n)),this.updateBuffers()}resetState(){this.unbind()}updateBuffers(){const t=this._activeGeometry,e=this._renderer.buffer;for(let r=0;r<t.buffers.length;r++){const n=t.buffers[r];e.updateBuffer(n)}}checkCompatibility(t,e){const r=t.attributes,n=e._attributeData;for(const a in n)if(!r[a])throw new Error(`shader and geometry incompatible, geometry missing the "${a}" attribute`)}getSignature(t,e){const r=t.attributes,n=e._attributeData,a=["g",t.uid];for(const l in r)n[l]&&a.push(l,n[l].location);return a.join("-")}getVao(t,e){return this._geometryVaoHash[t.uid]?.[e._key]||this.initGeometryVao(t,e)}initGeometryVao(t,e,r=!0){const n=this._renderer.gl,a=this._renderer.buffer;this._renderer.shader._getProgramData(e),this.checkCompatibility(t,e);const l=this.getSignature(t,e);this._geometryVaoHash[t.uid]||(this._geometryVaoHash[t.uid]=Object.create(null),t.on("destroy",this.onGeometryDestroy,this));const h=this._geometryVaoHash[t.uid];let d=h[l];if(d)return h[e._key]=d,d;jl(t,e._attributeData);const f=t.buffers;d=n.createVertexArray(),n.bindVertexArray(d);for(let m=0;m<f.length;m++){const g=f[m];a.bind(g)}return this.activateVao(t,e),h[e._key]=d,h[l]=d,n.bindVertexArray(null),d}onGeometryDestroy(t,e){const r=this._geometryVaoHash[t.uid],n=this.gl;if(r){if(e)for(const a in r)this._activeVao!==r[a]&&this.unbind(),n.deleteVertexArray(r[a]);this._geometryVaoHash[t.uid]=null}}destroyAll(t=!1){const e=this.gl;for(const r in this._geometryVaoHash){if(t)for(const n in this._geometryVaoHash[r]){const a=this._geometryVaoHash[r];this._activeVao!==a&&this.unbind(),e.deleteVertexArray(a[n])}this._geometryVaoHash[r]=null}}activateVao(t,e){const r=this._renderer.gl,n=this._renderer.buffer,a=t.attributes;t.indexBuffer&&n.bind(t.indexBuffer);let l=null;for(const h in a){const d=a[h],f=d.buffer,m=n.getGlBuffer(f),g=e._attributeData[h];if(g){l!==m&&(n.bind(f),l=m);const y=g.location;r.enableVertexAttribArray(y);const x=ue(d.format),o=Ay(d.format);if(g.format?.substring(1,4)==="int"?r.vertexAttribIPointer(y,x.size,o,d.stride,d.offset):r.vertexAttribPointer(y,x.size,o,x.normalised,d.stride,d.offset),d.instance)if(this.hasInstance){const c=d.divisor??1;r.vertexAttribDivisor(y,c)}else throw new Error("geometry error, GPU Instancing is not supported on this device")}}}draw(t,e,r,n){const{gl:a}=this._renderer,l=this._activeGeometry,h=Py[t||l.topology];if(n??(n=l.instanceCount),l.indexBuffer){const d=l.indexBuffer.data.BYTES_PER_ELEMENT,f=d===2?a.UNSIGNED_SHORT:a.UNSIGNED_INT;n!==1?a.drawElementsInstanced(h,e||l.indexBuffer.data.length,f,(r||0)*d,n):a.drawElements(h,e||l.indexBuffer.data.length,f,(r||0)*d)}else n!==1?a.drawArraysInstanced(h,r||0,e||l.getSize(),n):a.drawArrays(h,r||0,e||l.getSize());return this}unbind(){this.gl.bindVertexArray(null),this._activeVao=null,this._activeGeometry=null}destroy(){this._renderer=null,this.gl=null,this._activeVao=null,this._activeGeometry=null,this._geometryVaoHash={}}}Ql.extension={type:[C.WebGLSystem],name:"geometry"};const By=new Pi({attributes:{aPosition:[-1,-1,3,-1,-1,3]}}),Ln=class sd{constructor(t){this.useBackBuffer=!1,this._useBackBufferThisRender=!1,this._renderer=t}init(t={}){const{useBackBuffer:e,antialias:r}={...sd.defaultOptions,...t};this.useBackBuffer=e,this._antialias=r,this._renderer.context.supports.msaa||(F("antialiasing, is not supported on when using the back buffer"),this._antialias=!1),this._state=Ht.for2d();const n=new Se({vertex:`
|
|
678
|
+
`}},ky=new ut;class My extends dr{constructor(){super(),this.filters=[new vy({sprite:new ie(k.EMPTY),inverse:!1,resolution:"inherit",antialias:"inherit"})]}get sprite(){return this.filters[0].sprite}set sprite(t){this.filters[0].sprite=t}get inverse(){return this.filters[0].inverse}set inverse(t){this.filters[0].inverse=t}}class jl{constructor(t){this._activeMaskStage=[],this._renderer=t}push(t,e,r){const n=this._renderer;if(n.renderPipes.batch.break(r),r.add({renderPipeId:"alphaMask",action:"pushMaskBegin",mask:t,inverse:e._maskOptions.inverse,canBundle:!1,maskedContainer:e}),t.inverse=e._maskOptions.inverse,t.renderMaskToTexture){const o=t.mask;o.includeInBuild=!0,o.collectRenderables(r,n,null),o.includeInBuild=!1}n.renderPipes.batch.break(r),r.add({renderPipeId:"alphaMask",action:"pushMaskEnd",mask:t,maskedContainer:e,inverse:e._maskOptions.inverse,canBundle:!1})}pop(t,e,r){this._renderer.renderPipes.batch.break(r),r.add({renderPipeId:"alphaMask",action:"popMaskEnd",mask:t,inverse:e._maskOptions.inverse,canBundle:!1})}execute(t){const e=this._renderer,r=t.mask.renderMaskToTexture;if(t.action==="pushMaskBegin"){const n=at.get(My);if(n.inverse=t.inverse,r){t.mask.mask.measurable=!0;const o=As(t.mask.mask,!0,ky);t.mask.mask.measurable=!1,o.ceil();const l=e.renderTarget.renderTarget.colorTexture.source,h=dt.getOptimalTexture(o.width,o.height,l._resolution,l.antialias);e.renderTarget.push(h,!0),e.globalUniforms.push({offset:o,worldColor:4294967295});const u=n.sprite;u.texture=h,u.worldTransform.tx=o.minX,u.worldTransform.ty=o.minY,this._activeMaskStage.push({filterEffect:n,maskedContainer:t.maskedContainer,filterTexture:h})}else n.sprite=t.mask.mask,this._activeMaskStage.push({filterEffect:n,maskedContainer:t.maskedContainer})}else if(t.action==="pushMaskEnd"){const n=this._activeMaskStage[this._activeMaskStage.length-1];r&&(e.type===Nt.WEBGL&&e.renderTarget.finishRenderPass(),e.renderTarget.pop(),e.globalUniforms.pop()),e.filter.push({renderPipeId:"filter",action:"pushFilter",container:n.maskedContainer,filterEffect:n.filterEffect,canBundle:!1})}else if(t.action==="popMaskEnd"){e.filter.pop();const n=this._activeMaskStage.pop();r&&dt.returnTexture(n.filterTexture),at.return(n.filterEffect)}}destroy(){this._renderer=null,this._activeMaskStage=null}}jl.extension={type:[C.WebGLPipes,C.WebGPUPipes,C.CanvasPipes],name:"alphaMask"};class ql{constructor(t){this._colorStack=[],this._colorStackIndex=0,this._currentColor=0,this._renderer=t}buildStart(){this._colorStack[0]=15,this._colorStackIndex=1,this._currentColor=15}push(t,e,r){this._renderer.renderPipes.batch.break(r);const o=this._colorStack;o[this._colorStackIndex]=o[this._colorStackIndex-1]&t.mask;const l=this._colorStack[this._colorStackIndex];l!==this._currentColor&&(this._currentColor=l,r.add({renderPipeId:"colorMask",colorMask:l,canBundle:!1})),this._colorStackIndex++}pop(t,e,r){this._renderer.renderPipes.batch.break(r);const o=this._colorStack;this._colorStackIndex--;const l=o[this._colorStackIndex-1];l!==this._currentColor&&(this._currentColor=l,r.add({renderPipeId:"colorMask",colorMask:l,canBundle:!1}))}execute(t){this._renderer.colorMask.setMask(t.colorMask)}destroy(){this._renderer=null,this._colorStack=null}}ql.extension={type:[C.WebGLPipes,C.WebGPUPipes,C.CanvasPipes],name:"colorMask"};class Zl{constructor(t){this._maskStackHash={},this._maskHash=new WeakMap,this._renderer=t}push(t,e,r){var n;const o=t,l=this._renderer;l.renderPipes.batch.break(r),l.renderPipes.blendMode.setBlendMode(o.mask,"none",r),r.add({renderPipeId:"stencilMask",action:"pushMaskBegin",mask:t,inverse:e._maskOptions.inverse,canBundle:!1});const h=o.mask;h.includeInBuild=!0,this._maskHash.has(o)||this._maskHash.set(o,{instructionsStart:0,instructionsLength:0});const u=this._maskHash.get(o);u.instructionsStart=r.instructionSize,h.collectRenderables(r,l,null),h.includeInBuild=!1,l.renderPipes.batch.break(r),r.add({renderPipeId:"stencilMask",action:"pushMaskEnd",mask:t,inverse:e._maskOptions.inverse,canBundle:!1});const f=r.instructionSize-u.instructionsStart-1;u.instructionsLength=f;const m=l.renderTarget.renderTarget.uid;(n=this._maskStackHash)[m]??(n[m]=0)}pop(t,e,r){const n=t,o=this._renderer;o.renderPipes.batch.break(r),o.renderPipes.blendMode.setBlendMode(n.mask,"none",r),r.add({renderPipeId:"stencilMask",action:"popMaskBegin",inverse:e._maskOptions.inverse,canBundle:!1});const l=this._maskHash.get(t);for(let h=0;h<l.instructionsLength;h++)r.instructions[r.instructionSize++]=r.instructions[l.instructionsStart++];r.add({renderPipeId:"stencilMask",action:"popMaskEnd",canBundle:!1})}execute(t){var e;const r=this._renderer,n=r.renderTarget.renderTarget.uid;let o=(e=this._maskStackHash)[n]??(e[n]=0);t.action==="pushMaskBegin"?(r.renderTarget.ensureDepthStencil(),r.stencil.setStencilMode(ot.RENDERING_MASK_ADD,o),o++,r.colorMask.setMask(0)):t.action==="pushMaskEnd"?(t.inverse?r.stencil.setStencilMode(ot.INVERSE_MASK_ACTIVE,o):r.stencil.setStencilMode(ot.MASK_ACTIVE,o),r.colorMask.setMask(15)):t.action==="popMaskBegin"?(r.colorMask.setMask(0),o!==0?r.stencil.setStencilMode(ot.RENDERING_MASK_REMOVE,o):(r.renderTarget.clear(null,Pt.STENCIL),r.stencil.setStencilMode(ot.DISABLED,o)),o--):t.action==="popMaskEnd"&&(t.inverse?r.stencil.setStencilMode(ot.INVERSE_MASK_ACTIVE,o):r.stencil.setStencilMode(ot.MASK_ACTIVE,o),r.colorMask.setMask(15)),this._maskStackHash[n]=o}destroy(){this._renderer=null,this._maskStackHash=null,this._maskHash=null}}Zl.extension={type:[C.WebGLPipes,C.WebGPUPipes,C.CanvasPipes],name:"stencilMask"};var Nr=(s=>(s[s.ELEMENT_ARRAY_BUFFER=34963]="ELEMENT_ARRAY_BUFFER",s[s.ARRAY_BUFFER=34962]="ARRAY_BUFFER",s[s.UNIFORM_BUFFER=35345]="UNIFORM_BUFFER",s))(Nr||{});class Ry{constructor(t,e){this._lastBindBaseLocation=-1,this._lastBindCallId=-1,this.buffer=t||null,this.updateID=-1,this.byteLength=-1,this.type=e}}class Ql{constructor(t){this._gpuBuffers=Object.create(null),this._boundBufferBases=Object.create(null),this._minBaseLocation=0,this._nextBindBaseIndex=this._minBaseLocation,this._bindCallId=0,this._renderer=t,this._renderer.renderableGC.addManagedHash(this,"_gpuBuffers")}destroy(){this.destroyAll(),this._renderer=null,this._gl=null,this._gpuBuffers={},this._boundBufferBases={}}contextChange(){this._gl=this._renderer.gl,this._gpuBuffers=Object.create(null),this._maxBindings=this._renderer.limits.maxUniformBindings}getGlBuffer(t){return this._gpuBuffers[t.uid]||this.createGLBuffer(t)}bind(t){const{_gl:e}=this,r=this.getGlBuffer(t);e.bindBuffer(r.type,r.buffer)}bindBufferBase(t,e){const{_gl:r}=this;this._boundBufferBases[e]!==t&&(this._boundBufferBases[e]=t,t._lastBindBaseLocation=e,r.bindBufferBase(r.UNIFORM_BUFFER,e,t.buffer))}nextBindBase(t){this._bindCallId++,this._minBaseLocation=0,t&&(this._boundBufferBases[0]=null,this._minBaseLocation=1,this._nextBindBaseIndex<1&&(this._nextBindBaseIndex=1))}freeLocationForBufferBase(t){let e=this.getLastBindBaseLocation(t);if(e>=this._minBaseLocation)return t._lastBindCallId=this._bindCallId,e;let r=0,n=this._nextBindBaseIndex;for(;r<2;){n>=this._maxBindings&&(n=this._minBaseLocation,r++);const o=this._boundBufferBases[n];if(o&&o._lastBindCallId===this._bindCallId){n++;continue}break}return e=n,this._nextBindBaseIndex=n+1,r>=2?-1:(t._lastBindCallId=this._bindCallId,this._boundBufferBases[e]=null,e)}getLastBindBaseLocation(t){const e=t._lastBindBaseLocation;return this._boundBufferBases[e]===t?e:-1}bindBufferRange(t,e,r,n){const{_gl:o}=this;r||(r=0),e||(e=0),this._boundBufferBases[e]=null,o.bindBufferRange(o.UNIFORM_BUFFER,e||0,t.buffer,r*256,n||256)}updateBuffer(t){const{_gl:e}=this,r=this.getGlBuffer(t);if(t._updateID===r.updateID)return r;r.updateID=t._updateID,e.bindBuffer(r.type,r.buffer);const n=t.data,o=t.descriptor.usage&Y.STATIC?e.STATIC_DRAW:e.DYNAMIC_DRAW;return n?r.byteLength>=n.byteLength?e.bufferSubData(r.type,0,n,0,t._updateSize/n.BYTES_PER_ELEMENT):(r.byteLength=n.byteLength,e.bufferData(r.type,n,o)):(r.byteLength=t.descriptor.size,e.bufferData(r.type,r.byteLength,o)),r}destroyAll(){const t=this._gl;for(const e in this._gpuBuffers)this._gpuBuffers[e]&&t.deleteBuffer(this._gpuBuffers[e].buffer);this._gpuBuffers=Object.create(null)}onBufferDestroy(t,e){if(!this._gpuBuffers[t.uid])return;const r=this._gpuBuffers[t.uid],n=this._gl;e||n.deleteBuffer(r.buffer),t.off("destroy",this.onBufferDestroy,this),this._gpuBuffers[t.uid]=null}createGLBuffer(t){const{_gl:e}=this;let r=Nr.ARRAY_BUFFER;t.descriptor.usage&Y.INDEX?r=Nr.ELEMENT_ARRAY_BUFFER:t.descriptor.usage&Y.UNIFORM&&(r=Nr.UNIFORM_BUFFER);const n=new Ry(e.createBuffer(),r);return this._gpuBuffers[t.uid]=n,t.on("destroy",this.onBufferDestroy,this),n}resetState(){this._boundBufferBases=Object.create(null)}}Ql.extension={type:[C.WebGLSystem],name:"buffer"};const zn=class au{constructor(t){this.supports={uint32Indices:!0,uniformBufferObject:!0,vertexArrayObject:!0,srgbTextures:!0,nonPowOf2wrapping:!0,msaa:!0,nonPowOf2mipmaps:!0},this._renderer=t,this.extensions=Object.create(null),this.handleContextLost=this.handleContextLost.bind(this),this.handleContextRestored=this.handleContextRestored.bind(this)}get isLost(){return!this.gl||this.gl.isContextLost()}contextChange(t){this.gl=t,this._renderer.gl=t}init(t){t={...au.defaultOptions,...t};let e=this.multiView=t.multiView;if(t.context&&e&&(F("Renderer created with both a context and multiview enabled. Disabling multiView as both cannot work together."),e=!1),e?this.canvas=W.get().createCanvas(this._renderer.canvas.width,this._renderer.canvas.height):this.canvas=this._renderer.view.canvas,t.context)this.initFromContext(t.context);else{const r=this._renderer.background.alpha<1,n=t.premultipliedAlpha??!0,o=t.antialias&&!this._renderer.backBuffer.useBackBuffer;this.createContext(t.preferWebGLVersion,{alpha:r,premultipliedAlpha:n,antialias:o,stencil:!0,preserveDrawingBuffer:t.preserveDrawingBuffer,powerPreference:t.powerPreference??"default"})}}ensureCanvasSize(t){if(!this.multiView){t!==this.canvas&&F("multiView is disabled, but targetCanvas is not the main canvas");return}const{canvas:e}=this;(e.width<t.width||e.height<t.height)&&(e.width=Math.max(t.width,t.width),e.height=Math.max(t.height,t.height))}initFromContext(t){this.gl=t,this.webGLVersion=t instanceof W.get().getWebGLRenderingContext()?1:2,this.getExtensions(),this.validateContext(t),this._renderer.runners.contextChange.emit(t);const e=this._renderer.view.canvas;e.addEventListener("webglcontextlost",this.handleContextLost,!1),e.addEventListener("webglcontextrestored",this.handleContextRestored,!1)}createContext(t,e){let r;const n=this.canvas;if(t===2&&(r=n.getContext("webgl2",e)),!r&&(r=n.getContext("webgl",e),!r))throw new Error("This browser does not support WebGL. Try using the canvas renderer");this.gl=r,this.initFromContext(this.gl)}getExtensions(){const{gl:t}=this,e={anisotropicFiltering:t.getExtension("EXT_texture_filter_anisotropic"),floatTextureLinear:t.getExtension("OES_texture_float_linear"),s3tc:t.getExtension("WEBGL_compressed_texture_s3tc"),s3tc_sRGB:t.getExtension("WEBGL_compressed_texture_s3tc_srgb"),etc:t.getExtension("WEBGL_compressed_texture_etc"),etc1:t.getExtension("WEBGL_compressed_texture_etc1"),pvrtc:t.getExtension("WEBGL_compressed_texture_pvrtc")||t.getExtension("WEBKIT_WEBGL_compressed_texture_pvrtc"),atc:t.getExtension("WEBGL_compressed_texture_atc"),astc:t.getExtension("WEBGL_compressed_texture_astc"),bptc:t.getExtension("EXT_texture_compression_bptc"),rgtc:t.getExtension("EXT_texture_compression_rgtc"),loseContext:t.getExtension("WEBGL_lose_context")};if(this.webGLVersion===1)this.extensions={...e,drawBuffers:t.getExtension("WEBGL_draw_buffers"),depthTexture:t.getExtension("WEBGL_depth_texture"),vertexArrayObject:t.getExtension("OES_vertex_array_object")||t.getExtension("MOZ_OES_vertex_array_object")||t.getExtension("WEBKIT_OES_vertex_array_object"),uint32ElementIndex:t.getExtension("OES_element_index_uint"),floatTexture:t.getExtension("OES_texture_float"),floatTextureLinear:t.getExtension("OES_texture_float_linear"),textureHalfFloat:t.getExtension("OES_texture_half_float"),textureHalfFloatLinear:t.getExtension("OES_texture_half_float_linear"),vertexAttribDivisorANGLE:t.getExtension("ANGLE_instanced_arrays"),srgb:t.getExtension("EXT_sRGB")};else{this.extensions={...e,colorBufferFloat:t.getExtension("EXT_color_buffer_float")};const r=t.getExtension("WEBGL_provoking_vertex");r&&r.provokingVertexWEBGL(r.FIRST_VERTEX_CONVENTION_WEBGL)}}handleContextLost(t){t.preventDefault(),this._contextLossForced&&(this._contextLossForced=!1,setTimeout(()=>{this.gl.isContextLost()&&this.extensions.loseContext?.restoreContext()},0))}handleContextRestored(){this.getExtensions(),this._renderer.runners.contextChange.emit(this.gl)}destroy(){const t=this._renderer.view.canvas;this._renderer=null,t.removeEventListener("webglcontextlost",this.handleContextLost),t.removeEventListener("webglcontextrestored",this.handleContextRestored),this.gl.useProgram(null),this.extensions.loseContext?.loseContext()}forceContextLoss(){this.extensions.loseContext?.loseContext(),this._contextLossForced=!0}validateContext(t){const e=t.getContextAttributes();e&&!e.stencil&&F("Provided WebGL context does not have a stencil buffer, masks may not render correctly");const r=this.supports,n=this.webGLVersion===2,o=this.extensions;r.uint32Indices=n||!!o.uint32ElementIndex,r.uniformBufferObject=n,r.vertexArrayObject=n||!!o.vertexArrayObject,r.srgbTextures=n||!!o.srgb,r.nonPowOf2wrapping=n,r.nonPowOf2mipmaps=n,r.msaa=n,r.uint32Indices||F("Provided WebGL context does not support 32 index buffer, large scenes may not render correctly")}};zn.extension={type:[C.WebGLSystem],name:"context"},zn.defaultOptions={context:null,premultipliedAlpha:!0,preserveDrawingBuffer:!1,powerPreference:void 0,preferWebGLVersion:2,multiView:!1};let Iy=zn;function Jl(s,t){for(const e in s.attributes){const r=s.attributes[e],n=t[e];n?(r.format??(r.format=n.format),r.offset??(r.offset=n.offset),r.instance??(r.instance=n.instance)):F(`Attribute ${e} is not present in the shader, but is present in the geometry. Unable to infer attribute details.`)}Fy(s)}function Fy(s){const{buffers:t,attributes:e}=s,r={},n={};for(const o in t){const l=t[o];r[l.uid]=0,n[l.uid]=0}for(const o in e){const l=e[o];r[l.buffer.uid]+=fe(l.format).stride}for(const o in e){const l=e[o];l.stride??(l.stride=r[l.buffer.uid]),l.start??(l.start=n[l.buffer.uid]),n[l.buffer.uid]+=fe(l.format).stride}}var Nn=(s=>(s[s.RGBA=6408]="RGBA",s[s.RGB=6407]="RGB",s[s.RG=33319]="RG",s[s.RED=6403]="RED",s[s.RGBA_INTEGER=36249]="RGBA_INTEGER",s[s.RGB_INTEGER=36248]="RGB_INTEGER",s[s.RG_INTEGER=33320]="RG_INTEGER",s[s.RED_INTEGER=36244]="RED_INTEGER",s[s.ALPHA=6406]="ALPHA",s[s.LUMINANCE=6409]="LUMINANCE",s[s.LUMINANCE_ALPHA=6410]="LUMINANCE_ALPHA",s[s.DEPTH_COMPONENT=6402]="DEPTH_COMPONENT",s[s.DEPTH_STENCIL=34041]="DEPTH_STENCIL",s))(Nn||{}),tc=(s=>(s[s.TEXTURE_2D=3553]="TEXTURE_2D",s[s.TEXTURE_CUBE_MAP=34067]="TEXTURE_CUBE_MAP",s[s.TEXTURE_2D_ARRAY=35866]="TEXTURE_2D_ARRAY",s[s.TEXTURE_CUBE_MAP_POSITIVE_X=34069]="TEXTURE_CUBE_MAP_POSITIVE_X",s[s.TEXTURE_CUBE_MAP_NEGATIVE_X=34070]="TEXTURE_CUBE_MAP_NEGATIVE_X",s[s.TEXTURE_CUBE_MAP_POSITIVE_Y=34071]="TEXTURE_CUBE_MAP_POSITIVE_Y",s[s.TEXTURE_CUBE_MAP_NEGATIVE_Y=34072]="TEXTURE_CUBE_MAP_NEGATIVE_Y",s[s.TEXTURE_CUBE_MAP_POSITIVE_Z=34073]="TEXTURE_CUBE_MAP_POSITIVE_Z",s[s.TEXTURE_CUBE_MAP_NEGATIVE_Z=34074]="TEXTURE_CUBE_MAP_NEGATIVE_Z",s))(tc||{}),K=(s=>(s[s.UNSIGNED_BYTE=5121]="UNSIGNED_BYTE",s[s.UNSIGNED_SHORT=5123]="UNSIGNED_SHORT",s[s.UNSIGNED_SHORT_5_6_5=33635]="UNSIGNED_SHORT_5_6_5",s[s.UNSIGNED_SHORT_4_4_4_4=32819]="UNSIGNED_SHORT_4_4_4_4",s[s.UNSIGNED_SHORT_5_5_5_1=32820]="UNSIGNED_SHORT_5_5_5_1",s[s.UNSIGNED_INT=5125]="UNSIGNED_INT",s[s.UNSIGNED_INT_10F_11F_11F_REV=35899]="UNSIGNED_INT_10F_11F_11F_REV",s[s.UNSIGNED_INT_2_10_10_10_REV=33640]="UNSIGNED_INT_2_10_10_10_REV",s[s.UNSIGNED_INT_24_8=34042]="UNSIGNED_INT_24_8",s[s.UNSIGNED_INT_5_9_9_9_REV=35902]="UNSIGNED_INT_5_9_9_9_REV",s[s.BYTE=5120]="BYTE",s[s.SHORT=5122]="SHORT",s[s.INT=5124]="INT",s[s.FLOAT=5126]="FLOAT",s[s.FLOAT_32_UNSIGNED_INT_24_8_REV=36269]="FLOAT_32_UNSIGNED_INT_24_8_REV",s[s.HALF_FLOAT=36193]="HALF_FLOAT",s))(K||{});const ec={uint8x2:K.UNSIGNED_BYTE,uint8x4:K.UNSIGNED_BYTE,sint8x2:K.BYTE,sint8x4:K.BYTE,unorm8x2:K.UNSIGNED_BYTE,unorm8x4:K.UNSIGNED_BYTE,snorm8x2:K.BYTE,snorm8x4:K.BYTE,uint16x2:K.UNSIGNED_SHORT,uint16x4:K.UNSIGNED_SHORT,sint16x2:K.SHORT,sint16x4:K.SHORT,unorm16x2:K.UNSIGNED_SHORT,unorm16x4:K.UNSIGNED_SHORT,snorm16x2:K.SHORT,snorm16x4:K.SHORT,float16x2:K.HALF_FLOAT,float16x4:K.HALF_FLOAT,float32:K.FLOAT,float32x2:K.FLOAT,float32x3:K.FLOAT,float32x4:K.FLOAT,uint32:K.UNSIGNED_INT,uint32x2:K.UNSIGNED_INT,uint32x3:K.UNSIGNED_INT,uint32x4:K.UNSIGNED_INT,sint32:K.INT,sint32x2:K.INT,sint32x3:K.INT,sint32x4:K.INT};function Dy(s){return ec[s]??ec.float32}const Oy={"point-list":0,"line-list":1,"line-strip":3,"triangle-list":4,"triangle-strip":5};class ic{constructor(t){this._geometryVaoHash=Object.create(null),this._renderer=t,this._activeGeometry=null,this._activeVao=null,this.hasVao=!0,this.hasInstance=!0,this._renderer.renderableGC.addManagedHash(this,"_geometryVaoHash")}contextChange(){const t=this.gl=this._renderer.gl;if(!this._renderer.context.supports.vertexArrayObject)throw new Error("[PixiJS] Vertex Array Objects are not supported on this device");const e=this._renderer.context.extensions.vertexArrayObject;e&&(t.createVertexArray=()=>e.createVertexArrayOES(),t.bindVertexArray=n=>e.bindVertexArrayOES(n),t.deleteVertexArray=n=>e.deleteVertexArrayOES(n));const r=this._renderer.context.extensions.vertexAttribDivisorANGLE;r&&(t.drawArraysInstanced=(n,o,l,h)=>{r.drawArraysInstancedANGLE(n,o,l,h)},t.drawElementsInstanced=(n,o,l,h,u)=>{r.drawElementsInstancedANGLE(n,o,l,h,u)},t.vertexAttribDivisor=(n,o)=>r.vertexAttribDivisorANGLE(n,o)),this._activeGeometry=null,this._activeVao=null,this._geometryVaoHash=Object.create(null)}bind(t,e){const r=this.gl;this._activeGeometry=t;const n=this.getVao(t,e);this._activeVao!==n&&(this._activeVao=n,r.bindVertexArray(n)),this.updateBuffers()}resetState(){this.unbind()}updateBuffers(){const t=this._activeGeometry,e=this._renderer.buffer;for(let r=0;r<t.buffers.length;r++){const n=t.buffers[r];e.updateBuffer(n)}}checkCompatibility(t,e){const r=t.attributes,n=e._attributeData;for(const o in n)if(!r[o])throw new Error(`shader and geometry incompatible, geometry missing the "${o}" attribute`)}getSignature(t,e){const r=t.attributes,n=e._attributeData,o=["g",t.uid];for(const l in r)n[l]&&o.push(l,n[l].location);return o.join("-")}getVao(t,e){return this._geometryVaoHash[t.uid]?.[e._key]||this.initGeometryVao(t,e)}initGeometryVao(t,e,r=!0){const n=this._renderer.gl,o=this._renderer.buffer;this._renderer.shader._getProgramData(e),this.checkCompatibility(t,e);const l=this.getSignature(t,e);this._geometryVaoHash[t.uid]||(this._geometryVaoHash[t.uid]=Object.create(null),t.on("destroy",this.onGeometryDestroy,this));const h=this._geometryVaoHash[t.uid];let u=h[l];if(u)return h[e._key]=u,u;Jl(t,e._attributeData);const f=t.buffers;u=n.createVertexArray(),n.bindVertexArray(u);for(let m=0;m<f.length;m++){const g=f[m];o.bind(g)}return this.activateVao(t,e),h[e._key]=u,h[l]=u,n.bindVertexArray(null),u}onGeometryDestroy(t,e){const r=this._geometryVaoHash[t.uid],n=this.gl;if(r){if(e)for(const o in r)this._activeVao!==r[o]&&this.unbind(),n.deleteVertexArray(r[o]);this._geometryVaoHash[t.uid]=null}}destroyAll(t=!1){const e=this.gl;for(const r in this._geometryVaoHash){if(t)for(const n in this._geometryVaoHash[r]){const o=this._geometryVaoHash[r];this._activeVao!==o&&this.unbind(),e.deleteVertexArray(o[n])}this._geometryVaoHash[r]=null}}activateVao(t,e){const r=this._renderer.gl,n=this._renderer.buffer,o=t.attributes;t.indexBuffer&&n.bind(t.indexBuffer);let l=null;for(const h in o){const u=o[h],f=u.buffer,m=n.getGlBuffer(f),g=e._attributeData[h];if(g){l!==m&&(n.bind(f),l=m);const y=g.location;r.enableVertexAttribArray(y);const x=fe(u.format),a=Dy(u.format);if(g.format?.substring(1,4)==="int"?r.vertexAttribIPointer(y,x.size,a,u.stride,u.offset):r.vertexAttribPointer(y,x.size,a,x.normalised,u.stride,u.offset),u.instance)if(this.hasInstance){const c=u.divisor??1;r.vertexAttribDivisor(y,c)}else throw new Error("geometry error, GPU Instancing is not supported on this device")}}}draw(t,e,r,n){const{gl:o}=this._renderer,l=this._activeGeometry,h=Oy[t||l.topology];if(n??(n=l.instanceCount),l.indexBuffer){const u=l.indexBuffer.data.BYTES_PER_ELEMENT,f=u===2?o.UNSIGNED_SHORT:o.UNSIGNED_INT;n!==1?o.drawElementsInstanced(h,e||l.indexBuffer.data.length,f,(r||0)*u,n):o.drawElements(h,e||l.indexBuffer.data.length,f,(r||0)*u)}else n!==1?o.drawArraysInstanced(h,r||0,e||l.getSize(),n):o.drawArrays(h,r||0,e||l.getSize());return this}unbind(){this.gl.bindVertexArray(null),this._activeVao=null,this._activeGeometry=null}destroy(){this._renderer=null,this.gl=null,this._activeVao=null,this._activeGeometry=null,this._geometryVaoHash={}}}ic.extension={type:[C.WebGLSystem],name:"geometry"};const Gy=new Bi({attributes:{aPosition:[-1,-1,3,-1,-1,3]}}),Hn=class hu{constructor(t){this.useBackBuffer=!1,this._useBackBufferThisRender=!1,this._renderer=t}init(t={}){const{useBackBuffer:e,antialias:r}={...hu.defaultOptions,...t};this.useBackBuffer=e,this._antialias=r,this._renderer.context.supports.msaa||(F("antialiasing, is not supported on when using the back buffer"),this._antialias=!1),this._state=Ht.for2d();const n=new Te({vertex:`
|
|
679
679
|
attribute vec2 aPosition;
|
|
680
680
|
out vec2 vUv;
|
|
681
681
|
|
|
@@ -694,7 +694,7 @@ fn mainFragment(
|
|
|
694
694
|
|
|
695
695
|
void main() {
|
|
696
696
|
finalColor = texture(uTexture, vUv);
|
|
697
|
-
}`,name:"big-triangle"});this._bigTriangleShader=new
|
|
697
|
+
}`,name:"big-triangle"});this._bigTriangleShader=new Ft({glProgram:n,resources:{uTexture:k.WHITE.source}})}renderStart(t){const e=this._renderer.renderTarget.getRenderTarget(t.target);if(this._useBackBufferThisRender=this.useBackBuffer&&!!e.isRoot,this._useBackBufferThisRender){const r=this._renderer.renderTarget.getRenderTarget(t.target);this._targetTexture=r.colorTexture,t.target=this._getBackBufferTexture(r.colorTexture)}}renderEnd(){this._presentBackBuffer()}_presentBackBuffer(){const t=this._renderer;t.renderTarget.finishRenderPass(),this._useBackBufferThisRender&&(t.renderTarget.bind(this._targetTexture,!1),this._bigTriangleShader.resources.uTexture=this._backBufferTexture.source,t.encoder.draw({geometry:Gy,shader:this._bigTriangleShader,state:this._state}))}_getBackBufferTexture(t){return this._backBufferTexture=this._backBufferTexture||new k({source:new ht({width:t.width,height:t.height,resolution:t._resolution,antialias:this._antialias})}),this._backBufferTexture.source.resize(t.width,t.height,t._resolution),this._backBufferTexture}destroy(){this._backBufferTexture&&(this._backBufferTexture.destroy(),this._backBufferTexture=null)}};Hn.extension={type:[C.WebGLSystem],name:"backBuffer",priority:1},Hn.defaultOptions={useBackBuffer:!1};let Ly=Hn;class rc{constructor(t){this._colorMaskCache=15,this._renderer=t}setMask(t){this._colorMaskCache!==t&&(this._colorMaskCache=t,this._renderer.gl.colorMask(!!(t&8),!!(t&4),!!(t&2),!!(t&1)))}}rc.extension={type:[C.WebGLSystem],name:"colorMask"};class sc{constructor(t){this.commandFinished=Promise.resolve(),this._renderer=t}setGeometry(t,e){this._renderer.geometry.bind(t,e.glProgram)}finishRenderPass(){}draw(t){const e=this._renderer,{geometry:r,shader:n,state:o,skipSync:l,topology:h,size:u,start:f,instanceCount:m}=t;e.shader.bind(n,l),e.geometry.bind(r,e.shader._activeProgram),o&&e.state.set(o),e.geometry.draw(h,u,f,m??r.instanceCount)}destroy(){this._renderer=null}}sc.extension={type:[C.WebGLSystem],name:"encoder"};class nc{constructor(t){this._renderer=t}contextChange(){const t=this._renderer.gl;this.maxTextures=t.getParameter(t.MAX_TEXTURE_IMAGE_UNITS),this.maxBatchableTextures=Mh(this.maxTextures,t);const e=this._renderer.context.webGLVersion===2;this.maxUniformBindings=e?t.getParameter(t.MAX_UNIFORM_BUFFER_BINDINGS):0}destroy(){}}nc.extension={type:[C.WebGLSystem],name:"limits"};class zy{constructor(){this.width=-1,this.height=-1,this.msaa=!1,this.msaaRenderBuffer=[]}}const ge=[];ge[ot.NONE]=void 0,ge[ot.DISABLED]={stencilWriteMask:0,stencilReadMask:0},ge[ot.RENDERING_MASK_ADD]={stencilFront:{compare:"equal",passOp:"increment-clamp"},stencilBack:{compare:"equal",passOp:"increment-clamp"}},ge[ot.RENDERING_MASK_REMOVE]={stencilFront:{compare:"equal",passOp:"decrement-clamp"},stencilBack:{compare:"equal",passOp:"decrement-clamp"}},ge[ot.MASK_ACTIVE]={stencilWriteMask:0,stencilFront:{compare:"equal",passOp:"keep"},stencilBack:{compare:"equal",passOp:"keep"}},ge[ot.INVERSE_MASK_ACTIVE]={stencilWriteMask:0,stencilFront:{compare:"not-equal",passOp:"keep"},stencilBack:{compare:"not-equal",passOp:"keep"}};class oc{constructor(t){this._stencilCache={enabled:!1,stencilReference:0,stencilMode:ot.NONE},this._renderTargetStencilState=Object.create(null),t.renderTarget.onRenderTargetChange.add(this)}contextChange(t){this._gl=t,this._comparisonFuncMapping={always:t.ALWAYS,never:t.NEVER,equal:t.EQUAL,"not-equal":t.NOTEQUAL,less:t.LESS,"less-equal":t.LEQUAL,greater:t.GREATER,"greater-equal":t.GEQUAL},this._stencilOpsMapping={keep:t.KEEP,zero:t.ZERO,replace:t.REPLACE,invert:t.INVERT,"increment-clamp":t.INCR,"decrement-clamp":t.DECR,"increment-wrap":t.INCR_WRAP,"decrement-wrap":t.DECR_WRAP},this.resetState()}onRenderTargetChange(t){if(this._activeRenderTarget===t)return;this._activeRenderTarget=t;let e=this._renderTargetStencilState[t.uid];e||(e=this._renderTargetStencilState[t.uid]={stencilMode:ot.DISABLED,stencilReference:0}),this.setStencilMode(e.stencilMode,e.stencilReference)}resetState(){this._stencilCache.enabled=!1,this._stencilCache.stencilMode=ot.NONE,this._stencilCache.stencilReference=0}setStencilMode(t,e){const r=this._renderTargetStencilState[this._activeRenderTarget.uid],n=this._gl,o=ge[t],l=this._stencilCache;if(r.stencilMode=t,r.stencilReference=e,t===ot.DISABLED){this._stencilCache.enabled&&(this._stencilCache.enabled=!1,n.disable(n.STENCIL_TEST));return}this._stencilCache.enabled||(this._stencilCache.enabled=!0,n.enable(n.STENCIL_TEST)),(t!==l.stencilMode||l.stencilReference!==e)&&(l.stencilMode=t,l.stencilReference=e,n.stencilFunc(this._comparisonFuncMapping[o.stencilBack.compare],e,255),n.stencilOp(n.KEEP,n.KEEP,this._stencilOpsMapping[o.stencilBack.passOp]))}}oc.extension={type:[C.WebGLSystem],name:"stencil"};class ac{constructor(t){this._syncFunctionHash=Object.create(null),this._adaptor=t,this._systemCheck()}_systemCheck(){if(!lh())throw new Error("Current environment does not allow unsafe-eval, please use pixi.js/unsafe-eval module to enable support.")}ensureUniformGroup(t){const e=this.getUniformGroupData(t);t.buffer||(t.buffer=new Bt({data:new Float32Array(e.layout.size/4),usage:Y.UNIFORM|Y.COPY_DST}))}getUniformGroupData(t){return this._syncFunctionHash[t._signature]||this._initUniformGroup(t)}_initUniformGroup(t){const e=t._signature;let r=this._syncFunctionHash[e];if(!r){const n=Object.keys(t.uniformStructures).map(h=>t.uniformStructures[h]),o=this._adaptor.createUboElements(n),l=this._generateUboSync(o.uboElements);r=this._syncFunctionHash[e]={layout:o,syncFunction:l}}return this._syncFunctionHash[e]}_generateUboSync(t){return this._adaptor.generateUboSync(t)}syncUniformGroup(t,e,r){const n=this.getUniformGroupData(t);t.buffer||(t.buffer=new Bt({data:new Float32Array(n.layout.size/4),usage:Y.UNIFORM|Y.COPY_DST}));let o=null;return e||(e=t.buffer.data,o=t.buffer.dataInt32),r||(r=0),n.syncFunction(t.uniforms,e,o,r),!0}updateUniformGroup(t){if(t.isStatic&&!t._dirtyId)return!1;t._dirtyId=0;const e=this.syncUniformGroup(t);return t.buffer.update(),e}destroy(){this._syncFunctionHash=null}}const hc={f32:4,i32:4,"vec2<f32>":8,"vec3<f32>":12,"vec4<f32>":16,"vec2<i32>":8,"vec3<i32>":12,"vec4<i32>":16,"mat2x2<f32>":32,"mat3x3<f32>":48,"mat4x4<f32>":64};function Ny(s){const t=s.map(o=>({data:o,offset:0,size:0})),e=16;let r=0,n=0;for(let o=0;o<t.length;o++){const l=t[o];if(r=hc[l.data.type],!r)throw new Error(`Unknown type ${l.data.type}`);l.data.size>1&&(r=Math.max(r,e)*l.data.size);const h=r===12?16:r;l.size=r;const u=n%e;u>0&&e-u<h?n+=(e-u)%16:n+=(r-u%r)%r,l.offset=n,n+=r}return n=Math.ceil(n/16)*16,{uboElements:t,size:n}}const Be=[{type:"mat3x3<f32>",test:s=>s.value.a!==void 0,ubo:`
|
|
698
698
|
var matrix = uv[name].toArray(true);
|
|
699
699
|
data[offset] = matrix[0];
|
|
700
700
|
data[offset + 1] = matrix[1];
|
|
@@ -765,23 +765,23 @@ fn mainFragment(
|
|
|
765
765
|
cv[2] = v.blue;
|
|
766
766
|
gl.uniform3f(ud[name].location, v.red, v.green, v.blue);
|
|
767
767
|
}
|
|
768
|
-
`}];function
|
|
768
|
+
`}];function lc(s,t,e,r){const n=[`
|
|
769
769
|
var v = null;
|
|
770
770
|
var v2 = null;
|
|
771
771
|
var t = 0;
|
|
772
772
|
var index = 0;
|
|
773
773
|
var name = null;
|
|
774
774
|
var arrayOffset = null;
|
|
775
|
-
`];let
|
|
775
|
+
`];let o=0;for(let h=0;h<s.length;h++){const u=s[h],f=u.data.name;let m=!1,g=0;for(let y=0;y<Be.length;y++)if(Be[y].test(u.data)){g=u.offset/4,n.push(`name = "${f}";`,`offset += ${g-o};`,Be[y][t]||Be[y].ubo),m=!0;break}if(!m)if(u.data.size>1)g=u.offset/4,n.push(e(u,g-o));else{const y=r[u.data.type];g=u.offset/4,n.push(`
|
|
776
776
|
v = uv.${f};
|
|
777
|
-
offset += ${g-
|
|
777
|
+
offset += ${g-o};
|
|
778
778
|
${y};
|
|
779
|
-
`)}
|
|
780
|
-
`);return new Function("uv","data","dataInt32","offset",l)}function
|
|
779
|
+
`)}o=g}const l=n.join(`
|
|
780
|
+
`);return new Function("uv","data","dataInt32","offset",l)}function ti(s,t){return`
|
|
781
781
|
for (let i = 0; i < ${s*t}; i++) {
|
|
782
782
|
data[offset + (((i / ${s})|0) * 4) + (i % ${s})] = v[i];
|
|
783
783
|
}
|
|
784
|
-
`}const
|
|
784
|
+
`}const cc={f32:`
|
|
785
785
|
data[offset] = v;`,i32:`
|
|
786
786
|
dataInt32[offset] = v;`,"vec2<f32>":`
|
|
787
787
|
data[offset] = v[0];
|
|
@@ -817,12 +817,12 @@ fn mainFragment(
|
|
|
817
817
|
data[offset + 10] = v[8];`,"mat4x4<f32>":`
|
|
818
818
|
for (let i = 0; i < 16; i++) {
|
|
819
819
|
data[offset + i] = v[i];
|
|
820
|
-
}`,"mat3x2<f32>":
|
|
820
|
+
}`,"mat3x2<f32>":ti(3,2),"mat4x2<f32>":ti(4,2),"mat2x3<f32>":ti(2,3),"mat4x3<f32>":ti(4,3),"mat2x4<f32>":ti(2,4),"mat3x4<f32>":ti(3,4)},Hy={...cc,"mat2x2<f32>":`
|
|
821
821
|
data[offset] = v[0];
|
|
822
822
|
data[offset + 1] = v[1];
|
|
823
823
|
data[offset + 2] = v[2];
|
|
824
824
|
data[offset + 3] = v[3];
|
|
825
|
-
`};function
|
|
825
|
+
`};function Wy(s,t){const e=Math.max(hc[s.data.type]/16,1),r=s.data.value.length/s.data.size,n=(4-r%4)%4,o=s.data.type.indexOf("i32")>=0?"dataInt32":"data";return`
|
|
826
826
|
v = uv.${s.data.name};
|
|
827
827
|
offset += ${t};
|
|
828
828
|
|
|
@@ -834,19 +834,19 @@ fn mainFragment(
|
|
|
834
834
|
{
|
|
835
835
|
for(var j = 0; j < ${r}; j++)
|
|
836
836
|
{
|
|
837
|
-
${
|
|
837
|
+
${o}[arrayOffset++] = v[t++];
|
|
838
838
|
}
|
|
839
839
|
${n!==0?`arrayOffset += ${n};`:""}
|
|
840
840
|
}
|
|
841
|
-
`}function Fy(s){return nc(s,"uboStd40",Iy,ac)}class oc extends rc{constructor(){super({createUboElements:ky,generateUboSync:Fy})}}oc.extension={type:[C.WebGLSystem],name:"ubo"};class Dy{constructor(){this._clearColorCache=[0,0,0,0],this._viewPortCache=new L}init(t,e){this._renderer=t,this._renderTargetSystem=e,t.runners.contextChange.add(this)}contextChange(){this._clearColorCache=[0,0,0,0],this._viewPortCache=new L}copyToTexture(t,e,r,n,a){const l=this._renderTargetSystem,h=this._renderer,d=l.getGpuRenderTarget(t),f=h.gl;return this.finishRenderPass(t),f.bindFramebuffer(f.FRAMEBUFFER,d.resolveTargetFramebuffer),h.texture.bind(e,0),f.copyTexSubImage2D(f.TEXTURE_2D,0,a.x,a.y,r.x,r.y,n.width,n.height),e}startRenderPass(t,e=!0,r,n){const a=this._renderTargetSystem,l=t.colorTexture,h=a.getGpuRenderTarget(t);let d=n.y;t.isRoot&&(d=l.pixelHeight-n.height),t.colorTextures.forEach(g=>{this._renderer.texture.unbind(g)});const f=this._renderer.gl;f.bindFramebuffer(f.FRAMEBUFFER,h.framebuffer);const m=this._viewPortCache;(m.x!==n.x||m.y!==d||m.width!==n.width||m.height!==n.height)&&(m.x=n.x,m.y=d,m.width=n.width,m.height=n.height,f.viewport(n.x,d,n.width,n.height)),!h.depthStencilRenderBuffer&&(t.stencil||t.depth)&&this._initStencil(h),this.clear(t,e,r)}finishRenderPass(t){const r=this._renderTargetSystem.getGpuRenderTarget(t);if(!r.msaa)return;const n=this._renderer.gl;n.bindFramebuffer(n.FRAMEBUFFER,r.resolveTargetFramebuffer),n.bindFramebuffer(n.READ_FRAMEBUFFER,r.framebuffer),n.blitFramebuffer(0,0,r.width,r.height,0,0,r.width,r.height,n.COLOR_BUFFER_BIT,n.NEAREST),n.bindFramebuffer(n.FRAMEBUFFER,r.framebuffer)}initGpuRenderTarget(t){const r=this._renderer.gl,n=new My;return t.colorTexture instanceof ee?(this._renderer.context.ensureCanvasSize(t.colorTexture.resource),n.framebuffer=null,n):(this._initColor(t,n),r.bindFramebuffer(r.FRAMEBUFFER,null),n)}destroyGpuRenderTarget(t){const e=this._renderer.gl;t.framebuffer&&(e.deleteFramebuffer(t.framebuffer),t.framebuffer=null),t.resolveTargetFramebuffer&&(e.deleteFramebuffer(t.resolveTargetFramebuffer),t.resolveTargetFramebuffer=null),t.depthStencilRenderBuffer&&(e.deleteRenderbuffer(t.depthStencilRenderBuffer),t.depthStencilRenderBuffer=null),t.msaaRenderBuffer.forEach(r=>{e.deleteRenderbuffer(r)}),t.msaaRenderBuffer=null}clear(t,e,r){if(!e)return;const n=this._renderTargetSystem;typeof e=="boolean"&&(e=e?At.ALL:At.NONE);const a=this._renderer.gl;if(e&At.COLOR){r??(r=n.defaultClearColor);const l=this._clearColorCache,h=r;(l[0]!==h[0]||l[1]!==h[1]||l[2]!==h[2]||l[3]!==h[3])&&(l[0]=h[0],l[1]=h[1],l[2]=h[2],l[3]=h[3],a.clearColor(h[0],h[1],h[2],h[3]))}a.clear(e)}resizeGpuRenderTarget(t){if(t.isRoot)return;const r=this._renderTargetSystem.getGpuRenderTarget(t);this._resizeColor(t,r),(t.stencil||t.depth)&&this._resizeStencil(r)}_initColor(t,e){const r=this._renderer,n=r.gl,a=n.createFramebuffer();if(e.resolveTargetFramebuffer=a,n.bindFramebuffer(n.FRAMEBUFFER,a),e.width=t.colorTexture.source.pixelWidth,e.height=t.colorTexture.source.pixelHeight,t.colorTextures.forEach((l,h)=>{const d=l.source;d.antialias&&(r.context.supports.msaa?e.msaa=!0:F("[RenderTexture] Antialiasing on textures is not supported in WebGL1")),r.texture.bindSource(d,0);const m=r.texture.getGlSource(d).texture;n.framebufferTexture2D(n.FRAMEBUFFER,n.COLOR_ATTACHMENT0+h,3553,m,0)}),e.msaa){const l=n.createFramebuffer();e.framebuffer=l,n.bindFramebuffer(n.FRAMEBUFFER,l),t.colorTextures.forEach((h,d)=>{const f=n.createRenderbuffer();e.msaaRenderBuffer[d]=f})}else e.framebuffer=a;this._resizeColor(t,e)}_resizeColor(t,e){const r=t.colorTexture.source;if(e.width=r.pixelWidth,e.height=r.pixelHeight,t.colorTextures.forEach((n,a)=>{a!==0&&n.source.resize(r.width,r.height,r._resolution)}),e.msaa){const n=this._renderer,a=n.gl,l=e.framebuffer;a.bindFramebuffer(a.FRAMEBUFFER,l),t.colorTextures.forEach((h,d)=>{const f=h.source;n.texture.bindSource(f,0);const g=n.texture.getGlSource(f).internalFormat,y=e.msaaRenderBuffer[d];a.bindRenderbuffer(a.RENDERBUFFER,y),a.renderbufferStorageMultisample(a.RENDERBUFFER,4,g,f.pixelWidth,f.pixelHeight),a.framebufferRenderbuffer(a.FRAMEBUFFER,a.COLOR_ATTACHMENT0+d,a.RENDERBUFFER,y)})}}_initStencil(t){if(t.framebuffer===null)return;const e=this._renderer.gl,r=e.createRenderbuffer();t.depthStencilRenderBuffer=r,e.bindRenderbuffer(e.RENDERBUFFER,r),e.framebufferRenderbuffer(e.FRAMEBUFFER,e.DEPTH_STENCIL_ATTACHMENT,e.RENDERBUFFER,r),this._resizeStencil(t)}_resizeStencil(t){const e=this._renderer.gl;e.bindRenderbuffer(e.RENDERBUFFER,t.depthStencilRenderBuffer),t.msaa?e.renderbufferStorageMultisample(e.RENDERBUFFER,4,e.DEPTH24_STENCIL8,t.width,t.height):e.renderbufferStorage(e.RENDERBUFFER,this._renderer.context.webGLVersion===2?e.DEPTH24_STENCIL8:e.DEPTH_STENCIL,t.width,t.height)}prerender(t){const e=t.colorTexture.resource;this._renderer.context.multiView&&ee.test(e)&&this._renderer.context.ensureCanvasSize(e)}postrender(t){if(this._renderer.context.multiView&&ee.test(t.colorTexture.resource)){const e=this._renderer.context.canvas,r=t.colorTexture;r.context2D.drawImage(e,0,r.pixelHeight-e.height)}}}function Gy(s,t,e,r,n,a){const l=a?1:-1;return s.identity(),s.a=1/r*2,s.d=l*(1/n*2),s.tx=-1-t*s.a,s.ty=-l-e*s.d,s}const ti=new Map;Ne.register(ti);function hc(s,t){if(!ti.has(s)){const e=new M({source:new ee({resource:s,...t})}),r=()=>{ti.get(s)===e&&ti.delete(s)};e.once("destroy",r),e.source.once("destroy",r),ti.set(s,e)}return ti.get(s)}function Oy(s){const t=s.colorTexture.source.resource;return globalThis.HTMLCanvasElement&&t instanceof HTMLCanvasElement&&document.body.contains(t)}const lc=class nd{constructor(t={}){if(this.uid=et("renderTarget"),this.colorTextures=[],this.dirtyId=0,this.isRoot=!1,this._size=new Float32Array(2),this._managedColorTextures=!1,t={...nd.defaultOptions,...t},this.stencil=t.stencil,this.depth=t.depth,this.isRoot=t.isRoot,typeof t.colorTextures=="number"){this._managedColorTextures=!0;for(let e=0;e<t.colorTextures;e++)this.colorTextures.push(new ht({width:t.width,height:t.height,resolution:t.resolution,antialias:t.antialias}))}else{this.colorTextures=[...t.colorTextures.map(r=>r.source)];const e=this.colorTexture.source;this.resize(e.width,e.height,e._resolution)}this.colorTexture.source.on("resize",this.onSourceResize,this),(t.depthStencilTexture||this.stencil)&&(t.depthStencilTexture instanceof M||t.depthStencilTexture instanceof ht?this.depthStencilTexture=t.depthStencilTexture.source:this.ensureDepthStencilTexture())}get size(){const t=this._size;return t[0]=this.pixelWidth,t[1]=this.pixelHeight,t}get width(){return this.colorTexture.source.width}get height(){return this.colorTexture.source.height}get pixelWidth(){return this.colorTexture.source.pixelWidth}get pixelHeight(){return this.colorTexture.source.pixelHeight}get resolution(){return this.colorTexture.source._resolution}get colorTexture(){return this.colorTextures[0]}onSourceResize(t){this.resize(t.width,t.height,t._resolution,!0)}ensureDepthStencilTexture(){this.depthStencilTexture||(this.depthStencilTexture=new ht({width:this.width,height:this.height,resolution:this.resolution,format:"depth24plus-stencil8",autoGenerateMipmaps:!1,antialias:!1,mipLevelCount:1}))}resize(t,e,r=this.resolution,n=!1){this.dirtyId++,this.colorTextures.forEach((a,l)=>{n&&l===0||a.source.resize(t,e,r)}),this.depthStencilTexture&&this.depthStencilTexture.source.resize(t,e,r)}destroy(){this.colorTexture.source.off("resize",this.onSourceResize,this),this._managedColorTextures&&this.colorTextures.forEach(t=>{t.destroy()}),this.depthStencilTexture&&(this.depthStencilTexture.destroy(),delete this.depthStencilTexture)}};lc.defaultOptions={width:0,height:0,resolution:1,colorTextures:1,stencil:!1,depth:!1,antialias:!1,isRoot:!1};let zn=lc;class cc{constructor(t){this.rootViewPort=new L,this.viewport=new L,this.onRenderTargetChange=new dh("onRenderTargetChange"),this.projectionMatrix=new k,this.defaultClearColor=[0,0,0,0],this._renderSurfaceToRenderTargetHash=new Map,this._gpuRenderTargetHash=Object.create(null),this._renderTargetStack=[],this._renderer=t,t.renderableGC.addManagedHash(this,"_gpuRenderTargetHash")}finishRenderPass(){this.adaptor.finishRenderPass(this.renderTarget)}renderStart({target:t,clear:e,clearColor:r,frame:n}){this._renderTargetStack.length=0,this.push(t,e,r,n),this.rootViewPort.copyFrom(this.viewport),this.rootRenderTarget=this.renderTarget,this.renderingToScreen=Oy(this.rootRenderTarget),this.adaptor.prerender?.(this.rootRenderTarget)}postrender(){this.adaptor.postrender?.(this.rootRenderTarget)}bind(t,e=!0,r,n){const a=this.getRenderTarget(t),l=this.renderTarget!==a;this.renderTarget=a,this.renderSurface=t;const h=this.getGpuRenderTarget(a);(a.pixelWidth!==h.width||a.pixelHeight!==h.height)&&(this.adaptor.resizeGpuRenderTarget(a),h.width=a.pixelWidth,h.height=a.pixelHeight);const d=a.colorTexture,f=this.viewport,m=d.pixelWidth,g=d.pixelHeight;if(!n&&t instanceof M&&(n=t.frame),n){const y=d._resolution;f.x=n.x*y+.5|0,f.y=n.y*y+.5|0,f.width=n.width*y+.5|0,f.height=n.height*y+.5|0}else f.x=0,f.y=0,f.width=m,f.height=g;return Gy(this.projectionMatrix,0,0,f.width/d.resolution,f.height/d.resolution,!a.isRoot),this.adaptor.startRenderPass(a,e,r,f),l&&this.onRenderTargetChange.emit(a),a}clear(t,e=At.ALL,r){e&&(t&&(t=this.getRenderTarget(t)),this.adaptor.clear(t||this.renderTarget,e,r,this.viewport))}contextChange(){this._gpuRenderTargetHash=Object.create(null)}push(t,e=At.ALL,r,n){const a=this.bind(t,e,r,n);return this._renderTargetStack.push({renderTarget:a,frame:n}),a}pop(){this._renderTargetStack.pop();const t=this._renderTargetStack[this._renderTargetStack.length-1];this.bind(t.renderTarget,!1,null,t.frame)}getRenderTarget(t){return t.isTexture&&(t=t.source),this._renderSurfaceToRenderTargetHash.get(t)??this._initRenderTarget(t)}copyToTexture(t,e,r,n,a){r.x<0&&(n.width+=r.x,a.x-=r.x,r.x=0),r.y<0&&(n.height+=r.y,a.y-=r.y,r.y=0);const{pixelWidth:l,pixelHeight:h}=t;return n.width=Math.min(n.width,l-r.x),n.height=Math.min(n.height,h-r.y),this.adaptor.copyToTexture(t,e,r,n,a)}ensureDepthStencil(){this.renderTarget.stencil||(this.renderTarget.stencil=!0,this.adaptor.startRenderPass(this.renderTarget,!1,null,this.viewport))}destroy(){this._renderer=null,this._renderSurfaceToRenderTargetHash.forEach((t,e)=>{t!==e&&t.destroy()}),this._renderSurfaceToRenderTargetHash.clear(),this._gpuRenderTargetHash=Object.create(null)}_initRenderTarget(t){let e=null;return ee.test(t)&&(t=hc(t).source),t instanceof zn?e=t:t instanceof ht&&(e=new zn({colorTextures:[t]}),t.source instanceof ee&&(e.isRoot=!0),t.once("destroy",()=>{e.destroy(),this._renderSurfaceToRenderTargetHash.delete(t);const r=this._gpuRenderTargetHash[e.uid];r&&(this._gpuRenderTargetHash[e.uid]=null,this.adaptor.destroyGpuRenderTarget(r))})),this._renderSurfaceToRenderTargetHash.set(t,e),e}getGpuRenderTarget(t){return this._gpuRenderTargetHash[t.uid]||(this._gpuRenderTargetHash[t.uid]=this.adaptor.initGpuRenderTarget(t))}resetState(){this.renderTarget=null,this.renderSurface=null}}class uc extends cc{constructor(t){super(t),this.adaptor=new Dy,this.adaptor.init(t,this)}}uc.extension={type:[C.WebGLSystem],name:"renderTarget"};class Nn extends Tt{constructor({buffer:t,offset:e,size:r}){super(),this.uid=et("buffer"),this._resourceType="bufferResource",this._touched=0,this._resourceId=et("resource"),this._bufferResource=!0,this.destroyed=!1,this.buffer=t,this.offset=e|0,this.size=r,this.buffer.on("change",this.onBufferChange,this)}onBufferChange(){this._resourceId=et("resource"),this.emit("change",this)}destroy(t=!1){this.destroyed=!0,t&&this.buffer.destroy(),this.emit("change",this),this.buffer=null,this.removeAllListeners()}}function Ly(s,t){const e=[],r=[`
|
|
841
|
+
`}function Vy(s){return lc(s,"uboStd40",Wy,cc)}class dc extends ac{constructor(){super({createUboElements:Ny,generateUboSync:Vy})}}dc.extension={type:[C.WebGLSystem],name:"ubo"};class Yy{constructor(){this._clearColorCache=[0,0,0,0],this._viewPortCache=new G}init(t,e){this._renderer=t,this._renderTargetSystem=e,t.runners.contextChange.add(this)}contextChange(){this._clearColorCache=[0,0,0,0],this._viewPortCache=new G}copyToTexture(t,e,r,n,o){const l=this._renderTargetSystem,h=this._renderer,u=l.getGpuRenderTarget(t),f=h.gl;return this.finishRenderPass(t),f.bindFramebuffer(f.FRAMEBUFFER,u.resolveTargetFramebuffer),h.texture.bind(e,0),f.copyTexSubImage2D(f.TEXTURE_2D,0,o.x,o.y,r.x,r.y,n.width,n.height),e}startRenderPass(t,e=!0,r,n){const o=this._renderTargetSystem,l=t.colorTexture,h=o.getGpuRenderTarget(t);let u=n.y;t.isRoot&&(u=l.pixelHeight-n.height),t.colorTextures.forEach(g=>{this._renderer.texture.unbind(g)});const f=this._renderer.gl;f.bindFramebuffer(f.FRAMEBUFFER,h.framebuffer);const m=this._viewPortCache;(m.x!==n.x||m.y!==u||m.width!==n.width||m.height!==n.height)&&(m.x=n.x,m.y=u,m.width=n.width,m.height=n.height,f.viewport(n.x,u,n.width,n.height)),!h.depthStencilRenderBuffer&&(t.stencil||t.depth)&&this._initStencil(h),this.clear(t,e,r)}finishRenderPass(t){const r=this._renderTargetSystem.getGpuRenderTarget(t);if(!r.msaa)return;const n=this._renderer.gl;n.bindFramebuffer(n.FRAMEBUFFER,r.resolveTargetFramebuffer),n.bindFramebuffer(n.READ_FRAMEBUFFER,r.framebuffer),n.blitFramebuffer(0,0,r.width,r.height,0,0,r.width,r.height,n.COLOR_BUFFER_BIT,n.NEAREST),n.bindFramebuffer(n.FRAMEBUFFER,r.framebuffer)}initGpuRenderTarget(t){const r=this._renderer.gl,n=new zy;return t.colorTexture instanceof re?(this._renderer.context.ensureCanvasSize(t.colorTexture.resource),n.framebuffer=null,n):(this._initColor(t,n),r.bindFramebuffer(r.FRAMEBUFFER,null),n)}destroyGpuRenderTarget(t){const e=this._renderer.gl;t.framebuffer&&(e.deleteFramebuffer(t.framebuffer),t.framebuffer=null),t.resolveTargetFramebuffer&&(e.deleteFramebuffer(t.resolveTargetFramebuffer),t.resolveTargetFramebuffer=null),t.depthStencilRenderBuffer&&(e.deleteRenderbuffer(t.depthStencilRenderBuffer),t.depthStencilRenderBuffer=null),t.msaaRenderBuffer.forEach(r=>{e.deleteRenderbuffer(r)}),t.msaaRenderBuffer=null}clear(t,e,r){if(!e)return;const n=this._renderTargetSystem;typeof e=="boolean"&&(e=e?Pt.ALL:Pt.NONE);const o=this._renderer.gl;if(e&Pt.COLOR){r??(r=n.defaultClearColor);const l=this._clearColorCache,h=r;(l[0]!==h[0]||l[1]!==h[1]||l[2]!==h[2]||l[3]!==h[3])&&(l[0]=h[0],l[1]=h[1],l[2]=h[2],l[3]=h[3],o.clearColor(h[0],h[1],h[2],h[3]))}o.clear(e)}resizeGpuRenderTarget(t){if(t.isRoot)return;const r=this._renderTargetSystem.getGpuRenderTarget(t);this._resizeColor(t,r),(t.stencil||t.depth)&&this._resizeStencil(r)}_initColor(t,e){const r=this._renderer,n=r.gl,o=n.createFramebuffer();if(e.resolveTargetFramebuffer=o,n.bindFramebuffer(n.FRAMEBUFFER,o),e.width=t.colorTexture.source.pixelWidth,e.height=t.colorTexture.source.pixelHeight,t.colorTextures.forEach((l,h)=>{const u=l.source;u.antialias&&(r.context.supports.msaa?e.msaa=!0:F("[RenderTexture] Antialiasing on textures is not supported in WebGL1")),r.texture.bindSource(u,0);const m=r.texture.getGlSource(u).texture;n.framebufferTexture2D(n.FRAMEBUFFER,n.COLOR_ATTACHMENT0+h,3553,m,0)}),e.msaa){const l=n.createFramebuffer();e.framebuffer=l,n.bindFramebuffer(n.FRAMEBUFFER,l),t.colorTextures.forEach((h,u)=>{const f=n.createRenderbuffer();e.msaaRenderBuffer[u]=f})}else e.framebuffer=o;this._resizeColor(t,e)}_resizeColor(t,e){const r=t.colorTexture.source;if(e.width=r.pixelWidth,e.height=r.pixelHeight,t.colorTextures.forEach((n,o)=>{o!==0&&n.source.resize(r.width,r.height,r._resolution)}),e.msaa){const n=this._renderer,o=n.gl,l=e.framebuffer;o.bindFramebuffer(o.FRAMEBUFFER,l),t.colorTextures.forEach((h,u)=>{const f=h.source;n.texture.bindSource(f,0);const g=n.texture.getGlSource(f).internalFormat,y=e.msaaRenderBuffer[u];o.bindRenderbuffer(o.RENDERBUFFER,y),o.renderbufferStorageMultisample(o.RENDERBUFFER,4,g,f.pixelWidth,f.pixelHeight),o.framebufferRenderbuffer(o.FRAMEBUFFER,o.COLOR_ATTACHMENT0+u,o.RENDERBUFFER,y)})}}_initStencil(t){if(t.framebuffer===null)return;const e=this._renderer.gl,r=e.createRenderbuffer();t.depthStencilRenderBuffer=r,e.bindRenderbuffer(e.RENDERBUFFER,r),e.framebufferRenderbuffer(e.FRAMEBUFFER,e.DEPTH_STENCIL_ATTACHMENT,e.RENDERBUFFER,r),this._resizeStencil(t)}_resizeStencil(t){const e=this._renderer.gl;e.bindRenderbuffer(e.RENDERBUFFER,t.depthStencilRenderBuffer),t.msaa?e.renderbufferStorageMultisample(e.RENDERBUFFER,4,e.DEPTH24_STENCIL8,t.width,t.height):e.renderbufferStorage(e.RENDERBUFFER,this._renderer.context.webGLVersion===2?e.DEPTH24_STENCIL8:e.DEPTH_STENCIL,t.width,t.height)}prerender(t){const e=t.colorTexture.resource;this._renderer.context.multiView&&re.test(e)&&this._renderer.context.ensureCanvasSize(e)}postrender(t){if(this._renderer.context.multiView&&re.test(t.colorTexture.resource)){const e=this._renderer.context.canvas,r=t.colorTexture;r.context2D.drawImage(e,0,r.pixelHeight-e.height)}}}function Xy(s,t,e,r,n,o){const l=o?1:-1;return s.identity(),s.a=1/r*2,s.d=l*(1/n*2),s.tx=-1-t*s.a,s.ty=-l-e*s.d,s}const ei=new Map;He.register(ei);function uc(s,t){if(!ei.has(s)){const e=new k({source:new re({resource:s,...t})}),r=()=>{ei.get(s)===e&&ei.delete(s)};e.once("destroy",r),e.source.once("destroy",r),ei.set(s,e)}return ei.get(s)}function $y(s){const t=s.colorTexture.source.resource;return globalThis.HTMLCanvasElement&&t instanceof HTMLCanvasElement&&document.body.contains(t)}const fc=class lu{constructor(t={}){if(this.uid=et("renderTarget"),this.colorTextures=[],this.dirtyId=0,this.isRoot=!1,this._size=new Float32Array(2),this._managedColorTextures=!1,t={...lu.defaultOptions,...t},this.stencil=t.stencil,this.depth=t.depth,this.isRoot=t.isRoot,typeof t.colorTextures=="number"){this._managedColorTextures=!0;for(let e=0;e<t.colorTextures;e++)this.colorTextures.push(new ht({width:t.width,height:t.height,resolution:t.resolution,antialias:t.antialias}))}else{this.colorTextures=[...t.colorTextures.map(r=>r.source)];const e=this.colorTexture.source;this.resize(e.width,e.height,e._resolution)}this.colorTexture.source.on("resize",this.onSourceResize,this),(t.depthStencilTexture||this.stencil)&&(t.depthStencilTexture instanceof k||t.depthStencilTexture instanceof ht?this.depthStencilTexture=t.depthStencilTexture.source:this.ensureDepthStencilTexture())}get size(){const t=this._size;return t[0]=this.pixelWidth,t[1]=this.pixelHeight,t}get width(){return this.colorTexture.source.width}get height(){return this.colorTexture.source.height}get pixelWidth(){return this.colorTexture.source.pixelWidth}get pixelHeight(){return this.colorTexture.source.pixelHeight}get resolution(){return this.colorTexture.source._resolution}get colorTexture(){return this.colorTextures[0]}onSourceResize(t){this.resize(t.width,t.height,t._resolution,!0)}ensureDepthStencilTexture(){this.depthStencilTexture||(this.depthStencilTexture=new ht({width:this.width,height:this.height,resolution:this.resolution,format:"depth24plus-stencil8",autoGenerateMipmaps:!1,antialias:!1,mipLevelCount:1}))}resize(t,e,r=this.resolution,n=!1){this.dirtyId++,this.colorTextures.forEach((o,l)=>{n&&l===0||o.source.resize(t,e,r)}),this.depthStencilTexture&&this.depthStencilTexture.source.resize(t,e,r)}destroy(){this.colorTexture.source.off("resize",this.onSourceResize,this),this._managedColorTextures&&this.colorTextures.forEach(t=>{t.destroy()}),this.depthStencilTexture&&(this.depthStencilTexture.destroy(),delete this.depthStencilTexture)}};fc.defaultOptions={width:0,height:0,resolution:1,colorTextures:1,stencil:!1,depth:!1,antialias:!1,isRoot:!1};let Wn=fc;class pc{constructor(t){this.rootViewPort=new G,this.viewport=new G,this.onRenderTargetChange=new gh("onRenderTargetChange"),this.projectionMatrix=new M,this.defaultClearColor=[0,0,0,0],this._renderSurfaceToRenderTargetHash=new Map,this._gpuRenderTargetHash=Object.create(null),this._renderTargetStack=[],this._renderer=t,t.renderableGC.addManagedHash(this,"_gpuRenderTargetHash")}finishRenderPass(){this.adaptor.finishRenderPass(this.renderTarget)}renderStart({target:t,clear:e,clearColor:r,frame:n}){this._renderTargetStack.length=0,this.push(t,e,r,n),this.rootViewPort.copyFrom(this.viewport),this.rootRenderTarget=this.renderTarget,this.renderingToScreen=$y(this.rootRenderTarget),this.adaptor.prerender?.(this.rootRenderTarget)}postrender(){this.adaptor.postrender?.(this.rootRenderTarget)}bind(t,e=!0,r,n){const o=this.getRenderTarget(t),l=this.renderTarget!==o;this.renderTarget=o,this.renderSurface=t;const h=this.getGpuRenderTarget(o);(o.pixelWidth!==h.width||o.pixelHeight!==h.height)&&(this.adaptor.resizeGpuRenderTarget(o),h.width=o.pixelWidth,h.height=o.pixelHeight);const u=o.colorTexture,f=this.viewport,m=u.pixelWidth,g=u.pixelHeight;if(!n&&t instanceof k&&(n=t.frame),n){const y=u._resolution;f.x=n.x*y+.5|0,f.y=n.y*y+.5|0,f.width=n.width*y+.5|0,f.height=n.height*y+.5|0}else f.x=0,f.y=0,f.width=m,f.height=g;return Xy(this.projectionMatrix,0,0,f.width/u.resolution,f.height/u.resolution,!o.isRoot),this.adaptor.startRenderPass(o,e,r,f),l&&this.onRenderTargetChange.emit(o),o}clear(t,e=Pt.ALL,r){e&&(t&&(t=this.getRenderTarget(t)),this.adaptor.clear(t||this.renderTarget,e,r,this.viewport))}contextChange(){this._gpuRenderTargetHash=Object.create(null)}push(t,e=Pt.ALL,r,n){const o=this.bind(t,e,r,n);return this._renderTargetStack.push({renderTarget:o,frame:n}),o}pop(){this._renderTargetStack.pop();const t=this._renderTargetStack[this._renderTargetStack.length-1];this.bind(t.renderTarget,!1,null,t.frame)}getRenderTarget(t){return t.isTexture&&(t=t.source),this._renderSurfaceToRenderTargetHash.get(t)??this._initRenderTarget(t)}copyToTexture(t,e,r,n,o){r.x<0&&(n.width+=r.x,o.x-=r.x,r.x=0),r.y<0&&(n.height+=r.y,o.y-=r.y,r.y=0);const{pixelWidth:l,pixelHeight:h}=t;return n.width=Math.min(n.width,l-r.x),n.height=Math.min(n.height,h-r.y),this.adaptor.copyToTexture(t,e,r,n,o)}ensureDepthStencil(){this.renderTarget.stencil||(this.renderTarget.stencil=!0,this.adaptor.startRenderPass(this.renderTarget,!1,null,this.viewport))}destroy(){this._renderer=null,this._renderSurfaceToRenderTargetHash.forEach((t,e)=>{t!==e&&t.destroy()}),this._renderSurfaceToRenderTargetHash.clear(),this._gpuRenderTargetHash=Object.create(null)}_initRenderTarget(t){let e=null;return re.test(t)&&(t=uc(t).source),t instanceof Wn?e=t:t instanceof ht&&(e=new Wn({colorTextures:[t]}),t.source instanceof re&&(e.isRoot=!0),t.once("destroy",()=>{e.destroy(),this._renderSurfaceToRenderTargetHash.delete(t);const r=this._gpuRenderTargetHash[e.uid];r&&(this._gpuRenderTargetHash[e.uid]=null,this.adaptor.destroyGpuRenderTarget(r))})),this._renderSurfaceToRenderTargetHash.set(t,e),e}getGpuRenderTarget(t){return this._gpuRenderTargetHash[t.uid]||(this._gpuRenderTargetHash[t.uid]=this.adaptor.initGpuRenderTarget(t))}resetState(){this.renderTarget=null,this.renderSurface=null}}class mc extends pc{constructor(t){super(t),this.adaptor=new Yy,this.adaptor.init(t,this)}}mc.extension={type:[C.WebGLSystem],name:"renderTarget"};class Vn extends Ct{constructor({buffer:t,offset:e,size:r}){super(),this.uid=et("buffer"),this._resourceType="bufferResource",this._touched=0,this._resourceId=et("resource"),this._bufferResource=!0,this.destroyed=!1,this.buffer=t,this.offset=e|0,this.size=r,this.buffer.on("change",this.onBufferChange,this)}onBufferChange(){this._resourceId=et("resource"),this.emit("change",this)}destroy(t=!1){this.destroyed=!0,t&&this.buffer.destroy(),this.emit("change",this),this.buffer=null,this.removeAllListeners()}}function Ky(s,t){const e=[],r=[`
|
|
842
842
|
var g = s.groups;
|
|
843
843
|
var sS = r.shader;
|
|
844
844
|
var p = s.glProgram;
|
|
845
845
|
var ugS = r.uniformGroup;
|
|
846
846
|
var resources;
|
|
847
|
-
`];let n=!1,
|
|
848
|
-
resources = g[${
|
|
849
|
-
`);for(const m in f.resources){const g=f.resources[m];if(g instanceof
|
|
847
|
+
`];let n=!1,o=0;const l=t._getProgramData(s.glProgram);for(const u in s.groups){const f=s.groups[u];e.push(`
|
|
848
|
+
resources = g[${u}].resources;
|
|
849
|
+
`);for(const m in f.resources){const g=f.resources[m];if(g instanceof _t)if(g.ubo){const y=s._uniformBindMap[u][Number(m)];e.push(`
|
|
850
850
|
sS.bindUniformBlock(
|
|
851
851
|
resources[${m}],
|
|
852
852
|
'${y}',
|
|
@@ -854,21 +854,21 @@ fn mainFragment(
|
|
|
854
854
|
);
|
|
855
855
|
`)}else e.push(`
|
|
856
856
|
ugS.updateUniformGroup(resources[${m}], p, sD);
|
|
857
|
-
`);else if(g instanceof
|
|
857
|
+
`);else if(g instanceof Vn){const y=s._uniformBindMap[u][Number(m)];e.push(`
|
|
858
858
|
sS.bindUniformBlock(
|
|
859
859
|
resources[${m}],
|
|
860
860
|
'${y}',
|
|
861
861
|
${s.glProgram._uniformBlockData[y].index}
|
|
862
862
|
);
|
|
863
|
-
`)}else if(g instanceof ht){const y=s._uniformBindMap[
|
|
863
|
+
`)}else if(g instanceof ht){const y=s._uniformBindMap[u][m],x=l.uniformData[y];x&&(n||(n=!0,r.push(`
|
|
864
864
|
var tS = r.texture;
|
|
865
|
-
`)),t._gl.uniform1i(x.location,
|
|
866
|
-
tS.bind(resources[${m}], ${
|
|
867
|
-
`),
|
|
868
|
-
`);return new Function("r","s","sD",h)}class
|
|
865
|
+
`)),t._gl.uniform1i(x.location,o),e.push(`
|
|
866
|
+
tS.bind(resources[${m}], ${o});
|
|
867
|
+
`),o++)}}}const h=[...r,...e].join(`
|
|
868
|
+
`);return new Function("r","s","sD",h)}class jy{constructor(t,e){this.program=t,this.uniformData=e,this.uniformGroups={},this.uniformDirtyGroups={},this.uniformBlockBindings={}}destroy(){this.uniformData=null,this.uniformGroups=null,this.uniformDirtyGroups=null,this.uniformBlockBindings=null,this.program=null}}function gc(s,t,e){const r=s.createShader(t);return s.shaderSource(r,e),s.compileShader(r),r}function Yn(s){const t=new Array(s);for(let e=0;e<t.length;e++)t[e]=!1;return t}function _c(s,t){switch(s){case"float":return 0;case"vec2":return new Float32Array(2*t);case"vec3":return new Float32Array(3*t);case"vec4":return new Float32Array(4*t);case"int":case"uint":case"sampler2D":case"sampler2DArray":return 0;case"ivec2":return new Int32Array(2*t);case"ivec3":return new Int32Array(3*t);case"ivec4":return new Int32Array(4*t);case"uvec2":return new Uint32Array(2*t);case"uvec3":return new Uint32Array(3*t);case"uvec4":return new Uint32Array(4*t);case"bool":return!1;case"bvec2":return Yn(2*t);case"bvec3":return Yn(3*t);case"bvec4":return Yn(4*t);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}let Hr=null;const yc={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"},qy={float:"float32",vec2:"float32x2",vec3:"float32x3",vec4:"float32x4",int:"sint32",ivec2:"sint32x2",ivec3:"sint32x3",ivec4:"sint32x4",uint:"uint32",uvec2:"uint32x2",uvec3:"uint32x3",uvec4:"uint32x4",bool:"uint32",bvec2:"uint32x2",bvec3:"uint32x3",bvec4:"uint32x4"};function xc(s,t){if(!Hr){const e=Object.keys(yc);Hr={};for(let r=0;r<e.length;++r){const n=e[r];Hr[s[n]]=yc[n]}}return Hr[t]}function Zy(s,t){const e=xc(s,t);return qy[e]||"float32"}function Qy(s,t,e=!1){const r={},n=t.getProgramParameter(s,t.ACTIVE_ATTRIBUTES);for(let l=0;l<n;l++){const h=t.getActiveAttrib(s,l);if(h.name.startsWith("gl_"))continue;const u=Zy(t,h.type);r[h.name]={location:0,format:u,stride:fe(u).stride,offset:0,instance:!1,start:0}}const o=Object.keys(r);if(e){o.sort((l,h)=>l>h?1:-1);for(let l=0;l<o.length;l++)r[o[l]].location=l,t.bindAttribLocation(s,l,o[l]);t.linkProgram(s)}else for(let l=0;l<o.length;l++)r[o[l]].location=t.getAttribLocation(s,o[l]);return r}function Jy(s,t){if(!t.ACTIVE_UNIFORM_BLOCKS)return{};const e={},r=t.getProgramParameter(s,t.ACTIVE_UNIFORM_BLOCKS);for(let n=0;n<r;n++){const o=t.getActiveUniformBlockName(s,n),l=t.getUniformBlockIndex(s,o),h=t.getActiveUniformBlockParameter(s,n,t.UNIFORM_BLOCK_DATA_SIZE);e[o]={name:o,index:l,size:h}}return e}function tx(s,t){const e={},r=t.getProgramParameter(s,t.ACTIVE_UNIFORMS);for(let n=0;n<r;n++){const o=t.getActiveUniform(s,n),l=o.name.replace(/\[.*?\]$/,""),h=!!o.name.match(/\[.*?\]$/),u=xc(t,o.type);e[l]={name:l,index:n,type:u,size:o.size,isArray:h,value:_c(u,o.size)}}return e}function bc(s,t){const e=s.getShaderSource(t).split(`
|
|
869
869
|
`).map((f,m)=>`${m}: ${f}`),r=s.getShaderInfoLog(t),n=r.split(`
|
|
870
|
-
`),
|
|
871
|
-
`);h[0]=
|
|
870
|
+
`),o={},l=n.map(f=>parseFloat(f.replace(/^ERROR\: 0\:([\d]+)\:.*$/,"$1"))).filter(f=>f&&!o[f]?(o[f]=!0,!0):!1),h=[""];l.forEach(f=>{e[f-1]=`%c${e[f-1]}%c`,h.push("background: #FF0000; color:#FFFFFF; font-size: 10px","font-size: 10px")});const u=e.join(`
|
|
871
|
+
`);h[0]=u,console.error(r),console.groupCollapsed("click to view full shader code"),console.warn(...h),console.groupEnd()}function ex(s,t,e,r){s.getProgramParameter(t,s.LINK_STATUS)||(s.getShaderParameter(e,s.COMPILE_STATUS)||bc(s,e),s.getShaderParameter(r,s.COMPILE_STATUS)||bc(s,r),console.error("PixiJS Error: Could not initialize shader."),s.getProgramInfoLog(t)!==""&&console.warn("PixiJS Warning: gl.getProgramInfoLog()",s.getProgramInfoLog(t)))}function ix(s,t){const e=gc(s,s.VERTEX_SHADER,t.vertex),r=gc(s,s.FRAGMENT_SHADER,t.fragment),n=s.createProgram();s.attachShader(n,e),s.attachShader(n,r);const o=t.transformFeedbackVaryings;o&&(typeof s.transformFeedbackVaryings!="function"?F("TransformFeedback is not supported but TransformFeedbackVaryings are given."):s.transformFeedbackVaryings(n,o.names,o.bufferMode==="separate"?s.SEPARATE_ATTRIBS:s.INTERLEAVED_ATTRIBS)),s.linkProgram(n),s.getProgramParameter(n,s.LINK_STATUS)||ex(s,n,e,r),t._attributeData=Qy(n,s,!/^[ \t]*#[ \t]*version[ \t]+300[ \t]+es[ \t]*$/m.test(t.vertex)),t._uniformData=tx(n,s),t._uniformBlockData=Jy(n,s),s.deleteShader(e),s.deleteShader(r);const l={};for(const u in t._uniformData){const f=t._uniformData[u];l[u]={location:s.getUniformLocation(n,u),value:_c(f.type,f.size)}}return new jy(n,l)}const Wr={textureCount:0,blockIndex:0};class vc{constructor(t){this._activeProgram=null,this._programDataHash=Object.create(null),this._shaderSyncFunctions=Object.create(null),this._renderer=t,this._renderer.renderableGC.addManagedHash(this,"_programDataHash")}contextChange(t){this._gl=t,this._programDataHash=Object.create(null),this._shaderSyncFunctions=Object.create(null),this._activeProgram=null}bind(t,e){if(this._setProgram(t.glProgram),e)return;Wr.textureCount=0,Wr.blockIndex=0;let r=this._shaderSyncFunctions[t.glProgram._key];r||(r=this._shaderSyncFunctions[t.glProgram._key]=this._generateShaderSync(t,this)),this._renderer.buffer.nextBindBase(!!t.glProgram.transformFeedbackVaryings),r(this._renderer,t,Wr)}updateUniformGroup(t){this._renderer.uniformGroup.updateUniformGroup(t,this._activeProgram,Wr)}bindUniformBlock(t,e,r=0){const n=this._renderer.buffer,o=this._getProgramData(this._activeProgram),l=t._bufferResource;l||this._renderer.ubo.updateUniformGroup(t);const h=t.buffer,u=n.updateBuffer(h),f=n.freeLocationForBufferBase(u);if(l){const{offset:g,size:y}=t;g===0&&y===h.data.byteLength?n.bindBufferBase(u,f):n.bindBufferRange(u,f,g)}else n.getLastBindBaseLocation(u)!==f&&n.bindBufferBase(u,f);const m=this._activeProgram._uniformBlockData[e].index;o.uniformBlockBindings[r]!==f&&(o.uniformBlockBindings[r]=f,this._renderer.gl.uniformBlockBinding(o.program,m,f))}_setProgram(t){if(this._activeProgram===t)return;this._activeProgram=t;const e=this._getProgramData(t);this._gl.useProgram(e.program)}_getProgramData(t){return this._programDataHash[t._key]||this._createProgramData(t)}_createProgramData(t){const e=t._key;return this._programDataHash[e]=ix(this._gl,t),this._programDataHash[e]}destroy(){for(const t of Object.keys(this._programDataHash))this._programDataHash[t].destroy(),this._programDataHash[t]=null;this._programDataHash=null,this._shaderSyncFunctions=null,this._activeProgram=null,this._renderer=null,this._gl=null}_generateShaderSync(t,e){return Ky(t,e)}resetState(){this._activeProgram=null}}vc.extension={type:[C.WebGLSystem],name:"shader"};const rx={f32:`if (cv !== v) {
|
|
872
872
|
cu.value = v;
|
|
873
873
|
gl.uniform1f(location, v);
|
|
874
874
|
}`,"vec2<f32>":`if (cv[0] !== v[0] || cv[1] !== v[1]) {
|
|
@@ -940,27 +940,27 @@ fn mainFragment(
|
|
|
940
940
|
cv[2] = v[2];
|
|
941
941
|
cv[3] = v[3];
|
|
942
942
|
gl.uniform4i(location, v[0], v[1], v[2], v[3]);
|
|
943
|
-
}`,"mat2x2<f32>":"gl.uniformMatrix2fv(location, false, v);","mat3x3<f32>":"gl.uniformMatrix3fv(location, false, v);","mat4x4<f32>":"gl.uniformMatrix4fv(location, false, v);"},
|
|
943
|
+
}`,"mat2x2<f32>":"gl.uniformMatrix2fv(location, false, v);","mat3x3<f32>":"gl.uniformMatrix3fv(location, false, v);","mat4x4<f32>":"gl.uniformMatrix4fv(location, false, v);"},sx={f32:"gl.uniform1fv(location, v);","vec2<f32>":"gl.uniform2fv(location, v);","vec3<f32>":"gl.uniform3fv(location, v);","vec4<f32>":"gl.uniform4fv(location, v);","mat2x2<f32>":"gl.uniformMatrix2fv(location, false, v);","mat3x3<f32>":"gl.uniformMatrix3fv(location, false, v);","mat4x4<f32>":"gl.uniformMatrix4fv(location, false, v);",i32:"gl.uniform1iv(location, v);","vec2<i32>":"gl.uniform2iv(location, v);","vec3<i32>":"gl.uniform3iv(location, v);","vec4<i32>":"gl.uniform4iv(location, v);",u32:"gl.uniform1iv(location, v);","vec2<u32>":"gl.uniform2iv(location, v);","vec3<u32>":"gl.uniform3iv(location, v);","vec4<u32>":"gl.uniform4iv(location, v);",bool:"gl.uniform1iv(location, v);","vec2<bool>":"gl.uniform2iv(location, v);","vec3<bool>":"gl.uniform3iv(location, v);","vec4<bool>":"gl.uniform4iv(location, v);"};function nx(s,t){const e=[`
|
|
944
944
|
var v = null;
|
|
945
945
|
var cv = null;
|
|
946
946
|
var cu = null;
|
|
947
947
|
var t = 0;
|
|
948
948
|
var gl = renderer.gl;
|
|
949
949
|
var name = null;
|
|
950
|
-
`];for(const r in s.uniforms){if(!t[r]){s.uniforms[r]instanceof
|
|
950
|
+
`];for(const r in s.uniforms){if(!t[r]){s.uniforms[r]instanceof _t?s.uniforms[r].ubo?e.push(`
|
|
951
951
|
renderer.shader.bindUniformBlock(uv.${r}, "${r}");
|
|
952
952
|
`):e.push(`
|
|
953
953
|
renderer.shader.updateUniformGroup(uv.${r});
|
|
954
|
-
`):s.uniforms[r]instanceof
|
|
954
|
+
`):s.uniforms[r]instanceof Vn&&e.push(`
|
|
955
955
|
renderer.shader.bindBufferResource(uv.${r}, "${r}");
|
|
956
|
-
`);continue}const n=s.uniformStructures[r];let
|
|
956
|
+
`);continue}const n=s.uniformStructures[r];let o=!1;for(let l=0;l<Be.length;l++){const h=Be[l];if(n.type===h.type&&h.test(n)){e.push(`name = "${r}";`,Be[l].uniform),o=!0;break}}if(!o){const h=(n.size===1?rx:sx)[n.type].replace("location",`ud["${r}"].location`);e.push(`
|
|
957
957
|
cu = ud["${r}"];
|
|
958
958
|
cv = cu.value;
|
|
959
959
|
v = uv["${r}"];
|
|
960
960
|
${h};`)}}return new Function("ud","uv","renderer","syncData",e.join(`
|
|
961
|
-
`))}class yc{constructor(t){this._cache={},this._uniformGroupSyncHash={},this._renderer=t,this.gl=null,this._cache={}}contextChange(t){this.gl=t}updateUniformGroup(t,e,r){const n=this._renderer.shader._getProgramData(e);(!t.isStatic||t._dirtyId!==n.uniformDirtyGroups[t.uid])&&(n.uniformDirtyGroups[t.uid]=t._dirtyId,this._getUniformSyncFunction(t,e)(n.uniformData,t.uniforms,this._renderer,r))}_getUniformSyncFunction(t,e){return this._uniformGroupSyncHash[t._signature]?.[e._key]||this._createUniformSyncFunction(t,e)}_createUniformSyncFunction(t,e){const r=this._uniformGroupSyncHash[t._signature]||(this._uniformGroupSyncHash[t._signature]={}),n=this._getSignature(t,e._uniformData,"u");return this._cache[n]||(this._cache[n]=this._generateUniformsSync(t,e._uniformData)),r[e._key]=this._cache[n],r[e._key]}_generateUniformsSync(t,e){return qy(t,e)}_getSignature(t,e,r){const n=t.uniforms,a=[`${r}-`];for(const l in n)a.push(l),e[l]&&a.push(e[l].type);return a.join("-")}destroy(){this._renderer=null,this._cache=null}}yc.extension={type:[C.WebGLSystem],name:"uniformGroup"};function Zy(s){const t={};if(t.normal=[s.ONE,s.ONE_MINUS_SRC_ALPHA],t.add=[s.ONE,s.ONE],t.multiply=[s.DST_COLOR,s.ONE_MINUS_SRC_ALPHA,s.ONE,s.ONE_MINUS_SRC_ALPHA],t.screen=[s.ONE,s.ONE_MINUS_SRC_COLOR,s.ONE,s.ONE_MINUS_SRC_ALPHA],t.none=[0,0],t["normal-npm"]=[s.SRC_ALPHA,s.ONE_MINUS_SRC_ALPHA,s.ONE,s.ONE_MINUS_SRC_ALPHA],t["add-npm"]=[s.SRC_ALPHA,s.ONE,s.ONE,s.ONE],t["screen-npm"]=[s.SRC_ALPHA,s.ONE_MINUS_SRC_COLOR,s.ONE,s.ONE_MINUS_SRC_ALPHA],t.erase=[s.ZERO,s.ONE_MINUS_SRC_ALPHA],!(s instanceof W.get().getWebGLRenderingContext()))t.min=[s.ONE,s.ONE,s.ONE,s.ONE,s.MIN,s.MIN],t.max=[s.ONE,s.ONE,s.ONE,s.ONE,s.MAX,s.MAX];else{const r=s.getExtension("EXT_blend_minmax");r&&(t.min=[s.ONE,s.ONE,s.ONE,s.ONE,r.MIN_EXT,r.MIN_EXT],t.max=[s.ONE,s.ONE,s.ONE,s.ONE,r.MAX_EXT,r.MAX_EXT])}return t}const Qy=0,Jy=1,tx=2,ex=3,ix=4,rx=5,xc=class ba{constructor(t){this._invertFrontFace=!1,this.gl=null,this.stateId=0,this.polygonOffset=0,this.blendMode="none",this._blendEq=!1,this.map=[],this.map[Qy]=this.setBlend,this.map[Jy]=this.setOffset,this.map[tx]=this.setCullFace,this.map[ex]=this.setDepthTest,this.map[ix]=this.setFrontFace,this.map[rx]=this.setDepthMask,this.checks=[],this.defaultState=Ht.for2d(),t.renderTarget.onRenderTargetChange.add(this)}onRenderTargetChange(t){this._invertFrontFace=!t.isRoot,this._cullFace?this.setFrontFace(this._frontFace):this._frontFaceDirty=!0}contextChange(t){this.gl=t,this.blendModesMap=Zy(t),this.resetState()}set(t){if(t||(t=this.defaultState),this.stateId!==t.data){let e=this.stateId^t.data,r=0;for(;e;)e&1&&this.map[r].call(this,!!(t.data&1<<r)),e>>=1,r++;this.stateId=t.data}for(let e=0;e<this.checks.length;e++)this.checks[e](this,t)}forceState(t){t||(t=this.defaultState);for(let e=0;e<this.map.length;e++)this.map[e].call(this,!!(t.data&1<<e));for(let e=0;e<this.checks.length;e++)this.checks[e](this,t);this.stateId=t.data}setBlend(t){this._updateCheck(ba._checkBlendMode,t),this.gl[t?"enable":"disable"](this.gl.BLEND)}setOffset(t){this._updateCheck(ba._checkPolygonOffset,t),this.gl[t?"enable":"disable"](this.gl.POLYGON_OFFSET_FILL)}setDepthTest(t){this.gl[t?"enable":"disable"](this.gl.DEPTH_TEST)}setDepthMask(t){this.gl.depthMask(t)}setCullFace(t){this._cullFace=t,this.gl[t?"enable":"disable"](this.gl.CULL_FACE),this._cullFace&&this._frontFaceDirty&&this.setFrontFace(this._frontFace)}setFrontFace(t){this._frontFace=t,this._frontFaceDirty=!1;const e=this._invertFrontFace?!t:t;this._glFrontFace!==e&&(this._glFrontFace=e,this.gl.frontFace(this.gl[e?"CW":"CCW"]))}setBlendMode(t){if(this.blendModesMap[t]||(t="normal"),t===this.blendMode)return;this.blendMode=t;const e=this.blendModesMap[t],r=this.gl;e.length===2?r.blendFunc(e[0],e[1]):r.blendFuncSeparate(e[0],e[1],e[2],e[3]),e.length===6?(this._blendEq=!0,r.blendEquationSeparate(e[4],e[5])):this._blendEq&&(this._blendEq=!1,r.blendEquationSeparate(r.FUNC_ADD,r.FUNC_ADD))}setPolygonOffset(t,e){this.gl.polygonOffset(t,e)}resetState(){this._glFrontFace=!1,this._frontFace=!1,this._cullFace=!1,this._frontFaceDirty=!1,this._invertFrontFace=!1,this.gl.frontFace(this.gl.CCW),this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,!1),this.forceState(this.defaultState),this._blendEq=!0,this.blendMode="",this.setBlendMode("normal")}_updateCheck(t,e){const r=this.checks.indexOf(t);e&&r===-1?this.checks.push(t):!e&&r!==-1&&this.checks.splice(r,1)}static _checkBlendMode(t,e){t.setBlendMode(e.blendMode)}static _checkPolygonOffset(t,e){t.setPolygonOffset(1,e.polygonOffset)}destroy(){this.gl=null,this.checks.length=0}};xc.extension={type:[C.WebGLSystem],name:"state"};let sx=xc;class nx{constructor(t){this.target=ql.TEXTURE_2D,this.texture=t,this.width=-1,this.height=-1,this.type=K.UNSIGNED_BYTE,this.internalFormat=On.RGBA,this.format=On.RGBA,this.samplerType=0}}const ax={id:"buffer",upload(s,t,e){t.width===s.width||t.height===s.height?e.texSubImage2D(e.TEXTURE_2D,0,0,0,s.width,s.height,t.format,t.type,s.resource):e.texImage2D(t.target,0,t.internalFormat,s.width,s.height,0,t.format,t.type,s.resource),t.width=s.width,t.height=s.height}},ox={"bc1-rgba-unorm":!0,"bc1-rgba-unorm-srgb":!0,"bc2-rgba-unorm":!0,"bc2-rgba-unorm-srgb":!0,"bc3-rgba-unorm":!0,"bc3-rgba-unorm-srgb":!0,"bc4-r-unorm":!0,"bc4-r-snorm":!0,"bc5-rg-unorm":!0,"bc5-rg-snorm":!0,"bc6h-rgb-ufloat":!0,"bc6h-rgb-float":!0,"bc7-rgba-unorm":!0,"bc7-rgba-unorm-srgb":!0,"etc2-rgb8unorm":!0,"etc2-rgb8unorm-srgb":!0,"etc2-rgb8a1unorm":!0,"etc2-rgb8a1unorm-srgb":!0,"etc2-rgba8unorm":!0,"etc2-rgba8unorm-srgb":!0,"eac-r11unorm":!0,"eac-r11snorm":!0,"eac-rg11unorm":!0,"eac-rg11snorm":!0,"astc-4x4-unorm":!0,"astc-4x4-unorm-srgb":!0,"astc-5x4-unorm":!0,"astc-5x4-unorm-srgb":!0,"astc-5x5-unorm":!0,"astc-5x5-unorm-srgb":!0,"astc-6x5-unorm":!0,"astc-6x5-unorm-srgb":!0,"astc-6x6-unorm":!0,"astc-6x6-unorm-srgb":!0,"astc-8x5-unorm":!0,"astc-8x5-unorm-srgb":!0,"astc-8x6-unorm":!0,"astc-8x6-unorm-srgb":!0,"astc-8x8-unorm":!0,"astc-8x8-unorm-srgb":!0,"astc-10x5-unorm":!0,"astc-10x5-unorm-srgb":!0,"astc-10x6-unorm":!0,"astc-10x6-unorm-srgb":!0,"astc-10x8-unorm":!0,"astc-10x8-unorm-srgb":!0,"astc-10x10-unorm":!0,"astc-10x10-unorm-srgb":!0,"astc-12x10-unorm":!0,"astc-12x10-unorm-srgb":!0,"astc-12x12-unorm":!0,"astc-12x12-unorm-srgb":!0},hx={id:"compressed",upload(s,t,e){e.pixelStorei(e.UNPACK_ALIGNMENT,4);let r=s.pixelWidth,n=s.pixelHeight;const a=!!ox[s.format];for(let l=0;l<s.resource.length;l++){const h=s.resource[l];a?e.compressedTexImage2D(e.TEXTURE_2D,l,t.internalFormat,r,n,0,h):e.texImage2D(e.TEXTURE_2D,l,t.internalFormat,r,n,0,t.format,t.type,h),r=Math.max(r>>1,1),n=Math.max(n>>1,1)}}},bc={id:"image",upload(s,t,e,r){const n=t.width,a=t.height,l=s.pixelWidth,h=s.pixelHeight,d=s.resourceWidth,f=s.resourceHeight;d<l||f<h?((n!==l||a!==h)&&e.texImage2D(t.target,0,t.internalFormat,l,h,0,t.format,t.type,null),r===2?e.texSubImage2D(e.TEXTURE_2D,0,0,0,d,f,t.format,t.type,s.resource):e.texSubImage2D(e.TEXTURE_2D,0,0,0,t.format,t.type,s.resource)):n===l&&a===h?e.texSubImage2D(e.TEXTURE_2D,0,0,0,t.format,t.type,s.resource):r===2?e.texImage2D(t.target,0,t.internalFormat,l,h,0,t.format,t.type,s.resource):e.texImage2D(t.target,0,t.internalFormat,t.format,t.type,s.resource),t.width=l,t.height=h}},lx={id:"video",upload(s,t,e,r){if(!s.isValid){e.texImage2D(t.target,0,t.internalFormat,1,1,0,t.format,t.type,null);return}bc.upload(s,t,e,r)}},vc={linear:9729,nearest:9728},cx={linear:{linear:9987,nearest:9985},nearest:{linear:9986,nearest:9984}},Wn={"clamp-to-edge":33071,repeat:10497,"mirror-repeat":33648},ux={never:512,less:513,equal:514,"less-equal":515,greater:516,"not-equal":517,"greater-equal":518,always:519};function wc(s,t,e,r,n,a,l,h){const d=a;if(!h||s.addressModeU!=="repeat"||s.addressModeV!=="repeat"||s.addressModeW!=="repeat"){const f=Wn[l?"clamp-to-edge":s.addressModeU],m=Wn[l?"clamp-to-edge":s.addressModeV],g=Wn[l?"clamp-to-edge":s.addressModeW];t[n](d,t.TEXTURE_WRAP_S,f),t[n](d,t.TEXTURE_WRAP_T,m),t.TEXTURE_WRAP_R&&t[n](d,t.TEXTURE_WRAP_R,g)}if((!h||s.magFilter!=="linear")&&t[n](d,t.TEXTURE_MAG_FILTER,vc[s.magFilter]),e){if(!h||s.mipmapFilter!=="linear"){const f=cx[s.minFilter][s.mipmapFilter];t[n](d,t.TEXTURE_MIN_FILTER,f)}}else t[n](d,t.TEXTURE_MIN_FILTER,vc[s.minFilter]);if(r&&s.maxAnisotropy>1){const f=Math.min(s.maxAnisotropy,t.getParameter(r.MAX_TEXTURE_MAX_ANISOTROPY_EXT));t[n](d,r.TEXTURE_MAX_ANISOTROPY_EXT,f)}s.compare&&t[n](d,t.TEXTURE_COMPARE_FUNC,ux[s.compare])}function dx(s){return{r8unorm:s.RED,r8snorm:s.RED,r8uint:s.RED,r8sint:s.RED,r16uint:s.RED,r16sint:s.RED,r16float:s.RED,rg8unorm:s.RG,rg8snorm:s.RG,rg8uint:s.RG,rg8sint:s.RG,r32uint:s.RED,r32sint:s.RED,r32float:s.RED,rg16uint:s.RG,rg16sint:s.RG,rg16float:s.RG,rgba8unorm:s.RGBA,"rgba8unorm-srgb":s.RGBA,rgba8snorm:s.RGBA,rgba8uint:s.RGBA,rgba8sint:s.RGBA,bgra8unorm:s.RGBA,"bgra8unorm-srgb":s.RGBA,rgb9e5ufloat:s.RGB,rgb10a2unorm:s.RGBA,rg11b10ufloat:s.RGB,rg32uint:s.RG,rg32sint:s.RG,rg32float:s.RG,rgba16uint:s.RGBA,rgba16sint:s.RGBA,rgba16float:s.RGBA,rgba32uint:s.RGBA,rgba32sint:s.RGBA,rgba32float:s.RGBA,stencil8:s.STENCIL_INDEX8,depth16unorm:s.DEPTH_COMPONENT,depth24plus:s.DEPTH_COMPONENT,"depth24plus-stencil8":s.DEPTH_STENCIL,depth32float:s.DEPTH_COMPONENT,"depth32float-stencil8":s.DEPTH_STENCIL}}function fx(s,t){let e={},r=s.RGBA;return s instanceof W.get().getWebGLRenderingContext()?t.srgb&&(e={"rgba8unorm-srgb":t.srgb.SRGB8_ALPHA8_EXT,"bgra8unorm-srgb":t.srgb.SRGB8_ALPHA8_EXT}):(e={"rgba8unorm-srgb":s.SRGB8_ALPHA8,"bgra8unorm-srgb":s.SRGB8_ALPHA8},r=s.RGBA8),{r8unorm:s.R8,r8snorm:s.R8_SNORM,r8uint:s.R8UI,r8sint:s.R8I,r16uint:s.R16UI,r16sint:s.R16I,r16float:s.R16F,rg8unorm:s.RG8,rg8snorm:s.RG8_SNORM,rg8uint:s.RG8UI,rg8sint:s.RG8I,r32uint:s.R32UI,r32sint:s.R32I,r32float:s.R32F,rg16uint:s.RG16UI,rg16sint:s.RG16I,rg16float:s.RG16F,rgba8unorm:s.RGBA,...e,rgba8snorm:s.RGBA8_SNORM,rgba8uint:s.RGBA8UI,rgba8sint:s.RGBA8I,bgra8unorm:r,rgb9e5ufloat:s.RGB9_E5,rgb10a2unorm:s.RGB10_A2,rg11b10ufloat:s.R11F_G11F_B10F,rg32uint:s.RG32UI,rg32sint:s.RG32I,rg32float:s.RG32F,rgba16uint:s.RGBA16UI,rgba16sint:s.RGBA16I,rgba16float:s.RGBA16F,rgba32uint:s.RGBA32UI,rgba32sint:s.RGBA32I,rgba32float:s.RGBA32F,stencil8:s.STENCIL_INDEX8,depth16unorm:s.DEPTH_COMPONENT16,depth24plus:s.DEPTH_COMPONENT24,"depth24plus-stencil8":s.DEPTH24_STENCIL8,depth32float:s.DEPTH_COMPONENT32F,"depth32float-stencil8":s.DEPTH32F_STENCIL8,...t.s3tc?{"bc1-rgba-unorm":t.s3tc.COMPRESSED_RGBA_S3TC_DXT1_EXT,"bc2-rgba-unorm":t.s3tc.COMPRESSED_RGBA_S3TC_DXT3_EXT,"bc3-rgba-unorm":t.s3tc.COMPRESSED_RGBA_S3TC_DXT5_EXT}:{},...t.s3tc_sRGB?{"bc1-rgba-unorm-srgb":t.s3tc_sRGB.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT,"bc2-rgba-unorm-srgb":t.s3tc_sRGB.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT,"bc3-rgba-unorm-srgb":t.s3tc_sRGB.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT}:{},...t.rgtc?{"bc4-r-unorm":t.rgtc.COMPRESSED_RED_RGTC1_EXT,"bc4-r-snorm":t.rgtc.COMPRESSED_SIGNED_RED_RGTC1_EXT,"bc5-rg-unorm":t.rgtc.COMPRESSED_RED_GREEN_RGTC2_EXT,"bc5-rg-snorm":t.rgtc.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT}:{},...t.bptc?{"bc6h-rgb-float":t.bptc.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT,"bc6h-rgb-ufloat":t.bptc.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT,"bc7-rgba-unorm":t.bptc.COMPRESSED_RGBA_BPTC_UNORM_EXT,"bc7-rgba-unorm-srgb":t.bptc.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT}:{},...t.etc?{"etc2-rgb8unorm":t.etc.COMPRESSED_RGB8_ETC2,"etc2-rgb8unorm-srgb":t.etc.COMPRESSED_SRGB8_ETC2,"etc2-rgb8a1unorm":t.etc.COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2,"etc2-rgb8a1unorm-srgb":t.etc.COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2,"etc2-rgba8unorm":t.etc.COMPRESSED_RGBA8_ETC2_EAC,"etc2-rgba8unorm-srgb":t.etc.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC,"eac-r11unorm":t.etc.COMPRESSED_R11_EAC,"eac-rg11unorm":t.etc.COMPRESSED_SIGNED_RG11_EAC}:{},...t.astc?{"astc-4x4-unorm":t.astc.COMPRESSED_RGBA_ASTC_4x4_KHR,"astc-4x4-unorm-srgb":t.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR,"astc-5x4-unorm":t.astc.COMPRESSED_RGBA_ASTC_5x4_KHR,"astc-5x4-unorm-srgb":t.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR,"astc-5x5-unorm":t.astc.COMPRESSED_RGBA_ASTC_5x5_KHR,"astc-5x5-unorm-srgb":t.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR,"astc-6x5-unorm":t.astc.COMPRESSED_RGBA_ASTC_6x5_KHR,"astc-6x5-unorm-srgb":t.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR,"astc-6x6-unorm":t.astc.COMPRESSED_RGBA_ASTC_6x6_KHR,"astc-6x6-unorm-srgb":t.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR,"astc-8x5-unorm":t.astc.COMPRESSED_RGBA_ASTC_8x5_KHR,"astc-8x5-unorm-srgb":t.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR,"astc-8x6-unorm":t.astc.COMPRESSED_RGBA_ASTC_8x6_KHR,"astc-8x6-unorm-srgb":t.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR,"astc-8x8-unorm":t.astc.COMPRESSED_RGBA_ASTC_8x8_KHR,"astc-8x8-unorm-srgb":t.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR,"astc-10x5-unorm":t.astc.COMPRESSED_RGBA_ASTC_10x5_KHR,"astc-10x5-unorm-srgb":t.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR,"astc-10x6-unorm":t.astc.COMPRESSED_RGBA_ASTC_10x6_KHR,"astc-10x6-unorm-srgb":t.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR,"astc-10x8-unorm":t.astc.COMPRESSED_RGBA_ASTC_10x8_KHR,"astc-10x8-unorm-srgb":t.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR,"astc-10x10-unorm":t.astc.COMPRESSED_RGBA_ASTC_10x10_KHR,"astc-10x10-unorm-srgb":t.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR,"astc-12x10-unorm":t.astc.COMPRESSED_RGBA_ASTC_12x10_KHR,"astc-12x10-unorm-srgb":t.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR,"astc-12x12-unorm":t.astc.COMPRESSED_RGBA_ASTC_12x12_KHR,"astc-12x12-unorm-srgb":t.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR}:{}}}function px(s){return{r8unorm:s.UNSIGNED_BYTE,r8snorm:s.BYTE,r8uint:s.UNSIGNED_BYTE,r8sint:s.BYTE,r16uint:s.UNSIGNED_SHORT,r16sint:s.SHORT,r16float:s.HALF_FLOAT,rg8unorm:s.UNSIGNED_BYTE,rg8snorm:s.BYTE,rg8uint:s.UNSIGNED_BYTE,rg8sint:s.BYTE,r32uint:s.UNSIGNED_INT,r32sint:s.INT,r32float:s.FLOAT,rg16uint:s.UNSIGNED_SHORT,rg16sint:s.SHORT,rg16float:s.HALF_FLOAT,rgba8unorm:s.UNSIGNED_BYTE,"rgba8unorm-srgb":s.UNSIGNED_BYTE,rgba8snorm:s.BYTE,rgba8uint:s.UNSIGNED_BYTE,rgba8sint:s.BYTE,bgra8unorm:s.UNSIGNED_BYTE,"bgra8unorm-srgb":s.UNSIGNED_BYTE,rgb9e5ufloat:s.UNSIGNED_INT_5_9_9_9_REV,rgb10a2unorm:s.UNSIGNED_INT_2_10_10_10_REV,rg11b10ufloat:s.UNSIGNED_INT_10F_11F_11F_REV,rg32uint:s.UNSIGNED_INT,rg32sint:s.INT,rg32float:s.FLOAT,rgba16uint:s.UNSIGNED_SHORT,rgba16sint:s.SHORT,rgba16float:s.HALF_FLOAT,rgba32uint:s.UNSIGNED_INT,rgba32sint:s.INT,rgba32float:s.FLOAT,stencil8:s.UNSIGNED_BYTE,depth16unorm:s.UNSIGNED_SHORT,depth24plus:s.UNSIGNED_INT,"depth24plus-stencil8":s.UNSIGNED_INT_24_8,depth32float:s.FLOAT,"depth32float-stencil8":s.FLOAT_32_UNSIGNED_INT_24_8_REV}}const mx=4;class Sc{constructor(t){this.managedTextures=[],this._glTextures=Object.create(null),this._glSamplers=Object.create(null),this._boundTextures=[],this._activeTextureLocation=-1,this._boundSamplers=Object.create(null),this._uploads={image:bc,buffer:ax,video:lx,compressed:hx},this._premultiplyAlpha=!1,this._useSeparateSamplers=!1,this._renderer=t,this._renderer.renderableGC.addManagedHash(this,"_glTextures"),this._renderer.renderableGC.addManagedHash(this,"_glSamplers")}contextChange(t){this._gl=t,this._mapFormatToInternalFormat||(this._mapFormatToInternalFormat=fx(t,this._renderer.context.extensions),this._mapFormatToType=px(t),this._mapFormatToFormat=dx(t)),this._glTextures=Object.create(null),this._glSamplers=Object.create(null),this._boundSamplers=Object.create(null),this._premultiplyAlpha=!1;for(let e=0;e<16;e++)this.bind(M.EMPTY,e)}initSource(t){this.bind(t)}bind(t,e=0){const r=t.source;t?(this.bindSource(r,e),this._useSeparateSamplers&&this._bindSampler(r.style,e)):(this.bindSource(null,e),this._useSeparateSamplers&&this._bindSampler(null,e))}bindSource(t,e=0){const r=this._gl;if(t._touched=this._renderer.textureGC.count,this._boundTextures[e]!==t){this._boundTextures[e]=t,this._activateLocation(e),t||(t=M.EMPTY.source);const n=this.getGlSource(t);r.bindTexture(n.target,n.texture)}}_bindSampler(t,e=0){const r=this._gl;if(!t){this._boundSamplers[e]=null,r.bindSampler(e,null);return}const n=this._getGlSampler(t);this._boundSamplers[e]!==n&&(this._boundSamplers[e]=n,r.bindSampler(e,n))}unbind(t){const e=t.source,r=this._boundTextures,n=this._gl;for(let a=0;a<r.length;a++)if(r[a]===e){this._activateLocation(a);const l=this.getGlSource(e);n.bindTexture(l.target,null),r[a]=null}}_activateLocation(t){this._activeTextureLocation!==t&&(this._activeTextureLocation=t,this._gl.activeTexture(this._gl.TEXTURE0+t))}_initSource(t){const e=this._gl,r=new nx(e.createTexture());if(r.type=this._mapFormatToType[t.format],r.internalFormat=this._mapFormatToInternalFormat[t.format],r.format=this._mapFormatToFormat[t.format],t.autoGenerateMipmaps&&(this._renderer.context.supports.nonPowOf2mipmaps||t.isPowerOfTwo)){const n=Math.max(t.width,t.height);t.mipLevelCount=Math.floor(Math.log2(n))+1}return this._glTextures[t.uid]=r,this.managedTextures.includes(t)||(t.on("update",this.onSourceUpdate,this),t.on("resize",this.onSourceUpdate,this),t.on("styleChange",this.onStyleChange,this),t.on("destroy",this.onSourceDestroy,this),t.on("unload",this.onSourceUnload,this),t.on("updateMipmaps",this.onUpdateMipmaps,this),this.managedTextures.push(t)),this.onSourceUpdate(t),this.updateStyle(t,!1),r}onStyleChange(t){this.updateStyle(t,!1)}updateStyle(t,e){const r=this._gl,n=this.getGlSource(t);r.bindTexture(r.TEXTURE_2D,n.texture),this._boundTextures[this._activeTextureLocation]=t,wc(t.style,r,t.mipLevelCount>1,this._renderer.context.extensions.anisotropicFiltering,"texParameteri",r.TEXTURE_2D,!this._renderer.context.supports.nonPowOf2wrapping&&!t.isPowerOfTwo,e)}onSourceUnload(t){const e=this._glTextures[t.uid];e&&(this.unbind(t),this._glTextures[t.uid]=null,this._gl.deleteTexture(e.texture))}onSourceUpdate(t){const e=this._gl,r=this.getGlSource(t);e.bindTexture(e.TEXTURE_2D,r.texture),this._boundTextures[this._activeTextureLocation]=t;const n=t.alphaMode==="premultiply-alpha-on-upload";this._premultiplyAlpha!==n&&(this._premultiplyAlpha=n,e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,n)),this._uploads[t.uploadMethodId]?this._uploads[t.uploadMethodId].upload(t,r,e,this._renderer.context.webGLVersion):e.texImage2D(e.TEXTURE_2D,0,e.RGBA,t.pixelWidth,t.pixelHeight,0,e.RGBA,e.UNSIGNED_BYTE,null),t.autoGenerateMipmaps&&t.mipLevelCount>1&&this.onUpdateMipmaps(t,!1)}onUpdateMipmaps(t,e=!0){e&&this.bindSource(t,0);const r=this.getGlSource(t);this._gl.generateMipmap(r.target)}onSourceDestroy(t){t.off("destroy",this.onSourceDestroy,this),t.off("update",this.onSourceUpdate,this),t.off("resize",this.onSourceUpdate,this),t.off("unload",this.onSourceUnload,this),t.off("styleChange",this.onStyleChange,this),t.off("updateMipmaps",this.onUpdateMipmaps,this),this.managedTextures.splice(this.managedTextures.indexOf(t),1),this.onSourceUnload(t)}_initSampler(t){const e=this._gl,r=this._gl.createSampler();return this._glSamplers[t._resourceId]=r,wc(t,e,this._boundTextures[this._activeTextureLocation].mipLevelCount>1,this._renderer.context.extensions.anisotropicFiltering,"samplerParameteri",r,!1,!0),this._glSamplers[t._resourceId]}_getGlSampler(t){return this._glSamplers[t._resourceId]||this._initSampler(t)}getGlSource(t){return this._glTextures[t.uid]||this._initSource(t)}generateCanvas(t){const{pixels:e,width:r,height:n}=this.getPixels(t),a=W.get().createCanvas();a.width=r,a.height=n;const l=a.getContext("2d");if(l){const h=l.createImageData(r,n);h.data.set(e),l.putImageData(h,0,0)}return a}getPixels(t){const e=t.source.resolution,r=t.frame,n=Math.max(Math.round(r.width*e),1),a=Math.max(Math.round(r.height*e),1),l=new Uint8Array(mx*n*a),h=this._renderer,d=h.renderTarget.getRenderTarget(t),f=h.renderTarget.getGpuRenderTarget(d),m=h.gl;return m.bindFramebuffer(m.FRAMEBUFFER,f.resolveTargetFramebuffer),m.readPixels(Math.round(r.x*e),Math.round(r.y*e),n,a,m.RGBA,m.UNSIGNED_BYTE,l),{pixels:new Uint8ClampedArray(l.buffer),width:n,height:a}}destroy(){this.managedTextures.slice().forEach(t=>this.onSourceDestroy(t)),this.managedTextures=null,this._glTextures=null,this._glSamplers=null,this._boundTextures=null,this._boundSamplers=null,this._mapFormatToInternalFormat=null,this._mapFormatToType=null,this._mapFormatToFormat=null,this._uploads=null,this._renderer=null}resetState(){this._activeTextureLocation=-1,this._boundTextures.fill(M.EMPTY.source),this._boundSamplers=Object.create(null);const t=this._gl;this._premultiplyAlpha=!1,t.pixelStorei(t.UNPACK_PREMULTIPLY_ALPHA_WEBGL,this._premultiplyAlpha)}}Sc.extension={type:[C.WebGLSystem],name:"texture"};class Tc{contextChange(t){const e=new gt({uColor:{value:new Float32Array([1,1,1,1]),type:"vec4<f32>"},uTransformMatrix:{value:new k,type:"mat3x3<f32>"},uRound:{value:0,type:"f32"}}),r=t.limits.maxBatchableTextures,n=Ui({name:"graphics",bits:[ln,fn(r),Dn,ki]});this.shader=new It({glProgram:n,resources:{localUniforms:e,batchSamplers:pn(r)}})}execute(t,e){const r=e.context,n=r.customShader||this.shader,a=t.renderer,l=a.graphicsContext,{batcher:h,instructions:d}=l.getContextRenderData(r);n.groups[0]=a.globalUniforms.bindGroup,a.state.set(t.state),a.shader.bind(n),a.geometry.bind(h.geometry,n.glProgram);const f=d.instructions;for(let m=0;m<d.instructionSize;m++){const g=f[m];if(g.size){for(let y=0;y<g.textures.count;y++)a.texture.bind(g.textures.textures[y],y);a.geometry.draw(g.topology,g.size,g.start)}}}destroy(){this.shader.destroy(!0),this.shader=null}}Tc.extension={type:[C.WebGLPipesAdaptor],name:"graphics"};class Cc{init(){const t=Ui({name:"mesh",bits:[Dn,vy,ki]});this._shader=new It({glProgram:t,resources:{uTexture:M.EMPTY.source,textureUniforms:{uTextureMatrix:{type:"mat3x3<f32>",value:new k}}}})}execute(t,e){const r=t.renderer;let n=e._shader;if(n){if(!n.glProgram){F("Mesh shader has no glProgram",e.shader);return}}else{n=this._shader;const a=e.texture,l=a.source;n.resources.uTexture=l,n.resources.uSampler=l.style,n.resources.textureUniforms.uniforms.uTextureMatrix=a.textureMatrix.mapCoord}n.groups[100]=r.globalUniforms.bindGroup,n.groups[101]=t.localUniformsBindGroup,r.encoder.draw({geometry:e._geometry,shader:n,state:e.state})}destroy(){this._shader.destroy(!0),this._shader=null}}Cc.extension={type:[C.WebGLPipesAdaptor],name:"mesh"};class Ec{constructor(t){this._renderer=t}updateRenderable(){}destroyRenderable(){}validateRenderable(){return!1}addRenderable(t,e){this._renderer.renderPipes.batch.break(e),e.add(t)}execute(t){t.isRenderable&&t.render(this._renderer)}destroy(){this._renderer=null}}Ec.extension={type:[C.WebGLPipes,C.WebGPUPipes,C.CanvasPipes],name:"customRender"};class Hr{constructor(){this.batcherName="default",this.topology="triangle-list",this.attributeSize=4,this.indexSize=6,this.packAsQuad=!0,this.roundPixels=0,this._attributeStart=0,this._batcher=null,this._batch=null}get blendMode(){return this.renderable.groupBlendMode}get color(){return this.renderable.groupColorAlpha}reset(){this.renderable=null,this.texture=null,this._batcher=null,this._batch=null,this.bounds=null}destroy(){}}function Vn(s,t){const e=s.instructionSet,r=e.instructions;for(let n=0;n<e.instructionSize;n++){const a=r[n];t[a.renderPipeId].execute(a)}}const gx=new k;class Ac{constructor(t){this._renderer=t}addRenderGroup(t,e){t.isCachedAsTexture?this._addRenderableCacheAsTexture(t,e):this._addRenderableDirect(t,e)}execute(t){t.isRenderable&&(t.isCachedAsTexture?this._executeCacheAsTexture(t):this._executeDirect(t))}destroy(){this._renderer=null}_addRenderableDirect(t,e){this._renderer.renderPipes.batch.break(e),t._batchableRenderGroup&&(at.return(t._batchableRenderGroup),t._batchableRenderGroup=null),e.add(t)}_addRenderableCacheAsTexture(t,e){const r=t._batchableRenderGroup??(t._batchableRenderGroup=at.get(Hr));r.renderable=t.root,r.transform=t.root.relativeGroupTransform,r.texture=t.texture,r.bounds=t._textureBounds,e.add(t),this._renderer.renderPipes.blendMode.pushBlendMode(t,t.root.groupBlendMode,e),this._renderer.renderPipes.batch.addToBatch(r,e),this._renderer.renderPipes.blendMode.popBlendMode(e)}_executeCacheAsTexture(t){if(t.textureNeedsUpdate){t.textureNeedsUpdate=!1;const e=gx.identity().translate(-t._textureBounds.x,-t._textureBounds.y);this._renderer.renderTarget.push(t.texture,!0,null,t.texture.frame),this._renderer.globalUniforms.push({worldTransformMatrix:e,worldColor:4294967295,offset:{x:0,y:0}}),Vn(t,this._renderer.renderPipes),this._renderer.renderTarget.finishRenderPass(),this._renderer.renderTarget.pop(),this._renderer.globalUniforms.pop()}t._batchableRenderGroup._batcher.updateElement(t._batchableRenderGroup),t._batchableRenderGroup._batcher.geometry.buffers[0].update()}_executeDirect(t){this._renderer.globalUniforms.push({worldTransformMatrix:t.inverseParentTextureTransform,worldColor:t.worldColorAlpha}),Vn(t,this._renderer.renderPipes),this._renderer.globalUniforms.pop()}}Ac.extension={type:[C.WebGLPipes,C.WebGPUPipes,C.CanvasPipes],name:"renderGroup"};function Yn(s,t){t||(t=0);for(let e=t;e<s.length&&s[e];e++)s[e]=null}const _x=new ot,Pc=ui|pr|Us;function Bc(s,t=!1){yx(s);const e=s.childrenToUpdate,r=s.updateTick++;for(const n in e){const a=Number(n),l=e[n],h=l.list,d=l.index;for(let f=0;f<d;f++){const m=h[f];m.parentRenderGroup===s&&m.relativeRenderGroupDepth===a&&Uc(m,r,0)}Yn(h,d),l.index=0}if(t)for(let n=0;n<s.renderGroupChildren.length;n++)Bc(s.renderGroupChildren[n],t)}function yx(s){const t=s.root;let e;if(s.renderGroupParent){const r=s.renderGroupParent;s.worldTransform.appendFrom(t.relativeGroupTransform,r.worldTransform),s.worldColor=cr(t.groupColor,r.worldColor),e=t.groupAlpha*r.worldAlpha}else s.worldTransform.copyFrom(t.localTransform),s.worldColor=t.localColor,e=t.localAlpha;e=e<0?0:e>1?1:e,s.worldAlpha=e,s.worldColorAlpha=s.worldColor+((e*255|0)<<24)}function Uc(s,t,e){if(t===s.updateTick)return;s.updateTick=t,s.didChange=!1;const r=s.localTransform;s.updateLocalTransform();const n=s.parent;if(n&&!n.renderGroup?(e|=s._updateFlags,s.relativeGroupTransform.appendFrom(r,n.relativeGroupTransform),e&Pc&&Mc(s,n,e)):(e=s._updateFlags,s.relativeGroupTransform.copyFrom(r),e&Pc&&Mc(s,_x,e)),!s.renderGroup){const a=s.children,l=a.length;for(let f=0;f<l;f++)Uc(a[f],t,e);const h=s.parentRenderGroup,d=s;d.renderPipeId&&!h.structureDidChange&&h.updateRenderable(d)}}function Mc(s,t,e){if(e&pr){s.groupColor=cr(s.localColor,t.groupColor);let r=s.localAlpha*t.groupAlpha;r=r<0?0:r>1?1:r,s.groupAlpha=r,s.groupColorAlpha=s.groupColor+((r*255|0)<<24)}e&Us&&(s.groupBlendMode=s.localBlendMode==="inherit"?t.groupBlendMode:s.localBlendMode),e&ui&&(s.globalDisplayStatus=s.localDisplayStatus&t.globalDisplayStatus),s._updateFlags=0}function xx(s,t){const{list:e}=s.childrenRenderablesToUpdate;let r=!1;for(let n=0;n<s.childrenRenderablesToUpdate.index;n++){const a=e[n];if(r=t[a.renderPipeId].validateRenderable(a),r)break}return s.structureDidChange=r,r}const bx=new k;class kc{constructor(t){this._renderer=t}render({container:t,transform:e}){const r=t.parent,n=t.renderGroup.renderGroupParent;t.parent=null,t.renderGroup.renderGroupParent=null;const a=this._renderer,l=bx;e&&(l.copyFrom(t.renderGroup.localTransform),t.renderGroup.localTransform.copyFrom(e));const h=a.renderPipes;this._updateCachedRenderGroups(t.renderGroup,null),this._updateRenderGroups(t.renderGroup),a.globalUniforms.start({worldTransformMatrix:e?t.renderGroup.localTransform:t.renderGroup.worldTransform,worldColor:t.renderGroup.worldColorAlpha}),Vn(t.renderGroup,h),h.uniformBatch&&h.uniformBatch.renderEnd(),e&&t.renderGroup.localTransform.copyFrom(l),t.parent=r,t.renderGroup.renderGroupParent=n}destroy(){this._renderer=null}_updateCachedRenderGroups(t,e){if(t._parentCacheAsTextureRenderGroup=e,t.isCachedAsTexture){if(!t.textureNeedsUpdate)return;e=t}for(let r=t.renderGroupChildren.length-1;r>=0;r--)this._updateCachedRenderGroups(t.renderGroupChildren[r],e);if(t.invalidateMatrices(),t.isCachedAsTexture){if(t.textureNeedsUpdate){const r=t.root.getLocalBounds();r.ceil();const n=t.texture;t.texture&&ut.returnTexture(t.texture,!0);const a=this._renderer,l=t.textureOptions.resolution||a.view.resolution,h=t.textureOptions.antialias??a.view.antialias,d=t.textureOptions.scaleMode??"linear",f=ut.getOptimalTexture(r.width,r.height,l,h);f._source.style=new Kt({scaleMode:d}),t.texture=f,t._textureBounds||(t._textureBounds=new dt),t._textureBounds.copyFrom(r),n!==t.texture&&t.renderGroupParent&&(t.renderGroupParent.structureDidChange=!0)}}else t.texture&&(ut.returnTexture(t.texture,!0),t.texture=null)}_updateRenderGroups(t){const e=this._renderer,r=e.renderPipes;if(t.runOnRender(e),t.instructionSet.renderPipes=r,t.structureDidChange?Yn(t.childrenRenderablesToUpdate.list,0):xx(t,r),Bc(t),t.structureDidChange?(t.structureDidChange=!1,this._buildInstructions(t,e)):this._updateRenderables(t),t.childrenRenderablesToUpdate.index=0,e.renderPipes.batch.upload(t.instructionSet),!(t.isCachedAsTexture&&!t.textureNeedsUpdate))for(let n=0;n<t.renderGroupChildren.length;n++)this._updateRenderGroups(t.renderGroupChildren[n])}_updateRenderables(t){const{list:e,index:r}=t.childrenRenderablesToUpdate;for(let n=0;n<r;n++){const a=e[n];a.didViewUpdate&&t.updateRenderable(a)}Yn(e,r)}_buildInstructions(t,e){const r=t.root,n=t.instructionSet;n.reset();const a=e.renderPipes?e:e.batch.renderer,l=a.renderPipes;l.batch.buildStart(n),l.blendMode.buildStart(),l.colorMask.buildStart(),r.sortableChildren&&r.sortChildren(),r.collectRenderablesWithEffects(n,a,null),l.batch.buildEnd(n),l.blendMode.buildEnd(n)}}kc.extension={type:[C.WebGLSystem,C.WebGPUSystem,C.CanvasSystem],name:"renderGroup"};class Rc{constructor(t){this._renderer=t}addRenderable(t,e){const r=this._getGpuSprite(t);t.didViewUpdate&&this._updateBatchableSprite(t,r),this._renderer.renderPipes.batch.addToBatch(r,e)}updateRenderable(t){const e=this._getGpuSprite(t);t.didViewUpdate&&this._updateBatchableSprite(t,e),e._batcher.updateElement(e)}validateRenderable(t){const e=this._getGpuSprite(t);return!e._batcher.checkAndUpdateTexture(e,t._texture)}_updateBatchableSprite(t,e){e.bounds=t.visualBounds,e.texture=t._texture}_getGpuSprite(t){return t._gpuData[this._renderer.uid]||this._initGPUSprite(t)}_initGPUSprite(t){const e=new Hr;return e.renderable=t,e.transform=t.groupTransform,e.texture=t._texture,e.bounds=t.visualBounds,e.roundPixels=this._renderer._roundPixels|t._roundPixels,t._gpuData[this._renderer.uid]=e,e}destroy(){this._renderer=null}}Rc.extension={type:[C.WebGLPipes,C.WebGPUPipes,C.CanvasPipes],name:"sprite"};const Xn=class ad{constructor(){this.clearBeforeRender=!0,this._backgroundColor=new J(0),this.color=this._backgroundColor,this.alpha=1}init(t){t={...ad.defaultOptions,...t},this.clearBeforeRender=t.clearBeforeRender,this.color=t.background||t.backgroundColor||this._backgroundColor,this.alpha=t.backgroundAlpha,this._backgroundColor.setAlpha(t.backgroundAlpha)}get color(){return this._backgroundColor}set color(t){J.shared.setValue(t).alpha<1&&this._backgroundColor.alpha===1&&F("Cannot set a transparent background on an opaque canvas. To enable transparency, set backgroundAlpha < 1 when initializing your Application."),this._backgroundColor.setValue(t)}get alpha(){return this._backgroundColor.alpha}set alpha(t){this._backgroundColor.setAlpha(t)}get colorRgba(){return this._backgroundColor.toArray()}destroy(){}};Xn.extension={type:[C.WebGLSystem,C.WebGPUSystem,C.CanvasSystem],name:"background",priority:0},Xn.defaultOptions={backgroundAlpha:1,backgroundColor:0,clearBeforeRender:!0};let vx=Xn;const Hi={};D.handle(C.BlendMode,s=>{if(!s.name)throw new Error("BlendMode extension must have a name property");Hi[s.name]=s.ref},s=>{delete Hi[s.name]});class Ic{constructor(t){this._blendModeStack=[],this._isAdvanced=!1,this._filterHash=Object.create(null),this._renderer=t,this._renderer.runners.prerender.add(this)}prerender(){this._activeBlendMode="normal",this._isAdvanced=!1}pushBlendMode(t,e,r){this._blendModeStack.push(e),this.setBlendMode(t,e,r)}popBlendMode(t){this._blendModeStack.pop();const e=this._blendModeStack[this._activeBlendMode.length-1]??"normal";this.setBlendMode(null,e,t)}setBlendMode(t,e,r){const n=t instanceof As;if(this._activeBlendMode===e){this._isAdvanced&&t&&!n&&this._renderableList?.push(t);return}this._isAdvanced&&this._endAdvancedBlendMode(r),this._activeBlendMode=e,t&&(this._isAdvanced=!!Hi[e],this._isAdvanced&&this._beginAdvancedBlendMode(t,r))}_beginAdvancedBlendMode(t,e){this._renderer.renderPipes.batch.break(e);const r=this._activeBlendMode;if(!Hi[r]){F(`Unable to assign BlendMode: '${r}'. You may want to include: import 'pixi.js/advanced-blend-modes'`);return}const n=this._ensureFilterEffect(r),a=t instanceof As,l={renderPipeId:"filter",action:"pushFilter",filterEffect:n,renderables:a?null:[t],container:a?t.root:null,canBundle:!1};this._renderableList=l.renderables,e.add(l)}_ensureFilterEffect(t){let e=this._filterHash[t];return e||(e=this._filterHash[t]=new lr,e.filters=[new Hi[t]]),e}_endAdvancedBlendMode(t){this._isAdvanced=!1,this._renderableList=null,this._renderer.renderPipes.batch.break(t),t.add({renderPipeId:"filter",action:"popFilter",canBundle:!1})}buildStart(){this._isAdvanced=!1}buildEnd(t){this._isAdvanced&&this._endAdvancedBlendMode(t)}destroy(){this._renderer=null,this._renderableList=null;for(const t in this._filterHash)this._filterHash[t].destroy();this._filterHash=null}}Ic.extension={type:[C.WebGLPipes,C.WebGPUPipes,C.CanvasPipes],name:"blendMode"};const $n={png:"image/png",jpg:"image/jpeg",webp:"image/webp"},Kn=class od{constructor(t){this._renderer=t}_normalizeOptions(t,e={}){return t instanceof ot||t instanceof M?{target:t,...e}:{...e,...t}}async image(t){const e=W.get().createImage();return e.src=await this.base64(t),e}async base64(t){t=this._normalizeOptions(t,od.defaultImageOptions);const{format:e,quality:r}=t,n=this.canvas(t);if(n.toBlob!==void 0)return new Promise((a,l)=>{n.toBlob(h=>{if(!h){l(new Error("ICanvas.toBlob failed!"));return}const d=new FileReader;d.onload=()=>a(d.result),d.onerror=l,d.readAsDataURL(h)},$n[e],r)});if(n.toDataURL!==void 0)return n.toDataURL($n[e],r);if(n.convertToBlob!==void 0){const a=await n.convertToBlob({type:$n[e],quality:r});return new Promise((l,h)=>{const d=new FileReader;d.onload=()=>l(d.result),d.onerror=h,d.readAsDataURL(a)})}throw new Error("Extract.base64() requires ICanvas.toDataURL, ICanvas.toBlob, or ICanvas.convertToBlob to be implemented")}canvas(t){t=this._normalizeOptions(t);const e=t.target,r=this._renderer;if(e instanceof M)return r.texture.generateCanvas(e);const n=r.textureGenerator.generateTexture(t),a=r.texture.generateCanvas(n);return n.destroy(!0),a}pixels(t){t=this._normalizeOptions(t);const e=t.target,r=this._renderer,n=e instanceof M?e:r.textureGenerator.generateTexture(t),a=r.texture.getPixels(n);return e instanceof ot&&n.destroy(!0),a}texture(t){return t=this._normalizeOptions(t),t.target instanceof M?t.target:this._renderer.textureGenerator.generateTexture(t)}download(t){t=this._normalizeOptions(t);const e=this.canvas(t),r=document.createElement("a");r.download=t.filename??"image.png",r.href=e.toDataURL("image/png"),document.body.appendChild(r),r.click(),document.body.removeChild(r)}log(t){const e=t.width??200;t=this._normalizeOptions(t);const r=this.canvas(t),n=r.toDataURL();console.log(`[Pixi Texture] ${r.width}px ${r.height}px`);const a=["font-size: 1px;",`padding: ${e}px 300px;`,`background: url(${n}) no-repeat;`,"background-size: contain;"].join(" ");console.log("%c ",a)}destroy(){this._renderer=null}};Kn.extension={type:[C.WebGLSystem,C.WebGPUSystem],name:"extract"},Kn.defaultImageOptions={format:"png",quality:1};let wx=Kn;class Wi extends M{static create(t){return new Wi({source:new ht(t)})}resize(t,e,r){return this.source.resize(t,e,r),this}}const Sx=new L,Tx=new dt,Cx=[0,0,0,0];class Fc{constructor(t){this._renderer=t}generateTexture(t){t instanceof ot&&(t={target:t,frame:void 0,textureSourceOptions:{},resolution:void 0});const e=t.resolution||this._renderer.resolution,r=t.antialias||this._renderer.view.antialias,n=t.target;let a=t.clearColor;a?a=Array.isArray(a)&&a.length===4?a:J.shared.setValue(a).toArray():a=Cx;const l=t.frame?.copyTo(Sx)||Es(n,Tx).rectangle;l.width=Math.max(l.width,1/e)|0,l.height=Math.max(l.height,1/e)|0;const h=Wi.create({...t.textureSourceOptions,width:l.width,height:l.height,resolution:e,antialias:r}),d=k.shared.translate(-l.x,-l.y);return this._renderer.render({container:n,transform:d,target:h,clearColor:a}),h.source.updateMipmaps(),h}destroy(){this._renderer=null}}Fc.extension={type:[C.WebGLSystem,C.WebGPUSystem],name:"textureGenerator"};function Vi(s,t,e){const r=(s>>24&255)/255;t[e++]=(s&255)/255*r,t[e++]=(s>>8&255)/255*r,t[e++]=(s>>16&255)/255*r,t[e++]=r}class Dc{constructor(t){this._stackIndex=0,this._globalUniformDataStack=[],this._uniformsPool=[],this._activeUniforms=[],this._bindGroupPool=[],this._activeBindGroups=[],this._renderer=t}reset(){this._stackIndex=0;for(let t=0;t<this._activeUniforms.length;t++)this._uniformsPool.push(this._activeUniforms[t]);for(let t=0;t<this._activeBindGroups.length;t++)this._bindGroupPool.push(this._activeBindGroups[t]);this._activeUniforms.length=0,this._activeBindGroups.length=0}start(t){this.reset(),this.push(t)}bind({size:t,projectionMatrix:e,worldTransformMatrix:r,worldColor:n,offset:a}){const l=this._renderer.renderTarget.renderTarget,h=this._stackIndex?this._globalUniformDataStack[this._stackIndex-1]:{worldTransformMatrix:new k,worldColor:4294967295,offset:new q},d={projectionMatrix:e||this._renderer.renderTarget.projectionMatrix,resolution:t||l.size,worldTransformMatrix:r||h.worldTransformMatrix,worldColor:n||h.worldColor,offset:a||h.offset,bindGroup:null},f=this._uniformsPool.pop()||this._createUniforms();this._activeUniforms.push(f);const m=f.uniforms;m.uProjectionMatrix=d.projectionMatrix,m.uResolution=d.resolution,m.uWorldTransformMatrix.copyFrom(d.worldTransformMatrix),m.uWorldTransformMatrix.tx-=d.offset.x,m.uWorldTransformMatrix.ty-=d.offset.y,Vi(d.worldColor,m.uWorldColorAlpha,0),f.update();let g;this._renderer.renderPipes.uniformBatch?g=this._renderer.renderPipes.uniformBatch.getUniformBindGroup(f,!1):(g=this._bindGroupPool.pop()||new re,this._activeBindGroups.push(g),g.setResource(f,0)),d.bindGroup=g,this._currentGlobalUniformData=d}push(t){this.bind(t),this._globalUniformDataStack[this._stackIndex++]=this._currentGlobalUniformData}pop(){this._currentGlobalUniformData=this._globalUniformDataStack[--this._stackIndex-1],this._renderer.type===Nt.WEBGL&&this._currentGlobalUniformData.bindGroup.resources[0].update()}get bindGroup(){return this._currentGlobalUniformData.bindGroup}get globalUniformData(){return this._currentGlobalUniformData}get uniformGroup(){return this._currentGlobalUniformData.bindGroup.resources[0]}_createUniforms(){return new gt({uProjectionMatrix:{value:new k,type:"mat3x3<f32>"},uWorldTransformMatrix:{value:new k,type:"mat3x3<f32>"},uWorldColorAlpha:{value:new Float32Array(4),type:"vec4<f32>"},uResolution:{value:[0,0],type:"vec2<f32>"}},{isStatic:!0})}destroy(){this._renderer=null,this._globalUniformDataStack.length=0,this._uniformsPool.length=0,this._activeUniforms.length=0,this._bindGroupPool.length=0,this._activeBindGroups.length=0,this._currentGlobalUniformData=null}}Dc.extension={type:[C.WebGLSystem,C.WebGPUSystem,C.CanvasSystem],name:"globalUniforms"};let Ex=1;class Gc{constructor(){this._tasks=[],this._offset=0}init(){Ct.system.add(this._update,this)}repeat(t,e,r=!0){const n=Ex++;let a=0;return r&&(this._offset+=1e3,a=this._offset),this._tasks.push({func:t,duration:e,start:performance.now(),offset:a,last:performance.now(),repeat:!0,id:n}),n}cancel(t){for(let e=0;e<this._tasks.length;e++)if(this._tasks[e].id===t){this._tasks.splice(e,1);return}}_update(){const t=performance.now();for(let e=0;e<this._tasks.length;e++){const r=this._tasks[e];if(t-r.offset-r.last>=r.duration){const n=t-r.start;r.func(n),r.last=t}}}destroy(){Ct.system.remove(this._update,this),this._tasks.length=0}}Gc.extension={type:[C.WebGLSystem,C.WebGPUSystem,C.CanvasSystem],name:"scheduler",priority:0};let Oc=!1;function Ax(s){if(!Oc){if(W.get().getNavigator().userAgent.toLowerCase().indexOf("chrome")>-1){const t=[`%c %c %c %c %c PixiJS %c v${Cr} (${s}) http://www.pixijs.com/
|
|
961
|
+
`))}class wc{constructor(t){this._cache={},this._uniformGroupSyncHash={},this._renderer=t,this.gl=null,this._cache={}}contextChange(t){this.gl=t}updateUniformGroup(t,e,r){const n=this._renderer.shader._getProgramData(e);(!t.isStatic||t._dirtyId!==n.uniformDirtyGroups[t.uid])&&(n.uniformDirtyGroups[t.uid]=t._dirtyId,this._getUniformSyncFunction(t,e)(n.uniformData,t.uniforms,this._renderer,r))}_getUniformSyncFunction(t,e){return this._uniformGroupSyncHash[t._signature]?.[e._key]||this._createUniformSyncFunction(t,e)}_createUniformSyncFunction(t,e){const r=this._uniformGroupSyncHash[t._signature]||(this._uniformGroupSyncHash[t._signature]={}),n=this._getSignature(t,e._uniformData,"u");return this._cache[n]||(this._cache[n]=this._generateUniformsSync(t,e._uniformData)),r[e._key]=this._cache[n],r[e._key]}_generateUniformsSync(t,e){return nx(t,e)}_getSignature(t,e,r){const n=t.uniforms,o=[`${r}-`];for(const l in n)o.push(l),e[l]&&o.push(e[l].type);return o.join("-")}destroy(){this._renderer=null,this._cache=null}}wc.extension={type:[C.WebGLSystem],name:"uniformGroup"};function ox(s){const t={};if(t.normal=[s.ONE,s.ONE_MINUS_SRC_ALPHA],t.add=[s.ONE,s.ONE],t.multiply=[s.DST_COLOR,s.ONE_MINUS_SRC_ALPHA,s.ONE,s.ONE_MINUS_SRC_ALPHA],t.screen=[s.ONE,s.ONE_MINUS_SRC_COLOR,s.ONE,s.ONE_MINUS_SRC_ALPHA],t.none=[0,0],t["normal-npm"]=[s.SRC_ALPHA,s.ONE_MINUS_SRC_ALPHA,s.ONE,s.ONE_MINUS_SRC_ALPHA],t["add-npm"]=[s.SRC_ALPHA,s.ONE,s.ONE,s.ONE],t["screen-npm"]=[s.SRC_ALPHA,s.ONE_MINUS_SRC_COLOR,s.ONE,s.ONE_MINUS_SRC_ALPHA],t.erase=[s.ZERO,s.ONE_MINUS_SRC_ALPHA],!(s instanceof W.get().getWebGLRenderingContext()))t.min=[s.ONE,s.ONE,s.ONE,s.ONE,s.MIN,s.MIN],t.max=[s.ONE,s.ONE,s.ONE,s.ONE,s.MAX,s.MAX];else{const r=s.getExtension("EXT_blend_minmax");r&&(t.min=[s.ONE,s.ONE,s.ONE,s.ONE,r.MIN_EXT,r.MIN_EXT],t.max=[s.ONE,s.ONE,s.ONE,s.ONE,r.MAX_EXT,r.MAX_EXT])}return t}const ax=0,hx=1,lx=2,cx=3,dx=4,ux=5,Sc=class To{constructor(t){this._invertFrontFace=!1,this.gl=null,this.stateId=0,this.polygonOffset=0,this.blendMode="none",this._blendEq=!1,this.map=[],this.map[ax]=this.setBlend,this.map[hx]=this.setOffset,this.map[lx]=this.setCullFace,this.map[cx]=this.setDepthTest,this.map[dx]=this.setFrontFace,this.map[ux]=this.setDepthMask,this.checks=[],this.defaultState=Ht.for2d(),t.renderTarget.onRenderTargetChange.add(this)}onRenderTargetChange(t){this._invertFrontFace=!t.isRoot,this._cullFace?this.setFrontFace(this._frontFace):this._frontFaceDirty=!0}contextChange(t){this.gl=t,this.blendModesMap=ox(t),this.resetState()}set(t){if(t||(t=this.defaultState),this.stateId!==t.data){let e=this.stateId^t.data,r=0;for(;e;)e&1&&this.map[r].call(this,!!(t.data&1<<r)),e>>=1,r++;this.stateId=t.data}for(let e=0;e<this.checks.length;e++)this.checks[e](this,t)}forceState(t){t||(t=this.defaultState);for(let e=0;e<this.map.length;e++)this.map[e].call(this,!!(t.data&1<<e));for(let e=0;e<this.checks.length;e++)this.checks[e](this,t);this.stateId=t.data}setBlend(t){this._updateCheck(To._checkBlendMode,t),this.gl[t?"enable":"disable"](this.gl.BLEND)}setOffset(t){this._updateCheck(To._checkPolygonOffset,t),this.gl[t?"enable":"disable"](this.gl.POLYGON_OFFSET_FILL)}setDepthTest(t){this.gl[t?"enable":"disable"](this.gl.DEPTH_TEST)}setDepthMask(t){this.gl.depthMask(t)}setCullFace(t){this._cullFace=t,this.gl[t?"enable":"disable"](this.gl.CULL_FACE),this._cullFace&&this._frontFaceDirty&&this.setFrontFace(this._frontFace)}setFrontFace(t){this._frontFace=t,this._frontFaceDirty=!1;const e=this._invertFrontFace?!t:t;this._glFrontFace!==e&&(this._glFrontFace=e,this.gl.frontFace(this.gl[e?"CW":"CCW"]))}setBlendMode(t){if(this.blendModesMap[t]||(t="normal"),t===this.blendMode)return;this.blendMode=t;const e=this.blendModesMap[t],r=this.gl;e.length===2?r.blendFunc(e[0],e[1]):r.blendFuncSeparate(e[0],e[1],e[2],e[3]),e.length===6?(this._blendEq=!0,r.blendEquationSeparate(e[4],e[5])):this._blendEq&&(this._blendEq=!1,r.blendEquationSeparate(r.FUNC_ADD,r.FUNC_ADD))}setPolygonOffset(t,e){this.gl.polygonOffset(t,e)}resetState(){this._glFrontFace=!1,this._frontFace=!1,this._cullFace=!1,this._frontFaceDirty=!1,this._invertFrontFace=!1,this.gl.frontFace(this.gl.CCW),this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,!1),this.forceState(this.defaultState),this._blendEq=!0,this.blendMode="",this.setBlendMode("normal")}_updateCheck(t,e){const r=this.checks.indexOf(t);e&&r===-1?this.checks.push(t):!e&&r!==-1&&this.checks.splice(r,1)}static _checkBlendMode(t,e){t.setBlendMode(e.blendMode)}static _checkPolygonOffset(t,e){t.setPolygonOffset(1,e.polygonOffset)}destroy(){this.gl=null,this.checks.length=0}};Sc.extension={type:[C.WebGLSystem],name:"state"};let fx=Sc;class px{constructor(t){this.target=tc.TEXTURE_2D,this.texture=t,this.width=-1,this.height=-1,this.type=K.UNSIGNED_BYTE,this.internalFormat=Nn.RGBA,this.format=Nn.RGBA,this.samplerType=0}}const mx={id:"buffer",upload(s,t,e){t.width===s.width||t.height===s.height?e.texSubImage2D(e.TEXTURE_2D,0,0,0,s.width,s.height,t.format,t.type,s.resource):e.texImage2D(t.target,0,t.internalFormat,s.width,s.height,0,t.format,t.type,s.resource),t.width=s.width,t.height=s.height}},gx={"bc1-rgba-unorm":!0,"bc1-rgba-unorm-srgb":!0,"bc2-rgba-unorm":!0,"bc2-rgba-unorm-srgb":!0,"bc3-rgba-unorm":!0,"bc3-rgba-unorm-srgb":!0,"bc4-r-unorm":!0,"bc4-r-snorm":!0,"bc5-rg-unorm":!0,"bc5-rg-snorm":!0,"bc6h-rgb-ufloat":!0,"bc6h-rgb-float":!0,"bc7-rgba-unorm":!0,"bc7-rgba-unorm-srgb":!0,"etc2-rgb8unorm":!0,"etc2-rgb8unorm-srgb":!0,"etc2-rgb8a1unorm":!0,"etc2-rgb8a1unorm-srgb":!0,"etc2-rgba8unorm":!0,"etc2-rgba8unorm-srgb":!0,"eac-r11unorm":!0,"eac-r11snorm":!0,"eac-rg11unorm":!0,"eac-rg11snorm":!0,"astc-4x4-unorm":!0,"astc-4x4-unorm-srgb":!0,"astc-5x4-unorm":!0,"astc-5x4-unorm-srgb":!0,"astc-5x5-unorm":!0,"astc-5x5-unorm-srgb":!0,"astc-6x5-unorm":!0,"astc-6x5-unorm-srgb":!0,"astc-6x6-unorm":!0,"astc-6x6-unorm-srgb":!0,"astc-8x5-unorm":!0,"astc-8x5-unorm-srgb":!0,"astc-8x6-unorm":!0,"astc-8x6-unorm-srgb":!0,"astc-8x8-unorm":!0,"astc-8x8-unorm-srgb":!0,"astc-10x5-unorm":!0,"astc-10x5-unorm-srgb":!0,"astc-10x6-unorm":!0,"astc-10x6-unorm-srgb":!0,"astc-10x8-unorm":!0,"astc-10x8-unorm-srgb":!0,"astc-10x10-unorm":!0,"astc-10x10-unorm-srgb":!0,"astc-12x10-unorm":!0,"astc-12x10-unorm-srgb":!0,"astc-12x12-unorm":!0,"astc-12x12-unorm-srgb":!0},_x={id:"compressed",upload(s,t,e){e.pixelStorei(e.UNPACK_ALIGNMENT,4);let r=s.pixelWidth,n=s.pixelHeight;const o=!!gx[s.format];for(let l=0;l<s.resource.length;l++){const h=s.resource[l];o?e.compressedTexImage2D(e.TEXTURE_2D,l,t.internalFormat,r,n,0,h):e.texImage2D(e.TEXTURE_2D,l,t.internalFormat,r,n,0,t.format,t.type,h),r=Math.max(r>>1,1),n=Math.max(n>>1,1)}}},Tc={id:"image",upload(s,t,e,r){const n=t.width,o=t.height,l=s.pixelWidth,h=s.pixelHeight,u=s.resourceWidth,f=s.resourceHeight;u<l||f<h?((n!==l||o!==h)&&e.texImage2D(t.target,0,t.internalFormat,l,h,0,t.format,t.type,null),r===2?e.texSubImage2D(e.TEXTURE_2D,0,0,0,u,f,t.format,t.type,s.resource):e.texSubImage2D(e.TEXTURE_2D,0,0,0,t.format,t.type,s.resource)):n===l&&o===h?e.texSubImage2D(e.TEXTURE_2D,0,0,0,t.format,t.type,s.resource):r===2?e.texImage2D(t.target,0,t.internalFormat,l,h,0,t.format,t.type,s.resource):e.texImage2D(t.target,0,t.internalFormat,t.format,t.type,s.resource),t.width=l,t.height=h}},yx={id:"video",upload(s,t,e,r){if(!s.isValid){e.texImage2D(t.target,0,t.internalFormat,1,1,0,t.format,t.type,null);return}Tc.upload(s,t,e,r)}},Cc={linear:9729,nearest:9728},xx={linear:{linear:9987,nearest:9985},nearest:{linear:9986,nearest:9984}},Xn={"clamp-to-edge":33071,repeat:10497,"mirror-repeat":33648},bx={never:512,less:513,equal:514,"less-equal":515,greater:516,"not-equal":517,"greater-equal":518,always:519};function Ec(s,t,e,r,n,o,l,h){const u=o;if(!h||s.addressModeU!=="repeat"||s.addressModeV!=="repeat"||s.addressModeW!=="repeat"){const f=Xn[l?"clamp-to-edge":s.addressModeU],m=Xn[l?"clamp-to-edge":s.addressModeV],g=Xn[l?"clamp-to-edge":s.addressModeW];t[n](u,t.TEXTURE_WRAP_S,f),t[n](u,t.TEXTURE_WRAP_T,m),t.TEXTURE_WRAP_R&&t[n](u,t.TEXTURE_WRAP_R,g)}if((!h||s.magFilter!=="linear")&&t[n](u,t.TEXTURE_MAG_FILTER,Cc[s.magFilter]),e){if(!h||s.mipmapFilter!=="linear"){const f=xx[s.minFilter][s.mipmapFilter];t[n](u,t.TEXTURE_MIN_FILTER,f)}}else t[n](u,t.TEXTURE_MIN_FILTER,Cc[s.minFilter]);if(r&&s.maxAnisotropy>1){const f=Math.min(s.maxAnisotropy,t.getParameter(r.MAX_TEXTURE_MAX_ANISOTROPY_EXT));t[n](u,r.TEXTURE_MAX_ANISOTROPY_EXT,f)}s.compare&&t[n](u,t.TEXTURE_COMPARE_FUNC,bx[s.compare])}function vx(s){return{r8unorm:s.RED,r8snorm:s.RED,r8uint:s.RED,r8sint:s.RED,r16uint:s.RED,r16sint:s.RED,r16float:s.RED,rg8unorm:s.RG,rg8snorm:s.RG,rg8uint:s.RG,rg8sint:s.RG,r32uint:s.RED,r32sint:s.RED,r32float:s.RED,rg16uint:s.RG,rg16sint:s.RG,rg16float:s.RG,rgba8unorm:s.RGBA,"rgba8unorm-srgb":s.RGBA,rgba8snorm:s.RGBA,rgba8uint:s.RGBA,rgba8sint:s.RGBA,bgra8unorm:s.RGBA,"bgra8unorm-srgb":s.RGBA,rgb9e5ufloat:s.RGB,rgb10a2unorm:s.RGBA,rg11b10ufloat:s.RGB,rg32uint:s.RG,rg32sint:s.RG,rg32float:s.RG,rgba16uint:s.RGBA,rgba16sint:s.RGBA,rgba16float:s.RGBA,rgba32uint:s.RGBA,rgba32sint:s.RGBA,rgba32float:s.RGBA,stencil8:s.STENCIL_INDEX8,depth16unorm:s.DEPTH_COMPONENT,depth24plus:s.DEPTH_COMPONENT,"depth24plus-stencil8":s.DEPTH_STENCIL,depth32float:s.DEPTH_COMPONENT,"depth32float-stencil8":s.DEPTH_STENCIL}}function wx(s,t){let e={},r=s.RGBA;return s instanceof W.get().getWebGLRenderingContext()?t.srgb&&(e={"rgba8unorm-srgb":t.srgb.SRGB8_ALPHA8_EXT,"bgra8unorm-srgb":t.srgb.SRGB8_ALPHA8_EXT}):(e={"rgba8unorm-srgb":s.SRGB8_ALPHA8,"bgra8unorm-srgb":s.SRGB8_ALPHA8},r=s.RGBA8),{r8unorm:s.R8,r8snorm:s.R8_SNORM,r8uint:s.R8UI,r8sint:s.R8I,r16uint:s.R16UI,r16sint:s.R16I,r16float:s.R16F,rg8unorm:s.RG8,rg8snorm:s.RG8_SNORM,rg8uint:s.RG8UI,rg8sint:s.RG8I,r32uint:s.R32UI,r32sint:s.R32I,r32float:s.R32F,rg16uint:s.RG16UI,rg16sint:s.RG16I,rg16float:s.RG16F,rgba8unorm:s.RGBA,...e,rgba8snorm:s.RGBA8_SNORM,rgba8uint:s.RGBA8UI,rgba8sint:s.RGBA8I,bgra8unorm:r,rgb9e5ufloat:s.RGB9_E5,rgb10a2unorm:s.RGB10_A2,rg11b10ufloat:s.R11F_G11F_B10F,rg32uint:s.RG32UI,rg32sint:s.RG32I,rg32float:s.RG32F,rgba16uint:s.RGBA16UI,rgba16sint:s.RGBA16I,rgba16float:s.RGBA16F,rgba32uint:s.RGBA32UI,rgba32sint:s.RGBA32I,rgba32float:s.RGBA32F,stencil8:s.STENCIL_INDEX8,depth16unorm:s.DEPTH_COMPONENT16,depth24plus:s.DEPTH_COMPONENT24,"depth24plus-stencil8":s.DEPTH24_STENCIL8,depth32float:s.DEPTH_COMPONENT32F,"depth32float-stencil8":s.DEPTH32F_STENCIL8,...t.s3tc?{"bc1-rgba-unorm":t.s3tc.COMPRESSED_RGBA_S3TC_DXT1_EXT,"bc2-rgba-unorm":t.s3tc.COMPRESSED_RGBA_S3TC_DXT3_EXT,"bc3-rgba-unorm":t.s3tc.COMPRESSED_RGBA_S3TC_DXT5_EXT}:{},...t.s3tc_sRGB?{"bc1-rgba-unorm-srgb":t.s3tc_sRGB.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT,"bc2-rgba-unorm-srgb":t.s3tc_sRGB.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT,"bc3-rgba-unorm-srgb":t.s3tc_sRGB.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT}:{},...t.rgtc?{"bc4-r-unorm":t.rgtc.COMPRESSED_RED_RGTC1_EXT,"bc4-r-snorm":t.rgtc.COMPRESSED_SIGNED_RED_RGTC1_EXT,"bc5-rg-unorm":t.rgtc.COMPRESSED_RED_GREEN_RGTC2_EXT,"bc5-rg-snorm":t.rgtc.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT}:{},...t.bptc?{"bc6h-rgb-float":t.bptc.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT,"bc6h-rgb-ufloat":t.bptc.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT,"bc7-rgba-unorm":t.bptc.COMPRESSED_RGBA_BPTC_UNORM_EXT,"bc7-rgba-unorm-srgb":t.bptc.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT}:{},...t.etc?{"etc2-rgb8unorm":t.etc.COMPRESSED_RGB8_ETC2,"etc2-rgb8unorm-srgb":t.etc.COMPRESSED_SRGB8_ETC2,"etc2-rgb8a1unorm":t.etc.COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2,"etc2-rgb8a1unorm-srgb":t.etc.COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2,"etc2-rgba8unorm":t.etc.COMPRESSED_RGBA8_ETC2_EAC,"etc2-rgba8unorm-srgb":t.etc.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC,"eac-r11unorm":t.etc.COMPRESSED_R11_EAC,"eac-rg11unorm":t.etc.COMPRESSED_SIGNED_RG11_EAC}:{},...t.astc?{"astc-4x4-unorm":t.astc.COMPRESSED_RGBA_ASTC_4x4_KHR,"astc-4x4-unorm-srgb":t.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR,"astc-5x4-unorm":t.astc.COMPRESSED_RGBA_ASTC_5x4_KHR,"astc-5x4-unorm-srgb":t.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR,"astc-5x5-unorm":t.astc.COMPRESSED_RGBA_ASTC_5x5_KHR,"astc-5x5-unorm-srgb":t.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR,"astc-6x5-unorm":t.astc.COMPRESSED_RGBA_ASTC_6x5_KHR,"astc-6x5-unorm-srgb":t.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR,"astc-6x6-unorm":t.astc.COMPRESSED_RGBA_ASTC_6x6_KHR,"astc-6x6-unorm-srgb":t.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR,"astc-8x5-unorm":t.astc.COMPRESSED_RGBA_ASTC_8x5_KHR,"astc-8x5-unorm-srgb":t.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR,"astc-8x6-unorm":t.astc.COMPRESSED_RGBA_ASTC_8x6_KHR,"astc-8x6-unorm-srgb":t.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR,"astc-8x8-unorm":t.astc.COMPRESSED_RGBA_ASTC_8x8_KHR,"astc-8x8-unorm-srgb":t.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR,"astc-10x5-unorm":t.astc.COMPRESSED_RGBA_ASTC_10x5_KHR,"astc-10x5-unorm-srgb":t.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR,"astc-10x6-unorm":t.astc.COMPRESSED_RGBA_ASTC_10x6_KHR,"astc-10x6-unorm-srgb":t.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR,"astc-10x8-unorm":t.astc.COMPRESSED_RGBA_ASTC_10x8_KHR,"astc-10x8-unorm-srgb":t.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR,"astc-10x10-unorm":t.astc.COMPRESSED_RGBA_ASTC_10x10_KHR,"astc-10x10-unorm-srgb":t.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR,"astc-12x10-unorm":t.astc.COMPRESSED_RGBA_ASTC_12x10_KHR,"astc-12x10-unorm-srgb":t.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR,"astc-12x12-unorm":t.astc.COMPRESSED_RGBA_ASTC_12x12_KHR,"astc-12x12-unorm-srgb":t.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR}:{}}}function Sx(s){return{r8unorm:s.UNSIGNED_BYTE,r8snorm:s.BYTE,r8uint:s.UNSIGNED_BYTE,r8sint:s.BYTE,r16uint:s.UNSIGNED_SHORT,r16sint:s.SHORT,r16float:s.HALF_FLOAT,rg8unorm:s.UNSIGNED_BYTE,rg8snorm:s.BYTE,rg8uint:s.UNSIGNED_BYTE,rg8sint:s.BYTE,r32uint:s.UNSIGNED_INT,r32sint:s.INT,r32float:s.FLOAT,rg16uint:s.UNSIGNED_SHORT,rg16sint:s.SHORT,rg16float:s.HALF_FLOAT,rgba8unorm:s.UNSIGNED_BYTE,"rgba8unorm-srgb":s.UNSIGNED_BYTE,rgba8snorm:s.BYTE,rgba8uint:s.UNSIGNED_BYTE,rgba8sint:s.BYTE,bgra8unorm:s.UNSIGNED_BYTE,"bgra8unorm-srgb":s.UNSIGNED_BYTE,rgb9e5ufloat:s.UNSIGNED_INT_5_9_9_9_REV,rgb10a2unorm:s.UNSIGNED_INT_2_10_10_10_REV,rg11b10ufloat:s.UNSIGNED_INT_10F_11F_11F_REV,rg32uint:s.UNSIGNED_INT,rg32sint:s.INT,rg32float:s.FLOAT,rgba16uint:s.UNSIGNED_SHORT,rgba16sint:s.SHORT,rgba16float:s.HALF_FLOAT,rgba32uint:s.UNSIGNED_INT,rgba32sint:s.INT,rgba32float:s.FLOAT,stencil8:s.UNSIGNED_BYTE,depth16unorm:s.UNSIGNED_SHORT,depth24plus:s.UNSIGNED_INT,"depth24plus-stencil8":s.UNSIGNED_INT_24_8,depth32float:s.FLOAT,"depth32float-stencil8":s.FLOAT_32_UNSIGNED_INT_24_8_REV}}const Tx=4;class Ac{constructor(t){this.managedTextures=[],this._glTextures=Object.create(null),this._glSamplers=Object.create(null),this._boundTextures=[],this._activeTextureLocation=-1,this._boundSamplers=Object.create(null),this._uploads={image:Tc,buffer:mx,video:yx,compressed:_x},this._premultiplyAlpha=!1,this._useSeparateSamplers=!1,this._renderer=t,this._renderer.renderableGC.addManagedHash(this,"_glTextures"),this._renderer.renderableGC.addManagedHash(this,"_glSamplers")}contextChange(t){this._gl=t,this._mapFormatToInternalFormat||(this._mapFormatToInternalFormat=wx(t,this._renderer.context.extensions),this._mapFormatToType=Sx(t),this._mapFormatToFormat=vx(t)),this._glTextures=Object.create(null),this._glSamplers=Object.create(null),this._boundSamplers=Object.create(null),this._premultiplyAlpha=!1;for(let e=0;e<16;e++)this.bind(k.EMPTY,e)}initSource(t){this.bind(t)}bind(t,e=0){const r=t.source;t?(this.bindSource(r,e),this._useSeparateSamplers&&this._bindSampler(r.style,e)):(this.bindSource(null,e),this._useSeparateSamplers&&this._bindSampler(null,e))}bindSource(t,e=0){const r=this._gl;if(t._touched=this._renderer.textureGC.count,this._boundTextures[e]!==t){this._boundTextures[e]=t,this._activateLocation(e),t||(t=k.EMPTY.source);const n=this.getGlSource(t);r.bindTexture(n.target,n.texture)}}_bindSampler(t,e=0){const r=this._gl;if(!t){this._boundSamplers[e]=null,r.bindSampler(e,null);return}const n=this._getGlSampler(t);this._boundSamplers[e]!==n&&(this._boundSamplers[e]=n,r.bindSampler(e,n))}unbind(t){const e=t.source,r=this._boundTextures,n=this._gl;for(let o=0;o<r.length;o++)if(r[o]===e){this._activateLocation(o);const l=this.getGlSource(e);n.bindTexture(l.target,null),r[o]=null}}_activateLocation(t){this._activeTextureLocation!==t&&(this._activeTextureLocation=t,this._gl.activeTexture(this._gl.TEXTURE0+t))}_initSource(t){const e=this._gl,r=new px(e.createTexture());if(r.type=this._mapFormatToType[t.format],r.internalFormat=this._mapFormatToInternalFormat[t.format],r.format=this._mapFormatToFormat[t.format],t.autoGenerateMipmaps&&(this._renderer.context.supports.nonPowOf2mipmaps||t.isPowerOfTwo)){const n=Math.max(t.width,t.height);t.mipLevelCount=Math.floor(Math.log2(n))+1}return this._glTextures[t.uid]=r,this.managedTextures.includes(t)||(t.on("update",this.onSourceUpdate,this),t.on("resize",this.onSourceUpdate,this),t.on("styleChange",this.onStyleChange,this),t.on("destroy",this.onSourceDestroy,this),t.on("unload",this.onSourceUnload,this),t.on("updateMipmaps",this.onUpdateMipmaps,this),this.managedTextures.push(t)),this.onSourceUpdate(t),this.updateStyle(t,!1),r}onStyleChange(t){this.updateStyle(t,!1)}updateStyle(t,e){const r=this._gl,n=this.getGlSource(t);r.bindTexture(r.TEXTURE_2D,n.texture),this._boundTextures[this._activeTextureLocation]=t,Ec(t.style,r,t.mipLevelCount>1,this._renderer.context.extensions.anisotropicFiltering,"texParameteri",r.TEXTURE_2D,!this._renderer.context.supports.nonPowOf2wrapping&&!t.isPowerOfTwo,e)}onSourceUnload(t){const e=this._glTextures[t.uid];e&&(this.unbind(t),this._glTextures[t.uid]=null,this._gl.deleteTexture(e.texture))}onSourceUpdate(t){const e=this._gl,r=this.getGlSource(t);e.bindTexture(e.TEXTURE_2D,r.texture),this._boundTextures[this._activeTextureLocation]=t;const n=t.alphaMode==="premultiply-alpha-on-upload";this._premultiplyAlpha!==n&&(this._premultiplyAlpha=n,e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,n)),this._uploads[t.uploadMethodId]?this._uploads[t.uploadMethodId].upload(t,r,e,this._renderer.context.webGLVersion):e.texImage2D(e.TEXTURE_2D,0,e.RGBA,t.pixelWidth,t.pixelHeight,0,e.RGBA,e.UNSIGNED_BYTE,null),t.autoGenerateMipmaps&&t.mipLevelCount>1&&this.onUpdateMipmaps(t,!1)}onUpdateMipmaps(t,e=!0){e&&this.bindSource(t,0);const r=this.getGlSource(t);this._gl.generateMipmap(r.target)}onSourceDestroy(t){t.off("destroy",this.onSourceDestroy,this),t.off("update",this.onSourceUpdate,this),t.off("resize",this.onSourceUpdate,this),t.off("unload",this.onSourceUnload,this),t.off("styleChange",this.onStyleChange,this),t.off("updateMipmaps",this.onUpdateMipmaps,this),this.managedTextures.splice(this.managedTextures.indexOf(t),1),this.onSourceUnload(t)}_initSampler(t){const e=this._gl,r=this._gl.createSampler();return this._glSamplers[t._resourceId]=r,Ec(t,e,this._boundTextures[this._activeTextureLocation].mipLevelCount>1,this._renderer.context.extensions.anisotropicFiltering,"samplerParameteri",r,!1,!0),this._glSamplers[t._resourceId]}_getGlSampler(t){return this._glSamplers[t._resourceId]||this._initSampler(t)}getGlSource(t){return this._glTextures[t.uid]||this._initSource(t)}generateCanvas(t){const{pixels:e,width:r,height:n}=this.getPixels(t),o=W.get().createCanvas();o.width=r,o.height=n;const l=o.getContext("2d");if(l){const h=l.createImageData(r,n);h.data.set(e),l.putImageData(h,0,0)}return o}getPixels(t){const e=t.source.resolution,r=t.frame,n=Math.max(Math.round(r.width*e),1),o=Math.max(Math.round(r.height*e),1),l=new Uint8Array(Tx*n*o),h=this._renderer,u=h.renderTarget.getRenderTarget(t),f=h.renderTarget.getGpuRenderTarget(u),m=h.gl;return m.bindFramebuffer(m.FRAMEBUFFER,f.resolveTargetFramebuffer),m.readPixels(Math.round(r.x*e),Math.round(r.y*e),n,o,m.RGBA,m.UNSIGNED_BYTE,l),{pixels:new Uint8ClampedArray(l.buffer),width:n,height:o}}destroy(){this.managedTextures.slice().forEach(t=>this.onSourceDestroy(t)),this.managedTextures=null,this._glTextures=null,this._glSamplers=null,this._boundTextures=null,this._boundSamplers=null,this._mapFormatToInternalFormat=null,this._mapFormatToType=null,this._mapFormatToFormat=null,this._uploads=null,this._renderer=null}resetState(){this._activeTextureLocation=-1,this._boundTextures.fill(k.EMPTY.source),this._boundSamplers=Object.create(null);const t=this._gl;this._premultiplyAlpha=!1,t.pixelStorei(t.UNPACK_PREMULTIPLY_ALPHA_WEBGL,this._premultiplyAlpha)}}Ac.extension={type:[C.WebGLSystem],name:"texture"};class Pc{contextChange(t){const e=new _t({uColor:{value:new Float32Array([1,1,1,1]),type:"vec4<f32>"},uTransformMatrix:{value:new M,type:"mat3x3<f32>"},uRound:{value:0,type:"f32"}}),r=t.limits.maxBatchableTextures,n=ki({name:"graphics",bits:[un,gn(r),Ln,Ri]});this.shader=new Ft({glProgram:n,resources:{localUniforms:e,batchSamplers:_n(r)}})}execute(t,e){const r=e.context,n=r.customShader||this.shader,o=t.renderer,l=o.graphicsContext,{batcher:h,instructions:u}=l.getContextRenderData(r);n.groups[0]=o.globalUniforms.bindGroup,o.state.set(t.state),o.shader.bind(n),o.geometry.bind(h.geometry,n.glProgram);const f=u.instructions;for(let m=0;m<u.instructionSize;m++){const g=f[m];if(g.size){for(let y=0;y<g.textures.count;y++)o.texture.bind(g.textures.textures[y],y);o.geometry.draw(g.topology,g.size,g.start)}}}destroy(){this.shader.destroy(!0),this.shader=null}}Pc.extension={type:[C.WebGLPipesAdaptor],name:"graphics"};class Bc{init(){const t=ki({name:"mesh",bits:[Ln,Uy,Ri]});this._shader=new Ft({glProgram:t,resources:{uTexture:k.EMPTY.source,textureUniforms:{uTextureMatrix:{type:"mat3x3<f32>",value:new M}}}})}execute(t,e){const r=t.renderer;let n=e._shader;if(n){if(!n.glProgram){F("Mesh shader has no glProgram",e.shader);return}}else{n=this._shader;const o=e.texture,l=o.source;n.resources.uTexture=l,n.resources.uSampler=l.style,n.resources.textureUniforms.uniforms.uTextureMatrix=o.textureMatrix.mapCoord}n.groups[100]=r.globalUniforms.bindGroup,n.groups[101]=t.localUniformsBindGroup,r.encoder.draw({geometry:e._geometry,shader:n,state:e.state})}destroy(){this._shader.destroy(!0),this._shader=null}}Bc.extension={type:[C.WebGLPipesAdaptor],name:"mesh"};class Uc{constructor(t){this._renderer=t}updateRenderable(){}destroyRenderable(){}validateRenderable(){return!1}addRenderable(t,e){this._renderer.renderPipes.batch.break(e),e.add(t)}execute(t){t.isRenderable&&t.render(this._renderer)}destroy(){this._renderer=null}}Uc.extension={type:[C.WebGLPipes,C.WebGPUPipes,C.CanvasPipes],name:"customRender"};class Vr{constructor(){this.batcherName="default",this.topology="triangle-list",this.attributeSize=4,this.indexSize=6,this.packAsQuad=!0,this.roundPixels=0,this._attributeStart=0,this._batcher=null,this._batch=null}get blendMode(){return this.renderable.groupBlendMode}get color(){return this.renderable.groupColorAlpha}reset(){this.renderable=null,this.texture=null,this._batcher=null,this._batch=null,this.bounds=null}destroy(){}}function $n(s,t){const e=s.instructionSet,r=e.instructions;for(let n=0;n<e.instructionSize;n++){const o=r[n];t[o.renderPipeId].execute(o)}}const Cx=new M;class kc{constructor(t){this._renderer=t}addRenderGroup(t,e){t.isCachedAsTexture?this._addRenderableCacheAsTexture(t,e):this._addRenderableDirect(t,e)}execute(t){t.isRenderable&&(t.isCachedAsTexture?this._executeCacheAsTexture(t):this._executeDirect(t))}destroy(){this._renderer=null}_addRenderableDirect(t,e){this._renderer.renderPipes.batch.break(e),t._batchableRenderGroup&&(at.return(t._batchableRenderGroup),t._batchableRenderGroup=null),e.add(t)}_addRenderableCacheAsTexture(t,e){const r=t._batchableRenderGroup??(t._batchableRenderGroup=at.get(Vr));r.renderable=t.root,r.transform=t.root.relativeGroupTransform,r.texture=t.texture,r.bounds=t._textureBounds,e.add(t),this._renderer.renderPipes.blendMode.pushBlendMode(t,t.root.groupBlendMode,e),this._renderer.renderPipes.batch.addToBatch(r,e),this._renderer.renderPipes.blendMode.popBlendMode(e)}_executeCacheAsTexture(t){if(t.textureNeedsUpdate){t.textureNeedsUpdate=!1;const e=Cx.identity().translate(-t._textureBounds.x,-t._textureBounds.y);this._renderer.renderTarget.push(t.texture,!0,null,t.texture.frame),this._renderer.globalUniforms.push({worldTransformMatrix:e,worldColor:4294967295,offset:{x:0,y:0}}),$n(t,this._renderer.renderPipes),this._renderer.renderTarget.finishRenderPass(),this._renderer.renderTarget.pop(),this._renderer.globalUniforms.pop()}t._batchableRenderGroup._batcher.updateElement(t._batchableRenderGroup),t._batchableRenderGroup._batcher.geometry.buffers[0].update()}_executeDirect(t){this._renderer.globalUniforms.push({worldTransformMatrix:t.inverseParentTextureTransform,worldColor:t.worldColorAlpha}),$n(t,this._renderer.renderPipes),this._renderer.globalUniforms.pop()}}kc.extension={type:[C.WebGLPipes,C.WebGPUPipes,C.CanvasPipes],name:"renderGroup"};function Kn(s,t){t||(t=0);for(let e=t;e<s.length&&s[e];e++)s[e]=null}const Ex=new st,Mc=ui|gr|Rs;function Rc(s,t=!1){Ax(s);const e=s.childrenToUpdate,r=s.updateTick++;for(const n in e){const o=Number(n),l=e[n],h=l.list,u=l.index;for(let f=0;f<u;f++){const m=h[f];m.parentRenderGroup===s&&m.relativeRenderGroupDepth===o&&Ic(m,r,0)}Kn(h,u),l.index=0}if(t)for(let n=0;n<s.renderGroupChildren.length;n++)Rc(s.renderGroupChildren[n],t)}function Ax(s){const t=s.root;let e;if(s.renderGroupParent){const r=s.renderGroupParent;s.worldTransform.appendFrom(t.relativeGroupTransform,r.worldTransform),s.worldColor=ur(t.groupColor,r.worldColor),e=t.groupAlpha*r.worldAlpha}else s.worldTransform.copyFrom(t.localTransform),s.worldColor=t.localColor,e=t.localAlpha;e=e<0?0:e>1?1:e,s.worldAlpha=e,s.worldColorAlpha=s.worldColor+((e*255|0)<<24)}function Ic(s,t,e){if(t===s.updateTick)return;s.updateTick=t,s.didChange=!1;const r=s.localTransform;s.updateLocalTransform();const n=s.parent;if(n&&!n.renderGroup?(e|=s._updateFlags,s.relativeGroupTransform.appendFrom(r,n.relativeGroupTransform),e&Mc&&Fc(s,n,e)):(e=s._updateFlags,s.relativeGroupTransform.copyFrom(r),e&Mc&&Fc(s,Ex,e)),!s.renderGroup){const o=s.children,l=o.length;for(let f=0;f<l;f++)Ic(o[f],t,e);const h=s.parentRenderGroup,u=s;u.renderPipeId&&!h.structureDidChange&&h.updateRenderable(u)}}function Fc(s,t,e){if(e&gr){s.groupColor=ur(s.localColor,t.groupColor);let r=s.localAlpha*t.groupAlpha;r=r<0?0:r>1?1:r,s.groupAlpha=r,s.groupColorAlpha=s.groupColor+((r*255|0)<<24)}e&Rs&&(s.groupBlendMode=s.localBlendMode==="inherit"?t.groupBlendMode:s.localBlendMode),e&ui&&(s.globalDisplayStatus=s.localDisplayStatus&t.globalDisplayStatus),s._updateFlags=0}function Px(s,t){const{list:e}=s.childrenRenderablesToUpdate;let r=!1;for(let n=0;n<s.childrenRenderablesToUpdate.index;n++){const o=e[n];if(r=t[o.renderPipeId].validateRenderable(o),r)break}return s.structureDidChange=r,r}const Bx=new M;class Dc{constructor(t){this._renderer=t}render({container:t,transform:e}){const r=t.parent,n=t.renderGroup.renderGroupParent;t.parent=null,t.renderGroup.renderGroupParent=null;const o=this._renderer,l=Bx;e&&(l.copyFrom(t.renderGroup.localTransform),t.renderGroup.localTransform.copyFrom(e));const h=o.renderPipes;this._updateCachedRenderGroups(t.renderGroup,null),this._updateRenderGroups(t.renderGroup),o.globalUniforms.start({worldTransformMatrix:e?t.renderGroup.localTransform:t.renderGroup.worldTransform,worldColor:t.renderGroup.worldColorAlpha}),$n(t.renderGroup,h),h.uniformBatch&&h.uniformBatch.renderEnd(),e&&t.renderGroup.localTransform.copyFrom(l),t.parent=r,t.renderGroup.renderGroupParent=n}destroy(){this._renderer=null}_updateCachedRenderGroups(t,e){if(t._parentCacheAsTextureRenderGroup=e,t.isCachedAsTexture){if(!t.textureNeedsUpdate)return;e=t}for(let r=t.renderGroupChildren.length-1;r>=0;r--)this._updateCachedRenderGroups(t.renderGroupChildren[r],e);if(t.invalidateMatrices(),t.isCachedAsTexture){if(t.textureNeedsUpdate){const r=t.root.getLocalBounds();r.ceil();const n=t.texture;t.texture&&dt.returnTexture(t.texture,!0);const o=this._renderer,l=t.textureOptions.resolution||o.view.resolution,h=t.textureOptions.antialias??o.view.antialias,u=t.textureOptions.scaleMode??"linear",f=dt.getOptimalTexture(r.width,r.height,l,h);f._source.style=new jt({scaleMode:u}),t.texture=f,t._textureBounds||(t._textureBounds=new ut),t._textureBounds.copyFrom(r),n!==t.texture&&t.renderGroupParent&&(t.renderGroupParent.structureDidChange=!0)}}else t.texture&&(dt.returnTexture(t.texture,!0),t.texture=null)}_updateRenderGroups(t){const e=this._renderer,r=e.renderPipes;if(t.runOnRender(e),t.instructionSet.renderPipes=r,t.structureDidChange?Kn(t.childrenRenderablesToUpdate.list,0):Px(t,r),Rc(t),t.structureDidChange?(t.structureDidChange=!1,this._buildInstructions(t,e)):this._updateRenderables(t),t.childrenRenderablesToUpdate.index=0,e.renderPipes.batch.upload(t.instructionSet),!(t.isCachedAsTexture&&!t.textureNeedsUpdate))for(let n=0;n<t.renderGroupChildren.length;n++)this._updateRenderGroups(t.renderGroupChildren[n])}_updateRenderables(t){const{list:e,index:r}=t.childrenRenderablesToUpdate;for(let n=0;n<r;n++){const o=e[n];o.didViewUpdate&&t.updateRenderable(o)}Kn(e,r)}_buildInstructions(t,e){const r=t.root,n=t.instructionSet;n.reset();const o=e.renderPipes?e:e.batch.renderer,l=o.renderPipes;l.batch.buildStart(n),l.blendMode.buildStart(),l.colorMask.buildStart(),r.sortableChildren&&r.sortChildren(),r.collectRenderablesWithEffects(n,o,null),l.batch.buildEnd(n),l.blendMode.buildEnd(n)}}Dc.extension={type:[C.WebGLSystem,C.WebGPUSystem,C.CanvasSystem],name:"renderGroup"};class Oc{constructor(t){this._renderer=t}addRenderable(t,e){const r=this._getGpuSprite(t);t.didViewUpdate&&this._updateBatchableSprite(t,r),this._renderer.renderPipes.batch.addToBatch(r,e)}updateRenderable(t){const e=this._getGpuSprite(t);t.didViewUpdate&&this._updateBatchableSprite(t,e),e._batcher.updateElement(e)}validateRenderable(t){const e=this._getGpuSprite(t);return!e._batcher.checkAndUpdateTexture(e,t._texture)}_updateBatchableSprite(t,e){e.bounds=t.visualBounds,e.texture=t._texture}_getGpuSprite(t){return t._gpuData[this._renderer.uid]||this._initGPUSprite(t)}_initGPUSprite(t){const e=new Vr;return e.renderable=t,e.transform=t.groupTransform,e.texture=t._texture,e.bounds=t.visualBounds,e.roundPixels=this._renderer._roundPixels|t._roundPixels,t._gpuData[this._renderer.uid]=e,e}destroy(){this._renderer=null}}Oc.extension={type:[C.WebGLPipes,C.WebGPUPipes,C.CanvasPipes],name:"sprite"};const jn=class cu{constructor(){this.clearBeforeRender=!0,this._backgroundColor=new J(0),this.color=this._backgroundColor,this.alpha=1}init(t){t={...cu.defaultOptions,...t},this.clearBeforeRender=t.clearBeforeRender,this.color=t.background||t.backgroundColor||this._backgroundColor,this.alpha=t.backgroundAlpha,this._backgroundColor.setAlpha(t.backgroundAlpha)}get color(){return this._backgroundColor}set color(t){J.shared.setValue(t).alpha<1&&this._backgroundColor.alpha===1&&F("Cannot set a transparent background on an opaque canvas. To enable transparency, set backgroundAlpha < 1 when initializing your Application."),this._backgroundColor.setValue(t)}get alpha(){return this._backgroundColor.alpha}set alpha(t){this._backgroundColor.setAlpha(t)}get colorRgba(){return this._backgroundColor.toArray()}destroy(){}};jn.extension={type:[C.WebGLSystem,C.WebGPUSystem,C.CanvasSystem],name:"background",priority:0},jn.defaultOptions={backgroundAlpha:1,backgroundColor:0,clearBeforeRender:!0};let Ux=jn;const Wi={};D.handle(C.BlendMode,s=>{if(!s.name)throw new Error("BlendMode extension must have a name property");Wi[s.name]=s.ref},s=>{delete Wi[s.name]});class Gc{constructor(t){this._blendModeStack=[],this._isAdvanced=!1,this._filterHash=Object.create(null),this._renderer=t,this._renderer.runners.prerender.add(this)}prerender(){this._activeBlendMode="normal",this._isAdvanced=!1}pushBlendMode(t,e,r){this._blendModeStack.push(e),this.setBlendMode(t,e,r)}popBlendMode(t){this._blendModeStack.pop();const e=this._blendModeStack[this._activeBlendMode.length-1]??"normal";this.setBlendMode(null,e,t)}setBlendMode(t,e,r){const n=t instanceof Us;if(this._activeBlendMode===e){this._isAdvanced&&t&&!n&&this._renderableList?.push(t);return}this._isAdvanced&&this._endAdvancedBlendMode(r),this._activeBlendMode=e,t&&(this._isAdvanced=!!Wi[e],this._isAdvanced&&this._beginAdvancedBlendMode(t,r))}_beginAdvancedBlendMode(t,e){this._renderer.renderPipes.batch.break(e);const r=this._activeBlendMode;if(!Wi[r]){F(`Unable to assign BlendMode: '${r}'. You may want to include: import 'pixi.js/advanced-blend-modes'`);return}const n=this._ensureFilterEffect(r),o=t instanceof Us,l={renderPipeId:"filter",action:"pushFilter",filterEffect:n,renderables:o?null:[t],container:o?t.root:null,canBundle:!1};this._renderableList=l.renderables,e.add(l)}_ensureFilterEffect(t){let e=this._filterHash[t];return e||(e=this._filterHash[t]=new dr,e.filters=[new Wi[t]]),e}_endAdvancedBlendMode(t){this._isAdvanced=!1,this._renderableList=null,this._renderer.renderPipes.batch.break(t),t.add({renderPipeId:"filter",action:"popFilter",canBundle:!1})}buildStart(){this._isAdvanced=!1}buildEnd(t){this._isAdvanced&&this._endAdvancedBlendMode(t)}destroy(){this._renderer=null,this._renderableList=null;for(const t in this._filterHash)this._filterHash[t].destroy();this._filterHash=null}}Gc.extension={type:[C.WebGLPipes,C.WebGPUPipes,C.CanvasPipes],name:"blendMode"};const qn={png:"image/png",jpg:"image/jpeg",webp:"image/webp"},Zn=class du{constructor(t){this._renderer=t}_normalizeOptions(t,e={}){return t instanceof st||t instanceof k?{target:t,...e}:{...e,...t}}async image(t){const e=W.get().createImage();return e.src=await this.base64(t),e}async base64(t){t=this._normalizeOptions(t,du.defaultImageOptions);const{format:e,quality:r}=t,n=this.canvas(t);if(n.toBlob!==void 0)return new Promise((o,l)=>{n.toBlob(h=>{if(!h){l(new Error("ICanvas.toBlob failed!"));return}const u=new FileReader;u.onload=()=>o(u.result),u.onerror=l,u.readAsDataURL(h)},qn[e],r)});if(n.toDataURL!==void 0)return n.toDataURL(qn[e],r);if(n.convertToBlob!==void 0){const o=await n.convertToBlob({type:qn[e],quality:r});return new Promise((l,h)=>{const u=new FileReader;u.onload=()=>l(u.result),u.onerror=h,u.readAsDataURL(o)})}throw new Error("Extract.base64() requires ICanvas.toDataURL, ICanvas.toBlob, or ICanvas.convertToBlob to be implemented")}canvas(t){t=this._normalizeOptions(t);const e=t.target,r=this._renderer;if(e instanceof k)return r.texture.generateCanvas(e);const n=r.textureGenerator.generateTexture(t),o=r.texture.generateCanvas(n);return n.destroy(!0),o}pixels(t){t=this._normalizeOptions(t);const e=t.target,r=this._renderer,n=e instanceof k?e:r.textureGenerator.generateTexture(t),o=r.texture.getPixels(n);return e instanceof st&&n.destroy(!0),o}texture(t){return t=this._normalizeOptions(t),t.target instanceof k?t.target:this._renderer.textureGenerator.generateTexture(t)}download(t){t=this._normalizeOptions(t);const e=this.canvas(t),r=document.createElement("a");r.download=t.filename??"image.png",r.href=e.toDataURL("image/png"),document.body.appendChild(r),r.click(),document.body.removeChild(r)}log(t){const e=t.width??200;t=this._normalizeOptions(t);const r=this.canvas(t),n=r.toDataURL();console.log(`[Pixi Texture] ${r.width}px ${r.height}px`);const o=["font-size: 1px;",`padding: ${e}px 300px;`,`background: url(${n}) no-repeat;`,"background-size: contain;"].join(" ");console.log("%c ",o)}destroy(){this._renderer=null}};Zn.extension={type:[C.WebGLSystem,C.WebGPUSystem],name:"extract"},Zn.defaultImageOptions={format:"png",quality:1};let kx=Zn;class Vi extends k{static create(t){return new Vi({source:new ht(t)})}resize(t,e,r){return this.source.resize(t,e,r),this}}const Mx=new G,Rx=new ut,Ix=[0,0,0,0];class Lc{constructor(t){this._renderer=t}generateTexture(t){t instanceof st&&(t={target:t,frame:void 0,textureSourceOptions:{},resolution:void 0});const e=t.resolution||this._renderer.resolution,r=t.antialias||this._renderer.view.antialias,n=t.target;let o=t.clearColor;o?o=Array.isArray(o)&&o.length===4?o:J.shared.setValue(o).toArray():o=Ix;const l=t.frame?.copyTo(Mx)||Bs(n,Rx).rectangle;l.width=Math.max(l.width,1/e)|0,l.height=Math.max(l.height,1/e)|0;const h=Vi.create({...t.textureSourceOptions,width:l.width,height:l.height,resolution:e,antialias:r}),u=M.shared.translate(-l.x,-l.y);return this._renderer.render({container:n,transform:u,target:h,clearColor:o}),h.source.updateMipmaps(),h}destroy(){this._renderer=null}}Lc.extension={type:[C.WebGLSystem,C.WebGPUSystem],name:"textureGenerator"};function Yi(s,t,e){const r=(s>>24&255)/255;t[e++]=(s&255)/255*r,t[e++]=(s>>8&255)/255*r,t[e++]=(s>>16&255)/255*r,t[e++]=r}class zc{constructor(t){this._stackIndex=0,this._globalUniformDataStack=[],this._uniformsPool=[],this._activeUniforms=[],this._bindGroupPool=[],this._activeBindGroups=[],this._renderer=t}reset(){this._stackIndex=0;for(let t=0;t<this._activeUniforms.length;t++)this._uniformsPool.push(this._activeUniforms[t]);for(let t=0;t<this._activeBindGroups.length;t++)this._bindGroupPool.push(this._activeBindGroups[t]);this._activeUniforms.length=0,this._activeBindGroups.length=0}start(t){this.reset(),this.push(t)}bind({size:t,projectionMatrix:e,worldTransformMatrix:r,worldColor:n,offset:o}){const l=this._renderer.renderTarget.renderTarget,h=this._stackIndex?this._globalUniformDataStack[this._stackIndex-1]:{worldTransformMatrix:new M,worldColor:4294967295,offset:new q},u={projectionMatrix:e||this._renderer.renderTarget.projectionMatrix,resolution:t||l.size,worldTransformMatrix:r||h.worldTransformMatrix,worldColor:n||h.worldColor,offset:o||h.offset,bindGroup:null},f=this._uniformsPool.pop()||this._createUniforms();this._activeUniforms.push(f);const m=f.uniforms;m.uProjectionMatrix=u.projectionMatrix,m.uResolution=u.resolution,m.uWorldTransformMatrix.copyFrom(u.worldTransformMatrix),m.uWorldTransformMatrix.tx-=u.offset.x,m.uWorldTransformMatrix.ty-=u.offset.y,Yi(u.worldColor,m.uWorldColorAlpha,0),f.update();let g;this._renderer.renderPipes.uniformBatch?g=this._renderer.renderPipes.uniformBatch.getUniformBindGroup(f,!1):(g=this._bindGroupPool.pop()||new ne,this._activeBindGroups.push(g),g.setResource(f,0)),u.bindGroup=g,this._currentGlobalUniformData=u}push(t){this.bind(t),this._globalUniformDataStack[this._stackIndex++]=this._currentGlobalUniformData}pop(){this._currentGlobalUniformData=this._globalUniformDataStack[--this._stackIndex-1],this._renderer.type===Nt.WEBGL&&this._currentGlobalUniformData.bindGroup.resources[0].update()}get bindGroup(){return this._currentGlobalUniformData.bindGroup}get globalUniformData(){return this._currentGlobalUniformData}get uniformGroup(){return this._currentGlobalUniformData.bindGroup.resources[0]}_createUniforms(){return new _t({uProjectionMatrix:{value:new M,type:"mat3x3<f32>"},uWorldTransformMatrix:{value:new M,type:"mat3x3<f32>"},uWorldColorAlpha:{value:new Float32Array(4),type:"vec4<f32>"},uResolution:{value:[0,0],type:"vec2<f32>"}},{isStatic:!0})}destroy(){this._renderer=null,this._globalUniformDataStack.length=0,this._uniformsPool.length=0,this._activeUniforms.length=0,this._bindGroupPool.length=0,this._activeBindGroups.length=0,this._currentGlobalUniformData=null}}zc.extension={type:[C.WebGLSystem,C.WebGPUSystem,C.CanvasSystem],name:"globalUniforms"};let Fx=1;class Nc{constructor(){this._tasks=[],this._offset=0}init(){Et.system.add(this._update,this)}repeat(t,e,r=!0){const n=Fx++;let o=0;return r&&(this._offset+=1e3,o=this._offset),this._tasks.push({func:t,duration:e,start:performance.now(),offset:o,last:performance.now(),repeat:!0,id:n}),n}cancel(t){for(let e=0;e<this._tasks.length;e++)if(this._tasks[e].id===t){this._tasks.splice(e,1);return}}_update(){const t=performance.now();for(let e=0;e<this._tasks.length;e++){const r=this._tasks[e];if(t-r.offset-r.last>=r.duration){const n=t-r.start;r.func(n),r.last=t}}}destroy(){Et.system.remove(this._update,this),this._tasks.length=0}}Nc.extension={type:[C.WebGLSystem,C.WebGPUSystem,C.CanvasSystem],name:"scheduler",priority:0};let Hc=!1;function Dx(s){if(!Hc){if(W.get().getNavigator().userAgent.toLowerCase().indexOf("chrome")>-1){const t=[`%c %c %c %c %c PixiJS %c v${Ar} (${s}) http://www.pixijs.com/
|
|
962
962
|
|
|
963
|
-
`,"background: #E72264; padding:5px 0;","background: #6CA2EA; padding:5px 0;","background: #B5D33D; padding:5px 0;","background: #FED23F; padding:5px 0;","color: #FFFFFF; background: #E72264; padding:5px 0;","color: #E72264; background: #FFFFFF; padding:5px 0;"];globalThis.console.log(...t)}else globalThis.console&&globalThis.console.log(`PixiJS ${Cr} - ${s} - http://www.pixijs.com/`);Oc=!0}}class jn{constructor(t){this._renderer=t}init(t){if(t.hello){let e=this._renderer.name;this._renderer.type===Nt.WEBGL&&(e+=` ${this._renderer.context.webGLVersion}`),Ax(e)}}}jn.extension={type:[C.WebGLSystem,C.WebGPUSystem,C.CanvasSystem],name:"hello",priority:-2},jn.defaultOptions={hello:!1};function Px(s){let t=!1;for(const r in s)if(s[r]==null){t=!0;break}if(!t)return s;const e=Object.create(null);for(const r in s){const n=s[r];n&&(e[r]=n)}return e}function Bx(s){let t=0;for(let e=0;e<s.length;e++)s[e]==null?t++:s[e-t]=s[e];return s.length-=t,s}let Ux=0;const qn=class hd{constructor(t){this._managedRenderables=[],this._managedHashes=[],this._managedArrays=[],this._renderer=t}init(t){t={...hd.defaultOptions,...t},this.maxUnusedTime=t.renderableGCMaxUnusedTime,this._frequency=t.renderableGCFrequency,this.enabled=t.renderableGCActive}get enabled(){return!!this._handler}set enabled(t){this.enabled!==t&&(t?(this._handler=this._renderer.scheduler.repeat(()=>this.run(),this._frequency,!1),this._hashHandler=this._renderer.scheduler.repeat(()=>{for(const e of this._managedHashes)e.context[e.hash]=Px(e.context[e.hash])},this._frequency),this._arrayHandler=this._renderer.scheduler.repeat(()=>{for(const e of this._managedArrays)Bx(e.context[e.hash])},this._frequency)):(this._renderer.scheduler.cancel(this._handler),this._renderer.scheduler.cancel(this._hashHandler),this._renderer.scheduler.cancel(this._arrayHandler)))}addManagedHash(t,e){this._managedHashes.push({context:t,hash:e})}addManagedArray(t,e){this._managedArrays.push({context:t,hash:e})}prerender({container:t}){this._now=performance.now(),t.renderGroup.gcTick=Ux++,this._updateInstructionGCTick(t.renderGroup,t.renderGroup.gcTick)}addRenderable(t){this.enabled&&(t._lastUsed===-1&&(this._managedRenderables.push(t),t.once("destroyed",this._removeRenderable,this)),t._lastUsed=this._now)}run(){const t=this._now,e=this._managedRenderables,r=this._renderer.renderPipes;let n=0;for(let a=0;a<e.length;a++){const l=e[a];if(l===null){n++;continue}const h=l.renderGroup??l.parentRenderGroup,d=h?.instructionSet?.gcTick??-1;if((h?.gcTick??0)===d&&(l._lastUsed=t),t-l._lastUsed>this.maxUnusedTime){if(!l.destroyed){const f=r;h&&(h.structureDidChange=!0),f[l.renderPipeId].destroyRenderable(l)}l._lastUsed=-1,n++,l.off("destroyed",this._removeRenderable,this)}else e[a-n]=l}e.length-=n}destroy(){this.enabled=!1,this._renderer=null,this._managedRenderables.length=0,this._managedHashes.length=0,this._managedArrays.length=0}_removeRenderable(t){const e=this._managedRenderables.indexOf(t);e>=0&&(t.off("destroyed",this._removeRenderable,this),this._managedRenderables[e]=null)}_updateInstructionGCTick(t,e){t.instructionSet.gcTick=e;for(const r of t.renderGroupChildren)this._updateInstructionGCTick(r,e)}};qn.extension={type:[C.WebGLSystem,C.WebGPUSystem],name:"renderableGC",priority:0},qn.defaultOptions={renderableGCActive:!0,renderableGCMaxUnusedTime:6e4,renderableGCFrequency:3e4};let Mx=qn;const Zn=class ld{constructor(t){this._renderer=t,this.count=0,this.checkCount=0}init(t){t={...ld.defaultOptions,...t},this.checkCountMax=t.textureGCCheckCountMax,this.maxIdle=t.textureGCAMaxIdle??t.textureGCMaxIdle,this.active=t.textureGCActive}postrender(){this._renderer.renderingToScreen&&(this.count++,this.active&&(this.checkCount++,this.checkCount>this.checkCountMax&&(this.checkCount=0,this.run())))}run(){const t=this._renderer.texture.managedTextures;for(let e=0;e<t.length;e++){const r=t[e];r.autoGarbageCollect&&r.resource&&r._touched>-1&&this.count-r._touched>this.maxIdle&&(r._touched=-1,r.unload())}}destroy(){this._renderer=null}};Zn.extension={type:[C.WebGLSystem,C.WebGPUSystem],name:"textureGC"},Zn.defaultOptions={textureGCActive:!0,textureGCAMaxIdle:null,textureGCMaxIdle:3600,textureGCCheckCountMax:600};let kx=Zn;const Qn=class cd{get autoDensity(){return this.texture.source.autoDensity}set autoDensity(t){this.texture.source.autoDensity=t}get resolution(){return this.texture.source._resolution}set resolution(t){this.texture.source.resize(this.texture.source.width,this.texture.source.height,t)}init(t){t={...cd.defaultOptions,...t},t.view&&(z($,"ViewSystem.view has been renamed to ViewSystem.canvas"),t.canvas=t.view),this.screen=new L(0,0,t.width,t.height),this.canvas=t.canvas||W.get().createCanvas(),this.antialias=!!t.antialias,this.texture=hc(this.canvas,t),this.renderTarget=new zn({colorTextures:[this.texture],depth:!!t.depth,isRoot:!0}),this.texture.source.transparent=t.backgroundAlpha<1,this.resolution=t.resolution}resize(t,e,r){this.texture.source.resize(t,e,r),this.screen.width=this.texture.frame.width,this.screen.height=this.texture.frame.height}destroy(t=!1){(typeof t=="boolean"?t:!!t?.removeView)&&this.canvas.parentNode&&this.canvas.parentNode.removeChild(this.canvas),this.texture.destroy()}};Qn.extension={type:[C.WebGLSystem,C.WebGPUSystem,C.CanvasSystem],name:"view",priority:0},Qn.defaultOptions={width:800,height:600,autoDensity:!1,antialias:!1};const Lc=[vx,Dc,jn,Qn,kc,kx,Fc,wx,gh,Mx,Gc],zc=[Ic,Vl,Rc,Ac,Yl,$l,Xl,Ec],Rx=[...Lc,oc,Uy,Cy,ec,Kl,Sc,uc,Ql,yc,_c,tc,sx,ic,Jl],Ix=[...zc],Fx=[Hl,Cc,Tc],Nc=[],Hc=[],Wc=[];D.handleByNamedList(C.WebGLSystem,Nc),D.handleByNamedList(C.WebGLPipes,Hc),D.handleByNamedList(C.WebGLPipesAdaptor,Wc),D.add(...Rx,...Ix,...Fx);class Dx extends wr{constructor(){const t={name:"webgl",type:Nt.WEBGL,systems:Nc,renderPipes:Hc,renderPipeAdaptors:Wc};super(t)}}const Gx=Object.freeze(Object.defineProperty({__proto__:null,WebGLRenderer:Dx},Symbol.toStringTag,{value:"Module"}));class Vc{constructor(t){this._hash=Object.create(null),this._renderer=t,this._renderer.renderableGC.addManagedHash(this,"_hash")}contextChange(t){this._gpu=t}getBindGroup(t,e,r){return t._updateKey(),this._hash[t._key]||this._createBindGroup(t,e,r)}_createBindGroup(t,e,r){const n=this._gpu.device,a=e.layout[r],l=[],h=this._renderer;for(const m in a){const g=t.resources[m]??t.resources[a[m]];let y;if(g._resourceType==="uniformGroup"){const x=g;h.ubo.updateUniformGroup(x);const o=x.buffer;y={buffer:h.buffer.getGPUBuffer(o),offset:0,size:o.descriptor.size}}else if(g._resourceType==="buffer"){const x=g;y={buffer:h.buffer.getGPUBuffer(x),offset:0,size:x.descriptor.size}}else if(g._resourceType==="bufferResource"){const x=g;y={buffer:h.buffer.getGPUBuffer(x.buffer),offset:x.offset,size:x.size}}else if(g._resourceType==="textureSampler"){const x=g;y=h.texture.getGpuSampler(x)}else if(g._resourceType==="textureSource"){const x=g;y=h.texture.getGpuSource(x).createView({})}l.push({binding:a[m],resource:y})}const d=h.shader.getProgramData(e).bindGroups[r],f=n.createBindGroup({layout:d,entries:l});return this._hash[t._key]=f,f}destroy(){for(const t of Object.keys(this._hash))this._hash[t]=null;this._hash=null,this._renderer=null}}Vc.extension={type:[C.WebGPUSystem],name:"bindGroup"};class Yc{constructor(t){this._gpuBuffers=Object.create(null),t.renderableGC.addManagedHash(this,"_gpuBuffers")}contextChange(t){this._gpu=t}getGPUBuffer(t){return this._gpuBuffers[t.uid]||this.createGPUBuffer(t)}updateBuffer(t){const e=this._gpuBuffers[t.uid]||this.createGPUBuffer(t),r=t.data;return t._updateID&&r&&(t._updateID=0,this._gpu.device.queue.writeBuffer(e,0,r.buffer,0,(t._updateSize||r.byteLength)+3&-4)),e}destroyAll(){for(const t in this._gpuBuffers)this._gpuBuffers[t]?.destroy();this._gpuBuffers={}}createGPUBuffer(t){this._gpuBuffers[t.uid]||(t.on("update",this.updateBuffer,this),t.on("change",this.onBufferChange,this),t.on("destroy",this.onBufferDestroy,this));const e=this._gpu.device.createBuffer(t.descriptor);return t._updateID=0,t.data&&(an(t.data.buffer,e.getMappedRange()),e.unmap()),this._gpuBuffers[t.uid]=e,e}onBufferChange(t){this._gpuBuffers[t.uid].destroy(),t._updateID=0,this._gpuBuffers[t.uid]=this.createGPUBuffer(t)}onBufferDestroy(t){this._destroyBuffer(t)}destroy(){this.destroyAll(),this._gpuBuffers={}}_destroyBuffer(t){if(t.off("update",this.updateBuffer,this),t.off("change",this.onBufferChange,this),t.off("destroy",this.onBufferDestroy,this),!this._gpuBuffers[t.uid])return;this._gpuBuffers[t.uid].destroy(),this._gpuBuffers[t.uid]=null}}Yc.extension={type:[C.WebGPUSystem],name:"buffer"};class Ox{constructor({minUniformOffsetAlignment:t}){this._minUniformOffsetAlignment=256,this.byteIndex=0,this._minUniformOffsetAlignment=t,this.data=new Float32Array(65535)}clear(){this.byteIndex=0}addEmptyGroup(t){if(t>this._minUniformOffsetAlignment/4)throw new Error(`UniformBufferBatch: array is too large: ${t*4}`);const e=this.byteIndex;let r=e+t*4;if(r=Math.ceil(r/this._minUniformOffsetAlignment)*this._minUniformOffsetAlignment,r>this.data.length*4)throw new Error("UniformBufferBatch: ubo batch got too big");return this.byteIndex=r,e}addGroup(t){const e=this.addEmptyGroup(t.length);for(let r=0;r<t.length;r++)this.data[e/4+r]=t[r];return e}destroy(){this.data=null}}class Xc{constructor(t){this._colorMaskCache=15,this._renderer=t}setMask(t){this._colorMaskCache!==t&&(this._colorMaskCache=t,this._renderer.pipeline.setColorMask(t))}destroy(){this._renderer=null,this._colorMaskCache=null}}Xc.extension={type:[C.WebGPUSystem],name:"colorMask"};class Jn{constructor(t){this._renderer=t}async init(t){return this._initPromise?this._initPromise:(this._initPromise=(t.gpu?Promise.resolve(t.gpu):this._createDeviceAndAdaptor(t)).then(e=>{this.gpu=e,this._renderer.runners.contextChange.emit(this.gpu)}),this._initPromise)}contextChange(t){this._renderer.gpu=t}async _createDeviceAndAdaptor(t){const e=await W.get().getNavigator().gpu.requestAdapter({powerPreference:t.powerPreference,forceFallbackAdapter:t.forceFallbackAdapter}),r=["texture-compression-bc","texture-compression-astc","texture-compression-etc2"].filter(a=>e.features.has(a)),n=await e.requestDevice({requiredFeatures:r});return{adapter:e,device:n}}destroy(){this.gpu=null,this._renderer=null}}Jn.extension={type:[C.WebGPUSystem],name:"device"},Jn.defaultOptions={powerPreference:void 0,forceFallbackAdapter:!1};class $c{constructor(t){this._boundBindGroup=Object.create(null),this._boundVertexBuffer=Object.create(null),this._renderer=t}renderStart(){this.commandFinished=new Promise(t=>{this._resolveCommandFinished=t}),this.commandEncoder=this._renderer.gpu.device.createCommandEncoder()}beginRenderPass(t){this.endRenderPass(),this._clearCache(),this.renderPassEncoder=this.commandEncoder.beginRenderPass(t.descriptor)}endRenderPass(){this.renderPassEncoder&&this.renderPassEncoder.end(),this.renderPassEncoder=null}setViewport(t){this.renderPassEncoder.setViewport(t.x,t.y,t.width,t.height,0,1)}setPipelineFromGeometryProgramAndState(t,e,r,n){const a=this._renderer.pipeline.getPipeline(t,e,r,n);this.setPipeline(a)}setPipeline(t){this._boundPipeline!==t&&(this._boundPipeline=t,this.renderPassEncoder.setPipeline(t))}_setVertexBuffer(t,e){this._boundVertexBuffer[t]!==e&&(this._boundVertexBuffer[t]=e,this.renderPassEncoder.setVertexBuffer(t,this._renderer.buffer.updateBuffer(e)))}_setIndexBuffer(t){if(this._boundIndexBuffer===t)return;this._boundIndexBuffer=t;const e=t.data.BYTES_PER_ELEMENT===2?"uint16":"uint32";this.renderPassEncoder.setIndexBuffer(this._renderer.buffer.updateBuffer(t),e)}resetBindGroup(t){this._boundBindGroup[t]=null}setBindGroup(t,e,r){if(this._boundBindGroup[t]===e)return;this._boundBindGroup[t]=e,e._touch(this._renderer.textureGC.count);const n=this._renderer.bindGroup.getBindGroup(e,r,t);this.renderPassEncoder.setBindGroup(t,n)}setGeometry(t,e){const r=this._renderer.pipeline.getBufferNamesToBind(t,e);for(const n in r)this._setVertexBuffer(parseInt(n,10),t.attributes[r[n]].buffer);t.indexBuffer&&this._setIndexBuffer(t.indexBuffer)}_setShaderBindGroups(t,e){for(const r in t.groups){const n=t.groups[r];e||this._syncBindGroup(n),this.setBindGroup(r,n,t.gpuProgram)}}_syncBindGroup(t){for(const e in t.resources){const r=t.resources[e];r.isUniformGroup&&this._renderer.ubo.updateUniformGroup(r)}}draw(t){const{geometry:e,shader:r,state:n,topology:a,size:l,start:h,instanceCount:d,skipSync:f}=t;this.setPipelineFromGeometryProgramAndState(e,r.gpuProgram,n,a),this.setGeometry(e,r.gpuProgram),this._setShaderBindGroups(r,f),e.indexBuffer?this.renderPassEncoder.drawIndexed(l||e.indexBuffer.data.length,d??e.instanceCount,h||0):this.renderPassEncoder.draw(l||e.getSize(),d??e.instanceCount,h||0)}finishRenderPass(){this.renderPassEncoder&&(this.renderPassEncoder.end(),this.renderPassEncoder=null)}postrender(){this.finishRenderPass(),this._gpu.device.queue.submit([this.commandEncoder.finish()]),this._resolveCommandFinished(),this.commandEncoder=null}restoreRenderPass(){const t=this._renderer.renderTarget.adaptor.getDescriptor(this._renderer.renderTarget.renderTarget,!1,[0,0,0,1]);this.renderPassEncoder=this.commandEncoder.beginRenderPass(t);const e=this._boundPipeline,r={...this._boundVertexBuffer},n=this._boundIndexBuffer,a={...this._boundBindGroup};this._clearCache();const l=this._renderer.renderTarget.viewport;this.renderPassEncoder.setViewport(l.x,l.y,l.width,l.height,0,1),this.setPipeline(e);for(const h in r)this._setVertexBuffer(h,r[h]);for(const h in a)this.setBindGroup(h,a[h],null);this._setIndexBuffer(n)}_clearCache(){for(let t=0;t<16;t++)this._boundBindGroup[t]=null,this._boundVertexBuffer[t]=null;this._boundIndexBuffer=null,this._boundPipeline=null}destroy(){this._renderer=null,this._gpu=null,this._boundBindGroup=null,this._boundVertexBuffer=null,this._boundIndexBuffer=null,this._boundPipeline=null}contextChange(t){this._gpu=t}}$c.extension={type:[C.WebGPUSystem],name:"encoder",priority:1};class Kc{constructor(t){this._renderer=t}contextChange(){this.maxTextures=this._renderer.device.gpu.device.limits.maxSampledTexturesPerShaderStage,this.maxBatchableTextures=this.maxTextures}destroy(){}}Kc.extension={type:[C.WebGPUSystem],name:"limits"};class jc{constructor(t){this._renderTargetStencilState=Object.create(null),this._renderer=t,t.renderTarget.onRenderTargetChange.add(this)}onRenderTargetChange(t){let e=this._renderTargetStencilState[t.uid];e||(e=this._renderTargetStencilState[t.uid]={stencilMode:nt.DISABLED,stencilReference:0}),this._activeRenderTarget=t,this.setStencilMode(e.stencilMode,e.stencilReference)}setStencilMode(t,e){const r=this._renderTargetStencilState[this._activeRenderTarget.uid];r.stencilMode=t,r.stencilReference=e;const n=this._renderer;n.pipeline.setStencilMode(t),n.encoder.renderPassEncoder.setStencilReference(e)}destroy(){this._renderer.renderTarget.onRenderTargetChange.remove(this),this._renderer=null,this._activeRenderTarget=null,this._renderTargetStencilState=null}}jc.extension={type:[C.WebGPUSystem],name:"stencil"};const Wr={i32:{align:4,size:4},u32:{align:4,size:4},f32:{align:4,size:4},f16:{align:2,size:2},"vec2<i32>":{align:8,size:8},"vec2<u32>":{align:8,size:8},"vec2<f32>":{align:8,size:8},"vec2<f16>":{align:4,size:4},"vec3<i32>":{align:16,size:12},"vec3<u32>":{align:16,size:12},"vec3<f32>":{align:16,size:12},"vec3<f16>":{align:8,size:6},"vec4<i32>":{align:16,size:16},"vec4<u32>":{align:16,size:16},"vec4<f32>":{align:16,size:16},"vec4<f16>":{align:8,size:8},"mat2x2<f32>":{align:8,size:16},"mat2x2<f16>":{align:4,size:8},"mat3x2<f32>":{align:8,size:24},"mat3x2<f16>":{align:4,size:12},"mat4x2<f32>":{align:8,size:32},"mat4x2<f16>":{align:4,size:16},"mat2x3<f32>":{align:16,size:32},"mat2x3<f16>":{align:8,size:16},"mat3x3<f32>":{align:16,size:48},"mat3x3<f16>":{align:8,size:24},"mat4x3<f32>":{align:16,size:64},"mat4x3<f16>":{align:8,size:32},"mat2x4<f32>":{align:16,size:32},"mat2x4<f16>":{align:8,size:16},"mat3x4<f32>":{align:16,size:48},"mat3x4<f16>":{align:8,size:24},"mat4x4<f32>":{align:16,size:64},"mat4x4<f16>":{align:8,size:32}};function Lx(s){const t=s.map(r=>({data:r,offset:0,size:0}));let e=0;for(let r=0;r<t.length;r++){const n=t[r];let a=Wr[n.data.type].size;const l=Wr[n.data.type].align;if(!Wr[n.data.type])throw new Error(`[Pixi.js] WebGPU UniformBuffer: Unknown type ${n.data.type}`);n.data.size>1&&(a=Math.max(a,l)*n.data.size),e=Math.ceil(e/l)*l,n.size=a,n.offset=e,e+=a}return e=Math.ceil(e/16)*16,{uboElements:t,size:e}}function zx(s,t){const{size:e,align:r}=Wr[s.data.type],n=(r-e)/4,a=s.data.type.indexOf("i32")>=0?"dataInt32":"data";return`
|
|
963
|
+
`,"background: #E72264; padding:5px 0;","background: #6CA2EA; padding:5px 0;","background: #B5D33D; padding:5px 0;","background: #FED23F; padding:5px 0;","color: #FFFFFF; background: #E72264; padding:5px 0;","color: #E72264; background: #FFFFFF; padding:5px 0;"];globalThis.console.log(...t)}else globalThis.console&&globalThis.console.log(`PixiJS ${Ar} - ${s} - http://www.pixijs.com/`);Hc=!0}}class Qn{constructor(t){this._renderer=t}init(t){if(t.hello){let e=this._renderer.name;this._renderer.type===Nt.WEBGL&&(e+=` ${this._renderer.context.webGLVersion}`),Dx(e)}}}Qn.extension={type:[C.WebGLSystem,C.WebGPUSystem,C.CanvasSystem],name:"hello",priority:-2},Qn.defaultOptions={hello:!1};function Ox(s){let t=!1;for(const r in s)if(s[r]==null){t=!0;break}if(!t)return s;const e=Object.create(null);for(const r in s){const n=s[r];n&&(e[r]=n)}return e}function Gx(s){let t=0;for(let e=0;e<s.length;e++)s[e]==null?t++:s[e-t]=s[e];return s.length-=t,s}let Lx=0;const Jn=class uu{constructor(t){this._managedRenderables=[],this._managedHashes=[],this._managedArrays=[],this._renderer=t}init(t){t={...uu.defaultOptions,...t},this.maxUnusedTime=t.renderableGCMaxUnusedTime,this._frequency=t.renderableGCFrequency,this.enabled=t.renderableGCActive}get enabled(){return!!this._handler}set enabled(t){this.enabled!==t&&(t?(this._handler=this._renderer.scheduler.repeat(()=>this.run(),this._frequency,!1),this._hashHandler=this._renderer.scheduler.repeat(()=>{for(const e of this._managedHashes)e.context[e.hash]=Ox(e.context[e.hash])},this._frequency),this._arrayHandler=this._renderer.scheduler.repeat(()=>{for(const e of this._managedArrays)Gx(e.context[e.hash])},this._frequency)):(this._renderer.scheduler.cancel(this._handler),this._renderer.scheduler.cancel(this._hashHandler),this._renderer.scheduler.cancel(this._arrayHandler)))}addManagedHash(t,e){this._managedHashes.push({context:t,hash:e})}addManagedArray(t,e){this._managedArrays.push({context:t,hash:e})}prerender({container:t}){this._now=performance.now(),t.renderGroup.gcTick=Lx++,this._updateInstructionGCTick(t.renderGroup,t.renderGroup.gcTick)}addRenderable(t){this.enabled&&(t._lastUsed===-1&&(this._managedRenderables.push(t),t.once("destroyed",this._removeRenderable,this)),t._lastUsed=this._now)}run(){const t=this._now,e=this._managedRenderables,r=this._renderer.renderPipes;let n=0;for(let o=0;o<e.length;o++){const l=e[o];if(l===null){n++;continue}const h=l.renderGroup??l.parentRenderGroup,u=h?.instructionSet?.gcTick??-1;if((h?.gcTick??0)===u&&(l._lastUsed=t),t-l._lastUsed>this.maxUnusedTime){if(!l.destroyed){const f=r;h&&(h.structureDidChange=!0),f[l.renderPipeId].destroyRenderable(l)}l._lastUsed=-1,n++,l.off("destroyed",this._removeRenderable,this)}else e[o-n]=l}e.length-=n}destroy(){this.enabled=!1,this._renderer=null,this._managedRenderables.length=0,this._managedHashes.length=0,this._managedArrays.length=0}_removeRenderable(t){const e=this._managedRenderables.indexOf(t);e>=0&&(t.off("destroyed",this._removeRenderable,this),this._managedRenderables[e]=null)}_updateInstructionGCTick(t,e){t.instructionSet.gcTick=e;for(const r of t.renderGroupChildren)this._updateInstructionGCTick(r,e)}};Jn.extension={type:[C.WebGLSystem,C.WebGPUSystem],name:"renderableGC",priority:0},Jn.defaultOptions={renderableGCActive:!0,renderableGCMaxUnusedTime:6e4,renderableGCFrequency:3e4};let zx=Jn;const to=class fu{constructor(t){this._renderer=t,this.count=0,this.checkCount=0}init(t){t={...fu.defaultOptions,...t},this.checkCountMax=t.textureGCCheckCountMax,this.maxIdle=t.textureGCAMaxIdle??t.textureGCMaxIdle,this.active=t.textureGCActive}postrender(){this._renderer.renderingToScreen&&(this.count++,this.active&&(this.checkCount++,this.checkCount>this.checkCountMax&&(this.checkCount=0,this.run())))}run(){const t=this._renderer.texture.managedTextures;for(let e=0;e<t.length;e++){const r=t[e];r.autoGarbageCollect&&r.resource&&r._touched>-1&&this.count-r._touched>this.maxIdle&&(r._touched=-1,r.unload())}}destroy(){this._renderer=null}};to.extension={type:[C.WebGLSystem,C.WebGPUSystem],name:"textureGC"},to.defaultOptions={textureGCActive:!0,textureGCAMaxIdle:null,textureGCMaxIdle:3600,textureGCCheckCountMax:600};let Nx=to;const eo=class pu{get autoDensity(){return this.texture.source.autoDensity}set autoDensity(t){this.texture.source.autoDensity=t}get resolution(){return this.texture.source._resolution}set resolution(t){this.texture.source.resize(this.texture.source.width,this.texture.source.height,t)}init(t){t={...pu.defaultOptions,...t},t.view&&(z($,"ViewSystem.view has been renamed to ViewSystem.canvas"),t.canvas=t.view),this.screen=new G(0,0,t.width,t.height),this.canvas=t.canvas||W.get().createCanvas(),this.antialias=!!t.antialias,this.texture=uc(this.canvas,t),this.renderTarget=new Wn({colorTextures:[this.texture],depth:!!t.depth,isRoot:!0}),this.texture.source.transparent=t.backgroundAlpha<1,this.resolution=t.resolution}resize(t,e,r){this.texture.source.resize(t,e,r),this.screen.width=this.texture.frame.width,this.screen.height=this.texture.frame.height}destroy(t=!1){(typeof t=="boolean"?t:!!t?.removeView)&&this.canvas.parentNode&&this.canvas.parentNode.removeChild(this.canvas),this.texture.destroy()}};eo.extension={type:[C.WebGLSystem,C.WebGPUSystem,C.CanvasSystem],name:"view",priority:0},eo.defaultOptions={width:800,height:600,autoDensity:!1,antialias:!1};const Wc=[Ux,zc,Qn,eo,Dc,Nx,Lc,kx,bh,zx,Nc],Vc=[Gc,Kl,Oc,kc,jl,Zl,ql,Uc],Hx=[...Wc,dc,Ly,Iy,nc,Ql,Ac,mc,ic,wc,vc,sc,fx,oc,rc],Wx=[...Vc],Vx=[Xl,Bc,Pc],Yc=[],Xc=[],$c=[];D.handleByNamedList(C.WebGLSystem,Yc),D.handleByNamedList(C.WebGLPipes,Xc),D.handleByNamedList(C.WebGLPipesAdaptor,$c),D.add(...Hx,...Wx,...Vx);class Yx extends Tr{constructor(){const t={name:"webgl",type:Nt.WEBGL,systems:Yc,renderPipes:Xc,renderPipeAdaptors:$c};super(t)}}const Xx=Object.freeze(Object.defineProperty({__proto__:null,WebGLRenderer:Yx},Symbol.toStringTag,{value:"Module"}));class Kc{constructor(t){this._hash=Object.create(null),this._renderer=t,this._renderer.renderableGC.addManagedHash(this,"_hash")}contextChange(t){this._gpu=t}getBindGroup(t,e,r){return t._updateKey(),this._hash[t._key]||this._createBindGroup(t,e,r)}_createBindGroup(t,e,r){const n=this._gpu.device,o=e.layout[r],l=[],h=this._renderer;for(const m in o){const g=t.resources[m]??t.resources[o[m]];let y;if(g._resourceType==="uniformGroup"){const x=g;h.ubo.updateUniformGroup(x);const a=x.buffer;y={buffer:h.buffer.getGPUBuffer(a),offset:0,size:a.descriptor.size}}else if(g._resourceType==="buffer"){const x=g;y={buffer:h.buffer.getGPUBuffer(x),offset:0,size:x.descriptor.size}}else if(g._resourceType==="bufferResource"){const x=g;y={buffer:h.buffer.getGPUBuffer(x.buffer),offset:x.offset,size:x.size}}else if(g._resourceType==="textureSampler"){const x=g;y=h.texture.getGpuSampler(x)}else if(g._resourceType==="textureSource"){const x=g;y=h.texture.getGpuSource(x).createView({})}l.push({binding:o[m],resource:y})}const u=h.shader.getProgramData(e).bindGroups[r],f=n.createBindGroup({layout:u,entries:l});return this._hash[t._key]=f,f}destroy(){for(const t of Object.keys(this._hash))this._hash[t]=null;this._hash=null,this._renderer=null}}Kc.extension={type:[C.WebGPUSystem],name:"bindGroup"};class jc{constructor(t){this._gpuBuffers=Object.create(null),t.renderableGC.addManagedHash(this,"_gpuBuffers")}contextChange(t){this._gpu=t}getGPUBuffer(t){return this._gpuBuffers[t.uid]||this.createGPUBuffer(t)}updateBuffer(t){const e=this._gpuBuffers[t.uid]||this.createGPUBuffer(t),r=t.data;return t._updateID&&r&&(t._updateID=0,this._gpu.device.queue.writeBuffer(e,0,r.buffer,0,(t._updateSize||r.byteLength)+3&-4)),e}destroyAll(){for(const t in this._gpuBuffers)this._gpuBuffers[t]?.destroy();this._gpuBuffers={}}createGPUBuffer(t){this._gpuBuffers[t.uid]||(t.on("update",this.updateBuffer,this),t.on("change",this.onBufferChange,this),t.on("destroy",this.onBufferDestroy,this));const e=this._gpu.device.createBuffer(t.descriptor);return t._updateID=0,t.data&&(ln(t.data.buffer,e.getMappedRange()),e.unmap()),this._gpuBuffers[t.uid]=e,e}onBufferChange(t){this._gpuBuffers[t.uid].destroy(),t._updateID=0,this._gpuBuffers[t.uid]=this.createGPUBuffer(t)}onBufferDestroy(t){this._destroyBuffer(t)}destroy(){this.destroyAll(),this._gpuBuffers={}}_destroyBuffer(t){if(t.off("update",this.updateBuffer,this),t.off("change",this.onBufferChange,this),t.off("destroy",this.onBufferDestroy,this),!this._gpuBuffers[t.uid])return;this._gpuBuffers[t.uid].destroy(),this._gpuBuffers[t.uid]=null}}jc.extension={type:[C.WebGPUSystem],name:"buffer"};class $x{constructor({minUniformOffsetAlignment:t}){this._minUniformOffsetAlignment=256,this.byteIndex=0,this._minUniformOffsetAlignment=t,this.data=new Float32Array(65535)}clear(){this.byteIndex=0}addEmptyGroup(t){if(t>this._minUniformOffsetAlignment/4)throw new Error(`UniformBufferBatch: array is too large: ${t*4}`);const e=this.byteIndex;let r=e+t*4;if(r=Math.ceil(r/this._minUniformOffsetAlignment)*this._minUniformOffsetAlignment,r>this.data.length*4)throw new Error("UniformBufferBatch: ubo batch got too big");return this.byteIndex=r,e}addGroup(t){const e=this.addEmptyGroup(t.length);for(let r=0;r<t.length;r++)this.data[e/4+r]=t[r];return e}destroy(){this.data=null}}class qc{constructor(t){this._colorMaskCache=15,this._renderer=t}setMask(t){this._colorMaskCache!==t&&(this._colorMaskCache=t,this._renderer.pipeline.setColorMask(t))}destroy(){this._renderer=null,this._colorMaskCache=null}}qc.extension={type:[C.WebGPUSystem],name:"colorMask"};class io{constructor(t){this._renderer=t}async init(t){return this._initPromise?this._initPromise:(this._initPromise=(t.gpu?Promise.resolve(t.gpu):this._createDeviceAndAdaptor(t)).then(e=>{this.gpu=e,this._renderer.runners.contextChange.emit(this.gpu)}),this._initPromise)}contextChange(t){this._renderer.gpu=t}async _createDeviceAndAdaptor(t){const e=await W.get().getNavigator().gpu.requestAdapter({powerPreference:t.powerPreference,forceFallbackAdapter:t.forceFallbackAdapter}),r=["texture-compression-bc","texture-compression-astc","texture-compression-etc2"].filter(o=>e.features.has(o)),n=await e.requestDevice({requiredFeatures:r});return{adapter:e,device:n}}destroy(){this.gpu=null,this._renderer=null}}io.extension={type:[C.WebGPUSystem],name:"device"},io.defaultOptions={powerPreference:void 0,forceFallbackAdapter:!1};class Zc{constructor(t){this._boundBindGroup=Object.create(null),this._boundVertexBuffer=Object.create(null),this._renderer=t}renderStart(){this.commandFinished=new Promise(t=>{this._resolveCommandFinished=t}),this.commandEncoder=this._renderer.gpu.device.createCommandEncoder()}beginRenderPass(t){this.endRenderPass(),this._clearCache(),this.renderPassEncoder=this.commandEncoder.beginRenderPass(t.descriptor)}endRenderPass(){this.renderPassEncoder&&this.renderPassEncoder.end(),this.renderPassEncoder=null}setViewport(t){this.renderPassEncoder.setViewport(t.x,t.y,t.width,t.height,0,1)}setPipelineFromGeometryProgramAndState(t,e,r,n){const o=this._renderer.pipeline.getPipeline(t,e,r,n);this.setPipeline(o)}setPipeline(t){this._boundPipeline!==t&&(this._boundPipeline=t,this.renderPassEncoder.setPipeline(t))}_setVertexBuffer(t,e){this._boundVertexBuffer[t]!==e&&(this._boundVertexBuffer[t]=e,this.renderPassEncoder.setVertexBuffer(t,this._renderer.buffer.updateBuffer(e)))}_setIndexBuffer(t){if(this._boundIndexBuffer===t)return;this._boundIndexBuffer=t;const e=t.data.BYTES_PER_ELEMENT===2?"uint16":"uint32";this.renderPassEncoder.setIndexBuffer(this._renderer.buffer.updateBuffer(t),e)}resetBindGroup(t){this._boundBindGroup[t]=null}setBindGroup(t,e,r){if(this._boundBindGroup[t]===e)return;this._boundBindGroup[t]=e,e._touch(this._renderer.textureGC.count);const n=this._renderer.bindGroup.getBindGroup(e,r,t);this.renderPassEncoder.setBindGroup(t,n)}setGeometry(t,e){const r=this._renderer.pipeline.getBufferNamesToBind(t,e);for(const n in r)this._setVertexBuffer(parseInt(n,10),t.attributes[r[n]].buffer);t.indexBuffer&&this._setIndexBuffer(t.indexBuffer)}_setShaderBindGroups(t,e){for(const r in t.groups){const n=t.groups[r];e||this._syncBindGroup(n),this.setBindGroup(r,n,t.gpuProgram)}}_syncBindGroup(t){for(const e in t.resources){const r=t.resources[e];r.isUniformGroup&&this._renderer.ubo.updateUniformGroup(r)}}draw(t){const{geometry:e,shader:r,state:n,topology:o,size:l,start:h,instanceCount:u,skipSync:f}=t;this.setPipelineFromGeometryProgramAndState(e,r.gpuProgram,n,o),this.setGeometry(e,r.gpuProgram),this._setShaderBindGroups(r,f),e.indexBuffer?this.renderPassEncoder.drawIndexed(l||e.indexBuffer.data.length,u??e.instanceCount,h||0):this.renderPassEncoder.draw(l||e.getSize(),u??e.instanceCount,h||0)}finishRenderPass(){this.renderPassEncoder&&(this.renderPassEncoder.end(),this.renderPassEncoder=null)}postrender(){this.finishRenderPass(),this._gpu.device.queue.submit([this.commandEncoder.finish()]),this._resolveCommandFinished(),this.commandEncoder=null}restoreRenderPass(){const t=this._renderer.renderTarget.adaptor.getDescriptor(this._renderer.renderTarget.renderTarget,!1,[0,0,0,1]);this.renderPassEncoder=this.commandEncoder.beginRenderPass(t);const e=this._boundPipeline,r={...this._boundVertexBuffer},n=this._boundIndexBuffer,o={...this._boundBindGroup};this._clearCache();const l=this._renderer.renderTarget.viewport;this.renderPassEncoder.setViewport(l.x,l.y,l.width,l.height,0,1),this.setPipeline(e);for(const h in r)this._setVertexBuffer(h,r[h]);for(const h in o)this.setBindGroup(h,o[h],null);this._setIndexBuffer(n)}_clearCache(){for(let t=0;t<16;t++)this._boundBindGroup[t]=null,this._boundVertexBuffer[t]=null;this._boundIndexBuffer=null,this._boundPipeline=null}destroy(){this._renderer=null,this._gpu=null,this._boundBindGroup=null,this._boundVertexBuffer=null,this._boundIndexBuffer=null,this._boundPipeline=null}contextChange(t){this._gpu=t}}Zc.extension={type:[C.WebGPUSystem],name:"encoder",priority:1};class Qc{constructor(t){this._renderer=t}contextChange(){this.maxTextures=this._renderer.device.gpu.device.limits.maxSampledTexturesPerShaderStage,this.maxBatchableTextures=this.maxTextures}destroy(){}}Qc.extension={type:[C.WebGPUSystem],name:"limits"};class Jc{constructor(t){this._renderTargetStencilState=Object.create(null),this._renderer=t,t.renderTarget.onRenderTargetChange.add(this)}onRenderTargetChange(t){let e=this._renderTargetStencilState[t.uid];e||(e=this._renderTargetStencilState[t.uid]={stencilMode:ot.DISABLED,stencilReference:0}),this._activeRenderTarget=t,this.setStencilMode(e.stencilMode,e.stencilReference)}setStencilMode(t,e){const r=this._renderTargetStencilState[this._activeRenderTarget.uid];r.stencilMode=t,r.stencilReference=e;const n=this._renderer;n.pipeline.setStencilMode(t),n.encoder.renderPassEncoder.setStencilReference(e)}destroy(){this._renderer.renderTarget.onRenderTargetChange.remove(this),this._renderer=null,this._activeRenderTarget=null,this._renderTargetStencilState=null}}Jc.extension={type:[C.WebGPUSystem],name:"stencil"};const Yr={i32:{align:4,size:4},u32:{align:4,size:4},f32:{align:4,size:4},f16:{align:2,size:2},"vec2<i32>":{align:8,size:8},"vec2<u32>":{align:8,size:8},"vec2<f32>":{align:8,size:8},"vec2<f16>":{align:4,size:4},"vec3<i32>":{align:16,size:12},"vec3<u32>":{align:16,size:12},"vec3<f32>":{align:16,size:12},"vec3<f16>":{align:8,size:6},"vec4<i32>":{align:16,size:16},"vec4<u32>":{align:16,size:16},"vec4<f32>":{align:16,size:16},"vec4<f16>":{align:8,size:8},"mat2x2<f32>":{align:8,size:16},"mat2x2<f16>":{align:4,size:8},"mat3x2<f32>":{align:8,size:24},"mat3x2<f16>":{align:4,size:12},"mat4x2<f32>":{align:8,size:32},"mat4x2<f16>":{align:4,size:16},"mat2x3<f32>":{align:16,size:32},"mat2x3<f16>":{align:8,size:16},"mat3x3<f32>":{align:16,size:48},"mat3x3<f16>":{align:8,size:24},"mat4x3<f32>":{align:16,size:64},"mat4x3<f16>":{align:8,size:32},"mat2x4<f32>":{align:16,size:32},"mat2x4<f16>":{align:8,size:16},"mat3x4<f32>":{align:16,size:48},"mat3x4<f16>":{align:8,size:24},"mat4x4<f32>":{align:16,size:64},"mat4x4<f16>":{align:8,size:32}};function Kx(s){const t=s.map(r=>({data:r,offset:0,size:0}));let e=0;for(let r=0;r<t.length;r++){const n=t[r];let o=Yr[n.data.type].size;const l=Yr[n.data.type].align;if(!Yr[n.data.type])throw new Error(`[Pixi.js] WebGPU UniformBuffer: Unknown type ${n.data.type}`);n.data.size>1&&(o=Math.max(o,l)*n.data.size),e=Math.ceil(e/l)*l,n.size=o,n.offset=e,e+=o}return e=Math.ceil(e/16)*16,{uboElements:t,size:e}}function jx(s,t){const{size:e,align:r}=Yr[s.data.type],n=(r-e)/4,o=s.data.type.indexOf("i32")>=0?"dataInt32":"data";return`
|
|
964
964
|
v = uv.${s.data.name};
|
|
965
965
|
${t!==0?`offset += ${t};`:""}
|
|
966
966
|
|
|
@@ -972,11 +972,11 @@ fn mainFragment(
|
|
|
972
972
|
{
|
|
973
973
|
for(var j = 0; j < ${e/4}; j++)
|
|
974
974
|
{
|
|
975
|
-
${
|
|
975
|
+
${o}[arrayOffset++] = v[t++];
|
|
976
976
|
}
|
|
977
977
|
${n!==0?`arrayOffset += ${n};`:""}
|
|
978
978
|
}
|
|
979
|
-
`}function Nx(s){return nc(s,"uboWgsl",zx,Ry)}class qc extends rc{constructor(){super({createUboElements:Lx,generateUboSync:Nx})}}qc.extension={type:[C.WebGPUSystem],name:"ubo"};const ge=128;class Zc{constructor(t){this._bindGroupHash=Object.create(null),this._buffers=[],this._bindGroups=[],this._bufferResources=[],this._renderer=t,this._renderer.renderableGC.addManagedHash(this,"_bindGroupHash"),this._batchBuffer=new Ox({minUniformOffsetAlignment:ge});const e=256/ge;for(let r=0;r<e;r++){let n=Y.UNIFORM|Y.COPY_DST;r===0&&(n|=Y.COPY_SRC),this._buffers.push(new Pt({data:this._batchBuffer.data,usage:n}))}}renderEnd(){this._uploadBindGroups(),this._resetBindGroups()}_resetBindGroups(){for(const t in this._bindGroupHash)this._bindGroupHash[t]=null;this._batchBuffer.clear()}getUniformBindGroup(t,e){if(!e&&this._bindGroupHash[t.uid])return this._bindGroupHash[t.uid];this._renderer.ubo.ensureUniformGroup(t);const r=t.buffer.data,n=this._batchBuffer.addEmptyGroup(r.length);return this._renderer.ubo.syncUniformGroup(t,this._batchBuffer.data,n/4),this._bindGroupHash[t.uid]=this._getBindGroup(n/ge),this._bindGroupHash[t.uid]}getUboResource(t){this._renderer.ubo.updateUniformGroup(t);const e=t.buffer.data,r=this._batchBuffer.addGroup(e);return this._getBufferResource(r/ge)}getArrayBindGroup(t){const e=this._batchBuffer.addGroup(t);return this._getBindGroup(e/ge)}getArrayBufferResource(t){const r=this._batchBuffer.addGroup(t)/ge;return this._getBufferResource(r)}_getBufferResource(t){if(!this._bufferResources[t]){const e=this._buffers[t%2];this._bufferResources[t]=new Nn({buffer:e,offset:(t/2|0)*256,size:ge})}return this._bufferResources[t]}_getBindGroup(t){if(!this._bindGroups[t]){const e=new re({0:this._getBufferResource(t)});this._bindGroups[t]=e}return this._bindGroups[t]}_uploadBindGroups(){const t=this._renderer.buffer,e=this._buffers[0];e.update(this._batchBuffer.byteIndex),t.updateBuffer(e);const r=this._renderer.gpu.device.createCommandEncoder();for(let n=1;n<this._buffers.length;n++){const a=this._buffers[n];r.copyBufferToBuffer(t.getGPUBuffer(e),ge,t.getGPUBuffer(a),0,this._batchBuffer.byteIndex)}this._renderer.gpu.device.queue.submit([r.finish()])}destroy(){for(let t=0;t<this._bindGroups.length;t++)this._bindGroups[t]?.destroy();this._bindGroups=null,this._bindGroupHash=null;for(let t=0;t<this._buffers.length;t++)this._buffers[t].destroy();this._buffers=null;for(let t=0;t<this._bufferResources.length;t++)this._bufferResources[t].destroy();this._bufferResources=null,this._batchBuffer.destroy(),this._bindGroupHash=null,this._renderer=null}}Zc.extension={type:[C.WebGPUPipes],name:"uniformBatch"};const Hx={"point-list":0,"line-list":1,"line-strip":2,"triangle-list":3,"triangle-strip":4};function Wx(s,t,e,r,n){return s<<24|t<<16|e<<10|r<<5|n}function Vx(s,t,e,r){return e<<6|s<<3|r<<1|t}class Qc{constructor(t){this._moduleCache=Object.create(null),this._bufferLayoutsCache=Object.create(null),this._bindingNamesCache=Object.create(null),this._pipeCache=Object.create(null),this._pipeStateCaches=Object.create(null),this._colorMask=15,this._multisampleCount=1,this._renderer=t}contextChange(t){this._gpu=t,this.setStencilMode(nt.DISABLED),this._updatePipeHash()}setMultisampleCount(t){this._multisampleCount!==t&&(this._multisampleCount=t,this._updatePipeHash())}setRenderTarget(t){this._multisampleCount=t.msaaSamples,this._depthStencilAttachment=t.descriptor.depthStencilAttachment?1:0,this._updatePipeHash()}setColorMask(t){this._colorMask!==t&&(this._colorMask=t,this._updatePipeHash())}setStencilMode(t){this._stencilMode!==t&&(this._stencilMode=t,this._stencilState=me[t],this._updatePipeHash())}setPipeline(t,e,r,n){const a=this.getPipeline(t,e,r);n.setPipeline(a)}getPipeline(t,e,r,n){t._layoutKey||(jl(t,e.attributeData),this._generateBufferKey(t)),n||(n=t.topology);const a=Wx(t._layoutKey,e._layoutKey,r.data,r._blendModeId,Hx[n]);return this._pipeCache[a]?this._pipeCache[a]:(this._pipeCache[a]=this._createPipeline(t,e,r,n),this._pipeCache[a])}_createPipeline(t,e,r,n){const a=this._gpu.device,l=this._createVertexBufferLayouts(t,e),h=this._renderer.state.getColorTargets(r);h[0].writeMask=this._stencilMode===nt.RENDERING_MASK_ADD?0:this._colorMask;const d=this._renderer.shader.getProgramData(e).pipeline,f={vertex:{module:this._getModule(e.vertex.source),entryPoint:e.vertex.entryPoint,buffers:l},fragment:{module:this._getModule(e.fragment.source),entryPoint:e.fragment.entryPoint,targets:h},primitive:{topology:n,cullMode:r.cullMode},layout:d,multisample:{count:this._multisampleCount},label:"PIXI Pipeline"};return this._depthStencilAttachment&&(f.depthStencil={...this._stencilState,format:"depth24plus-stencil8",depthWriteEnabled:r.depthTest,depthCompare:r.depthTest?"less":"always"}),a.createRenderPipeline(f)}_getModule(t){return this._moduleCache[t]||this._createModule(t)}_createModule(t){const e=this._gpu.device;return this._moduleCache[t]=e.createShaderModule({code:t}),this._moduleCache[t]}_generateBufferKey(t){const e=[];let r=0;const n=Object.keys(t.attributes).sort();for(let l=0;l<n.length;l++){const h=t.attributes[n[l]];e[r++]=h.offset,e[r++]=h.format,e[r++]=h.stride,e[r++]=h.instance}const a=e.join("|");return t._layoutKey=mi(a,"geometry"),t._layoutKey}_generateAttributeLocationsKey(t){const e=[];let r=0;const n=Object.keys(t.attributeData).sort();for(let l=0;l<n.length;l++){const h=t.attributeData[n[l]];e[r++]=h.location}const a=e.join("|");return t._attributeLocationsKey=mi(a,"programAttributes"),t._attributeLocationsKey}getBufferNamesToBind(t,e){const r=t._layoutKey<<16|e._attributeLocationsKey;if(this._bindingNamesCache[r])return this._bindingNamesCache[r];const n=this._createVertexBufferLayouts(t,e),a=Object.create(null),l=e.attributeData;for(let h=0;h<n.length;h++){const f=Object.values(n[h].attributes)[0].shaderLocation;for(const m in l)if(l[m].location===f){a[h]=m;break}}return this._bindingNamesCache[r]=a,a}_createVertexBufferLayouts(t,e){e._attributeLocationsKey||this._generateAttributeLocationsKey(e);const r=t._layoutKey<<16|e._attributeLocationsKey;if(this._bufferLayoutsCache[r])return this._bufferLayoutsCache[r];const n=[];return t.buffers.forEach(a=>{const l={arrayStride:0,stepMode:"vertex",attributes:[]},h=l.attributes;for(const d in e.attributeData){const f=t.attributes[d];(f.divisor??1)!==1&&F(`Attribute ${d} has an invalid divisor value of '${f.divisor}'. WebGPU only supports a divisor value of 1`),f.buffer===a&&(l.arrayStride=f.stride,l.stepMode=f.instance?"instance":"vertex",h.push({shaderLocation:e.attributeData[d].location,offset:f.offset,format:f.format}))}h.length&&n.push(l)}),this._bufferLayoutsCache[r]=n,n}_updatePipeHash(){const t=Vx(this._stencilMode,this._multisampleCount,this._colorMask,this._depthStencilAttachment);this._pipeStateCaches[t]||(this._pipeStateCaches[t]=Object.create(null)),this._pipeCache=this._pipeStateCaches[t]}destroy(){this._renderer=null,this._bufferLayoutsCache=null}}Qc.extension={type:[C.WebGPUSystem],name:"pipeline"};class Yx{constructor(){this.contexts=[],this.msaaTextures=[],this.msaaSamples=1}}class Xx{init(t,e){this._renderer=t,this._renderTargetSystem=e}copyToTexture(t,e,r,n,a){const l=this._renderer,h=this._getGpuColorTexture(t),d=l.texture.getGpuSource(e.source);return l.encoder.commandEncoder.copyTextureToTexture({texture:h,origin:r},{texture:d,origin:a},n),e}startRenderPass(t,e=!0,r,n){const l=this._renderTargetSystem.getGpuRenderTarget(t),h=this.getDescriptor(t,e,r);l.descriptor=h,this._renderer.pipeline.setRenderTarget(l),this._renderer.encoder.beginRenderPass(l),this._renderer.encoder.setViewport(n)}finishRenderPass(){this._renderer.encoder.endRenderPass()}_getGpuColorTexture(t){const e=this._renderTargetSystem.getGpuRenderTarget(t);return e.contexts[0]?e.contexts[0].getCurrentTexture():this._renderer.texture.getGpuSource(t.colorTextures[0].source)}getDescriptor(t,e,r){typeof e=="boolean"&&(e=e?At.ALL:At.NONE);const n=this._renderTargetSystem,a=n.getGpuRenderTarget(t),l=t.colorTextures.map((f,m)=>{const g=a.contexts[m];let y,x;g?y=g.getCurrentTexture().createView():y=this._renderer.texture.getGpuSource(f).createView({mipLevelCount:1}),a.msaaTextures[m]&&(x=y,y=this._renderer.texture.getTextureView(a.msaaTextures[m]));const o=e&At.COLOR?"clear":"load";return r??(r=n.defaultClearColor),{view:y,resolveTarget:x,clearValue:r,storeOp:"store",loadOp:o}});let h;if((t.stencil||t.depth)&&!t.depthStencilTexture&&(t.ensureDepthStencilTexture(),t.depthStencilTexture.source.sampleCount=a.msaa?4:1),t.depthStencilTexture){const f=e&At.STENCIL?"clear":"load",m=e&At.DEPTH?"clear":"load";h={view:this._renderer.texture.getGpuSource(t.depthStencilTexture.source).createView(),stencilStoreOp:"store",stencilLoadOp:f,depthClearValue:1,depthLoadOp:m,depthStoreOp:"store"}}return{colorAttachments:l,depthStencilAttachment:h}}clear(t,e=!0,r,n){if(!e)return;const{gpu:a,encoder:l}=this._renderer,h=a.device;if(l.commandEncoder===null){const f=h.createCommandEncoder(),m=this.getDescriptor(t,e,r),g=f.beginRenderPass(m);g.setViewport(n.x,n.y,n.width,n.height,0,1),g.end();const y=f.finish();h.queue.submit([y])}else this.startRenderPass(t,e,r,n)}initGpuRenderTarget(t){t.isRoot=!0;const e=new Yx;return t.colorTextures.forEach((r,n)=>{if(r instanceof ee){const a=r.resource.getContext("webgpu"),l=r.transparent?"premultiplied":"opaque";try{a.configure({device:this._renderer.gpu.device,usage:GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_DST|GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.COPY_SRC,format:"bgra8unorm",alphaMode:l})}catch(h){console.error(h)}e.contexts[n]=a}if(e.msaa=r.source.antialias,r.source.antialias){const a=new ht({width:0,height:0,sampleCount:4});e.msaaTextures[n]=a}}),e.msaa&&(e.msaaSamples=4,t.depthStencilTexture&&(t.depthStencilTexture.source.sampleCount=4)),e}destroyGpuRenderTarget(t){t.contexts.forEach(e=>{e.unconfigure()}),t.msaaTextures.forEach(e=>{e.destroy()}),t.msaaTextures.length=0,t.contexts.length=0}ensureDepthStencilTexture(t){const e=this._renderTargetSystem.getGpuRenderTarget(t);t.depthStencilTexture&&e.msaa&&(t.depthStencilTexture.source.sampleCount=4)}resizeGpuRenderTarget(t){const e=this._renderTargetSystem.getGpuRenderTarget(t);e.width=t.width,e.height=t.height,e.msaa&&t.colorTextures.forEach((r,n)=>{e.msaaTextures[n]?.resize(r.source.width,r.source.height,r.source._resolution)})}}class Jc extends cc{constructor(t){super(t),this.adaptor=new Xx,this.adaptor.init(t,this)}}Jc.extension={type:[C.WebGPUSystem],name:"renderTarget"};class tu{constructor(){this._gpuProgramData=Object.create(null)}contextChange(t){this._gpu=t}getProgramData(t){return this._gpuProgramData[t._layoutKey]||this._createGPUProgramData(t)}_createGPUProgramData(t){const e=this._gpu.device,r=t.gpuLayout.map(a=>e.createBindGroupLayout({entries:a})),n={bindGroupLayouts:r};return this._gpuProgramData[t._layoutKey]={bindGroups:r,pipeline:e.createPipelineLayout(n)},this._gpuProgramData[t._layoutKey]}destroy(){this._gpu=null,this._gpuProgramData=null}}tu.extension={type:[C.WebGPUSystem],name:"shader"};const bt={};bt.normal={alpha:{srcFactor:"one",dstFactor:"one-minus-src-alpha",operation:"add"},color:{srcFactor:"one",dstFactor:"one-minus-src-alpha",operation:"add"}},bt.add={alpha:{srcFactor:"src-alpha",dstFactor:"one-minus-src-alpha",operation:"add"},color:{srcFactor:"one",dstFactor:"one",operation:"add"}},bt.multiply={alpha:{srcFactor:"one",dstFactor:"one-minus-src-alpha",operation:"add"},color:{srcFactor:"dst",dstFactor:"one-minus-src-alpha",operation:"add"}},bt.screen={alpha:{srcFactor:"one",dstFactor:"one-minus-src-alpha",operation:"add"},color:{srcFactor:"one",dstFactor:"one-minus-src",operation:"add"}},bt.overlay={alpha:{srcFactor:"one",dstFactor:"one-minus-src-alpha",operation:"add"},color:{srcFactor:"one",dstFactor:"one-minus-src",operation:"add"}},bt.none={alpha:{srcFactor:"one",dstFactor:"one-minus-src-alpha",operation:"add"},color:{srcFactor:"zero",dstFactor:"zero",operation:"add"}},bt["normal-npm"]={alpha:{srcFactor:"one",dstFactor:"one-minus-src-alpha",operation:"add"},color:{srcFactor:"src-alpha",dstFactor:"one-minus-src-alpha",operation:"add"}},bt["add-npm"]={alpha:{srcFactor:"one",dstFactor:"one",operation:"add"},color:{srcFactor:"src-alpha",dstFactor:"one",operation:"add"}},bt["screen-npm"]={alpha:{srcFactor:"one",dstFactor:"one-minus-src-alpha",operation:"add"},color:{srcFactor:"src-alpha",dstFactor:"one-minus-src",operation:"add"}},bt.erase={alpha:{srcFactor:"zero",dstFactor:"one-minus-src-alpha",operation:"add"},color:{srcFactor:"zero",dstFactor:"one-minus-src",operation:"add"}},bt.min={alpha:{srcFactor:"one",dstFactor:"one",operation:"min"},color:{srcFactor:"one",dstFactor:"one",operation:"min"}},bt.max={alpha:{srcFactor:"one",dstFactor:"one",operation:"max"},color:{srcFactor:"one",dstFactor:"one",operation:"max"}};class eu{constructor(){this.defaultState=new Ht,this.defaultState.blend=!0}contextChange(t){this.gpu=t}getColorTargets(t){return[{format:"bgra8unorm",writeMask:0,blend:bt[t.blendMode]||bt.normal}]}destroy(){this.gpu=null}}eu.extension={type:[C.WebGPUSystem],name:"state"};const $x={type:"image",upload(s,t,e){const r=s.resource,n=(s.pixelWidth|0)*(s.pixelHeight|0),a=r.byteLength/n;e.device.queue.writeTexture({texture:t},r,{offset:0,rowsPerImage:s.pixelHeight,bytesPerRow:s.pixelWidth*a},{width:s.pixelWidth,height:s.pixelHeight,depthOrArrayLayers:1})}},iu={"bc1-rgba-unorm":{blockBytes:8,blockWidth:4,blockHeight:4},"bc2-rgba-unorm":{blockBytes:16,blockWidth:4,blockHeight:4},"bc3-rgba-unorm":{blockBytes:16,blockWidth:4,blockHeight:4},"bc7-rgba-unorm":{blockBytes:16,blockWidth:4,blockHeight:4},"etc1-rgb-unorm":{blockBytes:8,blockWidth:4,blockHeight:4},"etc2-rgba8unorm":{blockBytes:16,blockWidth:4,blockHeight:4},"astc-4x4-unorm":{blockBytes:16,blockWidth:4,blockHeight:4}},Kx={blockBytes:4,blockWidth:1,blockHeight:1},jx={type:"compressed",upload(s,t,e){let r=s.pixelWidth,n=s.pixelHeight;const a=iu[s.format]||Kx;for(let l=0;l<s.resource.length;l++){const h=s.resource[l],d=Math.ceil(r/a.blockWidth)*a.blockBytes;e.device.queue.writeTexture({texture:t,mipLevel:l},h,{offset:0,bytesPerRow:d},{width:Math.ceil(r/a.blockWidth)*a.blockWidth,height:Math.ceil(n/a.blockHeight)*a.blockHeight,depthOrArrayLayers:1}),r=Math.max(r>>1,1),n=Math.max(n>>1,1)}}},ru={type:"image",upload(s,t,e){const r=s.resource;if(!r)return;if(globalThis.HTMLImageElement&&r instanceof HTMLImageElement){const h=W.get().createCanvas(r.width,r.height);h.getContext("2d").drawImage(r,0,0,r.width,r.height),s.resource=h,F("ImageSource: Image element passed, converting to canvas and replacing resource.")}const n=Math.min(t.width,s.resourceWidth||s.pixelWidth),a=Math.min(t.height,s.resourceHeight||s.pixelHeight),l=s.alphaMode==="premultiply-alpha-on-upload";e.device.queue.copyExternalImageToTexture({source:r},{texture:t,premultipliedAlpha:l},{width:n,height:a})}},qx={type:"video",upload(s,t,e){ru.upload(s,t,e)}};class Zx{constructor(t){this.device=t,this.sampler=t.createSampler({minFilter:"linear"}),this.pipelines={}}_getMipmapPipeline(t){let e=this.pipelines[t];return e||(this.mipmapShaderModule||(this.mipmapShaderModule=this.device.createShaderModule({code:`
|
|
979
|
+
`}function qx(s){return lc(s,"uboWgsl",jx,Hy)}class td extends ac{constructor(){super({createUboElements:Kx,generateUboSync:qx})}}td.extension={type:[C.WebGPUSystem],name:"ubo"};const _e=128;class ed{constructor(t){this._bindGroupHash=Object.create(null),this._buffers=[],this._bindGroups=[],this._bufferResources=[],this._renderer=t,this._renderer.renderableGC.addManagedHash(this,"_bindGroupHash"),this._batchBuffer=new $x({minUniformOffsetAlignment:_e});const e=256/_e;for(let r=0;r<e;r++){let n=Y.UNIFORM|Y.COPY_DST;r===0&&(n|=Y.COPY_SRC),this._buffers.push(new Bt({data:this._batchBuffer.data,usage:n}))}}renderEnd(){this._uploadBindGroups(),this._resetBindGroups()}_resetBindGroups(){for(const t in this._bindGroupHash)this._bindGroupHash[t]=null;this._batchBuffer.clear()}getUniformBindGroup(t,e){if(!e&&this._bindGroupHash[t.uid])return this._bindGroupHash[t.uid];this._renderer.ubo.ensureUniformGroup(t);const r=t.buffer.data,n=this._batchBuffer.addEmptyGroup(r.length);return this._renderer.ubo.syncUniformGroup(t,this._batchBuffer.data,n/4),this._bindGroupHash[t.uid]=this._getBindGroup(n/_e),this._bindGroupHash[t.uid]}getUboResource(t){this._renderer.ubo.updateUniformGroup(t);const e=t.buffer.data,r=this._batchBuffer.addGroup(e);return this._getBufferResource(r/_e)}getArrayBindGroup(t){const e=this._batchBuffer.addGroup(t);return this._getBindGroup(e/_e)}getArrayBufferResource(t){const r=this._batchBuffer.addGroup(t)/_e;return this._getBufferResource(r)}_getBufferResource(t){if(!this._bufferResources[t]){const e=this._buffers[t%2];this._bufferResources[t]=new Vn({buffer:e,offset:(t/2|0)*256,size:_e})}return this._bufferResources[t]}_getBindGroup(t){if(!this._bindGroups[t]){const e=new ne({0:this._getBufferResource(t)});this._bindGroups[t]=e}return this._bindGroups[t]}_uploadBindGroups(){const t=this._renderer.buffer,e=this._buffers[0];e.update(this._batchBuffer.byteIndex),t.updateBuffer(e);const r=this._renderer.gpu.device.createCommandEncoder();for(let n=1;n<this._buffers.length;n++){const o=this._buffers[n];r.copyBufferToBuffer(t.getGPUBuffer(e),_e,t.getGPUBuffer(o),0,this._batchBuffer.byteIndex)}this._renderer.gpu.device.queue.submit([r.finish()])}destroy(){for(let t=0;t<this._bindGroups.length;t++)this._bindGroups[t]?.destroy();this._bindGroups=null,this._bindGroupHash=null;for(let t=0;t<this._buffers.length;t++)this._buffers[t].destroy();this._buffers=null;for(let t=0;t<this._bufferResources.length;t++)this._bufferResources[t].destroy();this._bufferResources=null,this._batchBuffer.destroy(),this._bindGroupHash=null,this._renderer=null}}ed.extension={type:[C.WebGPUPipes],name:"uniformBatch"};const Zx={"point-list":0,"line-list":1,"line-strip":2,"triangle-list":3,"triangle-strip":4};function Qx(s,t,e,r,n){return s<<24|t<<16|e<<10|r<<5|n}function Jx(s,t,e,r){return e<<6|s<<3|r<<1|t}class id{constructor(t){this._moduleCache=Object.create(null),this._bufferLayoutsCache=Object.create(null),this._bindingNamesCache=Object.create(null),this._pipeCache=Object.create(null),this._pipeStateCaches=Object.create(null),this._colorMask=15,this._multisampleCount=1,this._renderer=t}contextChange(t){this._gpu=t,this.setStencilMode(ot.DISABLED),this._updatePipeHash()}setMultisampleCount(t){this._multisampleCount!==t&&(this._multisampleCount=t,this._updatePipeHash())}setRenderTarget(t){this._multisampleCount=t.msaaSamples,this._depthStencilAttachment=t.descriptor.depthStencilAttachment?1:0,this._updatePipeHash()}setColorMask(t){this._colorMask!==t&&(this._colorMask=t,this._updatePipeHash())}setStencilMode(t){this._stencilMode!==t&&(this._stencilMode=t,this._stencilState=ge[t],this._updatePipeHash())}setPipeline(t,e,r,n){const o=this.getPipeline(t,e,r);n.setPipeline(o)}getPipeline(t,e,r,n){t._layoutKey||(Jl(t,e.attributeData),this._generateBufferKey(t)),n||(n=t.topology);const o=Qx(t._layoutKey,e._layoutKey,r.data,r._blendModeId,Zx[n]);return this._pipeCache[o]?this._pipeCache[o]:(this._pipeCache[o]=this._createPipeline(t,e,r,n),this._pipeCache[o])}_createPipeline(t,e,r,n){const o=this._gpu.device,l=this._createVertexBufferLayouts(t,e),h=this._renderer.state.getColorTargets(r);h[0].writeMask=this._stencilMode===ot.RENDERING_MASK_ADD?0:this._colorMask;const u=this._renderer.shader.getProgramData(e).pipeline,f={vertex:{module:this._getModule(e.vertex.source),entryPoint:e.vertex.entryPoint,buffers:l},fragment:{module:this._getModule(e.fragment.source),entryPoint:e.fragment.entryPoint,targets:h},primitive:{topology:n,cullMode:r.cullMode},layout:u,multisample:{count:this._multisampleCount},label:"PIXI Pipeline"};return this._depthStencilAttachment&&(f.depthStencil={...this._stencilState,format:"depth24plus-stencil8",depthWriteEnabled:r.depthTest,depthCompare:r.depthTest?"less":"always"}),o.createRenderPipeline(f)}_getModule(t){return this._moduleCache[t]||this._createModule(t)}_createModule(t){const e=this._gpu.device;return this._moduleCache[t]=e.createShaderModule({code:t}),this._moduleCache[t]}_generateBufferKey(t){const e=[];let r=0;const n=Object.keys(t.attributes).sort();for(let l=0;l<n.length;l++){const h=t.attributes[n[l]];e[r++]=h.offset,e[r++]=h.format,e[r++]=h.stride,e[r++]=h.instance}const o=e.join("|");return t._layoutKey=gi(o,"geometry"),t._layoutKey}_generateAttributeLocationsKey(t){const e=[];let r=0;const n=Object.keys(t.attributeData).sort();for(let l=0;l<n.length;l++){const h=t.attributeData[n[l]];e[r++]=h.location}const o=e.join("|");return t._attributeLocationsKey=gi(o,"programAttributes"),t._attributeLocationsKey}getBufferNamesToBind(t,e){const r=t._layoutKey<<16|e._attributeLocationsKey;if(this._bindingNamesCache[r])return this._bindingNamesCache[r];const n=this._createVertexBufferLayouts(t,e),o=Object.create(null),l=e.attributeData;for(let h=0;h<n.length;h++){const f=Object.values(n[h].attributes)[0].shaderLocation;for(const m in l)if(l[m].location===f){o[h]=m;break}}return this._bindingNamesCache[r]=o,o}_createVertexBufferLayouts(t,e){e._attributeLocationsKey||this._generateAttributeLocationsKey(e);const r=t._layoutKey<<16|e._attributeLocationsKey;if(this._bufferLayoutsCache[r])return this._bufferLayoutsCache[r];const n=[];return t.buffers.forEach(o=>{const l={arrayStride:0,stepMode:"vertex",attributes:[]},h=l.attributes;for(const u in e.attributeData){const f=t.attributes[u];(f.divisor??1)!==1&&F(`Attribute ${u} has an invalid divisor value of '${f.divisor}'. WebGPU only supports a divisor value of 1`),f.buffer===o&&(l.arrayStride=f.stride,l.stepMode=f.instance?"instance":"vertex",h.push({shaderLocation:e.attributeData[u].location,offset:f.offset,format:f.format}))}h.length&&n.push(l)}),this._bufferLayoutsCache[r]=n,n}_updatePipeHash(){const t=Jx(this._stencilMode,this._multisampleCount,this._colorMask,this._depthStencilAttachment);this._pipeStateCaches[t]||(this._pipeStateCaches[t]=Object.create(null)),this._pipeCache=this._pipeStateCaches[t]}destroy(){this._renderer=null,this._bufferLayoutsCache=null}}id.extension={type:[C.WebGPUSystem],name:"pipeline"};class tb{constructor(){this.contexts=[],this.msaaTextures=[],this.msaaSamples=1}}class eb{init(t,e){this._renderer=t,this._renderTargetSystem=e}copyToTexture(t,e,r,n,o){const l=this._renderer,h=this._getGpuColorTexture(t),u=l.texture.getGpuSource(e.source);return l.encoder.commandEncoder.copyTextureToTexture({texture:h,origin:r},{texture:u,origin:o},n),e}startRenderPass(t,e=!0,r,n){const l=this._renderTargetSystem.getGpuRenderTarget(t),h=this.getDescriptor(t,e,r);l.descriptor=h,this._renderer.pipeline.setRenderTarget(l),this._renderer.encoder.beginRenderPass(l),this._renderer.encoder.setViewport(n)}finishRenderPass(){this._renderer.encoder.endRenderPass()}_getGpuColorTexture(t){const e=this._renderTargetSystem.getGpuRenderTarget(t);return e.contexts[0]?e.contexts[0].getCurrentTexture():this._renderer.texture.getGpuSource(t.colorTextures[0].source)}getDescriptor(t,e,r){typeof e=="boolean"&&(e=e?Pt.ALL:Pt.NONE);const n=this._renderTargetSystem,o=n.getGpuRenderTarget(t),l=t.colorTextures.map((f,m)=>{const g=o.contexts[m];let y,x;g?y=g.getCurrentTexture().createView():y=this._renderer.texture.getGpuSource(f).createView({mipLevelCount:1}),o.msaaTextures[m]&&(x=y,y=this._renderer.texture.getTextureView(o.msaaTextures[m]));const a=e&Pt.COLOR?"clear":"load";return r??(r=n.defaultClearColor),{view:y,resolveTarget:x,clearValue:r,storeOp:"store",loadOp:a}});let h;if((t.stencil||t.depth)&&!t.depthStencilTexture&&(t.ensureDepthStencilTexture(),t.depthStencilTexture.source.sampleCount=o.msaa?4:1),t.depthStencilTexture){const f=e&Pt.STENCIL?"clear":"load",m=e&Pt.DEPTH?"clear":"load";h={view:this._renderer.texture.getGpuSource(t.depthStencilTexture.source).createView(),stencilStoreOp:"store",stencilLoadOp:f,depthClearValue:1,depthLoadOp:m,depthStoreOp:"store"}}return{colorAttachments:l,depthStencilAttachment:h}}clear(t,e=!0,r,n){if(!e)return;const{gpu:o,encoder:l}=this._renderer,h=o.device;if(l.commandEncoder===null){const f=h.createCommandEncoder(),m=this.getDescriptor(t,e,r),g=f.beginRenderPass(m);g.setViewport(n.x,n.y,n.width,n.height,0,1),g.end();const y=f.finish();h.queue.submit([y])}else this.startRenderPass(t,e,r,n)}initGpuRenderTarget(t){t.isRoot=!0;const e=new tb;return t.colorTextures.forEach((r,n)=>{if(r instanceof re){const o=r.resource.getContext("webgpu"),l=r.transparent?"premultiplied":"opaque";try{o.configure({device:this._renderer.gpu.device,usage:GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_DST|GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.COPY_SRC,format:"bgra8unorm",alphaMode:l})}catch(h){console.error(h)}e.contexts[n]=o}if(e.msaa=r.source.antialias,r.source.antialias){const o=new ht({width:0,height:0,sampleCount:4});e.msaaTextures[n]=o}}),e.msaa&&(e.msaaSamples=4,t.depthStencilTexture&&(t.depthStencilTexture.source.sampleCount=4)),e}destroyGpuRenderTarget(t){t.contexts.forEach(e=>{e.unconfigure()}),t.msaaTextures.forEach(e=>{e.destroy()}),t.msaaTextures.length=0,t.contexts.length=0}ensureDepthStencilTexture(t){const e=this._renderTargetSystem.getGpuRenderTarget(t);t.depthStencilTexture&&e.msaa&&(t.depthStencilTexture.source.sampleCount=4)}resizeGpuRenderTarget(t){const e=this._renderTargetSystem.getGpuRenderTarget(t);e.width=t.width,e.height=t.height,e.msaa&&t.colorTextures.forEach((r,n)=>{e.msaaTextures[n]?.resize(r.source.width,r.source.height,r.source._resolution)})}}class rd extends pc{constructor(t){super(t),this.adaptor=new eb,this.adaptor.init(t,this)}}rd.extension={type:[C.WebGPUSystem],name:"renderTarget"};class sd{constructor(){this._gpuProgramData=Object.create(null)}contextChange(t){this._gpu=t}getProgramData(t){return this._gpuProgramData[t._layoutKey]||this._createGPUProgramData(t)}_createGPUProgramData(t){const e=this._gpu.device,r=t.gpuLayout.map(o=>e.createBindGroupLayout({entries:o})),n={bindGroupLayouts:r};return this._gpuProgramData[t._layoutKey]={bindGroups:r,pipeline:e.createPipelineLayout(n)},this._gpuProgramData[t._layoutKey]}destroy(){this._gpu=null,this._gpuProgramData=null}}sd.extension={type:[C.WebGPUSystem],name:"shader"};const vt={};vt.normal={alpha:{srcFactor:"one",dstFactor:"one-minus-src-alpha",operation:"add"},color:{srcFactor:"one",dstFactor:"one-minus-src-alpha",operation:"add"}},vt.add={alpha:{srcFactor:"src-alpha",dstFactor:"one-minus-src-alpha",operation:"add"},color:{srcFactor:"one",dstFactor:"one",operation:"add"}},vt.multiply={alpha:{srcFactor:"one",dstFactor:"one-minus-src-alpha",operation:"add"},color:{srcFactor:"dst",dstFactor:"one-minus-src-alpha",operation:"add"}},vt.screen={alpha:{srcFactor:"one",dstFactor:"one-minus-src-alpha",operation:"add"},color:{srcFactor:"one",dstFactor:"one-minus-src",operation:"add"}},vt.overlay={alpha:{srcFactor:"one",dstFactor:"one-minus-src-alpha",operation:"add"},color:{srcFactor:"one",dstFactor:"one-minus-src",operation:"add"}},vt.none={alpha:{srcFactor:"one",dstFactor:"one-minus-src-alpha",operation:"add"},color:{srcFactor:"zero",dstFactor:"zero",operation:"add"}},vt["normal-npm"]={alpha:{srcFactor:"one",dstFactor:"one-minus-src-alpha",operation:"add"},color:{srcFactor:"src-alpha",dstFactor:"one-minus-src-alpha",operation:"add"}},vt["add-npm"]={alpha:{srcFactor:"one",dstFactor:"one",operation:"add"},color:{srcFactor:"src-alpha",dstFactor:"one",operation:"add"}},vt["screen-npm"]={alpha:{srcFactor:"one",dstFactor:"one-minus-src-alpha",operation:"add"},color:{srcFactor:"src-alpha",dstFactor:"one-minus-src",operation:"add"}},vt.erase={alpha:{srcFactor:"zero",dstFactor:"one-minus-src-alpha",operation:"add"},color:{srcFactor:"zero",dstFactor:"one-minus-src",operation:"add"}},vt.min={alpha:{srcFactor:"one",dstFactor:"one",operation:"min"},color:{srcFactor:"one",dstFactor:"one",operation:"min"}},vt.max={alpha:{srcFactor:"one",dstFactor:"one",operation:"max"},color:{srcFactor:"one",dstFactor:"one",operation:"max"}};class nd{constructor(){this.defaultState=new Ht,this.defaultState.blend=!0}contextChange(t){this.gpu=t}getColorTargets(t){return[{format:"bgra8unorm",writeMask:0,blend:vt[t.blendMode]||vt.normal}]}destroy(){this.gpu=null}}nd.extension={type:[C.WebGPUSystem],name:"state"};const ib={type:"image",upload(s,t,e){const r=s.resource,n=(s.pixelWidth|0)*(s.pixelHeight|0),o=r.byteLength/n;e.device.queue.writeTexture({texture:t},r,{offset:0,rowsPerImage:s.pixelHeight,bytesPerRow:s.pixelWidth*o},{width:s.pixelWidth,height:s.pixelHeight,depthOrArrayLayers:1})}},od={"bc1-rgba-unorm":{blockBytes:8,blockWidth:4,blockHeight:4},"bc2-rgba-unorm":{blockBytes:16,blockWidth:4,blockHeight:4},"bc3-rgba-unorm":{blockBytes:16,blockWidth:4,blockHeight:4},"bc7-rgba-unorm":{blockBytes:16,blockWidth:4,blockHeight:4},"etc1-rgb-unorm":{blockBytes:8,blockWidth:4,blockHeight:4},"etc2-rgba8unorm":{blockBytes:16,blockWidth:4,blockHeight:4},"astc-4x4-unorm":{blockBytes:16,blockWidth:4,blockHeight:4}},rb={blockBytes:4,blockWidth:1,blockHeight:1},sb={type:"compressed",upload(s,t,e){let r=s.pixelWidth,n=s.pixelHeight;const o=od[s.format]||rb;for(let l=0;l<s.resource.length;l++){const h=s.resource[l],u=Math.ceil(r/o.blockWidth)*o.blockBytes;e.device.queue.writeTexture({texture:t,mipLevel:l},h,{offset:0,bytesPerRow:u},{width:Math.ceil(r/o.blockWidth)*o.blockWidth,height:Math.ceil(n/o.blockHeight)*o.blockHeight,depthOrArrayLayers:1}),r=Math.max(r>>1,1),n=Math.max(n>>1,1)}}},ad={type:"image",upload(s,t,e){const r=s.resource;if(!r)return;if(globalThis.HTMLImageElement&&r instanceof HTMLImageElement){const h=W.get().createCanvas(r.width,r.height);h.getContext("2d").drawImage(r,0,0,r.width,r.height),s.resource=h,F("ImageSource: Image element passed, converting to canvas and replacing resource.")}const n=Math.min(t.width,s.resourceWidth||s.pixelWidth),o=Math.min(t.height,s.resourceHeight||s.pixelHeight),l=s.alphaMode==="premultiply-alpha-on-upload";e.device.queue.copyExternalImageToTexture({source:r},{texture:t,premultipliedAlpha:l},{width:n,height:o})}},nb={type:"video",upload(s,t,e){ad.upload(s,t,e)}};class ob{constructor(t){this.device=t,this.sampler=t.createSampler({minFilter:"linear"}),this.pipelines={}}_getMipmapPipeline(t){let e=this.pipelines[t];return e||(this.mipmapShaderModule||(this.mipmapShaderModule=this.device.createShaderModule({code:`
|
|
980
980
|
var<private> pos : array<vec2<f32>, 3> = array<vec2<f32>, 3>(
|
|
981
981
|
vec2<f32>(-1.0, -1.0), vec2<f32>(-1.0, 3.0), vec2<f32>(3.0, -1.0));
|
|
982
982
|
|
|
@@ -1000,7 +1000,7 @@ fn mainFragment(
|
|
|
1000
1000
|
fn fragmentMain(@location(0) texCoord : vec2<f32>) -> @location(0) vec4<f32> {
|
|
1001
1001
|
return textureSample(img, imgSampler, texCoord);
|
|
1002
1002
|
}
|
|
1003
|
-
`})),e=this.device.createRenderPipeline({layout:"auto",vertex:{module:this.mipmapShaderModule,entryPoint:"vertexMain"},fragment:{module:this.mipmapShaderModule,entryPoint:"fragmentMain",targets:[{format:t}]}}),this.pipelines[t]=e),e}generateMipmap(t){const e=this._getMipmapPipeline(t.format);if(t.dimension==="3d"||t.dimension==="1d")throw new Error("Generating mipmaps for non-2d textures is currently unsupported!");let r=t;const n=t.depthOrArrayLayers||1,a=t.usage&GPUTextureUsage.RENDER_ATTACHMENT;if(!a){const d={size:{width:Math.ceil(t.width/2),height:Math.ceil(t.height/2),depthOrArrayLayers:n},format:t.format,usage:GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_SRC|GPUTextureUsage.RENDER_ATTACHMENT,mipLevelCount:t.mipLevelCount-1};r=this.device.createTexture(d)}const l=this.device.createCommandEncoder({}),h=e.getBindGroupLayout(0);for(let d=0;d<n;++d){let f=t.createView({baseMipLevel:0,mipLevelCount:1,dimension:"2d",baseArrayLayer:d,arrayLayerCount:1}),m=a?1:0;for(let g=1;g<t.mipLevelCount;++g){const y=r.createView({baseMipLevel:m++,mipLevelCount:1,dimension:"2d",baseArrayLayer:d,arrayLayerCount:1}),x=l.beginRenderPass({colorAttachments:[{view:y,storeOp:"store",loadOp:"clear",clearValue:{r:0,g:0,b:0,a:0}}]}),o=this.device.createBindGroup({layout:h,entries:[{binding:0,resource:this.sampler},{binding:1,resource:f}]});x.setPipeline(e),x.setBindGroup(0,o),x.draw(3,1,0,0),x.end(),f=y}}if(!a){const d={width:Math.ceil(t.width/2),height:Math.ceil(t.height/2),depthOrArrayLayers:n};for(let f=1;f<t.mipLevelCount;++f)l.copyTextureToTexture({texture:r,mipLevel:f-1},{texture:t,mipLevel:f},d),d.width=Math.ceil(d.width/2),d.height=Math.ceil(d.height/2)}return this.device.queue.submit([l.finish()]),a||r.destroy(),t}}class su{constructor(t){this.managedTextures=[],this._gpuSources=Object.create(null),this._gpuSamplers=Object.create(null),this._bindGroupHash=Object.create(null),this._textureViewHash=Object.create(null),this._uploads={image:ru,buffer:$x,video:qx,compressed:jx},this._renderer=t,t.renderableGC.addManagedHash(this,"_gpuSources"),t.renderableGC.addManagedHash(this,"_gpuSamplers"),t.renderableGC.addManagedHash(this,"_bindGroupHash"),t.renderableGC.addManagedHash(this,"_textureViewHash")}contextChange(t){this._gpu=t}initSource(t){return this._gpuSources[t.uid]?this._gpuSources[t.uid]:this._initSource(t)}_initSource(t){if(t.autoGenerateMipmaps){const d=Math.max(t.pixelWidth,t.pixelHeight);t.mipLevelCount=Math.floor(Math.log2(d))+1}let e=GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_DST;t.uploadMethodId!=="compressed"&&(e|=GPUTextureUsage.RENDER_ATTACHMENT,e|=GPUTextureUsage.COPY_SRC);const r=iu[t.format]||{blockWidth:1,blockHeight:1},n=Math.ceil(t.pixelWidth/r.blockWidth)*r.blockWidth,a=Math.ceil(t.pixelHeight/r.blockHeight)*r.blockHeight,l={label:t.label,size:{width:n,height:a},format:t.format,sampleCount:t.sampleCount,mipLevelCount:t.mipLevelCount,dimension:t.dimension,usage:e},h=this._gpuSources[t.uid]=this._gpu.device.createTexture(l);return this.managedTextures.includes(t)||(t.on("update",this.onSourceUpdate,this),t.on("resize",this.onSourceResize,this),t.on("destroy",this.onSourceDestroy,this),t.on("unload",this.onSourceUnload,this),t.on("updateMipmaps",this.onUpdateMipmaps,this),this.managedTextures.push(t)),this.onSourceUpdate(t),h}onSourceUpdate(t){const e=this.getGpuSource(t);e&&(this._uploads[t.uploadMethodId]&&this._uploads[t.uploadMethodId].upload(t,e,this._gpu),t.autoGenerateMipmaps&&t.mipLevelCount>1&&this.onUpdateMipmaps(t))}onSourceUnload(t){const e=this._gpuSources[t.uid];e&&(this._gpuSources[t.uid]=null,e.destroy())}onUpdateMipmaps(t){this._mipmapGenerator||(this._mipmapGenerator=new Zx(this._gpu.device));const e=this.getGpuSource(t);this._mipmapGenerator.generateMipmap(e)}onSourceDestroy(t){t.off("update",this.onSourceUpdate,this),t.off("unload",this.onSourceUnload,this),t.off("destroy",this.onSourceDestroy,this),t.off("resize",this.onSourceResize,this),t.off("updateMipmaps",this.onUpdateMipmaps,this),this.managedTextures.splice(this.managedTextures.indexOf(t),1),this.onSourceUnload(t)}onSourceResize(t){const e=this._gpuSources[t.uid];e?(e.width!==t.pixelWidth||e.height!==t.pixelHeight)&&(this._textureViewHash[t.uid]=null,this._bindGroupHash[t.uid]=null,this.onSourceUnload(t),this.initSource(t)):this.initSource(t)}_initSampler(t){return this._gpuSamplers[t._resourceId]=this._gpu.device.createSampler(t),this._gpuSamplers[t._resourceId]}getGpuSampler(t){return this._gpuSamplers[t._resourceId]||this._initSampler(t)}getGpuSource(t){return this._gpuSources[t.uid]||this.initSource(t)}getTextureBindGroup(t){return this._bindGroupHash[t.uid]??this._createTextureBindGroup(t)}_createTextureBindGroup(t){const e=t.source;return this._bindGroupHash[t.uid]=new re({0:e,1:e.style,2:new gt({uTextureMatrix:{type:"mat3x3<f32>",value:t.textureMatrix.mapCoord}})}),this._bindGroupHash[t.uid]}getTextureView(t){const e=t.source;return this._textureViewHash[e.uid]??this._createTextureView(e)}_createTextureView(t){return this._textureViewHash[t.uid]=this.getGpuSource(t).createView(),this._textureViewHash[t.uid]}generateCanvas(t){const e=this._renderer,r=e.gpu.device.createCommandEncoder(),n=W.get().createCanvas();n.width=t.source.pixelWidth,n.height=t.source.pixelHeight;const a=n.getContext("webgpu");return a.configure({device:e.gpu.device,usage:GPUTextureUsage.COPY_DST|GPUTextureUsage.COPY_SRC,format:W.get().getNavigator().gpu.getPreferredCanvasFormat(),alphaMode:"premultiplied"}),r.copyTextureToTexture({texture:e.texture.getGpuSource(t.source),origin:{x:0,y:0}},{texture:a.getCurrentTexture()},{width:n.width,height:n.height}),e.gpu.device.queue.submit([r.finish()]),n}getPixels(t){const e=this.generateCanvas(t),r=ne.getOptimalCanvasAndContext(e.width,e.height),n=r.context;n.drawImage(e,0,0);const{width:a,height:l}=e,h=n.getImageData(0,0,a,l),d=new Uint8ClampedArray(h.data.buffer);return ne.returnCanvasAndContext(r),{pixels:d,width:a,height:l}}destroy(){this.managedTextures.slice().forEach(t=>this.onSourceDestroy(t)),this.managedTextures=null;for(const t of Object.keys(this._bindGroupHash)){const e=Number(t);this._bindGroupHash[e]?.destroy(),this._bindGroupHash[e]=null}this._renderer=null,this._gpu=null,this._mipmapGenerator=null,this._gpuSources=null,this._bindGroupHash=null,this._textureViewHash=null,this._gpuSamplers=null}}su.extension={type:[C.WebGPUSystem],name:"texture"};class nu{constructor(){this._maxTextures=0}contextChange(t){const e=new gt({uTransformMatrix:{value:new k,type:"mat3x3<f32>"},uColor:{value:new Float32Array([1,1,1,1]),type:"vec4<f32>"},uRound:{value:0,type:"f32"}});this._maxTextures=t.limits.maxBatchableTextures;const r=Bi({name:"graphics",bits:[hn,un(this._maxTextures),xy,Mi]});this.shader=new It({gpuProgram:r,resources:{localUniforms:e}})}execute(t,e){const r=e.context,n=r.customShader||this.shader,a=t.renderer,l=a.graphicsContext,{batcher:h,instructions:d}=l.getContextRenderData(r),f=a.encoder;f.setGeometry(h.geometry,n.gpuProgram);const m=a.globalUniforms.bindGroup;f.setBindGroup(0,m,n.gpuProgram);const g=a.renderPipes.uniformBatch.getUniformBindGroup(n.resources.localUniforms,!0);f.setBindGroup(2,g,n.gpuProgram);const y=d.instructions;let x=null;for(let o=0;o<d.instructionSize;o++){const c=y[o];if(c.topology!==x&&(x=c.topology,f.setPipelineFromGeometryProgramAndState(h.geometry,n.gpuProgram,t.state,c.topology)),n.groups[1]=c.bindGroup,!c.gpuBindGroup){const u=c.textures;c.bindGroup=nn(u.textures,u.count,this._maxTextures),c.gpuBindGroup=a.bindGroup.getBindGroup(c.bindGroup,n.gpuProgram,1)}f.setBindGroup(1,c.bindGroup,n.gpuProgram),f.renderPassEncoder.drawIndexed(c.size,1,c.start)}}destroy(){this.shader.destroy(!0),this.shader=null}}nu.extension={type:[C.WebGPUPipesAdaptor],name:"graphics"};class au{init(){const t=Bi({name:"mesh",bits:[Ni,by,Mi]});this._shader=new It({gpuProgram:t,resources:{uTexture:M.EMPTY._source,uSampler:M.EMPTY._source.style,textureUniforms:{uTextureMatrix:{type:"mat3x3<f32>",value:new k}}}})}execute(t,e){const r=t.renderer;let n=e._shader;if(!n)n=this._shader,n.groups[2]=r.texture.getTextureBindGroup(e.texture);else if(!n.gpuProgram){F("Mesh shader has no gpuProgram",e.shader);return}const a=n.gpuProgram;if(a.autoAssignGlobalUniforms&&(n.groups[0]=r.globalUniforms.bindGroup),a.autoAssignLocalUniforms){const l=t.localUniforms;n.groups[1]=r.renderPipes.uniformBatch.getUniformBindGroup(l,!0)}r.encoder.draw({geometry:e._geometry,shader:n,state:e.state})}destroy(){this._shader.destroy(!0),this._shader=null}}au.extension={type:[C.WebGPUPipesAdaptor],name:"mesh"};const Qx=[...Lc,qc,$c,Jn,Kc,Yc,su,Jc,tu,eu,Qc,Xc,jc,Vc],Jx=[...zc,Zc],tb=[Wl,au,nu],ou=[],hu=[],lu=[];D.handleByNamedList(C.WebGPUSystem,ou),D.handleByNamedList(C.WebGPUPipes,hu),D.handleByNamedList(C.WebGPUPipesAdaptor,lu),D.add(...Qx,...Jx,...tb);class eb extends wr{constructor(){const t={name:"webgpu",type:Nt.WEBGPU,systems:ou,renderPipes:hu,renderPipeAdaptors:lu};super(t)}}const ib=Object.freeze(Object.defineProperty({__proto__:null,WebGPURenderer:eb},Symbol.toStringTag,{value:"Module"}));class rb{constructor(){this.batches=[],this.batched=!1}destroy(){this.batches.forEach(t=>{at.return(t)}),this.batches.length=0}}class cu{constructor(t,e){this.state=Ht.for2d(),this.renderer=t,this._adaptor=e,this.renderer.runners.contextChange.add(this)}contextChange(){this._adaptor.contextChange(this.renderer)}validateRenderable(t){const e=t.context,r=!!t._gpuData,n=this.renderer.graphicsContext.updateGpuContext(e);return!!(n.isBatchable||r!==n.isBatchable)}addRenderable(t,e){const r=this.renderer.graphicsContext.updateGpuContext(t.context);t.didViewUpdate&&this._rebuild(t),r.isBatchable?this._addToBatcher(t,e):(this.renderer.renderPipes.batch.break(e),e.add(t))}updateRenderable(t){const r=this._getGpuDataForRenderable(t).batches;for(let n=0;n<r.length;n++){const a=r[n];a._batcher.updateElement(a)}}execute(t){if(!t.isRenderable)return;const e=this.renderer,r=t.context;if(!e.graphicsContext.getGpuContext(r).batches.length)return;const a=r.customShader||this._adaptor.shader;this.state.blendMode=t.groupBlendMode;const l=a.resources.localUniforms.uniforms;l.uTransformMatrix=t.groupTransform,l.uRound=e._roundPixels|t._roundPixels,Vi(t.groupColorAlpha,l.uColor,0),this._adaptor.execute(this,t)}_rebuild(t){const e=this._getGpuDataForRenderable(t),r=this.renderer.graphicsContext.updateGpuContext(t.context);e.destroy(),r.isBatchable&&this._updateBatchesForRenderable(t,e)}_addToBatcher(t,e){const r=this.renderer.renderPipes.batch,n=this._getGpuDataForRenderable(t).batches;for(let a=0;a<n.length;a++){const l=n[a];r.addToBatch(l,e)}}_getGpuDataForRenderable(t){return t._gpuData[this.renderer.uid]||this._initGpuDataForRenderable(t)}_initGpuDataForRenderable(t){const e=new rb;return t._gpuData[this.renderer.uid]=e,e}_updateBatchesForRenderable(t,e){const r=t.context,n=this.renderer.graphicsContext.getGpuContext(r),a=this.renderer._roundPixels|t._roundPixels;e.batches=n.batches.map(l=>{const h=at.get(gn);return l.copyTo(h),h.renderable=t,h.roundPixels=a,h})}destroy(){this.renderer=null,this._adaptor.destroy(),this._adaptor=null,this.state=null}}cu.extension={type:[C.WebGLPipes,C.WebGPUPipes,C.CanvasPipes],name:"graphics"};const uu=class ud extends In{constructor(...t){super({});let e=t[0]??{};typeof e=="number"&&(z($,"PlaneGeometry constructor changed please use { width, height, verticesX, verticesY } instead"),e={width:e,height:t[1],verticesX:t[2],verticesY:t[3]}),this.build(e)}build(t){t={...ud.defaultOptions,...t},this.verticesX=this.verticesX??t.verticesX,this.verticesY=this.verticesY??t.verticesY,this.width=this.width??t.width,this.height=this.height??t.height;const e=this.verticesX*this.verticesY,r=[],n=[],a=[],l=this.verticesX-1,h=this.verticesY-1,d=this.width/l,f=this.height/h;for(let g=0;g<e;g++){const y=g%this.verticesX,x=g/this.verticesX|0;r.push(y*d,x*f),n.push(y/l,x/h)}const m=l*h;for(let g=0;g<m;g++){const y=g%l,x=g/l|0,o=x*this.verticesX+y,c=x*this.verticesX+y+1,u=(x+1)*this.verticesX+y,p=(x+1)*this.verticesX+y+1;a.push(o,c,u,c,p,u)}this.buffers[0].data=new Float32Array(r),this.buffers[1].data=new Float32Array(n),this.indexBuffer.data=new Uint32Array(a),this.buffers[0].update(),this.buffers[1].update(),this.indexBuffer.update()}};uu.defaultOptions={width:100,height:100,verticesX:10,verticesY:10};let sb=uu;class ta{constructor(){this.batcherName="default",this.packAsQuad=!1,this.indexOffset=0,this.attributeOffset=0,this.roundPixels=0,this._batcher=null,this._batch=null,this._textureMatrixUpdateId=-1,this._uvUpdateId=-1}get blendMode(){return this.renderable.groupBlendMode}get topology(){return this._topology||this.geometry.topology}set topology(t){this._topology=t}reset(){this.renderable=null,this.texture=null,this._batcher=null,this._batch=null,this.geometry=null,this._uvUpdateId=-1,this._textureMatrixUpdateId=-1}setTexture(t){this.texture!==t&&(this.texture=t,this._textureMatrixUpdateId=-1)}get uvs(){const e=this.geometry.getBuffer("aUV"),r=e.data;let n=r;const a=this.texture.textureMatrix;return a.isSimple||(n=this._transformedUvs,(this._textureMatrixUpdateId!==a._updateID||this._uvUpdateId!==e._updateID)&&((!n||n.length<r.length)&&(n=this._transformedUvs=new Float32Array(r.length)),this._textureMatrixUpdateId=a._updateID,this._uvUpdateId=e._updateID,a.multiplyUvs(r,n))),n}get positions(){return this.geometry.positions}get indices(){return this.geometry.indices}get color(){return this.renderable.groupColorAlpha}get groupTransform(){return this.renderable.groupTransform}get attributeSize(){return this.geometry.positions.length/2}get indexSize(){return this.geometry.indices.length}}class du{destroy(){}}class fu{constructor(t,e){this.localUniforms=new gt({uTransformMatrix:{value:new k,type:"mat3x3<f32>"},uColor:{value:new Float32Array([1,1,1,1]),type:"vec4<f32>"},uRound:{value:0,type:"f32"}}),this.localUniformsBindGroup=new re({0:this.localUniforms}),this.renderer=t,this._adaptor=e,this._adaptor.init()}validateRenderable(t){const e=this._getMeshData(t),r=e.batched,n=t.batched;if(e.batched=n,r!==n)return!0;if(n){const a=t._geometry;if(a.indices.length!==e.indexSize||a.positions.length!==e.vertexSize)return e.indexSize=a.indices.length,e.vertexSize=a.positions.length,!0;const l=this._getBatchableMesh(t);return l.texture.uid!==t._texture.uid&&(l._textureMatrixUpdateId=-1),!l._batcher.checkAndUpdateTexture(l,t._texture)}return!1}addRenderable(t,e){const r=this.renderer.renderPipes.batch,n=this._getMeshData(t);if(t.didViewUpdate&&(n.indexSize=t._geometry.indices?.length,n.vertexSize=t._geometry.positions?.length),n.batched){const a=this._getBatchableMesh(t);a.setTexture(t._texture),a.geometry=t._geometry,r.addToBatch(a,e)}else r.break(e),e.add(t)}updateRenderable(t){if(t.batched){const e=this._getBatchableMesh(t);e.setTexture(t._texture),e.geometry=t._geometry,e._batcher.updateElement(e)}}execute(t){if(!t.isRenderable)return;t.state.blendMode=Ci(t.groupBlendMode,t.texture._source);const e=this.localUniforms;e.uniforms.uTransformMatrix=t.groupTransform,e.uniforms.uRound=this.renderer._roundPixels|t._roundPixels,e.update(),Vi(t.groupColorAlpha,e.uniforms.uColor,0),this._adaptor.execute(this,t)}_getMeshData(t){var e,r;return(e=t._gpuData)[r=this.renderer.uid]||(e[r]=new du),t._gpuData[this.renderer.uid].meshData||this._initMeshData(t)}_initMeshData(t){return t._gpuData[this.renderer.uid].meshData={batched:t.batched,indexSize:0,vertexSize:0},t._gpuData[this.renderer.uid].meshData}_getBatchableMesh(t){var e,r;return(e=t._gpuData)[r=this.renderer.uid]||(e[r]=new du),t._gpuData[this.renderer.uid].batchableMesh||this._initBatchableMesh(t)}_initBatchableMesh(t){const e=new ta;return e.renderable=t,e.setTexture(t._texture),e.transform=t.groupTransform,e.roundPixels=this.renderer._roundPixels|t._roundPixels,t._gpuData[this.renderer.uid].batchableMesh=e,e}destroy(){this.localUniforms=null,this.localUniformsBindGroup=null,this._adaptor.destroy(),this._adaptor=null,this.renderer=null}}fu.extension={type:[C.WebGLPipes,C.WebGPUPipes,C.CanvasPipes],name:"mesh"};class nb{execute(t,e){const r=t.state,n=t.renderer,a=e.shader||t.defaultShader;a.resources.uTexture=e.texture._source,a.resources.uniforms=t.localUniforms;const l=n.gl,h=t.getBuffers(e);n.shader.bind(a),n.state.set(r),n.geometry.bind(h.geometry,a.glProgram);const f=h.geometry.indexBuffer.data.BYTES_PER_ELEMENT===2?l.UNSIGNED_SHORT:l.UNSIGNED_INT;l.drawElements(l.TRIANGLES,e.particleChildren.length*6,f,0)}}class ab{execute(t,e){const r=t.renderer,n=e.shader||t.defaultShader;n.groups[0]=r.renderPipes.uniformBatch.getUniformBindGroup(t.localUniforms,!0),n.groups[1]=r.texture.getTextureBindGroup(e.texture);const a=t.state,l=t.getBuffers(e);r.encoder.draw({geometry:l.geometry,shader:e.shader||t.defaultShader,state:a,size:e.particleChildren.length*6})}}function pu(s,t=null){const e=s*6;if(e>65535?t||(t=new Uint32Array(e)):t||(t=new Uint16Array(e)),t.length!==e)throw new Error(`Out buffer length is incorrect, got ${t.length} and expected ${e}`);for(let r=0,n=0;r<e;r+=6,n+=4)t[r+0]=n+0,t[r+1]=n+1,t[r+2]=n+2,t[r+3]=n+0,t[r+4]=n+2,t[r+5]=n+3;return t}function ob(s){return{dynamicUpdate:mu(s,!0),staticUpdate:mu(s,!1)}}function mu(s,t){const e=[];e.push(`
|
|
1003
|
+
`})),e=this.device.createRenderPipeline({layout:"auto",vertex:{module:this.mipmapShaderModule,entryPoint:"vertexMain"},fragment:{module:this.mipmapShaderModule,entryPoint:"fragmentMain",targets:[{format:t}]}}),this.pipelines[t]=e),e}generateMipmap(t){const e=this._getMipmapPipeline(t.format);if(t.dimension==="3d"||t.dimension==="1d")throw new Error("Generating mipmaps for non-2d textures is currently unsupported!");let r=t;const n=t.depthOrArrayLayers||1,o=t.usage&GPUTextureUsage.RENDER_ATTACHMENT;if(!o){const u={size:{width:Math.ceil(t.width/2),height:Math.ceil(t.height/2),depthOrArrayLayers:n},format:t.format,usage:GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_SRC|GPUTextureUsage.RENDER_ATTACHMENT,mipLevelCount:t.mipLevelCount-1};r=this.device.createTexture(u)}const l=this.device.createCommandEncoder({}),h=e.getBindGroupLayout(0);for(let u=0;u<n;++u){let f=t.createView({baseMipLevel:0,mipLevelCount:1,dimension:"2d",baseArrayLayer:u,arrayLayerCount:1}),m=o?1:0;for(let g=1;g<t.mipLevelCount;++g){const y=r.createView({baseMipLevel:m++,mipLevelCount:1,dimension:"2d",baseArrayLayer:u,arrayLayerCount:1}),x=l.beginRenderPass({colorAttachments:[{view:y,storeOp:"store",loadOp:"clear",clearValue:{r:0,g:0,b:0,a:0}}]}),a=this.device.createBindGroup({layout:h,entries:[{binding:0,resource:this.sampler},{binding:1,resource:f}]});x.setPipeline(e),x.setBindGroup(0,a),x.draw(3,1,0,0),x.end(),f=y}}if(!o){const u={width:Math.ceil(t.width/2),height:Math.ceil(t.height/2),depthOrArrayLayers:n};for(let f=1;f<t.mipLevelCount;++f)l.copyTextureToTexture({texture:r,mipLevel:f-1},{texture:t,mipLevel:f},u),u.width=Math.ceil(u.width/2),u.height=Math.ceil(u.height/2)}return this.device.queue.submit([l.finish()]),o||r.destroy(),t}}class hd{constructor(t){this.managedTextures=[],this._gpuSources=Object.create(null),this._gpuSamplers=Object.create(null),this._bindGroupHash=Object.create(null),this._textureViewHash=Object.create(null),this._uploads={image:ad,buffer:ib,video:nb,compressed:sb},this._renderer=t,t.renderableGC.addManagedHash(this,"_gpuSources"),t.renderableGC.addManagedHash(this,"_gpuSamplers"),t.renderableGC.addManagedHash(this,"_bindGroupHash"),t.renderableGC.addManagedHash(this,"_textureViewHash")}contextChange(t){this._gpu=t}initSource(t){return this._gpuSources[t.uid]?this._gpuSources[t.uid]:this._initSource(t)}_initSource(t){if(t.autoGenerateMipmaps){const u=Math.max(t.pixelWidth,t.pixelHeight);t.mipLevelCount=Math.floor(Math.log2(u))+1}let e=GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_DST;t.uploadMethodId!=="compressed"&&(e|=GPUTextureUsage.RENDER_ATTACHMENT,e|=GPUTextureUsage.COPY_SRC);const r=od[t.format]||{blockWidth:1,blockHeight:1},n=Math.ceil(t.pixelWidth/r.blockWidth)*r.blockWidth,o=Math.ceil(t.pixelHeight/r.blockHeight)*r.blockHeight,l={label:t.label,size:{width:n,height:o},format:t.format,sampleCount:t.sampleCount,mipLevelCount:t.mipLevelCount,dimension:t.dimension,usage:e},h=this._gpuSources[t.uid]=this._gpu.device.createTexture(l);return this.managedTextures.includes(t)||(t.on("update",this.onSourceUpdate,this),t.on("resize",this.onSourceResize,this),t.on("destroy",this.onSourceDestroy,this),t.on("unload",this.onSourceUnload,this),t.on("updateMipmaps",this.onUpdateMipmaps,this),this.managedTextures.push(t)),this.onSourceUpdate(t),h}onSourceUpdate(t){const e=this.getGpuSource(t);e&&(this._uploads[t.uploadMethodId]&&this._uploads[t.uploadMethodId].upload(t,e,this._gpu),t.autoGenerateMipmaps&&t.mipLevelCount>1&&this.onUpdateMipmaps(t))}onSourceUnload(t){const e=this._gpuSources[t.uid];e&&(this._gpuSources[t.uid]=null,e.destroy())}onUpdateMipmaps(t){this._mipmapGenerator||(this._mipmapGenerator=new ob(this._gpu.device));const e=this.getGpuSource(t);this._mipmapGenerator.generateMipmap(e)}onSourceDestroy(t){t.off("update",this.onSourceUpdate,this),t.off("unload",this.onSourceUnload,this),t.off("destroy",this.onSourceDestroy,this),t.off("resize",this.onSourceResize,this),t.off("updateMipmaps",this.onUpdateMipmaps,this),this.managedTextures.splice(this.managedTextures.indexOf(t),1),this.onSourceUnload(t)}onSourceResize(t){const e=this._gpuSources[t.uid];e?(e.width!==t.pixelWidth||e.height!==t.pixelHeight)&&(this._textureViewHash[t.uid]=null,this._bindGroupHash[t.uid]=null,this.onSourceUnload(t),this.initSource(t)):this.initSource(t)}_initSampler(t){return this._gpuSamplers[t._resourceId]=this._gpu.device.createSampler(t),this._gpuSamplers[t._resourceId]}getGpuSampler(t){return this._gpuSamplers[t._resourceId]||this._initSampler(t)}getGpuSource(t){return this._gpuSources[t.uid]||this.initSource(t)}getTextureBindGroup(t){return this._bindGroupHash[t.uid]??this._createTextureBindGroup(t)}_createTextureBindGroup(t){const e=t.source;return this._bindGroupHash[t.uid]=new ne({0:e,1:e.style,2:new _t({uTextureMatrix:{type:"mat3x3<f32>",value:t.textureMatrix.mapCoord}})}),this._bindGroupHash[t.uid]}getTextureView(t){const e=t.source;return this._textureViewHash[e.uid]??this._createTextureView(e)}_createTextureView(t){return this._textureViewHash[t.uid]=this.getGpuSource(t).createView(),this._textureViewHash[t.uid]}generateCanvas(t){const e=this._renderer,r=e.gpu.device.createCommandEncoder(),n=W.get().createCanvas();n.width=t.source.pixelWidth,n.height=t.source.pixelHeight;const o=n.getContext("webgpu");return o.configure({device:e.gpu.device,usage:GPUTextureUsage.COPY_DST|GPUTextureUsage.COPY_SRC,format:W.get().getNavigator().gpu.getPreferredCanvasFormat(),alphaMode:"premultiplied"}),r.copyTextureToTexture({texture:e.texture.getGpuSource(t.source),origin:{x:0,y:0}},{texture:o.getCurrentTexture()},{width:n.width,height:n.height}),e.gpu.device.queue.submit([r.finish()]),n}getPixels(t){const e=this.generateCanvas(t),r=ae.getOptimalCanvasAndContext(e.width,e.height),n=r.context;n.drawImage(e,0,0);const{width:o,height:l}=e,h=n.getImageData(0,0,o,l),u=new Uint8ClampedArray(h.data.buffer);return ae.returnCanvasAndContext(r),{pixels:u,width:o,height:l}}destroy(){this.managedTextures.slice().forEach(t=>this.onSourceDestroy(t)),this.managedTextures=null;for(const t of Object.keys(this._bindGroupHash)){const e=Number(t);this._bindGroupHash[e]?.destroy(),this._bindGroupHash[e]=null}this._renderer=null,this._gpu=null,this._mipmapGenerator=null,this._gpuSources=null,this._bindGroupHash=null,this._textureViewHash=null,this._gpuSamplers=null}}hd.extension={type:[C.WebGPUSystem],name:"texture"};class ld{constructor(){this._maxTextures=0}contextChange(t){const e=new _t({uTransformMatrix:{value:new M,type:"mat3x3<f32>"},uColor:{value:new Float32Array([1,1,1,1]),type:"vec4<f32>"},uRound:{value:0,type:"f32"}});this._maxTextures=t.limits.maxBatchableTextures;const r=Ui({name:"graphics",bits:[dn,pn(this._maxTextures),Py,Mi]});this.shader=new Ft({gpuProgram:r,resources:{localUniforms:e}})}execute(t,e){const r=e.context,n=r.customShader||this.shader,o=t.renderer,l=o.graphicsContext,{batcher:h,instructions:u}=l.getContextRenderData(r),f=o.encoder;f.setGeometry(h.geometry,n.gpuProgram);const m=o.globalUniforms.bindGroup;f.setBindGroup(0,m,n.gpuProgram);const g=o.renderPipes.uniformBatch.getUniformBindGroup(n.resources.localUniforms,!0);f.setBindGroup(2,g,n.gpuProgram);const y=u.instructions;let x=null;for(let a=0;a<u.instructionSize;a++){const c=y[a];if(c.topology!==x&&(x=c.topology,f.setPipelineFromGeometryProgramAndState(h.geometry,n.gpuProgram,t.state,c.topology)),n.groups[1]=c.bindGroup,!c.gpuBindGroup){const d=c.textures;c.bindGroup=hn(d.textures,d.count,this._maxTextures),c.gpuBindGroup=o.bindGroup.getBindGroup(c.bindGroup,n.gpuProgram,1)}f.setBindGroup(1,c.bindGroup,n.gpuProgram),f.renderPassEncoder.drawIndexed(c.size,1,c.start)}}destroy(){this.shader.destroy(!0),this.shader=null}}ld.extension={type:[C.WebGPUPipesAdaptor],name:"graphics"};class cd{init(){const t=Ui({name:"mesh",bits:[Hi,By,Mi]});this._shader=new Ft({gpuProgram:t,resources:{uTexture:k.EMPTY._source,uSampler:k.EMPTY._source.style,textureUniforms:{uTextureMatrix:{type:"mat3x3<f32>",value:new M}}}})}execute(t,e){const r=t.renderer;let n=e._shader;if(!n)n=this._shader,n.groups[2]=r.texture.getTextureBindGroup(e.texture);else if(!n.gpuProgram){F("Mesh shader has no gpuProgram",e.shader);return}const o=n.gpuProgram;if(o.autoAssignGlobalUniforms&&(n.groups[0]=r.globalUniforms.bindGroup),o.autoAssignLocalUniforms){const l=t.localUniforms;n.groups[1]=r.renderPipes.uniformBatch.getUniformBindGroup(l,!0)}r.encoder.draw({geometry:e._geometry,shader:n,state:e.state})}destroy(){this._shader.destroy(!0),this._shader=null}}cd.extension={type:[C.WebGPUPipesAdaptor],name:"mesh"};const ab=[...Wc,td,Zc,io,Qc,jc,hd,rd,sd,nd,id,qc,Jc,Kc],hb=[...Vc,ed],lb=[$l,cd,ld],dd=[],ud=[],fd=[];D.handleByNamedList(C.WebGPUSystem,dd),D.handleByNamedList(C.WebGPUPipes,ud),D.handleByNamedList(C.WebGPUPipesAdaptor,fd),D.add(...ab,...hb,...lb);class cb extends Tr{constructor(){const t={name:"webgpu",type:Nt.WEBGPU,systems:dd,renderPipes:ud,renderPipeAdaptors:fd};super(t)}}const db=Object.freeze(Object.defineProperty({__proto__:null,WebGPURenderer:cb},Symbol.toStringTag,{value:"Module"}));class ub{constructor(){this.batches=[],this.batched=!1}destroy(){this.batches.forEach(t=>{at.return(t)}),this.batches.length=0}}class pd{constructor(t,e){this.state=Ht.for2d(),this.renderer=t,this._adaptor=e,this.renderer.runners.contextChange.add(this)}contextChange(){this._adaptor.contextChange(this.renderer)}validateRenderable(t){const e=t.context,r=!!t._gpuData,n=this.renderer.graphicsContext.updateGpuContext(e);return!!(n.isBatchable||r!==n.isBatchable)}addRenderable(t,e){const r=this.renderer.graphicsContext.updateGpuContext(t.context);t.didViewUpdate&&this._rebuild(t),r.isBatchable?this._addToBatcher(t,e):(this.renderer.renderPipes.batch.break(e),e.add(t))}updateRenderable(t){const r=this._getGpuDataForRenderable(t).batches;for(let n=0;n<r.length;n++){const o=r[n];o._batcher.updateElement(o)}}execute(t){if(!t.isRenderable)return;const e=this.renderer,r=t.context;if(!e.graphicsContext.getGpuContext(r).batches.length)return;const o=r.customShader||this._adaptor.shader;this.state.blendMode=t.groupBlendMode;const l=o.resources.localUniforms.uniforms;l.uTransformMatrix=t.groupTransform,l.uRound=e._roundPixels|t._roundPixels,Yi(t.groupColorAlpha,l.uColor,0),this._adaptor.execute(this,t)}_rebuild(t){const e=this._getGpuDataForRenderable(t),r=this.renderer.graphicsContext.updateGpuContext(t.context);e.destroy(),r.isBatchable&&this._updateBatchesForRenderable(t,e)}_addToBatcher(t,e){const r=this.renderer.renderPipes.batch,n=this._getGpuDataForRenderable(t).batches;for(let o=0;o<n.length;o++){const l=n[o];r.addToBatch(l,e)}}_getGpuDataForRenderable(t){return t._gpuData[this.renderer.uid]||this._initGpuDataForRenderable(t)}_initGpuDataForRenderable(t){const e=new ub;return t._gpuData[this.renderer.uid]=e,e}_updateBatchesForRenderable(t,e){const r=t.context,n=this.renderer.graphicsContext.getGpuContext(r),o=this.renderer._roundPixels|t._roundPixels;e.batches=n.batches.map(l=>{const h=at.get(xn);return l.copyTo(h),h.renderable=t,h.roundPixels=o,h})}destroy(){this.renderer=null,this._adaptor.destroy(),this._adaptor=null,this.state=null}}pd.extension={type:[C.WebGLPipes,C.WebGPUPipes,C.CanvasPipes],name:"graphics"};const md=class mu extends On{constructor(...t){super({});let e=t[0]??{};typeof e=="number"&&(z($,"PlaneGeometry constructor changed please use { width, height, verticesX, verticesY } instead"),e={width:e,height:t[1],verticesX:t[2],verticesY:t[3]}),this.build(e)}build(t){t={...mu.defaultOptions,...t},this.verticesX=this.verticesX??t.verticesX,this.verticesY=this.verticesY??t.verticesY,this.width=this.width??t.width,this.height=this.height??t.height;const e=this.verticesX*this.verticesY,r=[],n=[],o=[],l=this.verticesX-1,h=this.verticesY-1,u=this.width/l,f=this.height/h;for(let g=0;g<e;g++){const y=g%this.verticesX,x=g/this.verticesX|0;r.push(y*u,x*f),n.push(y/l,x/h)}const m=l*h;for(let g=0;g<m;g++){const y=g%l,x=g/l|0,a=x*this.verticesX+y,c=x*this.verticesX+y+1,d=(x+1)*this.verticesX+y,p=(x+1)*this.verticesX+y+1;o.push(a,c,d,c,p,d)}this.buffers[0].data=new Float32Array(r),this.buffers[1].data=new Float32Array(n),this.indexBuffer.data=new Uint32Array(o),this.buffers[0].update(),this.buffers[1].update(),this.indexBuffer.update()}};md.defaultOptions={width:100,height:100,verticesX:10,verticesY:10};let fb=md;class ro{constructor(){this.batcherName="default",this.packAsQuad=!1,this.indexOffset=0,this.attributeOffset=0,this.roundPixels=0,this._batcher=null,this._batch=null,this._textureMatrixUpdateId=-1,this._uvUpdateId=-1}get blendMode(){return this.renderable.groupBlendMode}get topology(){return this._topology||this.geometry.topology}set topology(t){this._topology=t}reset(){this.renderable=null,this.texture=null,this._batcher=null,this._batch=null,this.geometry=null,this._uvUpdateId=-1,this._textureMatrixUpdateId=-1}setTexture(t){this.texture!==t&&(this.texture=t,this._textureMatrixUpdateId=-1)}get uvs(){const e=this.geometry.getBuffer("aUV"),r=e.data;let n=r;const o=this.texture.textureMatrix;return o.isSimple||(n=this._transformedUvs,(this._textureMatrixUpdateId!==o._updateID||this._uvUpdateId!==e._updateID)&&((!n||n.length<r.length)&&(n=this._transformedUvs=new Float32Array(r.length)),this._textureMatrixUpdateId=o._updateID,this._uvUpdateId=e._updateID,o.multiplyUvs(r,n))),n}get positions(){return this.geometry.positions}get indices(){return this.geometry.indices}get color(){return this.renderable.groupColorAlpha}get groupTransform(){return this.renderable.groupTransform}get attributeSize(){return this.geometry.positions.length/2}get indexSize(){return this.geometry.indices.length}}class gd{destroy(){}}class _d{constructor(t,e){this.localUniforms=new _t({uTransformMatrix:{value:new M,type:"mat3x3<f32>"},uColor:{value:new Float32Array([1,1,1,1]),type:"vec4<f32>"},uRound:{value:0,type:"f32"}}),this.localUniformsBindGroup=new ne({0:this.localUniforms}),this.renderer=t,this._adaptor=e,this._adaptor.init()}validateRenderable(t){const e=this._getMeshData(t),r=e.batched,n=t.batched;if(e.batched=n,r!==n)return!0;if(n){const o=t._geometry;if(o.indices.length!==e.indexSize||o.positions.length!==e.vertexSize)return e.indexSize=o.indices.length,e.vertexSize=o.positions.length,!0;const l=this._getBatchableMesh(t);return l.texture.uid!==t._texture.uid&&(l._textureMatrixUpdateId=-1),!l._batcher.checkAndUpdateTexture(l,t._texture)}return!1}addRenderable(t,e){const r=this.renderer.renderPipes.batch,n=this._getMeshData(t);if(t.didViewUpdate&&(n.indexSize=t._geometry.indices?.length,n.vertexSize=t._geometry.positions?.length),n.batched){const o=this._getBatchableMesh(t);o.setTexture(t._texture),o.geometry=t._geometry,r.addToBatch(o,e)}else r.break(e),e.add(t)}updateRenderable(t){if(t.batched){const e=this._getBatchableMesh(t);e.setTexture(t._texture),e.geometry=t._geometry,e._batcher.updateElement(e)}}execute(t){if(!t.isRenderable)return;t.state.blendMode=Ei(t.groupBlendMode,t.texture._source);const e=this.localUniforms;e.uniforms.uTransformMatrix=t.groupTransform,e.uniforms.uRound=this.renderer._roundPixels|t._roundPixels,e.update(),Yi(t.groupColorAlpha,e.uniforms.uColor,0),this._adaptor.execute(this,t)}_getMeshData(t){var e,r;return(e=t._gpuData)[r=this.renderer.uid]||(e[r]=new gd),t._gpuData[this.renderer.uid].meshData||this._initMeshData(t)}_initMeshData(t){return t._gpuData[this.renderer.uid].meshData={batched:t.batched,indexSize:0,vertexSize:0},t._gpuData[this.renderer.uid].meshData}_getBatchableMesh(t){var e,r;return(e=t._gpuData)[r=this.renderer.uid]||(e[r]=new gd),t._gpuData[this.renderer.uid].batchableMesh||this._initBatchableMesh(t)}_initBatchableMesh(t){const e=new ro;return e.renderable=t,e.setTexture(t._texture),e.transform=t.groupTransform,e.roundPixels=this.renderer._roundPixels|t._roundPixels,t._gpuData[this.renderer.uid].batchableMesh=e,e}destroy(){this.localUniforms=null,this.localUniformsBindGroup=null,this._adaptor.destroy(),this._adaptor=null,this.renderer=null}}_d.extension={type:[C.WebGLPipes,C.WebGPUPipes,C.CanvasPipes],name:"mesh"};class pb{execute(t,e){const r=t.state,n=t.renderer,o=e.shader||t.defaultShader;o.resources.uTexture=e.texture._source,o.resources.uniforms=t.localUniforms;const l=n.gl,h=t.getBuffers(e);n.shader.bind(o),n.state.set(r),n.geometry.bind(h.geometry,o.glProgram);const f=h.geometry.indexBuffer.data.BYTES_PER_ELEMENT===2?l.UNSIGNED_SHORT:l.UNSIGNED_INT;l.drawElements(l.TRIANGLES,e.particleChildren.length*6,f,0)}}class mb{execute(t,e){const r=t.renderer,n=e.shader||t.defaultShader;n.groups[0]=r.renderPipes.uniformBatch.getUniformBindGroup(t.localUniforms,!0),n.groups[1]=r.texture.getTextureBindGroup(e.texture);const o=t.state,l=t.getBuffers(e);r.encoder.draw({geometry:l.geometry,shader:e.shader||t.defaultShader,state:o,size:e.particleChildren.length*6})}}function yd(s,t=null){const e=s*6;if(e>65535?t||(t=new Uint32Array(e)):t||(t=new Uint16Array(e)),t.length!==e)throw new Error(`Out buffer length is incorrect, got ${t.length} and expected ${e}`);for(let r=0,n=0;r<e;r+=6,n+=4)t[r+0]=n+0,t[r+1]=n+1,t[r+2]=n+2,t[r+3]=n+0,t[r+4]=n+2,t[r+5]=n+3;return t}function gb(s){return{dynamicUpdate:xd(s,!0),staticUpdate:xd(s,!1)}}function xd(s,t){const e=[];e.push(`
|
|
1004
1004
|
|
|
1005
1005
|
var index = 0;
|
|
1006
1006
|
|
|
@@ -1008,13 +1008,13 @@ fn mainFragment(
|
|
|
1008
1008
|
{
|
|
1009
1009
|
const p = ps[i];
|
|
1010
1010
|
|
|
1011
|
-
`);let r=0;for(const
|
|
1011
|
+
`);let r=0;for(const o in s){const l=s[o];if(t!==l.dynamic)continue;e.push(`offset = index + ${r}`),e.push(l.code);const h=fe(l.format);r+=h.stride/4}e.push(`
|
|
1012
1012
|
index += stride * 4;
|
|
1013
1013
|
}
|
|
1014
1014
|
`),e.unshift(`
|
|
1015
1015
|
var stride = ${r};
|
|
1016
1016
|
`);const n=e.join(`
|
|
1017
|
-
`);return new Function("ps","f32v","u32v",n)}class
|
|
1017
|
+
`);return new Function("ps","f32v","u32v",n)}class _b{constructor(t){this._size=0,this._generateParticleUpdateCache={};const e=this._size=t.size??1e3,r=t.properties;let n=0,o=0;for(const m in r){const g=r[m],y=fe(g.format);g.dynamic?o+=y.stride:n+=y.stride}this._dynamicStride=o/4,this._staticStride=n/4,this.staticAttributeBuffer=new $e(e*4*n),this.dynamicAttributeBuffer=new $e(e*4*o),this.indexBuffer=yd(e);const l=new Bi;let h=0,u=0;this._staticBuffer=new Bt({data:new Float32Array(1),label:"static-particle-buffer",shrinkToFit:!1,usage:Y.VERTEX|Y.COPY_DST}),this._dynamicBuffer=new Bt({data:new Float32Array(1),label:"dynamic-particle-buffer",shrinkToFit:!1,usage:Y.VERTEX|Y.COPY_DST});for(const m in r){const g=r[m],y=fe(g.format);g.dynamic?(l.addAttribute(g.attributeName,{buffer:this._dynamicBuffer,stride:this._dynamicStride*4,offset:h*4,format:g.format}),h+=y.size):(l.addAttribute(g.attributeName,{buffer:this._staticBuffer,stride:this._staticStride*4,offset:u*4,format:g.format}),u+=y.size)}l.addIndex(this.indexBuffer);const f=this.getParticleUpdate(r);this._dynamicUpload=f.dynamicUpdate,this._staticUpload=f.staticUpdate,this.geometry=l}getParticleUpdate(t){const e=yb(t);return this._generateParticleUpdateCache[e]?this._generateParticleUpdateCache[e]:(this._generateParticleUpdateCache[e]=this.generateParticleUpdate(t),this._generateParticleUpdateCache[e])}generateParticleUpdate(t){return gb(t)}update(t,e){t.length>this._size&&(e=!0,this._size=Math.max(t.length,this._size*1.5|0),this.staticAttributeBuffer=new $e(this._size*this._staticStride*4*4),this.dynamicAttributeBuffer=new $e(this._size*this._dynamicStride*4*4),this.indexBuffer=yd(this._size),this.geometry.indexBuffer.setDataWithSize(this.indexBuffer,this.indexBuffer.byteLength,!0));const r=this.dynamicAttributeBuffer;if(this._dynamicUpload(t,r.float32View,r.uint32View),this._dynamicBuffer.setDataWithSize(this.dynamicAttributeBuffer.float32View,t.length*this._dynamicStride*4,!0),e){const n=this.staticAttributeBuffer;this._staticUpload(t,n.float32View,n.uint32View),this._staticBuffer.setDataWithSize(n.float32View,t.length*this._staticStride*4,!0)}}destroy(){this._staticBuffer.destroy(),this._dynamicBuffer.destroy(),this.geometry.destroy()}}function yb(s){const t=[];for(const e in s){const r=s[e];t.push(e,r.code,r.dynamic?"d":"s")}return t.join("_")}var xb=`varying vec2 vUV;
|
|
1018
1018
|
varying vec4 vColor;
|
|
1019
1019
|
|
|
1020
1020
|
uniform sampler2D uTexture;
|
|
@@ -1022,7 +1022,7 @@ uniform sampler2D uTexture;
|
|
|
1022
1022
|
void main(void){
|
|
1023
1023
|
vec4 color = texture2D(uTexture, vUV) * vColor;
|
|
1024
1024
|
gl_FragColor = color;
|
|
1025
|
-
}`,
|
|
1025
|
+
}`,bb=`attribute vec2 aVertex;
|
|
1026
1026
|
attribute vec2 aUV;
|
|
1027
1027
|
attribute vec4 aColor;
|
|
1028
1028
|
|
|
@@ -1061,7 +1061,7 @@ void main(void){
|
|
|
1061
1061
|
vUV = aUV;
|
|
1062
1062
|
vColor = vec4(aColor.rgb * aColor.a, aColor.a) * uColor;
|
|
1063
1063
|
}
|
|
1064
|
-
`,
|
|
1064
|
+
`,bd=`
|
|
1065
1065
|
struct ParticleUniforms {
|
|
1066
1066
|
uTranslationMatrix:mat3x3<f32>,
|
|
1067
1067
|
uColor:vec4<f32>,
|
|
@@ -1123,7 +1123,7 @@ fn mainFragment(
|
|
|
1123
1123
|
var sample = textureSample(uTexture, uSampler, uv) * color;
|
|
1124
1124
|
|
|
1125
1125
|
return sample;
|
|
1126
|
-
}`;class
|
|
1126
|
+
}`;class vb extends Ft{constructor(){const t=Te.from({vertex:bb,fragment:xb}),e=pe.from({fragment:{source:bd,entryPoint:"mainFragment"},vertex:{source:bd,entryPoint:"mainVertex"}});super({glProgram:t,gpuProgram:e,resources:{uTexture:k.WHITE.source,uSampler:new jt({}),uniforms:{uTranslationMatrix:{value:new M,type:"mat3x3<f32>"},uColor:{value:new J(16777215),type:"vec4<f32>"},uRound:{value:1,type:"f32"},uResolution:{value:[0,0],type:"vec2<f32>"}}}})}}class vd{constructor(t,e){this.state=Ht.for2d(),this.localUniforms=new _t({uTranslationMatrix:{value:new M,type:"mat3x3<f32>"},uColor:{value:new Float32Array(4),type:"vec4<f32>"},uRound:{value:1,type:"f32"},uResolution:{value:[0,0],type:"vec2<f32>"}}),this.renderer=t,this.adaptor=e,this.defaultShader=new vb,this.state=Ht.for2d()}validateRenderable(t){return!1}addRenderable(t,e){this.renderer.renderPipes.batch.break(e),e.add(t)}getBuffers(t){return t._gpuData[this.renderer.uid]||this._initBuffer(t)}_initBuffer(t){return t._gpuData[this.renderer.uid]=new _b({size:t.particleChildren.length,properties:t._properties}),t._gpuData[this.renderer.uid]}updateRenderable(t){}execute(t){const e=t.particleChildren;if(e.length===0)return;const r=this.renderer,n=this.getBuffers(t);t.texture||(t.texture=e[0].texture);const o=this.state;n.update(e,t._childrenDirty),t._childrenDirty=!1,o.blendMode=Ei(t.blendMode,t.texture._source);const l=this.localUniforms.uniforms,h=l.uTranslationMatrix;t.worldTransform.copyTo(h),h.prepend(r.globalUniforms.globalUniformData.projectionMatrix),l.uResolution=r.globalUniforms.globalUniformData.resolution,l.uRound=r._roundPixels|t._roundPixels,Yi(t.groupColorAlpha,l.uColor,0),this.adaptor.execute(this,t)}destroy(){this.renderer=null,this.defaultShader&&(this.defaultShader.destroy(),this.defaultShader=null)}}class wd extends vd{constructor(t){super(t,new pb)}}wd.extension={type:[C.WebGLPipes],name:"particle"};class Sd extends vd{constructor(t){super(t,new mb)}}Sd.extension={type:[C.WebGPUPipes],name:"particle"};const Td=class gu extends fb{constructor(t={}){t={...gu.defaultOptions,...t},super({width:t.width,height:t.height,verticesX:4,verticesY:4}),this.update(t)}update(t){this.width=t.width??this.width,this.height=t.height??this.height,this._originalWidth=t.originalWidth??this._originalWidth,this._originalHeight=t.originalHeight??this._originalHeight,this._leftWidth=t.leftWidth??this._leftWidth,this._rightWidth=t.rightWidth??this._rightWidth,this._topHeight=t.topHeight??this._topHeight,this._bottomHeight=t.bottomHeight??this._bottomHeight,this._anchorX=t.anchor?.x,this._anchorY=t.anchor?.y,this.updateUvs(),this.updatePositions()}updatePositions(){const t=this.positions,{width:e,height:r,_leftWidth:n,_rightWidth:o,_topHeight:l,_bottomHeight:h,_anchorX:u,_anchorY:f}=this,m=n+o,g=e>m?1:e/m,y=l+h,x=r>y?1:r/y,a=Math.min(g,x),c=u*e,d=f*r;t[0]=t[8]=t[16]=t[24]=-c,t[2]=t[10]=t[18]=t[26]=n*a-c,t[4]=t[12]=t[20]=t[28]=e-o*a-c,t[6]=t[14]=t[22]=t[30]=e-c,t[1]=t[3]=t[5]=t[7]=-d,t[9]=t[11]=t[13]=t[15]=l*a-d,t[17]=t[19]=t[21]=t[23]=r-h*a-d,t[25]=t[27]=t[29]=t[31]=r-d,this.getBuffer("aPosition").update()}updateUvs(){const t=this.uvs;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;const e=1/this._originalWidth,r=1/this._originalHeight;t[2]=t[10]=t[18]=t[26]=e*this._leftWidth,t[9]=t[11]=t[13]=t[15]=r*this._topHeight,t[4]=t[12]=t[20]=t[28]=1-e*this._rightWidth,t[17]=t[19]=t[21]=t[23]=1-r*this._bottomHeight,this.getBuffer("aUV").update()}};Td.defaultOptions={width:100,height:100,leftWidth:10,topHeight:10,rightWidth:10,bottomHeight:10,originalWidth:100,originalHeight:100};let wb=Td;class Sb extends ro{constructor(){super(),this.geometry=new wb}destroy(){this.geometry.destroy()}}class Cd{constructor(t){this._renderer=t}addRenderable(t,e){const r=this._getGpuSprite(t);t.didViewUpdate&&this._updateBatchableSprite(t,r),this._renderer.renderPipes.batch.addToBatch(r,e)}updateRenderable(t){const e=this._getGpuSprite(t);t.didViewUpdate&&this._updateBatchableSprite(t,e),e._batcher.updateElement(e)}validateRenderable(t){const e=this._getGpuSprite(t);return!e._batcher.checkAndUpdateTexture(e,t._texture)}_updateBatchableSprite(t,e){e.geometry.update(t),e.setTexture(t._texture)}_getGpuSprite(t){return t._gpuData[this._renderer.uid]||this._initGPUSprite(t)}_initGPUSprite(t){const e=t._gpuData[this._renderer.uid]=new Sb,r=e;return r.renderable=t,r.transform=t.groupTransform,r.texture=t._texture,r.roundPixels=this._renderer._roundPixels|t._roundPixels,t.didViewUpdate||this._updateBatchableSprite(t,r),e}destroy(){this._renderer=null}}Cd.extension={type:[C.WebGLPipes,C.WebGPUPipes,C.CanvasPipes],name:"nineSliceSprite"};const Tb={name:"tiling-bit",vertex:{header:`
|
|
1127
1127
|
struct TilingUniforms {
|
|
1128
1128
|
uMapCoord:mat3x3<f32>,
|
|
1129
1129
|
uClampFrame:vec4<f32>,
|
|
@@ -1166,7 +1166,7 @@ fn mainFragment(
|
|
|
1166
1166
|
}
|
|
1167
1167
|
|
|
1168
1168
|
outColor = textureSampleBias(uTexture, uSampler, coord, bias);
|
|
1169
|
-
`}},
|
|
1169
|
+
`}},Cb={name:"tiling-bit",vertex:{header:`
|
|
1170
1170
|
uniform mat3 uTextureTransform;
|
|
1171
1171
|
uniform vec4 uSizeAnchor;
|
|
1172
1172
|
|
|
@@ -1188,7 +1188,7 @@ fn mainFragment(
|
|
|
1188
1188
|
|
|
1189
1189
|
outColor = texture(uTexture, coord, unclamped == coord ? 0.0 : -32.0);// lod-bias very negative to force lod 0
|
|
1190
1190
|
|
|
1191
|
-
`}};let
|
|
1191
|
+
`}};let so,no;class Eb extends Ft{constructor(){so??(so=Ui({name:"tiling-sprite-shader",bits:[Hi,Tb,Mi]})),no??(no=ki({name:"tiling-sprite-shader",bits:[Ln,Cb,Ri]}));const t=new _t({uMapCoord:{value:new M,type:"mat3x3<f32>"},uClampFrame:{value:new Float32Array([0,0,1,1]),type:"vec4<f32>"},uClampOffset:{value:new Float32Array([0,0]),type:"vec2<f32>"},uTextureTransform:{value:new M,type:"mat3x3<f32>"},uSizeAnchor:{value:new Float32Array([100,100,.5,.5]),type:"vec4<f32>"}});super({glProgram:no,gpuProgram:so,resources:{localUniforms:new _t({uTransformMatrix:{value:new M,type:"mat3x3<f32>"},uColor:{value:new Float32Array([1,1,1,1]),type:"vec4<f32>"},uRound:{value:0,type:"f32"}}),tilingUniforms:t,uTexture:k.EMPTY.source,uSampler:k.EMPTY.source.style}})}updateUniforms(t,e,r,n,o,l){const h=this.resources.tilingUniforms,u=l.width,f=l.height,m=l.textureMatrix,g=h.uniforms.uTextureTransform;g.set(r.a*u/t,r.b*u/e,r.c*f/t,r.d*f/e,r.tx/t,r.ty/e),g.invert(),h.uniforms.uMapCoord=m.mapCoord,h.uniforms.uClampFrame=m.uClampFrame,h.uniforms.uClampOffset=m.uClampOffset,h.uniforms.uTextureTransform=g,h.uniforms.uSizeAnchor[0]=t,h.uniforms.uSizeAnchor[1]=e,h.uniforms.uSizeAnchor[2]=n,h.uniforms.uSizeAnchor[3]=o,l&&(this.resources.uTexture=l.source,this.resources.uSampler=l.source.style)}}class Ab extends On{constructor(){super({positions:new Float32Array([0,0,1,0,1,1,0,1]),uvs:new Float32Array([0,0,1,0,1,1,0,1]),indices:new Uint32Array([0,1,2,0,2,3])})}}function Pb(s,t){const e=s.anchor.x,r=s.anchor.y;t[0]=-e*s.width,t[1]=-r*s.height,t[2]=(1-e)*s.width,t[3]=-r*s.height,t[4]=(1-e)*s.width,t[5]=(1-r)*s.height,t[6]=-e*s.width,t[7]=(1-r)*s.height}function Bb(s,t,e,r){let n=0;const o=s.length/t,l=r.a,h=r.b,u=r.c,f=r.d,m=r.tx,g=r.ty;for(e*=t;n<o;){const y=s[e],x=s[e+1];s[e]=l*y+u*x+m,s[e+1]=h*y+f*x+g,e+=t,n++}}function Ub(s,t){const e=s.texture,r=e.frame.width,n=e.frame.height;let o=0,l=0;s.applyAnchorToTexture&&(o=s.anchor.x,l=s.anchor.y),t[0]=t[6]=-o,t[2]=t[4]=1-o,t[1]=t[3]=-l,t[5]=t[7]=1-l;const h=M.shared;h.copyFrom(s._tileTransform.matrix),h.tx/=s.width,h.ty/=s.height,h.invert(),h.scale(s.width/r,s.height/n),Bb(t,2,0,h)}const Xr=new Ab;class kb{constructor(){this.canBatch=!0,this.geometry=new On({indices:Xr.indices.slice(),positions:Xr.positions.slice(),uvs:Xr.uvs.slice()})}destroy(){this.geometry.destroy(),this.shader?.destroy()}}class Ed{constructor(t){this._state=Ht.default2d,this._renderer=t}validateRenderable(t){const e=this._getTilingSpriteData(t),r=e.canBatch;this._updateCanBatch(t);const n=e.canBatch;if(n&&n===r){const{batchableMesh:o}=e;return!o._batcher.checkAndUpdateTexture(o,t.texture)}return r!==n}addRenderable(t,e){const r=this._renderer.renderPipes.batch;this._updateCanBatch(t);const n=this._getTilingSpriteData(t),{geometry:o,canBatch:l}=n;if(l){n.batchableMesh||(n.batchableMesh=new ro);const h=n.batchableMesh;t.didViewUpdate&&(this._updateBatchableMesh(t),h.geometry=o,h.renderable=t,h.transform=t.groupTransform,h.setTexture(t._texture)),h.roundPixels=this._renderer._roundPixels|t._roundPixels,r.addToBatch(h,e)}else r.break(e),n.shader||(n.shader=new Eb),this.updateRenderable(t),e.add(t)}execute(t){const{shader:e}=this._getTilingSpriteData(t);e.groups[0]=this._renderer.globalUniforms.bindGroup;const r=e.resources.localUniforms.uniforms;r.uTransformMatrix=t.groupTransform,r.uRound=this._renderer._roundPixels|t._roundPixels,Yi(t.groupColorAlpha,r.uColor,0),this._state.blendMode=Ei(t.groupBlendMode,t.texture._source),this._renderer.encoder.draw({geometry:Xr,shader:e,state:this._state})}updateRenderable(t){const e=this._getTilingSpriteData(t),{canBatch:r}=e;if(r){const{batchableMesh:n}=e;t.didViewUpdate&&this._updateBatchableMesh(t),n._batcher.updateElement(n)}else if(t.didViewUpdate){const{shader:n}=e;n.updateUniforms(t.width,t.height,t._tileTransform.matrix,t.anchor.x,t.anchor.y,t.texture)}}_getTilingSpriteData(t){return t._gpuData[this._renderer.uid]||this._initTilingSpriteData(t)}_initTilingSpriteData(t){const e=new kb;return e.renderable=t,t._gpuData[this._renderer.uid]=e,e}_updateBatchableMesh(t){const e=this._getTilingSpriteData(t),{geometry:r}=e,n=t.texture.source.style;n.addressMode!=="repeat"&&(n.addressMode="repeat",n.update()),Ub(t,r.uvs),Pb(t,r.positions)}destroy(){this._renderer=null}_updateCanBatch(t){const e=this._getTilingSpriteData(t),r=t.texture;let n=!0;return this._renderer.type===Nt.WEBGL&&(n=this._renderer.context.supports.nonPowOf2wrapping),e.canBatch=r.textureMatrix.isSimple&&(n||r.source.isPowerOfTwo),e.canBatch}}Ed.extension={type:[C.WebGLPipes,C.WebGPUPipes,C.CanvasPipes],name:"tilingSprite"};const Mb={name:"local-uniform-msdf-bit",vertex:{header:`
|
|
1192
1192
|
struct LocalUniforms {
|
|
1193
1193
|
uColor:vec4<f32>,
|
|
1194
1194
|
uTransformMatrix:mat3x3<f32>,
|
|
@@ -1215,7 +1215,7 @@ fn mainFragment(
|
|
|
1215
1215
|
@group(2) @binding(0) var<uniform> localUniforms : LocalUniforms;
|
|
1216
1216
|
`,main:`
|
|
1217
1217
|
outColor = vec4<f32>(calculateMSDFAlpha(outColor, localUniforms.uColor, localUniforms.uDistance));
|
|
1218
|
-
`}},
|
|
1218
|
+
`}},Rb={name:"local-uniform-msdf-bit",vertex:{header:`
|
|
1219
1219
|
uniform mat3 uTransformMatrix;
|
|
1220
1220
|
uniform vec4 uColor;
|
|
1221
1221
|
uniform float uRound;
|
|
@@ -1231,7 +1231,7 @@ fn mainFragment(
|
|
|
1231
1231
|
uniform float uDistance;
|
|
1232
1232
|
`,main:`
|
|
1233
1233
|
outColor = vec4(calculateMSDFAlpha(outColor, vColor, uDistance));
|
|
1234
|
-
`}},
|
|
1234
|
+
`}},Ib={name:"msdf-bit",fragment:{header:`
|
|
1235
1235
|
fn calculateMSDFAlpha(msdfColor:vec4<f32>, shapeColor:vec4<f32>, distance:f32) -> f32 {
|
|
1236
1236
|
|
|
1237
1237
|
// MSDF
|
|
@@ -1258,7 +1258,7 @@ fn mainFragment(
|
|
|
1258
1258
|
return coverage;
|
|
1259
1259
|
|
|
1260
1260
|
}
|
|
1261
|
-
`}},
|
|
1261
|
+
`}},Fb={name:"msdf-bit",fragment:{header:`
|
|
1262
1262
|
float calculateMSDFAlpha(vec4 msdfColor, vec4 shapeColor, float distance) {
|
|
1263
1263
|
|
|
1264
1264
|
// MSDF
|
|
@@ -1285,11 +1285,11 @@ fn mainFragment(
|
|
|
1285
1285
|
|
|
1286
1286
|
return coverage;
|
|
1287
1287
|
}
|
|
1288
|
-
`}};let
|
|
1288
|
+
`}};let oo,ao;class Db extends Ft{constructor(t){const e=new _t({uColor:{value:new Float32Array([1,1,1,1]),type:"vec4<f32>"},uTransformMatrix:{value:new M,type:"mat3x3<f32>"},uDistance:{value:4,type:"f32"},uRound:{value:0,type:"f32"}});oo??(oo=Ui({name:"sdf-shader",bits:[dn,pn(t),Mb,Ib,Mi]})),ao??(ao=ki({name:"sdf-shader",bits:[un,gn(t),Rb,Fb,Ri]})),super({glProgram:ao,gpuProgram:oo,resources:{localUniforms:e,batchSamplers:_n(t)}})}}class Ob extends Zt{destroy(){this.context.customShader&&this.context.customShader.destroy(),super.destroy()}}class Ad{constructor(t){this._renderer=t}validateRenderable(t){const e=this._getGpuBitmapText(t);return this._renderer.renderPipes.graphics.validateRenderable(e)}addRenderable(t,e){const r=this._getGpuBitmapText(t);Pd(t,r),t._didTextUpdate&&(t._didTextUpdate=!1,this._updateContext(t,r)),this._renderer.renderPipes.graphics.addRenderable(r,e),r.context.customShader&&this._updateDistanceField(t)}updateRenderable(t){const e=this._getGpuBitmapText(t);Pd(t,e),this._renderer.renderPipes.graphics.updateRenderable(e),e.context.customShader&&this._updateDistanceField(t)}_updateContext(t,e){const{context:r}=e,n=Gi.getFont(t.text,t._style);r.clear(),n.distanceField.type!=="none"&&(r.customShader||(r.customShader=new Db(this._renderer.limits.maxBatchableTextures)));const o=xt.graphemeSegmenter(t.text),l=t._style;let h=n.baseLineOffset;const u=Pn(o,l,n,!0),f=l.padding,m=u.scale;let g=u.width,y=u.height+u.offsetY;l._stroke&&(g+=l._stroke.width/m,y+=l._stroke.width/m),r.translate(-t._anchor._x*g-f,-t._anchor._y*y-f).scale(m,m);const x=n.applyFillAsTint?l._fill.color:16777215;let a=n.fontMetrics.fontSize,c=n.lineHeight;l.lineHeight&&(a=l.fontSize/m,c=l.lineHeight/m);let d=(c-a)/2;d-n.baseLineOffset<0&&(d=0);for(let p=0;p<u.lines.length;p++){const _=u.lines[p];for(let b=0;b<_.charPositions.length;b++){const v=_.chars[b],w=n.chars[v];if(w?.texture){const S=w.texture;r.texture(S,x||"black",Math.round(_.charPositions[b]+w.xOffset),Math.round(h+w.yOffset+d),S.orig.width,S.orig.height)}}h+=c}}_getGpuBitmapText(t){return t._gpuData[this._renderer.uid]||this.initGpuText(t)}initGpuText(t){const e=new Ob;return t._gpuData[this._renderer.uid]=e,this._updateContext(t,e),e}_updateDistanceField(t){const e=this._getGpuBitmapText(t).context,r=t._style.fontFamily,n=Q.get(`${r}-bitmap`),{a:o,b:l,c:h,d:u}=t.groupTransform,f=Math.sqrt(o*o+l*l),m=Math.sqrt(h*h+u*u),g=(Math.abs(f)+Math.abs(m))/2,y=n.baseRenderedFontSize/t._style.fontSize,x=g*n.distanceField.range*(1/y);e.customShader.resources.localUniforms.uniforms.uDistance=x}destroy(){this._renderer=null}}Ad.extension={type:[C.WebGLPipes,C.WebGPUPipes,C.CanvasPipes],name:"bitmapText"};function Pd(s,t){t.groupTransform=s.groupTransform,t.groupColorAlpha=s.groupColorAlpha,t.groupColor=s.groupColor,t.groupBlendMode=s.groupBlendMode,t.globalDisplayStatus=s.globalDisplayStatus,t.groupTransform=s.groupTransform,t.localDisplayStatus=s.localDisplayStatus,t.groupAlpha=s.groupAlpha,t._roundPixels=s._roundPixels}function Gb(s){const{text:t,style:e,chars:r}=s,n=e,o=Gi.getFont(t,n),l=xt.graphemeSegmenter(t),h=Pn(l,n,o,!0),u=h.scale,f=[],m=[],g=[],y=e.lineHeight?e.lineHeight:o.lineHeight*u;let x=0;for(const a of h.lines){if(a.chars.length===0)continue;const c=new st({label:"line"});c.y=x,g.push(c);let d=new st({label:"word"}),p=0;for(let _=0;_<a.chars.length;_++){const b=a.chars[_];if(!b||!o.chars[b])continue;const w=b===" ",S=_===a.chars.length-1;let T;r.length>0?(T=r.shift(),T.text=b,T.style=n,T.label=`char-${b}`,T.x=a.charPositions[_]*u-a.charPositions[p]*u):T=new Ey({text:b,style:n,label:`char-${b}`,x:a.charPositions[_]*u-a.charPositions[p]*u}),w||(f.push(T),d.addChild(T)),(w||S)&&d.children.length>0&&(d.x=a.charPositions[p]*u,m.push(d),c.addChild(d),d=new st({label:"word"}),p=_+1)}x+=y}return{chars:f,lines:g,words:m}}class Lb extends Vr{constructor(t){super(),this.generatingTexture=!1,this.currentKey="--",this._renderer=t,t.runners.resolutionChange.add(this)}resolutionChange(){const t=this.renderable;t._autoResolution&&t.onViewUpdate()}destroy(){const{htmlText:t}=this._renderer;t.getReferenceCount(this.currentKey)===null?t.returnTexturePromise(this.texturePromise):t.decreaseReferenceCount(this.currentKey),this._renderer.runners.resolutionChange.remove(this),this.texturePromise=null,this._renderer=null}}function ho(s,t){const{texture:e,bounds:r}=s,n=t._style._getFinalPadding();na(r,t._anchor,e);const o=t._anchor._x*n*2,l=t._anchor._y*n*2;r.minX-=n-o,r.minY-=n-l,r.maxX-=n-o,r.maxY-=n-l}class Bd{constructor(t){this._renderer=t}validateRenderable(t){const e=this._getGpuText(t),r=t.styleKey;return e.currentKey!==r}addRenderable(t,e){const r=this._getGpuText(t);if(t._didTextUpdate){const n=t._autoResolution?this._renderer.resolution:t.resolution;(r.currentKey!==t.styleKey||t.resolution!==n)&&this._updateGpuText(t).catch(o=>{console.error(o)}),t._didTextUpdate=!1,ho(r,t)}this._renderer.renderPipes.batch.addToBatch(r,e)}updateRenderable(t){const e=this._getGpuText(t);e._batcher.updateElement(e)}async _updateGpuText(t){t._didTextUpdate=!1;const e=this._getGpuText(t);if(e.generatingTexture)return;const r=e.texturePromise;e.texturePromise=null,e.generatingTexture=!0,t._resolution=t._autoResolution?this._renderer.resolution:t.resolution;let n=this._renderer.htmlText.getTexturePromise(t);r&&(n=n.finally(()=>{this._renderer.htmlText.decreaseReferenceCount(e.currentKey),this._renderer.htmlText.returnTexturePromise(r)})),e.texturePromise=n,e.currentKey=t.styleKey,e.texture=await n;const o=t.renderGroup||t.parentRenderGroup;o&&(o.structureDidChange=!0),e.generatingTexture=!1,ho(e,t)}_getGpuText(t){return t._gpuData[this._renderer.uid]||this.initGpuText(t)}initGpuText(t){const e=new Lb(this._renderer);return e.renderable=t,e.transform=t.groupTransform,e.texture=k.EMPTY,e.bounds={minX:0,maxX:1,minY:0,maxY:0},e.roundPixels=this._renderer._roundPixels|t._roundPixels,t._resolution=t._autoResolution?this._renderer.resolution:t.resolution,t._gpuData[this._renderer.uid]=e,e}destroy(){this._renderer=null}}Bd.extension={type:[C.WebGLPipes,C.WebGPUPipes,C.CanvasPipes],name:"htmlText"};function zb(){const{userAgent:s}=W.get().getNavigator();return/^((?!chrome|android).)*safari/i.test(s)}const Nb=new ut;function Ud(s,t,e,r){const n=Nb;n.minX=0,n.minY=0,n.maxX=s.width/r|0,n.maxY=s.height/r|0;const o=dt.getOptimalTexture(n.width,n.height,r,!1);return o.source.uploadMethodId="image",o.source.resource=s,o.source.alphaMode="premultiply-alpha-on-upload",o.frame.width=t/r,o.frame.height=e/r,o.source.emit("update",o.source),o.updateUvs(),o}function Hb(s,t){const e=t.fontFamily,r=[],n={},o=/font-family:([^;"\s]+)/g,l=s.match(o);function h(u){n[u]||(r.push(u),n[u]=!0)}if(Array.isArray(e))for(let u=0;u<e.length;u++)h(e[u]);else h(e);l&&l.forEach(u=>{const f=u.split(":")[1].trim();h(f)});for(const u in t.tagStyles){const f=t.tagStyles[u].fontFamily;h(f)}return r}async function Wb(s){const e=await(await W.get().fetch(s)).blob(),r=new FileReader;return await new Promise((o,l)=>{r.onloadend=()=>o(r.result),r.onerror=l,r.readAsDataURL(e)})}async function Vb(s,t){const e=await Wb(t);return`@font-face {
|
|
1289
1289
|
font-family: "${s.fontFamily}";
|
|
1290
1290
|
font-weight: ${s.fontWeight};
|
|
1291
1291
|
font-style: ${s.fontStyle};
|
|
1292
1292
|
src: url('${e}');
|
|
1293
|
-
}`}const
|
|
1294
|
-
`)))}return
|
|
1295
|
-
`)}function Gb(s,t,e,r,n){const{domElement:a,styleElement:l,svgRoot:h}=n;a.innerHTML=`<style>${t.cssStyle}</style><div style='padding:0;'>${s}</div>`,a.setAttribute("style",`transform: scale(${e});transform-origin: top left; display: inline-block`),l.textContent=r;const{width:d,height:f}=n.image;return h.setAttribute("width",d.toString()),h.setAttribute("height",f.toString()),new XMLSerializer().serializeToString(h)}function Ob(s,t){const e=ne.getOptimalCanvasAndContext(s.width,s.height,t),{context:r}=e;return r.clearRect(0,0,s.width,s.height),r.drawImage(s,0,0),e}function Lb(s,t,e){return new Promise(async r=>{e&&await new Promise(n=>setTimeout(n,100)),s.onload=()=>{r()},s.src=`data:image/svg+xml;charset=utf8,${encodeURIComponent(t)}`,s.crossOrigin="anonymous"})}class Au{constructor(t){this._activeTextures={},this._renderer=t,this._createCanvas=t.type===Nt.WEBGPU}getTexture(t){return this.getTexturePromise(t)}getManagedTexture(t){const e=t.styleKey;if(this._activeTextures[e])return this._increaseReferenceCount(e),this._activeTextures[e].promise;const r=this._buildTexturePromise(t).then(n=>(this._activeTextures[e].texture=n,n));return this._activeTextures[e]={texture:null,promise:r,usageCount:1},r}getReferenceCount(t){return this._activeTextures[t]?.usageCount??null}_increaseReferenceCount(t){this._activeTextures[t].usageCount++}decreaseReferenceCount(t){const e=this._activeTextures[t];e&&(e.usageCount--,e.usageCount===0&&(e.texture?this._cleanUp(e.texture):e.promise.then(r=>{e.texture=r,this._cleanUp(e.texture)}).catch(()=>{F("HTMLTextSystem: Failed to clean texture")}),this._activeTextures[t]=null))}getTexturePromise(t){return this._buildTexturePromise(t)}async _buildTexturePromise(t){const{text:e,style:r,resolution:n,textureStyle:a}=t,l=at.get(zl),h=Rb(e,r),d=await Db(h),f=yy(e,r,d,l),m=Math.ceil(Math.ceil(Math.max(1,f.width)+r.padding*2)*n),g=Math.ceil(Math.ceil(Math.max(1,f.height)+r.padding*2)*n),y=l.image,x=2;y.width=(m|0)+x,y.height=(g|0)+x;const o=Gb(e,r,n,d,l);await Lb(y,o,Mb()&&h.length>0);const c=y;let u;this._createCanvas&&(u=Ob(y,n));const p=Eu(u?u.canvas:c,y.width-x,y.height-x,n);return a&&(p.source.style=a),this._createCanvas&&(this._renderer.texture.initSource(p.source),ne.returnCanvasAndContext(u)),at.return(l),p}returnTexturePromise(t){t.then(e=>{this._cleanUp(e)}).catch(()=>{F("HTMLTextSystem: Failed to clean texture")})}_cleanUp(t){ut.returnTexture(t,!0),t.source.resource=null,t.source.uploadMethodId="unknown"}destroy(){this._renderer=null;for(const t in this._activeTextures)this._activeTextures[t]&&this.returnTexturePromise(this._activeTextures[t].promise);this._activeTextures=null}}Au.extension={type:[C.WebGLSystem,C.WebGPUSystem,C.CanvasSystem],name:"htmlText"};class zb extends ot{constructor(t){const{text:e,style:r,autoSplit:n,lineAnchor:a,wordAnchor:l,charAnchor:h,...d}=t;super(d),this._dirty=!1,this._canReuseChars=!1,this.chars=[],this.words=[],this.lines=[],this._originalText=e,this._autoSplit=n,this._lineAnchor=a,this._wordAnchor=l,this._charAnchor=h,this.style=r}split(){const t=this.splitFn();this.chars=t.chars,this.words=t.words,this.lines=t.lines,this.addChild(...this.lines),this.charAnchor=this._charAnchor,this.wordAnchor=this._wordAnchor,this.lineAnchor=this._lineAnchor,this._dirty=!1,this._canReuseChars=!0}get text(){return this._originalText}set text(t){this._originalText=t,this.lines.forEach(e=>e.destroy({children:!0})),this.lines.length=0,this.words.length=0,this.chars.length=0,this._canReuseChars=!1,this.onTextUpdate()}_setOrigin(t,e,r){let n;typeof t=="number"?n={x:t,y:t}:n={x:t.x,y:t.y},e.forEach(a=>{const l=a.getLocalBounds(),h=l.minX+l.width*n.x,d=l.minY+l.height*n.y;a.origin.set(h,d)}),this[r]=t}get lineAnchor(){return this._lineAnchor}set lineAnchor(t){this._setOrigin(t,this.lines,"_lineAnchor")}get wordAnchor(){return this._wordAnchor}set wordAnchor(t){this._setOrigin(t,this.words,"_wordAnchor")}get charAnchor(){return this._charAnchor}set charAnchor(t){this._setOrigin(t,this.chars,"_charAnchor")}get style(){return this._style}set style(t){t||(t={}),this._style=new Bt(t),this.words.forEach(e=>e.destroy()),this.words.length=0,this.lines.forEach(e=>e.destroy()),this.lines.length=0,this._canReuseChars=!0,this.onTextUpdate()}onTextUpdate(){this._dirty=!0,this._autoSplit&&this.split()}destroy(t){super.destroy(t),this.chars=[],this.words=[],this.lines=[],(typeof t=="boolean"?t:t?.style)&&this._style.destroy(t),this._style=null,this._originalText=""}}const Pu=class jr extends zb{constructor(t){const e={...jr.defaultOptions,...t};super(e)}static from(t,e){const r={...jr.defaultOptions,...e,text:t.text,style:new Bt(t.style)};return new jr({...r})}splitFn(){return Bb({text:this._originalText,style:this._style,chars:this._canReuseChars?this.chars:[]})}};Pu.defaultOptions={autoSplit:!0,lineAnchor:0,wordAnchor:0,charAnchor:0};let Nb=Pu;class Hb extends Hr{constructor(t){super(),this._renderer=t,t.runners.resolutionChange.add(this)}resolutionChange(){const t=this.renderable;t._autoResolution&&t.onViewUpdate()}destroy(){const{canvasText:t}=this._renderer;t.getReferenceCount(this.currentKey)>0?t.decreaseReferenceCount(this.currentKey):this.texture&&t.returnTexture(this.texture),this._renderer.runners.resolutionChange.remove(this),this._renderer=null}}class Bu{constructor(t){this._renderer=t}validateRenderable(t){const e=this._getGpuText(t),r=t.styleKey;return e.currentKey!==r?!0:t._didTextUpdate}addRenderable(t,e){const r=this._getGpuText(t);if(t._didTextUpdate){const n=t._autoResolution?this._renderer.resolution:t.resolution;(r.currentKey!==t.styleKey||t.resolution!==n)&&this._updateGpuText(t),t._didTextUpdate=!1,na(r,t)}this._renderer.renderPipes.batch.addToBatch(r,e)}updateRenderable(t){const e=this._getGpuText(t);e._batcher.updateElement(e)}_updateGpuText(t){const e=this._getGpuText(t);e.texture&&this._renderer.canvasText.decreaseReferenceCount(e.currentKey),t._resolution=t._autoResolution?this._renderer.resolution:t.resolution,e.texture=this._renderer.canvasText.getManagedTexture(t),e.currentKey=t.styleKey}_getGpuText(t){return t._gpuData[this._renderer.uid]||this.initGpuText(t)}initGpuText(t){const e=new Hb(this._renderer);return e.currentKey="--",e.renderable=t,e.transform=t.groupTransform,e.bounds={minX:0,maxX:1,minY:0,maxY:0},e.roundPixels=this._renderer._roundPixels|t._roundPixels,t._gpuData[this._renderer.uid]=e,e}destroy(){this._renderer=null}}Bu.extension={type:[C.WebGLPipes,C.WebGPUPipes,C.CanvasPipes],name:"text"};class Uu{constructor(t){this._activeTextures={},this._renderer=t}getTexture(t,e,r,n){typeof t=="string"&&(z("8.0.0","CanvasTextSystem.getTexture: Use object TextOptions instead of separate arguments"),t={text:t,style:r,resolution:e}),t.style instanceof Bt||(t.style=new Bt(t.style)),t.textureStyle instanceof Kt||(t.textureStyle=new Kt(t.textureStyle)),typeof t.text!="string"&&(t.text=t.text.toString());const{text:a,style:l,textureStyle:h}=t,d=t.resolution??this._renderer.resolution,{frame:f,canvasAndContext:m}=zi.getCanvasAndContext({text:a,style:l,resolution:d}),g=Eu(m.canvas,f.width,f.height,d);if(h&&(g.source.style=h),l.trim&&(f.pad(l.padding),g.frame.copyFrom(f),g.frame.scale(1/d),g.updateUvs()),l.filters){const y=this._applyFilters(g,l.filters);return this.returnTexture(g),zi.returnCanvasAndContext(m),y}return this._renderer.texture.initSource(g._source),zi.returnCanvasAndContext(m),g}returnTexture(t){const e=t.source;e.resource=null,e.uploadMethodId="unknown",e.alphaMode="no-premultiply-alpha",ut.returnTexture(t,!0)}renderTextToCanvas(){z("8.10.0","CanvasTextSystem.renderTextToCanvas: no longer supported, use CanvasTextSystem.getTexture instead")}getManagedTexture(t){t._resolution=t._autoResolution?this._renderer.resolution:t.resolution;const e=t.styleKey;if(this._activeTextures[e])return this._increaseReferenceCount(e),this._activeTextures[e].texture;const r=this.getTexture({text:t.text,style:t.style,resolution:t._resolution,textureStyle:t.textureStyle});return this._activeTextures[e]={texture:r,usageCount:1},r}decreaseReferenceCount(t){const e=this._activeTextures[t];e.usageCount--,e.usageCount===0&&(this.returnTexture(e.texture),this._activeTextures[t]=null)}getReferenceCount(t){return this._activeTextures[t]?.usageCount??0}_increaseReferenceCount(t){this._activeTextures[t].usageCount++}_applyFilters(t,e){const r=this._renderer.renderTarget.renderTarget,n=this._renderer.filter.generateFilteredTexture({texture:t,filters:e});return this._renderer.renderTarget.bind(r,!1),n}destroy(){this._renderer=null;for(const t in this._activeTextures)this._activeTextures[t]&&this.returnTexture(this._activeTextures[t].texture);this._activeTextures=null}}Uu.extension={type:[C.WebGLSystem,C.WebGPUSystem,C.CanvasSystem],name:"canvasText"},D.add(wf,Sf);function vt(s){if(s!=null){if(typeof s=="number")return s;if(typeof s=="string"){if(s.startsWith("#")){const e=parseInt(s.slice(1),16);if(!isNaN(e))return e}if(s.startsWith("0x")){const e=parseInt(s,16);if(!isNaN(e))return e}const t=parseInt(s,16);if(!isNaN(t))return t;try{return new J(s).toNumber()}catch{return}}}}class Be extends li{ready;_meta={duration:1/0,width:0,height:0};get meta(){return{...this._meta}}text;get style(){if(!this.originalOpts)return{};const t=this.originalOpts;return{fontSize:t.fontSize,fontFamily:t.fontFamily,fontWeight:t.fontWeight,fontStyle:t.fontStyle,color:t.fill,align:t.align,stroke:t.stroke?typeof t.stroke=="object"?{color:t.stroke.color,width:t.stroke.width}:{color:t.stroke,width:t.strokeWidth??0}:void 0,shadow:t.dropShadow?{color:t.dropShadow.color??"#000000",alpha:t.dropShadow.alpha??.5,blur:t.dropShadow.blur??4,offsetX:t.dropShadow.distance?Math.cos((t.dropShadow.angle??0)*Math.PI/180)*t.dropShadow.distance:0,offsetY:t.dropShadow.distance?Math.sin((t.dropShadow.angle??0)*Math.PI/180)*t.dropShadow.distance:0}:void 0}}bottomOffset;opts;pixiTextContainer=null;renderTexture=null;wordTexts=[];extraPadding=0;textStyle;externalRenderer=null;pixiApp=null;originalOpts=null;constructor(t,e={},r){super(),this.text=t,this.originalOpts={...e},this.externalRenderer=r??null,this.opts={fontSize:e.fontSize??30,fontFamily:e.fontFamily??"Arial",fontUrl:e.fontUrl??"",fontWeight:e.fontWeight??"normal",fontStyle:e.fontStyle??"normal",fill:e.fill??"#ffffff",strokeWidth:e.strokeWidth??0,align:e.align??"center",wordWrapWidth:e.wordWrapWidth??0,wordWrap:e.wordWrap??!1,lineHeight:e.lineHeight??1,letterSpacing:e.letterSpacing??0,videoWidth:e.caption?.positioning?.videoWidth??e.videoWidth??1280,videoHeight:e.caption?.positioning?.videoHeight??e.videoHeight??720,bottomOffset:e.caption?.positioning?.bottomOffset??e.bottomOffset??30,keyword:e.caption?.colors?.keyword??e.colors?.keyword??"#ffff00",background:e.caption?.colors?.background??e.colors?.background??"#000000",active:e.caption?.colors?.active??e.colors?.active??"#ffffff",activeFill:e.caption?.colors?.activeFill??e.colors?.activeFill??"#00ff00",appeared:e.caption?.colors?.appeared??e.colors?.appeared??"#ffffff",words:e.caption?.words??e.words??[],preserveKeywordColor:e.caption?.preserveKeywordColor??e.preserveKeywordColor??!1};const n={fontSize:this.opts.fontSize,fontFamily:this.opts.fontFamily,fontWeight:this.opts.fontWeight,fontStyle:this.opts.fontStyle,align:this.opts.align};if(e.fill&&typeof e.fill=="object"&&e.fill.type==="gradient"){const h=new Vt(e.fill.x0,e.fill.y0,e.fill.x1,e.fill.y1);e.fill.colors.forEach(({ratio:d,color:f})=>{const m=typeof f=="number"?f:vt(f)??16777215;h.addColorStop(d,m)}),n.fill={fill:h}}else{const h=typeof e.fill=="string"||typeof e.fill=="number"?vt(e.fill):void 0;n.fill=h??16777215}if(e.stroke&&typeof e.stroke=="object"&&"color"in e.stroke){const h=vt(e.stroke.color);h!==void 0&&(n.stroke={color:h,width:e.stroke.width},e.stroke.join&&(n.stroke.join=e.stroke.join))}else{const h=vt(e.stroke);h!==void 0?n.stroke={color:h,width:this.opts.strokeWidth??0}:this.opts.strokeWidth&&this.opts.strokeWidth>0&&(n.stroke={color:0,width:this.opts.strokeWidth})}if(e.dropShadow){const h=vt(e.dropShadow.color);h!==void 0&&(n.dropShadow={color:h,alpha:e.dropShadow.alpha??.5,blur:e.dropShadow.blur??4,angle:e.dropShadow.angle??Math.PI/6,distance:e.dropShadow.distance??2})}const a=new Bt(n),l=new Bt({...n,fontFamily:"Arial"});this.textStyle=a,this.ready=(async()=>{this.pixiTextContainer=new ot;let h=0,d=0,f=0;this.wordTexts=this.opts.words.map(w=>{const S=new Nb({text:w.text,style:a});S.x=h,S.y=0;const T=S.getLocalBounds(),E=Math.ceil(T.width||S.width),P=Math.ceil(T.height||S.height);d=Math.max(d,P),h+=E+5,f=h-5,this.pixiTextContainer.addChild(S);const B=vt(this.opts.fill);return S.tint=B??16777215,S});const m=f,g=d,y=new pe;y.label="containerBackground";const x=vt(this.opts.background)||0,o=15,c=10,u=1;y.roundRect(0,0,m+o*2,g+o*2,c),y.fill({color:x,alpha:u}),this.wordTexts.forEach(w=>{const S=xt.measureText(w.text,this.textStyle),T=xt.measureText(w.text,l),E=S.fontProperties.descent,P=T.fontProperties.descent;this.extraPadding=P-E,w.pivot.y=0,w.pivot.x=0,w.y=o-this.extraPadding,w.x+=o}),this.pixiTextContainer.addChildAt(y,0),this.renderTexture=Wi.create({width:m+o*2,height:g+o*2}),this._meta.width=m+o*2,this._meta.height=g+o*2,this._meta.duration=1/0;const p=e.videoWidth??1280,_=e.videoHeight??720,b=e.bottomOffset??30;this.width=this.width===0?this._meta.width:this.width,this.height=this.height===0?this._meta.height:this.height,this.top=_-this.height-b,this.left=(p-this.width)/2;const v={...this._meta};return this.duration===0&&v.duration!==1/0&&(this.duration=v.duration,this.display.to=this.display.from+this.duration),H.info("CaptionClip ready:",v),v})()}lastLoggedTime=-1;updateState(t){const e=t/1e3,r=Math.floor(t/1e6);r!==this.lastLoggedTime&&(this.lastLoggedTime=r),this.opts.words.forEach((n,a)=>{const l=e>=n.from&&e<=n.to,h=e>n.to;let d;n.isKeyWord&&l?d=vt(this.opts.keyword):l?d=vt(this.opts.active):h&&this.opts.preserveKeywordColor&&n.isKeyWord?d=vt(this.opts.keyword):h?d=vt(this.opts.appeared):d=vt(this.opts.fill);const f=this.wordTexts[a];if(f){f.children.forEach(g=>{g.label!=="bgRect"&&(g.tint=d??16777215)});const m=f.getChildByLabel("bgRect");if(l)if(m){m.tint=16777215;const g=vt(this.opts.activeFill)||16753920;m.clear();const y=10,x=f.getLocalBounds();m.roundRect(x.x-y/2,x.y-y/2+this.extraPadding,x.width+y,x.height+y,16),m.fill(g)}else{const g=new pe;g.label="bgRect";const y=10,x=f.getLocalBounds(),o=10,c=vt(this.opts.activeFill)||16753920;g.roundRect(x.x-y/2,x.y-y/2+this.extraPadding,x.width+y,x.height+y,o),g.fill(c),g.tint=16777215,f.addChildAt(g,0)}else m&&f.removeChild(m)}else console.log(`¡WARNING: SplitBitmapText was not found for word "${n.text}"!`)})}async getTexture(){if(this.pixiTextContainer==null||this.renderTexture==null)return console.log("[CaptionClip] getTexture returning null - container or texture not ready"),null;try{return(await this.getRenderer()).render({container:this.pixiTextContainer,target:this.renderTexture}),this.renderTexture}catch(t){return console.error("[CaptionClip] Error in getTexture:",t),null}}setRenderer(t){this.externalRenderer=t}async getRenderer(){if(this.externalRenderer!=null)return this.externalRenderer;if(this.pixiApp?.renderer==null)throw new Error("CaptionClip: No renderer available. Provide a renderer via setRenderer().");return this.pixiApp.renderer}async tick(t){if(await this.ready,this.pixiTextContainer==null||this.renderTexture==null)throw new Error("CaptionClip not initialized");this.updateState(t);const e=await this.getRenderer();e.render({container:this.pixiTextContainer,target:this.renderTexture});const r=this.renderTexture.source?.resource?.source;let n;if(r instanceof HTMLCanvasElement)n=await createImageBitmap(r);else if(r instanceof OffscreenCanvas)n=await createImageBitmap(r);else{const l=e.extract.canvas(this.renderTexture);if(l instanceof HTMLCanvasElement||l instanceof OffscreenCanvas)n=await createImageBitmap(l);else throw new Error("Unable to extract canvas from render texture")}return{video:n,state:"success"}}async split(t){await this.ready;const e=await this.clone(),r=await this.clone();return[e,r]}async clone(){await this.ready;const t=this.originalOpts||{},e=new Be(this.text,t);return this.copyStateTo(e),e}destroy(){if(!this.destroyed){H.info("CaptionClip destroy");try{this.wordTexts.forEach(t=>{t!=null&&!t.destroyed&&t.destroy({children:!0})})}catch{}finally{this.wordTexts=[]}try{this.pixiTextContainer!=null&&this.pixiTextContainer.destroyed!==!0&&this.pixiTextContainer.destroy({children:!0})}catch{}finally{this.pixiTextContainer=null}try{this.renderTexture!=null&&this.renderTexture.destroyed!==!0&&this.renderTexture.destroy(!0)}catch{}finally{this.renderTexture=null}if(this.externalRenderer=null,this.pixiApp!=null)try{const t=this.pixiApp;t.destroyed!==!0&&t.renderer!=null&&this.pixiApp.destroy(!0,{children:!0,texture:!0})}catch{}finally{this.pixiApp=null}super.destroy()}}toJSON(t=!1){const e=super.toJSON(t),r={};if(this.originalOpts){const g=this.originalOpts;if(g.fontSize!==void 0&&(r.fontSize=g.fontSize),g.fontFamily!==void 0&&(r.fontFamily=g.fontFamily),g.fontWeight!==void 0&&(r.fontWeight=g.fontWeight),g.fontStyle!==void 0&&(r.fontStyle=g.fontStyle),g.fill!==void 0&&(r.color=g.fill),g.align!==void 0&&(r.align=g.align),g.fontUrl!==void 0&&(r.fontUrl=g.fontUrl),g.stroke&&(typeof g.stroke=="object"?r.stroke={color:g.stroke.color,width:g.stroke.width}:r.stroke={color:g.stroke,width:g.strokeWidth??0}),g.dropShadow){const y=g.dropShadow;r.shadow={color:y.color??"#000000",alpha:y.alpha??.5,blur:y.blur??4,offsetX:y.distance?Math.cos((y.angle??0)*Math.PI/180)*y.distance:0,offsetY:y.distance?Math.sin((y.angle??0)*Math.PI/180)*y.distance:0}}}const n={};this.opts.words&&this.opts.words.length>0&&(n.words=this.opts.words);const a={},l=this.originalOpts?.caption?.colors??this.originalOpts?.colors;l?.appeared!==void 0&&(a.appeared=l.appeared),l?.active!==void 0&&(a.active=l.active),l?.activeFill!==void 0&&(a.activeFill=l.activeFill),l?.background!==void 0&&(a.background=l.background),l?.keyword!==void 0&&(a.keyword=l.keyword);let h;this.originalOpts?.caption?.preserveKeywordColor!==void 0?h=this.originalOpts.caption.preserveKeywordColor:this.originalOpts?.preserveKeywordColor!==void 0&&(h=this.originalOpts.preserveKeywordColor),Object.keys(a).length>0&&(n.colors=a),h!==void 0&&(n.preserveKeywordColor=h);const d={};this.bottomOffset!==void 0&&(d.bottomOffset=this.bottomOffset);const f=this.originalOpts?.caption?.positioning?.videoWidth??this.originalOpts?.videoWidth,m=this.originalOpts?.caption?.positioning?.videoHeight??this.originalOpts?.videoHeight;return f!==void 0&&(d.videoWidth=f),m!==void 0&&(d.videoHeight=m),Object.keys(d).length>0&&(n.positioning=d),{...e,type:"Caption",text:this.text,style:r,caption:Object.keys(n).length>0?n:void 0}}static async fromObject(t){if(t.type!=="Caption")throw new Error(`Expected Caption, got ${t.type}`);const e=t.text||"",r=t.style||{},n={};if(r.fontSize!==void 0&&(n.fontSize=r.fontSize),r.fontFamily!==void 0&&(n.fontFamily=r.fontFamily),r.fontWeight!==void 0&&(n.fontWeight=r.fontWeight),r.fontStyle!==void 0&&(n.fontStyle=r.fontStyle),r.color!==void 0&&(n.fill=r.color),r.align!==void 0&&(n.align=r.align),r.fontUrl!==void 0?n.fontUrl=r.fontUrl:t.fontUrl!==void 0&&(n.fontUrl=t.fontUrl),r.stroke&&(n.stroke=r.stroke.color,n.strokeWidth=r.stroke.width),r.shadow){const l=Math.sqrt(r.shadow.offsetX**2+r.shadow.offsetY**2),h=Math.atan2(r.shadow.offsetY,r.shadow.offsetX)*180/Math.PI;n.dropShadow={color:r.shadow.color,alpha:r.shadow.alpha,blur:r.shadow.blur,distance:l,angle:h}}t.caption?n.caption=t.caption:(t.bottomOffset!==void 0&&(n.bottomOffset=t.bottomOffset),t.words!==void 0&&(n.words=t.words),(t.appearedColor!==void 0||t.activeColor!==void 0||t.activeFillColor!==void 0||t.backgroundColor!==void 0||t.isKeyWordColor!==void 0)&&(n.colors={},t.appearedColor!==void 0&&(n.colors.appeared=t.appearedColor),t.activeColor!==void 0&&(n.colors.active=t.activeColor),t.activeFillColor!==void 0&&(n.colors.activeFill=t.activeFillColor),t.backgroundColor!==void 0&&(n.colors.background=t.backgroundColor),t.isKeyWordColor!==void 0&&(n.colors.keyword=t.isKeyWordColor)),t.preservedColorKeyWord!==void 0&&(n.preserveKeywordColor=t.preservedColorKeyWord),t.videoWidth!==void 0&&(n.videoWidth=t.videoWidth),t.videoHeight!==void 0&&(n.videoHeight=t.videoHeight));const a=new Be(e,n);return a.left=t.left,a.top=t.top,a.width=t.width,a.height=t.height,a.angle=t.angle,a.display.from=t.display.from,a.display.to=t.display.to,a.duration=t.duration,a.playbackRate=t.playbackRate,a.zIndex=t.zIndex,a.opacity=t.opacity,a.flip=t.flip,t.animation&&a.setAnimation(t.animation.keyFrames,t.animation.opts),await a.ready,a}}class Dt extends li{ready;_meta={duration:0,width:0,height:0};get meta(){return{...this._meta}}img=null;pixiTexture=null;frames=[];static async fromUrl(t,e){const r=await Oi.load(t),n=r.source?.resource?.source;let a;try{if(n instanceof HTMLCanvasElement||n instanceof OffscreenCanvas)a=await createImageBitmap(n);else if(n instanceof HTMLImageElement){const h=new OffscreenCanvas(n.width,n.height),d=h.getContext("2d");if(d==null)throw new Error("Failed to create 2d context");d.drawImage(n,0,0),a=await createImageBitmap(h)}else if(n instanceof ImageBitmap)a=await createImageBitmap(n);else{const h=await fetch(t);if(!h.ok)throw new Error(`Failed to fetch image: ${h.status} ${h.statusText}`);const d=await h.blob();a=await createImageBitmap(d)}}catch{const d=await fetch(t);if(!d.ok)throw new Error(`Failed to fetch image: ${d.status} ${d.statusText}`);const f=await d.blob();a=await createImageBitmap(f)}const l=new Dt(a,e||t);return l.pixiTexture=r,l}getTexture(){return this.pixiTexture}constructor(t,e){super(),this.src=e!==void 0?e:"";const r=n=>{this.img=n,this._meta.width=n.width,this._meta.height=n.height,this._meta.duration=1/0;const a={...this._meta};return this.width=this.width===0?a.width:this.width,this.height=this.height===0?a.height:this.height,this.duration===0&&a.duration!==1/0&&(this.duration=a.duration,this.display.to=this.display.from+this.duration),a};if(t instanceof ReadableStream)this.ready=new Response(t).blob().then(n=>createImageBitmap(n)).then(r);else if(t instanceof ImageBitmap)this.ready=Promise.resolve(r(t));else if(Array.isArray(t)&&t.every(n=>n instanceof VideoFrame)){this.frames=t;const n=this.frames[0];if(n==null)throw Error("The frame count must be greater than 0");this._meta={width:n.displayWidth,height:n.displayHeight,duration:this.frames.reduce((l,h)=>l+(h.duration??0),0)};const a={...this._meta,duration:1/0};this.width=this.width===0?a.width:this.width,this.height=this.height===0?a.height:this.height,this.duration===0&&a.duration!==1/0&&(this.duration=a.duration,this.display.to=this.display.from+this.duration),this.ready=Promise.resolve(a)}else if("type"in t)this.ready=this.initAnimateImg(t.stream,t.type).then(()=>{const n={width:this._meta.width,height:this._meta.height,duration:1/0};return this.width=this.width===0?n.width:this.width,this.height=this.height===0?n.height:this.height,this.duration===0&&n.duration!==1/0&&(this.duration=n.duration,this.display.to=this.display.from+this.duration),n});else throw Error("Illegal arguments")}async initAnimateImg(t,e){this.frames=await _f(t,e);const r=this.frames[0];if(r==null)throw Error("No frame available in gif");this._meta={duration:this.frames.reduce((n,a)=>n+(a.duration??0),0),width:r.codedWidth,height:r.codedHeight},H.info("ImageClip ready:",this._meta)}tickInterceptor=async(t,e)=>e;async tick(t){if(this.img!=null)return await this.tickInterceptor(t,{video:await createImageBitmap(this.img),state:"success"});const e=t%this._meta.duration;return await this.tickInterceptor(t,{video:(this.frames.find(r=>e>=r.timestamp&&e<=r.timestamp+(r.duration??0))??this.frames[0]).clone(),state:"success"})}async split(t){if(await this.ready,this.img!=null)return[new Dt(await createImageBitmap(this.img),this.src),new Dt(await createImageBitmap(this.img),this.src)];let e=-1;for(let a=0;a<this.frames.length;a++){const l=this.frames[a];if(!(t>l.timestamp)){e=a;break}}if(e===-1)throw Error("Not found frame by time");const r=this.frames.slice(0,e).map(a=>new VideoFrame(a)),n=this.frames.slice(e).map(a=>new VideoFrame(a,{timestamp:a.timestamp-t}));return[new Dt(r,this.src),new Dt(n,this.src)]}async clone(){await this.ready;const t=this.img==null?this.frames.map(r=>r.clone()):await createImageBitmap(this.img),e=new Dt(t,this.src);return e.tickInterceptor=this.tickInterceptor,this.copyStateTo(e),e}destroy(){H.info("ImageClip destroy"),this.img?.close(),this.frames.forEach(t=>t.close()),this.pixiTexture=null,super.destroy()}toJSON(t=!1){return{...super.toJSON(t),type:"Image"}}static async fromObject(t){if(t.type!=="Image")throw new Error(`Expected Image, got ${t.type}`);if(!t.src||t.src.trim()==="")throw new Error("ImageClip requires a valid source URL. Generated clips (like text-to-image) cannot be loaded from JSON without their source data.");let e;try{const r=await fetch(t.src);if(!r.ok)throw new Error(`Failed to fetch image from ${t.src}: ${r.status} ${r.statusText}. Make sure the file exists in the public directory.`);const n=await r.blob();if(!n.type.startsWith("image/"))throw new Error(`Invalid image format: ${n.type}. Expected an image file.`);e=new Dt(await createImageBitmap(n),t.src)}catch(r){throw r instanceof Error&&r.message.includes("could not be decoded")?new Error(`Failed to decode image from ${t.src}. The image may be corrupted, in an unsupported format, or there may be CORS issues.`):r}return await e.ready,e.left=t.left,e.top=t.top,e.width=t.width,e.height=t.height,e.angle=t.angle,e.display.from=t.display.from,e.display.to=t.display.to,e.duration=t.duration,e.playbackRate=t.playbackRate,e.zIndex=t.zIndex,e.opacity=t.opacity,e.flip=t.flip,t.animation&&e.setAnimation(t.animation.keyFrames,t.animation.opts),e}async scaleToFit(t,e){await this.ready;const{width:r,height:n}=this.meta;if(r===0||n===0)return;const a=Math.min(t/r,e/n);this.width=r*a,this.height=n*a}async scaleToFill(t,e){await this.ready;const{width:r,height:n}=this.meta;if(r===0||n===0)return;const a=Math.max(t/r,e/n);this.width=r*a,this.height=n*a}centerInScene(t,e){this.left=(t-this.width)/2,this.top=(e-this.height)/2}}function oa(s,t){const e=t.videoTracks[0],r={};if(e!=null){const a=Wb(s.getTrackById(e.id))?.buffer,{descKey:l,type:h}=e.codec.startsWith("avc1")?{descKey:"avcDecoderConfigRecord",type:"avc1"}:e.codec.startsWith("hvc1")?{descKey:"hevcDecoderConfigRecord",type:"hvc1"}:{descKey:"",type:""};l!==""&&(r.videoTrackConf={timescale:e.timescale,duration:e.duration,width:e.video.width,height:e.video.height,brands:t.brands,type:h,[l]:a}),r.videoDecoderConf={codec:e.codec,codedHeight:e.video.height,codedWidth:e.video.width,description:a}}const n=t.audioTracks[0];if(n!=null){const a=Vb(s),l=a==null?{}:Yb(a);r.audioTrackConf={timescale:n.timescale,samplerate:l.sampleRate??n.audio.sample_rate,channel_count:l.numberOfChannels??n.audio.channel_count,hdlr:"soun",type:n.codec.startsWith("mp4a")?"mp4a":n.codec,description:a},r.audioDecoderConf={codec:l.codec??tt.codec,numberOfChannels:l.numberOfChannels??n.audio.channel_count,sampleRate:l.sampleRate??n.audio.sample_rate}}return r}function Wb(s){for(const t of s.mdia.minf.stbl.stsd.entries){const e=t.avcC??t.hvcC??t.av1C??t.vpcC;if(e!=null){const r=new yt.DataStream(void 0,0,yt.DataStream.BIG_ENDIAN);return e.write(r),new Uint8Array(r.buffer.slice(8))}}}function Vb(s,t="mp4a"){return s.moov?.traks.map(r=>r.mdia.minf.stbl.stsd.entries).flat().find(({type:r})=>r===t)?.esds}function Yb(s){let t="mp4a";const e=s.esd.descs[0];if(e==null)return{};t+="."+e.oti.toString(16);const r=e.descs[0];if(r==null)return t.endsWith("40")&&(t+=".2"),{codec:t};const n=(r.data[0]&248)>>3;t+="."+n;const[a,l]=r.data,h=((a&7)<<1)+(l>>7),d=(l&127)>>3;return{codec:t,sampleRate:[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350][h],numberOfChannels:d}}async function Xb(s,t,e){const r=yt.createFile(!1);r.onReady=a=>{t({mp4boxFile:r,info:a});const l=a.videoTracks[0]?.id;l!=null&&r.setExtractionOptions(l,"video",{nbSamples:100});const h=a.audioTracks[0]?.id;h!=null&&r.setExtractionOptions(h,"audio",{nbSamples:100}),r.start()},r.onSamples=e,await n();async function n(){let a=0;const l=30*1024*1024;for(;;){const h=await s.read(l,{at:a});if(h.byteLength===0)break;h.fileStart=a;const d=r.appendBuffer(h);if(d==null)break;a=d}r.stop()}}function $b(s){if(s?.length!==9)return{};const t=new Int32Array(s.buffer),e=t[0]/65536,r=t[1]/65536,n=t[3]/65536,a=t[4]/65536,l=t[6]/65536,h=t[7]/65536,d=t[8]/(1<<30),f=Math.sqrt(e*e+n*n),m=Math.sqrt(r*r+a*a),g=Math.atan2(n,e),y=g*180/Math.PI;return{scaleX:f,scaleY:m,rotationRad:g,rotationDeg:y,translateX:l,translateY:h,perspective:d}}function Kb(s,t,e){const r=(Math.round(e/90)*90+360)%360;if(r===0)return d=>d;const n=r===90||r===270?t:s,a=r===90||r===270?s:t,l=new OffscreenCanvas(n,a),h=l.getContext("2d");return h.translate(n/2,a/2),h.rotate(-r*Math.PI/180),h.translate(-s/2,-t/2),d=>{if(d==null)return null;h.drawImage(d,0,0);const f=new VideoFrame(l,{timestamp:d.timestamp,duration:d.duration??void 0});return d.close(),f}}let ha=0;function la(s){return s.kind==="file"&&s.createReader instanceof Function}class _t extends li{insId=ha++;logger=H.create(`VideoClip id:${this.insId},`);ready;_meta={duration:0,width:0,height:0,audioSampleRate:0,audioChanCount:0};get meta(){return{...this._meta}}localFile;headerBoxPos=[];async getFileHeaderBinData(){await this.ready;const t=await this.localFile.getOriginFile();if(t==null)throw Error("VideoClip localFile is not origin file");return await new Blob(this.headerBoxPos.map(({start:e,size:r})=>t.slice(e,e+r))).arrayBuffer()}parsedMatrix={perspective:1,rotationRad:0,rotationDeg:0,scaleX:1,scaleY:1,translateX:0,translateY:0};vfRotater=t=>t;volume=1;videoSamples=[];audioSamples=[];videoFrameFinder=null;audioFrameFinder=null;decoderConf={video:null,audio:null};opts={audio:!0};audio=!0;static async fromUrl(t,e={}){const r=await fetch(t);if(!r.ok)throw new Error(`Failed to fetch video from ${t}: ${r.status} ${r.statusText}`);const n=new _t(r.body,{},t);return await n.ready,e.x!==void 0&&(n.left=e.x),e.y!==void 0&&(n.top=e.y),e.width!==void 0&&(n.width=e.width),e.height!==void 0&&(n.height=e.height),n}constructor(t,e={},r){if(super(),this.src=r!==void 0?r:"",!(t instanceof ReadableStream)&&!la(t)&&!Array.isArray(t.videoSamples))throw Error("Illegal argument");this.opts={audio:!0,...e},this.audio=typeof this.opts.audio=="boolean"?this.opts.audio:!0,this.volume=typeof e.audio=="object"&&"volume"in e.audio?e.audio.volume:1;const n=async a=>(await ni(this.localFile,a),this.localFile);this.localFile=la(t)?t:"localFile"in t?t.localFile:rs(),this.ready=(t instanceof ReadableStream?n(t).then(a=>Mu(a,this.opts)):la(t)?Mu(t,this.opts):Promise.resolve(t)).then(async({videoSamples:a,audioSamples:l,decoderConf:h,headerBoxPos:d,parsedMatrix:f})=>{this.videoSamples=a,this.audioSamples=l,this.decoderConf=h,this.headerBoxPos=d,this.parsedMatrix=f;const{videoFrameFinder:m,audioFrameFinder:g}=qb({video:h.video==null?null:{...h.video,hardwareAcceleration:this.opts.__unsafe_hardwareAcceleration__},audio:h.audio},await this.localFile.createReader(),a,l,this.opts.audio!==!1?this.volume:0);this.videoFrameFinder=m,this.audioFrameFinder=g;const{codedWidth:y,codedHeight:x}=h.video??{};y&&x&&(this.vfRotater=Kb(y,x,f.rotationDeg)),this._meta=jb(h,a,l,f.rotationDeg),this.logger.info("VideoClip meta:",this._meta);const o={...this._meta};return this.width=this.width===0?o.width:this.width,this.height=this.height===0?o.height:this.height,this.duration=this.duration===0?o.duration:this.duration,this.display.to=this.display.from+this.duration,o})}tickInterceptor=async(t,e)=>e;async tick(t){if(t>=this._meta.duration)return await this.tickInterceptor(t,{audio:await this.audioFrameFinder?.find(t)??[],state:"done"});const[e,r]=await Promise.all([this.audioFrameFinder?.find(t)??[],this.videoFrameFinder?.find(t).then(this.vfRotater)]);return r==null?await this.tickInterceptor(t,{audio:e,state:"success"}):await this.tickInterceptor(t,{video:r,audio:e,state:"success"})}async split(t){if(await this.ready,t<=0||t>=this._meta.duration)throw Error('"time" out of bounds');const[e,r]=rv(this.videoSamples,t),[n,a]=sv(this.audioSamples,t),l=new _t({localFile:this.localFile,videoSamples:e??[],audioSamples:n??[],decoderConf:this.decoderConf,headerBoxPos:this.headerBoxPos,parsedMatrix:this.parsedMatrix},this.opts,this.src),h=new _t({localFile:this.localFile,videoSamples:r??[],audioSamples:a??[],decoderConf:this.decoderConf,headerBoxPos:this.headerBoxPos,parsedMatrix:this.parsedMatrix},this.opts,this.src);return await Promise.all([l.ready,h.ready]),[l,h]}async clone(){await this.ready;const t=new _t({localFile:this.localFile,videoSamples:[...this.videoSamples],audioSamples:[...this.audioSamples],decoderConf:this.decoderConf,headerBoxPos:this.headerBoxPos,parsedMatrix:this.parsedMatrix},this.opts,this.src);return await t.ready,t.tickInterceptor=this.tickInterceptor,this.copyStateTo(t),t}async splitTrack(){await this.ready;const t=[];if(this.videoSamples.length>0){const e=new _t({localFile:this.localFile,videoSamples:[...this.videoSamples],audioSamples:[],decoderConf:{video:this.decoderConf.video,audio:null},headerBoxPos:this.headerBoxPos,parsedMatrix:this.parsedMatrix},this.opts,this.src);await e.ready,e.tickInterceptor=this.tickInterceptor,t.push(e)}if(this.audioSamples.length>0){const e=new _t({localFile:this.localFile,videoSamples:[],audioSamples:[...this.audioSamples],decoderConf:{audio:this.decoderConf.audio,video:null},headerBoxPos:this.headerBoxPos,parsedMatrix:this.parsedMatrix},this.opts,this.src);await e.ready,e.tickInterceptor=this.tickInterceptor,t.push(e)}return t}destroy(){this.destroyed||(this.destroyed=!0,this.logger.info("VideoClip destroy"),super.destroy(),this.videoFrameFinder?.destroy(),this.audioFrameFinder?.destroy())}toJSON(t=!1){return{...super.toJSON(t),type:"Video",audio:this.audio}}static async fromObject(t){if(t.type!=="Video")throw new Error(`Expected Video, got ${t.type}`);const e=await fetch(t.src);if(!e.ok)throw new Error(`Failed to fetch video from ${t.src}: ${e.status} ${e.statusText}. Make sure the file exists in the public directory.`);const r=t.audio!==void 0?{audio:t.audio}:{},n=new _t(e.body,r,t.src);return await n.ready,n.left=t.left,n.top=t.top,n.width=t.width,n.height=t.height,n.angle=t.angle,n.display.from=t.display.from,n.display.to=t.display.to,n.duration=t.duration,n.playbackRate=t.playbackRate,n.zIndex=t.zIndex,n.opacity=t.opacity,n.flip=t.flip,t.animation&&n.setAnimation(t.animation.keyFrames,t.animation.opts),n}async createPlaybackElement(){await this.ready;const e=this.localFile;if(!e||typeof e.getOriginFile!="function")throw new Error("VideoClip does not have a local file for playback");const r=await e.getOriginFile();if(!r)throw new Error("Failed to get origin file from VideoClip");const n=URL.createObjectURL(r),a=document.createElement("video");return a.crossOrigin="anonymous",a.muted=!0,a.autoplay=!1,a.playsInline=!0,a.preload="auto",a.loop=!1,a.src=n,await new Promise((l,h)=>{const d=()=>{a.removeEventListener("loadeddata",d),a.removeEventListener("error",f),a.pause(),a.currentTime=0,l()},f=()=>{a.removeEventListener("loadeddata",d),a.removeEventListener("error",f),h(new Error("Failed to load video"))};a.addEventListener("loadeddata",d,{once:!0}),a.addEventListener("error",f,{once:!0}),a.load()}),{element:a,objectUrl:n}}async play(t,e){const r=t;if(Math.abs(r.currentTime-e)>.1&&(r.currentTime=e),r.muted=!1,r.paused)try{await r.play()}catch{try{await r.play()}catch(a){console.warn("Failed to play video:",a)}}}pause(t){const e=t;e.pause(),e.muted=!0}async seek(t,e){const r=t;return r.pause(),r.currentTime=e,new Promise(n=>{if(Math.abs(r.currentTime-e)<.01){n();return}const a=()=>{r.removeEventListener("seeked",a),n()};r.addEventListener("seeked",a,{once:!0}),setTimeout(()=>{r.removeEventListener("seeked",a),n()},500)})}syncPlayback(t,e,r){const n=t,a=this.meta.duration/1e6,l=r>=0&&r<a;e&&l?n.paused?this.play(n,r).catch(console.warn):(n.muted&&(n.muted=!1),n.ended&&(n.currentTime=r,n.play().catch(console.warn))):(n.paused||n.pause(),n.muted=!0,l&&Math.abs(n.currentTime-r)>.1&&(n.currentTime=r))}cleanupPlayback(t,e){const r=t;r.pause(),r.removeAttribute("src"),r.load(),e&&URL.revokeObjectURL(e)}async scaleToFit(t,e){await this.ready;const{width:r,height:n}=this.meta;if(r===0||n===0)return;const a=Math.min(t/r,e/n);this.width=r*a,this.height=n*a}async scaleToFill(t,e){await this.ready;const{width:r,height:n}=this.meta;if(r===0||n===0)return;const a=Math.max(t/r,e/n);this.width=r*a,this.height=n*a}centerInScene(t,e){this.left=(t-this.width)/2,this.top=(e-this.height)/2}}function jb(s,t,e,r){const n={duration:0,width:0,height:0,audioSampleRate:0,audioChanCount:0};if(s.video!=null&&t.length>0){n.width=s.video.codedWidth??0,n.height=s.video.codedHeight??0;const h=(Math.round(r/90)*90+360)%360;(h===90||h===270)&&([n.width,n.height]=[n.height,n.width])}s.audio!=null&&e.length>0&&(n.audioSampleRate=tt.sampleRate,n.audioChanCount=tt.channelCount);let a=0,l=0;if(t.length>0)for(let h=t.length-1;h>=0;h--){const d=t[h];if(!d.deleted){a=d.cts+d.duration;break}}if(e.length>0){const h=e.at(-1);l=h.cts+h.duration}return n.duration=Math.max(a,l),n}function qb(s,t,e,r,n){return{audioFrameFinder:n===0||s.audio==null||r.length===0?null:new Jb(t,r,s.audio,{volume:n,targetSampleRate:tt.sampleRate}),videoFrameFinder:s.video==null||e.length===0?null:new Zb(t,e,s.video)}}async function Mu(s,t={}){let e=null;const r={video:null,audio:null};let n=[],a=[],l=[];const h={perspective:1,rotationRad:0,rotationDeg:0,scaleX:1,scaleY:1,translateX:0,translateY:0};let d=-1,f=-1;const m=await s.createReader();await Xb(m,async y=>{e=y.info;const x=y.mp4boxFile.ftyp;l.push({start:x.start,size:x.size});const o=y.mp4boxFile.moov;l.push({start:o.start,size:o.size}),Object.assign(h,$b(e.videoTracks[0]?.matrix));let{videoDecoderConf:c,audioDecoderConf:u}=oa(y.mp4boxFile,y.info);if(r.video=c??null,r.audio=u??null,c==null&&u==null&&H.error("VideoClip no video and audio track"),u!=null){const{supported:p}=await AudioDecoder.isConfigSupported(u);p||H.error(`VideoClip audio codec is not supported: ${u.codec}`)}if(c!=null){const{supported:p}=await VideoDecoder.isConfigSupported(c);p||H.error(`VideoClip video codec is not supported: ${c.codec}`)}H.info("mp4BoxFile moov ready",{...y.info,tracks:null,videoTracks:null,audioTracks:null},r)},(y,x,o)=>{if(x==="video"){d===-1&&(d=o[0].dts);for(const c of o)n.push(ku(c,d,"video"))}else if(x==="audio"&&t.audio){f===-1&&(f=o[0].dts);for(const c of o)a.push(ku(c,f,"audio"))}}),await m.close();const g=n.at(-1)??a.at(-1);if(e==null)throw Error("VideoClip stream is done, but not emit ready");if(g==null)throw Error("VideoClip stream not contain any sample");return ca(n),H.info("mp4 stream parsed"),{videoSamples:n,audioSamples:a,decoderConf:r,headerBoxPos:l,parsedMatrix:h}}function ku(s,t=0,e){let r=s.offset;const n=e==="video"&&s.is_sync?av(s.data,s.description.type):-1;let a=s.size;return n>0&&(r+=n,a-=n),{...s,is_idr:n>=0,offset:r,size:a,cts:(s.cts-t)/s.timescale*1e6,dts:(s.dts-t)/s.timescale*1e6,duration:s.duration/s.timescale*1e6,timescale:1e6,data:e==="video"?null:s.data}}class Zb{constructor(t,e,r){this.localFileReader=t,this.samples=e,this.conf=r}decoder=null;timestamp=0;curAborter={abort:!1,st:performance.now()};find=async t=>{(this.decoder==null||this.decoder.state==="closed"||t<=this.timestamp||t-this.timestamp>3e6)&&this.reset(t),this.curAborter.abort=!0,this.timestamp=t,this.curAborter={abort:!1,st:performance.now()};const e=await this.parseFrame(t,this.decoder,this.curAborter);return this.sleepCnt=0,e};lastVfDur=0;downgradeSoftDecode=!1;videoDecCursorIdx=0;videoFrames=[];outputFrameCnt=0;inputChunkCnt=0;sleepCnt=0;predecodeErr=!1;parseFrame=async(t,e,r)=>{if(e==null||e.state==="closed"||r.abort)return null;if(this.videoFrames.length>0){const n=this.videoFrames[0];return t<n.timestamp?null:(this.videoFrames.shift(),t>n.timestamp+(n.duration??0)?(n.close(),await this.parseFrame(t,e,r)):(!this.predecodeErr&&this.videoFrames.length<10&&this.startDecode(e).catch(a=>{throw this.predecodeErr=!0,this.reset(t),a}),n))}if(this.decoding||this.outputFrameCnt<this.inputChunkCnt&&e.decodeQueueSize>0){if(performance.now()-r.st>6e3)throw Error(`VideoClip.tick video timeout, ${JSON.stringify(this.getState())}`);this.sleepCnt+=1,await cs(15)}else{if(this.videoDecCursorIdx>=this.samples.length)return null;try{await this.startDecode(e)}catch(n){throw this.reset(t),n}}return await this.parseFrame(t,e,r)};decoding=!1;startDecode=async t=>{if(this.decoding||t.decodeQueueSize>600)return;let e=this.videoDecCursorIdx+1;if(e>this.samples.length)return;this.decoding=!0;let r=!1;for(;e<this.samples.length;e++){const n=this.samples[e];if(!r&&!n.deleted&&(r=!0),n.is_idr)break}if(r){const n=this.samples.slice(this.videoDecCursorIdx,e);if(n[0]?.is_idr!==!0)H.warn("First sample not idr frame");else{const a=performance.now(),l=await iv(n,this.localFileReader),h=performance.now()-a;if(h>1e3){const d=n[0],f=n.at(-1),m=f.offset+f.size-d.offset;H.warn(`Read video samples time cost: ${Math.round(h)}ms, file chunk size: ${m}`)}if(t.state==="closed")return;this.lastVfDur=l[0]?.duration??0,nv(t,l,{onDecodingError:d=>{if(this.downgradeSoftDecode)throw d;this.outputFrameCnt===0&&(this.downgradeSoftDecode=!0,H.warn("Downgrade to software decode"),this.reset())}}),this.inputChunkCnt+=l.length}}this.videoDecCursorIdx=e,this.decoding=!1};reset=t=>{if(this.decoding=!1,this.videoFrames.forEach(r=>r.close()),this.videoFrames=[],t==null||t===0)this.videoDecCursorIdx=0;else{let r=0;for(let n=0;n<this.samples.length;n++){const a=this.samples[n];if(a.is_idr&&(r=n),!(a.cts<t)){this.videoDecCursorIdx=r;break}}}this.inputChunkCnt=0,this.outputFrameCnt=0,this.decoder?.state!=="closed"&&this.decoder?.close();const e={...this.conf,...this.downgradeSoftDecode?{hardwareAcceleration:"prefer-software"}:{}};this.decoder=new VideoDecoder({output:r=>{if(this.outputFrameCnt+=1,r.timestamp===-1){r.close();return}let n=r;r.duration==null&&(n=new VideoFrame(r,{duration:this.lastVfDur}),r.close()),this.videoFrames.push(n)},error:r=>{if(r.message.includes("Codec reclaimed due to inactivity")){this.decoder=null,H.warn(r.message);return}const n=`VideoFinder VideoDecoder err: ${r.message}, config: ${JSON.stringify(e)}, state: ${JSON.stringify(this.getState())}`;throw H.error(n),Error(n)}}),this.decoder.configure(e)};getState=()=>({time:this.timestamp,decState:this.decoder?.state,decQSize:this.decoder?.decodeQueueSize,decCursorIdx:this.videoDecCursorIdx,sampleLen:this.samples.length,inputCnt:this.inputChunkCnt,outputCnt:this.outputFrameCnt,cacheFrameLen:this.videoFrames.length,softDecode:this.downgradeSoftDecode,clipIdCnt:ha,sleepCnt:this.sleepCnt,memInfo:Iu()});destroy=()=>{this.decoder?.state!=="closed"&&this.decoder?.close(),this.decoder=null,this.curAborter.abort=!0,this.videoFrames.forEach(t=>t.close()),this.videoFrames=[],this.localFileReader.close()}}function Qb(s,t){for(let e=0;e<t.length;e++){const r=t[e];if(s>=r.cts&&s<r.cts+r.duration)return e;if(r.cts>s)break}return 0}class Jb{constructor(t,e,r,n){this.localFileReader=t,this.samples=e,this.conf=r,this.volume=n.volume,this.sampleRate=n.targetSampleRate}volume=1;sampleRate;decoder=null;curAborter={abort:!1,st:performance.now()};find=async t=>{const e=t<=this.timestamp||t-this.timestamp>1e5;(this.decoder==null||this.decoder.state==="closed"||e)&&this.reset(),e&&(this.timestamp=t,this.decCursorIdx=Qb(t,this.samples)),this.curAborter.abort=!0;const r=t-this.timestamp;this.timestamp=t,this.curAborter={abort:!1,st:performance.now()};const n=await this.parseFrame(Math.ceil(r*(this.sampleRate/1e6)),this.decoder,this.curAborter);return this.sleepCnt=0,n};timestamp=0;decCursorIdx=0;pcmData={frameCnt:0,data:[]};sleepCnt=0;parseFrame=async(t,e=null,r)=>{if(e==null||r.abort||e.state==="closed"||t===0)return[];const n=this.pcmData.frameCnt-t;if(n>0)return n<tt.sampleRate/10&&this.startDecode(e),Ru(this.pcmData,t);if(e.decoding){if(performance.now()-r.st>3e3)throw r.abort=!0,Error(`VideoClip.tick audio timeout, ${JSON.stringify(this.getState())}`);this.sleepCnt+=1,await cs(15)}else{if(this.decCursorIdx>=this.samples.length-1)return Ru(this.pcmData,this.pcmData.frameCnt);this.startDecode(e)}return this.parseFrame(t,e,r)};startDecode=t=>{if(t.decodeQueueSize>10)return;const r=[];let n=this.decCursorIdx;for(;n<this.samples.length;){const a=this.samples[n];if(n+=1,!a.deleted&&(r.push(a),r.length>=10))break}this.decCursorIdx=n,t.decode(r.map(a=>new EncodedAudioChunk({type:"key",timestamp:a.cts,duration:a.duration,data:a.data})))};reset=()=>{this.timestamp=0,this.decCursorIdx=0,this.pcmData={frameCnt:0,data:[]},this.decoder?.close(),this.decoder=tv(this.conf,{resampleRate:tt.sampleRate,volume:this.volume},t=>{this.pcmData.data.push(t),this.pcmData.frameCnt+=t[0].length})};getState=()=>({time:this.timestamp,decState:this.decoder?.state,decQSize:this.decoder?.decodeQueueSize,decCursorIdx:this.decCursorIdx,sampleLen:this.samples.length,pcmLen:this.pcmData.frameCnt,clipIdCnt:ha,sleepCnt:this.sleepCnt,memInfo:Iu()});destroy=()=>{this.decoder=null,this.curAborter.abort=!0,this.pcmData={frameCnt:0,data:[]},this.localFileReader.close()}}function tv(s,t,e){let r=0,n=0;const a=m=>{if(n+=1,m.length!==0){if(t.volume!==1)for(const g of m)for(let y=0;y<g.length;y++)g[y]*=t.volume;m.length===1&&(m=[m[0],m[0]]),e(m)}},l=ev(a),h=t.resampleRate!==s.sampleRate;let d=new AudioDecoder({output:m=>{const g=La(m);h?l(()=>tf(g,m.sampleRate,{rate:t.resampleRate,chanCount:m.numberOfChannels})):a(g),m.close()},error:m=>{m.message.includes("Codec reclaimed due to inactivity")||f("VideoClip AudioDecoder err",m)}});d.configure(s);function f(m,g){const y=`${m}: ${g.message}, state: ${JSON.stringify({qSize:d.decodeQueueSize,state:d.state,inputCnt:r,outputCnt:n})}`;throw H.error(y),Error(y)}return{decode(m){r+=m.length;try{for(const g of m)d.decode(g)}catch(g){f("decode audio chunk error",g)}},close(){d.state!=="closed"&&d.close()},get decoding(){return r>n&&d.decodeQueueSize>0},get state(){return d.state},get decodeQueueSize(){return d.decodeQueueSize}}}function ev(s){const t=[];let e=0;function r(l,h){t[h]=l,n()}function n(){const l=t[e];l!=null&&(s(l),e+=1,n())}let a=0;return l=>{const h=a;a+=1,l().then(d=>r(d,h)).catch(d=>r(d,h))}}function Ru(s,t){const e=[new Float32Array(t),new Float32Array(t)];let r=0,n=0;for(;n<s.data.length;){const[a,l]=s.data[n];if(r+a.length>t){const h=t-r;e[0].set(a.subarray(0,h),r),e[1].set(l.subarray(0,h),r),s.data[n][0]=a.subarray(h,a.length),s.data[n][1]=l.subarray(h,l.length);break}else e[0].set(a,r),e[1].set(l,r),r+=a.length,n++}return s.data=s.data.slice(n),s.frameCnt-=t,e}async function iv(s,t){const e=s[0],r=s.at(-1);if(r==null)return[];const n=r.offset+r.size-e.offset;if(n<3e7){const a=new Uint8Array(await t.read(n,{at:e.offset}));return s.map(l=>{const h=l.offset-e.offset;return new EncodedVideoChunk({type:l.is_sync?"key":"delta",timestamp:l.cts,duration:l.duration,data:a.subarray(h,h+l.size)})})}return await Promise.all(s.map(async a=>new EncodedVideoChunk({type:a.is_sync?"key":"delta",timestamp:a.cts,duration:a.duration,data:await t.read(a.size,{at:a.offset})})))}function rv(s,t){if(s.length===0)return[];let e=0,r=0,n=-1;for(let d=0;d<s.length;d++){const f=s[d];if(n===-1&&t<f.cts&&(n=d-1),f.is_idr)if(n===-1)e=d;else{r=d;break}}const a=s[n];if(a==null)throw Error("Not found video sample by time");const l=s.slice(0,r===0?s.length:r).map(d=>({...d}));for(let d=e;d<l.length;d++){const f=l[d];t<f.cts&&(f.deleted=!0,f.cts=-1)}ca(l);const h=s.slice(a.is_idr?n:e).map(d=>({...d,cts:d.cts-t}));for(const d of h)d.cts<0&&(d.deleted=!0,d.cts=-1);return ca(h),[l,h]}function sv(s,t){if(s.length===0)return[];let e=-1;for(let a=0;a<s.length;a++){const l=s[a];if(!(t>l.cts)){e=a;break}}if(e===-1)throw Error("Not found audio sample by time");const r=s.slice(0,e).map(a=>({...a})),n=s.slice(e).map(a=>({...a,cts:a.cts-t}));return[r,n]}function nv(s,t,e){if(s.state==="configured"){for(let r=0;r<t.length;r++)s.decode(t[r]);s.flush().catch(r=>{if(!(r instanceof Error))throw r;if(r.message.includes("Decoding error")&&e.onDecodingError!=null){e.onDecodingError(r);return}if(!r.message.includes("Aborted due to close"))throw r})}}function av(s,t){if(t!=="avc1"&&t!=="hvc1")return 0;const e=new DataView(s.buffer);for(let r=0;r<s.byteLength-4;){if(t==="avc1"){const n=e.getUint8(r+4)&31;if(n===5||n===7||n===8)return r}else if(t==="hvc1"){const n=e.getUint8(r+4)>>1&63;if(n===19||n===20||n===32||n===33||n===34)return r}r+=e.getUint32(r)+4}return-1}function ca(s){let t=0,e=null;for(const r of s)if(!r.deleted){if(r.is_sync&&(t+=1),t>=2)break;(e==null||r.cts<e.cts)&&(e=r)}e!=null&&e.cts<2e5&&(e.duration+=e.cts,e.cts=0)}function Iu(){try{const s=performance.memory;return{jsHeapSizeLimit:s.jsHeapSizeLimit,totalJSHeapSize:s.totalJSHeapSize,usedJSHeapSize:s.usedJSHeapSize,percentUsed:(s.usedJSHeapSize/s.jsHeapSizeLimit).toFixed(3),percentTotal:(s.totalJSHeapSize/s.jsHeapSizeLimit).toFixed(3)}}catch{return{}}}function Yi(s){if(s!=null){if(typeof s=="number")return s;if(typeof s=="string"){if(s.startsWith("#")){const e=parseInt(s.slice(1),16);if(!isNaN(e))return e}if(s.startsWith("0x")){const e=parseInt(s,16);if(!isNaN(e))return e}const t=parseInt(s,16);if(!isNaN(t))return t;try{return new J(s).toNumber()}catch{return}}}}class Ue extends li{ready;_meta={duration:1/0,width:0,height:0};get meta(){return{...this._meta}}text;get style(){return{fontSize:this.originalOpts.fontSize,fontFamily:this.originalOpts.fontFamily,fontWeight:this.originalOpts.fontWeight,fontStyle:this.originalOpts.fontStyle,color:this.originalOpts.fill,align:this.originalOpts.align,stroke:this.originalOpts.stroke?typeof this.originalOpts.stroke=="object"?{color:this.originalOpts.stroke.color,width:this.originalOpts.stroke.width}:{color:this.originalOpts.stroke,width:this.originalOpts.strokeWidth??0}:void 0,shadow:this.originalOpts.dropShadow?{color:this.originalOpts.dropShadow.color??"#000000",alpha:this.originalOpts.dropShadow.alpha??.5,blur:this.originalOpts.dropShadow.blur??4,offsetX:this.originalOpts.dropShadow.distance?Math.cos((this.originalOpts.dropShadow.angle??0)*Math.PI/180)*this.originalOpts.dropShadow.distance:0,offsetY:this.originalOpts.dropShadow.distance?Math.sin((this.originalOpts.dropShadow.angle??0)*Math.PI/180)*this.originalOpts.dropShadow.distance:0}:void 0}}pixiText=null;textStyle;renderTexture=null;externalRenderer=null;pixiApp=null;originalOpts;constructor(t,e={},r){super(),this.text=t,this.originalOpts={...e},this.externalRenderer=r??null;const n={fontSize:e.fontSize??40,fontFamily:e.fontFamily??"Arial",fontWeight:e.fontWeight??"normal",fontStyle:e.fontStyle??"normal",align:e.align??"left",wordWrap:e.wordWrap??!1,wordWrapWidth:e.wordWrapWidth??0,lineHeight:e.lineHeight??1,letterSpacing:e.letterSpacing??0};if(e.fill&&typeof e.fill=="object"&&e.fill.type==="gradient"){const l=new Vt(e.fill.x0,e.fill.y0,e.fill.x1,e.fill.y1);e.fill.colors.forEach(({ratio:h,color:d})=>{const f=typeof d=="number"?d:Yi(d)??16777215;l.addColorStop(h,f)}),n.fill={fill:l}}else{const l=typeof e.fill=="string"||typeof e.fill=="number"?Yi(e.fill):void 0;n.fill=l??16777215}if(e.stroke&&typeof e.stroke=="object"&&"color"in e.stroke){const l=Yi(e.stroke.color);l!==void 0&&(n.stroke={color:l,width:e.stroke.width},e.stroke.join&&(n.stroke.join=e.stroke.join))}else{const l=Yi(e.stroke),h=e.strokeWidth??0;l!==void 0&&h>0?n.stroke={color:l,width:h}:e.strokeWidth&&e.strokeWidth>0&&(n.stroke={color:0,width:e.strokeWidth})}if(e.dropShadow){const l=Yi(e.dropShadow.color);l!==void 0&&(n.dropShadow={color:l,alpha:e.dropShadow.alpha??.5,blur:e.dropShadow.blur??4,angle:e.dropShadow.angle??Math.PI/6,distance:e.dropShadow.distance??2})}const a=new Bt(n);this.textStyle=a,this.ready=(async()=>{this.pixiText=new gy({text:t,style:a});const l=this.pixiText.getLocalBounds(),h=Math.ceil(l.width||this.pixiText.width||100),d=Math.ceil(l.height||this.pixiText.height||40);this.renderTexture=Wi.create({width:h,height:d}),this._meta.width=h,this._meta.height=d,this._meta.duration=1/0,this.width=this.width===0?h:this.width,this.height=this.height===0?d:this.height;const f={...this._meta};return this.duration===0&&f.duration!==1/0&&(this.duration=f.duration,this.display.to=this.display.from+this.duration),H.info("TextClip ready:",f),f})()}setRenderer(t){this.externalRenderer=t,console.log("SET RENDERER",t)}async getRenderer(){if(this.externalRenderer!=null)return this.externalRenderer;if(this.pixiApp?.renderer==null)throw new Error("TextClip: Failed to create renderer. Please provide a renderer via constructor or setRenderer() method.");return this.pixiApp.renderer}async getTexture(){return this.pixiText==null||this.renderTexture==null?null:((await this.getRenderer()).render({container:this.pixiText,target:this.renderTexture}),this.renderTexture)}async tick(t){if(await this.ready,this.pixiText==null||this.renderTexture==null)throw new Error("TextClip not initialized");(await this.getRenderer()).render({container:this.pixiText,target:this.renderTexture});const r=this.renderTexture.source?.resource?.source;let n;if(r instanceof HTMLCanvasElement)n=await createImageBitmap(r);else if(r instanceof OffscreenCanvas)n=await createImageBitmap(r);else{const h=(await this.getRenderer()).extract.canvas(this.renderTexture);if(h instanceof HTMLCanvasElement||h instanceof OffscreenCanvas)n=await createImageBitmap(h);else{const d=this.renderTexture.width,f=this.renderTexture.height;throw new OffscreenCanvas(d,f).getContext("2d")==null?new Error("Failed to create 2d context for fallback rendering"):new Error("Unable to extract canvas from render texture")}}return{video:n,state:"success"}}async split(t){await this.ready;const e=await this.clone(),r=await this.clone();return[e,r]}async clone(){await this.ready;const t=this.textStyle,e=this.originalOpts||{},r=l=>{if(l!=null){if(typeof l=="number")return l;if(l instanceof J)return l.toNumber()}},n={fontSize:e.fontSize??t.fontSize,fontFamily:e.fontFamily??(Array.isArray(t.fontFamily)?t.fontFamily[0]:typeof t.fontFamily=="string"?t.fontFamily:"Arial"),fontWeight:e.fontWeight??t.fontWeight,fontStyle:e.fontStyle??t.fontStyle,align:e.align??(t.align==="justify"?"left":t.align)};if(e.fill&&typeof e.fill=="object"&&"type"in e.fill&&e.fill.type==="gradient")n.fill=e.fill;else{const l=r(t.fill);n.fill=l??16777215}if(e.stroke&&typeof e.stroke=="object"&&"color"in e.stroke)n.stroke=e.stroke;else{const l=r(t.stroke);l!==void 0&&(n.stroke=l),n.strokeWidth=e.strokeWidth??t.strokeThickness??0}if(e.dropShadow)n.dropShadow=e.dropShadow;else if(t.dropShadow){const l=t.dropShadow,h=r(l.color);h!==void 0&&(n.dropShadow={color:h,alpha:l.alpha,blur:l.blur,angle:l.angle,distance:l.distance})}e.wordWrap!==void 0?(n.wordWrap=e.wordWrap,n.wordWrapWidth=e.wordWrapWidth):t.wordWrap&&(n.wordWrap=t.wordWrap,n.wordWrapWidth=t.wordWrapWidth),e.lineHeight!==void 0?n.lineHeight=e.lineHeight:t.lineHeight!==void 0&&(n.lineHeight=t.lineHeight),e.letterSpacing!==void 0?n.letterSpacing=e.letterSpacing:t.letterSpacing!==void 0&&(n.letterSpacing=t.letterSpacing);const a=new Ue(this.text,n);return this.copyStateTo(a),a}destroy(){if(!this.destroyed){H.info("TextClip destroy");try{this.pixiText!=null&&this.pixiText.destroyed!==!0&&this.pixiText.destroy({children:!0})}catch{}finally{this.pixiText=null}try{this.renderTexture!=null&&this.renderTexture.destroyed!==!0&&this.renderTexture.destroy(!0)}catch{}finally{this.renderTexture=null}if(this.externalRenderer=null,this.pixiApp!=null)try{const t=this.pixiApp;t.destroyed!==!0&&t.renderer!=null&&this.pixiApp.destroy(!0,{children:!0,texture:!0})}catch{}finally{this.pixiApp=null}super.destroy()}}toJSON(t=!1){const e=super.toJSON(t),r={};if(this.originalOpts.fontSize!==void 0&&(r.fontSize=this.originalOpts.fontSize),this.originalOpts.fontFamily!==void 0&&(r.fontFamily=this.originalOpts.fontFamily),this.originalOpts.fontWeight!==void 0&&(r.fontWeight=this.originalOpts.fontWeight),this.originalOpts.fontStyle!==void 0&&(r.fontStyle=this.originalOpts.fontStyle),this.originalOpts.fill!==void 0&&(r.color=this.originalOpts.fill),this.originalOpts.align!==void 0&&(r.align=this.originalOpts.align),this.originalOpts.stroke&&(typeof this.originalOpts.stroke=="object"?r.stroke={color:this.originalOpts.stroke.color,width:this.originalOpts.stroke.width}:r.stroke={color:this.originalOpts.stroke,width:this.originalOpts.strokeWidth??0}),this.originalOpts.dropShadow){const n=this.originalOpts.dropShadow;r.shadow={color:n.color??"#000000",alpha:n.alpha??.5,blur:n.blur??4,offsetX:n.distance?Math.cos((n.angle??0)*Math.PI/180)*n.distance:0,offsetY:n.distance?Math.sin((n.angle??0)*Math.PI/180)*n.distance:0}}return{...e,type:"Text",text:this.text,style:r}}static async fromObject(t){if(t.type!=="Text")throw new Error(`Expected Text, got ${t.type}`);const e=t.text||"",r=t.style||{},n={};if(r.fontSize!==void 0&&(n.fontSize=r.fontSize),r.fontFamily!==void 0&&(n.fontFamily=r.fontFamily),r.fontWeight!==void 0&&(n.fontWeight=r.fontWeight),r.fontStyle!==void 0&&(n.fontStyle=r.fontStyle),r.color!==void 0&&(n.fill=r.color),r.align!==void 0&&(n.align=r.align),r.stroke&&(n.stroke=r.stroke.color,n.strokeWidth=r.stroke.width),r.shadow){const l=Math.sqrt(r.shadow.offsetX**2+r.shadow.offsetY**2),h=Math.atan2(r.shadow.offsetY,r.shadow.offsetX)*180/Math.PI;n.dropShadow={color:r.shadow.color,alpha:r.shadow.alpha,blur:r.shadow.blur,distance:l,angle:h}}const a=new Ue(e,n);return a.left=t.left,a.top=t.top,a.width=t.width,a.height=t.height,a.angle=t.angle,a.display.from=t.display.from,a.display.to=t.display.to,a.duration=t.duration,a.playbackRate=t.playbackRate,a.zIndex=t.zIndex,a.opacity=t.opacity,a.flip=t.flip,t.animation&&a.setAnimation(t.animation.keyFrames,t.animation.opts),await a.ready,a}}class Fu{readable;writable;inputBufOffset=0;constructor(){const t=yt.createFile();let e=!1;this.readable=new ReadableStream({start:r=>{t.onReady=a=>{const l=a.videoTracks[0]?.id;l!=null&&t.setExtractionOptions(l,"video",{nbSamples:100});const h=a.audioTracks[0]?.id;h!=null&&t.setExtractionOptions(h,"audio",{nbSamples:100}),r.enqueue({chunkType:"ready",data:{info:a,file:t}}),t.start()};const n={};t.onSamples=(a,l,h)=>{r.enqueue({chunkType:"samples",data:{id:a,type:l,samples:h.map(d=>({...d}))}}),n[a]=(n[a]??0)+h.length,t.releaseUsedSamples(a,n[a])},t.onFlush=()=>{r.close()}},cancel:()=>{t.stop(),e=!0}},{highWaterMark:50}),this.writable=new WritableStream({write:async r=>{if(e){this.writable.abort();return}const n=r.buffer;n.fileStart=this.inputBufOffset,this.inputBufOffset+=n.byteLength,t.appendBuffer(n)},close:()=>{t.flush(),t.stop(),t.onFlush?.()}})}}function ov(s){let t=0;const e=s.boxes,r=[];let n=0;async function a(){const o=x(e,t);t=e.length,r.forEach(({track:c,id:u})=>{const p=c.samples.at(-1);p!=null&&(n=Math.max(n,p.cts+p.duration)),s.releaseUsedSamples(u,c.samples.length),c.samples=[]}),s.mdats=[],s.moofs=[],o!=null&&await m?.write(o)}let l=[];function h(){if(l.length>0)return!0;const o=e.findIndex(c=>c.type==="moov");if(o===-1)return!1;if(l=e.slice(0,o+1),t=o+1,r.length===0)for(let c=1;;c+=1){const u=s.getTrackById(c);if(u==null)break;r.push({track:u,id:c})}return!0}let d=0;const f=rs();let m=null;const g=(async()=>{m=await f.createWriter(),d=self.setInterval(()=>{h()&&a()},100)})();let y=!1;return async()=>{if(y)throw Error("File exported");if(y=!0,await g,clearInterval(d),!h()||m==null)return null;s.flush(),await a(),await m?.close();const o=l.find(p=>p.type==="moov");if(o==null)return null;o.mvhd.duration=n;const c=rs(),u=x(l,0);return await ni(c,u.slice()),await ni(c,f,{overwrite:!1}),await c.stream()};function x(o,c){if(c>=o.length)return null;const u=new yt.DataStream;u.endianness=yt.DataStream.BIG_ENDIAN;for(let p=c;p<o.length;p++)o[p]!==null&&(o[p].write(u),delete o[p]);return new Uint8Array(u.buffer).slice()}}function hv(s){const t=new ArrayBuffer(s.byteLength);s.copyTo(t);const e=s.timestamp;return{duration:s.duration??0,dts:e,cts:e,is_sync:s.type==="key",data:t}}async function Du(s){const t=yt.createFile(),e=ov(t);await lv(s,t);const r=await e();if(r==null)throw Error("Can not generate file from streams");return r}async function lv(s,t){let e=0,r=0,n=0,a=0,l=0,h=0,d=null,f=null;for(const m of s){let g=null,y=null,x=null,o=null;if(await new Promise(async c=>{Ia(m.pipeThrough(new Fu),{onDone:c,onChunk:async({chunkType:u,data:p})=>{if(u==="ready"){const{videoTrackConf:_,audioTrackConf:b}=oa(p.file,p.info);e===0&&_!=null&&(e=t.addTrack(_)),a===0&&b!=null&&(a=t.addTrack(b))}else if(u==="samples"){const{type:_,samples:b}=p,v=_==="video"?e:a,w=_==="video"?r:l,S=_==="video"?n:h;b.forEach(E=>{let P,B;_==="video"?(g===null&&(g=E.dts,y=E.cts),P=E.dts-g,B=E.cts-(y??0)):(x===null&&(x=E.dts,o=E.cts),P=E.dts-x,B=E.cts-(o??0)),t.addSample(v,E.data,{duration:E.duration,dts:P+w,cts:B+S,is_sync:E.is_sync})});const T=b.at(-1);if(T==null)return;_==="video"?d=T:_==="audio"&&(f=T)}}})}),d!=null&&g!==null&&y!==null){const c=d.dts-g+d.duration,u=d.cts-y+d.duration;r+=c,n+=u}if(f!=null&&d!=null){const c=f.timescale/d.timescale;l=Math.round(r*c),h=Math.round(n*c)}}}async function cv(s){return await Du([s])}function uv(s){let t=[];const e=new AudioDecoder({output:r=>{t.push(r)},error:H.error});return e.configure(s),{decode:async r=>{r.forEach(a=>{e.decode(new EncodedAudioChunk({type:a.is_sync?"key":"delta",timestamp:1e6*a.cts/a.timescale,duration:1e6*a.duration/a.timescale,data:a.data}))}),await e.flush();const n=t;return t=[],n},close:()=>{e.close()}}}function dv(s,t){const e={codec:s.codec,sampleRate:s.sampleRate,numberOfChannels:s.numberOfChannels},r=new AudioEncoder({output:l=>{t(hv(l))},error:l=>{H.error("AudioEncoder error:",l,", config:",e)}});r.configure(e);let n=null;function a(l,h){return new AudioData({timestamp:h,numberOfChannels:s.numberOfChannels,numberOfFrames:l.length/s.numberOfChannels,sampleRate:s.sampleRate,format:"f32-planar",data:new Float32Array(l)})}return{encode:async(l,h)=>{n!=null&&r.encode(a(n.data,n.ts)),n={data:l,ts:h}},stop:async()=>{n!=null&&(fv(n.data,s.numberOfChannels,s.sampleRate),r.encode(a(n.data,n.ts)),n=null),await r.flush(),r.close()}}}function fv(s,t,e){const r=s.length-1,n=Math.min(e/2,r);for(let a=0;a<n;a++)for(let l=1;l<=t;l++)s[Math.floor(r/l)-a]*=a/n}function pv(s,t){H.info("mixinMP4AndAudio, opts:",{volume:t.volume,loop:t.loop});const e=yt.createFile(),{stream:r,stop:n}=Fa(e,500);let a=null,l=null,h=[],d=0,f=0,m=0,g=!0,y=tt.sampleRate;Ia(s.pipeThrough(new Fu),{onDone:async()=>{await l?.stop(),a?.close(),n()},onChunk:async({chunkType:u,data:p})=>{if(u==="ready"){const{videoTrackConf:_,audioTrackConf:b,audioDecoderConf:v}=oa(p.file,p.info);d===0&&_!=null&&(d=e.addTrack(_));const w=b??{timescale:1e6,samplerate:y,channel_count:tt.channelCount,hdlr:"soun",name:"SoundHandler",type:"mp4a"};f===0&&(f=e.addTrack(w),y=b?.samplerate??y,g=b!=null);const S=new AudioContext({sampleRate:y});h=hs(await S.decodeAudioData(await new Response(t.stream).arrayBuffer())),v!=null&&(a=uv(v)),l=dv(v??{codec:w.type==="mp4a"?tt.codec:w.type,numberOfChannels:w.channel_count,sampleRate:w.samplerate},T=>e.addSample(f,T.data,T))}else if(u==="samples"){const{id:_,type:b,samples:v}=p;if(b==="video"){v.forEach(w=>e.addSample(_,w.data,w)),g||await o(v);return}b==="audio"&&await c(v)}}});function x(u){const p=h.map(_=>t.loop?ls(_,m,m+u):_.slice(m,m+u));if(m+=u,t.volume!==1)for(const _ of p)for(let b=0;b<_.length;b++)_[b]*=t.volume;return p}async function o(u){const p=u[0],_=u[u.length-1],b=Math.floor((_.cts+_.duration-p.cts)/p.timescale*y),v=za([x(b)]);v.length!==0&&l?.encode(v,p.cts/p.timescale*1e6)}async function c(u){if(a==null)return;const p=(await a.decode(u)).map(La),_=Oa(p),b=x(_[0].length),v=u[0];l?.encode(za([_,b]),v.cts/v.timescale*1e6)}return r}function mv(s,t){const{opacity:e,zIndex:r,flip:n,left:a,top:l,width:h,height:d,angle:f}=s;t.x=a,t.y=l,t.width=Math.abs(h),t.height=Math.abs(d),t.rotation=f,t.alpha=e,t.zIndex=r,n==="horizontal"?t.scale.x=-Math.abs(t.scale.x):n==="vertical"&&(t.scale.y=-Math.abs(t.scale.y))}class Xi{constructor(t,e){this.pixiApp=t,this.sprite=e,this.canvas=new OffscreenCanvas(1,1);const r=this.canvas.getContext("2d");if(r==null)throw new Error("Failed to create 2d context for PixiSpriteRenderer");this.context=r}pixiSprite=null;texture=null;canvas;context;destroyed=!1;async updateFrame(t){if(this.destroyed)return;if(t==null){this.pixiSprite!=null&&(this.pixiSprite.visible=!1,this.applySpriteTransforms());return}if(t instanceof M){if(t.width===0||t.height===0){console.warn("PixiSpriteRenderer: Invalid texture dimensions",t.width,t.height);return}this.pixiSprite==null?(this.pixiSprite=new te(t),this.pixiApp.stage.addChild(this.pixiSprite),this.applySpriteTransforms()):this.pixiSprite.texture=t,this.pixiSprite!=null&&(this.pixiSprite.visible=!0,this.applySpriteTransforms());return}if(t.width===0||t.height===0){console.warn("PixiSpriteRenderer: Invalid frame dimensions",t.width,t.height);return}const e=this.texture==null||this.pixiSprite==null;if(this.canvas.width!==t.width||this.canvas.height!==t.height||e){if(this.canvas.width=t.width,this.canvas.height=t.height,this.texture!=null&&(this.texture.destroy(!0),this.texture=null),this.texture=M.from(this.canvas),!this.texture||!this.texture.source){console.error("PixiSpriteRenderer: Failed to create valid texture");return}this.pixiSprite==null?(this.pixiSprite=new te(this.texture),this.pixiApp.stage.addChild(this.pixiSprite),this.applySpriteTransforms()):this.pixiSprite.texture=this.texture}if(this.context.clearRect(0,0,this.canvas.width,this.canvas.height),this.context.drawImage(t,0,0),this.texture!=null&&this.texture.source!=null){const n=this.texture.source;if(n.resource){const a=n.resource;a.update&&a.update()}typeof n.update=="function"&&n.update()}this.pixiSprite!=null&&(this.pixiSprite.visible=!0,this.applySpriteTransforms())}applySpriteTransforms(){if(this.pixiSprite==null||this.destroyed)return;const{flip:t,center:e,width:r,height:n,angle:a,opacity:l,zIndex:h}=this.sprite;this.pixiSprite.x=e.x,this.pixiSprite.y=e.y,this.pixiSprite.anchor.set(.5,.5);const d=this.pixiSprite.texture?.width??1,f=this.pixiSprite.texture?.height??1,m=r&&r!==0?Math.abs(r)/d:1,g=n&&n!==0?Math.abs(n)/f:1;t==="horizontal"?(this.pixiSprite.scale.x=-m,this.pixiSprite.scale.y=g):t==="vertical"?(this.pixiSprite.scale.x=m,this.pixiSprite.scale.y=-g):(this.pixiSprite.scale.x=m,this.pixiSprite.scale.y=g),this.pixiSprite.rotation=(t==null?1:-1)*a,this.pixiSprite.alpha=l,this.pixiSprite.zIndex=h}updateTransforms(){this.pixiSprite!=null&&!this.destroyed&&this.applySpriteTransforms()}getSprite(){return this.pixiSprite}destroy(){this.destroyed||(this.destroyed=!0,this.pixiSprite!=null&&(this.pixiApp.stage.removeChild(this.pixiSprite),this.pixiSprite.destroy({children:!0}),this.pixiSprite=null),this.texture!=null&&(this.texture.destroy(!0),this.texture=null))}}function ua(s,t=!1){return s.toJSON(t)}async function da(s){let t,e=null;switch(s.type){case"Video":e=_t;break;case"Audio":e=pt;break;case"Image":e=Dt;break;case"Text":e=Ue;break;case"Caption":e=Be;break}if(e&&typeof e.fromObject=="function")return await e.fromObject(s);switch(s.type){case"Video":{const r=await fetch(s.src);if(!r.ok)throw new Error(`Failed to fetch video from ${s.src}: ${r.status} ${r.statusText}. Make sure the file exists in the public directory.`);const n=s.audio!==void 0?{audio:s.audio}:{};t=new _t(r.body,n,s.src);break}case"Audio":{if(!s.src||s.src.trim()==="")throw new Error("AudioClip requires a valid source URL");const r={};s.loop!==void 0&&(r.loop=s.loop),s.volume!==void 0&&(r.volume=s.volume),t=await pt.fromUrl(s.src,r);break}case"Image":{if(!s.src||s.src.trim()==="")throw new Error("ImageClip requires a valid source URL. Generated clips (like text-to-image) cannot be loaded from JSON without their source data.");try{const r=await fetch(s.src);if(!r.ok)throw new Error(`Failed to fetch image from ${s.src}: ${r.status} ${r.statusText}. Make sure the file exists in the public directory.`);const n=await r.blob();if(!n.type.startsWith("image/"))throw new Error(`Invalid image format: ${n.type}. Expected an image file.`);t=new Dt(await createImageBitmap(n),s.src)}catch(r){throw r instanceof Error&&r.message.includes("could not be decoded")?new Error(`Failed to decode image from ${s.src}. The image may be corrupted, in an unsupported format, or there may be CORS issues.`):r}break}case"Text":{const r=s.text||"",n=s.style||{},a={fontSize:n.fontSize,fontFamily:n.fontFamily,fontWeight:n.fontWeight,fontStyle:n.fontStyle,fill:n.color,align:n.align};n.stroke&&(a.stroke=n.stroke.color,a.strokeWidth=n.stroke.width),n.shadow&&(a.dropShadow={color:n.shadow.color,alpha:n.shadow.alpha,blur:n.shadow.blur,offsetX:n.shadow.offsetX,offsetY:n.shadow.offsetY}),t=new Ue(r,a);break}case"Caption":{const r=s.text||"",n=s.style||{},a={fontSize:n.fontSize,fontFamily:n.fontFamily,fontWeight:n.fontWeight,fontStyle:n.fontStyle,fill:n.color,align:n.align};if(n.fontUrl!==void 0?a.fontUrl=n.fontUrl:s.fontUrl!==void 0&&(a.fontUrl=s.fontUrl),n.stroke&&(a.stroke=n.stroke.color,a.strokeWidth=n.stroke.width),n.shadow&&(a.dropShadow={color:n.shadow.color,alpha:n.shadow.alpha,blur:n.shadow.blur,offsetX:n.shadow.offsetX,offsetY:n.shadow.offsetY}),s.caption){const l=s.caption;l.words&&(a.words=l.words),l.colors&&(l.colors.appeared!==void 0&&(a.appearedColor=l.colors.appeared),l.colors.active!==void 0&&(a.activeColor=l.colors.active),l.colors.activeFill!==void 0&&(a.activeFillColor=l.colors.activeFill),l.colors.background!==void 0&&(a.backgroundColor=l.colors.background),l.colors.keyword!==void 0&&(a.isKeyWordColor=l.colors.keyword)),l.preserveKeywordColor!==void 0&&(a.preservedColorKeyWord=l.preserveKeywordColor),l.positioning&&(l.positioning.bottomOffset!==void 0&&(a.bottomOffset=l.positioning.bottomOffset),l.positioning.videoWidth!==void 0&&(a.videoWidth=l.positioning.videoWidth),l.positioning.videoHeight!==void 0&&(a.videoHeight=l.positioning.videoHeight))}else s.bottomOffset!==void 0&&(a.bottomOffset=s.bottomOffset),s.words&&(a.words=s.words),s.appearedColor!==void 0&&(a.appearedColor=s.appearedColor),s.activeColor!==void 0&&(a.activeColor=s.activeColor),s.activeFillColor!==void 0&&(a.activeFillColor=s.activeFillColor),s.backgroundColor!==void 0&&(a.backgroundColor=s.backgroundColor),s.isKeyWordColor!==void 0&&(a.isKeyWordColor=s.isKeyWordColor),s.preservedColorKeyWord!==void 0&&(a.preservedColorKeyWord=s.preservedColorKeyWord),s.videoWidth!==void 0&&(a.videoWidth=s.videoWidth),s.videoHeight!==void 0&&(a.videoHeight=s.videoHeight);t=new Be(r,a);break}default:throw new Error(`Unsupported clip type: ${s.type}`)}return t.left=s.left,t.top=s.top,t.width=s.width,t.height=s.height,t.angle=s.angle,t.display.from=s.display.from,t.display.to=s.display.to,t.duration=s.duration,t.playbackRate=s.playbackRate,t.zIndex=s.zIndex,t.opacity=s.opacity,t.flip=s.flip,s.animation&&t.setAnimation(s.animation.keyFrames,s.animation.opts),t}let gv=0;async function Gu(s){s()>50&&(await cs(15),await Gu(s))}class _v{static async isSupported(t={}){return(self.OffscreenCanvas!=null&&self.VideoEncoder!=null&&self.VideoDecoder!=null&&self.VideoFrame!=null&&self.AudioEncoder!=null&&self.AudioDecoder!=null&&self.AudioData!=null&&((await self.VideoEncoder.isConfigSupported({codec:t.videoCodec??"avc1.42E032",width:t.width??1920,height:t.height??1080,bitrate:t.bitrate??7e6})).supported??!1)&&(await self.AudioEncoder.isConfigSupported({codec:tt.codec,sampleRate:tt.sampleRate,numberOfChannels:tt.channelCount})).supported)??!1}logger=H.create(`id:${gv++},`);destroyed=!1;sprites=[];canvas;pixiApp=null;stopOutput=null;opts;hasVideoTrack;evtTool=new ss;on=this.evtTool.on;constructor(t={}){const{width:e=0,height:r=0}=t;this.canvas=new OffscreenCanvas(e,r),this.opts=Object.assign({bgColor:"#000",width:0,height:0,videoCodec:"avc1.42E032",audio:!0,bitrate:5e6,fps:30,metaDataTags:null},t),this.hasVideoTrack=e*r>0}async initPixiApp(){const{width:t,height:e}=this.opts;if(this.pixiApp=new Qs,console.log("PIXI APP 000",this.pixiApp),await this.pixiApp.init({canvas:this.canvas,width:t,height:e,backgroundColor:0,antialias:!1,autoDensity:!1,resolution:1}),this.pixiApp.renderer==null||this.pixiApp.stage==null)throw new Error("Pixi.js Application failed to initialize properly");try{const r=this.pixiApp;r.ticker&&typeof r.ticker.stop=="function"&&r.ticker.stop()}catch{}}async addSprite(t,e={}){const r={rect:{x:t.left,y:t.top,w:t.width,h:t.height},display:{...t.display},duration:t.duration,playbackRate:t.playbackRate,zIndex:t.zIndex};this.logger.info("Compositor add clip",r);const n=await t.clone();console.log("PIXI APP 111",this.pixiApp),this.pixiApp!=null&&this.pixiApp.renderer!=null&&typeof n.setRenderer=="function"&&n.setRenderer(this.pixiApp.renderer),this.logger.info("Compositor add clip ready"),this.sprites.push(Object.assign(n,{main:e.main??!1,expired:!1})),this.sprites.sort((a,l)=>a.zIndex-l.zIndex)}initMuxer(t){const{fps:e,width:r,height:n,videoCodec:a,bitrate:l,audio:h,metaDataTags:d}=this.opts,f=this.sprites.some(y=>y.width>0&&y.height>0),m=this.hasVideoTrack&&f;return Rd({video:m?{width:r,height:n,expectFPS:e,codec:a,bitrate:l,__unsafe_hardwareAcceleration__:this.opts.__unsafe_hardwareAcceleration__}:null,audio:h===!1?null:{codec:"aac",sampleRate:tt.sampleRate,channelCount:tt.channelCount},duration:t,metaDataTags:d})}output(t={}){if(this.sprites.length===0)throw Error("No sprite added");const e=this.sprites.find(g=>g.main),n=this.sprites.map(g=>g.display.from+g.duration).filter(g=>g!==1/0),a=t.maxTime??(e!=null?e.display.from+e.duration:n.length>0?Math.max(...n):1/0);if(a===1/0||a<=0)throw Error("Unable to determine the end time, please specify a main sprite, or limit the duration of ImageClip, AudioClip");a===-1&&this.logger.warn("Unable to determine the end time, process value don't update"),this.logger.info(`start combinate video, maxTime:${a}`);const l=this.initMuxer(a);let h=performance.now();const d=this.runEncoding(l,a,{onProgress:g=>{this.logger.debug("OutputProgress:",g),this.evtTool.emit("OutputProgress",g)},onEnded:async()=>{await l.flush(),this.logger.info("===== output ended =====, cost:",performance.now()-h),this.evtTool.emit("OutputProgress",1),this.destroy()},onError:g=>{this.evtTool.emit("error",g),m(g),this.destroy()}});this.stopOutput=()=>{d(),l.close(),m()};const{stream:f,stop:m}=Fa(l.mp4file,500,this.destroy);return f}destroy(){if(!this.destroyed&&(this.destroyed=!0,this.stopOutput?.(),this.evtTool.destroy(),this.pixiApp!=null))try{const t=this.pixiApp;if(t.destroyed===!0){this.pixiApp=null;return}if(t.ticker&&typeof t.ticker.stop=="function")try{t.ticker.stop()}catch{}if(t.renderer!=null){const e=t.renderer.gl;if(e&&e.isContextLost()){this.pixiApp=null;return}this.pixiApp.destroy(!0,{children:!0,texture:!0})}}catch(t){console.warn("Error while destroying Pixi application:",t)}finally{this.pixiApp=null}}runEncoding(t,e,{onProgress:r,onEnded:n,onError:a}){let l=0;const h={aborted:!1};let d=null,f=null;const m=async()=>{const{fps:x,bgColor:o,audio:c}=this.opts,u=Math.round(1e6/x),p=this.sprites.some(v=>v.width>0&&v.height>0);f=yv({pixiApp:this.pixiApp,sprites:this.sprites,aborter:h});const _=xv({muxer:t,canvas:this.canvas,outputAudio:c,hasVideoTrack:this.hasVideoTrack&&p,timeSlice:u,fps:x});let b=0;for(;;){if(d!=null)return;if(h.aborted||e!==-1&&b>e||this.sprites.length===0){g(),await n();return}l=b/e;const{audios:v,mainSprDone:w,hasVideo:S}=await f.render(b);if(w){g(),await n();return}if(h.aborted)return;this.hasVideoTrack&&S&&await new Promise(T=>requestAnimationFrame(T)),_(b,v,S),b+=u,await Gu(t.getEncodeQueueSize)}},g=()=>{h.aborted||(h.aborted=!0,clearInterval(y),f?.cleanup(),this.sprites.forEach(x=>{x.destroy()}))};m().catch(x=>{d=x,this.logger.error(x),g(),a(x)});const y=setInterval(()=>{r(l)},500);return g}exportToJSON(){return{clips:this.sprites.map(e=>ua(e,e.main)),settings:{width:this.opts.width,height:this.opts.height,fps:this.opts.fps,bgColor:this.opts.bgColor,videoCodec:this.opts.videoCodec,bitrate:this.opts.bitrate,audio:this.opts.audio,metaDataTags:this.opts.metaDataTags}}}async loadFromJSON(t){this.sprites.forEach(e=>{e.destroy()}),this.sprites=[],t.settings&&(t.settings.width!==void 0&&(this.opts.width=t.settings.width),t.settings.height!==void 0&&(this.opts.height=t.settings.height),t.settings.fps!==void 0&&(this.opts.fps=t.settings.fps),t.settings.bgColor!==void 0&&(this.opts.bgColor=t.settings.bgColor),t.settings.videoCodec!==void 0&&(this.opts.videoCodec=t.settings.videoCodec),t.settings.bitrate!==void 0&&(this.opts.bitrate=t.settings.bitrate),t.settings.audio!==void 0&&(this.opts.audio=t.settings.audio===!1?!1:void 0),t.settings.metaDataTags!==void 0&&(this.opts.metaDataTags=t.settings.metaDataTags));for(const e of t.clips){const r=await da(e);await this.addSprite(r,{main:e.main||!1})}}}function yv(s){const{pixiApp:t,sprites:e,aborter:r}=s,n=t!=null,a=new Map;return{render:async d=>{const f=[];let m=!1,g=!1;const y=[...e].sort((x,o)=>x.zIndex-o.zIndex);for(const x of y){if(r.aborted)break;if(d<x.display.from||x.expired)continue;const o=d-x.display.from,c=o*x.playbackRate;x.animate(c);const{video:u,audio:p,done:_}=await x.getFrame(o);if(f.push(p),n&&t!=null){let b=a.get(x);b==null&&u!=null&&(b=new Xi(t,x),a.set(x,b)),b!=null&&(u!=null?(g=!0,await b.updateFrame(u)):await b.updateFrame(null)),b?.updateTransforms()}if(x.duration>0&&d>x.display.from+x.duration||_){if(x.main&&(m=!0),x.expired=!0,n){const b=a.get(x);b!=null&&(b.destroy(),a.delete(x))}}else if(n){const b=a.get(x);b?.updateTransforms()}}return n&&t!=null&&t.renderer!=null&&t.stage!=null&&a.size>0&&t.render(),{audios:f,mainSprDone:m,hasVideo:g}},cleanup:()=>{a.forEach(d=>{d.destroy()}),a.clear()}}}function xv(s){const{canvas:t,outputAudio:e,muxer:r,hasVideoTrack:n,timeSlice:a}=s;let l=0;const h=Math.floor(3*s.fps),d=bv(1024);return(f,m,g)=>{if(e!==!1)for(const y of d(f,m))r.encodeAudio(y);if(n&&g)try{const y=new VideoFrame(t,{duration:a,timestamp:f});r.encodeVideo(y,{keyFrame:l%h===0}),l+=1}catch(y){console.warn("Failed to create VideoFrame from canvas, skipping frame:",y)}}}function bv(s){const t=s*tt.channelCount,e=new Float32Array(t*3);let r=0,n=0;const a=s/tt.sampleRate*1e6,l=new Float32Array(t),h=d=>{let f=0;const m=Math.floor(r/t),g=[];for(let y=0;y<m;y++)g.push(new AudioData({timestamp:n,numberOfChannels:tt.channelCount,numberOfFrames:s,sampleRate:tt.sampleRate,format:"f32",data:e.subarray(f,f+t)})),f+=t,n+=a;for(e.set(e.subarray(f,r),0),r-=f;d-n>a;)g.push(new AudioData({timestamp:n,numberOfChannels:tt.channelCount,numberOfFrames:s,sampleRate:tt.sampleRate,format:"f32",data:l})),n+=a;return g};return(d,f)=>{const m=Math.max(...f.map(g=>g[0]?.length??0));for(let g=0;g<m;g++){let y=0,x=0;for(let o=0;o<f.length;o++){const c=f[o][0]?.[g]??0,u=f[o][1]?.[g]??c;y+=c,x+=u}e[r]=y,e[r+1]=x,r+=2}return h(d)}}class vv extends pe{constructor(){super(),this.eventMode="static",this.cursor="move"}draw(t){this.clear(),this.setStrokeStyle({width:1,color:5620223}).rect(t.x,t.y,t.width,t.height).stroke(),this.hitArea=t}}class he extends pe{#t=!1;handle;cursor;callbacks;constructor(t,e,r){super(),this.handle=t,this.cursor=e,this.callbacks=r,this.eventMode="static",this.#a(),this.on("pointerdown",this.#e),this.on("globalpointermove",this.#r),this.on("pointerup",this.#o),this.on("pointerupoutside",this.#o)}#a(){this.circle(0,0,6),this.fill({color:"#ffffff"}),this.stroke({width:1,color:0,alpha:.4}),this.hitArea=new Pr(0,0,20)}#e=t=>{this.#t=!0,this.cursor="grabbing",this.callbacks.beginDrag(this.handle,t.global),t.stopPropagation()};#r=t=>{this.#t&&(this.callbacks.updateDrag(this.handle,t.global),t.stopPropagation())};#o=t=>{this.#t&&(this.#t=!1,this.cursor="pointer",this.callbacks.endDrag(),t.stopPropagation())}}const Ou={delta:new k};class wv extends ot{group;wireframe=new vv;isDragging=!1;lastPointer=new q;activeHandle=null;#t;#a=new Map;#e=new q;#r=0;#o=0;#h=new L;#i=new q;#l=new L;#s=1;#n=1;opts;constructor(t){super(),this.opts=t,this.group=t.group,this.eventMode="static";const e={beginDrag:(r,n)=>this.#y(r,n),updateDrag:(r,n)=>this.#x(r,n),endDrag:()=>this.#d()};this.#t={tl:new he("tl","nwse-resize",e),tr:new he("tr","nesw-resize",e),bl:new he("bl","nesw-resize",e),br:new he("br","nwse-resize",e),ml:new he("ml","ew-resize",e),mr:new he("mr","ew-resize",e),mt:new he("mt","ns-resize",e),mb:new he("mb","ns-resize",e),rot:new he("rot","crosshair",{beginDrag:(r,n)=>this.#v(n),updateDrag:(r,n)=>this.#w(n),endDrag:()=>this.#d()})},this.addChild(this.wireframe,...Object.values(this.#t)),this.#p(),Ct.shared.addOnce(()=>this.#m())}#p(){this.on("pointerdown",this.#g),this.on("pointerup",this.#u),this.on("pointerupoutside",this.#u),this.on("globalpointermove",this.#_)}#m(){if(this.group.length===1){const t=this.group[0],e=t.getBounds();this.#e.set(e.x+e.width/2,e.y+e.height/2),this.#r=t.rotation;let r,n;if(this.opts.clip)r=this.opts.clip.width,n=this.opts.clip.height;else{const a=t.getLocalBounds();r=a.width,n=a.height}this.#l.copyFrom(new L(-r/2,-n/2,r,n))}else{const t=this.#S();this.#e.set(t.x+t.width/2,t.y+t.height/2);const e=new L(-t.width/2,-t.height/2,t.width,t.height);this.#l.copyFrom(e)}this.#c()}#g=t=>{this.isDragging=!0,this.lastPointer.copyFrom(t.global),this.cursor="grabbing"};#u=()=>{this.isDragging&&this.emit("transformEnd"),this.isDragging=!1,this.activeHandle=null,this.cursor="default"};#_=t=>{if(!this.isDragging||this.activeHandle||!this.parent)return;const e=this.parent.toLocal(this.lastPointer),r=this.parent.toLocal(t.global),n=r.x-e.x,a=r.y-e.y;for(const l of this.group)l.x+=n,l.y+=a;this.#e.x+=n,this.#e.y+=a,this.lastPointer.copyFrom(t.global),this.#c()};#y(t,e){this.isDragging=!0,this.activeHandle=t,this.#a.clear();for(const r of this.group)this.#a.set(r,r.localTransform.clone());this.rotation=this.#r,this.#h.copyFrom(this.#l),this.#T(t)}#x(t,e){this.#b(t,e)}#b(t,e){const r=this.#i,n=this.#C(t,this.toLocal(e),r),a=n.width/this.#h.width,l=n.height/this.#h.height,h=this.toGlobal(r);this.#f(this.#E(h,this.#r,a,l)),this.#l.copyFrom(n),this.#c()}#v(t){this.isDragging=!0,this.activeHandle="rot",this.#a.clear();for(const e of this.group)this.#a.set(e,e.localTransform.clone());this.#o=Math.atan2(t.y-this.#e.y,t.x-this.#e.x)}#w(t){const r=Math.atan2(t.y-this.#e.y,t.x-this.#e.x)-this.#o,n=this.#r+r;this.#f(this.#A(this.#e,r)),this.rotation=n,this.#c(n)}#d(){this.isDragging=!1,this.#r=this.rotation,this.activeHandle=null,this.#c(this.#r),this.emit("transformEnd")}#S(){let t=1/0,e=1/0,r=-1/0,n=-1/0;for(const a of this.group){const l=a.getBounds();t=Math.min(t,l.x),e=Math.min(e,l.y),r=Math.max(r,l.x+l.width),n=Math.max(n,l.y+l.height)}return new L(t,e,r-t,n-e)}#c(t=this.#r){this.parent&&this.position.copyFrom(this.parent.toLocal(this.#e)),this.rotation=t;const e=this.#l;this.wireframe.draw(e);const r=e.x+e.width/2,n=e.y+e.height/2;this.#t.tl.position.set(e.x,e.y),this.#t.tr.position.set(e.x+e.width,e.y),this.#t.bl.position.set(e.x,e.y+e.height),this.#t.br.position.set(e.x+e.width,e.y+e.height),this.#t.ml.position.set(e.x,n),this.#t.mr.position.set(e.x+e.width,n),this.#t.mt.position.set(r,e.y),this.#t.mb.position.set(r,e.y+e.height),this.#t.rot.position.set(r,e.y-30)}#T(t){const e=this.#h;if(this.opts.centeredScaling){this.#i.set(e.x+e.width/2,e.y+e.height/2);return}t==="tl"?this.#i.set(e.x+e.width,e.y+e.height):t==="tr"?this.#i.set(e.x,e.y+e.height):t==="bl"?this.#i.set(e.x+e.width,e.y):t==="br"?this.#i.set(e.x,e.y):t==="ml"?this.#i.set(e.x+e.width,e.y+e.height/2):t==="mr"?this.#i.set(e.x,e.y+e.height/2):t==="mt"?this.#i.set(e.x+e.width/2,e.y+e.height):t==="mb"&&this.#i.set(e.x+e.width/2,e.y)}#C(t,e,r){if(this.opts.centeredScaling){const a=Math.max(this.#s,Math.abs(e.x-r.x)*2),l=Math.max(this.#n,Math.abs(e.y-r.y)*2);return new L(r.x-a/2,r.y-l/2,a,l)}if(t==="tl"){const a=Math.min(e.x,r.x-this.#s),l=Math.min(e.y,r.y-this.#n);return new L(a,l,r.x-a,r.y-l)}if(t==="tr"){const a=Math.max(e.x,r.x+this.#s),l=Math.min(e.y,r.y-this.#n);return new L(r.x,l,a-r.x,r.y-l)}if(t==="bl"){const a=Math.min(e.x,r.x-this.#s),l=Math.max(e.y,r.y+this.#n);return new L(a,r.y,r.x-a,l-r.y)}if(t==="br"){const a=Math.max(e.x,r.x+this.#s),l=Math.max(e.y,r.y+this.#n);return new L(r.x,r.y,a-r.x,l-r.y)}const n=this.#h;if(t==="ml"){const a=Math.min(e.x,r.x-this.#s);return new L(a,n.y,r.x-a,n.height)}if(t==="mr"){const a=Math.max(e.x,r.x+this.#s);return new L(r.x,n.y,a-r.x,n.height)}if(t==="mt"){const a=Math.min(e.y,r.y-this.#n);return new L(n.x,a,n.width,r.y-a)}if(t==="mb"){const a=Math.max(e.y,r.y+this.#n);return new L(n.x,r.y,n.width,a-r.y)}return new L(r.x,r.y,this.#s,this.#n)}#E(t,e,r,n){return Ou.delta.identity().translate(-t.x,-t.y).rotate(-e).scale(r,n).rotate(e).translate(t.x,t.y)}#A(t,e){return Ou.delta.identity().translate(-t.x,-t.y).rotate(e).translate(t.x,t.y)}#f(t){for(const e of this.group){const r=this.#a.get(e),n=e.parent;if(!r||!n)continue;const a=n.worldTransform.clone().invert(),l=r.clone().append(n.worldTransform),h=t.clone().append(l),d=a.clone().append(h);e.setFromMatrix(d)}}}class Sv{pixiApp=null;clips=[];spriteRenderers=new Map;activeTransformer=null;selectedClips=new Set;interactiveClips=new Set;playbackElements=new Map;videoSprites=new Map;isPlaying=!1;currentTime=0;playStartTime=0;playStartTimestamp=0;rafId=null;maxDuration=0;opts;destroyed=!1;hexToNumber(t){const e=t.startsWith("#")?t.slice(1):t;return parseInt(e,16)}constructor(t){this.opts={fps:30,bgColor:"#000000",...t},this.initPixiApp()}async initPixiApp(){if(this.destroyed)return;const t=this.opts.canvas||document.createElement("canvas");t.width=this.opts.width,t.height=this.opts.height;const e=new Qs;await e.init({canvas:t,width:this.opts.width,height:this.opts.height,backgroundColor:this.hexToNumber(this.opts.bgColor),antialias:!0,resolution:window.devicePixelRatio||1,autoDensity:!0}),this.pixiApp=e,e.stage.eventMode="static",e.stage.hitArea=e.screen,e.stage.on("pointerdown",r=>{r.target===e.stage&&this.deselectClip()})}getCanvas(){if(this.opts.canvas)return this.opts.canvas;if(this.pixiApp?.canvas)return this.pixiApp.canvas;throw new Error("Canvas not initialized yet. Wait for initPixiApp to complete.")}async addClip(t,e){if(this.destroyed)return;if(this.pixiApp==null)throw new Error("Failed to initialize Pixi.js Application");this.pixiApp!=null&&typeof t.setRenderer=="function"&&t.setRenderer(this.pixiApp.renderer);const r=await t.ready;this.clips.push(t);let n=t.duration>0?t.duration:r.duration;if(n===1/0||isNaN(n))await this.recalculateMaxDuration();else{const a=t.display.from+n;a>0&&(this.maxDuration=Math.max(this.maxDuration,a))}if(await this.setupPlaybackForClip(t,e),r.width>0&&r.height>0)if(t instanceof _t){if(t.tickInterceptor!=null){const a=new Xi(this.pixiApp,t);this.spriteRenderers.set(t,a)}}else{const a=new Xi(this.pixiApp,t);this.spriteRenderers.set(t,a)}await this.updateFrame(this.currentTime),this.setupSpriteInteractivity(t)}setupSpriteInteractivity(t){if(this.interactiveClips.has(t))return;const e=this.spriteRenderers.get(t);if(e==null)return;const r=e.getSprite();r!=null&&(r.eventMode="static",r.cursor="pointer",r.on("pointerdown",n=>{n.stopPropagation(),this.selectClip(t,n.shiftKey)}),this.interactiveClips.add(t))}async setupPlaybackForClip(t,e){if(this.pixiApp!=null){if(!this.isPlaybackCapable(t)){if(this.pixiApp!=null&&(await t.ready).width>0&&(await t.ready).height>0){const r=new Xi(this.pixiApp,t);this.spriteRenderers.set(t,r)}return}try{const r=t;if(t instanceof pt&&e&&typeof e!="string"){const l=URL.createObjectURL(e);t.src=l}const{element:n,objectUrl:a}=await r.createPlaybackElement();if(t instanceof _t){const l=M.from(n),h=new te(l);h.visible=!1,this.pixiApp.stage.addChild(h),this.videoSprites.set(t,h)}this.playbackElements.set(t,{element:n,objectUrl:a})}catch(r){if(console.warn(`Failed to setup playback for ${t.constructor.name}, falling back to PixiSpriteRenderer:`,r),this.pixiApp!=null){const n=await t.ready;if(n.width>0&&n.height>0){const a=new Xi(this.pixiApp,t);this.spriteRenderers.set(t,a)}}}}}isPlaybackCapable(t){return"createPlaybackElement"in t&&"play"in t&&"pause"in t&&"seek"in t&&"syncPlayback"in t&&"cleanupPlayback"in t}async removeClip(t){const e=this.clips.findIndex(l=>l===t);if(e===-1)return;this.selectedClips.has(t)&&this.deselectClip(),this.clips.splice(e,1),this.interactiveClips.delete(t);const r=this.spriteRenderers.get(t);r!=null&&(r.destroy(),this.spriteRenderers.delete(t));const n=this.playbackElements.get(t);n!=null&&(this.isPlaybackCapable(t)&&t.cleanupPlayback(n.element,n.objectUrl),this.playbackElements.delete(t));const a=this.videoSprites.get(t);a!=null&&this.pixiApp!=null&&(this.pixiApp.stage.removeChild(a),a.destroy(),this.videoSprites.delete(t)),await this.recalculateMaxDuration()}clear(){this.deselectClip(),this.interactiveClips.clear(),this.spriteRenderers.forEach(t=>{t.destroy()}),this.spriteRenderers.clear();for(const[t,e]of this.playbackElements.entries())this.isPlaybackCapable(t)&&t.cleanupPlayback(e.element,e.objectUrl);if(this.playbackElements.clear(),this.videoSprites.clear(),this.clips=[],this.maxDuration=0,this.currentTime=0,this.pixiApp!=null){const t=this.pixiApp.stage.children.slice();for(const e of t)this.pixiApp.stage.removeChild(e),e.destroy()}}async play(){if(!(this.isPlaying||this.destroyed)){if(this.maxDuration<=0||this.maxDuration===1/0||isNaN(this.maxDuration)){console.warn("Cannot play: invalid duration",this.maxDuration);return}this.isPlaying=!0,this.playStartTime=this.currentTime,this.playStartTimestamp=performance.now();for(const[t,{element:e}]of this.playbackElements.entries()){if(!(this.currentTime>=t.display.from&&(t.display.to===0||this.currentTime<=t.display.to))){this.isPlaybackCapable(t)&&t.pause(e);continue}const n=(this.currentTime-t.display.from)/1e6;this.isPlaybackCapable(t)&&await t.play(e,n)}this.renderLoop()}}pause(){this.isPlaying=!1,this.rafId!=null&&(cancelAnimationFrame(this.rafId),this.rafId=null);for(const[t,{element:e}]of this.playbackElements.entries())this.isPlaybackCapable(t)&&t.pause(e)}async stop(){this.pause(),await this.seek(0)}async seek(t){if(this.destroyed)return;const e=this.isPlaying;this.playStartTime=Math.max(0,Math.min(t,this.maxDuration)),this.playStartTimestamp=performance.now(),this.currentTime=this.playStartTime;for(const[r,{element:n}]of this.playbackElements.entries()){if(!(this.currentTime>=r.display.from&&(r.display.to===0||this.currentTime<=r.display.to))){this.isPlaybackCapable(r)&&r.pause(n);continue}const l=(this.currentTime-r.display.from)/1e6;this.isPlaybackCapable(r)&&await r.seek(n,l)}if(await this.updateFrame(this.currentTime),e){this.isPlaying=!0;for(const[r,{element:n}]of this.playbackElements.entries()){if(!(this.currentTime>=r.display.from&&(r.display.to===0||this.currentTime<=r.display.to)))continue;const l=(this.currentTime-r.display.from)/1e6;this.isPlaybackCapable(r)&&await r.play(n,l)}}}getCurrentTime(){return this.currentTime}getMaxDuration(){return this.maxDuration===1/0||isNaN(this.maxDuration)||this.maxDuration<=0?0:this.maxDuration}getIsPlaying(){return this.isPlaying}async renderLoop(){if(!this.isPlaying||this.destroyed||this.pixiApp==null)return;if(this.maxDuration<=0||this.maxDuration===1/0||isNaN(this.maxDuration)){this.pause();return}const t=async()=>{if(!this.isPlaying||this.destroyed||this.pixiApp==null)return;if(this.currentTime>=this.maxDuration){this.currentTime=this.maxDuration,this.pause();return}const r=(performance.now()-this.playStartTimestamp)*1e3;this.currentTime=Math.min(this.playStartTime+r,this.maxDuration);try{await this.updateFrame(this.currentTime)}catch(n){console.warn("Error updating frame:",n)}this.isPlaying&&(this.rafId=requestAnimationFrame(t))};t()}async updateFrame(t){if(this.destroyed||this.pixiApp==null)return;const e=[...this.clips].sort((r,n)=>r.zIndex-n.zIndex);for(const r of e){if(t<r.display.from){const m=this.spriteRenderers.get(r);m!=null&&await m.updateFrame(null);continue}if(r.display.to>0&&t>r.display.to){const m=this.spriteRenderers.get(r);m!=null&&await m.updateFrame(null);continue}const n=t-r.display.from,a=n*r.playbackRate;r.animate(a);const l=await r.ready,h=r.duration||l.duration;if(h>0&&n>h){const m=this.spriteRenderers.get(r);m!=null&&await m.updateFrame(null);continue}const d=this.playbackElements.get(r);if(d!=null&&this.isPlaybackCapable(r)){const m=n/1e6;if(r.syncPlayback(d.element,this.isPlaying,m),r instanceof _t){const g=this.videoSprites.get(r);if(g!=null){const y=r.meta.duration/1e6;if(this.spriteRenderers.has(r))g.visible=!1;else{g.visible=m>=0&&m<y,g.visible&&mv(r,g);continue}}}else continue}const f=this.spriteRenderers.get(r);if(f!=null){const m=this.selectedClips.has(r);if(r instanceof Dt){const y=r.getTexture();if(y!=null){await f.updateFrame(y),m||f.updateTransforms();continue}}if(r instanceof Ue){const y=await r.getTexture();if(y!=null){await f.updateFrame(y),m||f.updateTransforms();continue}}if(r instanceof Be){r.updateState(n);const y=await r.getTexture();if(y!=null){await f.updateFrame(y),m||f.updateTransforms();continue}else console.log("[Studio] CaptionClip texture is null, falling back to traditional path")}const{video:g}=await r.getFrame(n);await f.updateFrame(g),m||f.updateTransforms()}}this.pixiApp!=null&&this.pixiApp.render()}async recalculateMaxDuration(){this.maxDuration=0;for(const t of this.clips){const e=await t.ready,r=t.duration>0?t.duration:e.duration,n=t.display.from+r;n!==1/0&&!isNaN(n)&&n>0&&(this.maxDuration=Math.max(this.maxDuration,n))}}destroy(){if(!this.destroyed&&(this.destroyed=!0,this.deselectClip(),this.pause(),this.clear(),this.pixiApp!=null))try{const t=this.pixiApp;if(t.ticker&&typeof t.ticker.stop=="function")try{t.ticker.stop()}catch{}if(t.renderer!=null)this.pixiApp.destroy(!0,{children:!0,texture:!0});else try{const e=t.view;e&&e.parentNode&&e.parentNode.removeChild(e)}catch{}}catch(t){console.warn("Error while destroying Pixi application:",t)}finally{this.pixiApp=null}}selectClip(t,e=!1){if(!(this.destroyed||this.pixiApp==null)){if(e||this.deselectClip(),e&&this.selectedClips.has(t)){this.selectedClips.delete(t),this.activeTransformer!=null&&(this.pixiApp.stage.removeChild(this.activeTransformer),this.activeTransformer.destroy(),this.activeTransformer=null),this.selectedClips.size>0&&this.createTransformer();return}this.selectedClips.add(t),this.activeTransformer!=null&&(this.pixiApp.stage.removeChild(this.activeTransformer),this.activeTransformer.destroy(),this.activeTransformer=null),this.createTransformer()}}createTransformer(){if(this.destroyed||this.pixiApp==null||this.selectedClips.size===0)return;const t=[];let e=null;for(const r of this.selectedClips){const n=this.spriteRenderers.get(r);if(n==null)continue;const a=n.getSprite();a!=null&&(t.push(a),this.selectedClips.size===1&&(e=r))}if(t.length===0){console.warn("Cannot create transformer: no sprites found");return}this.activeTransformer=new wv({group:t,clip:e}),this.activeTransformer.on("transformEnd",()=>{this.syncSelectedClipsTransforms()}),this.pixiApp.stage.addChild(this.activeTransformer)}syncSelectedClipsTransforms(){if(!(this.selectedClips.size===0||this.activeTransformer==null))for(const t of this.selectedClips){const e=this.spriteRenderers.get(t);if(e==null)continue;const r=e.getSprite();if(r==null||r.texture==null)continue;const n=r.texture.width,a=r.texture.height,l=Math.abs(r.scale.x)*n,h=Math.abs(r.scale.y)*a,d=r.x-l/2,f=r.y-h/2;t.left=d,t.top=f,t.width=l,t.height=h,t.angle=r.rotation}}deselectClip(){if(this.selectedClips.size>0&&this.activeTransformer!=null)for(const t of this.selectedClips){const e=this.spriteRenderers.get(t);if(e!=null){const r=e.getSprite();if(r!=null&&r.texture!=null){const n=r.texture.width,a=r.texture.height,l=Math.abs(r.scale.x)*n,h=Math.abs(r.scale.y)*a,d=r.x-l/2,f=r.y-h/2;t.left=d,t.top=f,t.width=l,t.height=h,t.angle=r.rotation,e.updateTransforms()}}}this.activeTransformer!=null&&(this.pixiApp!=null&&this.activeTransformer.parent!=null&&this.pixiApp.stage.removeChild(this.activeTransformer),this.activeTransformer.destroy(),this.activeTransformer=null),this.selectedClips.clear()}exportToJSON(){return{clips:this.clips.map(e=>ua(e,!1)),settings:{width:this.opts.width,height:this.opts.height,fps:this.opts.fps,bgColor:this.opts.bgColor}}}async loadFromJSON(t){this.clear(),t.settings&&(t.settings.width&&(this.opts.width=t.settings.width),t.settings.height&&(this.opts.height=t.settings.height),t.settings.fps&&(this.opts.fps=t.settings.fps),t.settings.bgColor&&(this.opts.bgColor=t.settings.bgColor));const e=[];for(const r of t.clips){if(r.type!=="Text"&&r.type!=="Caption"&&(!r.src||r.src.trim()==="")){e.push(r.type);continue}try{const n=await da(r),a=n instanceof pt?r.src:void 0;await this.addClip(n,a)}catch(n){console.warn(`Failed to load clip of type ${r.type}:`,n),e.push(r.type)}}e.length>0&&console.warn(`Skipped ${e.length} clip(s) that could not be loaded (empty source URLs or load errors):`,e)}}class ei{static instance;fonts=new Map;constructor(){}static getInstance(){return ei.instance||(ei.instance=new ei),ei.instance}async addFont(t){if(!this.fonts.has(t.name))try{const r=await new FontFace(t.name,`url(${t.url})`).load();document.fonts.add(r),this.fonts.set(t.name,r)}catch(e){console.error(`Failed to load font ${t.name}:`,e)}}async loadFonts(t){await Promise.all(t.map(e=>this.addFont(e)))}removeFont(t){const e=this.fonts.get(t);e&&(document.fonts.delete(e),this.fonts.delete(t))}clear(){this.fonts.forEach(t=>{document.fonts.delete(t)}),this.fonts.clear()}getLoadedFonts(){return Array.from(this.fonts.keys())}}const Tv=ei.getInstance();D.add(Bp),D.mixin(ot,Up),D.add(yh),D.add(xh),D.add(El),D.mixin(ot,ry),D.add(Cl),D.add(cu),D.add(yn),D.add(fu),D.add(yu),D.add(xu),D.add(Uu),D.add(Bu),D.add(Su),D.add(Au),D.add(Cu),D.add(wu),D.add(vu),D.add(Ul),D.add(Pl);const Cv=Object.freeze(Object.defineProperty({__proto__:null},Symbol.toStringTag,{value:"Module"})),Ev=Object.freeze(Object.defineProperty({__proto__:null},Symbol.toStringTag,{value:"Module"}));rt.AudioClip=pt,rt.CaptionClip=Be,rt.Compositor=_v,rt.ImageClip=Dt,rt.Log=H,rt.MP4Clip=_t,rt.Studio=Sv,rt.TextClip=Ue,rt.VideoClip=_t,rt.clipToJSON=ua,rt.createChromakey=df,rt.fastConcatMP4=Du,rt.fixFMP4Duration=cv,rt.fontManager=Tv,rt.jsonToClip=da,rt.mixinMP4AndAudio=pv,rt.renderTxt2ImgBitmap=gf,Object.defineProperty(rt,Symbol.toStringTag,{value:"Module"})}));
|
|
1293
|
+
}`}const lo=new Map;async function Yb(s){const t=s.filter(e=>Q.has(`${e}-and-url`)).map(e=>{if(!lo.has(e)){const{entries:r}=Q.get(`${e}-and-url`),n=[];r.forEach(o=>{const l=o.url,u=o.faces.map(f=>({weight:f.weight,style:f.style}));n.push(...u.map(f=>Vb({fontWeight:f.weight,fontStyle:f.style,fontFamily:e},l)))}),lo.set(e,Promise.all(n).then(o=>o.join(`
|
|
1294
|
+
`)))}return lo.get(e)});return(await Promise.all(t)).join(`
|
|
1295
|
+
`)}function Xb(s,t,e,r,n){const{domElement:o,styleElement:l,svgRoot:h}=n;o.innerHTML=`<style>${t.cssStyle}</style><div style='padding:0;'>${s}</div>`,o.setAttribute("style",`transform: scale(${e});transform-origin: top left; display: inline-block`),l.textContent=r;const{width:u,height:f}=n.image;return h.setAttribute("width",u.toString()),h.setAttribute("height",f.toString()),new XMLSerializer().serializeToString(h)}function $b(s,t){const e=ae.getOptimalCanvasAndContext(s.width,s.height,t),{context:r}=e;return r.clearRect(0,0,s.width,s.height),r.drawImage(s,0,0),e}function Kb(s,t,e){return new Promise(async r=>{e&&await new Promise(n=>setTimeout(n,100)),s.onload=()=>{r()},s.src=`data:image/svg+xml;charset=utf8,${encodeURIComponent(t)}`,s.crossOrigin="anonymous"})}class kd{constructor(t){this._activeTextures={},this._renderer=t,this._createCanvas=t.type===Nt.WEBGPU}getTexture(t){return this.getTexturePromise(t)}getManagedTexture(t){const e=t.styleKey;if(this._activeTextures[e])return this._increaseReferenceCount(e),this._activeTextures[e].promise;const r=this._buildTexturePromise(t).then(n=>(this._activeTextures[e].texture=n,n));return this._activeTextures[e]={texture:null,promise:r,usageCount:1},r}getReferenceCount(t){return this._activeTextures[t]?.usageCount??null}_increaseReferenceCount(t){this._activeTextures[t].usageCount++}decreaseReferenceCount(t){const e=this._activeTextures[t];e&&(e.usageCount--,e.usageCount===0&&(e.texture?this._cleanUp(e.texture):e.promise.then(r=>{e.texture=r,this._cleanUp(e.texture)}).catch(()=>{F("HTMLTextSystem: Failed to clean texture")}),this._activeTextures[t]=null))}getTexturePromise(t){return this._buildTexturePromise(t)}async _buildTexturePromise(t){const{text:e,style:r,resolution:n,textureStyle:o}=t,l=at.get(Vl),h=Hb(e,r),u=await Yb(h),f=Ay(e,r,u,l),m=Math.ceil(Math.ceil(Math.max(1,f.width)+r.padding*2)*n),g=Math.ceil(Math.ceil(Math.max(1,f.height)+r.padding*2)*n),y=l.image,x=2;y.width=(m|0)+x,y.height=(g|0)+x;const a=Xb(e,r,n,u,l);await Kb(y,a,zb()&&h.length>0);const c=y;let d;this._createCanvas&&(d=$b(y,n));const p=Ud(d?d.canvas:c,y.width-x,y.height-x,n);return o&&(p.source.style=o),this._createCanvas&&(this._renderer.texture.initSource(p.source),ae.returnCanvasAndContext(d)),at.return(l),p}returnTexturePromise(t){t.then(e=>{this._cleanUp(e)}).catch(()=>{F("HTMLTextSystem: Failed to clean texture")})}_cleanUp(t){dt.returnTexture(t,!0),t.source.resource=null,t.source.uploadMethodId="unknown"}destroy(){this._renderer=null;for(const t in this._activeTextures)this._activeTextures[t]&&this.returnTexturePromise(this._activeTextures[t].promise);this._activeTextures=null}}kd.extension={type:[C.WebGLSystem,C.WebGPUSystem,C.CanvasSystem],name:"htmlText"};class jb extends st{constructor(t){const{text:e,style:r,autoSplit:n,lineAnchor:o,wordAnchor:l,charAnchor:h,...u}=t;super(u),this._dirty=!1,this._canReuseChars=!1,this.chars=[],this.words=[],this.lines=[],this._originalText=e,this._autoSplit=n,this._lineAnchor=o,this._wordAnchor=l,this._charAnchor=h,this.style=r}split(){const t=this.splitFn();this.chars=t.chars,this.words=t.words,this.lines=t.lines,this.addChild(...this.lines),this.charAnchor=this._charAnchor,this.wordAnchor=this._wordAnchor,this.lineAnchor=this._lineAnchor,this._dirty=!1,this._canReuseChars=!0}get text(){return this._originalText}set text(t){this._originalText=t,this.lines.forEach(e=>e.destroy({children:!0})),this.lines.length=0,this.words.length=0,this.chars.length=0,this._canReuseChars=!1,this.onTextUpdate()}_setOrigin(t,e,r){let n;typeof t=="number"?n={x:t,y:t}:n={x:t.x,y:t.y},e.forEach(o=>{const l=o.getLocalBounds(),h=l.minX+l.width*n.x,u=l.minY+l.height*n.y;o.origin.set(h,u)}),this[r]=t}get lineAnchor(){return this._lineAnchor}set lineAnchor(t){this._setOrigin(t,this.lines,"_lineAnchor")}get wordAnchor(){return this._wordAnchor}set wordAnchor(t){this._setOrigin(t,this.words,"_wordAnchor")}get charAnchor(){return this._charAnchor}set charAnchor(t){this._setOrigin(t,this.chars,"_charAnchor")}get style(){return this._style}set style(t){t||(t={}),this._style=new bt(t),this.words.forEach(e=>e.destroy()),this.words.length=0,this.lines.forEach(e=>e.destroy()),this.lines.length=0,this._canReuseChars=!0,this.onTextUpdate()}onTextUpdate(){this._dirty=!0,this._autoSplit&&this.split()}destroy(t){super.destroy(t),this.chars=[],this.words=[],this.lines=[],(typeof t=="boolean"?t:t?.style)&&this._style.destroy(t),this._style=null,this._originalText=""}}const Md=class Zr extends jb{constructor(t){const e={...Zr.defaultOptions,...t};super(e)}static from(t,e){const r={...Zr.defaultOptions,...e,text:t.text,style:new bt(t.style)};return new Zr({...r})}splitFn(){return Gb({text:this._originalText,style:this._style,chars:this._canReuseChars?this.chars:[]})}};Md.defaultOptions={autoSplit:!0,lineAnchor:0,wordAnchor:0,charAnchor:0};let qb=Md;class Zb extends Vr{constructor(t){super(),this._renderer=t,t.runners.resolutionChange.add(this)}resolutionChange(){const t=this.renderable;t._autoResolution&&t.onViewUpdate()}destroy(){const{canvasText:t}=this._renderer;t.getReferenceCount(this.currentKey)>0?t.decreaseReferenceCount(this.currentKey):this.texture&&t.returnTexture(this.texture),this._renderer.runners.resolutionChange.remove(this),this._renderer=null}}class Rd{constructor(t){this._renderer=t}validateRenderable(t){const e=this._getGpuText(t),r=t.styleKey;return e.currentKey!==r?!0:t._didTextUpdate}addRenderable(t,e){const r=this._getGpuText(t);if(t._didTextUpdate){const n=t._autoResolution?this._renderer.resolution:t.resolution;(r.currentKey!==t.styleKey||t.resolution!==n)&&this._updateGpuText(t),t._didTextUpdate=!1,ho(r,t)}this._renderer.renderPipes.batch.addToBatch(r,e)}updateRenderable(t){const e=this._getGpuText(t);e._batcher.updateElement(e)}_updateGpuText(t){const e=this._getGpuText(t);e.texture&&this._renderer.canvasText.decreaseReferenceCount(e.currentKey),t._resolution=t._autoResolution?this._renderer.resolution:t.resolution,e.texture=this._renderer.canvasText.getManagedTexture(t),e.currentKey=t.styleKey}_getGpuText(t){return t._gpuData[this._renderer.uid]||this.initGpuText(t)}initGpuText(t){const e=new Zb(this._renderer);return e.currentKey="--",e.renderable=t,e.transform=t.groupTransform,e.bounds={minX:0,maxX:1,minY:0,maxY:0},e.roundPixels=this._renderer._roundPixels|t._roundPixels,t._gpuData[this._renderer.uid]=e,e}destroy(){this._renderer=null}}Rd.extension={type:[C.WebGLPipes,C.WebGPUPipes,C.CanvasPipes],name:"text"};class Id{constructor(t){this._activeTextures={},this._renderer=t}getTexture(t,e,r,n){typeof t=="string"&&(z("8.0.0","CanvasTextSystem.getTexture: Use object TextOptions instead of separate arguments"),t={text:t,style:r,resolution:e}),t.style instanceof bt||(t.style=new bt(t.style)),t.textureStyle instanceof jt||(t.textureStyle=new jt(t.textureStyle)),typeof t.text!="string"&&(t.text=t.text.toString());const{text:o,style:l,textureStyle:h}=t,u=t.resolution??this._renderer.resolution,{frame:f,canvasAndContext:m}=Ni.getCanvasAndContext({text:o,style:l,resolution:u}),g=Ud(m.canvas,f.width,f.height,u);if(h&&(g.source.style=h),l.trim&&(f.pad(l.padding),g.frame.copyFrom(f),g.frame.scale(1/u),g.updateUvs()),l.filters){const y=this._applyFilters(g,l.filters);return this.returnTexture(g),Ni.returnCanvasAndContext(m),y}return this._renderer.texture.initSource(g._source),Ni.returnCanvasAndContext(m),g}returnTexture(t){const e=t.source;e.resource=null,e.uploadMethodId="unknown",e.alphaMode="no-premultiply-alpha",dt.returnTexture(t,!0)}renderTextToCanvas(){z("8.10.0","CanvasTextSystem.renderTextToCanvas: no longer supported, use CanvasTextSystem.getTexture instead")}getManagedTexture(t){t._resolution=t._autoResolution?this._renderer.resolution:t.resolution;const e=t.styleKey;if(this._activeTextures[e])return this._increaseReferenceCount(e),this._activeTextures[e].texture;const r=this.getTexture({text:t.text,style:t.style,resolution:t._resolution,textureStyle:t.textureStyle});return this._activeTextures[e]={texture:r,usageCount:1},r}decreaseReferenceCount(t){const e=this._activeTextures[t];e.usageCount--,e.usageCount===0&&(this.returnTexture(e.texture),this._activeTextures[t]=null)}getReferenceCount(t){return this._activeTextures[t]?.usageCount??0}_increaseReferenceCount(t){this._activeTextures[t].usageCount++}_applyFilters(t,e){const r=this._renderer.renderTarget.renderTarget,n=this._renderer.filter.generateFilteredTexture({texture:t,filters:e});return this._renderer.renderTarget.bind(r,!1),n}destroy(){this._renderer=null;for(const t in this._activeTextures)this._activeTextures[t]&&this.returnTexture(this._activeTextures[t].texture);this._activeTextures=null}}Id.extension={type:[C.WebGLSystem,C.WebGPUSystem,C.CanvasSystem],name:"canvasText"},D.add(kf,Mf);function wt(s){if(s!=null){if(typeof s=="number")return s;if(typeof s=="string"){if(s.startsWith("#")){const e=parseInt(s.slice(1),16);if(!isNaN(e))return e}if(s.startsWith("0x")){const e=parseInt(s,16);if(!isNaN(e))return e}const t=parseInt(s,16);if(!isNaN(t))return t;try{return new J(s).toNumber()}catch{return}}}}class Ue extends ci{ready;_meta={duration:1/0,width:0,height:0};get meta(){return{...this._meta}}text;get style(){if(!this.originalOpts)return{};const t=this.originalOpts;return{fontSize:t.fontSize,fontFamily:t.fontFamily,fontWeight:t.fontWeight,fontStyle:t.fontStyle,color:t.fill,align:t.align,stroke:t.stroke?typeof t.stroke=="object"?{color:t.stroke.color,width:t.stroke.width}:{color:t.stroke,width:t.strokeWidth??0}:void 0,shadow:t.dropShadow?{color:t.dropShadow.color??"#000000",alpha:t.dropShadow.alpha??.5,blur:t.dropShadow.blur??4,offsetX:t.dropShadow.distance?Math.cos((t.dropShadow.angle??0)*Math.PI/180)*t.dropShadow.distance:0,offsetY:t.dropShadow.distance?Math.sin((t.dropShadow.angle??0)*Math.PI/180)*t.dropShadow.distance:0}:void 0}}bottomOffset;opts;pixiTextContainer=null;renderTexture=null;wordTexts=[];extraPadding=0;textStyle;externalRenderer=null;pixiApp=null;originalOpts=null;constructor(t,e={},r){super(),this.text=t,this.originalOpts={...e},this.externalRenderer=r??null,this.opts={fontSize:e.fontSize??30,fontFamily:e.fontFamily??"Arial",fontUrl:e.fontUrl??"",fontWeight:e.fontWeight??"normal",fontStyle:e.fontStyle??"normal",fill:e.fill??"#ffffff",strokeWidth:e.strokeWidth??0,align:e.align??"center",wordWrapWidth:e.wordWrapWidth??0,wordWrap:e.wordWrap??!1,lineHeight:e.lineHeight??1,letterSpacing:e.letterSpacing??0,videoWidth:e.caption?.positioning?.videoWidth??e.videoWidth??1280,videoHeight:e.caption?.positioning?.videoHeight??e.videoHeight??720,bottomOffset:e.caption?.positioning?.bottomOffset??e.bottomOffset??30,keyword:e.caption?.colors?.keyword??e.colors?.keyword??"#ffff00",background:e.caption?.colors?.background??e.colors?.background??"#000000",active:e.caption?.colors?.active??e.colors?.active??"#ffffff",activeFill:e.caption?.colors?.activeFill??e.colors?.activeFill??"#00ff00",appeared:e.caption?.colors?.appeared??e.colors?.appeared??"#ffffff",words:e.caption?.words??e.words??[],preserveKeywordColor:e.caption?.preserveKeywordColor??e.preserveKeywordColor??!1};const n={fontSize:this.opts.fontSize,fontFamily:this.opts.fontFamily,fontWeight:this.opts.fontWeight,fontStyle:this.opts.fontStyle,align:this.opts.align};if(e.fill&&typeof e.fill=="object"&&e.fill.type==="gradient"){const h=new Vt(e.fill.x0,e.fill.y0,e.fill.x1,e.fill.y1);e.fill.colors.forEach(({ratio:u,color:f})=>{const m=typeof f=="number"?f:wt(f)??16777215;h.addColorStop(u,m)}),n.fill={fill:h}}else{const h=typeof e.fill=="string"||typeof e.fill=="number"?wt(e.fill):void 0;n.fill=h??16777215}if(e.stroke&&typeof e.stroke=="object"&&"color"in e.stroke){const h=wt(e.stroke.color);h!==void 0&&(n.stroke={color:h,width:e.stroke.width},e.stroke.join&&(n.stroke.join=e.stroke.join))}else{const h=wt(e.stroke);h!==void 0?n.stroke={color:h,width:this.opts.strokeWidth??0}:this.opts.strokeWidth&&this.opts.strokeWidth>0&&(n.stroke={color:0,width:this.opts.strokeWidth})}if(e.dropShadow){const h=wt(e.dropShadow.color);h!==void 0&&(n.dropShadow={color:h,alpha:e.dropShadow.alpha??.5,blur:e.dropShadow.blur??4,angle:e.dropShadow.angle??Math.PI/6,distance:e.dropShadow.distance??2})}const o=new bt(n),l=new bt({...n,fontFamily:"Arial"});this.textStyle=o,this.ready=(async()=>{this.pixiTextContainer=new st;let h=0,u=0,f=0;this.wordTexts=this.opts.words.map(w=>{const S=new qb({text:w.text,style:o});S.x=h,S.y=0;const T=S.getLocalBounds(),E=Math.ceil(T.width||S.width),P=Math.ceil(T.height||S.height);u=Math.max(u,P),h+=E+5,f=h-5,this.pixiTextContainer.addChild(S);const B=wt(this.opts.fill);return S.tint=B??16777215,S});const m=f,g=u,y=new Zt;y.label="containerBackground";const x=wt(this.opts.background)||0,a=15,c=10,d=1;y.roundRect(0,0,m+a*2,g+a*2,c),y.fill({color:x,alpha:d}),this.wordTexts.forEach(w=>{const S=xt.measureText(w.text,this.textStyle),T=xt.measureText(w.text,l),E=S.fontProperties.descent,P=T.fontProperties.descent;this.extraPadding=P-E,w.pivot.y=0,w.pivot.x=0,w.y=a-this.extraPadding,w.x+=a}),this.pixiTextContainer.addChildAt(y,0),this.renderTexture=Vi.create({width:m+a*2,height:g+a*2}),this._meta.width=m+a*2,this._meta.height=g+a*2,this._meta.duration=1/0;const p=e.videoWidth??1280,_=e.videoHeight??720,b=e.bottomOffset??30;this.width=this.width===0?this._meta.width:this.width,this.height=this.height===0?this._meta.height:this.height,this.top=_-this.height-b,this.left=(p-this.width)/2;const v={...this._meta};return this.duration===0&&v.duration!==1/0&&(this.duration=v.duration,this.display.to=this.display.from+this.duration),H.info("CaptionClip ready:",v),v})()}lastLoggedTime=-1;updateState(t){const e=t/1e3,r=Math.floor(t/1e6);r!==this.lastLoggedTime&&(this.lastLoggedTime=r),this.opts.words.forEach((n,o)=>{const l=e>=n.from&&e<=n.to,h=e>n.to;let u;n.isKeyWord&&l?u=wt(this.opts.keyword):l?u=wt(this.opts.active):h&&this.opts.preserveKeywordColor&&n.isKeyWord?u=wt(this.opts.keyword):h?u=wt(this.opts.appeared):u=wt(this.opts.fill);const f=this.wordTexts[o];if(f){f.children.forEach(g=>{g.label!=="bgRect"&&(g.tint=u??16777215)});const m=f.getChildByLabel("bgRect");if(l)if(m){m.tint=16777215;const g=wt(this.opts.activeFill)||16753920;m.clear();const y=10,x=f.getLocalBounds();m.roundRect(x.x-y/2,x.y-y/2+this.extraPadding,x.width+y,x.height+y,16),m.fill(g)}else{const g=new Zt;g.label="bgRect";const y=10,x=f.getLocalBounds(),a=10,c=wt(this.opts.activeFill)||16753920;g.roundRect(x.x-y/2,x.y-y/2+this.extraPadding,x.width+y,x.height+y,a),g.fill(c),g.tint=16777215,f.addChildAt(g,0)}else m&&f.removeChild(m)}else console.log(`¡WARNING: SplitBitmapText was not found for word "${n.text}"!`)})}async getTexture(){if(this.pixiTextContainer==null||this.renderTexture==null)return console.log("[CaptionClip] getTexture returning null - container or texture not ready"),null;try{return(await this.getRenderer()).render({container:this.pixiTextContainer,target:this.renderTexture}),this.renderTexture}catch(t){return console.error("[CaptionClip] Error in getTexture:",t),null}}setRenderer(t){this.externalRenderer=t}async getRenderer(){if(this.externalRenderer!=null)return this.externalRenderer;if(this.pixiApp?.renderer==null)throw new Error("CaptionClip: No renderer available. Provide a renderer via setRenderer().");return this.pixiApp.renderer}async tick(t){if(await this.ready,this.pixiTextContainer==null||this.renderTexture==null)throw new Error("CaptionClip not initialized");this.updateState(t);const e=await this.getRenderer();e.render({container:this.pixiTextContainer,target:this.renderTexture});const r=this.renderTexture.source?.resource?.source;let n;if(r instanceof HTMLCanvasElement)n=await createImageBitmap(r);else if(r instanceof OffscreenCanvas)n=await createImageBitmap(r);else{const l=e.extract.canvas(this.renderTexture);if(l instanceof HTMLCanvasElement||l instanceof OffscreenCanvas)n=await createImageBitmap(l);else throw new Error("Unable to extract canvas from render texture")}return{video:n,state:"success"}}async split(t){await this.ready;const e=await this.clone(),r=await this.clone();return[e,r]}async clone(){await this.ready;const t=this.originalOpts||{},e=new Ue(this.text,t);return this.copyStateTo(e),e}destroy(){if(!this.destroyed){H.info("CaptionClip destroy");try{this.wordTexts.forEach(t=>{t!=null&&!t.destroyed&&t.destroy({children:!0})})}catch{}finally{this.wordTexts=[]}try{this.pixiTextContainer!=null&&this.pixiTextContainer.destroyed!==!0&&this.pixiTextContainer.destroy({children:!0})}catch{}finally{this.pixiTextContainer=null}try{this.renderTexture!=null&&this.renderTexture.destroyed!==!0&&this.renderTexture.destroy(!0)}catch{}finally{this.renderTexture=null}if(this.externalRenderer=null,this.pixiApp!=null)try{const t=this.pixiApp;t.destroyed!==!0&&t.renderer!=null&&this.pixiApp.destroy(!0,{children:!0,texture:!0})}catch{}finally{this.pixiApp=null}super.destroy()}}toJSON(t=!1){const e=super.toJSON(t),r={};if(this.originalOpts){const g=this.originalOpts;if(g.fontSize!==void 0&&(r.fontSize=g.fontSize),g.fontFamily!==void 0&&(r.fontFamily=g.fontFamily),g.fontWeight!==void 0&&(r.fontWeight=g.fontWeight),g.fontStyle!==void 0&&(r.fontStyle=g.fontStyle),g.fill!==void 0&&(r.color=g.fill),g.align!==void 0&&(r.align=g.align),g.fontUrl!==void 0&&(r.fontUrl=g.fontUrl),g.stroke&&(typeof g.stroke=="object"?r.stroke={color:g.stroke.color,width:g.stroke.width}:r.stroke={color:g.stroke,width:g.strokeWidth??0}),g.dropShadow){const y=g.dropShadow;r.shadow={color:y.color??"#000000",alpha:y.alpha??.5,blur:y.blur??4,offsetX:y.distance?Math.cos((y.angle??0)*Math.PI/180)*y.distance:0,offsetY:y.distance?Math.sin((y.angle??0)*Math.PI/180)*y.distance:0}}}const n={};this.opts.words&&this.opts.words.length>0&&(n.words=this.opts.words);const o={},l=this.originalOpts?.caption?.colors??this.originalOpts?.colors;l?.appeared!==void 0&&(o.appeared=l.appeared),l?.active!==void 0&&(o.active=l.active),l?.activeFill!==void 0&&(o.activeFill=l.activeFill),l?.background!==void 0&&(o.background=l.background),l?.keyword!==void 0&&(o.keyword=l.keyword);let h;this.originalOpts?.caption?.preserveKeywordColor!==void 0?h=this.originalOpts.caption.preserveKeywordColor:this.originalOpts?.preserveKeywordColor!==void 0&&(h=this.originalOpts.preserveKeywordColor),Object.keys(o).length>0&&(n.colors=o),h!==void 0&&(n.preserveKeywordColor=h);const u={};this.bottomOffset!==void 0&&(u.bottomOffset=this.bottomOffset);const f=this.originalOpts?.caption?.positioning?.videoWidth??this.originalOpts?.videoWidth,m=this.originalOpts?.caption?.positioning?.videoHeight??this.originalOpts?.videoHeight;return f!==void 0&&(u.videoWidth=f),m!==void 0&&(u.videoHeight=m),Object.keys(u).length>0&&(n.positioning=u),{...e,type:"Caption",text:this.text,style:r,caption:Object.keys(n).length>0?n:void 0}}static async fromObject(t){if(t.type!=="Caption")throw new Error(`Expected Caption, got ${t.type}`);const e=t.text||"",r=t.style||{},n={};if(r.fontSize!==void 0&&(n.fontSize=r.fontSize),r.fontFamily!==void 0&&(n.fontFamily=r.fontFamily),r.fontWeight!==void 0&&(n.fontWeight=r.fontWeight),r.fontStyle!==void 0&&(n.fontStyle=r.fontStyle),r.color!==void 0&&(n.fill=r.color),r.align!==void 0&&(n.align=r.align),r.fontUrl!==void 0?n.fontUrl=r.fontUrl:t.fontUrl!==void 0&&(n.fontUrl=t.fontUrl),r.stroke&&(n.stroke=r.stroke.color,n.strokeWidth=r.stroke.width),r.shadow){const l=Math.sqrt(r.shadow.offsetX**2+r.shadow.offsetY**2),h=Math.atan2(r.shadow.offsetY,r.shadow.offsetX)*180/Math.PI;n.dropShadow={color:r.shadow.color,alpha:r.shadow.alpha,blur:r.shadow.blur,distance:l,angle:h}}t.caption?n.caption=t.caption:(t.bottomOffset!==void 0&&(n.bottomOffset=t.bottomOffset),t.words!==void 0&&(n.words=t.words),(t.appearedColor!==void 0||t.activeColor!==void 0||t.activeFillColor!==void 0||t.backgroundColor!==void 0||t.isKeyWordColor!==void 0)&&(n.colors={},t.appearedColor!==void 0&&(n.colors.appeared=t.appearedColor),t.activeColor!==void 0&&(n.colors.active=t.activeColor),t.activeFillColor!==void 0&&(n.colors.activeFill=t.activeFillColor),t.backgroundColor!==void 0&&(n.colors.background=t.backgroundColor),t.isKeyWordColor!==void 0&&(n.colors.keyword=t.isKeyWordColor)),t.preservedColorKeyWord!==void 0&&(n.preserveKeywordColor=t.preservedColorKeyWord),t.videoWidth!==void 0&&(n.videoWidth=t.videoWidth),t.videoHeight!==void 0&&(n.videoHeight=t.videoHeight));const o=new Ue(e,n);return o.left=t.left,o.top=t.top,o.width=t.width,o.height=t.height,o.angle=t.angle,o.display.from=t.display.from,o.display.to=t.display.to,o.duration=t.duration,o.playbackRate=t.playbackRate,o.zIndex=t.zIndex,o.opacity=t.opacity,o.flip=t.flip,t.animation&&o.setAnimation(t.animation.keyFrames,t.animation.opts),await o.ready,o}}class Ut extends ci{ready;_meta={duration:0,width:0,height:0};get meta(){return{...this._meta}}img=null;pixiTexture=null;frames=[];static async fromUrl(t,e){const r=await Li.load(t),n=r.source?.resource?.source;let o;try{if(n instanceof HTMLCanvasElement||n instanceof OffscreenCanvas)o=await createImageBitmap(n);else if(n instanceof HTMLImageElement){const h=new OffscreenCanvas(n.width,n.height),u=h.getContext("2d");if(u==null)throw new Error("Failed to create 2d context");u.drawImage(n,0,0),o=await createImageBitmap(h)}else if(n instanceof ImageBitmap)o=await createImageBitmap(n);else{const h=await fetch(t);if(!h.ok)throw new Error(`Failed to fetch image: ${h.status} ${h.statusText}`);const u=await h.blob();o=await createImageBitmap(u)}}catch{const u=await fetch(t);if(!u.ok)throw new Error(`Failed to fetch image: ${u.status} ${u.statusText}`);const f=await u.blob();o=await createImageBitmap(f)}const l=new Ut(o,e||t);return l.pixiTexture=r,l}getTexture(){return this.pixiTexture}constructor(t,e){super(),this.src=e!==void 0?e:"";const r=n=>{this.img=n,this._meta.width=n.width,this._meta.height=n.height,this._meta.duration=1/0;const o={...this._meta};return this.width=this.width===0?o.width:this.width,this.height=this.height===0?o.height:this.height,this.duration===0&&o.duration!==1/0&&(this.duration=o.duration,this.display.to=this.display.from+this.duration),o};if(t instanceof ReadableStream)this.ready=new Response(t).blob().then(n=>createImageBitmap(n)).then(r);else if(t instanceof ImageBitmap)this.ready=Promise.resolve(r(t));else if(Array.isArray(t)&&t.every(n=>n instanceof VideoFrame)){this.frames=t;const n=this.frames[0];if(n==null)throw Error("The frame count must be greater than 0");this._meta={width:n.displayWidth,height:n.displayHeight,duration:this.frames.reduce((l,h)=>l+(h.duration??0),0)};const o={...this._meta,duration:1/0};this.width=this.width===0?o.width:this.width,this.height=this.height===0?o.height:this.height,this.duration===0&&o.duration!==1/0&&(this.duration=o.duration,this.display.to=this.display.from+this.duration),this.ready=Promise.resolve(o)}else if("type"in t)this.ready=this.initAnimateImg(t.stream,t.type).then(()=>{const n={width:this._meta.width,height:this._meta.height,duration:1/0};return this.width=this.width===0?n.width:this.width,this.height=this.height===0?n.height:this.height,this.duration===0&&n.duration!==1/0&&(this.duration=n.duration,this.display.to=this.display.from+this.duration),n});else throw Error("Illegal arguments")}async initAnimateImg(t,e){this.frames=await Ef(t,e);const r=this.frames[0];if(r==null)throw Error("No frame available in gif");this._meta={duration:this.frames.reduce((n,o)=>n+(o.duration??0),0),width:r.codedWidth,height:r.codedHeight},H.info("ImageClip ready:",this._meta)}tickInterceptor=async(t,e)=>e;async tick(t){if(this.img!=null)return await this.tickInterceptor(t,{video:await createImageBitmap(this.img),state:"success"});const e=t%this._meta.duration;return await this.tickInterceptor(t,{video:(this.frames.find(r=>e>=r.timestamp&&e<=r.timestamp+(r.duration??0))??this.frames[0]).clone(),state:"success"})}async split(t){if(await this.ready,this.img!=null)return[new Ut(await createImageBitmap(this.img),this.src),new Ut(await createImageBitmap(this.img),this.src)];let e=-1;for(let o=0;o<this.frames.length;o++){const l=this.frames[o];if(!(t>l.timestamp)){e=o;break}}if(e===-1)throw Error("Not found frame by time");const r=this.frames.slice(0,e).map(o=>new VideoFrame(o)),n=this.frames.slice(e).map(o=>new VideoFrame(o,{timestamp:o.timestamp-t}));return[new Ut(r,this.src),new Ut(n,this.src)]}async clone(){await this.ready;const t=this.img==null?this.frames.map(r=>r.clone()):await createImageBitmap(this.img),e=new Ut(t,this.src);return e.tickInterceptor=this.tickInterceptor,this.copyStateTo(e),e}destroy(){H.info("ImageClip destroy"),this.img?.close(),this.frames.forEach(t=>t.close()),this.pixiTexture=null,super.destroy()}toJSON(t=!1){return{...super.toJSON(t),type:"Image"}}static async fromObject(t){if(t.type!=="Image")throw new Error(`Expected Image, got ${t.type}`);if(!t.src||t.src.trim()==="")throw new Error("ImageClip requires a valid source URL. Generated clips (like text-to-image) cannot be loaded from JSON without their source data.");let e;try{const r=await fetch(t.src);if(!r.ok)throw new Error(`Failed to fetch image from ${t.src}: ${r.status} ${r.statusText}. Make sure the file exists in the public directory.`);const n=await r.blob();if(!n.type.startsWith("image/"))throw new Error(`Invalid image format: ${n.type}. Expected an image file.`);e=new Ut(await createImageBitmap(n),t.src)}catch(r){throw r instanceof Error&&r.message.includes("could not be decoded")?new Error(`Failed to decode image from ${t.src}. The image may be corrupted, in an unsupported format, or there may be CORS issues.`):r}return await e.ready,e.left=t.left,e.top=t.top,e.width=t.width,e.height=t.height,e.angle=t.angle,e.display.from=t.display.from,e.display.to=t.display.to,e.duration=t.duration,e.playbackRate=t.playbackRate,e.zIndex=t.zIndex,e.opacity=t.opacity,e.flip=t.flip,t.animation&&e.setAnimation(t.animation.keyFrames,t.animation.opts),e}async scaleToFit(t,e){await this.ready;const{width:r,height:n}=this.meta;if(r===0||n===0)return;const o=Math.min(t/r,e/n);this.width=r*o,this.height=n*o}async scaleToFill(t,e){await this.ready;const{width:r,height:n}=this.meta;if(r===0||n===0)return;const o=Math.max(t/r,e/n);this.width=r*o,this.height=n*o}centerInScene(t,e){this.left=(t-this.width)/2,this.top=(e-this.height)/2}}function co(s,t){const e=t.videoTracks[0],r={};if(e!=null){const o=Qb(s.getTrackById(e.id))?.buffer,{descKey:l,type:h}=e.codec.startsWith("avc1")?{descKey:"avcDecoderConfigRecord",type:"avc1"}:e.codec.startsWith("hvc1")?{descKey:"hevcDecoderConfigRecord",type:"hvc1"}:{descKey:"",type:""};l!==""&&(r.videoTrackConf={timescale:e.timescale,duration:e.duration,width:e.video.width,height:e.video.height,brands:t.brands,type:h,[l]:o}),r.videoDecoderConf={codec:e.codec,codedHeight:e.video.height,codedWidth:e.video.width,description:o}}const n=t.audioTracks[0];if(n!=null){const o=Jb(s),l=o==null?{}:tv(o);r.audioTrackConf={timescale:n.timescale,samplerate:l.sampleRate??n.audio.sample_rate,channel_count:l.numberOfChannels??n.audio.channel_count,hdlr:"soun",type:n.codec.startsWith("mp4a")?"mp4a":n.codec,description:o},r.audioDecoderConf={codec:l.codec??tt.codec,numberOfChannels:l.numberOfChannels??n.audio.channel_count,sampleRate:l.sampleRate??n.audio.sample_rate}}return r}function Qb(s){for(const t of s.mdia.minf.stbl.stsd.entries){const e=t.avcC??t.hvcC??t.av1C??t.vpcC;if(e!=null){const r=new yt.DataStream(void 0,0,yt.DataStream.BIG_ENDIAN);return e.write(r),new Uint8Array(r.buffer.slice(8))}}}function Jb(s,t="mp4a"){return s.moov?.traks.map(r=>r.mdia.minf.stbl.stsd.entries).flat().find(({type:r})=>r===t)?.esds}function tv(s){let t="mp4a";const e=s.esd.descs[0];if(e==null)return{};t+="."+e.oti.toString(16);const r=e.descs[0];if(r==null)return t.endsWith("40")&&(t+=".2"),{codec:t};const n=(r.data[0]&248)>>3;t+="."+n;const[o,l]=r.data,h=((o&7)<<1)+(l>>7),u=(l&127)>>3;return{codec:t,sampleRate:[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350][h],numberOfChannels:u}}async function ev(s,t,e){const r=yt.createFile(!1);r.onReady=o=>{t({mp4boxFile:r,info:o});const l=o.videoTracks[0]?.id;l!=null&&r.setExtractionOptions(l,"video",{nbSamples:100});const h=o.audioTracks[0]?.id;h!=null&&r.setExtractionOptions(h,"audio",{nbSamples:100}),r.start()},r.onSamples=e,await n();async function n(){let o=0;const l=30*1024*1024;for(;;){const h=await s.read(l,{at:o});if(h.byteLength===0)break;h.fileStart=o;const u=r.appendBuffer(h);if(u==null)break;o=u}r.stop()}}function iv(s){if(s?.length!==9)return{};const t=new Int32Array(s.buffer),e=t[0]/65536,r=t[1]/65536,n=t[3]/65536,o=t[4]/65536,l=t[6]/65536,h=t[7]/65536,u=t[8]/(1<<30),f=Math.sqrt(e*e+n*n),m=Math.sqrt(r*r+o*o),g=Math.atan2(n,e),y=g*180/Math.PI;return{scaleX:f,scaleY:m,rotationRad:g,rotationDeg:y,translateX:l,translateY:h,perspective:u}}function rv(s,t,e){const r=(Math.round(e/90)*90+360)%360;if(r===0)return u=>u;const n=r===90||r===270?t:s,o=r===90||r===270?s:t,l=new OffscreenCanvas(n,o),h=l.getContext("2d");return h.translate(n/2,o/2),h.rotate(-r*Math.PI/180),h.translate(-s/2,-t/2),u=>{if(u==null)return null;h.drawImage(u,0,0);const f=new VideoFrame(l,{timestamp:u.timestamp,duration:u.duration??void 0});return u.close(),f}}let uo=0;function fo(s){return s.kind==="file"&&s.createReader instanceof Function}class ft extends ci{insId=uo++;logger=H.create(`VideoClip id:${this.insId},`);ready;_meta={duration:0,width:0,height:0,audioSampleRate:0,audioChanCount:0};get meta(){return{...this._meta}}localFile;headerBoxPos=[];async getFileHeaderBinData(){await this.ready;const t=await this.localFile.getOriginFile();if(t==null)throw Error("VideoClip localFile is not origin file");return await new Blob(this.headerBoxPos.map(({start:e,size:r})=>t.slice(e,e+r))).arrayBuffer()}parsedMatrix={perspective:1,rotationRad:0,rotationDeg:0,scaleX:1,scaleY:1,translateX:0,translateY:0};vfRotater=t=>t;volume=1;videoSamples=[];audioSamples=[];videoFrameFinder=null;audioFrameFinder=null;decoderConf={video:null,audio:null};opts={audio:!0};audio=!0;static async fromUrl(t,e={}){const r=await fetch(t);if(!r.ok)throw new Error(`Failed to fetch video from ${t}: ${r.status} ${r.statusText}`);const n=new ft(r.body,{},t);return await n.ready,e.x!==void 0&&(n.left=e.x),e.y!==void 0&&(n.top=e.y),e.width!==void 0&&(n.width=e.width),e.height!==void 0&&(n.height=e.height),n}constructor(t,e={},r){if(super(),this.src=r!==void 0?r:"",!(t instanceof ReadableStream)&&!fo(t)&&!Array.isArray(t.videoSamples))throw Error("Illegal argument");this.opts={audio:!0,...e},this.audio=typeof this.opts.audio=="boolean"?this.opts.audio:!0,this.volume=typeof e.audio=="object"&&"volume"in e.audio?e.audio.volume:1;const n=async o=>(await oi(this.localFile,o),this.localFile);this.localFile=fo(t)?t:"localFile"in t?t.localFile:ns(),this.ready=(t instanceof ReadableStream?n(t).then(o=>Fd(o,this.opts)):fo(t)?Fd(t,this.opts):Promise.resolve(t)).then(async({videoSamples:o,audioSamples:l,decoderConf:h,headerBoxPos:u,parsedMatrix:f})=>{this.videoSamples=o,this.audioSamples=l,this.decoderConf=h,this.headerBoxPos=u,this.parsedMatrix=f;const{videoFrameFinder:m,audioFrameFinder:g}=nv({video:h.video==null?null:{...h.video,hardwareAcceleration:this.opts.__unsafe_hardwareAcceleration__},audio:h.audio},await this.localFile.createReader(),o,l,this.opts.audio!==!1?this.volume:0);this.videoFrameFinder=m,this.audioFrameFinder=g;const{codedWidth:y,codedHeight:x}=h.video??{};y&&x&&(this.vfRotater=rv(y,x,f.rotationDeg)),this._meta=sv(h,o,l,f.rotationDeg),this.logger.info("VideoClip meta:",this._meta);const a={...this._meta};return this.width=this.width===0?a.width:this.width,this.height=this.height===0?a.height:this.height,this.duration=this.duration===0?a.duration:this.duration,this.display.to=this.display.from+this.duration,a})}tickInterceptor=async(t,e)=>e;async tick(t){if(t>=this._meta.duration)return await this.tickInterceptor(t,{audio:await this.audioFrameFinder?.find(t)??[],state:"done"});const[e,r]=await Promise.all([this.audioFrameFinder?.find(t)??[],this.videoFrameFinder?.find(t).then(this.vfRotater)]);return r==null?await this.tickInterceptor(t,{audio:e,state:"success"}):await this.tickInterceptor(t,{video:r,audio:e,state:"success"})}async split(t){if(await this.ready,t<=0||t>=this._meta.duration)throw Error('"time" out of bounds');const[e,r]=uv(this.videoSamples,t),[n,o]=fv(this.audioSamples,t),l=new ft({localFile:this.localFile,videoSamples:e??[],audioSamples:n??[],decoderConf:this.decoderConf,headerBoxPos:this.headerBoxPos,parsedMatrix:this.parsedMatrix},this.opts,this.src),h=new ft({localFile:this.localFile,videoSamples:r??[],audioSamples:o??[],decoderConf:this.decoderConf,headerBoxPos:this.headerBoxPos,parsedMatrix:this.parsedMatrix},this.opts,this.src);return await Promise.all([l.ready,h.ready]),[l,h]}async clone(){await this.ready;const t=new ft({localFile:this.localFile,videoSamples:[...this.videoSamples],audioSamples:[...this.audioSamples],decoderConf:this.decoderConf,headerBoxPos:this.headerBoxPos,parsedMatrix:this.parsedMatrix},this.opts,this.src);return await t.ready,t.tickInterceptor=this.tickInterceptor,this.copyStateTo(t),t}async splitTrack(){await this.ready;const t=[];if(this.videoSamples.length>0){const e=new ft({localFile:this.localFile,videoSamples:[...this.videoSamples],audioSamples:[],decoderConf:{video:this.decoderConf.video,audio:null},headerBoxPos:this.headerBoxPos,parsedMatrix:this.parsedMatrix},this.opts,this.src);await e.ready,e.tickInterceptor=this.tickInterceptor,t.push(e)}if(this.audioSamples.length>0){const e=new ft({localFile:this.localFile,videoSamples:[],audioSamples:[...this.audioSamples],decoderConf:{audio:this.decoderConf.audio,video:null},headerBoxPos:this.headerBoxPos,parsedMatrix:this.parsedMatrix},this.opts,this.src);await e.ready,e.tickInterceptor=this.tickInterceptor,t.push(e)}return t}destroy(){this.destroyed||(this.destroyed=!0,this.logger.info("VideoClip destroy"),super.destroy(),this.videoFrameFinder?.destroy(),this.audioFrameFinder?.destroy())}toJSON(t=!1){return{...super.toJSON(t),type:"Video",audio:this.audio}}static async fromObject(t){if(t.type!=="Video")throw new Error(`Expected Video, got ${t.type}`);const e=await fetch(t.src);if(!e.ok)throw new Error(`Failed to fetch video from ${t.src}: ${e.status} ${e.statusText}. Make sure the file exists in the public directory.`);const r=t.audio!==void 0?{audio:t.audio}:{},n=new ft(e.body,r,t.src);return await n.ready,n.left=t.left,n.top=t.top,n.width=t.width,n.height=t.height,n.angle=t.angle,n.display.from=t.display.from,n.display.to=t.display.to,n.duration=t.duration,n.playbackRate=t.playbackRate,n.zIndex=t.zIndex,n.opacity=t.opacity,n.flip=t.flip,t.animation&&n.setAnimation(t.animation.keyFrames,t.animation.opts),n}async createPlaybackElement(){await this.ready;const e=this.localFile;if(!e||typeof e.getOriginFile!="function")throw new Error("VideoClip does not have a local file for playback");const r=await e.getOriginFile();if(!r)throw new Error("Failed to get origin file from VideoClip");const n=URL.createObjectURL(r),o=document.createElement("video");return o.crossOrigin="anonymous",o.muted=!0,o.autoplay=!1,o.playsInline=!0,o.preload="auto",o.loop=!1,o.src=n,await new Promise((l,h)=>{const u=()=>{o.removeEventListener("loadeddata",u),o.removeEventListener("error",f),o.pause(),o.currentTime=0,l()},f=()=>{o.removeEventListener("loadeddata",u),o.removeEventListener("error",f),h(new Error("Failed to load video"))};o.addEventListener("loadeddata",u,{once:!0}),o.addEventListener("error",f,{once:!0}),o.load()}),{element:o,objectUrl:n}}async play(t,e){const r=t;if(Math.abs(r.currentTime-e)>.1&&(r.currentTime=e),r.muted=!1,r.paused)try{await r.play()}catch{try{await r.play()}catch(o){console.warn("Failed to play video:",o)}}}pause(t){const e=t;e.pause(),e.muted=!0}async seek(t,e){const r=t;return r.pause(),r.currentTime=e,new Promise(n=>{if(Math.abs(r.currentTime-e)<.01){n();return}const o=()=>{r.removeEventListener("seeked",o),n()};r.addEventListener("seeked",o,{once:!0}),setTimeout(()=>{r.removeEventListener("seeked",o),n()},500)})}syncPlayback(t,e,r){const n=t,o=this.meta.duration/1e6,l=r>=0&&r<o;e&&l?n.paused?this.play(n,r).catch(console.warn):(n.muted&&(n.muted=!1),n.ended&&(n.currentTime=r,n.play().catch(console.warn))):(n.paused||n.pause(),n.muted=!0,l&&Math.abs(n.currentTime-r)>.1&&(n.currentTime=r))}cleanupPlayback(t,e){const r=t;r.pause(),r.removeAttribute("src"),r.load(),e&&URL.revokeObjectURL(e)}async scaleToFit(t,e){await this.ready;const{width:r,height:n}=this.meta;if(r===0||n===0)return;const o=Math.min(t/r,e/n);this.width=r*o,this.height=n*o}async scaleToFill(t,e){await this.ready;const{width:r,height:n}=this.meta;if(r===0||n===0)return;const o=Math.max(t/r,e/n);this.width=r*o,this.height=n*o}centerInScene(t,e){this.left=(t-this.width)/2,this.top=(e-this.height)/2}}function sv(s,t,e,r){const n={duration:0,width:0,height:0,audioSampleRate:0,audioChanCount:0};if(s.video!=null&&t.length>0){n.width=s.video.codedWidth??0,n.height=s.video.codedHeight??0;const h=(Math.round(r/90)*90+360)%360;(h===90||h===270)&&([n.width,n.height]=[n.height,n.width])}s.audio!=null&&e.length>0&&(n.audioSampleRate=tt.sampleRate,n.audioChanCount=tt.channelCount);let o=0,l=0;if(t.length>0)for(let h=t.length-1;h>=0;h--){const u=t[h];if(!u.deleted){o=u.cts+u.duration;break}}if(e.length>0){const h=e.at(-1);l=h.cts+h.duration}return n.duration=Math.max(o,l),n}function nv(s,t,e,r,n){return{audioFrameFinder:n===0||s.audio==null||r.length===0?null:new hv(t,r,s.audio,{volume:n,targetSampleRate:tt.sampleRate}),videoFrameFinder:s.video==null||e.length===0?null:new ov(t,e,s.video)}}async function Fd(s,t={}){let e=null;const r={video:null,audio:null};let n=[],o=[],l=[];const h={perspective:1,rotationRad:0,rotationDeg:0,scaleX:1,scaleY:1,translateX:0,translateY:0};let u=-1,f=-1;const m=await s.createReader();await ev(m,async y=>{e=y.info;const x=y.mp4boxFile.ftyp;l.push({start:x.start,size:x.size});const a=y.mp4boxFile.moov;l.push({start:a.start,size:a.size}),Object.assign(h,iv(e.videoTracks[0]?.matrix));let{videoDecoderConf:c,audioDecoderConf:d}=co(y.mp4boxFile,y.info);if(r.video=c??null,r.audio=d??null,c==null&&d==null&&H.error("VideoClip no video and audio track"),d!=null){const{supported:p}=await AudioDecoder.isConfigSupported(d);p||H.error(`VideoClip audio codec is not supported: ${d.codec}`)}if(c!=null){const{supported:p}=await VideoDecoder.isConfigSupported(c);p||H.error(`VideoClip video codec is not supported: ${c.codec}`)}H.info("mp4BoxFile moov ready",{...y.info,tracks:null,videoTracks:null,audioTracks:null},r)},(y,x,a)=>{if(x==="video"){u===-1&&(u=a[0].dts);for(const c of a)n.push(Dd(c,u,"video"))}else if(x==="audio"&&t.audio){f===-1&&(f=a[0].dts);for(const c of a)o.push(Dd(c,f,"audio"))}}),await m.close();const g=n.at(-1)??o.at(-1);if(e==null)throw Error("VideoClip stream is done, but not emit ready");if(g==null)throw Error("VideoClip stream not contain any sample");return po(n),H.info("mp4 stream parsed"),{videoSamples:n,audioSamples:o,decoderConf:r,headerBoxPos:l,parsedMatrix:h}}function Dd(s,t=0,e){let r=s.offset;const n=e==="video"&&s.is_sync?mv(s.data,s.description.type):-1;let o=s.size;return n>0&&(r+=n,o-=n),{...s,is_idr:n>=0,offset:r,size:o,cts:(s.cts-t)/s.timescale*1e6,dts:(s.dts-t)/s.timescale*1e6,duration:s.duration/s.timescale*1e6,timescale:1e6,data:e==="video"?null:s.data}}class ov{constructor(t,e,r){this.localFileReader=t,this.samples=e,this.conf=r}decoder=null;timestamp=0;curAborter={abort:!1,st:performance.now()};find=async t=>{(this.decoder==null||this.decoder.state==="closed"||t<=this.timestamp||t-this.timestamp>3e6)&&this.reset(t),this.curAborter.abort=!0,this.timestamp=t,this.curAborter={abort:!1,st:performance.now()};const e=await this.parseFrame(t,this.decoder,this.curAborter);return this.sleepCnt=0,e};lastVfDur=0;downgradeSoftDecode=!1;videoDecCursorIdx=0;videoFrames=[];outputFrameCnt=0;inputChunkCnt=0;sleepCnt=0;predecodeErr=!1;parseFrame=async(t,e,r)=>{if(e==null||e.state==="closed"||r.abort)return null;if(this.videoFrames.length>0){const n=this.videoFrames[0];return t<n.timestamp?null:(this.videoFrames.shift(),t>n.timestamp+(n.duration??0)?(n.close(),await this.parseFrame(t,e,r)):(!this.predecodeErr&&this.videoFrames.length<10&&this.startDecode(e).catch(o=>{throw this.predecodeErr=!0,this.reset(t),o}),n))}if(this.decoding||this.outputFrameCnt<this.inputChunkCnt&&e.decodeQueueSize>0){if(performance.now()-r.st>6e3)throw Error(`VideoClip.tick video timeout, ${JSON.stringify(this.getState())}`);this.sleepCnt+=1,await us(15)}else{if(this.videoDecCursorIdx>=this.samples.length)return null;try{await this.startDecode(e)}catch(n){throw this.reset(t),n}}return await this.parseFrame(t,e,r)};decoding=!1;startDecode=async t=>{if(this.decoding||t.decodeQueueSize>600)return;let e=this.videoDecCursorIdx+1;if(e>this.samples.length)return;this.decoding=!0;let r=!1;for(;e<this.samples.length;e++){const n=this.samples[e];if(!r&&!n.deleted&&(r=!0),n.is_idr)break}if(r){const n=this.samples.slice(this.videoDecCursorIdx,e);if(n[0]?.is_idr!==!0)H.warn("First sample not idr frame");else{const o=performance.now(),l=await dv(n,this.localFileReader),h=performance.now()-o;if(h>1e3){const u=n[0],f=n.at(-1),m=f.offset+f.size-u.offset;H.warn(`Read video samples time cost: ${Math.round(h)}ms, file chunk size: ${m}`)}if(t.state==="closed")return;this.lastVfDur=l[0]?.duration??0,pv(t,l,{onDecodingError:u=>{if(this.downgradeSoftDecode)throw u;this.outputFrameCnt===0&&(this.downgradeSoftDecode=!0,H.warn("Downgrade to software decode"),this.reset())}}),this.inputChunkCnt+=l.length}}this.videoDecCursorIdx=e,this.decoding=!1};reset=t=>{if(this.decoding=!1,this.videoFrames.forEach(r=>r.close()),this.videoFrames=[],t==null||t===0)this.videoDecCursorIdx=0;else{let r=0;for(let n=0;n<this.samples.length;n++){const o=this.samples[n];if(o.is_idr&&(r=n),!(o.cts<t)){this.videoDecCursorIdx=r;break}}}this.inputChunkCnt=0,this.outputFrameCnt=0,this.decoder?.state!=="closed"&&this.decoder?.close();const e={...this.conf,...this.downgradeSoftDecode?{hardwareAcceleration:"prefer-software"}:{}};this.decoder=new VideoDecoder({output:r=>{if(this.outputFrameCnt+=1,r.timestamp===-1){r.close();return}let n=r;r.duration==null&&(n=new VideoFrame(r,{duration:this.lastVfDur}),r.close()),this.videoFrames.push(n)},error:r=>{if(r.message.includes("Codec reclaimed due to inactivity")){this.decoder=null,H.warn(r.message);return}const n=`VideoFinder VideoDecoder err: ${r.message}, config: ${JSON.stringify(e)}, state: ${JSON.stringify(this.getState())}`;throw H.error(n),Error(n)}}),this.decoder.configure(e)};getState=()=>({time:this.timestamp,decState:this.decoder?.state,decQSize:this.decoder?.decodeQueueSize,decCursorIdx:this.videoDecCursorIdx,sampleLen:this.samples.length,inputCnt:this.inputChunkCnt,outputCnt:this.outputFrameCnt,cacheFrameLen:this.videoFrames.length,softDecode:this.downgradeSoftDecode,clipIdCnt:uo,sleepCnt:this.sleepCnt,memInfo:Gd()});destroy=()=>{this.decoder?.state!=="closed"&&this.decoder?.close(),this.decoder=null,this.curAborter.abort=!0,this.videoFrames.forEach(t=>t.close()),this.videoFrames=[],this.localFileReader.close()}}function av(s,t){for(let e=0;e<t.length;e++){const r=t[e];if(s>=r.cts&&s<r.cts+r.duration)return e;if(r.cts>s)break}return 0}class hv{constructor(t,e,r,n){this.localFileReader=t,this.samples=e,this.conf=r,this.volume=n.volume,this.sampleRate=n.targetSampleRate}volume=1;sampleRate;decoder=null;curAborter={abort:!1,st:performance.now()};find=async t=>{const e=t<=this.timestamp||t-this.timestamp>1e5;(this.decoder==null||this.decoder.state==="closed"||e)&&this.reset(),e&&(this.timestamp=t,this.decCursorIdx=av(t,this.samples)),this.curAborter.abort=!0;const r=t-this.timestamp;this.timestamp=t,this.curAborter={abort:!1,st:performance.now()};const n=await this.parseFrame(Math.ceil(r*(this.sampleRate/1e6)),this.decoder,this.curAborter);return this.sleepCnt=0,n};timestamp=0;decCursorIdx=0;pcmData={frameCnt:0,data:[]};sleepCnt=0;parseFrame=async(t,e=null,r)=>{if(e==null||r.abort||e.state==="closed"||t===0)return[];const n=this.pcmData.frameCnt-t;if(n>0)return n<tt.sampleRate/10&&this.startDecode(e),Od(this.pcmData,t);if(e.decoding){if(performance.now()-r.st>3e3)throw r.abort=!0,Error(`VideoClip.tick audio timeout, ${JSON.stringify(this.getState())}`);this.sleepCnt+=1,await us(15)}else{if(this.decCursorIdx>=this.samples.length-1)return Od(this.pcmData,this.pcmData.frameCnt);this.startDecode(e)}return this.parseFrame(t,e,r)};startDecode=t=>{if(t.decodeQueueSize>10)return;const r=[];let n=this.decCursorIdx;for(;n<this.samples.length;){const o=this.samples[n];if(n+=1,!o.deleted&&(r.push(o),r.length>=10))break}this.decCursorIdx=n,t.decode(r.map(o=>new EncodedAudioChunk({type:"key",timestamp:o.cts,duration:o.duration,data:o.data})))};reset=()=>{this.timestamp=0,this.decCursorIdx=0,this.pcmData={frameCnt:0,data:[]},this.decoder?.close(),this.decoder=lv(this.conf,{resampleRate:tt.sampleRate,volume:this.volume},t=>{this.pcmData.data.push(t),this.pcmData.frameCnt+=t[0].length})};getState=()=>({time:this.timestamp,decState:this.decoder?.state,decQSize:this.decoder?.decodeQueueSize,decCursorIdx:this.decCursorIdx,sampleLen:this.samples.length,pcmLen:this.pcmData.frameCnt,clipIdCnt:uo,sleepCnt:this.sleepCnt,memInfo:Gd()});destroy=()=>{this.decoder=null,this.curAborter.abort=!0,this.pcmData={frameCnt:0,data:[]},this.localFileReader.close()}}function lv(s,t,e){let r=0,n=0;const o=m=>{if(n+=1,m.length!==0){if(t.volume!==1)for(const g of m)for(let y=0;y<g.length;y++)g[y]*=t.volume;m.length===1&&(m=[m[0],m[0]]),e(m)}},l=cv(o),h=t.resampleRate!==s.sampleRate;let u=new AudioDecoder({output:m=>{const g=Wo(m);h?l(()=>of(g,m.sampleRate,{rate:t.resampleRate,chanCount:m.numberOfChannels})):o(g),m.close()},error:m=>{m.message.includes("Codec reclaimed due to inactivity")||f("VideoClip AudioDecoder err",m)}});u.configure(s);function f(m,g){const y=`${m}: ${g.message}, state: ${JSON.stringify({qSize:u.decodeQueueSize,state:u.state,inputCnt:r,outputCnt:n})}`;throw H.error(y),Error(y)}return{decode(m){r+=m.length;try{for(const g of m)u.decode(g)}catch(g){f("decode audio chunk error",g)}},close(){u.state!=="closed"&&u.close()},get decoding(){return r>n&&u.decodeQueueSize>0},get state(){return u.state},get decodeQueueSize(){return u.decodeQueueSize}}}function cv(s){const t=[];let e=0;function r(l,h){t[h]=l,n()}function n(){const l=t[e];l!=null&&(s(l),e+=1,n())}let o=0;return l=>{const h=o;o+=1,l().then(u=>r(u,h)).catch(u=>r(u,h))}}function Od(s,t){const e=[new Float32Array(t),new Float32Array(t)];let r=0,n=0;for(;n<s.data.length;){const[o,l]=s.data[n];if(r+o.length>t){const h=t-r;e[0].set(o.subarray(0,h),r),e[1].set(l.subarray(0,h),r),s.data[n][0]=o.subarray(h,o.length),s.data[n][1]=l.subarray(h,l.length);break}else e[0].set(o,r),e[1].set(l,r),r+=o.length,n++}return s.data=s.data.slice(n),s.frameCnt-=t,e}async function dv(s,t){const e=s[0],r=s.at(-1);if(r==null)return[];const n=r.offset+r.size-e.offset;if(n<3e7){const o=new Uint8Array(await t.read(n,{at:e.offset}));return s.map(l=>{const h=l.offset-e.offset;return new EncodedVideoChunk({type:l.is_sync?"key":"delta",timestamp:l.cts,duration:l.duration,data:o.subarray(h,h+l.size)})})}return await Promise.all(s.map(async o=>new EncodedVideoChunk({type:o.is_sync?"key":"delta",timestamp:o.cts,duration:o.duration,data:await t.read(o.size,{at:o.offset})})))}function uv(s,t){if(s.length===0)return[];let e=0,r=0,n=-1;for(let u=0;u<s.length;u++){const f=s[u];if(n===-1&&t<f.cts&&(n=u-1),f.is_idr)if(n===-1)e=u;else{r=u;break}}const o=s[n];if(o==null)throw Error("Not found video sample by time");const l=s.slice(0,r===0?s.length:r).map(u=>({...u}));for(let u=e;u<l.length;u++){const f=l[u];t<f.cts&&(f.deleted=!0,f.cts=-1)}po(l);const h=s.slice(o.is_idr?n:e).map(u=>({...u,cts:u.cts-t}));for(const u of h)u.cts<0&&(u.deleted=!0,u.cts=-1);return po(h),[l,h]}function fv(s,t){if(s.length===0)return[];let e=-1;for(let o=0;o<s.length;o++){const l=s[o];if(!(t>l.cts)){e=o;break}}if(e===-1)throw Error("Not found audio sample by time");const r=s.slice(0,e).map(o=>({...o})),n=s.slice(e).map(o=>({...o,cts:o.cts-t}));return[r,n]}function pv(s,t,e){if(s.state==="configured"){for(let r=0;r<t.length;r++)s.decode(t[r]);s.flush().catch(r=>{if(!(r instanceof Error))throw r;if(r.message.includes("Decoding error")&&e.onDecodingError!=null){e.onDecodingError(r);return}if(!r.message.includes("Aborted due to close"))throw r})}}function mv(s,t){if(t!=="avc1"&&t!=="hvc1")return 0;const e=new DataView(s.buffer);for(let r=0;r<s.byteLength-4;){if(t==="avc1"){const n=e.getUint8(r+4)&31;if(n===5||n===7||n===8)return r}else if(t==="hvc1"){const n=e.getUint8(r+4)>>1&63;if(n===19||n===20||n===32||n===33||n===34)return r}r+=e.getUint32(r)+4}return-1}function po(s){let t=0,e=null;for(const r of s)if(!r.deleted){if(r.is_sync&&(t+=1),t>=2)break;(e==null||r.cts<e.cts)&&(e=r)}e!=null&&e.cts<2e5&&(e.duration+=e.cts,e.cts=0)}function Gd(){try{const s=performance.memory;return{jsHeapSizeLimit:s.jsHeapSizeLimit,totalJSHeapSize:s.totalJSHeapSize,usedJSHeapSize:s.usedJSHeapSize,percentUsed:(s.usedJSHeapSize/s.jsHeapSizeLimit).toFixed(3),percentTotal:(s.totalJSHeapSize/s.jsHeapSizeLimit).toFixed(3)}}catch{return{}}}function Xi(s){if(s!=null){if(typeof s=="number")return s;if(typeof s=="string"){if(s.startsWith("#")){const e=parseInt(s.slice(1),16);if(!isNaN(e))return e}if(s.startsWith("0x")){const e=parseInt(s,16);if(!isNaN(e))return e}const t=parseInt(s,16);if(!isNaN(t))return t;try{return new J(s).toNumber()}catch{return}}}}class Xt extends ci{ready;_meta={duration:1/0,width:0,height:0};get meta(){return{...this._meta}}text;get style(){return{fontSize:this.originalOpts.fontSize,fontFamily:this.originalOpts.fontFamily,fontWeight:this.originalOpts.fontWeight,fontStyle:this.originalOpts.fontStyle,color:this.originalOpts.fill,align:this.originalOpts.align,stroke:this.originalOpts.stroke?typeof this.originalOpts.stroke=="object"?{color:this.originalOpts.stroke.color,width:this.originalOpts.stroke.width,join:this.originalOpts.stroke.join,cap:this.originalOpts.stroke.cap,miterLimit:this.originalOpts.stroke.miterLimit}:{color:this.originalOpts.stroke,width:this.originalOpts.strokeWidth??0}:void 0,shadow:this.originalOpts.dropShadow?{color:this.originalOpts.dropShadow.color??"#000000",alpha:this.originalOpts.dropShadow.alpha??.5,blur:this.originalOpts.dropShadow.blur??4,offsetX:this.originalOpts.dropShadow.distance?Math.cos((this.originalOpts.dropShadow.angle??0)*Math.PI/180)*this.originalOpts.dropShadow.distance:0,offsetY:this.originalOpts.dropShadow.distance?Math.sin((this.originalOpts.dropShadow.angle??0)*Math.PI/180)*this.originalOpts.dropShadow.distance:0}:void 0,wordWrap:this.originalOpts.wordWrap,wordWrapWidth:this.originalOpts.wordWrapWidth,lineHeight:this.originalOpts.lineHeight,letterSpacing:this.originalOpts.letterSpacing}}pixiText=null;textStyle;renderTexture=null;externalRenderer=null;pixiApp=null;originalOpts;constructor(t,e={},r){super(),this.text=t,this.originalOpts={...e},this.externalRenderer=r??null,console.log("[TextClip] Constructor:",{opts:e});const n=this.createStyleFromOpts(e),o=new bt(n);this.textStyle=o,this.ready=(async()=>{await this.refreshText();const l={...this._meta};return H.info("TextClip ready:",l),l})()}setRenderer(t){this.externalRenderer=t,console.log("SET RENDERER",t)}async getRenderer(){if(this.externalRenderer!=null)return this.externalRenderer;if(this.pixiApp?.renderer==null)throw new Error("TextClip: Failed to create renderer. Please provide a renderer via constructor or setRenderer() method.");return this.pixiApp.renderer}async getTexture(){return this.pixiText==null||this.renderTexture==null?null:((await this.getRenderer()).render({container:this.pixiText,target:this.renderTexture}),this.renderTexture)}async tick(t){if(await this.ready,this.pixiText==null||this.renderTexture==null)throw new Error("TextClip not initialized");if(this.renderTexture.width<=0||this.renderTexture.height<=0)throw new Error(`Invalid RenderTexture dimensions: ${this.renderTexture.width}x${this.renderTexture.height}`);(await this.getRenderer()).render({container:this.pixiText,target:this.renderTexture});const r=this.renderTexture.source?.resource?.source;let n;if(r instanceof HTMLCanvasElement)n=await createImageBitmap(r);else if(r instanceof OffscreenCanvas)n=await createImageBitmap(r);else{const h=(await this.getRenderer()).extract.canvas(this.renderTexture);if(h instanceof HTMLCanvasElement||h instanceof OffscreenCanvas)n=await createImageBitmap(h);else{const u=this.renderTexture.width,f=this.renderTexture.height;throw new OffscreenCanvas(u,f).getContext("2d")==null?new Error("Failed to create 2d context for fallback rendering"):new Error("Unable to extract canvas from render texture")}}return{video:n,state:"success"}}async split(t){await this.ready;const e=await this.clone(),r=await this.clone();return[e,r]}async clone(){await this.ready;const t=this.textStyle,e=this.originalOpts||{},r=l=>{if(l!=null){if(typeof l=="number")return l;if(l instanceof J)return l.toNumber()}},n={fontSize:e.fontSize??t.fontSize,fontFamily:e.fontFamily??(Array.isArray(t.fontFamily)?t.fontFamily[0]:typeof t.fontFamily=="string"?t.fontFamily:"Arial"),fontWeight:e.fontWeight??t.fontWeight,fontStyle:e.fontStyle??t.fontStyle,align:e.align??(t.align==="justify"?"left":t.align)};if(e.fill&&typeof e.fill=="object"&&"type"in e.fill&&e.fill.type==="gradient")n.fill=e.fill;else{const l=r(t.fill);n.fill=l??16777215}if(e.stroke&&typeof e.stroke=="object"&&"color"in e.stroke)n.stroke=e.stroke;else{const l=r(t.stroke);l!==void 0&&(n.stroke=l),n.strokeWidth=e.strokeWidth??t.strokeThickness??0}if(e.dropShadow)n.dropShadow=e.dropShadow;else if(t.dropShadow){const l=t.dropShadow,h=r(l.color);h!==void 0&&(n.dropShadow={color:h,alpha:l.alpha,blur:l.blur,angle:l.angle,distance:l.distance})}if(e.wordWrap!==void 0?(n.wordWrap=e.wordWrap,n.wordWrapWidth=e.wordWrapWidth):t.wordWrap&&(n.wordWrap=t.wordWrap,n.wordWrapWidth=t.wordWrapWidth),e.lineHeight!==void 0)n.lineHeight=e.lineHeight;else if(t.lineHeight!==void 0){const l=n.fontSize??t.fontSize??40;n.lineHeight=t.lineHeight/l}e.letterSpacing!==void 0?n.letterSpacing=e.letterSpacing:t.letterSpacing!==void 0&&(n.letterSpacing=t.letterSpacing);const o=new Xt(this.text,n);return await o.ready,this.copyStateTo(o),o}async updateStyle(t){this.originalOpts={...this.originalOpts,...t};const e=this.createStyleFromOpts(this.originalOpts),r=new bt(e);this.textStyle=r,await this.refreshText()}async refreshText(){const t=this.textStyle;this.pixiText&&this.pixiText.destroy({children:!0}),this.pixiText=new Cy({text:this.text,style:t});const e=this.pixiText.getLocalBounds();let r=Math.max(1,Math.ceil(e.width||this.pixiText.width||100));t.wordWrap&&t.wordWrapWidth>0&&(r=Math.max(1,Math.ceil(Math.max(r,t.wordWrapWidth))));const n=Math.max(1,Math.ceil(e.height||this.pixiText.height||40));this.renderTexture&&this.renderTexture.destroy(!0),this.renderTexture=Vi.create({width:r,height:n}),this._meta.width=r,this._meta.height=n,this.width=r,this.height=n,this.duration===0&&this._meta.duration!==1/0&&(this.duration=this._meta.duration,this.display.to=this.display.from+this.duration)}createStyleFromOpts(t){const e=t.fontSize??40,r=t.lineHeight??1,n={fontSize:e,fontFamily:t.fontFamily??"Arial",fontWeight:t.fontWeight??"normal",fontStyle:t.fontStyle??"normal",align:t.align??"left",wordWrap:t.wordWrap??!1,wordWrapWidth:t.wordWrapWidth??100,lineHeight:e*r,letterSpacing:t.letterSpacing??0};if(t.fill&&typeof t.fill=="object"&&t.fill.type==="gradient"){const o=new Vt(t.fill.x0,t.fill.y0,t.fill.x1,t.fill.y1);t.fill.colors.forEach(({ratio:l,color:h})=>{const u=typeof h=="number"?h:Xi(h)??16777215;o.addColorStop(l,u)}),n.fill={fill:o}}else{const o=typeof t.fill=="string"||typeof t.fill=="number"?Xi(t.fill):void 0;n.fill=o??16777215}if(t.stroke&&typeof t.stroke=="object"&&"color"in t.stroke){const o=Xi(t.stroke.color);o!==void 0&&(n.stroke={color:o,width:t.stroke.width},t.stroke.join&&(n.stroke.join=t.stroke.join),t.stroke.cap&&(n.stroke.cap=t.stroke.cap),t.stroke.miterLimit&&(n.stroke.miterLimit=t.stroke.miterLimit))}else{const o=Xi(t.stroke),l=t.strokeWidth??0;o!==void 0&&l>0?n.stroke={color:o,width:l}:t.strokeWidth&&t.strokeWidth>0&&(n.stroke={color:0,width:t.strokeWidth})}if(t.dropShadow){const o=Xi(t.dropShadow.color);o!==void 0&&(n.dropShadow={color:o,alpha:t.dropShadow.alpha??.5,blur:t.dropShadow.blur??4,angle:t.dropShadow.angle??Math.PI/6,distance:t.dropShadow.distance??2})}return n}destroy(){if(!this.destroyed){H.info("TextClip destroy");try{this.pixiText!=null&&this.pixiText.destroyed!==!0&&this.pixiText.destroy({children:!0})}catch{}finally{this.pixiText=null}try{this.renderTexture!=null&&this.renderTexture.destroyed!==!0&&this.renderTexture.destroy(!0)}catch{}finally{this.renderTexture=null}if(this.externalRenderer=null,this.pixiApp!=null)try{const t=this.pixiApp;t.destroyed!==!0&&t.renderer!=null&&this.pixiApp.destroy(!0,{children:!0,texture:!0})}catch{}finally{this.pixiApp=null}super.destroy()}}toJSON(t=!1){const e=super.toJSON(t),r={};if(this.originalOpts.fontSize!==void 0&&(r.fontSize=this.originalOpts.fontSize),this.originalOpts.fontFamily!==void 0&&(r.fontFamily=this.originalOpts.fontFamily),this.originalOpts.fontWeight!==void 0&&(r.fontWeight=this.originalOpts.fontWeight),this.originalOpts.fontStyle!==void 0&&(r.fontStyle=this.originalOpts.fontStyle),this.originalOpts.fill!==void 0&&(r.color=this.originalOpts.fill),this.originalOpts.align!==void 0&&(r.align=this.originalOpts.align),this.originalOpts.wordWrap!==void 0&&(r.wordWrap=this.originalOpts.wordWrap),this.originalOpts.wordWrapWidth!==void 0&&(r.wordWrapWidth=this.originalOpts.wordWrapWidth),this.originalOpts.lineHeight!==void 0&&(r.lineHeight=this.originalOpts.lineHeight),this.originalOpts.letterSpacing!==void 0&&(r.letterSpacing=this.originalOpts.letterSpacing),this.originalOpts.stroke&&(typeof this.originalOpts.stroke=="object"?r.stroke={color:this.originalOpts.stroke.color,width:this.originalOpts.stroke.width,join:this.originalOpts.stroke.join,cap:this.originalOpts.stroke.cap,miterLimit:this.originalOpts.stroke.miterLimit}:r.stroke={color:this.originalOpts.stroke,width:this.originalOpts.strokeWidth??0}),this.originalOpts.dropShadow){const n=this.originalOpts.dropShadow;r.shadow={color:n.color??"#000000",alpha:n.alpha??.5,blur:n.blur??4,offsetX:n.distance?Math.cos((n.angle??0)*Math.PI/180)*n.distance:0,offsetY:n.distance?Math.sin((n.angle??0)*Math.PI/180)*n.distance:0}}return{...e,type:"Text",text:this.text,style:r}}static async fromObject(t){if(t.type!=="Text")throw new Error(`Expected Text, got ${t.type}`);const e=t.text||"",r=t.style||{},n={};if(r.fontSize!==void 0&&(n.fontSize=r.fontSize),r.fontFamily!==void 0&&(n.fontFamily=r.fontFamily),r.fontWeight!==void 0&&(n.fontWeight=r.fontWeight),r.fontStyle!==void 0&&(n.fontStyle=r.fontStyle),r.color!==void 0&&(n.fill=r.color),r.align!==void 0&&(n.align=r.align),r.wordWrap!==void 0&&(n.wordWrap=r.wordWrap),r.wordWrapWidth!==void 0&&(n.wordWrapWidth=r.wordWrapWidth),r.lineHeight!==void 0&&(n.lineHeight=r.lineHeight),r.letterSpacing!==void 0&&(n.letterSpacing=r.letterSpacing),r.stroke&&(r.stroke.join||r.stroke.cap||r.stroke.miterLimit!==void 0?n.stroke={color:r.stroke.color,width:r.stroke.width,join:r.stroke.join,cap:r.stroke.cap,miterLimit:r.stroke.miterLimit}:(n.stroke=r.stroke.color,n.strokeWidth=r.stroke.width)),r.shadow){const l=Math.sqrt(r.shadow.offsetX**2+r.shadow.offsetY**2),h=Math.atan2(r.shadow.offsetY,r.shadow.offsetX)*180/Math.PI;n.dropShadow={color:r.shadow.color,alpha:r.shadow.alpha,blur:r.shadow.blur,distance:l,angle:h}}const o=new Xt(e,n);return o.left=t.left,o.top=t.top,o.width=t.width,o.height=t.height,o.angle=t.angle,o.display.from=t.display.from,o.display.to=t.display.to,o.duration=t.duration,o.playbackRate=t.playbackRate,o.zIndex=t.zIndex,o.opacity=t.opacity,o.flip=t.flip,t.animation&&o.setAnimation(t.animation.keyFrames,t.animation.opts),await o.ready,o}}class Ld{readable;writable;inputBufOffset=0;constructor(){const t=yt.createFile();let e=!1;this.readable=new ReadableStream({start:r=>{t.onReady=o=>{const l=o.videoTracks[0]?.id;l!=null&&t.setExtractionOptions(l,"video",{nbSamples:100});const h=o.audioTracks[0]?.id;h!=null&&t.setExtractionOptions(h,"audio",{nbSamples:100}),r.enqueue({chunkType:"ready",data:{info:o,file:t}}),t.start()};const n={};t.onSamples=(o,l,h)=>{r.enqueue({chunkType:"samples",data:{id:o,type:l,samples:h.map(u=>({...u}))}}),n[o]=(n[o]??0)+h.length,t.releaseUsedSamples(o,n[o])},t.onFlush=()=>{r.close()}},cancel:()=>{t.stop(),e=!0}},{highWaterMark:50}),this.writable=new WritableStream({write:async r=>{if(e){this.writable.abort();return}const n=r.buffer;n.fileStart=this.inputBufOffset,this.inputBufOffset+=n.byteLength,t.appendBuffer(n)},close:()=>{t.flush(),t.stop(),t.onFlush?.()}})}}function gv(s){let t=0;const e=s.boxes,r=[];let n=0;async function o(){const a=x(e,t);t=e.length,r.forEach(({track:c,id:d})=>{const p=c.samples.at(-1);p!=null&&(n=Math.max(n,p.cts+p.duration)),s.releaseUsedSamples(d,c.samples.length),c.samples=[]}),s.mdats=[],s.moofs=[],a!=null&&await m?.write(a)}let l=[];function h(){if(l.length>0)return!0;const a=e.findIndex(c=>c.type==="moov");if(a===-1)return!1;if(l=e.slice(0,a+1),t=a+1,r.length===0)for(let c=1;;c+=1){const d=s.getTrackById(c);if(d==null)break;r.push({track:d,id:c})}return!0}let u=0;const f=ns();let m=null;const g=(async()=>{m=await f.createWriter(),u=self.setInterval(()=>{h()&&o()},100)})();let y=!1;return async()=>{if(y)throw Error("File exported");if(y=!0,await g,clearInterval(u),!h()||m==null)return null;s.flush(),await o(),await m?.close();const a=l.find(p=>p.type==="moov");if(a==null)return null;a.mvhd.duration=n;const c=ns(),d=x(l,0);return await oi(c,d.slice()),await oi(c,f,{overwrite:!1}),await c.stream()};function x(a,c){if(c>=a.length)return null;const d=new yt.DataStream;d.endianness=yt.DataStream.BIG_ENDIAN;for(let p=c;p<a.length;p++)a[p]!==null&&(a[p].write(d),delete a[p]);return new Uint8Array(d.buffer).slice()}}function _v(s){const t=new ArrayBuffer(s.byteLength);s.copyTo(t);const e=s.timestamp;return{duration:s.duration??0,dts:e,cts:e,is_sync:s.type==="key",data:t}}async function zd(s){const t=yt.createFile(),e=gv(t);await yv(s,t);const r=await e();if(r==null)throw Error("Can not generate file from streams");return r}async function yv(s,t){let e=0,r=0,n=0,o=0,l=0,h=0,u=null,f=null;for(const m of s){let g=null,y=null,x=null,a=null;if(await new Promise(async c=>{Go(m.pipeThrough(new Ld),{onDone:c,onChunk:async({chunkType:d,data:p})=>{if(d==="ready"){const{videoTrackConf:_,audioTrackConf:b}=co(p.file,p.info);e===0&&_!=null&&(e=t.addTrack(_)),o===0&&b!=null&&(o=t.addTrack(b))}else if(d==="samples"){const{type:_,samples:b}=p,v=_==="video"?e:o,w=_==="video"?r:l,S=_==="video"?n:h;b.forEach(E=>{let P,B;_==="video"?(g===null&&(g=E.dts,y=E.cts),P=E.dts-g,B=E.cts-(y??0)):(x===null&&(x=E.dts,a=E.cts),P=E.dts-x,B=E.cts-(a??0)),t.addSample(v,E.data,{duration:E.duration,dts:P+w,cts:B+S,is_sync:E.is_sync})});const T=b.at(-1);if(T==null)return;_==="video"?u=T:_==="audio"&&(f=T)}}})}),u!=null&&g!==null&&y!==null){const c=u.dts-g+u.duration,d=u.cts-y+u.duration;r+=c,n+=d}if(f!=null&&u!=null){const c=f.timescale/u.timescale;l=Math.round(r*c),h=Math.round(n*c)}}}async function xv(s){return await zd([s])}function bv(s){let t=[];const e=new AudioDecoder({output:r=>{t.push(r)},error:H.error});return e.configure(s),{decode:async r=>{r.forEach(o=>{e.decode(new EncodedAudioChunk({type:o.is_sync?"key":"delta",timestamp:1e6*o.cts/o.timescale,duration:1e6*o.duration/o.timescale,data:o.data}))}),await e.flush();const n=t;return t=[],n},close:()=>{e.close()}}}function vv(s,t){const e={codec:s.codec,sampleRate:s.sampleRate,numberOfChannels:s.numberOfChannels},r=new AudioEncoder({output:l=>{t(_v(l))},error:l=>{H.error("AudioEncoder error:",l,", config:",e)}});r.configure(e);let n=null;function o(l,h){return new AudioData({timestamp:h,numberOfChannels:s.numberOfChannels,numberOfFrames:l.length/s.numberOfChannels,sampleRate:s.sampleRate,format:"f32-planar",data:new Float32Array(l)})}return{encode:async(l,h)=>{n!=null&&r.encode(o(n.data,n.ts)),n={data:l,ts:h}},stop:async()=>{n!=null&&(wv(n.data,s.numberOfChannels,s.sampleRate),r.encode(o(n.data,n.ts)),n=null),await r.flush(),r.close()}}}function wv(s,t,e){const r=s.length-1,n=Math.min(e/2,r);for(let o=0;o<n;o++)for(let l=1;l<=t;l++)s[Math.floor(r/l)-o]*=o/n}function Sv(s,t){H.info("mixinMP4AndAudio, opts:",{volume:t.volume,loop:t.loop});const e=yt.createFile(),{stream:r,stop:n}=Lo(e,500);let o=null,l=null,h=[],u=0,f=0,m=0,g=!0,y=tt.sampleRate;Go(s.pipeThrough(new Ld),{onDone:async()=>{await l?.stop(),o?.close(),n()},onChunk:async({chunkType:d,data:p})=>{if(d==="ready"){const{videoTrackConf:_,audioTrackConf:b,audioDecoderConf:v}=co(p.file,p.info);u===0&&_!=null&&(u=e.addTrack(_));const w=b??{timescale:1e6,samplerate:y,channel_count:tt.channelCount,hdlr:"soun",name:"SoundHandler",type:"mp4a"};f===0&&(f=e.addTrack(w),y=b?.samplerate??y,g=b!=null);const S=new AudioContext({sampleRate:y});h=cs(await S.decodeAudioData(await new Response(t.stream).arrayBuffer())),v!=null&&(o=bv(v)),l=vv(v??{codec:w.type==="mp4a"?tt.codec:w.type,numberOfChannels:w.channel_count,sampleRate:w.samplerate},T=>e.addSample(f,T.data,T))}else if(d==="samples"){const{id:_,type:b,samples:v}=p;if(b==="video"){v.forEach(w=>e.addSample(_,w.data,w)),g||await a(v);return}b==="audio"&&await c(v)}}});function x(d){const p=h.map(_=>t.loop?ds(_,m,m+d):_.slice(m,m+d));if(m+=d,t.volume!==1)for(const _ of p)for(let b=0;b<_.length;b++)_[b]*=t.volume;return p}async function a(d){const p=d[0],_=d[d.length-1],b=Math.floor((_.cts+_.duration-p.cts)/p.timescale*y),v=Vo([x(b)]);v.length!==0&&l?.encode(v,p.cts/p.timescale*1e6)}async function c(d){if(o==null)return;const p=(await o.decode(d)).map(Wo),_=Ho(p),b=x(_[0].length),v=d[0];l?.encode(Vo([_,b]),v.cts/v.timescale*1e6)}return r}function Tv(s,t){const{opacity:e,zIndex:r,flip:n,left:o,top:l,width:h,height:u,angle:f}=s;t.x=o,t.y=l,t.width=Math.abs(h),t.height=Math.abs(u),t.rotation=f,t.alpha=e,t.zIndex=r,n==="horizontal"?t.scale.x=-Math.abs(t.scale.x):n==="vertical"&&(t.scale.y=-Math.abs(t.scale.y))}class $i{constructor(t,e,r=null){this.sprite=e,this.targetContainer=r,!r&&t&&(this.targetContainer=t.stage),this.targetContainer,this.canvas=new OffscreenCanvas(1,1);const n=this.canvas.getContext("2d");if(n==null)throw new Error("Failed to create 2d context for PixiSpriteRenderer");this.context=n}pixiSprite=null;texture=null;canvas;context;destroyed=!1;async updateFrame(t){if(this.destroyed)return;if(t==null){this.pixiSprite!=null&&(this.pixiSprite.visible=!1,this.applySpriteTransforms());return}if(t instanceof k){if(t.width===0||t.height===0){console.warn("PixiSpriteRenderer: Invalid texture dimensions",t.width,t.height);return}this.pixiSprite==null?(this.pixiSprite=new ie(t),this.targetContainer?.addChild(this.pixiSprite),this.applySpriteTransforms()):this.pixiSprite.texture=t,this.pixiSprite!=null&&(this.pixiSprite.visible=!0,this.applySpriteTransforms());return}if(t.width===0||t.height===0){console.warn("PixiSpriteRenderer: Invalid frame dimensions",t.width,t.height);return}const e=this.texture==null||this.pixiSprite==null;if(this.canvas.width!==t.width||this.canvas.height!==t.height||e){if(this.canvas.width=t.width,this.canvas.height=t.height,this.texture!=null&&(this.texture.destroy(!0),this.texture=null),this.texture=k.from(this.canvas),!this.texture||!this.texture.source){console.error("PixiSpriteRenderer: Failed to create valid texture");return}this.pixiSprite==null?(this.pixiSprite=new ie(this.texture),this.targetContainer?.addChild(this.pixiSprite),this.applySpriteTransforms()):this.pixiSprite.texture=this.texture}if(this.context.clearRect(0,0,this.canvas.width,this.canvas.height),this.context.drawImage(t,0,0),this.texture!=null&&this.texture.source!=null){const n=this.texture.source;if(n.resource){const o=n.resource;o.update&&o.update()}typeof n.update=="function"&&n.update()}this.pixiSprite!=null&&(this.pixiSprite.visible=!0,this.applySpriteTransforms())}applySpriteTransforms(){if(this.pixiSprite==null||this.destroyed)return;const{flip:t,center:e,width:r,height:n,angle:o,opacity:l,zIndex:h}=this.sprite;this.pixiSprite.x=e.x,this.pixiSprite.y=e.y,this.pixiSprite.anchor.set(.5,.5);const u=this.pixiSprite.texture?.width??1,f=this.pixiSprite.texture?.height??1,m=r&&r!==0?Math.abs(r)/u:1,g=n&&n!==0?Math.abs(n)/f:1;t==="horizontal"?(this.pixiSprite.scale.x=-m,this.pixiSprite.scale.y=g):t==="vertical"?(this.pixiSprite.scale.x=m,this.pixiSprite.scale.y=-g):(this.pixiSprite.scale.x=m,this.pixiSprite.scale.y=g),this.pixiSprite.rotation=(t==null?1:-1)*o,this.pixiSprite.alpha=l,this.pixiSprite.zIndex=h}updateTransforms(){this.pixiSprite!=null&&!this.destroyed&&this.applySpriteTransforms()}getSprite(){return this.pixiSprite}destroy(){this.destroyed||(this.destroyed=!0,this.pixiSprite!=null&&(this.targetContainer?.removeChild(this.pixiSprite),this.pixiSprite.destroy({children:!0}),this.pixiSprite=null),this.texture!=null&&(this.texture.destroy(),this.texture=null))}}function mo(s,t=!1){return s.toJSON(t)}async function go(s){let t,e=null;switch(s.type){case"Video":e=ft;break;case"Audio":e=mt;break;case"Image":e=Ut;break;case"Text":e=Xt;break;case"Caption":e=Ue;break}if(e&&typeof e.fromObject=="function")return await e.fromObject(s);switch(s.type){case"Video":{const r=await fetch(s.src);if(!r.ok)throw new Error(`Failed to fetch video from ${s.src}: ${r.status} ${r.statusText}. Make sure the file exists in the public directory.`);const n=s.audio!==void 0?{audio:s.audio}:{};t=new ft(r.body,n,s.src);break}case"Audio":{if(!s.src||s.src.trim()==="")throw new Error("AudioClip requires a valid source URL");const r={};s.loop!==void 0&&(r.loop=s.loop),s.volume!==void 0&&(r.volume=s.volume),t=await mt.fromUrl(s.src,r);break}case"Image":{if(!s.src||s.src.trim()==="")throw new Error("ImageClip requires a valid source URL. Generated clips (like text-to-image) cannot be loaded from JSON without their source data.");try{const r=await fetch(s.src);if(!r.ok)throw new Error(`Failed to fetch image from ${s.src}: ${r.status} ${r.statusText}. Make sure the file exists in the public directory.`);const n=await r.blob();if(!n.type.startsWith("image/"))throw new Error(`Invalid image format: ${n.type}. Expected an image file.`);t=new Ut(await createImageBitmap(n),s.src)}catch(r){throw r instanceof Error&&r.message.includes("could not be decoded")?new Error(`Failed to decode image from ${s.src}. The image may be corrupted, in an unsupported format, or there may be CORS issues.`):r}break}case"Text":{const r=s.text||"",n=s.style||{},o={fontSize:n.fontSize,fontFamily:n.fontFamily,fontWeight:n.fontWeight,fontStyle:n.fontStyle,fill:n.color,align:n.align};n.stroke&&(o.stroke=n.stroke.color,o.strokeWidth=n.stroke.width),n.shadow&&(o.dropShadow={color:n.shadow.color,alpha:n.shadow.alpha,blur:n.shadow.blur,offsetX:n.shadow.offsetX,offsetY:n.shadow.offsetY}),t=new Xt(r,o);break}case"Caption":{const r=s.text||"",n=s.style||{},o={fontSize:n.fontSize,fontFamily:n.fontFamily,fontWeight:n.fontWeight,fontStyle:n.fontStyle,fill:n.color,align:n.align};if(n.fontUrl!==void 0?o.fontUrl=n.fontUrl:s.fontUrl!==void 0&&(o.fontUrl=s.fontUrl),n.stroke&&(o.stroke=n.stroke.color,o.strokeWidth=n.stroke.width),n.shadow&&(o.dropShadow={color:n.shadow.color,alpha:n.shadow.alpha,blur:n.shadow.blur,offsetX:n.shadow.offsetX,offsetY:n.shadow.offsetY}),s.caption){const l=s.caption;l.words&&(o.words=l.words),l.colors&&(l.colors.appeared!==void 0&&(o.appearedColor=l.colors.appeared),l.colors.active!==void 0&&(o.activeColor=l.colors.active),l.colors.activeFill!==void 0&&(o.activeFillColor=l.colors.activeFill),l.colors.background!==void 0&&(o.backgroundColor=l.colors.background),l.colors.keyword!==void 0&&(o.isKeyWordColor=l.colors.keyword)),l.preserveKeywordColor!==void 0&&(o.preservedColorKeyWord=l.preserveKeywordColor),l.positioning&&(l.positioning.bottomOffset!==void 0&&(o.bottomOffset=l.positioning.bottomOffset),l.positioning.videoWidth!==void 0&&(o.videoWidth=l.positioning.videoWidth),l.positioning.videoHeight!==void 0&&(o.videoHeight=l.positioning.videoHeight))}else s.bottomOffset!==void 0&&(o.bottomOffset=s.bottomOffset),s.words&&(o.words=s.words),s.appearedColor!==void 0&&(o.appearedColor=s.appearedColor),s.activeColor!==void 0&&(o.activeColor=s.activeColor),s.activeFillColor!==void 0&&(o.activeFillColor=s.activeFillColor),s.backgroundColor!==void 0&&(o.backgroundColor=s.backgroundColor),s.isKeyWordColor!==void 0&&(o.isKeyWordColor=s.isKeyWordColor),s.preservedColorKeyWord!==void 0&&(o.preservedColorKeyWord=s.preservedColorKeyWord),s.videoWidth!==void 0&&(o.videoWidth=s.videoWidth),s.videoHeight!==void 0&&(o.videoHeight=s.videoHeight);t=new Ue(r,o);break}default:throw new Error(`Unsupported clip type: ${s.type}`)}return t.left=s.left,t.top=s.top,t.width=s.width,t.height=s.height,t.angle=s.angle,t.display.from=s.display.from,t.display.to=s.display.to,t.duration=s.duration,t.playbackRate=s.playbackRate,t.zIndex=s.zIndex,t.opacity=s.opacity,t.flip=s.flip,s.animation&&t.setAnimation(s.animation.keyFrames,s.animation.opts),t}let Cv=0;async function Nd(s){s()>50&&(await us(15),await Nd(s))}class Ev{static async isSupported(t={}){return(self.OffscreenCanvas!=null&&self.VideoEncoder!=null&&self.VideoDecoder!=null&&self.VideoFrame!=null&&self.AudioEncoder!=null&&self.AudioDecoder!=null&&self.AudioData!=null&&((await self.VideoEncoder.isConfigSupported({codec:t.videoCodec??"avc1.42E032",width:t.width??1920,height:t.height??1080,bitrate:t.bitrate??7e6})).supported??!1)&&(await self.AudioEncoder.isConfigSupported({codec:(await $o()).codec,sampleRate:tt.sampleRate,numberOfChannels:tt.channelCount})).supported)??!1}logger=H.create(`id:${Cv++},`);destroyed=!1;sprites=[];canvas;pixiApp=null;stopOutput=null;opts;hasVideoTrack;evtTool=new os;on=this.evtTool.on;constructor(t={}){const{width:e=0,height:r=0}=t;this.canvas=new OffscreenCanvas(e,r),this.opts=Object.assign({bgColor:"#000",width:0,height:0,videoCodec:"avc1.42E032",audio:!0,bitrate:5e6,fps:30,metaDataTags:null},t),this.hasVideoTrack=e*r>0,$o().catch(n=>{this.logger.warn("Failed to detect audio codec:",n)})}async initPixiApp(){const{width:t,height:e}=this.opts;if(this.pixiApp=new en,console.log("PIXI APP 000",this.pixiApp),await this.pixiApp.init({canvas:this.canvas,width:t,height:e,backgroundColor:0,antialias:!1,autoDensity:!1,resolution:1,preference:"webgl"}),this.pixiApp.renderer==null||this.pixiApp.stage==null)throw new Error("Pixi.js Application failed to initialize properly");try{const r=this.pixiApp;r.ticker&&typeof r.ticker.stop=="function"&&r.ticker.stop()}catch{}}async addSprite(t,e={}){const r={rect:{x:t.left,y:t.top,w:t.width,h:t.height},display:{...t.display},duration:t.duration,playbackRate:t.playbackRate,zIndex:t.zIndex};this.logger.info("Compositor add clip",r);const n=await t.clone();console.log("PIXI APP 111",this.pixiApp),this.pixiApp!=null&&this.pixiApp.renderer!=null&&typeof n.setRenderer=="function"&&n.setRenderer(this.pixiApp.renderer),this.logger.info("Compositor add clip ready"),this.sprites.push(Object.assign(n,{main:e.main??!1,expired:!1})),this.sprites.sort((o,l)=>o.zIndex-l.zIndex)}initMuxer(t){const{fps:e,width:r,height:n,videoCodec:o,bitrate:l,audio:h,metaDataTags:u}=this.opts,f=this.sprites.some(y=>y.width>0&&y.height>0),m=this.hasVideoTrack&&f;return Ou({video:m?{width:r,height:n,expectFPS:e,codec:o,bitrate:l,__unsafe_hardwareAcceleration__:this.opts.__unsafe_hardwareAcceleration__}:null,audio:h===!1?null:{codec:tt.codecType,sampleRate:tt.sampleRate,channelCount:tt.channelCount},duration:t,metaDataTags:u})}output(t={}){if(this.sprites.length===0)throw Error("No sprite added");const e=this.sprites.find(g=>g.main),n=this.sprites.map(g=>g.display.from+g.duration).filter(g=>g!==1/0),o=t.maxTime??(e!=null?e.display.from+e.duration:n.length>0?Math.max(...n):1/0);if(o===1/0||o<=0)throw Error("Unable to determine the end time, please specify a main sprite, or limit the duration of ImageClip, AudioClip");o===-1&&this.logger.warn("Unable to determine the end time, process value don't update"),this.logger.info(`start combinate video, maxTime:${o}`);const l=this.initMuxer(o);let h=performance.now();const u=this.runEncoding(l,o,{onProgress:g=>{this.logger.debug("OutputProgress:",g),this.evtTool.emit("OutputProgress",g)},onEnded:async()=>{await l.flush(),this.logger.info("===== output ended =====, cost:",performance.now()-h),this.evtTool.emit("OutputProgress",1),this.destroy()},onError:g=>{this.evtTool.emit("error",g),m(g),this.destroy()}});this.stopOutput=()=>{u(),l.close(),m()};const{stream:f,stop:m}=Lo(l.mp4file,500,this.destroy);return f}destroy(){if(!this.destroyed&&(this.destroyed=!0,this.stopOutput?.(),this.evtTool.destroy(),this.pixiApp!=null))try{const t=this.pixiApp;if(t.destroyed===!0){this.pixiApp=null;return}if(t.ticker&&typeof t.ticker.stop=="function")try{t.ticker.stop()}catch{}if(t.renderer!=null){const e=t.renderer.gl;if(e&&e.isContextLost()){this.pixiApp=null;return}this.pixiApp.destroy()}}catch(t){console.warn("Error while destroying Pixi application:",t)}finally{this.pixiApp=null}}runEncoding(t,e,{onProgress:r,onEnded:n,onError:o}){let l=0;const h={aborted:!1};let u=null,f=null;const m=async()=>{const{fps:x,bgColor:a,audio:c}=this.opts,d=Math.round(1e6/x),p=this.sprites.some(v=>v.width>0&&v.height>0);f=Av({pixiApp:this.pixiApp,sprites:this.sprites,aborter:h});const _=Pv({muxer:t,canvas:this.canvas,outputAudio:c,hasVideoTrack:this.hasVideoTrack&&p,timeSlice:d,fps:x});let b=0;for(;;){if(u!=null)return;if(h.aborted||e!==-1&&b>e||this.sprites.length===0){g(),await n();return}l=b/e;const{audios:v,mainSprDone:w,hasVideo:S}=await f.render(b);if(w){g(),await n();return}if(h.aborted)return;this.hasVideoTrack&&S&&await new Promise(T=>requestAnimationFrame(T)),_(b,v,S),b+=d,await Nd(t.getEncodeQueueSize)}},g=()=>{h.aborted||(h.aborted=!0,clearInterval(y),f?.cleanup(),this.sprites.forEach(x=>{x.destroy()}))};m().catch(x=>{u=x,this.logger.error(x),g(),o(x)});const y=setInterval(()=>{r(l)},500);return g}exportToJSON(){return{clips:this.sprites.map(e=>mo(e,e.main)),settings:{width:this.opts.width,height:this.opts.height,fps:this.opts.fps,bgColor:this.opts.bgColor,videoCodec:this.opts.videoCodec,bitrate:this.opts.bitrate,audio:this.opts.audio,metaDataTags:this.opts.metaDataTags}}}async loadFromJSON(t){this.sprites.forEach(e=>{e.destroy()}),this.sprites=[],t.settings&&(t.settings.width!==void 0&&(this.opts.width=t.settings.width),t.settings.height!==void 0&&(this.opts.height=t.settings.height),t.settings.fps!==void 0&&(this.opts.fps=t.settings.fps),t.settings.bgColor!==void 0&&(this.opts.bgColor=t.settings.bgColor),t.settings.videoCodec!==void 0&&(this.opts.videoCodec=t.settings.videoCodec),t.settings.bitrate!==void 0&&(this.opts.bitrate=t.settings.bitrate),t.settings.audio!==void 0&&(this.opts.audio=t.settings.audio===!1?!1:void 0),t.settings.metaDataTags!==void 0&&(this.opts.metaDataTags=t.settings.metaDataTags));for(const e of t.clips){const r=await go(e);await this.addSprite(r,{main:e.main||!1})}}}function Av(s){const{pixiApp:t,sprites:e,aborter:r}=s,n=t!=null,o=new Map;return{render:async u=>{const f=[];let m=!1,g=!1;const y=[...e].sort((x,a)=>x.zIndex-a.zIndex);for(const x of y){if(r.aborted)break;if(u<x.display.from||x.expired)continue;const a=u-x.display.from,c=a*x.playbackRate;x.animate(c);const{video:d,audio:p,done:_}=await x.getFrame(a);if(f.push(p),n&&t!=null){let b=o.get(x);b==null&&d!=null&&(b=new $i(t,x,t.stage),o.set(x,b)),b!=null&&(d!=null?(g=!0,await b.updateFrame(d)):await b.updateFrame(null)),b?.updateTransforms()}if(x.duration>0&&u>x.display.from+x.duration||_){if(x.main&&(m=!0),x.expired=!0,n){const b=o.get(x);if(b!=null){const v=b.getSprite();v&&(v.visible=!1)}}}else if(n){const b=o.get(x);b?.updateTransforms()}}return n&&t!=null&&t.renderer!=null&&t.stage!=null&&o.size>0&&t.render(),{audios:f,mainSprDone:m,hasVideo:g}},cleanup:()=>{o.forEach(u=>{u.destroy()}),o.clear()}}}function Pv(s){const{canvas:t,outputAudio:e,muxer:r,hasVideoTrack:n,timeSlice:o}=s;let l=0;const h=Math.floor(3*s.fps),u=Bv(1024);return(f,m,g)=>{if(e!==!1)for(const y of u(f,m))r.encodeAudio(y);if(n&&g)try{const y=new VideoFrame(t,{duration:o,timestamp:f});r.encodeVideo(y,{keyFrame:l%h===0}),l+=1}catch(y){console.warn("Failed to create VideoFrame from canvas, skipping frame:",y)}}}function Bv(s){const t=s*tt.channelCount,e=new Float32Array(t*3);let r=0,n=0;const o=s/tt.sampleRate*1e6,l=new Float32Array(t),h=u=>{let f=0;const m=Math.floor(r/t),g=[];for(let y=0;y<m;y++)g.push(new AudioData({timestamp:n,numberOfChannels:tt.channelCount,numberOfFrames:s,sampleRate:tt.sampleRate,format:"f32",data:e.subarray(f,f+t)})),f+=t,n+=o;for(e.set(e.subarray(f,r),0),r-=f;u-n>o;)g.push(new AudioData({timestamp:n,numberOfChannels:tt.channelCount,numberOfFrames:s,sampleRate:tt.sampleRate,format:"f32",data:l})),n+=o;return g};return(u,f)=>{const m=Math.max(...f.map(g=>g[0]?.length??0));for(let g=0;g<m;g++){let y=0,x=0;for(let a=0;a<f.length;a++){const c=f[a][0]?.[g]??0,d=f[a][1]?.[g]??c;y+=c,x+=d}e[r]=y,e[r+1]=x,r+=2}return h(u)}}class Uv extends Zt{constructor(){super(),this.eventMode="static",this.cursor="move"}draw(t,e=1){const n=1*e;this.clear(),this.setStrokeStyle({width:n,color:5620223}).rect(t.x,t.y,t.width,t.height).stroke(),this.hitArea=t}}class ce extends Zt{#t=!1;handle;cursor;callbacks;constructor(t,e,r){super(),this.handle=t,this.cursor=e,this.callbacks=r,this.eventMode="static",this.#o(),this.on("pointerdown",this.#e),this.on("globalpointermove",this.#r),this.on("pointerup",this.#h),this.on("pointerupoutside",this.#h)}#o(){this.clear(),this.handle==="rot"?(this.circle(0,0,10),this.fill({color:"#ffffff"}),this.stroke({width:1,color:13421772}),this.moveTo(0,-5),this.arc(0,0,5,-Math.PI/2,Math.PI,!1),this.stroke({width:1,color:0}),this.moveTo(0,-8),this.lineTo(-3,-5),this.lineTo(0,-2),this.stroke({width:1,color:0,cap:"round",join:"round"}),this.hitArea=new Ur(0,0,24)):(this.rect(-5,-5,10,10),this.fill({color:"#ffffff"}),this.stroke({width:1,color:5620223}),this.hitArea=new G(-15,-15,30,30))}#e=t=>{this.#t=!0,this.cursor="grabbing",this.callbacks.beginDrag(this.handle,t.global),t.stopPropagation()};#r=t=>{this.#t&&(this.callbacks.updateDrag(this.handle,t.global),t.stopPropagation())};#h=t=>{this.#t&&(this.#t=!1,this.cursor="pointer",this.callbacks.endDrag(),t.stopPropagation())}}const Hd={delta:new M};class kv extends st{group;wireframe=new Uv;isDragging=!1;lastPointer=new q;activeHandle=null;#t;#o=new Map;#e=new q;#r=0;#h=0;#a=new G;#i=new q;#l=new G;#s=1;#n=1;opts;constructor(t){super(),this.opts=t,this.group=t.group,this.eventMode="static";const e={beginDrag:(r,n)=>this.#y(r,n),updateDrag:(r,n)=>this.#x(r,n),endDrag:()=>this.#f()};this.#t={tl:new ce("tl","nwse-resize",e),tr:new ce("tr","nesw-resize",e),bl:new ce("bl","nesw-resize",e),br:new ce("br","nwse-resize",e),ml:new ce("ml","ew-resize",e),mr:new ce("mr","ew-resize",e),mt:new ce("mt","ns-resize",e),mb:new ce("mb","ns-resize",e),rot:new ce("rot","crosshair",{beginDrag:(r,n)=>this.#v(n),updateDrag:(r,n)=>this.#w(n),endDrag:()=>this.#f()})},this.addChild(this.wireframe,...Object.values(this.#t)),this.#m(),Et.shared.addOnce(()=>this.#c())}#m(){this.on("pointerdown",this.#g),this.on("pointerup",this.#u),this.on("pointerupoutside",this.#u),this.on("globalpointermove",this.#_)}#c(){if(this.group.length===1){const t=this.group[0],e=t.getBounds();this.#e.set(e.x+e.width/2,e.y+e.height/2),this.#r=t.rotation;let r,n;if(this.opts.clip)r=this.opts.clip.width,n=this.opts.clip.height;else{const o=t.getLocalBounds();r=o.width,n=o.height}this.#l.copyFrom(new G(-r/2,-n/2,r,n))}else{const t=this.#S();this.#e.set(t.x+t.width/2,t.y+t.height/2);const e=new G(-t.width/2,-t.height/2,t.width,t.height);this.#l.copyFrom(e)}this.#d()}updateBounds(){this.#c()}#g=t=>{this.#c(),this.isDragging=!0,this.lastPointer.copyFrom(t.global),this.cursor="grabbing"};#u=()=>{this.isDragging&&this.emit("transformEnd"),this.isDragging=!1,this.activeHandle=null,this.cursor="default"};#_=t=>{if(!this.isDragging||this.activeHandle||!this.parent)return;const e=this.parent.toLocal(this.lastPointer),r=this.parent.toLocal(t.global),n=r.x-e.x,o=r.y-e.y;for(const u of this.group)u.x+=n,u.y+=o;const l=t.global.x-this.lastPointer.x,h=t.global.y-this.lastPointer.y;this.#e.x+=l,this.#e.y+=h,this.lastPointer.copyFrom(t.global),this.#d()};#y(t,e){this.#c(),this.isDragging=!0,this.activeHandle=t,console.log("[Transformer] #beginHandleDrag called, activeHandle:",this.activeHandle),this.#o.clear();for(const r of this.group)this.#o.set(r,r.localTransform.clone());this.rotation=this.#r,this.#a.copyFrom(this.#l),this.#T(t)}#x(t,e){this.#b(t,e)}async#b(t,e){const r=this.#i,n=this.#C(t,this.toLocal(e),r),o=n.width/this.#a.width,l=n.height/this.#a.height,h=this.toGlobal(r);if(this.opts.clip&&this.opts.clip.constructor.name==="TextClip"){const f=n.width;console.log("[Transformer] TextClip scaling:",{handle:t,originalWidth:this.#a.width,newWidth:f,sx:o,sy:l}),this.emit("textClipResize",{handle:t,newWidth:f,newHeight:n.height,pivotWorld:h,proposed:n})}else this.#p(this.#E(h,this.#r,o,l));this.#l.copyFrom(n),this.#d()}#v(t){this.#c(),this.isDragging=!0,this.activeHandle="rot",this.#o.clear();for(const e of this.group)this.#o.set(e,e.localTransform.clone());this.#h=Math.atan2(t.y-this.#e.y,t.x-this.#e.x)}#w(t){const r=Math.atan2(t.y-this.#e.y,t.x-this.#e.x)-this.#h,n=this.#r+r;this.#p(this.#A(this.#e,r)),this.rotation=n,this.#d(n)}#f(){console.log("[Transformer] #endDrag called, activeHandle:",this.activeHandle),this.isDragging=!1,this.#r=this.rotation,this.activeHandle=null,this.#d(this.#r),this.emit("transformEnd")}#S(){let t=1/0,e=1/0,r=-1/0,n=-1/0;for(const o of this.group){const l=o.getBounds();t=Math.min(t,l.x),e=Math.min(e,l.y),r=Math.max(r,l.x+l.width),n=Math.max(n,l.y+l.height)}return new G(t,e,r-t,n-e)}#d(t=this.#r){this.parent&&this.position.copyFrom(this.parent.toLocal(this.#e)),this.rotation=t;const r=1/((this.parent?Math.abs(this.parent.worldTransform.a):1)||1),n=this.#l;this.wireframe.draw(n,r);const o=n.x+n.width/2,l=n.y+n.height/2,h=[this.#t.tl,this.#t.tr,this.#t.bl,this.#t.br,this.#t.ml,this.#t.mr,this.#t.mt,this.#t.mb,this.#t.rot];for(const u of h)u.scale.set(r);this.#t.tl.position.set(n.x,n.y),this.#t.tr.position.set(n.x+n.width,n.y),this.#t.bl.position.set(n.x,n.y+n.height),this.#t.br.position.set(n.x+n.width,n.y+n.height),this.#t.ml.position.set(n.x,l),this.#t.mr.position.set(n.x+n.width,l),this.#t.mt.position.set(o,n.y),this.#t.mb.position.set(o,n.y+n.height),this.#t.rot.position.set(o,n.y-30*r)}#T(t){const e=this.#a;if(this.opts.centeredScaling){this.#i.set(e.x+e.width/2,e.y+e.height/2);return}t==="tl"?this.#i.set(e.x+e.width,e.y+e.height):t==="tr"?this.#i.set(e.x,e.y+e.height):t==="bl"?this.#i.set(e.x+e.width,e.y):t==="br"?this.#i.set(e.x,e.y):t==="ml"?this.#i.set(e.x+e.width,e.y+e.height/2):t==="mr"?this.#i.set(e.x,e.y+e.height/2):t==="mt"?this.#i.set(e.x+e.width/2,e.y+e.height):t==="mb"&&this.#i.set(e.x+e.width/2,e.y)}#C(t,e,r){if(this.opts.centeredScaling){const o=Math.max(this.#s,Math.abs(e.x-r.x)*2),l=Math.max(this.#n,Math.abs(e.y-r.y)*2);return new G(r.x-o/2,r.y-l/2,o,l)}if(t==="tl"){const o=Math.min(e.x,r.x-this.#s),l=Math.min(e.y,r.y-this.#n);return new G(o,l,r.x-o,r.y-l)}if(t==="tr"){const o=Math.max(e.x,r.x+this.#s),l=Math.min(e.y,r.y-this.#n);return new G(r.x,l,o-r.x,r.y-l)}if(t==="bl"){const o=Math.min(e.x,r.x-this.#s),l=Math.max(e.y,r.y+this.#n);return new G(o,r.y,r.x-o,l-r.y)}if(t==="br"){const o=Math.max(e.x,r.x+this.#s),l=Math.max(e.y,r.y+this.#n);return new G(r.x,r.y,o-r.x,l-r.y)}const n=this.#a;if(t==="ml"){const o=Math.min(e.x,r.x-this.#s);return new G(o,n.y,r.x-o,n.height)}if(t==="mr"){const o=Math.max(e.x,r.x+this.#s);return new G(r.x,n.y,o-r.x,n.height)}if(t==="mt"){const o=Math.min(e.y,r.y-this.#n);return new G(n.x,o,n.width,r.y-o)}if(t==="mb"){const o=Math.max(e.y,r.y+this.#n);return new G(n.x,r.y,n.width,o-r.y)}return new G(r.x,r.y,this.#s,this.#n)}#E(t,e,r,n){return Hd.delta.identity().translate(-t.x,-t.y).rotate(-e).scale(r,n).rotate(e).translate(t.x,t.y)}#A(t,e){return Hd.delta.identity().translate(-t.x,-t.y).rotate(e).translate(t.x,t.y)}#p(t){for(const e of this.group){const r=this.#o.get(e),n=e.parent;if(!r||!n)continue;const o=n.worldTransform.clone().invert(),l=n.worldTransform.clone().append(r),h=t.clone().append(l),u=o.clone().append(h);e.setFromMatrix(u)}}}class Mv{pixiApp=null;clips=[];spriteRenderers=new Map;artboard=null;clipContainer=null;artboardMask=null;artboardBg=null;activeTransformer=null;selectedClips=new Set;interactiveClips=new Set;playbackElements=new Map;videoSprites=new Map;isPlaying=!1;currentTime=0;playStartTime=0;playStartTimestamp=0;rafId=null;maxDuration=0;opts;destroyed=!1;hexToNumber(t){const e=t.startsWith("#")?t.slice(1):t;return parseInt(e,16)}ready;constructor(t){this.opts={fps:30,bgColor:"#000000",...t},this.ready=this.initPixiApp()}async initPixiApp(){if(this.destroyed)return;const t=this.opts.canvas||document.createElement("canvas");t.width=this.opts.width,t.height=this.opts.height,console.log("Initializing Pixi.js Application...",{width:this.opts.width,height:this.opts.height});const e=new en,r=t.parentElement||window;console.log("Initializing Pixi.js Application...",{resizeTo:r}),await e.init({canvas:t,resizeTo:r,backgroundColor:this.hexToNumber(this.opts.bgColor),antialias:!0,resolution:window.devicePixelRatio||1,autoDensity:!0}),this.pixiApp=e,e.stage.eventMode="static",e.stage.hitArea=e.screen,e.stage.on("pointerdown",n=>{n.target===e.stage&&this.deselectClip()}),this.artboard=new st,this.artboard.label="ArtboardRoot",e.stage.addChild(this.artboard),this.clipContainer=new st,this.clipContainer.label="ClipContainer",this.artboard.addChild(this.clipContainer),this.artboardBg=new Zt,this.artboardBg.rect(0,0,this.opts.width,this.opts.height).fill({color:3355443}),this.clipContainer.addChild(this.artboardBg),this.artboardMask=new Zt,this.artboardMask.rect(0,0,this.opts.width,this.opts.height).fill({color:16777215}),this.clipContainer.addChild(this.artboardMask),this.clipContainer.mask=this.artboardMask,this.updateArtboardLayout(),e.renderer.on("resize",()=>{this.handleResize()})}handleResize=()=>{this.destroyed||!this.pixiApp||this.updateArtboardLayout()};updateArtboardLayout(){if(!this.pixiApp||!this.artboard)return;const t=this.pixiApp.canvas.width,e=this.pixiApp.canvas.height,r=this.opts.width,n=this.opts.height,o=this.pixiApp.canvas.parentElement?.clientWidth||t,l=this.pixiApp.canvas.parentElement?.clientHeight||e;this.pixiApp.renderer.resize(o,l);const h=o/r,u=l/n,f=Math.min(h,u);this.artboard.scale.set(f),this.artboard.x=(o-r*f)/2,this.artboard.y=(l-n*f)/2}getCanvas(){if(this.opts.canvas)return this.opts.canvas;if(this.pixiApp?.canvas)return this.pixiApp.canvas;throw new Error("Canvas not initialized yet. Wait for initPixiApp to complete.")}async addClip(t,e){if(this.destroyed)return;if(this.pixiApp==null)throw new Error("Failed to initialize Pixi.js Application");this.pixiApp!=null&&typeof t.setRenderer=="function"&&t.setRenderer(this.pixiApp.renderer);const r=await t.ready;this.clips.push(t);let n=t.duration>0?t.duration:r.duration;if(n===1/0||isNaN(n))await this.recalculateMaxDuration();else{const o=t.display.from+n;o>0&&(this.maxDuration=Math.max(this.maxDuration,o))}if(await this.setupPlaybackForClip(t,e),r.width>0&&r.height>0)if(t instanceof ft){if(t.tickInterceptor!=null){const o=new $i(this.pixiApp,t,this.clipContainer);this.spriteRenderers.set(t,o)}}else{const o=new $i(this.pixiApp,t,this.clipContainer);this.spriteRenderers.set(t,o)}await this.updateFrame(this.currentTime),this.setupSpriteInteractivity(t)}setupSpriteInteractivity(t){if(this.interactiveClips.has(t))return;const e=this.spriteRenderers.get(t);if(e==null)return;const r=e.getSprite();r!=null&&(r.eventMode="static",r.cursor="pointer",r.on("pointerdown",n=>{n.stopPropagation(),this.selectClip(t,n.shiftKey)}),this.interactiveClips.add(t))}async setupPlaybackForClip(t,e){if(this.pixiApp!=null){if(!this.isPlaybackCapable(t)){if(this.pixiApp!=null&&(await t.ready).width>0&&(await t.ready).height>0){const r=new $i(this.pixiApp,t,this.clipContainer);this.spriteRenderers.set(t,r)}return}try{const r=t;if(t instanceof mt&&e&&typeof e!="string"){const l=URL.createObjectURL(e);t.src=l}const{element:n,objectUrl:o}=await r.createPlaybackElement();if(t instanceof ft){const l=k.from(n),h=new ie(l);h.visible=!1,this.clipContainer&&this.clipContainer.addChild(h),this.videoSprites.set(t,h)}this.playbackElements.set(t,{element:n,objectUrl:o})}catch(r){if(console.warn(`Failed to setup playback for ${t.constructor.name}, falling back to PixiSpriteRenderer:`,r),this.pixiApp!=null){const n=await t.ready;if(n.width>0&&n.height>0){const o=new $i(this.pixiApp,t,this.artboard);this.spriteRenderers.set(t,o)}}}}}isPlaybackCapable(t){return"createPlaybackElement"in t&&"play"in t&&"pause"in t&&"seek"in t&&"syncPlayback"in t&&"cleanupPlayback"in t}async removeClip(t){const e=this.clips.findIndex(l=>l===t);if(e===-1)return;this.selectedClips.has(t)&&this.deselectClip(),this.clips.splice(e,1),this.interactiveClips.delete(t);const r=this.spriteRenderers.get(t);r!=null&&(r.destroy(),this.spriteRenderers.delete(t));const n=this.playbackElements.get(t);n!=null&&(this.isPlaybackCapable(t)&&t.cleanupPlayback(n.element,n.objectUrl),this.playbackElements.delete(t));const o=this.videoSprites.get(t);o!=null&&this.pixiApp!=null&&(this.artboard?.removeChild(o),o.destroy(),this.videoSprites.delete(t)),await this.recalculateMaxDuration()}clear(){this.deselectClip(),this.interactiveClips.clear(),this.spriteRenderers.forEach(t=>{t.destroy()}),this.spriteRenderers.clear();for(const[t,e]of this.playbackElements.entries())this.isPlaybackCapable(t)&&t.cleanupPlayback(e.element,e.objectUrl);this.playbackElements.clear();for(const t of this.videoSprites.values())t.destroy();this.videoSprites.clear(),this.clips=[],this.maxDuration=0,this.currentTime=0}async play(){if(!(this.isPlaying||this.destroyed)){if(this.maxDuration<=0||this.maxDuration===1/0||isNaN(this.maxDuration)){console.warn("Cannot play: invalid duration",this.maxDuration);return}this.isPlaying||(this.isPlaying=!0),this.playStartTime=this.currentTime,this.playStartTimestamp=performance.now();for(const[t,{element:e}]of this.playbackElements.entries()){if(!(this.currentTime>=t.display.from&&(t.display.to===0||this.currentTime<=t.display.to))){this.isPlaybackCapable(t)&&t.pause(e);continue}const n=(this.currentTime-t.display.from)/1e6;this.isPlaybackCapable(t)&&await t.play(e,n)}this.renderLoop()}}pause(){this.isPlaying=!1,this.rafId!=null&&(cancelAnimationFrame(this.rafId),this.rafId=null);for(const[t,{element:e}]of this.playbackElements.entries())this.isPlaybackCapable(t)&&t.pause(e)}async stop(){this.pause(),await this.seek(0)}async seek(t){if(this.destroyed)return;const e=this.isPlaying;this.playStartTime=Math.max(0,Math.min(t,this.maxDuration)),this.playStartTimestamp=performance.now(),this.currentTime=this.playStartTime;for(const[r,{element:n}]of this.playbackElements.entries()){if(!(this.currentTime>=r.display.from&&(r.display.to===0||this.currentTime<=r.display.to))){this.isPlaybackCapable(r)&&r.pause(n);continue}const l=(this.currentTime-r.display.from)/1e6;this.isPlaybackCapable(r)&&await r.seek(n,l)}if(await this.updateFrame(this.currentTime),e){this.isPlaying=!0;for(const[r,{element:n}]of this.playbackElements.entries()){if(!(this.currentTime>=r.display.from&&(r.display.to===0||this.currentTime<=r.display.to)))continue;const l=(this.currentTime-r.display.from)/1e6;this.isPlaybackCapable(r)&&await r.play(n,l)}}}getCurrentTime(){return this.currentTime}getMaxDuration(){return this.maxDuration===1/0||isNaN(this.maxDuration)||this.maxDuration<=0?0:this.maxDuration}getIsPlaying(){return this.isPlaying}async renderLoop(){if(!this.isPlaying||this.destroyed||this.pixiApp==null)return;if(this.maxDuration<=0||this.maxDuration===1/0||isNaN(this.maxDuration)){this.pause();return}const t=async()=>{if(!this.isPlaying||this.destroyed||this.pixiApp==null)return;if(this.currentTime>=this.maxDuration){this.currentTime=this.maxDuration,this.pause();return}const r=(performance.now()-this.playStartTimestamp)*1e3;this.currentTime=Math.min(this.playStartTime+r,this.maxDuration);try{await this.updateFrame(this.currentTime)}catch(n){console.warn("Error updating frame:",n)}this.isPlaying&&(this.rafId=requestAnimationFrame(t))};t()}async updateFrame(t){if(this.destroyed||this.pixiApp==null)return;const e=[...this.clips].sort((r,n)=>r.zIndex-n.zIndex);for(const r of e){if(t<r.display.from){const m=this.spriteRenderers.get(r);m!=null&&await m.updateFrame(null);continue}if(r.display.to>0&&t>r.display.to){const m=this.spriteRenderers.get(r);m!=null&&await m.updateFrame(null);continue}const n=t-r.display.from,o=n*r.playbackRate;r.animate(o);const l=await r.ready,h=r.duration||l.duration;if(h>0&&n>h){const m=this.spriteRenderers.get(r);m!=null&&await m.updateFrame(null);continue}const u=this.playbackElements.get(r);if(u!=null&&this.isPlaybackCapable(r)){const m=n/1e6;if(r.syncPlayback(u.element,this.isPlaying,m),r instanceof ft){const g=this.videoSprites.get(r);if(g!=null){const y=r.meta.duration/1e6;if(this.spriteRenderers.has(r))g.visible=!1;else{g.visible=m>=0&&m<y,g.visible&&Tv(r,g);continue}}}else continue}const f=this.spriteRenderers.get(r);if(f!=null){const m=this.selectedClips.has(r);if(r instanceof Ut){const y=r.getTexture();if(y!=null){await f.updateFrame(y),m||f.updateTransforms();continue}}if(r instanceof Xt){const y=await r.getTexture();if(y!=null){await f.updateFrame(y),m||f.updateTransforms();continue}}if(r instanceof Ue){r.updateState(n);const y=await r.getTexture();if(y!=null){await f.updateFrame(y),m||f.updateTransforms();continue}else console.log("[Studio] CaptionClip texture is null, falling back to traditional path")}const{video:g}=await r.getFrame(n);await f.updateFrame(g),m||f.updateTransforms()}}this.pixiApp!=null&&this.pixiApp.render()}async recalculateMaxDuration(){this.maxDuration=0;for(const t of this.clips){const e=await t.ready,r=t.duration>0?t.duration:e.duration,n=t.display.from+r;n!==1/0&&!isNaN(n)&&n>0&&(this.maxDuration=Math.max(this.maxDuration,n))}}destroy(){this.destroyed||(window.removeEventListener("resize",this.handleResize),this.destroyed=!0,this.stop(),this.clear(),this.pixiApp&&(this.pixiApp.destroy(!0,{children:!0,texture:!0}),this.pixiApp=null))}selectClip(t,e=!1){if(!(this.destroyed||this.pixiApp==null)){if(e||this.deselectClip(),e&&this.selectedClips.has(t)){this.selectedClips.delete(t),this.activeTransformer!=null&&(this.activeTransformer.parent&&this.activeTransformer.parent.removeChild(this.activeTransformer),this.activeTransformer.destroy(),this.activeTransformer=null),this.selectedClips.size>0&&this.createTransformer();return}this.selectedClips.add(t),this.activeTransformer!=null&&(this.activeTransformer.parent&&this.activeTransformer.parent.removeChild(this.activeTransformer),this.activeTransformer.destroy(),this.activeTransformer=null),this.createTransformer()}}createTransformer(){if(this.destroyed||this.artboard==null||this.selectedClips.size===0)return;const t=[];let e=null;for(const n of this.selectedClips){const o=this.spriteRenderers.get(n);if(o==null)continue;const l=o.getSprite();l!=null&&(t.push(l),this.selectedClips.size===1&&(e=n))}if(t.length===0){console.warn("Cannot create transformer: no sprites found");return}this.activeTransformer=new kv({group:t,clip:e}),console.log("[Studio] Transformer created, setting up listeners");let r=null;this.activeTransformer.on("transforming",()=>{r===null&&(r=requestAnimationFrame(()=>{r=null,this.syncSelectedClipsTransformsRealtime()}))}),this.activeTransformer.on("textClipResize",n=>{this.textClipResizedWidth=n.newWidth,console.log("[Studio] textClipResize event:",{newWidth:n.newWidth})}),this.activeTransformer.on("transformEnd",()=>{console.log("[Studio] transformEnd event fired!"),r!==null&&(cancelAnimationFrame(r),r=null),this.syncSelectedClipsTransforms()}),this.artboard.addChild(this.activeTransformer)}isUpdatingTextClipRealtime=!1;textClipResizedWidth=null;async syncSelectedClipsTransformsRealtime(){if(!(this.selectedClips.size===0||this.activeTransformer==null)&&!this.isUpdatingTextClipRealtime){this.isUpdatingTextClipRealtime=!0;try{if(this.activeTransformer.activeHandle!=="mr")return;for(const e of this.selectedClips){if(!(e instanceof Xt))continue;const r=this.spriteRenderers.get(e);if(r==null)continue;const n=r.getSprite();if(n==null||n.texture==null)continue;const o=Math.abs(n.scale.x);if(o===1)continue;const l=e.left,h=e.top,u=n.texture.width,f=o*u;console.log("[Studio] Reflow triggered:",{preservedLeft:l,currentScale:o,textureWidth:u,newWidth:f}),await e.updateStyle({wordWrap:!0,wordWrapWidth:f});const m=await e.getTexture();m&&(await r.updateFrame(m),n.scale.set(1,1),e.left=l,e.top=h,n.x=e.left+e.width/2,n.y=e.top+e.height/2,console.log("[Studio] Reflow complete:",{clipWidth:e.width,spriteScale:n.scale.x}))}}finally{this.isUpdatingTextClipRealtime=!1}}}async syncSelectedClipsTransforms(){if(console.log("[Studio] syncSelectedClipsTransforms called"),!(this.selectedClips.size===0||this.activeTransformer==null)){for(const t of this.selectedClips){const e=this.spriteRenderers.get(t);if(e==null)continue;const r=e.getSprite();if(r==null||r.texture==null)continue;console.log("[Studio] Sprite state before calculations:",{spriteScale:{x:r.scale.x,y:r.scale.y},spritePosition:{x:r.x,y:r.y},textureSize:{width:r.texture.width,height:r.texture.height},clipDimensions:{width:t.width,height:t.height}});const n=r.texture.width,o=r.texture.height,l=Math.abs(r.scale.x)*n,h=Math.abs(r.scale.y)*o;console.log("[Studio] Calculated dimensions:",{newWidth:l,newHeight:h,calculation:`${r.scale.x} * ${n} = ${l}`,storedTextClipWidth:this.textClipResizedWidth});const u=t instanceof Xt&&this.textClipResizedWidth!==null?this.textClipResizedWidth:l;console.log("[Studio] Using width:",{finalNewWidth:u,source:t instanceof Xt&&this.textClipResizedWidth!==null?"stored":"calculated"});const f=r.x-u/2,m=r.y-h/2;if(t instanceof Xt&&this.textClipResizedWidth!==null){console.log("[Studio] TextClip resize detected - doing reflow:",{spriteScale:{x:r.scale.x,y:r.scale.y},textureSize:{width:n,height:o},newWidth:l,newHeight:h,spritePosition:{x:r.x,y:r.y},resizedWidth:this.textClipResizedWidth}),await t.updateStyle({wordWrap:!0,wordWrapWidth:u}),console.log("[Studio] TextClip after updateStyle:",{clipWidth:t.width,clipHeight:t.height});const g=await t.getTexture();console.log("[Studio] New texture:",{width:g?.width,height:g?.height}),g&&(await e.updateFrame(g),t.width=u,t.height=g.height,this.textClipResizedWidth=null,t.left=r.x-t.width/2,t.top=r.y-t.height/2,r.scale.set(1,1),console.log("[Studio] After texture update (before transform update):",{clipDimensions:{width:t.width,height:t.height},clipPosition:{left:t.left,top:t.top},spriteScale:{x:r.scale.x,y:r.scale.y}}))}else t.left=f,t.top=m,t.width=l,t.height=h,t.angle=r.rotation}this.activeTransformer!=null&&this.activeTransformer.updateBounds();for(const t of this.selectedClips){const e=this.spriteRenderers.get(t);e?.updateTransforms()}}}deselectClip(){if(this.selectedClips.size>0&&this.activeTransformer!=null)for(const t of this.selectedClips){const e=this.spriteRenderers.get(t);if(e!=null){const r=e.getSprite();if(r!=null&&r.texture!=null){const n=r.texture.width,o=r.texture.height,l=Math.abs(r.scale.x)*n,h=Math.abs(r.scale.y)*o,u=r.x-l/2,f=r.y-h/2;t.left=u,t.top=f,t.width=l,t.height=h,t.angle=r.rotation,e.updateTransforms()}}}this.activeTransformer!=null&&(this.activeTransformer.parent!=null&&this.activeTransformer.parent.removeChild(this.activeTransformer),this.activeTransformer.destroy(),this.activeTransformer=null),this.selectedClips.clear()}exportToJSON(){return{clips:this.clips.map(e=>mo(e,!1)),settings:{width:this.opts.width,height:this.opts.height,fps:this.opts.fps,bgColor:this.opts.bgColor}}}async loadFromJSON(t){if(this.clear(),t.settings){const r=t.settings.width&&t.settings.width!==this.opts.width||t.settings.height&&t.settings.height!==this.opts.height;if(t.settings.width&&(this.opts.width=t.settings.width),t.settings.height&&(this.opts.height=t.settings.height),t.settings.fps&&(this.opts.fps=t.settings.fps),t.settings.bgColor&&(this.opts.bgColor=t.settings.bgColor),r&&this.pixiApp!=null){const n=this.opts.width,o=this.opts.height;this.pixiApp.renderer.resize(n,o),this.opts.canvas&&(this.opts.canvas.width=n,this.opts.canvas.height=o)}}const e=[];for(const r of t.clips){if(r.type!=="Text"&&r.type!=="Caption"&&(!r.src||r.src.trim()==="")){e.push(r.type);continue}try{const n=await go(r),o=n instanceof mt?r.src:void 0;await this.addClip(n,o),(n instanceof ft||n instanceof Ut)&&(!r.width||!r.height)&&(await n.scaleToFit(this.opts.width,this.opts.height),n.centerInScene(this.opts.width,this.opts.height))}catch(n){console.warn(`Failed to load clip of type ${r.type}:`,n),e.push(r.type)}}e.length>0&&console.warn(`Skipped ${e.length} clip(s) that could not be loaded (empty source URLs or load errors):`,e)}}class ii{static instance;fonts=new Map;constructor(){}static getInstance(){return ii.instance||(ii.instance=new ii),ii.instance}async addFont(t){if(!this.fonts.has(t.name))try{const r=await new FontFace(t.name,`url(${t.url})`).load();document.fonts.add(r),this.fonts.set(t.name,r)}catch(e){console.error(`Failed to load font ${t.name}:`,e)}}async loadFonts(t){await Promise.all(t.map(e=>this.addFont(e)))}removeFont(t){const e=this.fonts.get(t);e&&(document.fonts.delete(e),this.fonts.delete(t))}clear(){this.fonts.forEach(t=>{document.fonts.delete(t)}),this.fonts.clear()}getLoadedFonts(){return Array.from(this.fonts.keys())}}const Rv=ii.getInstance();D.add(Gp),D.mixin(st,Lp),D.add(wh),D.add(Sh),D.add(Ul),D.mixin(st,uy),D.add(Bl),D.add(pd),D.add(vn),D.add(_d),D.add(wd),D.add(Sd),D.add(Id),D.add(Rd),D.add(Ad),D.add(kd),D.add(Bd),D.add(Ed),D.add(Cd),D.add(Il),D.add(Ml);const Iv=Object.freeze(Object.defineProperty({__proto__:null},Symbol.toStringTag,{value:"Module"})),Fv=Object.freeze(Object.defineProperty({__proto__:null},Symbol.toStringTag,{value:"Module"}));rt.AudioClip=mt,rt.CaptionClip=Ue,rt.Compositor=Ev,rt.ImageClip=Ut,rt.Log=H,rt.MP4Clip=ft,rt.Studio=Mv,rt.TextClip=Xt,rt.VideoClip=ft,rt.clipToJSON=mo,rt.createChromakey=vf,rt.fastConcatMP4=zd,rt.fixFMP4Duration=xv,rt.fontManager=Rv,rt.jsonToClip=go,rt.mixinMP4AndAudio=Sv,rt.renderTxt2ImgBitmap=Cf,Object.defineProperty(rt,Symbol.toStringTag,{value:"Module"})}));
|