untitled-pixi-live2d-engine 1.3.2 → 1.3.3

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/index.min.js CHANGED
@@ -1 +1 @@
1
- !function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports,require("pixi.js")):"function"==typeof define&&define.amd?define(["exports","pixi.js"],e):e(((t="undefined"!=typeof globalThis?globalThis:t||self).PIXI=t.PIXI||{},t.PIXI.live2d=t.PIXI.live2d||{}),t.PIXI)}(this,function(t,e){"use strict";var i=Object.defineProperty,s=Object.defineProperties,r=Object.getOwnPropertyDescriptors,a=Object.getOwnPropertySymbols,n=Object.prototype.hasOwnProperty,o=Object.prototype.propertyIsEnumerable,l=Math.pow,u=(t,e,s)=>e in t?i(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,h=(t,e)=>{for(var i in e||(e={}))n.call(e,i)&&u(t,i,e[i]);if(a)for(var i of a(e))o.call(e,i)&&u(t,i,e[i]);return t},d=(t,e,i)=>u(t,"symbol"!=typeof e?e+"":e,i),g=(t,e,i)=>new Promise((s,r)=>{var a=t=>{try{o(i.next(t))}catch(e){r(e)}},n=t=>{try{o(i.throw(t))}catch(e){r(e)}},o=t=>t.done?s(t.value):Promise.resolve(t.value).then(a,n);o((i=i.apply(t,e)).next())});const c={LOG_LEVEL_VERBOSE:0,LOG_LEVEL_WARNING:1,LOG_LEVEL_ERROR:2,LOG_LEVEL_NONE:999,logLevel:1,sound:!0,fftSize:512,motionSync:!0,motionFadingDuration:500,idleMotionFadingDuration:2e3,expressionFadingDuration:500,preserveExpressionOnMotion:!0,cubism:Object.freeze(Object.defineProperty({__proto__:null,CSM_LOG_LEVEL:0,CSM_LOG_LEVEL_DEBUG:1,CSM_LOG_LEVEL_ERROR:4,CSM_LOG_LEVEL_INFO:2,CSM_LOG_LEVEL_OFF:5,CSM_LOG_LEVEL_VERBOSE:0,CSM_LOG_LEVEL_WARNING:3},Symbol.toStringTag,{value:"Module"}))},p={log(t,...e){c.logLevel<=c.LOG_LEVEL_VERBOSE&&console.log(`[${t}]`,...e)},warn(t,...e){c.logLevel<=c.LOG_LEVEL_WARNING&&console.warn(`[${t}]`,...e)},error(t,...e){c.logLevel<=c.LOG_LEVEL_ERROR&&console.error(`[${t}]`,...e)}};function m(t,e,i){return t<e?e:t>i?i:t}function _(t,e){return Math.random()*(e-t)+t}function f(t){return 1024*t*1024}function y(t,e,i,s,r){const a=e[s];null!==a&&typeof a===t&&(i[r]=a)}function x(t,e,i,s,r){const a=e[s];Array.isArray(a)&&(i[r]=a.filter(e=>null!==e&&typeof e===t))}function M(t,e){e.forEach(e=>{Object.getOwnPropertyNames(e.prototype).forEach(i=>{"constructor"!==i&&Object.defineProperty(t.prototype,i,Object.getOwnPropertyDescriptor(e.prototype,i))})})}function C(t){let e=t.lastIndexOf("/");return-1!=e&&(t=t.slice(0,e)),e=t.lastIndexOf("/"),-1!==e&&(t=t.slice(e+1)),t}function S(t,e){const i=t.indexOf(e);-1!==i&&t.splice(i,1)}const v=/^[a-zA-Z][a-zA-Z0-9+.-]*:/;function b(t,e){if(!e)return t;if(v.test(e))return e;if(e.startsWith("/"))return v.test(t)?new URL(e,t).toString():e;if(v.test(t))return new URL(e,t).toString();const i="http://example.com",s=t.startsWith("/")?i+t:`${i}/${t}`,r=new URL(e,s);let a=r.pathname+r.search+r.hash;return!t.startsWith("/")&&a.startsWith("/")&&(a=a.slice(1)),a}class P extends e.EventEmitter{constructor(t,e){super(),d(this,"expressionDataType","json"),d(this,"tag"),d(this,"settings"),d(this,"expressions",[]),d(this,"defaultExpression"),d(this,"currentExpression"),d(this,"reserveExpressionIndex",-1),d(this,"destroyed",!1),this.settings=t,this.tag=`ExpressionManager(${t.name})`}init(){this.defaultExpression=this.createDefaultExpression(),this.currentExpression=this.defaultExpression,this.stopAllExpressions()}createDefaultExpression(){return this.createExpression({},void 0)}loadExpression(t){return g(this,null,function*(){if(!this.definitions[t])return void p.warn(this.tag,`Undefined expression at [${t}]`);if(null===this.expressions[t])return void p.warn(this.tag,`Cannot set expression at [${t}] because it's already failed in loading.`);if(this.expressions[t])return this.expressions[t];const e=yield this._loadExpression(t);return this.expressions[t]=e,e})}_loadExpression(t){throw new Error("Not implemented.")}setRandomExpression(){return g(this,null,function*(){if(this.definitions.length){const t=[];for(let e=0;e<this.definitions.length;e++)null!==this.expressions[e]&&this.expressions[e]!==this.currentExpression&&e!==this.reserveExpressionIndex&&t.push(e);if(t.length){const e=Math.floor(Math.random()*t.length);return this.setExpression(e)}}return!1})}resetExpression(){this._setExpression(this.defaultExpression)}restoreExpression(){this._setExpression(this.currentExpression)}setExpression(t){return g(this,null,function*(){if("number"!=typeof t&&(t=this.getExpressionIndex(t)),!(t>-1&&t<this.definitions.length))return!1;if(t===this.expressions.indexOf(this.currentExpression))return!1;this.reserveExpressionIndex=t;const e=yield this.loadExpression(t);return!(!e||this.reserveExpressionIndex!==t)&&(this.reserveExpressionIndex=-1,this.currentExpression=e,this._setExpression(e),!0)})}update(t,e){return!this.isFinished()&&this.updateParameters(t,e)}destroy(){this.destroyed=!0,this.emit("destroy");this.definitions=void 0,this.expressions=void 0}}const B=40/7.5,w=1/150;class I{constructor(){d(this,"targetX",0),d(this,"targetY",0),d(this,"x",0),d(this,"y",0),d(this,"vx",0),d(this,"vy",0)}focus(t,e,i=!1){this.targetX=m(t,-1,1),this.targetY=m(e,-1,1),i&&(this.x=this.targetX,this.y=this.targetY)}update(t){const e=this.targetX-this.x,i=this.targetY-this.y;if(Math.abs(e)<.01&&Math.abs(i)<.01)return;const s=Math.sqrt(l(e,2)+l(i,2)),r=B/(1e3/t);let a=r*(e/s)-this.vx,n=r*(i/s)-this.vy;const o=Math.sqrt(l(a,2)+l(n,2)),u=r*w*t;o>u&&(a*=u/o,n*=u/o),this.vx+=a,this.vy+=n;const h=Math.sqrt(l(this.vx,2)+l(this.vy,2)),d=.5*(Math.sqrt(l(u,2)+8*u*s)-u);h>d&&(this.vx*=d/h,this.vy*=d/h),this.x+=this.vx,this.y+=this.vy}}class F{constructor(t){d(this,"json"),d(this,"name"),d(this,"url"),d(this,"pose"),d(this,"physics"),this.json=t,this.url=t.url,this.name=C(this.url)}normalizeName(){this.name&&"name"!==this.name.toLowerCase()||(this.name=C(this.url))}setModelName(...t){for(const e of t){const t="string"==typeof e?e.trim():"";if(t&&"name"!==t.toLowerCase())return void(this.name=t)}this.normalizeName()}getFileStem(t){if(!t)return;const e=t.split(/[/\\]/).filter(Boolean).pop();return null==e?void 0:e.replace(/\.[^.]+$/,"")}resolveURL(t){return b(this.url,t)}replaceFiles(t){this.moc=t(this.moc,"moc"),void 0!==this.pose&&(this.pose=t(this.pose,"pose")),void 0!==this.physics&&(this.physics=t(this.physics,"physics"));for(let e=0;e<this.textures.length;e++)this.textures[e]=t(this.textures[e],`textures[${e}]`)}getDefinedFiles(){const t=[];return this.replaceFiles(e=>(t.push(e),e)),t}validateFiles(t){const e=(e,i)=>{const s=this.resolveURL(e);if(!t.includes(s)){if(i)throw new Error(`File "${e}" is defined in settings, but doesn't exist in given files`);return!1}return!0};[this.moc,...this.textures].forEach(t=>e(t,!0));return this.getDefinedFiles().filter(t=>e(t,!1))}}var E=(t=>(t[t.NONE=0]="NONE",t[t.IDLE=1]="IDLE",t[t.NORMAL=2]="NORMAL",t[t.FORCE=3]="FORCE",t))(E||{});class L{constructor(){d(this,"tag"),d(this,"debug",!1),d(this,"currentPriority",0),d(this,"reservePriority",0),d(this,"currentGroup"),d(this,"currentIndex"),d(this,"reservedGroup"),d(this,"reservedIndex"),d(this,"reservedIdleGroup"),d(this,"reservedIdleIndex")}reserve(t,e,i){if(i<=0)return p.log(this.tag,"Cannot start a motion with MotionPriority.NONE."),!1;if(t===this.currentGroup&&e===this.currentIndex)return p.log(this.tag,"Motion is already playing.",this.dump(t,e)),!1;if(t===this.reservedGroup&&e===this.reservedIndex||t===this.reservedIdleGroup&&e===this.reservedIdleIndex)return p.log(this.tag,"Motion is already reserved.",this.dump(t,e)),!1;if(1===i){if(0!==this.currentPriority)return p.log(this.tag,"Cannot start idle motion because another motion is playing.",this.dump(t,e)),!1;if(void 0!==this.reservedIdleGroup)return p.log(this.tag,"Cannot start idle motion because another idle motion has reserved.",this.dump(t,e)),!1;this.setReservedIdle(t,e)}else{if(i<3){if(i<=this.currentPriority)return p.log(this.tag,"Cannot start motion because another motion is playing as an equivalent or higher priority.",this.dump(t,e)),!1;if(i<=this.reservePriority)return p.log(this.tag,"Cannot start motion because another motion has reserved as an equivalent or higher priority.",this.dump(t,e)),!1}this.setReserved(t,e,i)}return!0}start(t,e,i,s){if(1===s){if(this.setReservedIdle(void 0,void 0),0!==this.currentPriority)return p.log(this.tag,"Cannot start idle motion because another motion is playing.",this.dump(e,i)),!1}else{if(e!==this.reservedGroup||i!==this.reservedIndex)return p.log(this.tag,"Cannot start motion because another motion has taken the place.",this.dump(e,i)),!1;this.setReserved(void 0,void 0,0)}return!!t&&(this.setCurrent(e,i,s),!0)}complete(){this.setCurrent(void 0,void 0,0)}setCurrent(t,e,i){this.currentPriority=i,this.currentGroup=t,this.currentIndex=e}setReserved(t,e,i){this.reservePriority=i,this.reservedGroup=t,this.reservedIndex=e}setReservedIdle(t,e){this.reservedIdleGroup=t,this.reservedIdleIndex=e}isActive(t,e){return t===this.currentGroup&&e===this.currentIndex||t===this.reservedGroup&&e===this.reservedIndex||t===this.reservedIdleGroup&&e===this.reservedIdleIndex}reset(){this.setCurrent(void 0,void 0,0),this.setReserved(void 0,void 0,0),this.setReservedIdle(void 0,void 0)}shouldRequestIdleMotion(){return void 0===this.currentGroup&&void 0===this.reservedIdleGroup}shouldOverrideExpression(){return!c.preserveExpressionOnMotion&&this.currentPriority>1}dump(t,e){if(this.debug){return`\n<Requested> group = "${t}", index = ${e}\n`+["currentPriority","reservePriority","currentGroup","currentIndex","reservedGroup","reservedIndex","reservedIdleGroup","reservedIdleIndex"].map(t=>"["+t+"] "+this[t]).join("\n")}return""}}const V="SoundManager",T=.5;let R,D=0;const A=new WeakSet;function O(t){if(!A.has(t)){try{t.disableAutoPause=!0}catch(e){p.warn(V,"Failed to disable @pixi/sound auto pause.",e)}A.add(t)}return t}function k(){return g(this,null,function*(){const t="undefined"!=typeof PIXI?null==PIXI?void 0:PIXI.sound:void 0;return t?O(t):(null!=R||(R=import("@pixi/sound").then(({sound:t})=>O(t)).catch(t=>(p.warn(V,"@pixi/sound is not available. Load pixi-sound.js before using motion sounds, speak(), or lip sync.",t),null))),R)})}function N(t,e){try{t.remove(e)}catch(i){p.warn(V,`Failed to remove sound "${e}".`,i)}}function U(t){const e=t.media.buffer;if(!e||"object"!=typeof e)return;return"function"==typeof e.getChannelData?e:void 0}class z{static get volume(){return this._volume}static set volume(t){this._volume=(t>1?1:t<0?0:t)||0,this.audios.forEach(t=>t.volume=this._volume)}static add(t,e){return g(this,null,function*(){let i,s=null;try{if(s=yield k(),!s)throw new Error("@pixi/sound is not available");i="live2d-sound-"+D++;const e=s,r=i,a=new Promise((i,s)=>{const a=e.add(r,{url:t,volume:this._volume,preload:!0,loaded:(e,r)=>{if(e)return void s(e);const n=null!=r?r:a;n?U(n)?i(n):s(new Error(`Error: ${t} is not WebAudioMedia`)):s(new Error(`Error: ${t} failed to load`))}})}),n=yield a;return this.aliases.set(n,{alias:r,library:e}),this.audios.push(n),n}catch(r){return s&&i&&N(s,i),p.warn(V,`Error occurred on "${t}"`,r),null==e||e(r),null}})}static play(t,e){t.play({singleInstance:!0,complete:()=>{null==e||e(),this.dispose(t)}})}static addAnalyzer(t,e){const i=U(t);if(!i)return void p.warn(V,"Cannot create audio analyzer because WebAudio media is unavailable.");const s=e.createBufferSource();s.buffer=i;const r=e.createAnalyser();return r.fftSize=c.fftSize,r.minDecibels=-90,r.maxDecibels=-10,r.smoothingTimeConstant=.85,s.connect(r),s.start(0),this.analysers.push(r),r}static analyze(t){if(!t)return parseFloat(Math.random().toFixed(1));const e=new Float32Array(t.fftSize);t.getFloatTimeDomainData(e);let i=0;for(let n=0;n<e.length;n++)i+=l(e[n],2);const s=Math.sqrt(i/e.length),r=20*Math.log10(s||l(10,-5)),a=Math.min(Math.max((r-t.minDecibels)/(t.maxDecibels-t.minDecibels),0),1);return parseFloat(a.toFixed(1))}static dispose(t){try{t.pause()}catch(i){p.warn(V,"Failed to pause audio.",i)}const e=this.aliases.get(t);e?(N(e.library,e.alias),this.aliases.delete(t)):function(t){try{t.destroy()}catch(i){p.warn(V,"Failed to destroy audio.",i)}}(t),S(this.audios,t)}static destroy(){for(let t=this.contexts.length-1;t>=0;t--){const e=this.contexts[t];null==e||e.close().catch(t=>{p.warn(V,"Failed to close AudioContext.",t)})}for(let t=this.audios.length-1;t>=0;t--)this.dispose(this.audios[t])}}d(z,"audios",[]),d(z,"analysers",[]),d(z,"contexts",[]),d(z,"aliases",new WeakMap),d(z,"_volume",T);var j=(t=>(t.ALL="ALL",t.IDLE="IDLE",t.NONE="NONE",t))(j||{});class G extends e.EventEmitter{constructor(t){super(),d(this,"tag"),d(this,"settings"),d(this,"motionGroups",{}),d(this,"state",new L),d(this,"currentAudio"),d(this,"currentAnalyzer"),d(this,"currentContext"),d(this,"playing",!1),d(this,"destroyed",!1),d(this,"parent"),this.settings=t.settings,this.tag=`MotionManager(${this.settings.name})`,this.state.tag=this.tag,this.parent=t}init(t){(null==t?void 0:t.idleMotionGroup)&&(this.groups.idle=t.idleMotionGroup),this.setupMotions(t),this.stopAllMotions()}setupMotions(t){if(!this.definitions)return void p.warn(this.tag,"Motion definitions are not initialized.");for(const i of Object.keys(this.definitions))this.motionGroups[i]=[];let e;switch(null==t?void 0:t.motionPreload){case"NONE":return;case"ALL":e=Object.keys(this.definitions);break;default:e=[this.groups.idle]}for(const i of e){const t=this.definitions[i];if(t)for(let e=0;e<t.length;e++)this.loadMotion(i,e)}}loadMotion(t,e){return g(this,null,function*(){var i,s;if(this.destroyed)return;if(!this.getMotionDefinition(t,e))return;const r=null!=(s=(i=this.motionGroups)[t])?s:i[t]=[];if(null===r[e])return void p.warn(this.tag,`Cannot start motion at "${t}"[${e}] because it's already failed in loading.`);if(r[e])return r[e];const a=yield this._loadMotion(t,e);return this.destroyed?void 0:(r[e]=null!=a?a:null,a)})}_loadMotion(t,e){throw new Error("Not implemented.")}initializeAudio(t,e){this.currentAudio=t,z.volume=e,this.currentContext=t.context.audioContext,this.currentAnalyzer=z.addAnalyzer(this.currentAudio,this.currentContext)}speak(t){return g(this,arguments,function*(t,{volume:e=.5,expression:i,resetExpression:s=!0,onFinish:r,onError:a}={}){if(!c.sound)return!1;let n,o;if(this.currentAudio&&this.currentAudio.isPlaying)return!1;const l=t&&t.startsWith("data:");if(t&&!l){const e=document.createElement("a");e.href=t,o=t=e.href}else o="data:audio/";const u=t;if(u)try{if(n=yield z.add(u,(t,e=this)=>{p.error(this.tag,"Error during audio playback:",t),null==a||a(t),s&&i&&e.expressionManager&&e.expressionManager.resetExpression(),e.currentAudio=void 0}),!n)return!1;this.initializeAudio(n,e)}catch(h){return p.warn(this.tag,"Failed to create audio",o,h),!1}if(n){let t=!0;try{c.motionSync&&z.play(n,()=>{null==r||r(),s&&i&&this.expressionManager&&this.expressionManager.resetExpression(),this.currentAudio=void 0})}catch(h){p.warn(this.tag,"Failed to play audio",n.url,h),t=!1}if(!t)return!1}return this.state.shouldOverrideExpression()&&this.expressionManager&&this.expressionManager.resetExpression(),i&&this.expressionManager&&(yield this.expressionManager.setExpression(i)),this.playing=!0,!0})}startMotion(t,e){return g(this,arguments,function*(t,e,i=E.NORMAL,{sound:s,volume:r=.5,expression:a,resetExpression:n=!0,onFinish:o,onError:l,ignoreParamIds:u=[],loop:h}={}){if(this.destroyed)return!1;if(!this.state.reserve(t,e,i))return!1;if(this.currentAudio&&this.currentAudio.isPlaying&&i!=E.FORCE)return!1;const d=this.getMotionDefinition(t,e);if(!d)return!1;let g,m;this.currentAudio&&z.dispose(this.currentAudio);const _=s&&s.startsWith("data:");if(s&&!_){const t=document.createElement("a");t.href=s,m=s=t.href}else m=this.getSoundFile(d),m&&(m=this.settings.resolveURL(m));const f=m;if(f)try{g=yield z.add(f,(t,e=this)=>{p.error(this.tag,"Error during audio playback:",t),null==l||l(t),n&&a&&e.expressionManager&&e.expressionManager.resetExpression(),e.currentAudio=void 0}),g&&this.initializeAudio(g,r)}catch(x){p.warn(this.tag,"Failed to create audio",m,x)}const y=yield this.loadMotion(t,e);if(g&&c.motionSync)try{z.play(g,(t=this)=>{null==o||o(),n&&a&&t.expressionManager&&t.expressionManager.resetExpression(),t.currentAudio=void 0})}catch(x){p.warn(this.tag,"Failed to play audio",g.url,x)}return this.state.start(y,t,e,i)?(this.state.shouldOverrideExpression()&&this.expressionManager&&this.expressionManager.resetExpression(),p.log(this.tag,"Start motion:",this.getMotionName(d)),this.emit("motionStart",t,e,g),a&&this.expressionManager&&this.state.shouldOverrideExpression()&&(yield this.expressionManager.setExpression(a)),this.playing=!0,y&&this._startMotion(y,void 0,u,h),!0):(g&&(z.dispose(g),this.currentAudio=void 0),!1)})}startRandomMotion(t,e){return g(this,arguments,function*(t,e,{sound:i,volume:s=.5,expression:r,resetExpression:a=!0,onFinish:n,onError:o,loop:l}={}){var u,h;if(this.destroyed)return!1;const d=null==(u=this.definitions)?void 0:u[t];if(null==d?void 0:d.length){const u=[],g=null!=(h=this.motionGroups[t])?h:[];for(let e=0;e<d.length;e++)null===g[e]||this.state.isActive(t,e)||u.push(e);if(u.length){const h=u[Math.floor(Math.random()*u.length)];return this.startMotion(t,h,e,{sound:i,volume:s,expression:r,resetExpression:a,onFinish:n,onError:o,loop:l})}}return!1})}stopSpeaking(){this.currentAudio&&(z.dispose(this.currentAudio),this.currentAudio=void 0)}stopAllMotions(){this._stopAllMotions(),this.state.reset(),this.stopSpeaking()}update(t,e){var i;return this.isFinished()&&(this.playing&&(this.playing=!1,this.emit("motionFinish")),this.state.shouldOverrideExpression()&&(null==(i=this.expressionManager)||i.restoreExpression()),this.state.complete(),this.state.shouldRequestIdleMotion()&&this.startRandomMotion(this.groups.idle,E.IDLE)),this.updateParameters(t,e)}mouthSync(){return this.currentAnalyzer?z.analyze(this.currentAnalyzer):0}destroy(){var t;this.destroyed=!0,this.emit("destroy"),this.stopAllMotions(),null==(t=this.expressionManager)||t.destroy();this.definitions=void 0,this.motionGroups=void 0}getMotionAndApplyExpression(t,e,i){return g(this,null,function*(){if(this.destroyed)return null;if(!this.state.reserve(t,e,E.FORCE))return null;const s=this.getMotionDefinition(t,e);if(!s)return null;this.currentAudio&&z.dispose(this.currentAudio);const r=yield this.loadMotion(t,e);return this.state.start(r,t,e,E.FORCE)?(this.state.shouldOverrideExpression()&&this.expressionManager&&this.expressionManager.resetExpression(),p.log(this.tag,"Start motion:",this.getMotionName(s)),this.emit("motionStart",t,e,void 0),i&&this.expressionManager&&this.state.shouldOverrideExpression()&&(yield this.expressionManager.setExpression(i)),r):null})}getMotionDefinition(t,e){var i,s;const r=null==(s=null==(i=this.definitions)?void 0:i[t])?void 0:s[e];return r||p.warn(this.tag,`Undefined motion at "${t}"[${e}]`),r}}function X(t,e){return 2*e*t.scale}function H(t){return 2*t.scale}function Y(t,e,i){t.scale=i/(2*e)}function q(t,e){t.scale=e/2}function W(t,e){t.x=e}function J(t,e){t.y=e}function $(t,e,i){W(t,i-X(t,e)/2)}function Z(t,e){J(t,e-H(t)/2)}function K(t,e,i){W(t,i-X(t,e))}function Q(t,e){J(t,e-H(t))}function tt(t,e,i,s){if(e<=0||i<=0)return t.identity(),{width:0,height:0};const r=function(t){const e=[];for(const[i,s]of Object.entries(t))"number"==typeof s&&e.push([i,s]);return e}(s),a=e/i,n={scale:1,x:0,y:0};for(const[u,h]of r)"width"===u?Y(n,a,h):"height"===u&&q(n,h);for(const[u,h]of r)"x"===u?W(n,h):"y"===u?J(n,h):"centerX"===u?$(n,a,h):"centerY"===u?Z(n,h):"top"===u?J(n,h):"bottom"===u?Q(n,h):"left"===u?W(n,h):"right"===u&&K(n,a,h);const o=i/2,l=2*a/2;return t.identity(),function(t,e){t.a=e,t.b=0,t.c=0,t.d=e}(t,n.scale),t.tx=o*(n.x+l)-e*n.scale/2,t.ty=o*(1-n.y)-i*n.scale/2,{width:e*n.scale,height:i*n.scale}}function et(t,e){if(!Array.isArray(t))return[];const i=[];for(const s of t){if(!s||"object"!=typeof s)continue;const t=s,r="string"==typeof t.id?t.id:"string"==typeof t.Id?t.Id:void 0,a="string"==typeof t.name?t.name:"string"==typeof t.Name?t.Name:void 0;r&&a&&i.push({id:r,name:a,index:e(r)})}return i}const it={x:0,y:0,width:0,height:0};class st extends e.EventEmitter{constructor(){super(...arguments),d(this,"focusController",new I),d(this,"pose"),d(this,"physics"),d(this,"originalWidth",0),d(this,"originalHeight",0),d(this,"width",0),d(this,"height",0),d(this,"localTransform",new e.Matrix),d(this,"drawingMatrix",new e.Matrix),d(this,"hitAreas",{}),d(this,"textureFlipY",!1),d(this,"viewport",[0,0,0,0]),d(this,"destroyed",!1)}init(){this.setupLayout(),this.setupHitAreas()}setupLayout(){const t=this,e=this.getSize();t.originalWidth=e[0],t.originalHeight=e[1];const i=function(t,e,i,s){var r,a;const n=h({width:2,height:2},s),o=null!=(r=n.width)?r:2,l=null!=(a=n.height)?a:2;t.identity(),t.scale(o/2,l/2);const u=e*t.a,d=i*t.d,g=void 0!==n.x&&n.x-o/2||void 0!==n.centerX&&n.centerX||void 0!==n.left&&n.left-o/2||void 0!==n.right&&n.right+o/2||0,c=void 0!==n.y&&n.y-l/2||void 0!==n.centerY&&n.centerY||void 0!==n.top&&n.top-l/2||void 0!==n.bottom&&n.bottom+l/2||0;return t.translate(u*g,-d*c),{width:u,height:d}}(this.localTransform,this.originalWidth,this.originalHeight,this.getLayout());t.width=i.width,t.height=i.height}setupHitAreas(){const t=this.getHitAreaDefs();this.hitAreas={};for(const e of t)e.name&&(this.hitAreas[e.name]=e)}hitTest(t,e){return Object.keys(this.hitAreas).filter(i=>this.isHit(i,t,e))}isHit(t,e,i){const s=this.hitAreas[t];if(!s)return!1;let r=s.index;if(r<0){if(!s.id)return!1;if(r=this.getDrawableIndex(s.id),r<0)return!1;s.index=r}const a=this.getDrawableBounds(r,it);return a.x<=e&&e<=a.x+a.width&&a.y<=i&&i<=a.y+a.height}getDrawableBounds(t,e){const i=this.getDrawableVertices(t);let s=i[0],r=i[0],a=i[1],n=i[1];for(let o=0;o<i.length;o+=2){const t=i[o],e=i[o+1];s=Math.min(t,s),r=Math.max(t,r),a=Math.min(e,a),n=Math.max(e,n)}return null!=e||(e={}),e.x=s,e.y=a,e.width=r-s,e.height=n-a,e}updateTransform(t){this.drawingMatrix.copyFrom(t).append(this.localTransform)}update(t,e){this.focusController.update(t)}destroy(){this.destroyed=!0,this.emit("destroy"),this.motionManager.destroy(),this.motionManager=void 0,this.parallelMotionManager.forEach(t=>t.destroy()),this.parallelMotionManager=[]}updateMotions(t,e){this.emit("beforeMotionUpdate");const i=this.motionManager.update(t,e),s=this.parallelMotionManager.map(i=>i.update(t,e)),r=i||s.reduce((t,e)=>t||e,!1);return this.emit("afterMotionUpdate"),r}}class rt extends Error{constructor(t,e,i,s=!1){super(t),this.url=e,this.status=i,this.aborted=s}}const at=class t{static createXHR(e,i,s,r,a){const n=new XMLHttpRequest;if(t.allXhrSet.add(n),e){let i=t.xhrMap.get(e);i?i.add(n):(i=new Set([n]),t.xhrMap.set(e,i))}return n.open("GET",i),n.responseType=s,n.onload=()=>{var t;200!==n.status&&0!==n.status||!n.response?null==(t=n.onerror)||t.call(n,new ProgressEvent("error")):r(n.response)},n.onerror=()=>{p.warn("XHRLoader",`Failed to load resource as ${n.responseType} (Status ${n.status}): ${i}`),a(new rt("Network error.",i,n.status))},n.onabort=()=>a(new rt("Aborted.",i,n.status,!0)),n.onloadend=()=>{var i;t.allXhrSet.delete(n),e&&(null==(i=t.xhrMap.get(e))||i.delete(n))},n}static cancelXHRs(){var e;null==(e=t.xhrMap.get(this))||e.forEach(e=>{e.abort(),t.allXhrSet.delete(e)}),t.xhrMap.delete(this)}static release(){t.allXhrSet.forEach(t=>t.abort()),t.allXhrSet.clear(),t.xhrMap=new WeakMap}};d(at,"xhrMap",new WeakMap),d(at,"allXhrSet",new Set),d(at,"loader",t=>new Promise((e,i)=>{const s=t.target,r=t.target&&"function"==typeof at.cancelXHRs?at.cancelXHRs.bind(t.target):void 0,a=at.createXHR(t.target,t.settings?t.settings.resolveURL(t.url):t.url,t.type,i=>{t.result=i,e()},i);if(t.target&&r&&"function"==typeof s.listeners&&"function"==typeof s.once){const t=s.listeners("destroy");Array.isArray(t)&&t.includes(r)||s.once("destroy",r)}a.send()}));let nt=at;function ot(t,e){let i=-1;return function s(r,a){if(a)return Promise.reject(a);if(r<=i)return Promise.reject(new Error("next() called multiple times"));i=r;const n=t[r];if(!n)return Promise.resolve();try{return Promise.resolve(n(e,s.bind(null,r+1)))}catch(o){const t=o instanceof Error?o:new Error(String(o));return Promise.reject(t)}}(0)}class lt{static load(t){return g(this,null,function*(){return yield ot(this.middlewares,t),t.result})}}d(lt,"middlewares",[nt.loader]);class ut extends F{constructor(t){if(super(t),d(this,"moc"),d(this,"textures"),d(this,"layout"),d(this,"hitAreas"),d(this,"initParams"),d(this,"initOpacities"),d(this,"expressions"),d(this,"motions",{}),!ut.isValidJSON(t))throw new TypeError("Invalid JSON.");this.moc=t.model,x("string",t,this,"textures","textures"),this.copy(t)}static isValidJSON(t){if(!t||"object"!=typeof t)return!1;const e=!!Array.isArray(t.textures)&&t.textures.every(t=>"string"==typeof t);return"string"==typeof t.model&&e}copy(t){y("string",t,this,"name","name"),y("string",t,this,"pose","pose"),y("string",t,this,"physics","physics"),y("object",t,this,"layout","layout"),y("object",t,this,"motions","motions"),x("object",t,this,"hit_areas","hitAreas"),x("object",t,this,"expressions","expressions"),x("object",t,this,"init_params","initParams"),x("object",t,this,"init_opacities","initOpacities");const e=this.getFileStem(this.moc);this.setModelName(this.name,e)}replaceFiles(t){super.replaceFiles(t);for(const[e,i]of Object.entries(this.motions))for(let s=0;s<i.length;s++)i[s].file=t(i[s].file,`motions.${e}[${s}].file`),void 0!==i[s].sound&&(i[s].sound=t(i[s].sound,`motions.${e}[${s}].sound`));if(this.expressions)for(let e=0;e<this.expressions.length;e++)this.expressions[e].file=t(this.expressions[e].file,`expressions[${e}].file`)}}function ht({lod:t,effectiveScale:e,textureWidth:i,textureHeight:s,lodScaleThreshold:r,lodTextureSizeThreshold:a,lodMaxLevel:n}){if("single-auto"!==dt(t))return;if(!Number.isFinite(e)||e<=0)return;const o=Math.floor(i),u=Math.floor(s);if(o<=1||u<=1)return;if(e>=ct(r,.5))return;const h=ct(a,4096);if(Math.max(o,u)<h)return;const d=Math.round(Math.log2(1/e)),g=Math.max(1,Math.floor(Math.log2(Math.max(o,u)))),c=Math.min(g,(m=g,void 0!==(p=n)&&Number.isFinite(p)&&p>=1?Math.floor(p):m));var p,m;const _=function(t,e,i){return Math.min(i,Math.max(e,t))}(Math.max(1,d),1,c),f=l(2,_);return{level:_,width:Math.max(1,Math.round(o/f)),height:Math.max(1,Math.round(u/f))}}function dt(t){return!1===t||"single-auto"===t?t:"full"}function gt(t){return"nearest"===t?"nearest":"linear"}function ct(t,e){return void 0!==t&&Number.isFinite(t)&&t>0?t:e}function pt(){}const mt="Live2DFactory",_t=(t,e)=>g(null,null,function*(){if("string"==typeof t.source){const e=yield lt.load({url:t.source,type:"json",target:t.live2dModel});e.url="string"==typeof e.url?e.url:t.source,t.source=e,t.live2dModel.emit("settingsJSONLoaded",e)}return e()}),ft=(t,e)=>g(null,null,function*(){if(t.source instanceof F)return t.settings=t.source,e();if("object"==typeof t.source){const i=Pt.findRuntime(t.source);if(i){const s=i.createModelSettings(t.source);return t.settings=s,t.live2dModel.emit("settingsLoaded",s),e()}}const i=t.source&&"string"==typeof t.source.url?t.source.url:void 0,s=Pt.runtimes.map(t=>t.version).join(", ");if(0===Pt.runtimes.length)throw new TypeError(["Unknown settings format: no Live2D runtimes registered.",'Import a published runtime entry before loading models (e.g. "<package>/cubism" for Cubism 3/4/5, "<package>/cubism-legacy" for Cubism 2).',i?`Settings URL: ${i}`:void 0].filter(Boolean).join("\n"));const r=(()=>{try{if(!t.source||"object"!=typeof t.source||Array.isArray(t.source))return;return Object.keys(t.source).slice(0,30).join(", ")}catch(e){return}})();throw new TypeError(["Unknown settings format: no matching runtime found for the loaded settings JSON.",s?`Registered runtimes (versions): ${s}`:void 0,r?`Settings JSON keys: ${r}`:void 0,i?`Settings URL: ${i}`:void 0].filter(Boolean).join("\n"))}),yt=(t,e)=>{if(t.settings){const i=Pt.findRuntime(t.settings);if(i)return i.ready().then(()=>e())}return e()},xt=(t,e)=>g(null,null,function*(){yield e();const i=t.internalModel;if(i){const e=t.settings,s=Pt.findRuntime(e);if(s){const r=[],a=e instanceof ut?"json":"arraybuffer";e.pose&&r.push(lt.load({settings:e,url:e.pose,type:a,target:i}).then(e=>{i.pose=s.createPose(i.coreModel,e),t.live2dModel.emit("poseLoaded",i.pose)}).catch(e=>{t.live2dModel.emit("poseLoadError",e),p.warn(mt,"Failed to load pose.",e)})),e.physics&&r.push(lt.load({settings:e,url:e.physics,type:a,target:i}).then(e=>{i.physics=s.createPhysics(i.coreModel,e),t.live2dModel.emit("physicsLoaded",i.physics)}).catch(e=>{t.live2dModel.emit("physicsLoadError",e),p.warn(mt,"Failed to load physics.",e)})),r.length&&(yield Promise.all(r))}}}),Mt=(t,i)=>g(null,null,function*(){if(!t.settings)throw new TypeError("Missing settings.");{const s=t.live2dModel,r=h({crossOrigin:t.options.crossOrigin},t.options.textureOptions);t.settings instanceof ut&&(r.preferCreateImageBitmap=!1);const a=Promise.all(t.settings.textures.map(i=>function(t,i={}){const s=e.loadTextures.config,r=null==s?void 0:s.crossOrigin,a=null==s?void 0:s.preferCreateImageBitmap,n=null==s?void 0:s.preferWorkers;return void 0!==i.crossOrigin&&s&&(s.crossOrigin=i.crossOrigin),!1===i.preferCreateImageBitmap&&s&&(s.preferCreateImageBitmap=!1,s.preferWorkers=!1),e.Assets.load({src:t,data:{autoGenerateMipmaps:"full"===dt(i.lod)}}).catch(t=>{if(t instanceof Error)throw t;throw new Error("Texture loading error",{cause:t})}).finally(()=>{s&&(s.crossOrigin=null!=r?r:s.crossOrigin,!1===i.preferCreateImageBitmap&&(s.preferCreateImageBitmap=null!=a?a:s.preferCreateImageBitmap,s.preferWorkers=null!=n?n:s.preferWorkers))})}(t.settings.resolveURL(i),r)));if(a.catch(pt),yield i(),!t.internalModel)throw new TypeError("Missing internal model.");s.internalModel=t.internalModel,s.emit("modelLoaded",t.internalModel),s.textures=yield a,s.emit("textureLoaded",s.textures)}}),Ct=(t,e)=>g(null,null,function*(){const i=t.settings;if(i instanceof F){const s=Pt.findRuntime(i);if(!s)throw new TypeError("Unknown model settings.");const r=yield lt.load({settings:i,url:i.moc,type:"arraybuffer",target:t.live2dModel});if(!s.isValidMoc(r))throw new Error("Invalid moc data");const a=s.createCoreModel(r);return t.internalModel=s.createInternalModel(a,i,t.options),e()}throw new TypeError("Missing settings.")}),St=class t{static resolveURL(e,i){var s;const r=null==(s=t.filesMap[e])?void 0:s[i];if(void 0===r)throw new Error("Cannot find this file from uploaded files: "+i);return r}static upload(e,i){const s={};for(const t of i.getDefinedFiles()){const r=decodeURI(b(i.url,t)),a=e.find(t=>t.webkitRelativePath===r);a&&(s[t]=URL.createObjectURL(a))}t.filesMap[i._objectURL]=s}static createSettings(e){return g(this,null,function*(){const i=e.find(t=>t.name.endsWith("model.json")||t.name.endsWith("model3.json"));if(!i)throw new TypeError("Settings file not found");const s=yield t.readText(i),r=JSON.parse(s);r.url=i.webkitRelativePath;const a=Pt.findRuntime(r);if(!a)throw new Error("Unknown settings JSON");const n=a.createModelSettings(r);return n._objectURL=URL.createObjectURL(i),n})}static readText(t){return g(this,null,function*(){return new Promise((e,i)=>{const s=new FileReader;s.onload=()=>e(s.result),s.onerror=i,s.readAsText(t,"utf8")})})}};d(St,"live2dFactory"),d(St,"filesMap",{}),d(St,"factory",(t,e)=>g(null,null,function*(){if(Array.isArray(t.source)&&t.source[0]instanceof File){const e=t.source;let i=e.settings;if(i){if(!i._objectURL)throw new Error('"_objectURL" must be specified in ModelSettings')}else i=yield St.createSettings(e);i.validateFiles(e.map(t=>encodeURI(t.webkitRelativePath))),St.upload(e,i),i.resolveURL=function(t){return St.resolveURL(this._objectURL,t)},t.source=i,t.live2dModel.once("modelLoaded",t=>{t.once("destroy",function(){const t=this.settings._objectURL;if(URL.revokeObjectURL(t),St.filesMap[t])for(const e of Object.values(St.filesMap[t]))URL.revokeObjectURL(e);delete St.filesMap[t]})})}return e()}));let vt=St;const bt=class t{static registerRuntime(e){t.runtimes.push(e),t.runtimes.sort((t,e)=>e.version-t.version)}static findRuntime(e){for(const i of t.runtimes)if(i.test(e))return i}static setupLive2DModel(e,i,s){return g(this,null,function*(){const r=new Promise(t=>e.once("textureLoaded",t)),a=new Promise(t=>e.once("modelLoaded",t)),n=Promise.all([r,a]).then(()=>e.emit("ready"));yield ot(t.live2DModelMiddlewares,{live2dModel:e,source:i,options:s||{}}),yield n,e.emit("load")})}static loadMotion(e,i,s){var r;const a=t=>e.emit("motionLoadError",i,s,t);try{const n=null==(r=e.definitions[i])?void 0:r[s];if(!n)return Promise.resolve(void 0);e.once("destroy",()=>t.releaseMotionTasks(e));let o=t.motionTasksMap.get(e);o||(o={},t.motionTasksMap.set(e,o));let l=o[i];l||(l=[],o[i]=l);const u=e.getMotionFile(n);return null!=l[s]||(l[s]=lt.load({url:u,settings:e.settings,type:e.motionDataType,target:e}).then(r=>{var a;const o=null==(a=t.motionTasksMap.get(e))?void 0:a[i];o&&(o[s]=void 0);const l=r,u=e.createMotion(l,i,n);return e.emit("motionLoaded",i,s,u),u}).catch(t=>{p.warn(e.tag,`Failed to load motion: ${u}\n`,t),a(t)})),l[s]}catch(n){p.warn(e.tag,`Failed to load motion at "${i}"[${s}]\n`,n),a(n)}return Promise.resolve(void 0)}static loadExpression(e,i){var s;const r=t=>e.emit("expressionLoadError",i,t);try{const a=e.definitions[i];if(!a)return Promise.resolve(void 0);e.once("destroy",()=>t.releaseExpressionTasks(e));let n=t.expressionTasksMap.get(e);n||(n=[],t.expressionTasksMap.set(e,n));const o=e.getExpressionFile(a),l=null!=(s=e.expressionDataType)?s:"json";return null!=n[i]||(n[i]=lt.load({url:o,settings:e.settings,type:l,target:e}).then(s=>{const r=t.expressionTasksMap.get(e);r&&(r[i]=void 0);const n=s,o=e.createExpression(n,a);return e.emit("expressionLoaded",i,o),o}).catch(t=>{p.warn(e.tag,`Failed to load expression: ${o}\n`,t),r(t)})),n[i]}catch(a){p.warn(e.tag,`Failed to load expression at [${i}]\n`,a),r(a)}return Promise.resolve(void 0)}static releaseMotionTasks(e){t.motionTasksMap.delete(e)}static releaseExpressionTasks(e){t.expressionTasksMap.delete(e)}};d(bt,"runtimes",[]),d(bt,"urlToJSON",_t),d(bt,"jsonToSettings",ft),d(bt,"waitUntilReady",yt),d(bt,"setupOptionals",xt),d(bt,"setupEssentials",Mt),d(bt,"createInternalModel",Ct),d(bt,"live2DModelMiddlewares",[vt.factory,_t,ft,yt,xt,Mt,Ct]),d(bt,"motionTasksMap",new WeakMap),d(bt,"expressionTasksMap",new WeakMap);let Pt=bt;G.prototype._loadMotion=function(t,e){return Pt.loadMotion(this,t,e)},P.prototype._loadExpression=function(t){return Pt.loadExpression(this,t)},vt.live2dFactory=Pt;const Bt=class t{constructor(i,{autoUpdate:s=!0,autoHitTest:r=!0,autoFocus:a=!0,autoInteract:n,ticker:o}={}){var l;d(this,"model"),d(this,"destroyed",!1),d(this,"_ticker"),d(this,"_autoUpdate",!1),d(this,"_autoHitTest",!1),d(this,"_autoFocus",!1),null!=o||(o=null!=(l=t.defaultTicker)?l:"undefined"!=typeof PIXI?PIXI.Ticker.shared:e.Ticker.shared),void 0!==n&&(r=n,a=n,p.warn(i.tag,"options.autoInteract is deprecated since v0.5.0, use autoHitTest and autoFocus instead.")),this.model=i,this.ticker=o,this.autoUpdate=s,this.autoHitTest=r,this.autoFocus=a,(r||a)&&(this.model.eventMode="static")}get ticker(){return this._ticker}set ticker(t){var e,i;this._ticker&&this._ticker.remove(It,this),this._ticker=t,this._autoUpdate&&(null==(e=this._ticker)||e.add(It,this),null==(i=this._ticker)||i.start())}get autoUpdate(){return this._autoUpdate}set autoUpdate(t){var e;this.destroyed||(t?this._ticker?(this._ticker.add(It,this),this._autoUpdate=!0):p.warn(this.model.tag,"No Ticker to be used for automatic updates. Either set option.ticker when creating Live2DModel, or expose PIXI to global scope (window.PIXI = PIXI)."):(null==(e=this._ticker)||e.remove(It,this),this._autoUpdate=!1))}get autoHitTest(){return this._autoHitTest}set autoHitTest(t){t!==this.autoHitTest&&(t?this.model.on("pointertap",Ft,this):this.model.off("pointertap",Ft,this),this._autoHitTest=t)}get autoFocus(){return this._autoFocus}set autoFocus(t){t!==this.autoFocus&&(t?(this.model.on("globalpointermove",Et,this),this.model.on("pointermove",Et,this)):(this.model.off("globalpointermove",Et,this),this.model.off("pointermove",Et,this)),this._autoFocus=t)}get autoInteract(){return this._autoHitTest&&this._autoFocus}set autoInteract(t){this.autoHitTest=t,this.autoFocus=t}onTickerUpdate(){const t=this.ticker.deltaMS;this.model.update(t)}onTap(t){this.model.tap(t.global.x,t.global.y)}onPointerMove(t){this.model.focus(t.global.x,t.global.y)}destroy(){this.autoFocus=!1,this.autoHitTest=!1,this.autoUpdate=!1,this.ticker=void 0,this.destroyed=!0}};d(Bt,"defaultTicker");let wt=Bt;function It(){this.onTickerUpdate()}function Ft(t){this.onTap(t)}function Et(t){this.onPointerMove(t)}class Lt extends e.Transform{}const Vt=new e.Point,Tt=new e.Matrix,Rt=new e.Matrix,Dt={x:0,y:0,width:0,height:0},At=new e.Bounds;let Ot=!1;class kt{constructor(t){this.renderer=t}addRenderable(t,e){var i,s;null==(s=null==(i=this.renderer.renderPipes.batch)?void 0:i.break)||s.call(i,e),e.add(t)}execute(t){!t.visible||t.alpha<=0||t.renderLive2D(this.renderer)}updateRenderable(){}destroyRenderable(){}validateRenderable(){return!1}destroy(){}}d(kt,"extension",{type:[e.ExtensionType.WebGLPipes],name:"live2d"});const Nt=kt;class Ut extends e.Container{constructor(t){super(),d(this,"renderPipeId","live2d"),d(this,"tag","Live2DModel(uninitialized)"),d(this,"internalModel"),d(this,"textures",[]),d(this,"textureOptions"),d(this,"textureLODStates",[]),d(this,"textureLODFailures",[]),d(this,"transform",new Lt),d(this,"anchor"),d(this,"_bounds",new e.Bounds),d(this,"_boundsDirty",!0),d(this,"_boundsRetryAfterDraw",!1),d(this,"gl",null),d(this,"elapsedTime",0),d(this,"deltaTime",0),d(this,"automator"),d(this,"currentGlId",0),d(this,"renderLive2D",t=>{var i,s,r,a,n;if(!(t instanceof e.WebGLRenderer))throw new Error("Renderer is not supported");t.geometry.resetState(),t.shader.resetState(),t.texture.resetState();let o=!1;this.gl!==t.gl&&(this.gl=t.gl,this.internalModel.updateWebGLContext(t.gl,this.generateUID()),o=!0);const{projectionMatrix:l,offset:u,worldTransformMatrix:h}=t.globalUniforms.globalUniformData,d=Rt.copyFrom(h).append(this.groupTransform),g=(c=d,Math.max(Math.hypot(c.a,c.b),Math.hypot(c.c,c.d))*t.resolution);var c;for(let e=0;e<this.textures.length;e++){const i=this.textures[e];let s=this.resolveTextureForRender(e,i,g);try{this.uploadTextureForRender(t,s,o)}catch(C){if(s===i)throw new Error("Failed to upload Live2D texture.");const r=this.textureLODStates[e];(null==r?void 0:r.texture)===s&&(this.markTextureLODFailure(e,i,r.level),this.destroyTextureLODState(e)),s=i,this.uploadTextureForRender(t,s,o)}this.internalModel.bindTexture(e,t.texture.getGlSource(s.source).texture)}const p=t.renderTarget.viewport,m=t.renderTarget.renderTarget;let _=p.y;if(null==m?void 0:m.isRoot){_=m.colorTexture.source.pixelHeight-p.height-p.y}this.internalModel.viewport=[p.x,_,p.width,p.height];const f=this.deltaTime;this.deltaTime=0,f&&this.internalModel.update(f,this.elapsedTime),d.tx-=null!=(i=null==u?void 0:u.x)?i:0,d.ty-=null!=(s=null==u?void 0:u.y)?s:0;const y=Tt.copyFrom(l).append(d);this.internalModel.updateTransform(y),this.internalModel.draw(t.gl),this._boundsRetryAfterDraw&&this.updateDrawableBounds(),t.state.resetState(),t.texture.resetState();const x=null==(r=t.renderTarget)?void 0:r.defaultClearColor,M=null==(n=null==(a=t.renderTarget)?void 0:a.adaptor)?void 0:n._clearColorCache;x&&(t.gl.clearColor(x[0],x[1],x[2],x[3]),M&&(M[0]=x[0],M[1]=x[1],M[2]=x[2],M[3]=x[3]))}),this.textureOptions=null==t?void 0:t.textureOptions,this.anchor=new e.ObservablePoint({_onUpdate:()=>this.onAnchorChange()},0,0),this.automator=new wt(this,t),this.once("modelLoaded",()=>this.initializeOnModelLoad(t))}get isRenderable(){return!0}get canBundle(){return!1}static from(t,e){return g(this,null,function*(){const i=new this(e);return yield Pt.setupLive2DModel(i,t,e),i})}static fromSync(t,e){const i=new this(e);return Pt.setupLive2DModel(i,t,e).then(()=>{var t;return null==(t=null==e?void 0:e.onLoad)?void 0:t.call(e)}).catch(t=>{var i;return null==(i=null==e?void 0:e.onError)?void 0:i.call(e,t)}),i}static registerTicker(t){wt.defaultTicker=t.shared}get bounds(){return this.internalModel?(this._boundsDirty&&this.updateDrawableBounds(),this._bounds):(this._bounds.set(0,0,0,0),this._bounds)}updateDrawableBounds(){if(!this.internalModel)return this._bounds.set(0,0,0,0),void(this._boundsDirty=!1);const t=this.internalModel.getDrawableIDs();At.clear();for(let i=0;i<t.length;i++){const s=t[i],r=this.internalModel.getDrawableIndex(s);if(r<0)continue;const a=this.internalModel.getDrawableBounds(r,Dt);Number.isFinite(a.x)&&Number.isFinite(a.y)&&Number.isFinite(a.width)&&Number.isFinite(a.height)&&At.addFrame(a.x,a.y,a.x+a.width,a.y+a.height,e.Matrix.IDENTITY)}if(this._bounds.clear(),At.isValid&&At.isPositive)this._bounds.addFrame(At.minX,At.minY,At.maxX,At.maxY,this.internalModel.localTransform),this._boundsRetryAfterDraw=!1;else{const t=this.internalModel.originalWidth||this.internalModel.width,e=this.internalModel.originalHeight||this.internalModel.height;this._bounds.addFrame(0,0,t,e,this.internalModel.localTransform),this._boundsRetryAfterDraw=!0}this._boundsDirty=!1,this._didViewChangeTick++,this.onAnchorChange()}generateUID(){return++this.currentGlId}collectRenderables(t,e,i){var s,r,a,n;if(this.parentRenderLayer&&this.parentRenderLayer!==i)return;if(this.globalDisplayStatus<7)return;if(!this.includeInBuild)return;this.sortableChildren&&this.sortChildren(),function(t){const e=t;e.renderPipes.live2d||(Ot||(Ot=!0,console.warn("[untitled-pixi-live2d-engine] Lazy Live2D render pipe registration is deprecated. Register Live2DPlugin explicitly with `extensions.add(Live2DPlugin)` before creating the Pixi renderer.")),e.renderPipes.live2d=new kt(t))}(e);const o=e.renderPipes,l=()=>{o.live2d.addRenderable(this,t)},u=()=>{const s=this.children,r=s.length;for(let a=0;a<r;a++)s[a].collectRenderables(t,e,i)},h=this.effects;if(h){for(let e=0;e<h.length;e++){const i=h[e],a=i.filters;if(a)for(const t of a)t&&"number"==typeof t.resolution&&1===t.resolution&&(t.resolution="inherit");null==(r=null==(s=o[i.pipe])?void 0:s.push)||r.call(s,i,this,t)}l(),u();for(let e=h.length-1;e>=0;e--){const i=h[e];null==(n=null==(a=o[i.pipe])?void 0:a.pop)||n.call(a,i,this,t)}}else l(),u()}initializeOnModelLoad(t){this.tag=`Live2DModel(${this.internalModel.settings.name})`,this.updateDrawableBounds()}onAnchorChange(){if(!this.internalModel||!this.pivot)return;const t=this.bounds;this.pivot.set(t.minX+this.anchor.x*t.width,t.minY+this.anchor.y*t.height)}motion(t,e,i){return g(this,arguments,function*(t,e,i,{sound:s,volume:r=.5,expression:a,resetExpression:n=!0,onFinish:o,onError:l,loop:u}={}){return void 0===e?this.internalModel.motionManager.startRandomMotion(t,i,{sound:s,volume:r,expression:a,resetExpression:n,onFinish:o,onError:l,loop:u}):this.internalModel.motionManager.startMotion(t,e,i,{sound:s,volume:r,expression:a,resetExpression:n,onFinish:o,onError:l,loop:u})})}motionLastFrame(t,e){return g(this,arguments,function*(t,e,{expression:i}={}){return this.internalModel.motionManager.motionLastFrame(t,e,{expression:i})})}parallelMotion(t){return g(this,null,function*(){this.internalModel.extendParallelMotionManager(t.length);const e=t.map((t,e)=>this.internalModel.parallelMotionManager[e].startMotion(t.group,t.index,t.priority,{ignoreParamIds:t.ignoreParamIds,loop:t.loop})),i=[];for(const t of e)i.push(yield t);return i})}parallelLastFrame(t){return g(this,null,function*(){this.internalModel.extendParallelMotionManager(t.length);const e=t.map((t,e)=>this.internalModel.parallelMotionManager[e].playMotionLastFrame(t.group,t.index)),i=[];for(const t of e)i.push(yield t);return i})}stopMotions(){return this.internalModel.motionManager.stopAllMotions()}speak(t,{volume:e=.5,expression:i,resetExpression:s=!0,onFinish:r,onError:a}={}){return this.internalModel.motionManager.speak(t,{volume:e,expression:i,resetExpression:s,onFinish:r,onError:a})}stopSpeaking(){return this.internalModel.motionManager.stopSpeaking()}expression(t){return this.internalModel.motionManager.expressionManager?void 0===t?this.internalModel.motionManager.expressionManager.setRandomExpression():this.internalModel.motionManager.expressionManager.setExpression(t):Promise.resolve(!1)}focus(t,e,i=!1){Vt.x=t,Vt.y=e,this.toModelPosition(Vt,Vt,!0);const s=Vt.x/this.internalModel.originalWidth*2-1,r=Vt.y/this.internalModel.originalHeight*2-1,a=Math.atan2(r,s);this.internalModel.focusController.focus(Math.cos(a),-Math.sin(a),i)}tap(t,e){const i=this.hitTest(t,e);i.length&&this.emit("hit",i)}hitTest(t,e){return Vt.x=t,Vt.y=e,this.toModelPosition(Vt,Vt),this.internalModel.hitTest(Vt.x,Vt.y)}toModelPosition(t,e=t.clone(),i){return i||this.updateLocalTransform(),this.toLocal(t,void 0,e,i),this.internalModel.localTransform.applyInverse(e,e),e}containsPoint(t){return this.bounds.containsPoint(t.x,t.y)}_calculateBounds(){if(!this.internalModel)return void this.getBounds().set(0,0,0,0);const t=this.bounds;this.getBounds().addFrame(t.minX,t.minY,t.maxX,t.maxY,this.transform.matrix)}update(t){this.deltaTime+=t,this.elapsedTime+=t}resolveTextureForRender(t,i,a){var n;const o=ht((l=h({},this.textureOptions),u={effectiveScale:a,textureWidth:i.source.pixelWidth,textureHeight:i.source.pixelHeight},s(l,r(u))));var l,u;if(!o)return i;const d=this.textureLODFailures[t];if((null==d?void 0:d.source)===i&&d.levels.has(o.level))return i;const g=this.textureLODStates[t];if((null==g?void 0:g.source)===i&&g.level===o.level&&!g.texture.destroyed)return g.texture;this.destroyTextureLODState(t);const c=function(t,i,s,r,a){var n,o;const l=t.source.resource;if(!function(t){if(!t||"object"!=typeof t)return!1;const{width:e,height:i}=t;return"number"==typeof e&&e>0&&"number"==typeof i&&i>0}(l))return;const u=e.DOMAdapter.get().createCanvas(s,r),h=u.getContext("2d");if(!h)return;try{h.clearRect(0,0,s,r),h.imageSmoothingEnabled="nearest"!==a,"imageSmoothingQuality"in h&&"nearest"!==a&&(h.imageSmoothingQuality="high"),h.drawImage(l,0,0,t.source.pixelWidth,t.source.pixelHeight,0,0,s,r)}catch(g){return}const d=`${null!=(o=null!=(n=t.label)?n:t.source.label)?o:"Live2DTexture"} LOD ${i}`;return new e.Texture({label:d,source:new e.CanvasSource({resource:u,width:s,height:r,resolution:1,scaleMode:gt(a),autoGenerateMipmaps:!1,label:d})})}(i,o.level,o.width,o.height,null==(n=this.textureOptions)?void 0:n.lodFilter);return c?(this.textureLODStates[t]={source:i,level:o.level,texture:c},c):(this.markTextureLODFailure(t,i,o.level),i)}markTextureLODFailure(t,e,i){let s=this.textureLODFailures[t];(null==s?void 0:s.source)!==e&&(s={source:e,levels:new Set},this.textureLODFailures[t]=s),s.levels.add(i)}destroyTextureLODState(t){const e=this.textureLODStates[t];e&&(e.texture.destroy(!0),this.textureLODStates[t]=void 0)}destroyTextureLODStates(){for(let t=0;t<this.textureLODStates.length;t++)this.destroyTextureLODState(t);this.textureLODFailures.length=0}uploadTextureForRender(t,e,i){const s=Boolean(e.source._gpuData[t.uid]);!i&&s||(t.gl.pixelStorei(WebGLRenderingContext.UNPACK_FLIP_Y_WEBGL,this.internalModel.textureFlipY),t.texture.bind(e,0))}destroy(t){this.emit("destroy"),this.destroyTextureLODStates(),(null==t?void 0:t.texture)&&this.textures.forEach(e=>e.destroy(t.baseTexture)),this.automator.destroy(),this.internalModel.destroy(),super.destroy(t)}}if(!("Live2D"in window))throw new Error("Could not find Cubism 2 runtime. This plugin requires live2d.min.js to be loaded.");const zt=Live2DMotion.prototype.updateParam;Live2DMotion.prototype.updateParam=function(t,e){zt.call(this,t,e),e.isFinished()&&this.onFinishHandler&&(this.onFinishHandler(this),delete this.onFinishHandler)};class jt extends AMotion{constructor(t){super(),d(this,"params",[]),this.setFadeIn(t.fade_in>0?t.fade_in:c.expressionFadingDuration),this.setFadeOut(t.fade_out>0?t.fade_out:c.expressionFadingDuration),Array.isArray(t.params)&&t.params.forEach(t=>{const e=t.calc||"add";if("add"===e){const e=t.def||0;t.val-=e}else if("mult"===e){const e=t.def||1;t.val/=e}this.params.push({calc:e,val:t.val,id:t.id})})}updateParamExe(t,e,i,s){this.params.forEach(e=>{t.setParamFloat(e.id,e.val*i)})}}class Gt extends P{constructor(t,e){var i;super(t,e),d(this,"queueManager",new MotionQueueManager),d(this,"definitions"),this.definitions=null!=(i=this.settings.expressions)?i:[],this.init()}isFinished(){return this.queueManager.isFinished()}getExpressionIndex(t){return this.definitions.findIndex(e=>e.name===t)}getExpressionFile(t){return t.file}createExpression(t,e){return new jt(t)}_setExpression(t){return this.queueManager.startMotion(t)}stopAllExpressions(){this.queueManager.stopAllMotions()}updateParameters(t,e){return this.queueManager.updateParam(t)}}function Xt(t,e,i){const s=i.getDurationMSec(),r=t.startMotion(i,!0),a=t.motions.find(t=>!!t&&t._$sr===r);return!!a&&(i.updateParamExe(e.coreModel,s,1,a),!0)}class Ht extends G{constructor(t){super(t),d(this,"definitions"),d(this,"groups",{idle:"idle"}),d(this,"motionDataType","arraybuffer"),d(this,"queueManager",new MotionQueueManager),d(this,"lipSyncIds"),d(this,"expressionManager"),this.definitions=this.settings.motions,this.init(t.options),this.lipSyncIds=["PARAM_MOUTH_OPEN_Y"]}init(t){super.init(t),this.settings.expressions&&(this.expressionManager=new Gt(this.settings,t))}isFinished(){return this.queueManager.isFinished()}createMotion(t,e,i){const s=Live2DMotion.loadMotion(t),r=e===this.groups.idle?c.idleMotionFadingDuration:c.motionFadingDuration;return s.setFadeIn(i.fade_in>0?i.fade_in:r),s.setFadeOut(i.fade_out>0?i.fade_out:r),s}getMotionFile(t){return t.file}getMotionName(t){return t.file}getSoundFile(t){return t.sound}_startMotion(t,e,i,s){return t.onFinishHandler=e,i&&i.length>0&&(t.motions=t.motions.filter(t=>!i.includes(t._$4P))),this.queueManager.stopAllMotions(),this.queueManager.startMotion(t)}_stopAllMotions(){this.queueManager.stopAllMotions()}updateParameters(t,e){return this.queueManager.updateParam(t)}destroy(){super.destroy(),this.queueManager=void 0}motionLastFrame(t,e){return g(this,arguments,function*(t,e,{expression:i}={}){const s=yield this.getMotionAndApplyExpression(t,e,i);return!!s&&(this.playing=!0,Xt(this.queueManager,this.parent,s),this.playing=!1,!0)})}}class Yt extends e.EventEmitter{constructor(t){super(),d(this,"tag"),d(this,"manager"),d(this,"settings"),d(this,"state",new L),d(this,"playing",!1),d(this,"destroyed",!1),d(this,"parent"),this.settings=t.settings,this.tag=`ParallelMotionManager(${this.settings.name})`,this.state.tag=this.tag,this.manager=t.motionManager,this.parent=t}startMotion(t,e){return g(this,arguments,function*(t,e,i=E.NORMAL,s={}){var r;const{ignoreParamIds:a=[],loop:n}=Array.isArray(s)?{ignoreParamIds:s,loop:void 0}:s;if(!this.state.reserve(t,e,i))return!1;const o=null==(r=this.manager.definitions[t])?void 0:r[e];if(!o)return!1;const l=yield this.manager.loadMotion(t,e);return!!this.state.start(l,t,e,i)&&(p.log(this.tag,"Start motion:",this.getMotionName(o)),this.emit("motionStart",t,e,void 0),this.playing=!0,this._startMotion(l,void 0,a,n),!0)})}startRandomMotion(t,e){return g(this,arguments,function*(t,e,{loop:i}={}){var s;const r=this.manager.definitions[t];if(null==r?void 0:r.length){const a=[],n=null!=(s=this.manager.motionGroups[t])?s:[];for(let e=0;e<r.length;e++)null===n[e]||this.state.isActive(t,e)||a.push(e);if(a.length){const s=a[Math.floor(Math.random()*a.length)];return this.startMotion(t,s,e,{loop:i})}}return!1})}stopAllMotions(){this._stopAllMotions(),this.state.reset()}update(t,e){return this.isFinished()&&(this.playing&&(this.playing=!1,this.emit("motionFinish")),this.state.complete()),this.updateParameters(t,e)}destroy(){this.destroyed=!0,this.emit("destroy"),this.stopAllMotions()}}class qt extends Yt{constructor(t){super(t),d(this,"queueManager",new MotionQueueManager)}isFinished(){return this.queueManager.isFinished()}getMotionName(t){return t.file}_startMotion(t,e,i,s){return t.onFinishHandler=e,i&&i.length>0&&(t.motions=t.motions.filter(t=>!i.includes(t._$4P))),this.queueManager.stopAllMotions(),this.queueManager.startMotion(t)}_stopAllMotions(){this.queueManager.stopAllMotions()}updateParameters(t,e){return this.queueManager.updateParam(t)}destroy(){super.destroy(),this.queueManager=void 0}playMotionLastFrame(t,e){return g(this,null,function*(){var i;if(!this.state.reserve(t,e,E.FORCE))return!1;const s=null==(i=this.manager.definitions[t])?void 0:i[e];if(!s)return!1;const r=yield this.manager.loadMotion(t,e);return!!this.state.start(r,t,e,E.FORCE)&&(p.log(this.tag,"Start motion:",this.getMotionName(s)),this.queueManager.stopAllMotions(),this.emit("motionStart",t,e,void 0),this.playing=!0,!!Xt(this.queueManager,this.parent,r)&&(this.playing=!1,!0))})}}class Wt{constructor(t){d(this,"leftParam"),d(this,"rightParam"),d(this,"blinkInterval",4e3),d(this,"closingDuration",100),d(this,"closedDuration",50),d(this,"openingDuration",150),d(this,"eyeState",0),d(this,"eyeParamValue",1),d(this,"closedTimer",0),d(this,"nextBlinkTimeLeft",this.blinkInterval),this.coreModel=t,this.leftParam=t.getParamIndex("PARAM_EYE_L_OPEN"),this.rightParam=t.getParamIndex("PARAM_EYE_R_OPEN")}setEyeParams(t){this.eyeParamValue=m(t,0,1),this.coreModel.setParamFloat(this.leftParam,this.eyeParamValue),this.coreModel.setParamFloat(this.rightParam,this.eyeParamValue)}update(t){switch(this.eyeState){case 0:this.nextBlinkTimeLeft-=t,this.nextBlinkTimeLeft<0&&(this.eyeState=1,this.nextBlinkTimeLeft=this.blinkInterval+this.closingDuration+this.closedDuration+this.openingDuration+_(0,2e3));break;case 1:this.setEyeParams(this.eyeParamValue+t/this.closingDuration),this.eyeParamValue<=0&&(this.eyeState=2,this.closedTimer=0);break;case 2:this.closedTimer+=t,this.closedTimer>=this.closedDuration&&(this.eyeState=3);break;case 3:this.setEyeParams(this.eyeParamValue+t/this.openingDuration),this.eyeParamValue>=1&&(this.eyeState=0)}}}const Jt=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);class $t extends st{constructor(t,e,i){super(),d(this,"settings"),d(this,"options"),d(this,"coreModel"),d(this,"motionManager"),d(this,"parallelMotionManager"),d(this,"eyeBlink"),d(this,"eyeballXParamIndex"),d(this,"eyeballYParamIndex"),d(this,"angleXParamIndex"),d(this,"angleYParamIndex"),d(this,"angleZParamIndex"),d(this,"bodyAngleXParamIndex"),d(this,"breathParamIndex"),d(this,"textureFlipY",!0),d(this,"lipSync",!0),d(this,"drawDataCount",0),d(this,"disableCulling",!1),d(this,"hasDrawn",!1),d(this,"customHitAreas"),this.coreModel=t,this.settings=e,this.options=Object.assign({},{breathDepth:1,lipSyncGain:1.5,lipSyncWeight:.4},i),void 0!==(null==i?void 0:i.useHighPrecisionMask)&&!1!==i.useHighPrecisionMask&&p.warn("CubismLegacyInternalModel","`useHighPrecisionMask` is only supported by Cubism 3/4/5 models and will be ignored for Cubism 2 models."),this.motionManager=new Ht(this),this.parallelMotionManager=[],!1!==this.options.eyeBlink&&(this.eyeBlink=new Wt(t)),this.eyeballXParamIndex=t.getParamIndex("PARAM_EYE_BALL_X"),this.eyeballYParamIndex=t.getParamIndex("PARAM_EYE_BALL_Y"),this.angleXParamIndex=t.getParamIndex("PARAM_ANGLE_X"),this.angleYParamIndex=t.getParamIndex("PARAM_ANGLE_Y"),this.angleZParamIndex=t.getParamIndex("PARAM_ANGLE_Z"),this.bodyAngleXParamIndex=t.getParamIndex("PARAM_BODY_ANGLE_X"),this.breathParamIndex=t.getParamIndex("PARAM_BREATH"),this.init()}init(){super.init(),this.settings.initParams&&this.settings.initParams.forEach(({id:t,value:e})=>this.coreModel.setParamFloat(t,e)),this.settings.initOpacities&&this.settings.initOpacities.forEach(({id:t,value:e})=>this.coreModel.setPartsOpacity(t,e)),this.coreModel.saveParam();const t=this.coreModel.getModelContext()._$aS;(null==t?void 0:t.length)&&(this.drawDataCount=t.length);let e=this.coreModel.drawParamWebGL.culling;Object.defineProperty(this.coreModel.drawParamWebGL,"culling",{set:t=>e=t,get:()=>!this.disableCulling&&e});const i=this.coreModel.getModelContext().clipManager,s=i.setupClip.bind(i);i.setupClip=(t,e)=>{s.call(i,t,e),e.gl.viewport(...this.viewport)}}getSize(){return[this.coreModel.getCanvasWidth(),this.coreModel.getCanvasHeight()]}getLayout(){const t={};if(this.settings.layout)for(const[e,i]of Object.entries(this.settings.layout)){let s=e;"center_x"===e?s="centerX":"center_y"===e&&(s="centerY"),"number"==typeof i&&(t[s]=i)}return t}updateWebGLContext(t,e){const i=this.coreModel.drawParamWebGL;i.firstDraw=!0,i.setGL(t),i.glno=e,i._$NT=null,i._$no=null,i._$vS=null;const s=this.coreModel.getModelContext().clipManager;s.curFrameNo=e;const r=t.getParameter(t.FRAMEBUFFER_BINDING);s.getMaskRenderTexture(),t.bindFramebuffer(t.FRAMEBUFFER,r)}bindTexture(t,e){this.coreModel.setTexture(t,e)}getHitAreaDefs(){var t,e,i;const s=this.settings.json;return et(null!=(i=null!=(e=null!=(t=this.settings.hitAreas)?t:s.hit_areas)?e:s.HitAreas)?i:s.hitAreas,t=>this.coreModel.getDrawDataIndex(t))}getDrawableIDs(){const t=this.coreModel.getModelContext(),e=[];for(let i=0;i<this.drawDataCount;i++){const s=t.getDrawData(i);s&&e.push(s.getDrawDataID().id)}return e}getDrawableIndex(t){return this.coreModel.getDrawDataIndex(t)}getDrawableVertices(t){if("string"==typeof t&&-1===(t=this.coreModel.getDrawDataIndex(t)))throw new TypeError("Unable to find drawable ID: "+t);return this.coreModel.getTransformedPoints(t).slice()}hitTest(t,e){this.hasDrawn||p.warn("Trying to hit-test a Cubism 2 model that has not been rendered yet. Drawable hit areas may be empty until the first draw.");const i=super.hitTest(t,e),s=this.hitTestCustom(t,e);return s.length?i.length?[...new Set([...i,...s])]:s:i}update(t,e){var i,s,r,a;super.update(t,e);const n=this.coreModel,o=this.updateMotions(n,e);if(n.saveParam(),null==(i=this.motionManager.expressionManager)||i.update(n,e),o||null==(s=this.eyeBlink)||s.update(t),this.updateFocus(),this.updateNaturalMovements(t,e),this.lipSync&&this.motionManager.currentAudio){let t=this.motionManager.mouthSync()*this.options.lipSyncGain;const e=1,i=t>0?.1:0;t=Math.pow(t,1.15),t=m(t,i,e);for(let s=0;s<this.motionManager.lipSyncIds.length;++s)this.coreModel.addToParamFloat(this.coreModel.getParamIndex(this.motionManager.lipSyncIds[s]),t,this.options.lipSyncWeight)}null==(r=this.physics)||r.update(e),null==(a=this.pose)||a.update(t),this.emit("beforeModelUpdate"),n.update(),n.loadParam()}updateFocus(){this.coreModel.addToParamFloat(this.eyeballXParamIndex,this.focusController.x),this.coreModel.addToParamFloat(this.eyeballYParamIndex,this.focusController.y),this.coreModel.addToParamFloat(this.angleXParamIndex,30*this.focusController.x),this.coreModel.addToParamFloat(this.angleYParamIndex,30*this.focusController.y),this.coreModel.addToParamFloat(this.angleZParamIndex,this.focusController.x*this.focusController.y*-30),this.coreModel.addToParamFloat(this.bodyAngleXParamIndex,10*this.focusController.x)}updateNaturalMovements(t,e){const i=e/1e3*2*Math.PI;this.coreModel.addToParamFloat(this.angleXParamIndex,15*this.options.breathDepth*Math.sin(i/6.5345)*.5),this.coreModel.addToParamFloat(this.angleYParamIndex,8*this.options.breathDepth*Math.sin(i/3.5345)*.5),this.coreModel.addToParamFloat(this.angleZParamIndex,10*this.options.breathDepth*Math.sin(i/5.5345)*.5),this.coreModel.addToParamFloat(this.bodyAngleXParamIndex,4*this.options.breathDepth*Math.sin(i/15.5345)*.5),this.coreModel.setParamFloat(this.breathParamIndex,.5+.5*Math.sin(i/3.2345))}draw(t){const e=this.disableCulling;t.getParameter(t.FRAMEBUFFER_BINDING)&&(this.disableCulling=!0);const i=this.drawingMatrix;Jt[0]=i.a,Jt[1]=i.b,Jt[4]=i.c,Jt[5]=i.d,Jt[12]=i.tx,Jt[13]=i.ty,this.coreModel.setMatrix(Jt),this.coreModel.draw(),this.hasDrawn=!0,this.disableCulling=e}extendParallelMotionManager(t){for(;this.parallelMotionManager.length<t;)this.parallelMotionManager.push(new qt(this))}destroy(){super.destroy(),this.coreModel=void 0}hitTestCustom(t,e){const i=this.getCustomHitAreas();if(!i)return[];const s=this.originalWidth||this.width,r=this.originalHeight||this.height;if(!s||!r)return[];const a=t/s*2-1,n=1-e/r*2,o=[];for(const[l,u]of Object.entries(i))a>=u.minX&&a<=u.maxX&&n>=u.minY&&n<=u.maxY&&o.push(l);return o}getCustomHitAreas(){var t,e,i,s,r;if(void 0!==this.customHitAreas)return this.customHitAreas;const a=this.settings.json,n=null!=(i=null!=(e=null!=(t=a.hit_areas_custom)?t:a.hitAreasCustom)?e:a.HitAreasCustom)?i:a.HitAreas_Custom;if(!n||"object"!=typeof n)return this.customHitAreas=null,null;const o=n,l={},u=(t,e,i)=>{if(!t||!Array.isArray(e)||!Array.isArray(i))return;if(e.length<2||i.length<2)return;const s=Number(e[0]),r=Number(e[1]),a=Number(i[0]),n=Number(i[1]);Number.isFinite(s)&&Number.isFinite(r)&&Number.isFinite(a)&&Number.isFinite(n)&&(l[t]={minX:Math.min(s,r),maxX:Math.max(s,r),minY:Math.min(a,n),maxY:Math.max(a,n)})};for(const[h,d]of Object.entries(o)){if(h.endsWith("_x")){const t=h.slice(0,-2);u(t,d,o[`${t}_y`]);continue}if(!h.endsWith("_y")&&(d&&"object"==typeof d)){const t=d;u(h,null!=(s=t.x)?s:t.X,null!=(r=t.y)?r:t.Y)}}return this.customHitAreas=Object.keys(l).length?l:null,this.customHitAreas}}const Zt={x:PhysicsHair.Src.SRC_TO_X,y:PhysicsHair.Src.SRC_TO_Y,angle:PhysicsHair.Src.SRC_TO_G_ANGLE},Kt={x:PhysicsHair.Src.SRC_TO_X,y:PhysicsHair.Src.SRC_TO_Y,angle:PhysicsHair.Src.SRC_TO_G_ANGLE};class Qt{constructor(t,e){d(this,"physicsHairs",[]),this.coreModel=t,e.physics_hair&&(this.physicsHairs=e.physics_hair.map(t=>{const e=new PhysicsHair;return e.setup(t.setup.length,t.setup.regist,t.setup.mass),t.src.forEach(({id:t,ptype:i,scale:s,weight:r})=>{const a=Zt[i];a&&e.addSrcParam(a,t,s,r)}),t.targets.forEach(({id:t,ptype:i,scale:s,weight:r})=>{const a=Kt[i];a&&e.addTargetParam(a,t,s,r)}),e}))}update(t){this.physicsHairs.forEach(e=>e.update(this.coreModel,t))}}class te{constructor(t){d(this,"paramIndex",-1),d(this,"partsIndex",-1),d(this,"link",[]),this.id=t}initIndex(t){this.paramIndex=t.getParamIndex("VISIBLE:"+this.id),this.partsIndex=t.getPartsDataIndex(PartsDataID.getID(this.id)),t.setParamFloat(this.paramIndex,1)}}class ee{constructor(t,e){d(this,"opacityAnimDuration",500),d(this,"partsGroups",[]),this.coreModel=t,e.parts_visible&&(this.partsGroups=e.parts_visible.map(({group:t})=>t.map(({id:t,link:e})=>{const i=new te(t);return e&&(i.link=e.map(t=>new te(t))),i})),this.init())}init(){this.partsGroups.forEach(t=>{t.forEach(t=>{if(t.initIndex(this.coreModel),t.paramIndex>=0){const e=0!==this.coreModel.getParamFloat(t.paramIndex);this.coreModel.setPartsOpacity(t.partsIndex,e?1:0),this.coreModel.setParamFloat(t.paramIndex,e?1:0),t.link.length>0&&t.link.forEach(t=>t.initIndex(this.coreModel))}})})}normalizePartsOpacityGroup(t,e){const i=this.coreModel,s=.5;let r=1,a=t.findIndex(({paramIndex:t,partsIndex:e})=>e>=0&&0!==i.getParamFloat(t));if(a>=0){const s=i.getPartsOpacity(t[a].partsIndex);r=m(s+e/this.opacityAnimDuration,0,1)}else a=0,r=1;t.forEach(({partsIndex:t},e)=>{if(t>=0)if(a==e)i.setPartsOpacity(t,r);else{let e,a=i.getPartsOpacity(t);e=r<s?-.5*r/s+1:(1-r)*s/.5;(1-e)*(1-r)>.15&&(e=1-.15/(1-r)),a>e&&(a=e),i.setPartsOpacity(t,a)}})}copyOpacity(t){const e=this.coreModel;t.forEach(({partsIndex:t,link:i})=>{if(t>=0&&i){const s=e.getPartsOpacity(t);i.forEach(({partsIndex:t})=>{t>=0&&e.setPartsOpacity(t,s)})}})}update(t){this.partsGroups.forEach(e=>{this.normalizePartsOpacityGroup(e,t),this.copyOpacity(e)})}}if(Pt.registerRuntime({version:2,test:t=>t instanceof ut||ut.isValidJSON(t),ready:()=>Promise.resolve(),isValidMoc(t){if(t.byteLength<3)return!1;const e=new Int8Array(t,0,3);return"moc"===String.fromCharCode(...e)},createModelSettings:t=>new ut(t),createCoreModel(t){const e=Live2DModelWebGL.loadModel(t),i=Live2D.getError();if(i){if(i instanceof Error)throw i;const t="string"==typeof i?i:`Live2D error: ${JSON.stringify(i)}`;throw new Error(t)}return e},createInternalModel:(t,e,i)=>new $t(t,e,i),createPose:(t,e)=>new ee(t,e),createPhysics:(t,e)=>new Qt(t,e)}),"undefined"==typeof window||void 0===window.Live2DCubismCore)throw new Error("Could not find Cubism runtime. This plugin requires live2dcubismcore.js to be loaded.");const ie=class t{constructor(t=0){t<1?(this._ptr=[],this._capacity=0,this._size=0):(this._ptr=new Array(t),this._capacity=t,this._size=0)}at(t){return this._ptr[t]}set(t,e){this._ptr[t]=e}get(t=0){const e=new Array;for(let i=t;i<this._size;i++)e.push(this._ptr[i]);return e}pushBack(e){this._size>=this._capacity&&this.prepareCapacity(0==this._capacity?t.DefaultSize:2*this._capacity),this._ptr[this._size++]=e}clear(){this._ptr.length=0,this._size=0}getSize(){return this._size}assign(t,e){this._size<t&&this.prepareCapacity(t);for(let i=0;i<t;i++)this._ptr[i]=e;this._size=t}resize(t,e=null){this.updateSize(t,e,!0)}updateSize(t,e=null,i=!0){if(this._size<t)if(this.prepareCapacity(t),i)for(let s=this._size;s<t;s++)this._ptr[s]="function"==typeof e?JSON.parse(JSON.stringify(new e)):e;else for(let s=this._size;s<t;s++)this._ptr[s]=e;else{const e=this._size-t;this._ptr.splice(this._size-e,e)}this._size=t}insert(t,e,i){let s=t._index;const r=e._index,a=i._index,n=a-r;this.prepareCapacity(this._size+n);const o=this._size-s;if(o>0)for(let l=0;l<o;l++)this._ptr.splice(s+l,0,null);for(let l=r;l<a;l++,s++)this._ptr[s]=e._vector._ptr[l];this._size=this._size+n}remove(t){return!(t<0||this._size<=t)&&(this._ptr.splice(t,1),--this._size,!0)}erase(t){const e=t._index;if(e<0||this._size<=e)return t;this._ptr.splice(e,1),--this._size;return new re(this,e)}prepareCapacity(t){t>this._capacity&&(0==this._capacity?(this._ptr=new Array(t),this._capacity=t):(this._ptr.length=t,this._capacity=t))}begin(){return 0==this._size?this.end():new re(this,0)}end(){return new re(this,this._size)}getOffset(e){const i=new t;return i._ptr=this.get(e),i._size=this.get(e).length,i._capacity=this.get(e).length,i}};ie.DefaultSize=10;let se=ie,re=class t{constructor(t,e){this._vector=null!=t?t:null,this._index=null!=e?e:0}set(t){return this._index=t._index,this._vector=t._vector,this}preIncrement(){return++this._index,this}preDecrement(){return--this._index,this}increment(){return new t(this._vector,this._index++)}decrement(){return new t(this._vector,this._index--)}ptr(){return this._vector._ptr[this._index]}substitution(t){return this._index=t._index,this._vector=t._vector,this}notEqual(t){return this._index!=t._index||this._vector!=t._vector}};var ae,ne,oe,le,ue,he,de;(ne=ae||(ae={})).csmVector=se,ne.iterator=re;class ge{append(t,e){return this.s+=void 0!==e?t.substr(0,e):t,this}expansion(t,e){for(let i=0;i<t;i++)this.append(e);return this}getBytes(){return encodeURIComponent(this.s).replace(/%../g,"x").length}getLength(){return this.s.length}isLess(t){return this.s<t.s}isGreat(t){return this.s>t.s}isEqual(t){return this.s==t}isEmpty(){return 0==this.s.length}constructor(t){this.s=t}}(t=>{t.csmString=ge})(oe||(oe={}));class ce{static createIdInternal(t){return new ce(t)}getString(){return this._id}isEqual(t){return"string"==typeof t?this._id.isEqual(t):t instanceof ge?this._id.isEqual(t.s):t instanceof ce&&this._id.isEqual(t._id.s)}isNotEqual(t){return"string"==typeof t?!this._id.isEqual(t):t instanceof ge?!this._id.isEqual(t.s):t instanceof ce&&!this._id.isEqual(t._id.s)}constructor(t){this._id="string"!=typeof t?t:new ge(t)}}(t=>{t.CubismId=ce})(le||(le={}));class pe{constructor(){this._ids=new se}release(){for(let t=0;t<this._ids.getSize();++t)this._ids.set(t,void 0);this._ids=null}registerIds(t){for(let e=0;e<t.length;e++)this.registerId(t[e])}registerId(t){let e=null;return"string"!=typeof t?this.registerId(t.s):(null!=(e=this.findId(t))||(e=ce.createIdInternal(t),this._ids.pushBack(e)),e)}getId(t){return this.registerId(t)}isExist(t){return"string"==typeof t?null!=this.findId(t):this.isExist(t.s)}findId(t){for(let e=0;e<this._ids.getSize();++e)if(this._ids.at(e).getString().isEqual(t))return this._ids.at(e);return null}}(t=>{t.CubismIdManager=pe})(ue||(ue={}));class me{constructor(){this._tr=new Float32Array(16),this.loadIdentity()}static multiply(t,e,i){const s=new Float32Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]);for(let r=0;r<4;++r)for(let i=0;i<4;++i)for(let a=0;a<4;++a)s[i+4*r]+=t[a+4*r]*e[i+4*a];for(let r=0;r<16;++r)i[r]=s[r]}loadIdentity(){const t=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);this.setMatrix(t)}setMatrix(t){for(let e=0;e<16;++e)this._tr[e]=t[e]}getArray(){return this._tr}getScaleX(){return this._tr[0]}getScaleY(){return this._tr[5]}getTranslateX(){return this._tr[12]}getTranslateY(){return this._tr[13]}transformX(t){return this._tr[0]*t+this._tr[12]}transformY(t){return this._tr[5]*t+this._tr[13]}invertTransformX(t){return(t-this._tr[12])/this._tr[0]}invertTransformY(t){return(t-this._tr[13])/this._tr[5]}translateRelative(t,e){const i=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,t,e,0,1]);me.multiply(i,this._tr,this._tr)}translate(t,e){this._tr[12]=t,this._tr[13]=e}translateX(t){this._tr[12]=t}translateY(t){this._tr[13]=t}scaleRelative(t,e){const i=new Float32Array([t,0,0,0,0,e,0,0,0,0,1,0,0,0,0,1]);me.multiply(i,this._tr,this._tr)}scale(t,e){this._tr[0]=t,this._tr[5]=e}multiplyByMatrix(t){me.multiply(t.getArray(),this._tr,this._tr)}clone(){const t=new me;for(let e=0;e<this._tr.length;e++)t._tr[e]=this._tr[e];return t}}(t=>{t.CubismMatrix44=me})(he||(he={}));class _e{constructor(t,e,i,s){this.x=t,this.y=e,this.width=i,this.height=s}getCenterX(){return this.x+.5*this.width}getCenterY(){return this.y+.5*this.height}getRight(){return this.x+this.width}getBottom(){return this.y+this.height}setRect(t){this.x=t.x,this.y=t.y,this.width=t.width,this.height=t.height}expand(t,e){this.x-=t,this.y-=e,this.width+=2*t,this.height+=2*e}}(t=>{t.csmRect=_e})(de||(de={}));class fe{static create(){return null}static delete(t){}initialize(t){this._model=t}drawModel(){null!=this.getModel()&&(this.saveProfile(),this.doDrawModel(),this.restoreProfile())}setMvpMatrix(t){this._mvpMatrix4x4.setMatrix(t.getArray())}getMvpMatrix(){return this._mvpMatrix4x4}setModelColor(t,e,i,s){t<0?t=0:t>1&&(t=1),e<0?e=0:e>1&&(e=1),i<0?i=0:i>1&&(i=1),s<0?s=0:s>1&&(s=1),this._modelColor.r=t,this._modelColor.g=e,this._modelColor.b=i,this._modelColor.a=s}getModelColor(){return JSON.parse(JSON.stringify(this._modelColor))}getModelColorWithOpacity(t){const e=this.getModelColor();return e.a*=t,this.isPremultipliedAlpha()&&(e.r*=e.a,e.g*=e.a,e.b*=e.a),e}setIsPremultipliedAlpha(t){this._isPremultipliedAlpha=t}isPremultipliedAlpha(){return this._isPremultipliedAlpha}setIsCulling(t){this._isCulling=t}isCulling(){return this._isCulling}setAnisotropy(t){this._anisotropy=t}getAnisotropy(){return this._anisotropy}getModel(){return this._model}useHighPrecisionMask(t){this._useHighPrecisionMask=t}isUsingHighPrecisionMask(){return this._useHighPrecisionMask}constructor(){this._isCulling=!1,this._isPremultipliedAlpha=!1,this._anisotropy=0,this._model=null,this._modelColor=new Me,this._useHighPrecisionMask=!1,this._mvpMatrix4x4=new me,this._mvpMatrix4x4.loadIdentity()}}var ye,xe=(t=>(t[t.CubismBlendMode_Normal=0]="CubismBlendMode_Normal",t[t.CubismBlendMode_Additive=1]="CubismBlendMode_Additive",t[t.CubismBlendMode_Multiplicative=2]="CubismBlendMode_Multiplicative",t))(xe||{});class Me{constructor(t=1,e=1,i=1,s=1){this.r=t,this.g=e,this.b=i,this.a=s}}class Ce{constructor(t,e){this._clippingIdList=t,this._clippingIdCount=e,this._allClippedDrawRect=new _e,this._layoutBounds=new _e,this._clippedDrawableIndexList=[],this._matrixForMask=new me,this._matrixForDraw=new me,this._bufferIndex=0}release(){null!=this._layoutBounds&&(this._layoutBounds=null),null!=this._allClippedDrawRect&&(this._allClippedDrawRect=null),null!=this._clippedDrawableIndexList&&(this._clippedDrawableIndexList=null)}addClippedDrawable(t){this._clippedDrawableIndexList.push(t)}}(t=>{t.CubismBlendMode=xe,t.CubismRenderer=fe,t.CubismTextureColor=Me})(ye||(ye={}));const Se=(t,e,i)=>{((t,e,i)=>{Ie.print(t,"[CSM]"+e,i)})(t,e+"\n",i)},ve=t=>{console.assert(t)};let be,Pe,Be,we;be=(t,...e)=>{Se(si.LogLevel_Debug,"[D]"+t,e)},Pe=(t,...e)=>{Se(si.LogLevel_Info,"[I]"+t,e)},Be=(t,...e)=>{Se(si.LogLevel_Warning,"[W]"+t,e)},we=(t,...e)=>{Se(si.LogLevel_Error,"[E]"+t,e)};class Ie{static print(t,e,i){if(t<ti.getLoggingLevel())return;const s=ti.coreLogFunction;if(!s)return;s(e.replace(/\{(\d+)\}/g,(t,e)=>i[e]))}static dumpBytes(t,e,i){for(let s=0;s<i;s++)s%16==0&&s>0?this.print(t,"\n"):s%8==0&&s>0&&this.print(t," "),this.print(t,"{0} ",[255&e[s]]);this.print(t,"\n")}constructor(){}}var Fe;(t=>{t.CubismDebug=Ie})(Fe||(Fe={}));class Ee{constructor(t,e){this.first=null==t?null:t,this.second=null==e?null:e}}const Le=class t{constructor(t){null!=t?t<1?(this._keyValues=[],this._dummyValue=null,this._size=0):(this._keyValues=new Array(t),this._size=t):(this._keyValues=[],this._dummyValue=null,this._size=0)}release(){this.clear()}appendKey(t){let e=-1;for(let i=0;i<this._size;i++)if(this._keyValues[i].first==t){e=i;break}-1==e?(this.prepareCapacity(this._size+1,!1),this._keyValues[this._size]=new Ee(t),this._size+=1):Be("The key `{0}` is already append.",t)}getValue(t){let e=-1;for(let i=0;i<this._size;i++)if(this._keyValues[i].first==t){e=i;break}return e>=0?this._keyValues[e].second:(this.appendKey(t),this._keyValues[this._size-1].second)}setValue(t,e){let i=-1;for(let s=0;s<this._size;s++)if(this._keyValues[s].first==t){i=s;break}i>=0?this._keyValues[i].second=e:(this.appendKey(t),this._keyValues[this._size-1].second=e)}isExist(t){for(let e=0;e<this._size;e++)if(this._keyValues[e].first==t)return!0;return!1}clear(){this._keyValues=void 0,this._keyValues=null,this._keyValues=[],this._size=0}getSize(){return this._size}prepareCapacity(e,i){e>this._keyValues.length&&(0==this._keyValues.length?(!i&&e<t.DefaultSize&&(e=t.DefaultSize),this._keyValues.length=e):(!i&&e<2*this._keyValues.length&&(e=2*this._keyValues.length),this._keyValues.length=e))}begin(){return new Te(this,0)}end(){return new Te(this,this._size)}erase(t){const e=t._index;if(e<0||this._size<=e)return t;this._keyValues.splice(e,1),--this._size;return new Te(this,e)}dumpAsInt(){for(let t=0;t<this._size;t++)be("{0} ,",this._keyValues[t]),be("\n")}};Le.DefaultSize=10;let Ve=Le;class Te{constructor(t,e){this._map=null!=t?t:new Ve,this._index=null!=e?e:0}set(t){return this._index=t._index,this._map=t._map,this}preIncrement(){return++this._index,this}preDecrement(){return--this._index,this}increment(){return new Te(this._map,this._index++)}decrement(){const t=new Te(this._map,this._index);return this._map=t._map,this._index=t._index,this}ptr(){return this._map._keyValues[this._index]}notEqual(t){return this._index!=t._index||this._map!=t._map}}var Re;(t=>{t.csmMap=Ve,t.csmPair=Ee,t.iterator=Te})(Re||(Re={}));class De{static parseJsonObject(t,e){return Object.keys(t).forEach(i=>{if("boolean"==typeof t[i]){const s=Boolean(t[i]);e.put(i,new Ue(s))}else if("string"==typeof t[i]){const s=String(t[i]);e.put(i,new ze(s))}else if("number"==typeof t[i]){const s=Number(t[i]);e.put(i,new Ne(s))}else t[i]instanceof Array?e.put(i,De.parseJsonArray(t[i])):t[i]instanceof Object?e.put(i,De.parseJsonObject(t[i],new He)):null==t[i]?e.put(i,new Ge):e.put(i,t[i])}),e}static parseJsonArray(t){const e=new Xe;return Object.keys(t).forEach(i=>{if("number"==typeof Number(i))if("boolean"==typeof t[i]){const s=Boolean(t[i]);e.add(new Ue(s))}else if("string"==typeof t[i]){const s=String(t[i]);e.add(new ze(s))}else if("number"==typeof t[i]){const s=Number(t[i]);e.add(new Ne(s))}else t[i]instanceof Array?e.add(this.parseJsonArray(t[i])):t[i]instanceof Object?e.add(this.parseJsonObject(t[i],new He)):null==t[i]?e.add(new Ge):e.add(t[i]);else if(t[i]instanceof Array)e.add(this.parseJsonArray(t[i]));else if(t[i]instanceof Object)e.add(this.parseJsonObject(t[i],new He));else if(null==t[i])e.add(new Ge);else{const s=Array(t[i]);for(let t=0;t<s.length;t++)e.add(s[t])}}),e}}const Ae="Error: type mismatch";let Oe=class t{constructor(){}getRawString(t,e){return this.getString(t,e)}toInt(t=0){return t}toFloat(t=0){return t}toBoolean(t=!1){return t}getSize(){return 0}getArray(t=null){return t}getVector(t=new se){return t}getMap(t){return t}getValueByIndex(e){return t.errorValue.setErrorNotForClientCall(Ae)}getValueByString(e){return t.nullValue.setErrorNotForClientCall(Ae)}getKeys(){return t.dummyKeys}isError(){return!1}isNull(){return!1}isBool(){return!1}isFloat(){return!1}isString(){return!1}isArray(){return!1}isMap(){return!1}equals(t){return!1}isStatic(){return!1}setErrorNotForClientCall(t){return je.errorValue}static staticInitializeNotForClientCall(){Ue.trueValue=new Ue(!0),Ue.falseValue=new Ue(!1),t.errorValue=new je("ERROR",!0),t.nullValue=new Ge,t.dummyKeys=new se}static staticReleaseNotForClientCall(){Ue.trueValue=null,Ue.falseValue=null,t.errorValue=null,t.nullValue=null,t.dummyKeys=null}};class ke{constructor(t,e){this._parseCallback=De.parseJsonObject,this._error=null,this._lineCount=0,this._root=null,null!=t&&this.parseBytes(t,e,this._parseCallback)}static create(t,e){const i=new ke;return i.parseBytes(t,e,i._parseCallback)?i:(ke.delete(i),null)}static delete(t){}getRoot(){return this._root}static arrayBufferToString(t){const e=new Uint8Array(t);let i="";for(let s=0,r=e.length;s<r;++s)i+="%"+this.pad(e[s].toString(16));return i=decodeURIComponent(i),i}static pad(t){return t.length<2?"0"+t:t}parseBytes(t,e,i){const s=new Array(1),r=ke.arrayBufferToString(t);if(this._root=null==i?this.parseValue(r,e,0,s):i(JSON.parse(r),new He),this._error){let t="\0";return t="Json parse error : @line "+(this._lineCount+1)+"\n",this._root=new ze(t),Pe("{0}",this._root.getRawString()),!1}return null!=this._root||(this._root=new je(new ge(this._error),!1),!1)}getParseError(){return this._error}checkEndOfFile(){return this._root.getArray()[1].equals("EOF")}parseValue(t,e,i,s){if(this._error)return null;let r,a=null,n=i;for(;n<e;n++){switch(t[n]){case"-":case".":case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{const e=new Array(1);return r=qe(t.slice(n),e),s[0]=t.indexOf(e[0]),new Ne(r)}case'"':return new ze(this.parseString(t,e,n+1,s));case"[":return a=this.parseArray(t,e,n+1,s),a;case"{":return a=this.parseObject(t,e,n+1,s),a;case"n":return n+3<e?(a=new Ge,s[0]=n+4):this._error="parse null",a;case"t":return n+3<e?(a=Ue.trueValue,s[0]=n+4):this._error="parse true",a;case"f":return n+4<e?(a=Ue.falseValue,s[0]=n+5):this._error="illegal ',' position",a;case",":return this._error="illegal ',' position",null;case"]":return s[0]=n,null;case"\n":this._lineCount++}}return this._error="illegal end of value",null}parseString(t,e,i,s){if(this._error)return null;if(!t)return this._error="string is null",null;let r,a,n=i;const o=new ge("");let l=i;for(;n<e;n++)switch(r=t[n],r){case'"':return s[0]=n+1,o.append(t.slice(l),n-l),o.s;case"//":if(n++,n-1>l&&o.append(t.slice(l),n-l),l=n+1,n<e)switch(a=t[n],a){case"\\":o.expansion(1,"\\");break;case'"':o.expansion(1,'"');break;case"/":o.expansion(1,"/");break;case"b":o.expansion(1,"\b");break;case"f":o.expansion(1,"\f");break;case"n":o.expansion(1,"\n");break;case"r":o.expansion(1,"\r");break;case"t":o.expansion(1,"\t");break;case"u":this._error="parse string/unicord escape not supported"}else this._error="parse string/escape error"}return this._error="parse string/illegal end",null}parseObject(t,e,i,s){if(this._error)return null;if(!t)return this._error="buffer is null",null;const r=new He;let a="",n=i,o="";const l=Array(1);let u=!1;for(;n<e;n++){t:for(;n<e;n++)switch(o=t[n],o){case'"':if(a=this.parseString(t,e,n+1,l),this._error)return null;n=l[0],u=!0;break t;case"}":return s[0]=n+1,r;case":":this._error="illegal ':' position";break;case"\n":this._lineCount++}if(!u)return this._error="key not found",null;u=!1;t:for(;n<e;n++)switch(o=t[n],o){case":":u=!0,n++;break t;case"}":this._error="illegal '}' position";break;case"\n":this._lineCount++}if(!u)return this._error="':' not found",null;const i=this.parseValue(t,e,n,l);if(this._error)return null;n=l[0],r.put(a,i);t:for(;n<e;n++)switch(o=t[n],o){case",":break t;case"}":return s[0]=n+1,r;case"\n":this._lineCount++}}return this._error="illegal end of perseObject",null}parseArray(t,e,i,s){if(this._error)return null;if(!t)return this._error="buffer is null",null;let r,a=new Xe,n=i;const o=new Array(1);for(;n<e;n++){const i=this.parseValue(t,e,n,o);if(this._error)return null;n=o[0],i&&a.add(i);t:for(;n<e;n++)switch(r=t[n],r){case",":break t;case"]":return s[0]=n+1,a;case"\n":++this._lineCount}}return a=void 0,this._error="illegal end of parseObject",null}}class Ne extends Oe{constructor(t){super(),this._value=t}isFloat(){return!0}getString(t,e){return this._value=parseFloat("\0"),this._stringBuffer="\0",this._stringBuffer}toInt(t=0){return parseInt(this._value.toString())}toFloat(t=0){return this._value}equals(t){return"number"==typeof t&&(!Math.round(t)&&t==this._value)}}class Ue extends Oe{isBool(){return!0}toBoolean(t=!1){return this._boolValue}getString(t,e){return this._stringBuffer=this._boolValue?"true":"false",this._stringBuffer}equals(t){return"boolean"==typeof t&&t==this._boolValue}isStatic(){return!0}constructor(t){super(),this._boolValue=t}}class ze extends Oe{constructor(t){super(),"string"==typeof t&&(this._stringBuffer=t),t instanceof ge&&(this._stringBuffer=t.s)}isString(){return!0}getString(t,e){return this._stringBuffer}equals(t){return"string"==typeof t?this._stringBuffer==t:t instanceof ge&&this._stringBuffer==t.s}}class je extends ze{isStatic(){return this._isStatic}setErrorNotForClientCall(t){return this._stringBuffer=t,this}constructor(t,e){super(t),this._isStatic=e}isError(){return!0}}class Ge extends Oe{isNull(){return!0}getString(t,e){return this._stringBuffer}isStatic(){return!0}setErrorNotForClientCall(t){return this._stringBuffer=t,je.nullValue}constructor(){super(),this._stringBuffer="NullValue"}}class Xe extends Oe{constructor(){super(),this._array=new se}release(){for(let t=this._array.begin();t.notEqual(this._array.end());t.preIncrement()){let e=t.ptr();e&&!e.isStatic()&&(e=void 0,e=null)}}isArray(){return!0}getValueByIndex(t){if(t<0||this._array.getSize()<=t)return Oe.errorValue.setErrorNotForClientCall("Error: index out of bounds");const e=this._array.at(t);return null==e?Oe.nullValue:e}getValueByString(t){return Oe.errorValue.setErrorNotForClientCall(Ae)}getString(t,e){const i=e+"[\n";for(let s=this._array.begin();s.notEqual(this._array.end());s.increment()){const t=s.ptr();this._stringBuffer+=e+""+t.getString(e+" ")+"\n"}return this._stringBuffer=i+e+"]\n",this._stringBuffer}add(t){this._array.pushBack(t)}getVector(t=null){return this._array}getSize(){return this._array.getSize()}}class He extends Oe{constructor(){super(),this._map=new Ve}release(){const t=this._map.begin();for(;t.notEqual(this._map.end());){let e=t.ptr().second;e&&!e.isStatic()&&(e=void 0,e=null),t.preIncrement()}}isMap(){return!0}getValueByString(t){if(t instanceof ge){const e=this._map.getValue(t.s);return null==e?Oe.nullValue:e}for(let e=this._map.begin();e.notEqual(this._map.end());e.preIncrement())if(e.ptr().first==t)return null==e.ptr().second?Oe.nullValue:e.ptr().second;return Oe.nullValue}getValueByIndex(t){return Oe.errorValue.setErrorNotForClientCall(Ae)}getString(t,e){this._stringBuffer=e+"{\n";const i=this._map.begin();for(;i.notEqual(this._map.end());){const t=i.ptr().first,s=i.ptr().second;this._stringBuffer+=e+" "+t+" : "+s.getString(e+" ")+" \n",i.preIncrement()}return this._stringBuffer+=e+"}\n",this._stringBuffer}getMap(t){return this._map}put(t,e){this._map.setValue(t,e)}getKeys(){if(!this._keys){this._keys=new se;const t=this._map.begin();for(;t.notEqual(this._map.end());){const e=t.ptr().first;this._keys.pushBack(e),t.preIncrement()}}return this._keys}getSize(){return this._keys.getSize()}}var Ye;function qe(t,e){let i=0;for(let r=1;;r++){const e=t.slice(r-1,r);if("e"==e||"-"==e||"E"==e)continue;const s=t.substring(0,r),a=Number(s);if(isNaN(a))break;i=r}let s=parseFloat(t);return isNaN(s)&&(s=NaN),e[0]=t.slice(i),s}(t=>{t.CubismJson=ke,t.JsonArray=Xe,t.JsonBoolean=Ue,t.JsonError=je,t.JsonFloat=Ne,t.JsonMap=He,t.JsonNullvalue=Ge,t.JsonString=ze,t.Value=Oe})(Ye||(Ye={}));let We=!1,Je=!1,$e=null,Ze=null;const Ke=Object.freeze({vertexOffset:0,vertexStep:2});function Qe(t){t&&(t=void 0)}class ti{static startUp(t=null){if(We)return Pe("CubismFramework.startUp() is already done."),We;if($e=t,null!=$e&&Live2DCubismCore.Logging.csmSetLogFunction($e.logFunction),We=!0,We){const t=Live2DCubismCore.Version.csmGetVersion(),e=(16711680&t)>>16,i=65535&t,s=t;Pe("Live2D Cubism Core version: {0}.{1}.{2} ({3})",("00"+((4278190080&t)>>24)).slice(-2),("00"+e).slice(-2),("0000"+i).slice(-4),s)}return Pe("CubismFramework.startUp() is complete."),We}static cleanUp(){We=!1,Je=!1,$e=null,Ze=null}static initialize(t=0){ve(We),We?Je?Be("CubismFramework.initialize() skipped, already initialized."):(Oe.staticInitializeNotForClientCall(),Ze=new pe,Live2DCubismCore.Memory.initializeAmountOfMemory(t),Je=!0,Pe("CubismFramework.initialize() is complete.")):Be("CubismFramework is not started.")}static dispose(){ve(We),We?Je?(Oe.staticReleaseNotForClientCall(),Ze.release(),Ze=null,fe.staticRelease(),Je=!1,Pe("CubismFramework.dispose() is complete.")):Be("CubismFramework.dispose() skipped, not initialized."):Be("CubismFramework is not started.")}static isStarted(){return We}static isInitialized(){return Je}static coreLogFunction(t){Live2DCubismCore.Logging.csmGetLogFunction()&&Live2DCubismCore.Logging.csmGetLogFunction()(t)}static getLoggingLevel(){return null!=$e?$e.loggingLevel:5}static getIdManager(){return Ze}constructor(){}}var ei,ii,si=(t=>(t[t.LogLevel_Verbose=0]="LogLevel_Verbose",t[t.LogLevel_Debug=1]="LogLevel_Debug",t[t.LogLevel_Info=2]="LogLevel_Info",t[t.LogLevel_Warning=3]="LogLevel_Warning",t[t.LogLevel_Error=4]="LogLevel_Error",t[t.LogLevel_Off=5]="LogLevel_Off",t))(si||{});(t=>{t.Constant=Ke,t.csmDelete=Qe,t.CubismFramework=ti})(ei||(ei={}));class ri{constructor(t,e){this.x=t,this.y=e,this.x=null==t?0:t,this.y=null==e?0:e}add(t){const e=new ri(0,0);return e.x=this.x+t.x,e.y=this.y+t.y,e}substract(t){const e=new ri(0,0);return e.x=this.x-t.x,e.y=this.y-t.y,e}multiply(t){const e=new ri(0,0);return e.x=this.x*t.x,e.y=this.y*t.y,e}multiplyByScaler(t){return this.multiply(new ri(t,t))}division(t){const e=new ri(0,0);return e.x=this.x/t.x,e.y=this.y/t.y,e}divisionByScalar(t){return this.division(new ri(t,t))}getLength(){return Math.sqrt(this.x*this.x+this.y*this.y)}getDistanceWith(t){return Math.sqrt((this.x-t.x)*(this.x-t.x)+(this.y-t.y)*(this.y-t.y))}dot(t){return this.x*t.x+this.y*t.y}normalize(){const t=Math.pow(this.x*this.x+this.y*this.y,.5);this.x=this.x/t,this.y=this.y/t}isEqual(t){return this.x==t.x&&this.y==t.y}isNotEqual(t){return!this.isEqual(t)}}(t=>{t.CubismVector2=ri})(ii||(ii={}));const ai=class t{static range(t,e,i){return t<e?t=e:t>i&&(t=i),t}static sin(t){return Math.sin(t)}static cos(t){return Math.cos(t)}static abs(t){return Math.abs(t)}static sqrt(t){return Math.sqrt(t)}static cbrt(t){if(0===t)return t;let e=t;const i=e<0;let s;return i&&(e=-e),e===1/0?s=1/0:(s=Math.exp(Math.log(e)/3),s=(e/(s*s)+2*s)/3),i?-s:s}static getEasingSine(t){return t<0?0:t>1?1:.5-.5*this.cos(t*Math.PI)}static max(t,e){return t>e?t:e}static min(t,e){return t>e?e:t}static clamp(t,e,i){return t<e?e:i<t?i:t}static degreesToRadian(t){return t/180*Math.PI}static radianToDegrees(t){return 180*t/Math.PI}static directionToRadian(t,e){let i=Math.atan2(e.y,e.x)-Math.atan2(t.y,t.x);for(;i<-Math.PI;)i+=2*Math.PI;for(;i>Math.PI;)i-=2*Math.PI;return i}static directionToDegrees(t,e){const i=this.directionToRadian(t,e);let s=this.radianToDegrees(i);return e.x-t.x>0&&(s=-s),s}static radianToDirection(t){const e=new ri;return e.x=this.sin(t),e.y=this.cos(t),e}static quadraticEquation(e,i,s){return this.abs(e)<t.Epsilon?this.abs(i)<t.Epsilon?-s:-s/i:-(i+this.sqrt(i*i-4*e*s))/(2*e)}static cardanoAlgorithmForBezier(e,i,s,r){if(this.abs(e)<t.Epsilon)return this.range(this.quadraticEquation(i,s,r),0,1);const a=i/e,n=s/e,o=(3*n-a*a)/3,l=o/3,u=(2*a*a*a-9*a*n+27*(r/e))/27,h=u/2,d=h*h+l*l*l,g=.5,c=.51;if(d<0){const t=-o/3,e=t*t*t,i=this.sqrt(e),s=-u/(2*i),r=this.range(s,-1,1),n=Math.acos(r),l=2*this.cbrt(i),h=l*this.cos(n/3)-a/3;if(this.abs(h-g)<c)return this.range(h,0,1);const d=l*this.cos((n+2*Math.PI)/3)-a/3;if(this.abs(d-g)<c)return this.range(d,0,1);const p=l*this.cos((n+4*Math.PI)/3)-a/3;return this.range(p,0,1)}if(0==d){let t;t=h<0?this.cbrt(-h):-this.cbrt(h);const e=2*t-a/3;if(this.abs(e-g)<c)return this.range(e,0,1);const i=-t-a/3;return this.range(i,0,1)}const p=this.sqrt(d),m=this.cbrt(p-h)-this.cbrt(p+h)-a/3;return this.range(m,0,1)}static mod(t,e){if(!isFinite(t)||0===e||isNaN(t)||isNaN(e))return console.warn(`divided: ${t}, divisor: ${e} mod() returns 'NaN'.`),NaN;const i=Math.abs(t),s=Math.abs(e);let r=i-Math.floor(i/s)*s;return r*=Math.sign(t),r}constructor(){}};ai.Epsilon=1e-5;let ni=ai;var oi,li;(t=>{t.CubismMath=ni})(oi||(oi={}));class ui{constructor(){this.setBeganMotionHandler=t=>this._onBeganMotion=t,this.getBeganMotionHandler=()=>this._onBeganMotion,this.setFinishedMotionHandler=t=>this._onFinishedMotion=t,this.getFinishedMotionHandler=()=>this._onFinishedMotion,this._fadeInSeconds=-1,this._fadeOutSeconds=-1,this._weight=1,this._offsetSeconds=0,this._isLoop=!1,this._isLoopFadeIn=!0,this._previousLoopState=this._isLoop,this._firedEventValues=new se}static delete(t){t.release(),t=null}release(){this._weight=0}updateParameters(t,e,i){if(!e.isAvailable()||e.isFinished())return;this.setupMotionQueueEntry(e,i);const s=this.updateFadeWeight(e,i);this.doUpdateParameters(t,i,s,e),e.getEndTime()>0&&e.getEndTime()<i&&e.setIsFinished(!0)}setupMotionQueueEntry(t,e){null==t||t.isStarted()||t.isAvailable()&&(t.setIsStarted(!0),t.setStartTime(e-this._offsetSeconds),t.setFadeInStartTime(e),t.getEndTime()<0&&this.adjustEndTime(t),t._motion._onBeganMotion&&t._motion._onBeganMotion(t._motion))}updateFadeWeight(t,e){null==t&&Ie.print(si.LogLevel_Error,"motionQueueEntry is null.");let i=this._weight;return i=i*(0==this._fadeInSeconds?1:ni.getEasingSine((e-t.getFadeInStartTime())/this._fadeInSeconds))*(0==this._fadeOutSeconds||t.getEndTime()<0?1:ni.getEasingSine((t.getEndTime()-e)/this._fadeOutSeconds)),t.setState(e,i),ve(0<=i&&i<=1),i}setFadeInTime(t){this._fadeInSeconds=t}setFadeOutTime(t){this._fadeOutSeconds=t}getFadeOutTime(){return this._fadeOutSeconds}getFadeInTime(){return this._fadeInSeconds}setWeight(t){this._weight=t}getWeight(){return this._weight}getDuration(){return-1}getLoopDuration(){return-1}setOffsetTime(t){this._offsetSeconds=t}setLoop(t){this._isLoop=t}getLoop(){return this._isLoop}setLoopFadeIn(t){this._isLoopFadeIn=t}getLoopFadeIn(){return this._isLoopFadeIn}getFiredEvent(t,e){return this._firedEventValues}isExistModelOpacity(){return!1}getModelOpacityIndex(){return-1}getModelOpacityId(t){return null}getModelOpacityValue(){return 1}adjustEndTime(t){const e=this.getDuration(),i=e<=0?-1:t.getStartTime()+e;t.setEndTime(i)}}(t=>{t.ACubismMotion=ui})(li||(li={}));const hi="Parameters",di="Blend",gi=class t extends ui{static create(e,i){const s=new t;return s.parse(e,i),s}doUpdateParameters(t,e,i,s){for(let r=0;r<this._parameters.getSize();++r){const e=this._parameters.at(r);switch(e.blendType){case 0:t.addParameterValueById(e.parameterId,e.value,i);break;case 1:t.multiplyParameterValueById(e.parameterId,e.value,i);break;case 2:t.setParameterValueById(e.parameterId,e.value,i)}}}calculateExpressionParameters(e,i,s,r,a,n){if(null!=s&&null!=r&&s.isAvailable()){this._fadeWeight=this.updateFadeWeight(s,i);for(let i=0;i<r.getSize();++i){const s=r.at(i);if(null==s.parameterId)continue;const o=s.overwriteValue=e.getParameterValueById(s.parameterId),l=this.getExpressionParameters();let u=-1;for(let t=0;t<l.getSize();++t)if(s.parameterId==l.at(t).parameterId){u=t;break}if(u<0){0==a?(s.additiveValue=t.DefaultAdditiveValue,s.multiplyValue=t.DefaultMultiplyValue,s.overwriteValue=o):(s.additiveValue=this.calculateValue(s.additiveValue,t.DefaultAdditiveValue,n),s.multiplyValue=this.calculateValue(s.multiplyValue,t.DefaultMultiplyValue,n),s.overwriteValue=this.calculateValue(s.overwriteValue,o,n));continue}const h=l.at(u).value;let d,g,c;switch(l.at(u).blendType){case 0:d=h,g=t.DefaultMultiplyValue,c=o;break;case 1:d=t.DefaultAdditiveValue,g=h,c=o;break;case 2:d=t.DefaultAdditiveValue,g=t.DefaultMultiplyValue,c=h;break;default:return}0==a?(s.additiveValue=d,s.multiplyValue=g,s.overwriteValue=c):(s.additiveValue=s.additiveValue*(1-n)+d*n,s.multiplyValue=s.multiplyValue*(1-n)+g*n,s.overwriteValue=s.overwriteValue*(1-n)+c*n)}}}getExpressionParameters(){return this._parameters}getFadeWeight(){return this._fadeWeight}parse(t,e){const i=ke.create(t,e);if(!i)return;const s=i.getRoot();this.setFadeInTime(s.getValueByString("FadeInTime").toFloat(1)),this.setFadeOutTime(s.getValueByString("FadeOutTime").toFloat(1));const r=s.getValueByString(hi).getSize();this._parameters.prepareCapacity(r);for(let a=0;a<r;++a){const t=s.getValueByString(hi).getValueByIndex(a),e=ti.getIdManager().getId(t.getValueByString("Id").getRawString()),i=t.getValueByString("Value").toFloat();let r;r=t.getValueByString(di).isNull()||"Add"==t.getValueByString(di).getString()?0:"Multiply"==t.getValueByString(di).getString()?1:"Overwrite"==t.getValueByString(di).getString()?2:0;const n=new fi;n.parameterId=e,n.blendType=r,n.value=i,this._parameters.pushBack(n)}ke.delete(i)}calculateValue(t,e,i){return t*(1-i)+e*i}constructor(){super(),this._parameters=new se,this._fadeWeight=0}};gi.DefaultAdditiveValue=0,gi.DefaultMultiplyValue=1;let ci=gi;var pi,mi,_i=(t=>(t[t.Additive=0]="Additive",t[t.Multiply=1]="Multiply",t[t.Overwrite=2]="Overwrite",t))(_i||{});class fi{}(t=>{t.CubismExpressionMotion=ci,t.ExpressionBlendType=_i,t.ExpressionParameter=fi})(pi||(pi={}));class yi{constructor(){this._autoDelete=!1,this._motion=null,this._available=!0,this._finished=!1,this._started=!1,this._startTimeSeconds=-1,this._fadeInStartTimeSeconds=0,this._endTimeSeconds=-1,this._stateTimeSeconds=0,this._stateWeight=0,this._lastEventCheckSeconds=0,this._motionQueueEntryHandle=this,this._fadeOutSeconds=0,this._isTriggeredFadeOut=!1}release(){this._autoDelete&&this._motion&&ui.delete(this._motion)}setFadeOut(t){this._fadeOutSeconds=t,this._isTriggeredFadeOut=!0}startFadeOut(t,e){const i=e+t;this._isTriggeredFadeOut=!0,(this._endTimeSeconds<0||i<this._endTimeSeconds)&&(this._endTimeSeconds=i)}isFinished(){return this._finished}isStarted(){return this._started}getStartTime(){return this._startTimeSeconds}getFadeInStartTime(){return this._fadeInStartTimeSeconds}getEndTime(){return this._endTimeSeconds}setStartTime(t){this._startTimeSeconds=t}setFadeInStartTime(t){this._fadeInStartTimeSeconds=t}setEndTime(t){this._endTimeSeconds=t}setIsFinished(t){this._finished=t}setIsStarted(t){this._started=t}isAvailable(){return this._available}setIsAvailable(t){this._available=t}setState(t,e){this._stateTimeSeconds=t,this._stateWeight=e}getStateTime(){return this._stateTimeSeconds}getStateWeight(){return this._stateWeight}getLastCheckEventSeconds(){return this._lastEventCheckSeconds}setLastCheckEventSeconds(t){this._lastEventCheckSeconds=t}isTriggeredFadeOut(){return this._isTriggeredFadeOut}getFadeOutSeconds(){return this._fadeOutSeconds}getCubismMotion(){return this._motion}}(t=>{t.CubismMotionQueueEntry=yi})(mi||(mi={}));class xi{constructor(){this._userTimeSeconds=0,this._eventCallBack=null,this._eventCustomData=null,this._motions=new se}release(){for(let t=0;t<this._motions.getSize();++t)this._motions.at(t)&&(this._motions.at(t).release(),this._motions.set(t,null));this._motions=null}startMotion(t,e,i){if(null==t)return Mi;let s=null;for(let r=0;r<this._motions.getSize();++r)s=this._motions.at(r),null!=s&&s.setFadeOut(s._motion.getFadeOutTime());return s=new yi,s._autoDelete=e,s._motion=t,this._motions.pushBack(s),s._motionQueueEntryHandle}isFinished(){for(let t=this._motions.begin();t.notEqual(this._motions.end());){let e=t.ptr();if(null==e){t=this._motions.erase(t);continue}if(null!=e._motion){if(!e.isFinished())return!1;t.preIncrement()}else e.release(),e=null,t=this._motions.erase(t)}return!0}isFinishedByHandle(t){for(let e=this._motions.begin();e.notEqual(this._motions.end());e.increment()){const i=e.ptr();if(null!=i&&(i._motionQueueEntryHandle==t&&!i.isFinished()))return!1}return!0}stopAllMotions(){for(let t=this._motions.begin();t.notEqual(this._motions.end());){let e=t.ptr();null!=e?(e.release(),e=null,t=this._motions.erase(t)):t=this._motions.erase(t)}}getCubismMotionQueueEntries(){return this._motions}getCubismMotionQueueEntry(t){for(let e=this._motions.begin();e.notEqual(this._motions.end());e.preIncrement()){const i=e.ptr();if(null!=i&&i._motionQueueEntryHandle==t)return i}return null}setEventCallback(t,e=null){this._eventCallBack=t,this._eventCustomData=e}doUpdateMotion(t,e){let i=!1;for(let s=this._motions.begin();s.notEqual(this._motions.end());){let r=s.ptr();if(null==r){s=this._motions.erase(s);continue}const a=r._motion;if(null==a){r.release(),r=null,s=this._motions.erase(s);continue}a.updateParameters(t,r,e),i=!0;const n=a.getFiredEvent(r.getLastCheckEventSeconds()-r.getStartTime(),e-r.getStartTime());for(let t=0;t<n.getSize();++t)this._eventCallBack(this,n.at(t),this._eventCustomData);r.setLastCheckEventSeconds(e),r.isFinished()?(r.release(),r=null,s=this._motions.erase(s)):(r.isTriggeredFadeOut()&&r.startFadeOut(r.getFadeOutSeconds(),e),s.preIncrement())}return i}}const Mi=-1;var Ci;(t=>{t.CubismMotionQueueManager=xi,t.InvalidMotionQueueEntryHandleValue=Mi})(Ci||(Ci={}));class Si extends P{constructor(t,e){var i,s;super(t,e),d(this,"expressionDataType","arraybuffer"),d(this,"queueManager",new xi),d(this,"definitions"),this.definitions=null!=(s=null==(i=t.expressions)?void 0:i.filter(t=>!!t&&"string"==typeof t.File))?s:[],this.init()}isFinished(){return this.queueManager.isFinished()}getExpressionIndex(t){return this.definitions.findIndex(e=>e.Name===t)}getExpressionFile(t){return t.File}createExpression(t,e){return ci.create(t,t.byteLength)}_setExpression(t){return this.queueManager.startMotion(t,!1)}stopAllExpressions(){this.queueManager.stopAllMotions()}updateParameters(t,e){return this.queueManager.doUpdateMotion(t,e)}createDefaultExpression(){const t=(new TextEncoder).encode(JSON.stringify({FadeInTime:0,FadeOutTime:0,Parameters:[]})).buffer;return ci.create(t,t.byteLength)}}var vi,bi=(t=>(t[t.CubismMotionCurveTarget_Model=0]="CubismMotionCurveTarget_Model",t[t.CubismMotionCurveTarget_Parameter=1]="CubismMotionCurveTarget_Parameter",t[t.CubismMotionCurveTarget_PartOpacity=2]="CubismMotionCurveTarget_PartOpacity",t))(bi||{}),Pi=(t=>(t[t.CubismMotionSegmentType_Linear=0]="CubismMotionSegmentType_Linear",t[t.CubismMotionSegmentType_Bezier=1]="CubismMotionSegmentType_Bezier",t[t.CubismMotionSegmentType_Stepped=2]="CubismMotionSegmentType_Stepped",t[t.CubismMotionSegmentType_InverseStepped=3]="CubismMotionSegmentType_InverseStepped",t))(Pi||{});class Bi{constructor(){this.time=0,this.value=0}}class wi{constructor(){this.evaluate=null,this.basePointIndex=0,this.segmentType=0}}class Ii{constructor(){this.type=0,this.segmentCount=0,this.baseSegmentIndex=0,this.fadeInTime=0,this.fadeOutTime=0}}class Fi{constructor(){this.fireTime=0}}class Ei{constructor(){this.duration=0,this.loop=!1,this.curveCount=0,this.eventCount=0,this.fps=0,this.curves=new se,this.segments=new se,this.points=new se,this.events=new se}}(t=>{t.CubismMotionCurve=Ii,t.CubismMotionCurveTarget=bi,t.CubismMotionData=Ei,t.CubismMotionEvent=Fi,t.CubismMotionPoint=Bi,t.CubismMotionSegment=wi,t.CubismMotionSegmentType=Pi})(vi||(vi={}));const Li="Meta",Vi="Curves",Ti="FadeInTime",Ri="FadeOutTime",Di="Segments",Ai="UserData";class Oi{constructor(t,e){this._json=ke.create(t,e)}release(){ke.delete(this._json)}getMotionDuration(){return this._json.getRoot().getValueByString(Li).getValueByString("Duration").toFloat()}isMotionLoop(){return this._json.getRoot().getValueByString(Li).getValueByString("Loop").toBoolean()}hasConsistency(){let t=!0;if(!this._json||!this._json.getRoot())return!1;const e=this._json.getRoot().getValueByString(Vi).getVector().getSize();let i=0,s=0;for(let r=0;r<e;++r)for(let t=0;t<this.getMotionCurveSegmentCount(r);){0==t&&(s+=1,t+=2);switch(this.getMotionCurveSegment(r,t)){case Pi.CubismMotionSegmentType_Linear:s+=1,t+=3;break;case Pi.CubismMotionSegmentType_Bezier:s+=3,t+=7;break;case Pi.CubismMotionSegmentType_Stepped:case Pi.CubismMotionSegmentType_InverseStepped:s+=1,t+=3;break;default:ve(0)}++i}return e!=this.getMotionCurveCount()&&(Be("The number of curves does not match the metadata."),t=!1),i!=this.getMotionTotalSegmentCount()&&(Be("The number of segment does not match the metadata."),t=!1),s!=this.getMotionTotalPointCount()&&(Be("The number of point does not match the metadata."),t=!1),t}getEvaluationOptionFlag(t){return 0==t&&this._json.getRoot().getValueByString(Li).getValueByString("AreBeziersRestricted").toBoolean()}getMotionCurveCount(){return this._json.getRoot().getValueByString(Li).getValueByString("CurveCount").toInt()}getMotionFps(){return this._json.getRoot().getValueByString(Li).getValueByString("Fps").toFloat()}getMotionTotalSegmentCount(){return this._json.getRoot().getValueByString(Li).getValueByString("TotalSegmentCount").toInt()}getMotionTotalPointCount(){return this._json.getRoot().getValueByString(Li).getValueByString("TotalPointCount").toInt()}isExistMotionFadeInTime(){return!this._json.getRoot().getValueByString(Li).getValueByString(Ti).isNull()}isExistMotionFadeOutTime(){return!this._json.getRoot().getValueByString(Li).getValueByString(Ri).isNull()}getMotionFadeInTime(){return this._json.getRoot().getValueByString(Li).getValueByString(Ti).toFloat()}getMotionFadeOutTime(){return this._json.getRoot().getValueByString(Li).getValueByString(Ri).toFloat()}getMotionCurveTarget(t){return this._json.getRoot().getValueByString(Vi).getValueByIndex(t).getValueByString("Target").getRawString()}getMotionCurveId(t){return ti.getIdManager().getId(this._json.getRoot().getValueByString(Vi).getValueByIndex(t).getValueByString("Id").getRawString())}isExistMotionCurveFadeInTime(t){return!this._json.getRoot().getValueByString(Vi).getValueByIndex(t).getValueByString(Ti).isNull()}isExistMotionCurveFadeOutTime(t){return!this._json.getRoot().getValueByString(Vi).getValueByIndex(t).getValueByString(Ri).isNull()}getMotionCurveFadeInTime(t){return this._json.getRoot().getValueByString(Vi).getValueByIndex(t).getValueByString(Ti).toFloat()}getMotionCurveFadeOutTime(t){return this._json.getRoot().getValueByString(Vi).getValueByIndex(t).getValueByString(Ri).toFloat()}getMotionCurveSegmentCount(t){return this._json.getRoot().getValueByString(Vi).getValueByIndex(t).getValueByString(Di).getVector().getSize()}getMotionCurveSegment(t,e){return this._json.getRoot().getValueByString(Vi).getValueByIndex(t).getValueByString(Di).getValueByIndex(e).toFloat()}getEventCount(){return this._json.getRoot().getValueByString(Li).getValueByString("UserDataCount").toInt()}getTotalEventValueSize(){return this._json.getRoot().getValueByString(Li).getValueByString("TotalUserDataSize").toInt()}getEventTime(t){return this._json.getRoot().getValueByString(Ai).getValueByIndex(t).getValueByString("Time").toFloat()}getEventValue(t){return new ge(this._json.getRoot().getValueByString(Ai).getValueByIndex(t).getValueByString("Value").getRawString())}}var ki,Ni=(t=>(t[t.EvaluationOptionFlag_AreBeziersRistricted=0]="EvaluationOptionFlag_AreBeziersRistricted",t))(Ni||{});(t=>{t.CubismMotionJson=Oi})(ki||(ki={}));const Ui="Opacity";function zi(t,e,i){const s=new Bi;return s.time=t.time+(e.time-t.time)*i,s.value=t.value+(e.value-t.value)*i,s}function ji(t,e){let i=(e-t[0].time)/(t[1].time-t[0].time);return i<0&&(i=0),t[0].value+(t[1].value-t[0].value)*i}function Gi(t,e){let i=(e-t[0].time)/(t[3].time-t[0].time);i<0&&(i=0);const s=zi(t[0],t[1],i),r=zi(t[1],t[2],i),a=zi(t[2],t[3],i),n=zi(s,r,i),o=zi(r,a,i);return zi(n,o,i).value}function Xi(t,e){const i=e,s=t[0].time,r=t[3].time,a=t[1].time,n=t[2].time,o=r-3*n+3*a-s,l=3*n-6*a+3*s,u=3*a-3*s,h=s-i,d=ni.cardanoAlgorithmForBezier(o,l,u,h),g=zi(t[0],t[1],d),c=zi(t[1],t[2],d),p=zi(t[2],t[3],d),m=zi(g,c,d),_=zi(c,p,d);return zi(m,_,d).value}function Hi(t,e){return t[0].value}function Yi(t,e){return t[1].value}function qi(t,e,i,s,r){const a=t.curves.at(e);let n=-1;const o=a.baseSegmentIndex+a.segmentCount;let l=0;for(let h=a.baseSegmentIndex;h<o;++h)if(l=t.segments.at(h).basePointIndex+(t.segments.at(h).segmentType==Pi.CubismMotionSegmentType_Bezier?3:1),t.points.at(l).time>i){n=h;break}if(-1==n)return s&&i<r?function(t,e,i,s,r,a){const n=[new Bi,new Bi];{const e=t.points.at(s);n[0].time=e.time,n[0].value=e.value}{const e=t.points.at(i);n[1].time=a,n[1].value=e.value}switch(t.segments.at(e).segmentType){case Pi.CubismMotionSegmentType_Linear:case Pi.CubismMotionSegmentType_Bezier:default:return ji(n,r);case Pi.CubismMotionSegmentType_Stepped:return Hi(n);case Pi.CubismMotionSegmentType_InverseStepped:return Yi(n)}}(t,o-1,t.segments.at(a.baseSegmentIndex).basePointIndex,l,i,r):t.points.at(l).value;const u=t.segments.at(n);return u.evaluate(t.points.get(u.basePointIndex),i)}class Wi extends ui{constructor(){super(),this._motionBehavior=1,this._sourceFrameRate=30,this._loopDurationSeconds=-1,this._isLoop=!1,this._isLoopFadeIn=!0,this._lastWeight=0,this._motionData=null,this._modelCurveIdEyeBlink=null,this._modelCurveIdLipSync=null,this._modelCurveIdOpacity=null,this._eyeBlinkParameterIds=null,this._lipSyncParameterIds=null,this._modelOpacity=1,this._debugMode=!1}static create(t,e,i,s,r=!1){const a=new Wi;return a.parse(t,e,r),a._motionData?(a._sourceFrameRate=a._motionData.fps,a._loopDurationSeconds=a._motionData.duration,a._onFinishedMotion=i,a._onBeganMotion=s,a):(Qe(a),null)}doUpdateParameters(t,e,i,s){null==this._modelCurveIdEyeBlink&&(this._modelCurveIdEyeBlink=ti.getIdManager().getId("EyeBlink")),null==this._modelCurveIdLipSync&&(this._modelCurveIdLipSync=ti.getIdManager().getId("LipSync")),null==this._modelCurveIdOpacity&&(this._modelCurveIdOpacity=ti.getIdManager().getId(Ui)),1===this._motionBehavior&&this._previousLoopState!==this._isLoop&&(this.adjustEndTime(s),this._previousLoopState=this._isLoop);let r=e-s.getStartTime();r<0&&(r=0);let a=Number.MAX_VALUE,n=Number.MAX_VALUE;const o=64;let l=0,u=0;this._eyeBlinkParameterIds.getSize()>o&&be("too many eye blink targets : {0}",this._eyeBlinkParameterIds.getSize()),this._lipSyncParameterIds.getSize()>o&&be("too many lip sync targets : {0}",this._lipSyncParameterIds.getSize());const h=this._fadeInSeconds<=0?1:ni.getEasingSine((e-s.getFadeInStartTime())/this._fadeInSeconds),d=this._fadeOutSeconds<=0||s.getEndTime()<0?1:ni.getEasingSine((s.getEndTime()-e)/this._fadeOutSeconds);let g,c,p,m=r,_=this._motionData.duration;const f=1===this._motionBehavior&&this._isLoop;if(this._isLoop)for(1===this._motionBehavior&&(_+=1/this._motionData.fps);m>_;)m-=_;const y=this._motionData.curves;for(c=0;c<this._motionData.curveCount&&y.at(c).type==bi.CubismMotionCurveTarget_Model;++c)g=qi(this._motionData,c,m,f,_),y.at(c).id==this._modelCurveIdEyeBlink?n=g:y.at(c).id==this._modelCurveIdLipSync?a=g:y.at(c).id==this._modelCurveIdOpacity&&(this._modelOpacity=g,t.setModelOapcity(this.getModelOpacityValue()));for(;c<this._motionData.curveCount&&y.at(c).type==bi.CubismMotionCurveTarget_Parameter;++c){if(p=t.getParameterIndex(y.at(c).id),-1==p)continue;const r=t.getParameterValueByIndex(p);if(g=qi(this._motionData,c,m,f,_),n!=Number.MAX_VALUE)for(let t=0;t<this._eyeBlinkParameterIds.getSize()&&t<o;++t)if(this._eyeBlinkParameterIds.at(t)==y.at(c).id){g*=n,u|=1<<t;break}if(a!=Number.MAX_VALUE)for(let t=0;t<this._lipSyncParameterIds.getSize()&&t<o;++t)if(this._lipSyncParameterIds.at(t)==y.at(c).id){g+=a,l|=1<<t;break}let x;if(t.isRepeat(p)&&(g=t.getParameterRepeatValue(p,g)),y.at(c).fadeInTime<0&&y.at(c).fadeOutTime<0)x=r+(g-r)*i;else{let t,i;t=y.at(c).fadeInTime<0?h:0==y.at(c).fadeInTime?1:ni.getEasingSine((e-s.getFadeInStartTime())/y.at(c).fadeInTime),i=y.at(c).fadeOutTime<0?d:0==y.at(c).fadeOutTime||s.getEndTime()<0?1:ni.getEasingSine((s.getEndTime()-e)/y.at(c).fadeOutTime);x=r+(g-r)*(this._weight*t*i)}t.setParameterValueByIndex(p,x,1)}if(n!=Number.MAX_VALUE)for(let x=0;x<this._eyeBlinkParameterIds.getSize()&&x<o;++x){const e=t.getParameterValueById(this._eyeBlinkParameterIds.at(x));if(u>>x&1)continue;const s=e+(n-e)*i;t.setParameterValueById(this._eyeBlinkParameterIds.at(x),s)}if(a!=Number.MAX_VALUE)for(let x=0;x<this._lipSyncParameterIds.getSize()&&x<o;++x){const e=t.getParameterValueById(this._lipSyncParameterIds.at(x));if(l>>x&1)continue;const s=e+(a-e)*i;t.setParameterValueById(this._lipSyncParameterIds.at(x),s)}for(;c<this._motionData.curveCount&&y.at(c).type==bi.CubismMotionCurveTarget_PartOpacity;++c)p=t.getParameterIndex(y.at(c).id),-1!=p&&(g=qi(this._motionData,c,m,f,_),t.setParameterValueByIndex(p,g));r>=_&&(this._isLoop?this.updateForNextLoop(s,e,m):(this._onFinishedMotion&&this._onFinishedMotion(this),s.setIsFinished(!0))),this._lastWeight=i}setIsLoop(t){Be("setIsLoop() is a deprecated function. Please use setLoop()."),this._isLoop=t}isLoop(){return Be("isLoop() is a deprecated function. Please use getLoop()."),this._isLoop}setIsLoopFadeIn(t){Be("setIsLoopFadeIn() is a deprecated function. Please use setLoopFadeIn()."),this._isLoopFadeIn=t}isLoopFadeIn(){return Be("isLoopFadeIn() is a deprecated function. Please use getLoopFadeIn()."),this._isLoopFadeIn}setMotionBehavior(t){this._motionBehavior=t}getMotionBehavior(){return this._motionBehavior}getDuration(){return this._isLoop?-1:this._loopDurationSeconds}getLoopDuration(){return this._loopDurationSeconds}setParameterFadeInTime(t,e){const i=this._motionData.curves;for(let s=0;s<this._motionData.curveCount;++s)if(t==i.at(s).id)return void(i.at(s).fadeInTime=e)}setParameterFadeOutTime(t,e){const i=this._motionData.curves;for(let s=0;s<this._motionData.curveCount;++s)if(t==i.at(s).id)return void(i.at(s).fadeOutTime=e)}getParameterFadeInTime(t){const e=this._motionData.curves;for(let i=0;i<this._motionData.curveCount;++i)if(t==e.at(i).id)return e.at(i).fadeInTime;return-1}getParameterFadeOutTime(t){const e=this._motionData.curves;for(let i=0;i<this._motionData.curveCount;++i)if(t==e.at(i).id)return e.at(i).fadeOutTime;return-1}setEffectIds(t,e){this._eyeBlinkParameterIds=t,this._lipSyncParameterIds=e}release(){this._motionData=void 0,this._motionData=null}updateForNextLoop(t,e,i){switch(this._motionBehavior){case 1:default:t.setStartTime(e-i),this._isLoopFadeIn&&t.setFadeInStartTime(e-i),null!=this._onFinishedMotion&&this._onFinishedMotion(this);break;case 0:t.setStartTime(e),this._isLoopFadeIn&&t.setFadeInStartTime(e)}}parse(t,e,i=!1){let s=new Oi(t,e);if(!s)return s.release(),void(s=void 0);if(i){if(!s.hasConsistency())return s.release(),void we("Inconsistent motion3.json.")}this._motionData=new Ei,this._motionData.duration=s.getMotionDuration(),this._motionData.loop=s.isMotionLoop(),this._motionData.curveCount=s.getMotionCurveCount(),this._motionData.fps=s.getMotionFps(),this._motionData.eventCount=s.getEventCount();const r=s.getEvaluationOptionFlag(Ni.EvaluationOptionFlag_AreBeziersRistricted);s.isExistMotionFadeInTime()?this._fadeInSeconds=s.getMotionFadeInTime()<0?1:s.getMotionFadeInTime():this._fadeInSeconds=1,s.isExistMotionFadeOutTime()?this._fadeOutSeconds=s.getMotionFadeOutTime()<0?1:s.getMotionFadeOutTime():this._fadeOutSeconds=1,this._motionData.curves.updateSize(this._motionData.curveCount,Ii,!0),this._motionData.segments.updateSize(s.getMotionTotalSegmentCount(),wi,!0),this._motionData.points.updateSize(s.getMotionTotalPointCount(),Bi,!0),this._motionData.events.updateSize(this._motionData.eventCount,Fi,!0);let a=0,n=0;for(let o=0;o<this._motionData.curveCount;++o){"Model"==s.getMotionCurveTarget(o)?this._motionData.curves.at(o).type=bi.CubismMotionCurveTarget_Model:"Parameter"==s.getMotionCurveTarget(o)?this._motionData.curves.at(o).type=bi.CubismMotionCurveTarget_Parameter:"PartOpacity"==s.getMotionCurveTarget(o)?this._motionData.curves.at(o).type=bi.CubismMotionCurveTarget_PartOpacity:Be('Warning : Unable to get segment type from Curve! The number of "CurveCount" may be incorrect!'),this._motionData.curves.at(o).id=s.getMotionCurveId(o),this._motionData.curves.at(o).baseSegmentIndex=n,this._motionData.curves.at(o).fadeInTime=s.isExistMotionCurveFadeInTime(o)?s.getMotionCurveFadeInTime(o):-1,this._motionData.curves.at(o).fadeOutTime=s.isExistMotionCurveFadeOutTime(o)?s.getMotionCurveFadeOutTime(o):-1;for(let t=0;t<s.getMotionCurveSegmentCount(o);){0==t?(this._motionData.segments.at(n).basePointIndex=a,this._motionData.points.at(a).time=s.getMotionCurveSegment(o,t),this._motionData.points.at(a).value=s.getMotionCurveSegment(o,t+1),a+=1,t+=2):this._motionData.segments.at(n).basePointIndex=a-1;switch(s.getMotionCurveSegment(o,t)){case Pi.CubismMotionSegmentType_Linear:this._motionData.segments.at(n).segmentType=Pi.CubismMotionSegmentType_Linear,this._motionData.segments.at(n).evaluate=ji,this._motionData.points.at(a).time=s.getMotionCurveSegment(o,t+1),this._motionData.points.at(a).value=s.getMotionCurveSegment(o,t+2),a+=1,t+=3;break;case Pi.CubismMotionSegmentType_Bezier:this._motionData.segments.at(n).segmentType=Pi.CubismMotionSegmentType_Bezier,this._motionData.segments.at(n).evaluate=r?Gi:Xi,this._motionData.points.at(a).time=s.getMotionCurveSegment(o,t+1),this._motionData.points.at(a).value=s.getMotionCurveSegment(o,t+2),this._motionData.points.at(a+1).time=s.getMotionCurveSegment(o,t+3),this._motionData.points.at(a+1).value=s.getMotionCurveSegment(o,t+4),this._motionData.points.at(a+2).time=s.getMotionCurveSegment(o,t+5),this._motionData.points.at(a+2).value=s.getMotionCurveSegment(o,t+6),a+=3,t+=7;break;case Pi.CubismMotionSegmentType_Stepped:this._motionData.segments.at(n).segmentType=Pi.CubismMotionSegmentType_Stepped,this._motionData.segments.at(n).evaluate=Hi,this._motionData.points.at(a).time=s.getMotionCurveSegment(o,t+1),this._motionData.points.at(a).value=s.getMotionCurveSegment(o,t+2),a+=1,t+=3;break;case Pi.CubismMotionSegmentType_InverseStepped:this._motionData.segments.at(n).segmentType=Pi.CubismMotionSegmentType_InverseStepped,this._motionData.segments.at(n).evaluate=Yi,this._motionData.points.at(a).time=s.getMotionCurveSegment(o,t+1),this._motionData.points.at(a).value=s.getMotionCurveSegment(o,t+2),a+=1,t+=3;break;default:ve(0)}++this._motionData.curves.at(o).segmentCount,++n}}for(let o=0;o<s.getEventCount();++o)this._motionData.events.at(o).fireTime=s.getEventTime(o),this._motionData.events.at(o).value=s.getEventValue(o);s.release(),s=void 0,s=null}getFiredEvent(t,e){this._firedEventValues.updateSize(0);for(let i=0;i<this._motionData.eventCount;++i)this._motionData.events.at(i).fireTime>t&&this._motionData.events.at(i).fireTime<=e&&this._firedEventValues.pushBack(new ge(this._motionData.events.at(i).value.s));return this._firedEventValues}isExistModelOpacity(){for(let t=0;t<this._motionData.curveCount;t++){const e=this._motionData.curves.at(t);if(e.type==bi.CubismMotionCurveTarget_Model&&0==e.id.getString().s.localeCompare(Ui))return!0}return!1}getModelOpacityIndex(){if(this.isExistModelOpacity())for(let t=0;t<this._motionData.curveCount;t++){const e=this._motionData.curves.at(t);if(e.type==bi.CubismMotionCurveTarget_Model&&0==e.id.getString().s.localeCompare(Ui))return t}return-1}getModelOpacityId(t){if(-1!=t){const e=this._motionData.curves.at(t);if(e.type==bi.CubismMotionCurveTarget_Model&&0==e.id.getString().s.localeCompare(Ui))return ti.getIdManager().getId(e.id.getString().s)}return null}getModelOpacityValue(){return this._modelOpacity}setDebugMode(t){this._debugMode=t}}var Ji;function $i(t,e,i){const s=t.startMotion(i,!1),r=t.getCubismMotionQueueEntry(s);if(!r)return!1;r.setStartTime(0),r.setFadeInStartTime(0);const a=i.getDuration(),n=r.getStartTime()+a;return i.doUpdateParameters(e.coreModel,n,1,r),r.setIsFinished(!0),!0}(t=>{t.CubismMotion=Wi})(Ji||(Ji={}));class Zi extends G{constructor(t){var e;super(t),d(this,"definitions"),d(this,"groups",{idle:"Idle"}),d(this,"motionDataType","arraybuffer"),d(this,"queueManager",new xi),d(this,"expressionManager"),d(this,"eyeBlinkIds"),d(this,"lipSyncIds",["ParamMouthOpenY"]),this.definitions=null!=(e=t.settings.motions)?e:{},this.eyeBlinkIds=t.settings.getEyeBlinkParameters()||[];const i=t.settings.getLipSyncParameters();(null==i?void 0:i.length)&&(this.lipSyncIds=i),this.init(t.options)}init(t){super.init(t),this.settings.expressions&&(this.expressionManager=new Si(this.settings,t)),this.queueManager.setEventCallback((t,e)=>{const i="string"==typeof e?e:"number"==typeof e?String(e):e&&"object"==typeof e?e.s:"undefined";this.emit("motion:"+i)})}isFinished(){return this.queueManager.isFinished()}_startMotion(t,e,i,s){if(t.setFinishedMotionHandler(e),t.setLoop(null!=s?s:t._motionData.loop),i&&i.length>0){const e=t._motionData.curves,s=function(t){if(Ki(t))return new se;return[]}(e),r=Qi(e);for(let t=0;t<r;t++){const r=ts(e,t);if(!r)continue;const a=es(r);a&&i.includes(a)||is(s,r)}t._motionData.curves=s,t._motionData.curveCount=Qi(s)}return this.queueManager.stopAllMotions(),this.queueManager.startMotion(t,!1)}_stopAllMotions(){this.queueManager.stopAllMotions()}createMotion(t,e,i){const s=!!this.parent.options.checkMotionConsistency,r=Wi.create(t,t.byteLength,void 0,void 0,s),a=new Oi(t,t.byteLength);r.setLoop(a.isMotionLoop());const n=(e===this.groups.idle?c.idleMotionFadingDuration:c.motionFadingDuration)/1e3;return void 0===a.getMotionFadeInTime()&&r.setFadeInTime(i.FadeInTime>0?i.FadeInTime:n),void 0===a.getMotionFadeOutTime()&&r.setFadeOutTime(i.FadeOutTime>0?i.FadeOutTime:n),r.setEffectIds(this.createIdVector(this.eyeBlinkIds),this.createIdVector(this.lipSyncIds)),r}getMotionFile(t){return t.File}getMotionName(t){return t.File}getSoundFile(t){return t.Sound}updateParameters(t,e){return this.queueManager.doUpdateMotion(t,e)}destroy(){super.destroy(),this.queueManager.release(),this.queueManager=void 0}motionLastFrame(t,e){return g(this,arguments,function*(t,e,{expression:i}={}){const s=yield this.getMotionAndApplyExpression(t,e,i);return!!s&&(this.playing=!0,$i(this.queueManager,this.parent,s),this.playing=!1,!0)})}createIdVector(t){const e=new se,i=ti.getIdManager();for(const s of t)e.pushBack(i.getId(s));return e}}function Ki(t){return"function"==typeof t.pushBack}function Qi(t){return Ki(t)?t.getSize():t.length}function ts(t,e){return Ki(t)?t.at(e):t[e]}function es(t){if(!t||"object"!=typeof t)return;const e=t.id;return"string"==typeof e?e:e&&"function"==typeof e.getString?e.getString().s:void 0}function is(t,e){Ki(t)?t.pushBack(e):t.push(e)}class ss extends Yt{constructor(t){super(t),d(this,"queueManager",new xi),this.init()}init(){this.queueManager.setEventCallback((t,e)=>{const i="string"==typeof e?e:"number"==typeof e?String(e):e&&"object"==typeof e?e.s:"undefined";this.emit("motion:"+i)})}isFinished(){return this.queueManager.isFinished()}_startMotion(t,e,i,s){if(t.setFinishedMotionHandler(e),t.setLoop(null!=s?s:t._motionData.loop),i&&i.length>0){const e=t._motionData.curves,s=function(t){if(rs(t))return new se;return[]}(e),r=as(e);for(let t=0;t<r;t++){const r=ns(e,t);if(!r)continue;const a=os(r);a&&i.includes(a)||ls(s,r)}t._motionData.curves=s,t._motionData.curveCount=as(s)}return this.queueManager.stopAllMotions(),this.queueManager.startMotion(t,!1)}_stopAllMotions(){this.queueManager.stopAllMotions()}updateParameters(t,e){return this.queueManager.doUpdateMotion(t,e)}getMotionName(t){return t.File}destroy(){super.destroy(),this.queueManager.release(),this.queueManager=void 0}playMotionLastFrame(t,e){return g(this,null,function*(){var i;if(!this.state.reserve(t,e,E.FORCE))return!1;const s=null==(i=this.manager.definitions[t])?void 0:i[e];if(!s)return!1;const r=yield this.manager.loadMotion(t,e);return!!this.state.start(r,t,e,E.FORCE)&&(p.log(this.tag,"Start motion:",this.getMotionName(s)),this.emit("motionStart",t,e,void 0),this.playing=!0,this.queueManager.stopAllMotions(),$i(this.queueManager,this.parent,r)?(this.playing=!1,!0):(this.playing=!1,!1))})}}function rs(t){return"function"==typeof t.pushBack}function as(t){return rs(t)?t.getSize():t.length}function ns(t,e){return rs(t)?t.at(e):t[e]}function os(t){if(!t||"object"!=typeof t)return;const e=t.id;return"string"==typeof e?e:e&&"function"==typeof e.getString?e.getString().s:void 0}function ls(t,e){rs(t)?t.pushBack(e):t.push(e)}const us=Object.freeze({HitAreaPrefix:"HitArea",HitAreaHead:"Head",HitAreaBody:"Body",PartsIdCore:"Parts01Core",PartsArmPrefix:"Parts01Arm_",PartsArmLPrefix:"Parts01ArmL_",PartsArmRPrefix:"Parts01ArmR_",ParamAngleX:"ParamAngleX",ParamAngleY:"ParamAngleY",ParamAngleZ:"ParamAngleZ",ParamEyeLOpen:"ParamEyeLOpen",ParamEyeLSmile:"ParamEyeLSmile",ParamEyeROpen:"ParamEyeROpen",ParamEyeRSmile:"ParamEyeRSmile",ParamEyeBallX:"ParamEyeBallX",ParamEyeBallY:"ParamEyeBallY",ParamEyeBallForm:"ParamEyeBallForm",ParamBrowLY:"ParamBrowLY",ParamBrowRY:"ParamBrowRY",ParamBrowLX:"ParamBrowLX",ParamBrowRX:"ParamBrowRX",ParamBrowLAngle:"ParamBrowLAngle",ParamBrowRAngle:"ParamBrowRAngle",ParamBrowLForm:"ParamBrowLForm",ParamBrowRForm:"ParamBrowRForm",ParamMouthForm:"ParamMouthForm",ParamMouthOpenY:"ParamMouthOpenY",ParamCheek:"ParamCheek",ParamBodyAngleX:"ParamBodyAngleX",ParamBodyAngleY:"ParamBodyAngleY",ParamBodyAngleZ:"ParamBodyAngleZ",ParamBreath:"ParamBreath",ParamArmLA:"ParamArmLA",ParamArmRA:"ParamArmRA",ParamArmLB:"ParamArmLB",ParamArmRB:"ParamArmRB",ParamHandL:"ParamHandL",ParamHandR:"ParamHandR",ParamHairFront:"ParamHairFront",ParamHairSide:"ParamHairSide",ParamHairBack:"ParamHairBack",ParamHairFluffy:"ParamHairFluffy",ParamShoulderY:"ParamShoulderY",ParamBustX:"ParamBustX",ParamBustY:"ParamBustY",ParamBaseX:"ParamBaseX",ParamBaseY:"ParamBaseY",ParamNONE:"NONE:"});var hs,ds;(t=>{t.HitAreaBody=us.HitAreaBody,t.HitAreaHead=us.HitAreaHead,t.HitAreaPrefix=us.HitAreaPrefix,t.ParamAngleX=us.ParamAngleX,t.ParamAngleY=us.ParamAngleY,t.ParamAngleZ=us.ParamAngleZ,t.ParamArmLA=us.ParamArmLA,t.ParamArmLB=us.ParamArmLB,t.ParamArmRA=us.ParamArmRA,t.ParamArmRB=us.ParamArmRB,t.ParamBaseX=us.ParamBaseX,t.ParamBaseY=us.ParamBaseY,t.ParamBodyAngleX=us.ParamBodyAngleX,t.ParamBodyAngleY=us.ParamBodyAngleY,t.ParamBodyAngleZ=us.ParamBodyAngleZ,t.ParamBreath=us.ParamBreath,t.ParamBrowLAngle=us.ParamBrowLAngle,t.ParamBrowLForm=us.ParamBrowLForm,t.ParamBrowLX=us.ParamBrowLX,t.ParamBrowLY=us.ParamBrowLY,t.ParamBrowRAngle=us.ParamBrowRAngle,t.ParamBrowRForm=us.ParamBrowRForm,t.ParamBrowRX=us.ParamBrowRX,t.ParamBrowRY=us.ParamBrowRY,t.ParamBustX=us.ParamBustX,t.ParamBustY=us.ParamBustY,t.ParamCheek=us.ParamCheek,t.ParamEyeBallForm=us.ParamEyeBallForm,t.ParamEyeBallX=us.ParamEyeBallX,t.ParamEyeBallY=us.ParamEyeBallY,t.ParamEyeLOpen=us.ParamEyeLOpen,t.ParamEyeLSmile=us.ParamEyeLSmile,t.ParamEyeROpen=us.ParamEyeROpen,t.ParamEyeRSmile=us.ParamEyeRSmile,t.ParamHairBack=us.ParamHairBack,t.ParamHairFluffy=us.ParamHairFluffy,t.ParamHairFront=us.ParamHairFront,t.ParamHairSide=us.ParamHairSide,t.ParamHandL=us.ParamHandL,t.ParamHandR=us.ParamHandR,t.ParamMouthForm=us.ParamMouthForm,t.ParamMouthOpenY=us.ParamMouthOpenY,t.ParamNONE=us.ParamNONE,t.ParamShoulderY=us.ParamShoulderY,t.PartsArmLPrefix=us.PartsArmLPrefix,t.PartsArmPrefix=us.PartsArmPrefix,t.PartsArmRPrefix=us.PartsArmRPrefix,t.PartsIdCore=us.PartsIdCore})(hs||(hs={}));class gs{static create(){return new gs}static delete(t){}setParameters(t){this._breathParameters=t}getParameters(){return this._breathParameters}updateParameters(t,e){this._currentTime+=e;const i=2*this._currentTime*Math.PI;for(let s=0;s<this._breathParameters.getSize();++s){const e=this._breathParameters.at(s);t.addParameterValueById(e.parameterId,e.offset+e.peak*Math.sin(i/e.cycle),e.weight)}}constructor(){this._currentTime=0}}class cs{constructor(t,e,i,s,r){this.parameterId=null==t?null:t,this.offset=null==e?0:e,this.peak=null==i?0:i,this.cycle=null==s?0:s,this.weight=null==r?0:r}}(t=>{t.BreathParameterData=cs,t.CubismBreath=gs})(ds||(ds={}));const ps=class t{static create(e=null){return new t(e)}static delete(t){}setBlinkingInterval(t){this._blinkingIntervalSeconds=t}setBlinkingSetting(t,e,i){this._closingSeconds=t,this._closedSeconds=e,this._openingSeconds=i}setParameterIds(t){this._parameterIds=t}getParameterIds(){return this._parameterIds}updateParameters(e,i){let s;this._userTimeSeconds+=i;let r=0;switch(this._blinkingState){case 2:r=(this._userTimeSeconds-this._stateStartTimeSeconds)/this._closingSeconds,r>=1&&(r=1,this._blinkingState=3,this._stateStartTimeSeconds=this._userTimeSeconds),s=1-r;break;case 3:r=(this._userTimeSeconds-this._stateStartTimeSeconds)/this._closedSeconds,r>=1&&(this._blinkingState=4,this._stateStartTimeSeconds=this._userTimeSeconds),s=0;break;case 4:r=(this._userTimeSeconds-this._stateStartTimeSeconds)/this._openingSeconds,r>=1&&(r=1,this._blinkingState=1,this._nextBlinkingTime=this.determinNextBlinkingTiming()),s=r;break;case 1:this._nextBlinkingTime<this._userTimeSeconds&&(this._blinkingState=2,this._stateStartTimeSeconds=this._userTimeSeconds),s=1;break;default:this._blinkingState=1,this._nextBlinkingTime=this.determinNextBlinkingTiming(),s=1}t.CloseIfZero||(s=-s);for(let t=0;t<this._parameterIds.getSize();++t)e.setParameterValueById(this._parameterIds.at(t),s)}constructor(t){if(this._blinkingState=0,this._nextBlinkingTime=0,this._stateStartTimeSeconds=0,this._blinkingIntervalSeconds=4,this._closingSeconds=.1,this._closedSeconds=.05,this._openingSeconds=.15,this._userTimeSeconds=0,this._parameterIds=new se,null!=t)for(let e=0;e<t.getEyeBlinkParameterCount();++e)this._parameterIds.pushBack(t.getEyeBlinkParameterId(e))}determinNextBlinkingTiming(){const t=Math.random();return this._userTimeSeconds+t*(2*this._blinkingIntervalSeconds-1)}};ps.CloseIfZero=!0;let ms=ps;var _s,fs=(t=>(t[t.EyeState_First=0]="EyeState_First",t[t.EyeState_Interval=1]="EyeState_Interval",t[t.EyeState_Closing=2]="EyeState_Closing",t[t.EyeState_Closed=3]="EyeState_Closed",t[t.EyeState_Opening=4]="EyeState_Opening",t))(fs||{});(t=>{t.CubismEyeBlink=ms,t.EyeState=fs})(_s||(_s={}));class ys{constructor(t){this._renderTextureCount=0,this._clippingMaskBufferSize=256,this._clippingContextListForMask=new se,this._clippingContextListForDraw=new se,this._channelColors=new se,this._tmpBoundsOnModel=new _e,this._tmpMatrix=new me,this._tmpMatrixForMask=new me,this._tmpMatrixForDraw=new me,this._clippingContexttConstructor=t;let e=new Me;e.r=1,e.g=0,e.b=0,e.a=0,this._channelColors.pushBack(e),e=new Me,e.r=0,e.g=1,e.b=0,e.a=0,this._channelColors.pushBack(e),e=new Me,e.r=0,e.g=0,e.b=1,e.a=0,this._channelColors.pushBack(e),e=new Me,e.r=0,e.g=0,e.b=0,e.a=1,this._channelColors.pushBack(e)}release(){for(let t=0;t<this._clippingContextListForMask.getSize();t++)this._clippingContextListForMask.at(t)&&(this._clippingContextListForMask.at(t).release(),this._clippingContextListForMask.set(t,void 0)),this._clippingContextListForMask.set(t,null);this._clippingContextListForMask=null;for(let t=0;t<this._clippingContextListForDraw.getSize();t++)this._clippingContextListForDraw.set(t,null);this._clippingContextListForDraw=null;for(let t=0;t<this._channelColors.getSize();t++)this._channelColors.set(t,null);this._channelColors=null,null!=this._clearedFrameBufferFlags&&this._clearedFrameBufferFlags.clear(),this._clearedFrameBufferFlags=null}initialize(t,e){e%1!=0&&(Be("The number of render textures must be specified as an integer. The decimal point is rounded down and corrected to an integer."),e=~~e),e<1&&Be("The number of render textures must be an integer greater than or equal to 1. Set the number of render textures to 1."),this._renderTextureCount=e<1?1:e,this._clearedFrameBufferFlags=new se(this._renderTextureCount);for(let i=0;i<t.getDrawableCount();i++){if(t.getDrawableMaskCounts()[i]<=0){this._clippingContextListForDraw.pushBack(null);continue}let e=this.findSameClip(t.getDrawableMasks()[i],t.getDrawableMaskCounts()[i]);null==e&&(e=new this._clippingContexttConstructor(this,t.getDrawableMasks()[i],t.getDrawableMaskCounts()[i]),this._clippingContextListForMask.pushBack(e)),e.addClippedDrawable(i),this._clippingContextListForDraw.pushBack(e)}}findSameClip(t,e){for(let i=0;i<this._clippingContextListForMask.getSize();i++){const s=this._clippingContextListForMask.at(i),r=s._clippingIdCount;if(r!=e)continue;let a=0;for(let e=0;e<r;e++){const i=s._clippingIdList[e];for(let e=0;e<r;e++)if(t[e]==i){a++;break}}if(a==r)return s}return null}setupMatrixForHighPrecision(t,e){let i=0;for(let s=0;s<this._clippingContextListForMask.getSize();s++){const e=this._clippingContextListForMask.at(s);this.calcClippedDrawTotalBounds(t,e),e._isUsing&&i++}if(i>0){if(this.setupLayoutBounds(0),this._clearedFrameBufferFlags.getSize()!=this._renderTextureCount){this._clearedFrameBufferFlags.clear();for(let t=0;t<this._renderTextureCount;t++)this._clearedFrameBufferFlags.pushBack(!1)}else for(let t=0;t<this._renderTextureCount;t++)this._clearedFrameBufferFlags.set(t,!1);for(let i=0;i<this._clippingContextListForMask.getSize();i++){const s=this._clippingContextListForMask.at(i),r=s._allClippedDrawRect,a=s._layoutBounds,n=.05;let o=0,l=0;const u=t.getPixelsPerUnit(),h=s.getClippingManager().getClippingMaskBufferSize(),d=a.width*h,g=a.height*h;this._tmpBoundsOnModel.setRect(r),this._tmpBoundsOnModel.width*u>d?(this._tmpBoundsOnModel.expand(r.width*n,0),o=a.width/this._tmpBoundsOnModel.width):o=u/d,this._tmpBoundsOnModel.height*u>g?(this._tmpBoundsOnModel.expand(0,r.height*n),l=a.height/this._tmpBoundsOnModel.height):l=u/g,this.createMatrixForMask(e,a,o,l),s._matrixForMask.setMatrix(this._tmpMatrixForMask.getArray()),s._matrixForDraw.setMatrix(this._tmpMatrixForDraw.getArray())}}}createMatrixForMask(t,e,i,s){this._tmpMatrix.loadIdentity(),this._tmpMatrix.translateRelative(-1,-1),this._tmpMatrix.scaleRelative(2,2),this._tmpMatrix.translateRelative(e.x,e.y),this._tmpMatrix.scaleRelative(i,s),this._tmpMatrix.translateRelative(-this._tmpBoundsOnModel.x,-this._tmpBoundsOnModel.y),this._tmpMatrixForMask.setMatrix(this._tmpMatrix.getArray()),this._tmpMatrix.loadIdentity(),this._tmpMatrix.translateRelative(e.x,e.y*(t?-1:1)),this._tmpMatrix.scaleRelative(i,s*(t?-1:1)),this._tmpMatrix.translateRelative(-this._tmpBoundsOnModel.x,-this._tmpBoundsOnModel.y),this._tmpMatrixForDraw.setMatrix(this._tmpMatrix.getArray())}setupLayoutBounds(t){const e=this._renderTextureCount<=1?36:32*this._renderTextureCount;if(t<=0||t>e){t>e&&we("not supported mask count : {0}\n[Details] render texture count : {1}, mask count : {2}",t-e,this._renderTextureCount,t);for(let t=0;t<this._clippingContextListForMask.getSize();t++){const e=this._clippingContextListForMask.at(t);e._layoutChannelIndex=0,e._layoutBounds.x=0,e._layoutBounds.y=0,e._layoutBounds.width=1,e._layoutBounds.height=1,e._bufferIndex=0}return}const i=this._renderTextureCount<=1?9:8;let s=t/this._renderTextureCount;const r=t%this._renderTextureCount;s=Math.ceil(s);let a=s/4;const n=s%4;a=~~a;let o=0;for(let l=0;l<this._renderTextureCount;l++)for(let s=0;s<4;s++){let u=a+(s<n?1:0);if(s==n+(a<1?-1:0)&&r>0&&(u-=l<r?0:1),0==u);else if(1==u){const t=this._clippingContextListForMask.at(o++);t._layoutChannelIndex=s,t._layoutBounds.x=0,t._layoutBounds.y=0,t._layoutBounds.width=1,t._layoutBounds.height=1,t._bufferIndex=l}else if(2==u)for(let t=0;t<u;t++){let e=t%2;e=~~e;const i=this._clippingContextListForMask.at(o++);i._layoutChannelIndex=s,i._layoutBounds.x=.5*e,i._layoutBounds.y=0,i._layoutBounds.width=.5,i._layoutBounds.height=1,i._bufferIndex=l}else if(u<=4)for(let t=0;t<u;t++){let e=t%2,i=t/2;e=~~e,i=~~i;const r=this._clippingContextListForMask.at(o++);r._layoutChannelIndex=s,r._layoutBounds.x=.5*e,r._layoutBounds.y=.5*i,r._layoutBounds.width=.5,r._layoutBounds.height=.5,r._bufferIndex=l}else if(u<=i)for(let t=0;t<u;t++){let e=t%3,i=t/3;e=~~e,i=~~i;const r=this._clippingContextListForMask.at(o++);r._layoutChannelIndex=s,r._layoutBounds.x=e/3,r._layoutBounds.y=i/3,r._layoutBounds.width=1/3,r._layoutBounds.height=1/3,r._bufferIndex=l}else{we("not supported mask count : {0}\n[Details] render texture count : {1}, mask count : {2}",t-e,this._renderTextureCount,t);for(let t=0;t<u;t++){const t=this._clippingContextListForMask.at(o++);t._layoutChannelIndex=0,t._layoutBounds.x=0,t._layoutBounds.y=0,t._layoutBounds.width=1,t._layoutBounds.height=1,t._bufferIndex=0}}}}calcClippedDrawTotalBounds(t,e){let i=Number.MAX_VALUE,s=Number.MAX_VALUE,r=Number.MIN_VALUE,a=Number.MIN_VALUE;const n=e._clippedDrawableIndexList.length;for(let o=0;o<n;o++){const n=e._clippedDrawableIndexList[o],l=t.getDrawableVertexCount(n),u=t.getDrawableVertices(n);let h=Number.MAX_VALUE,d=Number.MAX_VALUE,g=-Number.MAX_VALUE,c=-Number.MAX_VALUE;const p=l*Ke.vertexStep;for(let t=Ke.vertexOffset;t<p;t+=Ke.vertexStep){const e=u[t],i=u[t+1];e<h&&(h=e),e>g&&(g=e),i<d&&(d=i),i>c&&(c=i)}if(h!=Number.MAX_VALUE)if(h<i&&(i=h),d<s&&(s=d),g>r&&(r=g),c>a&&(a=c),i==Number.MAX_VALUE)e._allClippedDrawRect.x=0,e._allClippedDrawRect.y=0,e._allClippedDrawRect.width=0,e._allClippedDrawRect.height=0,e._isUsing=!1;else{e._isUsing=!0;const t=r-i,n=a-s;e._allClippedDrawRect.x=i,e._allClippedDrawRect.y=s,e._allClippedDrawRect.width=t,e._allClippedDrawRect.height=n}}}getClippingContextListForDraw(){return this._clippingContextListForDraw}getClippingMaskBufferSize(){return this._clippingMaskBufferSize}getRenderTextureCount(){return this._renderTextureCount}getChannelFlagAsColor(t){return this._channelColors.at(t)}setClippingMaskBufferSize(t){this._clippingMaskBufferSize=t}}let xs;class Ms{constructor(){this._shaderSets=new se}release(){this.releaseShaderProgram()}setupShaderProgramForDraw(t,e,i){let s,r,a,n;t.isPremultipliedAlpha()||we("NoPremultipliedAlpha is not allowed"),0==this._shaderSets.getSize()&&this.generateShaders();const o=null!=t.getClippingContextBufferForDraw(),l=e.getDrawableInvertedMaskBit(i),u=o?l?2:1:0;let h;switch(e.getDrawableBlendMode(i)){case xe.CubismBlendMode_Normal:default:h=this._shaderSets.at(1+u),s=this.gl.ONE,r=this.gl.ONE_MINUS_SRC_ALPHA,a=this.gl.ONE,n=this.gl.ONE_MINUS_SRC_ALPHA;break;case xe.CubismBlendMode_Additive:h=this._shaderSets.at(4+u),s=this.gl.ONE,r=this.gl.ONE,a=this.gl.ZERO,n=this.gl.ONE;break;case xe.CubismBlendMode_Multiplicative:h=this._shaderSets.at(7+u),s=this.gl.DST_COLOR,r=this.gl.ONE_MINUS_SRC_ALPHA,a=this.gl.ZERO,n=this.gl.ONE}this.gl.useProgram(h.shaderProgram),null==t._bufferData.vertex&&(t._bufferData.vertex=this.gl.createBuffer()),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,t._bufferData.vertex);const d=e.getDrawableVertices(i);this.gl.bufferData(this.gl.ARRAY_BUFFER,d,this.gl.DYNAMIC_DRAW),this.gl.enableVertexAttribArray(h.attributePositionLocation),this.gl.vertexAttribPointer(h.attributePositionLocation,2,this.gl.FLOAT,!1,0,0),null==t._bufferData.uv&&(t._bufferData.uv=this.gl.createBuffer()),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,t._bufferData.uv);const g=e.getDrawableVertexUvs(i);if(this.gl.bufferData(this.gl.ARRAY_BUFFER,g,this.gl.DYNAMIC_DRAW),this.gl.enableVertexAttribArray(h.attributeTexCoordLocation),this.gl.vertexAttribPointer(h.attributeTexCoordLocation,2,this.gl.FLOAT,!1,0,0),o){this.gl.activeTexture(this.gl.TEXTURE1);const e=t.getClippingContextBufferForDraw().getClippingManager().getColorBuffer().at(t.getClippingContextBufferForDraw()._bufferIndex);this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.uniform1i(h.samplerTexture1Location,1),this.gl.uniformMatrix4fv(h.uniformClipMatrixLocation,!1,t.getClippingContextBufferForDraw()._matrixForDraw.getArray());const i=t.getClippingContextBufferForDraw()._layoutChannelIndex,s=t.getClippingContextBufferForDraw().getClippingManager().getChannelFlagAsColor(i);this.gl.uniform4f(h.uniformChannelFlagLocation,s.r,s.g,s.b,s.a)}const c=e.getDrawableTextureIndex(i),p=t.getBindedTextures().getValue(c);this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,p),this.gl.uniform1i(h.samplerTexture0Location,0);const m=t.getMvpMatrix();this.gl.uniformMatrix4fv(h.uniformMatrixLocation,!1,m.getArray());const _=t.getModelColorWithOpacity(e.getDrawableOpacity(i)),f=e.getMultiplyColor(i),y=e.getScreenColor(i);this.gl.uniform4f(h.uniformBaseColorLocation,_.r,_.g,_.b,_.a),this.gl.uniform4f(h.uniformMultiplyColorLocation,f.r,f.g,f.b,f.a),this.gl.uniform4f(h.uniformScreenColorLocation,y.r,y.g,y.b,y.a),null==t._bufferData.index&&(t._bufferData.index=this.gl.createBuffer());const x=e.getDrawableVertexIndices(i);this.gl.bindBuffer(this.gl.ELEMENT_ARRAY_BUFFER,t._bufferData.index),this.gl.bufferData(this.gl.ELEMENT_ARRAY_BUFFER,x,this.gl.DYNAMIC_DRAW),this.gl.blendFuncSeparate(s,r,a,n)}setupShaderProgramForMask(t,e,i){t.isPremultipliedAlpha()||we("NoPremultipliedAlpha is not allowed"),0==this._shaderSets.getSize()&&this.generateShaders();const s=this._shaderSets.at(0);this.gl.useProgram(s.shaderProgram),null==t._bufferData.vertex&&(t._bufferData.vertex=this.gl.createBuffer()),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,t._bufferData.vertex);const r=e.getDrawableVertices(i);this.gl.bufferData(this.gl.ARRAY_BUFFER,r,this.gl.DYNAMIC_DRAW),this.gl.enableVertexAttribArray(s.attributePositionLocation),this.gl.vertexAttribPointer(s.attributePositionLocation,2,this.gl.FLOAT,!1,0,0),null==t._bufferData.uv&&(t._bufferData.uv=this.gl.createBuffer()),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,t._bufferData.uv);const a=e.getDrawableTextureIndex(i),n=t.getBindedTextures().getValue(a);this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,n),this.gl.uniform1i(s.samplerTexture0Location,0),null==t._bufferData.uv&&(t._bufferData.uv=this.gl.createBuffer()),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,t._bufferData.uv);const o=e.getDrawableVertexUvs(i);this.gl.bufferData(this.gl.ARRAY_BUFFER,o,this.gl.DYNAMIC_DRAW),this.gl.enableVertexAttribArray(s.attributeTexCoordLocation),this.gl.vertexAttribPointer(s.attributeTexCoordLocation,2,this.gl.FLOAT,!1,0,0),t.getClippingContextBufferForMask();const l=t.getClippingContextBufferForMask()._layoutChannelIndex,u=t.getClippingContextBufferForMask().getClippingManager().getChannelFlagAsColor(l);this.gl.uniform4f(s.uniformChannelFlagLocation,u.r,u.g,u.b,u.a),this.gl.uniformMatrix4fv(s.uniformClipMatrixLocation,!1,t.getClippingContextBufferForMask()._matrixForMask.getArray());const h=t.getClippingContextBufferForMask()._layoutBounds;this.gl.uniform4f(s.uniformBaseColorLocation,2*h.x-1,2*h.y-1,2*h.getRight()-1,2*h.getBottom()-1);const d=e.getMultiplyColor(i),g=e.getScreenColor(i);this.gl.uniform4f(s.uniformMultiplyColorLocation,d.r,d.g,d.b,d.a),this.gl.uniform4f(s.uniformScreenColorLocation,g.r,g.g,g.b,g.a);const c=this.gl.ZERO,p=this.gl.ONE_MINUS_SRC_COLOR,m=this.gl.ZERO,_=this.gl.ONE_MINUS_SRC_ALPHA;null==t._bufferData.index&&(t._bufferData.index=this.gl.createBuffer());const f=e.getDrawableVertexIndices(i);this.gl.bindBuffer(this.gl.ELEMENT_ARRAY_BUFFER,t._bufferData.index),this.gl.bufferData(this.gl.ELEMENT_ARRAY_BUFFER,f,this.gl.DYNAMIC_DRAW),this.gl.blendFuncSeparate(c,p,m,_)}releaseShaderProgram(){for(let t=0;t<this._shaderSets.getSize();t++)this.gl.deleteProgram(this._shaderSets.at(t).shaderProgram),this._shaderSets.at(t).shaderProgram=0,this._shaderSets.set(t,void 0),this._shaderSets.set(t,null)}generateShaders(){for(let t=0;t<10;t++)this._shaderSets.pushBack(new Ss);this._shaderSets.at(0).shaderProgram=this.loadShaderProgram(bs,Ps),this._shaderSets.at(1).shaderProgram=this.loadShaderProgram(Bs,Is),this._shaderSets.at(2).shaderProgram=this.loadShaderProgram(ws,Fs),this._shaderSets.at(3).shaderProgram=this.loadShaderProgram(ws,Es),this._shaderSets.at(4).shaderProgram=this._shaderSets.at(1).shaderProgram,this._shaderSets.at(5).shaderProgram=this._shaderSets.at(2).shaderProgram,this._shaderSets.at(6).shaderProgram=this._shaderSets.at(3).shaderProgram,this._shaderSets.at(7).shaderProgram=this._shaderSets.at(1).shaderProgram,this._shaderSets.at(8).shaderProgram=this._shaderSets.at(2).shaderProgram,this._shaderSets.at(9).shaderProgram=this._shaderSets.at(3).shaderProgram,this._shaderSets.at(0).attributePositionLocation=this.gl.getAttribLocation(this._shaderSets.at(0).shaderProgram,"a_position"),this._shaderSets.at(0).attributeTexCoordLocation=this.gl.getAttribLocation(this._shaderSets.at(0).shaderProgram,"a_texCoord"),this._shaderSets.at(0).samplerTexture0Location=this.gl.getUniformLocation(this._shaderSets.at(0).shaderProgram,"s_texture0"),this._shaderSets.at(0).uniformClipMatrixLocation=this.gl.getUniformLocation(this._shaderSets.at(0).shaderProgram,"u_clipMatrix"),this._shaderSets.at(0).uniformChannelFlagLocation=this.gl.getUniformLocation(this._shaderSets.at(0).shaderProgram,"u_channelFlag"),this._shaderSets.at(0).uniformBaseColorLocation=this.gl.getUniformLocation(this._shaderSets.at(0).shaderProgram,"u_baseColor"),this._shaderSets.at(0).uniformMultiplyColorLocation=this.gl.getUniformLocation(this._shaderSets.at(0).shaderProgram,"u_multiplyColor"),this._shaderSets.at(0).uniformScreenColorLocation=this.gl.getUniformLocation(this._shaderSets.at(0).shaderProgram,"u_screenColor"),this._shaderSets.at(1).attributePositionLocation=this.gl.getAttribLocation(this._shaderSets.at(1).shaderProgram,"a_position"),this._shaderSets.at(1).attributeTexCoordLocation=this.gl.getAttribLocation(this._shaderSets.at(1).shaderProgram,"a_texCoord"),this._shaderSets.at(1).samplerTexture0Location=this.gl.getUniformLocation(this._shaderSets.at(1).shaderProgram,"s_texture0"),this._shaderSets.at(1).uniformMatrixLocation=this.gl.getUniformLocation(this._shaderSets.at(1).shaderProgram,"u_matrix"),this._shaderSets.at(1).uniformBaseColorLocation=this.gl.getUniformLocation(this._shaderSets.at(1).shaderProgram,"u_baseColor"),this._shaderSets.at(1).uniformMultiplyColorLocation=this.gl.getUniformLocation(this._shaderSets.at(1).shaderProgram,"u_multiplyColor"),this._shaderSets.at(1).uniformScreenColorLocation=this.gl.getUniformLocation(this._shaderSets.at(1).shaderProgram,"u_screenColor"),this._shaderSets.at(2).attributePositionLocation=this.gl.getAttribLocation(this._shaderSets.at(2).shaderProgram,"a_position"),this._shaderSets.at(2).attributeTexCoordLocation=this.gl.getAttribLocation(this._shaderSets.at(2).shaderProgram,"a_texCoord"),this._shaderSets.at(2).samplerTexture0Location=this.gl.getUniformLocation(this._shaderSets.at(2).shaderProgram,"s_texture0"),this._shaderSets.at(2).samplerTexture1Location=this.gl.getUniformLocation(this._shaderSets.at(2).shaderProgram,"s_texture1"),this._shaderSets.at(2).uniformMatrixLocation=this.gl.getUniformLocation(this._shaderSets.at(2).shaderProgram,"u_matrix"),this._shaderSets.at(2).uniformClipMatrixLocation=this.gl.getUniformLocation(this._shaderSets.at(2).shaderProgram,"u_clipMatrix"),this._shaderSets.at(2).uniformChannelFlagLocation=this.gl.getUniformLocation(this._shaderSets.at(2).shaderProgram,"u_channelFlag"),this._shaderSets.at(2).uniformBaseColorLocation=this.gl.getUniformLocation(this._shaderSets.at(2).shaderProgram,"u_baseColor"),this._shaderSets.at(2).uniformMultiplyColorLocation=this.gl.getUniformLocation(this._shaderSets.at(2).shaderProgram,"u_multiplyColor"),this._shaderSets.at(2).uniformScreenColorLocation=this.gl.getUniformLocation(this._shaderSets.at(2).shaderProgram,"u_screenColor"),this._shaderSets.at(3).attributePositionLocation=this.gl.getAttribLocation(this._shaderSets.at(3).shaderProgram,"a_position"),this._shaderSets.at(3).attributeTexCoordLocation=this.gl.getAttribLocation(this._shaderSets.at(3).shaderProgram,"a_texCoord"),this._shaderSets.at(3).samplerTexture0Location=this.gl.getUniformLocation(this._shaderSets.at(3).shaderProgram,"s_texture0"),this._shaderSets.at(3).samplerTexture1Location=this.gl.getUniformLocation(this._shaderSets.at(3).shaderProgram,"s_texture1"),this._shaderSets.at(3).uniformMatrixLocation=this.gl.getUniformLocation(this._shaderSets.at(3).shaderProgram,"u_matrix"),this._shaderSets.at(3).uniformClipMatrixLocation=this.gl.getUniformLocation(this._shaderSets.at(3).shaderProgram,"u_clipMatrix"),this._shaderSets.at(3).uniformChannelFlagLocation=this.gl.getUniformLocation(this._shaderSets.at(3).shaderProgram,"u_channelFlag"),this._shaderSets.at(3).uniformBaseColorLocation=this.gl.getUniformLocation(this._shaderSets.at(3).shaderProgram,"u_baseColor"),this._shaderSets.at(3).uniformMultiplyColorLocation=this.gl.getUniformLocation(this._shaderSets.at(3).shaderProgram,"u_multiplyColor"),this._shaderSets.at(3).uniformScreenColorLocation=this.gl.getUniformLocation(this._shaderSets.at(3).shaderProgram,"u_screenColor"),this._shaderSets.at(4).attributePositionLocation=this.gl.getAttribLocation(this._shaderSets.at(4).shaderProgram,"a_position"),this._shaderSets.at(4).attributeTexCoordLocation=this.gl.getAttribLocation(this._shaderSets.at(4).shaderProgram,"a_texCoord"),this._shaderSets.at(4).samplerTexture0Location=this.gl.getUniformLocation(this._shaderSets.at(4).shaderProgram,"s_texture0"),this._shaderSets.at(4).uniformMatrixLocation=this.gl.getUniformLocation(this._shaderSets.at(4).shaderProgram,"u_matrix"),this._shaderSets.at(4).uniformBaseColorLocation=this.gl.getUniformLocation(this._shaderSets.at(4).shaderProgram,"u_baseColor"),this._shaderSets.at(4).uniformMultiplyColorLocation=this.gl.getUniformLocation(this._shaderSets.at(4).shaderProgram,"u_multiplyColor"),this._shaderSets.at(4).uniformScreenColorLocation=this.gl.getUniformLocation(this._shaderSets.at(4).shaderProgram,"u_screenColor"),this._shaderSets.at(5).attributePositionLocation=this.gl.getAttribLocation(this._shaderSets.at(5).shaderProgram,"a_position"),this._shaderSets.at(5).attributeTexCoordLocation=this.gl.getAttribLocation(this._shaderSets.at(5).shaderProgram,"a_texCoord"),this._shaderSets.at(5).samplerTexture0Location=this.gl.getUniformLocation(this._shaderSets.at(5).shaderProgram,"s_texture0"),this._shaderSets.at(5).samplerTexture1Location=this.gl.getUniformLocation(this._shaderSets.at(5).shaderProgram,"s_texture1"),this._shaderSets.at(5).uniformMatrixLocation=this.gl.getUniformLocation(this._shaderSets.at(5).shaderProgram,"u_matrix"),this._shaderSets.at(5).uniformClipMatrixLocation=this.gl.getUniformLocation(this._shaderSets.at(5).shaderProgram,"u_clipMatrix"),this._shaderSets.at(5).uniformChannelFlagLocation=this.gl.getUniformLocation(this._shaderSets.at(5).shaderProgram,"u_channelFlag"),this._shaderSets.at(5).uniformBaseColorLocation=this.gl.getUniformLocation(this._shaderSets.at(5).shaderProgram,"u_baseColor"),this._shaderSets.at(5).uniformMultiplyColorLocation=this.gl.getUniformLocation(this._shaderSets.at(5).shaderProgram,"u_multiplyColor"),this._shaderSets.at(5).uniformScreenColorLocation=this.gl.getUniformLocation(this._shaderSets.at(5).shaderProgram,"u_screenColor"),this._shaderSets.at(6).attributePositionLocation=this.gl.getAttribLocation(this._shaderSets.at(6).shaderProgram,"a_position"),this._shaderSets.at(6).attributeTexCoordLocation=this.gl.getAttribLocation(this._shaderSets.at(6).shaderProgram,"a_texCoord"),this._shaderSets.at(6).samplerTexture0Location=this.gl.getUniformLocation(this._shaderSets.at(6).shaderProgram,"s_texture0"),this._shaderSets.at(6).samplerTexture1Location=this.gl.getUniformLocation(this._shaderSets.at(6).shaderProgram,"s_texture1"),this._shaderSets.at(6).uniformMatrixLocation=this.gl.getUniformLocation(this._shaderSets.at(6).shaderProgram,"u_matrix"),this._shaderSets.at(6).uniformClipMatrixLocation=this.gl.getUniformLocation(this._shaderSets.at(6).shaderProgram,"u_clipMatrix"),this._shaderSets.at(6).uniformChannelFlagLocation=this.gl.getUniformLocation(this._shaderSets.at(6).shaderProgram,"u_channelFlag"),this._shaderSets.at(6).uniformBaseColorLocation=this.gl.getUniformLocation(this._shaderSets.at(6).shaderProgram,"u_baseColor"),this._shaderSets.at(6).uniformMultiplyColorLocation=this.gl.getUniformLocation(this._shaderSets.at(6).shaderProgram,"u_multiplyColor"),this._shaderSets.at(6).uniformScreenColorLocation=this.gl.getUniformLocation(this._shaderSets.at(6).shaderProgram,"u_screenColor"),this._shaderSets.at(7).attributePositionLocation=this.gl.getAttribLocation(this._shaderSets.at(7).shaderProgram,"a_position"),this._shaderSets.at(7).attributeTexCoordLocation=this.gl.getAttribLocation(this._shaderSets.at(7).shaderProgram,"a_texCoord"),this._shaderSets.at(7).samplerTexture0Location=this.gl.getUniformLocation(this._shaderSets.at(7).shaderProgram,"s_texture0"),this._shaderSets.at(7).uniformMatrixLocation=this.gl.getUniformLocation(this._shaderSets.at(7).shaderProgram,"u_matrix"),this._shaderSets.at(7).uniformBaseColorLocation=this.gl.getUniformLocation(this._shaderSets.at(7).shaderProgram,"u_baseColor"),this._shaderSets.at(7).uniformMultiplyColorLocation=this.gl.getUniformLocation(this._shaderSets.at(7).shaderProgram,"u_multiplyColor"),this._shaderSets.at(7).uniformScreenColorLocation=this.gl.getUniformLocation(this._shaderSets.at(7).shaderProgram,"u_screenColor"),this._shaderSets.at(8).attributePositionLocation=this.gl.getAttribLocation(this._shaderSets.at(8).shaderProgram,"a_position"),this._shaderSets.at(8).attributeTexCoordLocation=this.gl.getAttribLocation(this._shaderSets.at(8).shaderProgram,"a_texCoord"),this._shaderSets.at(8).samplerTexture0Location=this.gl.getUniformLocation(this._shaderSets.at(8).shaderProgram,"s_texture0"),this._shaderSets.at(8).samplerTexture1Location=this.gl.getUniformLocation(this._shaderSets.at(8).shaderProgram,"s_texture1"),this._shaderSets.at(8).uniformMatrixLocation=this.gl.getUniformLocation(this._shaderSets.at(8).shaderProgram,"u_matrix"),this._shaderSets.at(8).uniformClipMatrixLocation=this.gl.getUniformLocation(this._shaderSets.at(8).shaderProgram,"u_clipMatrix"),this._shaderSets.at(8).uniformChannelFlagLocation=this.gl.getUniformLocation(this._shaderSets.at(8).shaderProgram,"u_channelFlag"),this._shaderSets.at(8).uniformBaseColorLocation=this.gl.getUniformLocation(this._shaderSets.at(8).shaderProgram,"u_baseColor"),this._shaderSets.at(8).uniformMultiplyColorLocation=this.gl.getUniformLocation(this._shaderSets.at(8).shaderProgram,"u_multiplyColor"),this._shaderSets.at(8).uniformScreenColorLocation=this.gl.getUniformLocation(this._shaderSets.at(8).shaderProgram,"u_screenColor"),this._shaderSets.at(9).attributePositionLocation=this.gl.getAttribLocation(this._shaderSets.at(9).shaderProgram,"a_position"),this._shaderSets.at(9).attributeTexCoordLocation=this.gl.getAttribLocation(this._shaderSets.at(9).shaderProgram,"a_texCoord"),this._shaderSets.at(9).samplerTexture0Location=this.gl.getUniformLocation(this._shaderSets.at(9).shaderProgram,"s_texture0"),this._shaderSets.at(9).samplerTexture1Location=this.gl.getUniformLocation(this._shaderSets.at(9).shaderProgram,"s_texture1"),this._shaderSets.at(9).uniformMatrixLocation=this.gl.getUniformLocation(this._shaderSets.at(9).shaderProgram,"u_matrix"),this._shaderSets.at(9).uniformClipMatrixLocation=this.gl.getUniformLocation(this._shaderSets.at(9).shaderProgram,"u_clipMatrix"),this._shaderSets.at(9).uniformChannelFlagLocation=this.gl.getUniformLocation(this._shaderSets.at(9).shaderProgram,"u_channelFlag"),this._shaderSets.at(9).uniformBaseColorLocation=this.gl.getUniformLocation(this._shaderSets.at(9).shaderProgram,"u_baseColor"),this._shaderSets.at(9).uniformMultiplyColorLocation=this.gl.getUniformLocation(this._shaderSets.at(9).shaderProgram,"u_multiplyColor"),this._shaderSets.at(9).uniformScreenColorLocation=this.gl.getUniformLocation(this._shaderSets.at(9).shaderProgram,"u_screenColor")}loadShaderProgram(t,e){let i=this.gl.createProgram(),s=this.compileShaderSource(this.gl.VERTEX_SHADER,t);if(!s)return we("Vertex shader compile error!"),0;let r=this.compileShaderSource(this.gl.FRAGMENT_SHADER,e);if(!r)return we("Vertex shader compile error!"),0;this.gl.attachShader(i,s),this.gl.attachShader(i,r),this.gl.linkProgram(i);return this.gl.getProgramParameter(i,this.gl.LINK_STATUS)?(this.gl.deleteShader(s),this.gl.deleteShader(r),i):(we("Failed to link program: {0}",i),this.gl.deleteShader(s),s=0,this.gl.deleteShader(r),r=0,i&&(this.gl.deleteProgram(i),i=0),0)}compileShaderSource(t,e){const i=e,s=this.gl.createShader(t);if(this.gl.shaderSource(s,i),this.gl.compileShader(s),!s){const t=this.gl.getShaderInfoLog(s);we("Shader compile log: {0} ",t)}return this.gl.getShaderParameter(s,this.gl.COMPILE_STATUS)?s:(this.gl.deleteShader(s),null)}setGl(t){this.gl=t}}class Cs{static getInstance(){return null==xs&&(xs=new Cs),xs}static deleteInstance(){xs&&(xs.release(),xs=null)}constructor(){this._shaderMap=new Ve}release(){for(const t=this._shaderMap.begin();t.notEqual(this._shaderMap.end());t.preIncrement())t.ptr().second.release();this._shaderMap.clear()}getShader(t){return this._shaderMap.getValue(t)}setGlContext(t){if(!this._shaderMap.isExist(t)){const e=new Ms;e.setGl(t),this._shaderMap.setValue(t,e)}}}class Ss{}var vs=(t=>(t[t.ShaderNames_SetupMask=0]="ShaderNames_SetupMask",t[t.ShaderNames_NormalPremultipliedAlpha=1]="ShaderNames_NormalPremultipliedAlpha",t[t.ShaderNames_NormalMaskedPremultipliedAlpha=2]="ShaderNames_NormalMaskedPremultipliedAlpha",t[t.ShaderNames_NomralMaskedInvertedPremultipliedAlpha=3]="ShaderNames_NomralMaskedInvertedPremultipliedAlpha",t[t.ShaderNames_AddPremultipliedAlpha=4]="ShaderNames_AddPremultipliedAlpha",t[t.ShaderNames_AddMaskedPremultipliedAlpha=5]="ShaderNames_AddMaskedPremultipliedAlpha",t[t.ShaderNames_AddMaskedPremultipliedAlphaInverted=6]="ShaderNames_AddMaskedPremultipliedAlphaInverted",t[t.ShaderNames_MultPremultipliedAlpha=7]="ShaderNames_MultPremultipliedAlpha",t[t.ShaderNames_MultMaskedPremultipliedAlpha=8]="ShaderNames_MultMaskedPremultipliedAlpha",t[t.ShaderNames_MultMaskedPremultipliedAlphaInverted=9]="ShaderNames_MultMaskedPremultipliedAlphaInverted",t))(vs||{});const bs="attribute vec4 a_position;attribute vec2 a_texCoord;varying vec2 v_texCoord;varying vec4 v_myPos;uniform mat4 u_clipMatrix;void main(){ gl_Position = u_clipMatrix * a_position; v_myPos = u_clipMatrix * a_position; v_texCoord = a_texCoord; v_texCoord.y = 1.0 - v_texCoord.y;}",Ps="precision mediump float;varying vec2 v_texCoord;varying vec4 v_myPos;uniform vec4 u_baseColor;uniform vec4 u_channelFlag;uniform sampler2D s_texture0;void main(){ float isInside = step(u_baseColor.x, v_myPos.x/v_myPos.w) * step(u_baseColor.y, v_myPos.y/v_myPos.w) * step(v_myPos.x/v_myPos.w, u_baseColor.z) * step(v_myPos.y/v_myPos.w, u_baseColor.w); gl_FragColor = u_channelFlag * texture2D(s_texture0, v_texCoord).a * isInside;}",Bs="attribute vec4 a_position;attribute vec2 a_texCoord;varying vec2 v_texCoord;uniform mat4 u_matrix;void main(){ gl_Position = u_matrix * a_position; v_texCoord = a_texCoord; v_texCoord.y = 1.0 - v_texCoord.y;}",ws="attribute vec4 a_position;attribute vec2 a_texCoord;varying vec2 v_texCoord;varying vec4 v_clipPos;uniform mat4 u_matrix;uniform mat4 u_clipMatrix;void main(){ gl_Position = u_matrix * a_position; v_clipPos = u_clipMatrix * a_position; v_texCoord = a_texCoord; v_texCoord.y = 1.0 - v_texCoord.y;}",Is="precision mediump float;varying vec2 v_texCoord;uniform vec4 u_baseColor;uniform sampler2D s_texture0;uniform vec4 u_multiplyColor;uniform vec4 u_screenColor;void main(){ vec4 texColor = texture2D(s_texture0, v_texCoord); texColor.rgb = texColor.rgb * u_multiplyColor.rgb; texColor.rgb = (texColor.rgb + u_screenColor.rgb * texColor.a) - (texColor.rgb * u_screenColor.rgb); vec4 color = texColor * u_baseColor; gl_FragColor = vec4(color.rgb, color.a);}",Fs="precision mediump float;varying vec2 v_texCoord;varying vec4 v_clipPos;uniform vec4 u_baseColor;uniform vec4 u_channelFlag;uniform sampler2D s_texture0;uniform sampler2D s_texture1;uniform vec4 u_multiplyColor;uniform vec4 u_screenColor;void main(){ vec4 texColor = texture2D(s_texture0, v_texCoord); texColor.rgb = texColor.rgb * u_multiplyColor.rgb; texColor.rgb = (texColor.rgb + u_screenColor.rgb * texColor.a) - (texColor.rgb * u_screenColor.rgb); vec4 col_formask = texColor * u_baseColor; vec4 clipMask = (1.0 - texture2D(s_texture1, v_clipPos.xy / v_clipPos.w)) * u_channelFlag; float maskVal = clipMask.r + clipMask.g + clipMask.b + clipMask.a; col_formask = col_formask * maskVal; gl_FragColor = col_formask;}",Es="precision mediump float;varying vec2 v_texCoord;varying vec4 v_clipPos;uniform sampler2D s_texture0;uniform sampler2D s_texture1;uniform vec4 u_channelFlag;uniform vec4 u_baseColor;uniform vec4 u_multiplyColor;uniform vec4 u_screenColor;void main(){ vec4 texColor = texture2D(s_texture0, v_texCoord); texColor.rgb = texColor.rgb * u_multiplyColor.rgb; texColor.rgb = (texColor.rgb + u_screenColor.rgb * texColor.a) - (texColor.rgb * u_screenColor.rgb); vec4 col_formask = texColor * u_baseColor; vec4 clipMask = (1.0 - texture2D(s_texture1, v_clipPos.xy / v_clipPos.w)) * u_channelFlag; float maskVal = clipMask.r + clipMask.g + clipMask.b + clipMask.a; col_formask = col_formask * (1.0 - maskVal); gl_FragColor = col_formask;}";var Ls;let Vs,Ts;(t=>{t.CubismShaderSet=Ss,t.CubismShader_WebGL=Ms,t.CubismShaderManager_WebGL=Cs,t.ShaderNames=vs})(Ls||(Ls={}));class Rs extends ys{getMaskRenderTexture(){if(this._maskTexture&&null!=this._maskTexture.textures)this._maskTexture.frameNo=this._currentFrameNo;else{null!=this._maskRenderTextures&&this._maskRenderTextures.clear(),this._maskRenderTextures=new se,null!=this._maskColorBuffers&&this._maskColorBuffers.clear(),this._maskColorBuffers=new se;const t=this._clippingMaskBufferSize;for(let e=0;e<this._renderTextureCount;e++)this._maskColorBuffers.pushBack(this.gl.createTexture()),this.gl.bindTexture(this.gl.TEXTURE_2D,this._maskColorBuffers.at(e)),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,t,t,0,this.gl.RGBA,this.gl.UNSIGNED_BYTE,null),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),this.gl.bindTexture(this.gl.TEXTURE_2D,null),this._maskRenderTextures.pushBack(this.gl.createFramebuffer()),this.gl.bindFramebuffer(this.gl.FRAMEBUFFER,this._maskRenderTextures.at(e)),this.gl.framebufferTexture2D(this.gl.FRAMEBUFFER,this.gl.COLOR_ATTACHMENT0,this.gl.TEXTURE_2D,this._maskColorBuffers.at(e),0);this.gl.bindFramebuffer(this.gl.FRAMEBUFFER,Ts),this._maskTexture=new Ds(this._currentFrameNo,this._maskRenderTextures)}return this._maskTexture.textures}setGL(t){this.gl=t}constructor(){super(As)}setupClippingContext(t,e){this._currentFrameNo++;let i=0;for(let s=0;s<this._clippingContextListForMask.getSize();s++){const e=this._clippingContextListForMask.at(s);this.calcClippedDrawTotalBounds(t,e),e._isUsing&&i++}if(i>0){this.gl.viewport(0,0,this._clippingMaskBufferSize,this._clippingMaskBufferSize),this._currentMaskRenderTexture=this.getMaskRenderTexture().at(0),e.preDraw(),this.setupLayoutBounds(i),this.gl.bindFramebuffer(this.gl.FRAMEBUFFER,this._currentMaskRenderTexture),this._clearedFrameBufferFlags.getSize()!=this._renderTextureCount&&(this._clearedFrameBufferFlags.clear(),this._clearedFrameBufferFlags=new se(this._renderTextureCount));for(let t=0;t<this._clearedFrameBufferFlags.getSize();t++)this._clearedFrameBufferFlags.set(t,!1);for(let i=0;i<this._clippingContextListForMask.getSize();i++){const s=this._clippingContextListForMask.at(i),r=s._allClippedDrawRect,a=s._layoutBounds,n=.05;let o=0,l=0;const u=this.getMaskRenderTexture().at(s._bufferIndex);this._currentMaskRenderTexture!=u&&(this._currentMaskRenderTexture=u,e.preDraw(),this.gl.bindFramebuffer(this.gl.FRAMEBUFFER,this._currentMaskRenderTexture)),this._tmpBoundsOnModel.setRect(r),this._tmpBoundsOnModel.expand(r.width*n,r.height*n),o=a.width/this._tmpBoundsOnModel.width,l=a.height/this._tmpBoundsOnModel.height,this._tmpMatrix.loadIdentity(),this._tmpMatrix.translateRelative(-1,-1),this._tmpMatrix.scaleRelative(2,2),this._tmpMatrix.translateRelative(a.x,a.y),this._tmpMatrix.scaleRelative(o,l),this._tmpMatrix.translateRelative(-this._tmpBoundsOnModel.x,-this._tmpBoundsOnModel.y),this._tmpMatrixForMask.setMatrix(this._tmpMatrix.getArray()),this._tmpMatrix.loadIdentity(),this._tmpMatrix.translateRelative(a.x,a.y),this._tmpMatrix.scaleRelative(o,l),this._tmpMatrix.translateRelative(-this._tmpBoundsOnModel.x,-this._tmpBoundsOnModel.y),this._tmpMatrixForDraw.setMatrix(this._tmpMatrix.getArray()),s._matrixForMask.setMatrix(this._tmpMatrixForMask.getArray()),s._matrixForDraw.setMatrix(this._tmpMatrixForDraw.getArray());const h=s._clippingIdCount;for(let i=0;i<h;i++){const r=s._clippingIdList[i];t.getDrawableDynamicFlagVertexPositionsDidChange(r)&&(e.setIsCulling(0!=t.getDrawableCulling(r)),this._clearedFrameBufferFlags.at(s._bufferIndex)||(this.gl.clearColor(1,1,1,1),this.gl.clear(this.gl.COLOR_BUFFER_BIT),this._clearedFrameBufferFlags.set(s._bufferIndex,!0)),e.setClippingContextBufferForMask(s),e.drawMeshWebGL(t,r))}}this.gl.bindFramebuffer(this.gl.FRAMEBUFFER,Ts),e.setClippingContextBufferForMask(null),this.gl.viewport(Vs[0],Vs[1],Vs[2],Vs[3])}}getColorBuffer(){return this._maskColorBuffers}getClippingMaskCount(){return this._clippingContextListForMask.getSize()}}class Ds{constructor(t,e){this.frameNo=t,this.textures=e}}class As extends Ce{constructor(t,e,i){super(e,i),this._owner=t}getClippingManager(){return this._owner}setGl(t){this._owner.setGL(t)}}class Os{setGlEnable(t,e){e?this.gl.enable(t):this.gl.disable(t)}setGlEnableVertexAttribArray(t,e){e?this.gl.enableVertexAttribArray(t):this.gl.disableVertexAttribArray(t)}save(){null!=this.gl?(this._lastArrayBufferBinding=this.gl.getParameter(this.gl.ARRAY_BUFFER_BINDING),this._lastElementArrayBufferBinding=this.gl.getParameter(this.gl.ELEMENT_ARRAY_BUFFER_BINDING),this._lastProgram=this.gl.getParameter(this.gl.CURRENT_PROGRAM),this._lastActiveTexture=this.gl.getParameter(this.gl.ACTIVE_TEXTURE),this.gl.activeTexture(this.gl.TEXTURE1),this._lastTexture1Binding2D=this.gl.getParameter(this.gl.TEXTURE_BINDING_2D),this.gl.activeTexture(this.gl.TEXTURE0),this._lastTexture0Binding2D=this.gl.getParameter(this.gl.TEXTURE_BINDING_2D),this._lastVertexAttribArrayEnabled[0]=this.gl.getVertexAttrib(0,this.gl.VERTEX_ATTRIB_ARRAY_ENABLED),this._lastVertexAttribArrayEnabled[1]=this.gl.getVertexAttrib(1,this.gl.VERTEX_ATTRIB_ARRAY_ENABLED),this._lastVertexAttribArrayEnabled[2]=this.gl.getVertexAttrib(2,this.gl.VERTEX_ATTRIB_ARRAY_ENABLED),this._lastVertexAttribArrayEnabled[3]=this.gl.getVertexAttrib(3,this.gl.VERTEX_ATTRIB_ARRAY_ENABLED),this._lastScissorTest=this.gl.isEnabled(this.gl.SCISSOR_TEST),this._lastStencilTest=this.gl.isEnabled(this.gl.STENCIL_TEST),this._lastDepthTest=this.gl.isEnabled(this.gl.DEPTH_TEST),this._lastCullFace=this.gl.isEnabled(this.gl.CULL_FACE),this._lastBlend=this.gl.isEnabled(this.gl.BLEND),this._lastFrontFace=this.gl.getParameter(this.gl.FRONT_FACE),this._lastColorMask=this.gl.getParameter(this.gl.COLOR_WRITEMASK),this._lastBlending[0]=this.gl.getParameter(this.gl.BLEND_SRC_RGB),this._lastBlending[1]=this.gl.getParameter(this.gl.BLEND_DST_RGB),this._lastBlending[2]=this.gl.getParameter(this.gl.BLEND_SRC_ALPHA),this._lastBlending[3]=this.gl.getParameter(this.gl.BLEND_DST_ALPHA),this._lastFBO=this.gl.getParameter(this.gl.FRAMEBUFFER_BINDING),this._lastViewport=this.gl.getParameter(this.gl.VIEWPORT)):we("'gl' is null. WebGLRenderingContext is required.\nPlease call 'CubimRenderer_WebGL.startUp' function.")}restore(){null!=this.gl?(this.gl.useProgram(this._lastProgram),this.setGlEnableVertexAttribArray(0,this._lastVertexAttribArrayEnabled[0]),this.setGlEnableVertexAttribArray(1,this._lastVertexAttribArrayEnabled[1]),this.setGlEnableVertexAttribArray(2,this._lastVertexAttribArrayEnabled[2]),this.setGlEnableVertexAttribArray(3,this._lastVertexAttribArrayEnabled[3]),this.setGlEnable(this.gl.SCISSOR_TEST,this._lastScissorTest),this.setGlEnable(this.gl.STENCIL_TEST,this._lastStencilTest),this.setGlEnable(this.gl.DEPTH_TEST,this._lastDepthTest),this.setGlEnable(this.gl.CULL_FACE,this._lastCullFace),this.setGlEnable(this.gl.BLEND,this._lastBlend),this.gl.frontFace(this._lastFrontFace),this.gl.colorMask(this._lastColorMask[0],this._lastColorMask[1],this._lastColorMask[2],this._lastColorMask[3]),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this._lastArrayBufferBinding),this.gl.bindBuffer(this.gl.ELEMENT_ARRAY_BUFFER,this._lastElementArrayBufferBinding),this.gl.activeTexture(this.gl.TEXTURE1),this.gl.bindTexture(this.gl.TEXTURE_2D,this._lastTexture1Binding2D),this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this._lastTexture0Binding2D),this.gl.activeTexture(this._lastActiveTexture),this.gl.blendFuncSeparate(this._lastBlending[0],this._lastBlending[1],this._lastBlending[2],this._lastBlending[3])):we("'gl' is null. WebGLRenderingContext is required.\nPlease call 'CubimRenderer_WebGL.startUp' function.")}setGl(t){this.gl=t}constructor(){this._lastVertexAttribArrayEnabled=new Array(4),this._lastColorMask=new Array(4),this._lastBlending=new Array(4),this._lastViewport=new Array(4)}}class ks extends fe{initialize(t,e=1){t.isUsingMasking()&&(this._clippingManager=new Rs,this._clippingManager.initialize(t,e)),this._sortedDrawableIndexList.resize(t.getDrawableCount(),0),super.initialize(t)}bindTexture(t,e){this._textures.setValue(t,e)}getBindedTextures(){return this._textures}setClippingMaskBufferSize(t){if(!this._model.isUsingMasking())return;const e=this._clippingManager.getRenderTextureCount();this._clippingManager.release(),this._clippingManager=void 0,this._clippingManager=null,this._clippingManager=new Rs,this._clippingManager.setClippingMaskBufferSize(t),this._clippingManager.initialize(this.getModel(),e)}getClippingMaskBufferSize(){return this._model.isUsingMasking()?this._clippingManager.getClippingMaskBufferSize():-1}getRenderTextureCount(){return this._model.isUsingMasking()?this._clippingManager.getRenderTextureCount():-1}constructor(){super(),this._clippingContextBufferForMask=null,this._clippingContextBufferForDraw=null,this._rendererProfile=new Os,this.firstDraw=!0,this._textures=new Ve,this._sortedDrawableIndexList=new se,this._bufferData={vertex:WebGLBuffer=null,uv:WebGLBuffer=null,index:WebGLBuffer=null},this._textures.prepareCapacity(32,!0)}release(){this._clippingManager&&(this._clippingManager.release(),this._clippingManager=void 0,this._clippingManager=null),null!=this.gl&&(this.gl.deleteBuffer(this._bufferData.vertex),this._bufferData.vertex=null,this.gl.deleteBuffer(this._bufferData.uv),this._bufferData.uv=null,this.gl.deleteBuffer(this._bufferData.index),this._bufferData.index=null,this._bufferData=null,this._textures=null)}doDrawModel(){if(null==this.gl)return void we("'gl' is null. WebGLRenderingContext is required.\nPlease call 'CubimRenderer_WebGL.startUp' function.");null!=this._clippingManager&&(this.preDraw(),this.isUsingHighPrecisionMask()?this._clippingManager.setupMatrixForHighPrecision(this.getModel(),!1):this._clippingManager.setupClippingContext(this.getModel(),this)),this.preDraw();const t=this.getModel().getDrawableCount(),e=this.getModel().getDrawableRenderOrders();for(let i=0;i<t;++i){const t=e[i];this._sortedDrawableIndexList.set(t,i)}for(let i=0;i<t;++i){const t=this._sortedDrawableIndexList.at(i);if(!this.getModel().getDrawableDynamicFlagIsVisible(t))continue;const e=null!=this._clippingManager?this._clippingManager.getClippingContextListForDraw().at(t):null;if(null!=e&&this.isUsingHighPrecisionMask()){e._isUsing&&(this.gl.viewport(0,0,this._clippingManager.getClippingMaskBufferSize(),this._clippingManager.getClippingMaskBufferSize()),this.preDraw(),this.gl.bindFramebuffer(this.gl.FRAMEBUFFER,e.getClippingManager().getMaskRenderTexture().at(e._bufferIndex)),this.gl.clearColor(1,1,1,1),this.gl.clear(this.gl.COLOR_BUFFER_BIT));{const t=e._clippingIdCount;for(let i=0;i<t;i++){const t=e._clippingIdList[i];this._model.getDrawableDynamicFlagVertexPositionsDidChange(t)&&(this.setIsCulling(0!=this._model.getDrawableCulling(t)),this.setClippingContextBufferForMask(e),this.drawMeshWebGL(this._model,t))}}this.gl.bindFramebuffer(this.gl.FRAMEBUFFER,Ts),this.setClippingContextBufferForMask(null),this.gl.viewport(Vs[0],Vs[1],Vs[2],Vs[3]),this.preDraw()}this.setClippingContextBufferForDraw(e),this.setIsCulling(this.getModel().getDrawableCulling(t)),this.drawMeshWebGL(this._model,t)}}drawMeshWebGL(t,e){this.isCulling()?this.gl.enable(this.gl.CULL_FACE):this.gl.disable(this.gl.CULL_FACE),this.gl.frontFace(this.gl.CCW),this.isGeneratingMask()?Cs.getInstance().getShader(this.gl).setupShaderProgramForMask(this,t,e):Cs.getInstance().getShader(this.gl).setupShaderProgramForDraw(this,t,e);{const i=t.getDrawableVertexIndexCount(e);this.gl.drawElements(this.gl.TRIANGLES,i,this.gl.UNSIGNED_SHORT,0)}this.gl.useProgram(null),this.setClippingContextBufferForDraw(null),this.setClippingContextBufferForMask(null)}saveProfile(){this._rendererProfile.save()}restoreProfile(){this._rendererProfile.restore()}static doStaticRelease(){Cs.deleteInstance()}setRenderState(t,e){Ts=t,Vs=e}preDraw(){if(this.firstDraw&&(this.firstDraw=!1),this.gl.disable(this.gl.SCISSOR_TEST),this.gl.disable(this.gl.STENCIL_TEST),this.gl.disable(this.gl.DEPTH_TEST),this.gl.frontFace(this.gl.CW),this.gl.enable(this.gl.BLEND),this.gl.colorMask(!0,!0,!0,!0),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),this.gl.bindBuffer(this.gl.ELEMENT_ARRAY_BUFFER,null),this.getAnisotropy()>0&&this._extension)for(let t=0;t<this._textures.getSize();++t)this.gl.bindTexture(this.gl.TEXTURE_2D,this._textures.getValue(t)),this.gl.texParameterf(this.gl.TEXTURE_2D,this._extension.TEXTURE_MAX_ANISOTROPY_EXT,this.getAnisotropy())}setClippingContextBufferForMask(t){this._clippingContextBufferForMask=t}getClippingContextBufferForMask(){return this._clippingContextBufferForMask}setClippingContextBufferForDraw(t){this._clippingContextBufferForDraw=t}getClippingContextBufferForDraw(){return this._clippingContextBufferForDraw}isGeneratingMask(){return null!=this.getClippingContextBufferForMask()}startUp(t){this.gl=t,this._clippingManager&&this._clippingManager.setGL(t),Cs.getInstance().setGlContext(t),this._rendererProfile.setGl(t),this._extension=this.gl.getExtension("EXT_texture_filter_anisotropic")||this.gl.getExtension("WEBKIT_EXT_texture_filter_anisotropic")||this.gl.getExtension("MOZ_EXT_texture_filter_anisotropic")}}var Ns;fe.staticRelease=()=>{ks.doStaticRelease()},(t=>{t.CubismClippingContext=As,t.CubismClippingManager_WebGL=Rs,t.CubismRenderTextureResource=Ds,t.CubismRenderer_WebGL=ks})(Ns||(Ns={}));const Us=new me,zs={CenterX:"centerX",centerX:"centerX",center_x:"centerX",CenterY:"centerY",centerY:"centerY",center_y:"centerY",X:"x",x:"x",Y:"y",y:"y",Width:"width",width:"width",Height:"height",height:"height",Top:"top",top:"top",Bottom:"bottom",bottom:"bottom",Left:"left",left:"left",Right:"right",right:"right"};function js(t){if(!t.isUsingMasking())return!1;const e=function(t){var e,i;const s=t.getDrawableMaskCounts(),r=t.getDrawableMasks(),a=new Set,n=t.getDrawableCount();let o=0,l=0,u=0,h=0;for(let d=0;d<n;d++){const n=t.getDrawableVertexCount(d),g=null!=(e=s[d])?e:0;if(h+=n,g<=0)continue;o++,u+=n,l=Math.max(l,g);const c=Array.from(null!=(i=r[d])?i:[]).slice(0,g).sort((t,e)=>t-e).join(",");a.add(c)}return{maskedDrawableCount:o,uniqueMaskSetCount:a.size,maxMasksPerDrawable:l,maskedVertexCount:u,totalVertexCount:h}}(t),i=e.totalVertexCount>0?e.maskedVertexCount/e.totalVertexCount:0;return e.uniqueMaskSetCount>16||e.maskedDrawableCount>64||e.maxMasksPerDrawable>=3||e.maskedVertexCount>4096||i>=.5&&e.maskedDrawableCount>24}class Gs extends st{constructor(t,i,s){super(),d(this,"settings"),d(this,"options"),d(this,"coreModel"),d(this,"motionManager"),d(this,"parallelMotionManager"),d(this,"lipSync",!0),d(this,"breath",gs.create()),d(this,"eyeBlink"),d(this,"renderer",new ks),d(this,"idManager"),d(this,"idParamAngleX"),d(this,"idParamAngleY"),d(this,"idParamAngleZ"),d(this,"idParamEyeBallX"),d(this,"idParamEyeBallY"),d(this,"idParamBodyAngleX"),d(this,"idParamBreath"),d(this,"idParamMouthForm"),d(this,"pixelsPerUnit",1),d(this,"modelTransform",new e.Matrix),this.coreModel=t,this.settings=i,this.options=Object.assign({},{breathDepth:1,lipSyncGain:1.5,lipSyncWeight:.4},s),this.idManager=ti.getIdManager(),this.idParamAngleX=this.getIdSafe(us.ParamAngleX),this.idParamAngleY=this.getIdSafe(us.ParamAngleY),this.idParamAngleZ=this.getIdSafe(us.ParamAngleZ),this.idParamEyeBallX=this.getIdSafe(us.ParamEyeBallX),this.idParamEyeBallY=this.getIdSafe(us.ParamEyeBallY),this.idParamBodyAngleX=this.getIdSafe(us.ParamBodyAngleX),this.idParamBreath=this.getIdSafe(us.ParamBreath),this.idParamMouthForm=this.getIdSafe(us.ParamMouthForm),this.motionManager=new Zi(this),this.parallelMotionManager=[],this.init()}init(){var t;super.init();const e=this.settings.getEyeBlinkParameters();if(!1!==this.options.eyeBlink&&e.length){const i=new se;for(const t of e)i.pushBack(this.idManager.getId(t));const s=ms.create();null==(t=s.setParameterIds)||t.call(s,i),this.eyeBlink=s}const i=new se;var s,r;i.pushBack(new cs(this.idParamAngleX,0,15*this.options.breathDepth,6.5345,.5)),i.pushBack(new cs(this.idParamAngleY,0,8*this.options.breathDepth,3.5345,.5)),i.pushBack(new cs(this.idParamAngleZ,0,10*this.options.breathDepth,5.5345,.5)),i.pushBack(new cs(this.idParamBodyAngleX,0,4*this.options.breathDepth,15.5345,.5)),i.pushBack(new cs(this.idParamBreath,0,.5,3.2345,.5)),this.breath.setParameters(i),this.renderer.initialize(this.coreModel,function(t){var e;if(!t.isUsingMasking())return 1;const i=t.getDrawableMaskCounts(),s=t.getDrawableMasks(),r=new Set;for(let n=0;n<t.getDrawableCount();n++){const t=i[n];if(!t||t<=0)continue;const a=Array.from(null!=(e=s[n])?e:[]).slice(0,t).sort((t,e)=>t-e).join(",");r.add(a)}const a=r.size;return a<=36?1:Math.ceil(a/32)}(this.coreModel)),this.renderer.useHighPrecisionMask((s=this.coreModel,"boolean"==typeof(r=this.options.useHighPrecisionMask)?r:js(s))),this.renderer.setIsPremultipliedAlpha(!0)}getIdSafe(t){return this.idManager.getId(null!=t?t:"")}getSize(){return[this.coreModel.getModel().canvasinfo.CanvasWidth,this.coreModel.getModel().canvasinfo.CanvasHeight]}getLayout(){const t={},e=this.settings.layout;if(e)for(const[i,s]of Object.entries(e)){const e=zs[i];e&&"number"==typeof s&&(t[e]=s)}return t}setupLayout(){const t=this,e=this.getSize();t.originalWidth=e[0],t.originalHeight=e[1],t.pixelsPerUnit=this.coreModel.getModel().canvasinfo.PixelsPerUnit;const i=tt(this.localTransform,this.originalWidth,this.originalHeight,this.getLayout());t.width=i.width,t.height=i.height,this.modelTransform.identity().scale(this.pixelsPerUnit,this.pixelsPerUnit).translate(this.originalWidth/2,this.originalHeight/2)}updateWebGLContext(t,e){this.renderer.firstDraw=!0,this.renderer._bufferData={vertex:null,uv:null,index:null},this.renderer.startUp(t),this.renderer._clippingManager&&(this.renderer._clippingManager._currentFrameNo=e),Cs.getInstance().setGlContext(t)}bindTexture(t,e){this.renderer.bindTexture(t,e)}getHitAreaDefs(){var t,e,i;const s=this.settings.json;return et(null!=(i=null!=(e=null!=(t=this.settings.hitAreas)?t:s.HitAreas)?e:s.hitAreas)?i:s.hit_areas,t=>this.coreModel.getDrawableIndex(this.idManager.getId(t)))}getDrawableIDs(){const t=this.coreModel.getDrawableCount(),e=[];for(let i=0;i<t;i++)e.push(this.coreModel.getDrawableId(i).getString().s);return e}getDrawableIndex(t){return this.coreModel.getDrawableIndex(this.idManager.getId(t))}getDrawableVertices(t){if("string"==typeof t){const e=t;if(-1===(t=this.getDrawableIndex(e)))throw new TypeError("Unable to find drawable ID: "+e)}const e=this.coreModel.getDrawableVertices(t).slice();for(let i=0;i<e.length;i+=2)e[i]=e[i]*this.pixelsPerUnit+this.originalWidth/2,e[i+1]=-e[i+1]*this.pixelsPerUnit+this.originalHeight/2;return e}updateTransform(t){this.drawingMatrix.copyFrom(this.modelTransform).prepend(this.localTransform).prepend(t)}update(t,e){var i,s,r,a,n;super.update(t,e),t/=1e3,e/=1e3;const o=this.coreModel,l=this.updateMotions(o,e);if(o.saveParameters(),null==(i=this.motionManager.expressionManager)||i.update(o,e),l||null==(r=null==(s=this.eyeBlink)?void 0:s.updateParameters)||r.call(s,o,t),this.updateFocus(),this.updateNaturalMovements(1e3*t,1e3*e),this.lipSync&&this.motionManager.currentAudio){let t=this.motionManager.mouthSync()*this.options.lipSyncGain;t=Math.pow(t,1.15);t=m(t,t>0?.1:0,1),this.motionManager.lipSyncIds.forEach(e=>{o.addParameterValueById(this.getIdSafe(e),t,this.options.lipSyncWeight)})}null==(a=this.physics)||a.evaluate(o,t),null==(n=this.pose)||n.updateParameters(o,t),this.emit("beforeModelUpdate"),o.update(),o.loadParameters()}updateFocus(){this.coreModel.addParameterValueById(this.idParamEyeBallX,this.focusController.x),this.coreModel.addParameterValueById(this.idParamEyeBallY,this.focusController.y),this.coreModel.addParameterValueById(this.idParamAngleX,30*this.focusController.x),this.coreModel.addParameterValueById(this.idParamAngleY,30*this.focusController.y),this.coreModel.addParameterValueById(this.idParamAngleZ,this.focusController.x*this.focusController.y*-30),this.coreModel.addParameterValueById(this.idParamBodyAngleX,10*this.focusController.x)}updateFacialEmotion(t){this.coreModel.addParameterValueById(this.idParamMouthForm,t)}updateNaturalMovements(t,e){var i;null==(i=this.breath)||i.updateParameters(this.coreModel,t/1e3)}draw(t){const e=this.drawingMatrix,i=Us.getArray();i[0]=e.a,i[1]=e.b,i[4]=-e.c,i[5]=-e.d,i[12]=e.tx,i[13]=e.ty,this.renderer.setMvpMatrix(Us);const s=t.getParameter(t.FRAMEBUFFER_BINDING),r=t.getParameter(t.CULL_FACE_MODE),a=i[0]*i[5]-i[1]*i[4];t.cullFace(a<0?t.FRONT:t.BACK),this.renderer.setRenderState(s,this.viewport);try{this.renderer.drawModel()}finally{t.cullFace(r)}}extendParallelMotionManager(t){for(;this.parallelMotionManager.length<t;)this.parallelMotionManager.push(new ss(this))}destroy(){super.destroy(),this.renderer.release(),this.coreModel.release(),this.renderer=void 0,this.coreModel=void 0}}class Xs{}var Hs;(t=>{t.ICubismModelSetting=Xs})(Hs||(Hs={}));var Ys,qs=(t=>(t[t.FrequestNode_Groups=0]="FrequestNode_Groups",t[t.FrequestNode_Moc=1]="FrequestNode_Moc",t[t.FrequestNode_Motions=2]="FrequestNode_Motions",t[t.FrequestNode_Expressions=3]="FrequestNode_Expressions",t[t.FrequestNode_Textures=4]="FrequestNode_Textures",t[t.FrequestNode_Physics=5]="FrequestNode_Physics",t[t.FrequestNode_Pose=6]="FrequestNode_Pose",t[t.FrequestNode_HitAreas=7]="FrequestNode_HitAreas",t))(qs||{});class Ws extends Xs{constructor(t,e){super(),this.version="Version",this.fileReferences="FileReferences",this.groups="Groups",this.layout="Layout",this.hitAreas="HitAreas",this.moc="Moc",this.textures="Textures",this.physics="Physics",this.pose="Pose",this.expressions="Expressions",this.motions="Motions",this.userData="UserData",this.name="Name",this.filePath="File",this.id="Id",this.ids="Ids",this.target="Target",this.idle="Idle",this.tapBody="TapBody",this.pinchIn="PinchIn",this.pinchOut="PinchOut",this.shake="Shake",this.flickHead="FlickHead",this.parameter="Parameter",this.soundPath="Sound",this.fadeInTime="FadeInTime",this.fadeOutTime="FadeOutTime",this.centerX="CenterX",this.centerY="CenterY",this.x="X",this.y="Y",this.width="Width",this.height="Height",this.lipSync="LipSync",this.eyeBlink="EyeBlink",this.initParameter="init_param",this.initPartsVisible="init_parts_visible",this.val="val",this._json=ke.create(t,e),this.getJson()&&(this._jsonValue=new se,this._jsonValue.pushBack(this.getJson().getRoot().getValueByString(this.groups)),this._jsonValue.pushBack(this.getJson().getRoot().getValueByString(this.fileReferences).getValueByString(this.moc)),this._jsonValue.pushBack(this.getJson().getRoot().getValueByString(this.fileReferences).getValueByString(this.motions)),this._jsonValue.pushBack(this.getJson().getRoot().getValueByString(this.fileReferences).getValueByString(this.expressions)),this._jsonValue.pushBack(this.getJson().getRoot().getValueByString(this.fileReferences).getValueByString(this.textures)),this._jsonValue.pushBack(this.getJson().getRoot().getValueByString(this.fileReferences).getValueByString(this.physics)),this._jsonValue.pushBack(this.getJson().getRoot().getValueByString(this.fileReferences).getValueByString(this.pose)),this._jsonValue.pushBack(this.getJson().getRoot().getValueByString(this.hitAreas)))}release(){ke.delete(this._json),this._jsonValue=null}getJson(){return this._json}getModelFileName(){return this.isExistModelFile()?this._jsonValue.at(1).getRawString():""}getTextureCount(){return this.isExistTextureFiles()?this._jsonValue.at(4).getSize():0}getTextureDirectory(){const t=this._jsonValue.at(4).getValueByIndex(0).getRawString().split("/"),e=t.length-1;let i="";for(let s=0;s<e;s++)i+=t[s],s<e-1&&(i+="/");return i}getTextureFileName(t){return this._jsonValue.at(4).getValueByIndex(t).getRawString()}getHitAreasCount(){return this.isExistHitAreas()?this._jsonValue.at(7).getSize():0}getHitAreaId(t){return ti.getIdManager().getId(this._jsonValue.at(7).getValueByIndex(t).getValueByString(this.id).getRawString())}getHitAreaName(t){return this._jsonValue.at(7).getValueByIndex(t).getValueByString(this.name).getRawString()}getPhysicsFileName(){return this.isExistPhysicsFile()?this._jsonValue.at(5).getRawString():""}getPoseFileName(){return this.isExistPoseFile()?this._jsonValue.at(6).getRawString():""}getExpressionCount(){return this.isExistExpressionFile()?this._jsonValue.at(3).getSize():0}getExpressionName(t){return this._jsonValue.at(3).getValueByIndex(t).getValueByString(this.name).getRawString()}getExpressionFileName(t){return this._jsonValue.at(3).getValueByIndex(t).getValueByString(this.filePath).getRawString()}getMotionGroupCount(){return this.isExistMotionGroups()?this._jsonValue.at(2).getKeys().getSize():0}getMotionGroupName(t){return this.isExistMotionGroups()?this._jsonValue.at(2).getKeys().at(t):null}getMotionCount(t){return this.isExistMotionGroupName(t)?this._jsonValue.at(2).getValueByString(t).getSize():0}getMotionFileName(t,e){return this.isExistMotionGroupName(t)?this._jsonValue.at(2).getValueByString(t).getValueByIndex(e).getValueByString(this.filePath).getRawString():""}getMotionSoundFileName(t,e){return this.isExistMotionSoundFile(t,e)?this._jsonValue.at(2).getValueByString(t).getValueByIndex(e).getValueByString(this.soundPath).getRawString():""}getMotionFadeInTimeValue(t,e){return this.isExistMotionFadeIn(t,e)?this._jsonValue.at(2).getValueByString(t).getValueByIndex(e).getValueByString(this.fadeInTime).toFloat():-1}getMotionFadeOutTimeValue(t,e){return this.isExistMotionFadeOut(t,e)?this._jsonValue.at(2).getValueByString(t).getValueByIndex(e).getValueByString(this.fadeOutTime).toFloat():-1}getUserDataFile(){return this.isExistUserDataFile()?this.getJson().getRoot().getValueByString(this.fileReferences).getValueByString(this.userData).getRawString():""}getLayoutMap(t){const e=this.getJson().getRoot().getValueByString(this.layout).getMap();if(null==e)return!1;let i=!1;for(const s=e.begin();s.notEqual(e.end());s.preIncrement())t.setValue(s.ptr().first,s.ptr().second.toFloat()),i=!0;return i}getEyeBlinkParameterCount(){if(!this.isExistEyeBlinkParameters())return 0;let t=0;for(let e=0;e<this._jsonValue.at(0).getSize();e++){const i=this._jsonValue.at(0).getValueByIndex(e);if(!i.isNull()&&!i.isError()&&i.getValueByString(this.name).getRawString()==this.eyeBlink){t=i.getValueByString(this.ids).getVector().getSize();break}}return t}getEyeBlinkParameterId(t){if(!this.isExistEyeBlinkParameters())return null;for(let e=0;e<this._jsonValue.at(0).getSize();e++){const i=this._jsonValue.at(0).getValueByIndex(e);if(!i.isNull()&&!i.isError()&&i.getValueByString(this.name).getRawString()==this.eyeBlink)return ti.getIdManager().getId(i.getValueByString(this.ids).getValueByIndex(t).getRawString())}return null}getLipSyncParameterCount(){if(!this.isExistLipSyncParameters())return 0;let t=0;for(let e=0;e<this._jsonValue.at(0).getSize();e++){const i=this._jsonValue.at(0).getValueByIndex(e);if(!i.isNull()&&!i.isError()&&i.getValueByString(this.name).getRawString()==this.lipSync){t=i.getValueByString(this.ids).getVector().getSize();break}}return t}getLipSyncParameterId(t){if(!this.isExistLipSyncParameters())return null;for(let e=0;e<this._jsonValue.at(0).getSize();e++){const i=this._jsonValue.at(0).getValueByIndex(e);if(!i.isNull()&&!i.isError()&&i.getValueByString(this.name).getRawString()==this.lipSync)return ti.getIdManager().getId(i.getValueByString(this.ids).getValueByIndex(t).getRawString())}return null}isExistModelFile(){const t=this._jsonValue.at(1);return!t.isNull()&&!t.isError()}isExistTextureFiles(){const t=this._jsonValue.at(4);return!t.isNull()&&!t.isError()}isExistHitAreas(){const t=this._jsonValue.at(7);return!t.isNull()&&!t.isError()}isExistPhysicsFile(){const t=this._jsonValue.at(5);return!t.isNull()&&!t.isError()}isExistPoseFile(){const t=this._jsonValue.at(6);return!t.isNull()&&!t.isError()}isExistExpressionFile(){const t=this._jsonValue.at(3);return!t.isNull()&&!t.isError()}isExistMotionGroups(){const t=this._jsonValue.at(2);return!t.isNull()&&!t.isError()}isExistMotionGroupName(t){const e=this._jsonValue.at(2).getValueByString(t);return!e.isNull()&&!e.isError()}isExistMotionSoundFile(t,e){const i=this._jsonValue.at(2).getValueByString(t).getValueByIndex(e).getValueByString(this.soundPath);return!i.isNull()&&!i.isError()}isExistMotionFadeIn(t,e){const i=this._jsonValue.at(2).getValueByString(t).getValueByIndex(e).getValueByString(this.fadeInTime);return!i.isNull()&&!i.isError()}isExistMotionFadeOut(t,e){const i=this._jsonValue.at(2).getValueByString(t).getValueByIndex(e).getValueByString(this.fadeOutTime);return!i.isNull()&&!i.isError()}isExistUserDataFile(){const t=this.getJson().getRoot().getValueByString(this.fileReferences).getValueByString(this.userData);return!t.isNull()&&!t.isError()}isExistEyeBlinkParameters(){if(this._jsonValue.at(0).isNull()||this._jsonValue.at(0).isError())return!1;for(let t=0;t<this._jsonValue.at(0).getSize();++t)if(this._jsonValue.at(0).getValueByIndex(t).getValueByString(this.name).getRawString()==this.eyeBlink)return!0;return!1}isExistLipSyncParameters(){if(this._jsonValue.at(0).isNull()||this._jsonValue.at(0).isError())return!1;for(let t=0;t<this._jsonValue.at(0).getSize();++t)if(this._jsonValue.at(0).getValueByIndex(t).getValueByString(this.name).getRawString()==this.lipSync)return!0;return!1}}(t=>{t.CubismModelSettingJson=Ws,t.FrequestNode=qs})(Ys||(Ys={}));const Js=[us.ParamEyeLOpen,us.ParamEyeROpen];class $s extends F{constructor(t){var e,i;if(super(t),d(this,"moc"),d(this,"textures"),d(this,"layout"),d(this,"hitAreas"),d(this,"expressions"),d(this,"motions"),!$s.isValidJSON(t))throw new TypeError("Invalid JSON.");const s=(new TextEncoder).encode(JSON.stringify(t)).buffer;Object.assign(this,new Ws(s,s.byteLength)),this.moc=t.FileReferences.Moc,this.textures=[...t.FileReferences.Textures],this.pose=t.FileReferences.Pose,this.physics=t.FileReferences.Physics,this.expressions=null==(e=t.FileReferences.Expressions)?void 0:e.filter(t=>!!t&&"string"==typeof t.File),this.motions=null!=(i=t.FileReferences.Motions)?i:t.Motions,this.layout=t.Layout,this.hitAreas=t.HitAreas;const r=this.getFileStem(this.moc);this.setModelName(r,this.name)}static isValidJSON(t){if(!t||"object"!=typeof t)return!1;const e=t.FileReferences;if(!e||"object"!=typeof e||"string"!=typeof e.Moc)return!1;const i=e.Textures;if(!Array.isArray(i)||0===i.length)return!1;if(!i.every(t=>"string"==typeof t))return!1;const s=e.Expressions;return!(void 0!==s&&(!Array.isArray(s)||s.some(t=>!(t=>!!t&&"string"==typeof t.File)(t))))}replaceFiles(t){if(super.replaceFiles(t),this.motions)for(const[e,i]of Object.entries(this.motions))for(let s=0;s<i.length;s++){const r=i[s];(null==r?void 0:r.File)&&(r.File=t(r.File,`motions.${e}[${s}].File`),r.Sound&&(r.Sound=t(r.Sound,`motions.${e}[${s}].Sound`)))}if(this.expressions)for(let e=0;e<this.expressions.length;e++){const i=this.expressions[e];(null==i?void 0:i.File)&&(i.File=t(i.File,`expressions[${e}].File`))}}getEyeBlinkParameters(){var t,e,i;const s=[],r=null!=(e=null==(t=this.getEyeBlinkParameterCount)?void 0:t.call(this))?e:0;if(r>0)for(let a=0;a<r;a++){const t=null==(i=this.getEyeBlinkParameterId)?void 0:i.call(this,a);(null==t?void 0:t.getString)&&s.push(t.getString().s)}else{let t=!1;const e=this.json.Groups;if(Array.isArray(e))for(const i of e)if("EyeBlink"===(null==i?void 0:i.Name)&&(t=!0,Array.isArray(i.Ids)))for(const t of i.Ids)"string"==typeof t?s.push(t):(null==t?void 0:t.Id)&&s.push(t.Id);if(t)return s}return s.length?s:[...Js]}getLipSyncParameters(){var t,e,i;const s=[],r=null!=(e=null==(t=this.getLipSyncParameterCount)?void 0:t.call(this))?e:0;if(r>0)for(let a=0;a<r;a++){const t=null==(i=this.getLipSyncParameterId)?void 0:i.call(this,a);(null==t?void 0:t.getString)&&s.push(t.getString().s)}else if(Array.isArray(this.json.Groups)){const t=this.json.Groups;for(const e of t)if("LipSync"===(null==e?void 0:e.Name)&&Array.isArray(e.Ids))for(const t of e.Ids)"string"==typeof t?s.push(t):(null==t?void 0:t.Id)&&s.push(t.Id)}return s}}let Zs;M($s,[Ws]);let Ks=20,Qs=16;function tr(t={}){null!=t.memorySizeMB&&(Qs=t.memorySizeMB)}function er(){return ti.isStarted()?Promise.resolve():(null!=Zs||(Zs=new Promise((t,e)=>{!function i(){try{ir(),t()}catch(s){if(Ks--,Ks<0)return void e(new Error("Failed to start up Cubism framework.",{cause:s}));p.log("Cubism","Startup failed, retrying 10ms later..."),setTimeout(i,10)}}()})),Zs)}function ir(t,e){const i=h({logFunction:console.log,loggingLevel:si.LogLevel_Verbose},t),s=null!=e?e:Qs;ti.startUp(i),ti.initialize(f(s))}const sr="FadeInTime",rr="Link";class ar{static create(t,e){const i=ke.create(t,e);if(!i)return null;const s=new ar,r=i.getRoot();r.getValueByString(sr).isNull()||(s._fadeTimeSeconds=r.getValueByString(sr).toFloat(.5),s._fadeTimeSeconds<0&&(s._fadeTimeSeconds=.5));const a=r.getValueByString("Groups"),n=a.getSize();for(let o=0;o<n;++o){const t=a.getValueByIndex(o),e=t.getSize();let i=0;for(let r=0;r<e;++r){const e=t.getValueByIndex(r),a=new nr,n=ti.getIdManager().getId(e.getValueByString("Id").getRawString());if(a.partId=n,!e.getValueByString(rr).isNull()){const t=e.getValueByString(rr),i=t.getSize();for(let e=0;e<i;++e){const i=new nr,s=ti.getIdManager().getId(t.getValueByIndex(e).getString());i.partId=s,a.link.pushBack(i)}}s._partGroups.pushBack(a.clone()),++i}s._partGroupCounts.pushBack(i)}return ke.delete(i),s}static delete(t){}updateParameters(t,e){t!=this._lastModel&&this.reset(t),this._lastModel=t,e<0&&(e=0);let i=0;for(let s=0;s<this._partGroupCounts.getSize();s++){const r=this._partGroupCounts.at(s);this.doFade(t,e,i,r),i+=r}this.copyPartOpacities(t)}reset(t){let e=0;for(let i=0;i<this._partGroupCounts.getSize();++i){const s=this._partGroupCounts.at(i);for(let i=e;i<e+s;++i){this._partGroups.at(i).initialize(t);const s=this._partGroups.at(i).partIndex,r=this._partGroups.at(i).parameterIndex;if(!(s<0)){t.setPartOpacityByIndex(s,i==e?1:0),t.setParameterValueByIndex(r,i==e?1:0);for(let e=0;e<this._partGroups.at(i).link.getSize();++e)this._partGroups.at(i).link.at(e).initialize(t)}}e+=s}}copyPartOpacities(t){for(let e=0;e<this._partGroups.getSize();++e){const i=this._partGroups.at(e);if(0==i.link.getSize())continue;const s=this._partGroups.at(e).partIndex,r=t.getPartOpacityByIndex(s);for(let e=0;e<i.link.getSize();++e){const s=i.link.at(e).partIndex;s<0||t.setPartOpacityByIndex(s,r)}}}doFade(t,e,i,s){let r=-1,a=1;const n=.5;for(let o=i;o<i+s;++o){const i=this._partGroups.at(o).partIndex,s=this._partGroups.at(o).parameterIndex;if(t.getParameterValueByIndex(s)>.001){if(r>=0)break;if(r=o,0==this._fadeTimeSeconds){a=1;continue}a=t.getPartOpacityByIndex(i),a+=e/this._fadeTimeSeconds,a>1&&(a=1)}}r<0&&(r=0,a=1);for(let o=i;o<i+s;++o){const e=this._partGroups.at(o).partIndex;if(r==o)t.setPartOpacityByIndex(e,a);else{let i,s=t.getPartOpacityByIndex(e);i=a<n?-.5*a/n+1:(1-a)*n/.5;(1-i)*(1-a)>.15&&(i=1-.15/(1-a)),s>i&&(s=i),t.setPartOpacityByIndex(e,s)}}}constructor(){this._fadeTimeSeconds=.5,this._lastModel=null,this._partGroups=new se,this._partGroupCounts=new se}}class nr{constructor(t){if(this.parameterIndex=0,this.partIndex=0,this.link=new se,null!=t){this.partId=t.partId;for(const e=t.link.begin();e.notEqual(t.link.end());e.preIncrement())this.link.pushBack(e.ptr().clone())}}assignment(t){this.partId=t.partId;for(const e=t.link.begin();e.notEqual(t.link.end());e.preIncrement())this.link.pushBack(e.ptr().clone());return this}initialize(t){this.parameterIndex=t.getParameterIndex(this.partId),this.partIndex=t.getPartIndex(this.partId),t.setParameterValueByIndex(this.parameterIndex,1)}clone(){const t=new nr;t.partId=this.partId,t.parameterIndex=this.parameterIndex,t.partIndex=this.partIndex,t.link=new se;for(let e=this.link.begin();e.notEqual(this.link.end());e.increment())t.link.pushBack(e.ptr().clone());return t}}var or,lr,ur;(t=>{t.CubismPose=ar,t.PartData=nr})(or||(or={}));class hr{constructor(t=!1,e=!1){this.isOverridden=t,this.isParameterRepeated=e}}class dr{constructor(t=!1,e=new Me){this.isOverridden=t,this.color=e}get isOverwritten(){return this.isOverridden}}class gr{constructor(t=!1,e=new Me){this.isOverridden=t,this.color=e}get isOverwritten(){return this.isOverridden}}class cr{constructor(t=!1,e=!1){this.isOverridden=t,this.isCulling=e}get isOverwritten(){return this.isOverridden}}class pr{update(){this._model.update(),this._model.drawables.resetDynamicFlags()}getPixelsPerUnit(){return null==this._model?0:this._model.canvasinfo.PixelsPerUnit}getCanvasWidth(){return null==this._model?0:this._model.canvasinfo.CanvasWidth/this._model.canvasinfo.PixelsPerUnit}getCanvasHeight(){return null==this._model?0:this._model.canvasinfo.CanvasHeight/this._model.canvasinfo.PixelsPerUnit}saveParameters(){const t=this._model.parameters.count,e=this._savedParameters.getSize();for(let i=0;i<t;++i)i<e?this._savedParameters.set(i,this._parameterValues[i]):this._savedParameters.pushBack(this._parameterValues[i])}getMultiplyColor(t){if(this.getOverrideFlagForModelMultiplyColors()||this.getOverrideFlagForDrawableMultiplyColors(t))return this._userMultiplyColors.at(t).color;return this.getDrawableMultiplyColor(t)}getScreenColor(t){if(this.getOverrideFlagForModelScreenColors()||this.getOverrideFlagForDrawableScreenColors(t))return this._userScreenColors.at(t).color;return this.getDrawableScreenColor(t)}setMultiplyColorByTextureColor(t,e){this.setMultiplyColorByRGBA(t,e.r,e.g,e.b,e.a)}setMultiplyColorByRGBA(t,e,i,s,r=1){this._userMultiplyColors.at(t).color.r=e,this._userMultiplyColors.at(t).color.g=i,this._userMultiplyColors.at(t).color.b=s,this._userMultiplyColors.at(t).color.a=r}setScreenColorByTextureColor(t,e){this.setScreenColorByRGBA(t,e.r,e.g,e.b,e.a)}setScreenColorByRGBA(t,e,i,s,r=1){this._userScreenColors.at(t).color.r=e,this._userScreenColors.at(t).color.g=i,this._userScreenColors.at(t).color.b=s,this._userScreenColors.at(t).color.a=r}getPartMultiplyColor(t){return this._userPartMultiplyColors.at(t).color}getPartScreenColor(t){return this._userPartScreenColors.at(t).color}setPartColor(t,e,i,s,r,a,n){if(a.at(t).color.r=e,a.at(t).color.g=i,a.at(t).color.b=s,a.at(t).color.a=r,a.at(t).isOverridden)for(let o=0;o<this._partChildDrawables.at(t).getSize();++o){const a=this._partChildDrawables.at(t).at(o);n.at(a).color.r=e,n.at(a).color.g=i,n.at(a).color.b=s,n.at(a).color.a=r}}setPartMultiplyColorByTextureColor(t,e){this.setPartMultiplyColorByRGBA(t,e.r,e.g,e.b,e.a)}setPartMultiplyColorByRGBA(t,e,i,s,r){this.setPartColor(t,e,i,s,r,this._userPartMultiplyColors,this._userMultiplyColors)}setPartScreenColorByTextureColor(t,e){this.setPartScreenColorByRGBA(t,e.r,e.g,e.b,e.a)}setPartScreenColorByRGBA(t,e,i,s,r){this.setPartColor(t,e,i,s,r,this._userPartScreenColors,this._userScreenColors)}getOverrideFlagForModelParameterRepeat(){return this._isOverriddenParameterRepeat}setOverrideFlagForModelParameterRepeat(t){this._isOverriddenParameterRepeat=t}getOverrideFlagForParameterRepeat(t){return this._userParameterRepeatDataList.at(t).isOverridden}setOverrideFlagForParameterRepeat(t,e){this._userParameterRepeatDataList.at(t).isOverridden=e}getRepeatFlagForParameterRepeat(t){return this._userParameterRepeatDataList.at(t).isParameterRepeated}setRepeatFlagForParameterRepeat(t,e){this._userParameterRepeatDataList.at(t).isParameterRepeated=e}getOverwriteFlagForModelMultiplyColors(){return Be("getOverwriteFlagForModelMultiplyColors() is a deprecated function. Please use getOverrideFlagForModelMultiplyColors()."),this.getOverrideFlagForModelMultiplyColors()}getOverrideFlagForModelMultiplyColors(){return this._isOverriddenModelMultiplyColors}getOverwriteFlagForModelScreenColors(){return Be("getOverwriteFlagForModelScreenColors() is a deprecated function. Please use getOverrideFlagForModelScreenColors()."),this.getOverrideFlagForModelScreenColors()}getOverrideFlagForModelScreenColors(){return this._isOverriddenModelScreenColors}setOverwriteFlagForModelMultiplyColors(t){Be("setOverwriteFlagForModelMultiplyColors(value: boolean) is a deprecated function. Please use setOverrideFlagForModelMultiplyColors(value: boolean)."),this.setOverrideFlagForModelMultiplyColors(t)}setOverrideFlagForModelMultiplyColors(t){this._isOverriddenModelMultiplyColors=t}setOverwriteFlagForModelScreenColors(t){Be("setOverwriteFlagForModelScreenColors(value: boolean) is a deprecated function. Please use setOverrideFlagForModelScreenColors(value: boolean)."),this.setOverrideFlagForModelScreenColors(t)}setOverrideFlagForModelScreenColors(t){this._isOverriddenModelScreenColors=t}getOverwriteFlagForDrawableMultiplyColors(t){return Be("getOverwriteFlagForDrawableMultiplyColors(drawableindex: number) is a deprecated function. Please use getOverrideFlagForDrawableMultiplyColors(drawableindex: number)."),this.getOverrideFlagForDrawableMultiplyColors(t)}getOverrideFlagForDrawableMultiplyColors(t){return this._userMultiplyColors.at(t).isOverridden}getOverwriteFlagForDrawableScreenColors(t){return Be("getOverwriteFlagForDrawableScreenColors(drawableindex: number) is a deprecated function. Please use getOverrideFlagForDrawableScreenColors(drawableindex: number)."),this.getOverrideFlagForDrawableScreenColors(t)}getOverrideFlagForDrawableScreenColors(t){return this._userScreenColors.at(t).isOverridden}setOverwriteFlagForDrawableMultiplyColors(t,e){Be("setOverwriteFlagForDrawableMultiplyColors(drawableindex: number, value: boolean) is a deprecated function. Please use setOverrideFlagForDrawableMultiplyColors(drawableindex: number, value: boolean)."),this.setOverrideFlagForDrawableMultiplyColors(t,e)}setOverrideFlagForDrawableMultiplyColors(t,e){this._userMultiplyColors.at(t).isOverridden=e}setOverwriteFlagForDrawableScreenColors(t,e){Be("setOverwriteFlagForDrawableScreenColors(drawableindex: number, value: boolean) is a deprecated function. Please use setOverrideFlagForDrawableScreenColors(drawableindex: number, value: boolean)."),this.setOverrideFlagForDrawableScreenColors(t,e)}setOverrideFlagForDrawableScreenColors(t,e){this._userScreenColors.at(t).isOverridden=e}getOverwriteColorForPartMultiplyColors(t){return Be("getOverwriteColorForPartMultiplyColors(partIndex: number) is a deprecated function. Please use getOverrideColorForPartMultiplyColors(partIndex: number)."),this.getOverrideColorForPartMultiplyColors(t)}getOverrideColorForPartMultiplyColors(t){return this._userPartMultiplyColors.at(t).isOverridden}getOverwriteColorForPartScreenColors(t){return Be("getOverwriteColorForPartScreenColors(partIndex: number) is a deprecated function. Please use getOverrideColorForPartScreenColors(partIndex: number)."),this.getOverrideColorForPartScreenColors(t)}getOverrideColorForPartScreenColors(t){return this._userPartScreenColors.at(t).isOverridden}setOverwriteColorForPartColors(t,e,i,s){Be("setOverwriteColorForPartColors(partIndex: number, value: boolean, partColors: csmVector<PartColorData>, drawableColors: csmVector<DrawableColorData>) is a deprecated function. Please use setOverrideColorForPartColors(partIndex: number, value: boolean, partColors: csmVector<PartColorData>, drawableColors: csmVector<DrawableColorData>)."),this.setOverrideColorForPartColors(t,e,i,s)}setOverrideColorForPartColors(t,e,i,s){i.at(t).isOverridden=e;for(let r=0;r<this._partChildDrawables.at(t).getSize();++r){const a=this._partChildDrawables.at(t).at(r);s.at(a).isOverridden=e,e&&(s.at(a).color.r=i.at(t).color.r,s.at(a).color.g=i.at(t).color.g,s.at(a).color.b=i.at(t).color.b,s.at(a).color.a=i.at(t).color.a)}}setOverwriteColorForPartMultiplyColors(t,e){Be("setOverwriteColorForPartMultiplyColors(partIndex: number, value: boolean) is a deprecated function. Please use setOverrideColorForPartMultiplyColors(partIndex: number, value: boolean)."),this.setOverrideColorForPartMultiplyColors(t,e)}setOverrideColorForPartMultiplyColors(t,e){this._userPartMultiplyColors.at(t).isOverridden=e,this.setOverrideColorForPartColors(t,e,this._userPartMultiplyColors,this._userMultiplyColors)}setOverwriteColorForPartScreenColors(t,e){Be("setOverwriteColorForPartScreenColors(partIndex: number, value: boolean) is a deprecated function. Please use setOverrideColorForPartScreenColors(partIndex: number, value: boolean)."),this.setOverrideColorForPartScreenColors(t,e)}setOverrideColorForPartScreenColors(t,e){this._userPartScreenColors.at(t).isOverridden=e,this.setOverrideColorForPartColors(t,e,this._userPartScreenColors,this._userScreenColors)}getDrawableCulling(t){if(this.getOverrideFlagForModelCullings()||this.getOverrideFlagForDrawableCullings(t))return this._userCullings.at(t).isCulling;const e=this._model.drawables.constantFlags;return!Live2DCubismCore.Utils.hasIsDoubleSidedBit(e[t])}setDrawableCulling(t,e){this._userCullings.at(t).isCulling=e}getOverwriteFlagForModelCullings(){return Be("getOverwriteFlagForModelCullings() is a deprecated function. Please use getOverrideFlagForModelCullings()."),this.getOverrideFlagForModelCullings()}getOverrideFlagForModelCullings(){return this._isOverriddenCullings}setOverwriteFlagForModelCullings(t){Be("setOverwriteFlagForModelCullings(isOverriddenCullings: boolean) is a deprecated function. Please use setOverrideFlagForModelCullings(isOverriddenCullings: boolean)."),this.setOverrideFlagForModelCullings(t)}setOverrideFlagForModelCullings(t){this._isOverriddenCullings=t}getOverwriteFlagForDrawableCullings(t){return Be("getOverwriteFlagForDrawableCullings(drawableIndex: number) is a deprecated function. Please use getOverrideFlagForDrawableCullings(drawableIndex: number)."),this.getOverrideFlagForDrawableCullings(t)}getOverrideFlagForDrawableCullings(t){return this._userCullings.at(t).isOverridden}setOverwriteFlagForDrawableCullings(t,e){Be("setOverwriteFlagForDrawableCullings(drawableIndex: number, isOverriddenCullings: boolean) is a deprecated function. Please use setOverrideFlagForDrawableCullings(drawableIndex: number, isOverriddenCullings: boolean)."),this.setOverrideFlagForDrawableCullings(t,e)}setOverrideFlagForDrawableCullings(t,e){this._userCullings.at(t).isOverridden=e}getModelOapcity(){return this._modelOpacity}setModelOapcity(t){this._modelOpacity=t}getModel(){return this._model}getPartIndex(t){let e;const i=this._model.parts.count;for(e=0;e<i;++e)if(t==this._partIds.at(e))return e;return this._notExistPartId.isExist(t)?this._notExistPartId.getValue(t):(e=i+this._notExistPartId.getSize(),this._notExistPartId.setValue(t,e),this._notExistPartOpacities.appendKey(e),e)}getPartId(t){const e=this._model.parts.ids[t];return ti.getIdManager().getId(e)}getPartCount(){return this._model.parts.count}getPartParentPartIndices(){return this._model.parts.parentIndices}setPartOpacityByIndex(t,e){this._notExistPartOpacities.isExist(t)?this._notExistPartOpacities.setValue(t,e):(ve(0<=t&&t<this.getPartCount()),this._partOpacities[t]=e)}setPartOpacityById(t,e){const i=this.getPartIndex(t);i<0||this.setPartOpacityByIndex(i,e)}getPartOpacityByIndex(t){return this._notExistPartOpacities.isExist(t)?this._notExistPartOpacities.getValue(t):(ve(0<=t&&t<this.getPartCount()),this._partOpacities[t])}getPartOpacityById(t){const e=this.getPartIndex(t);return e<0?0:this.getPartOpacityByIndex(e)}getParameterIndex(t){let e;const i=this._model.parameters.count;for(e=0;e<i;++e)if(t==this._parameterIds.at(e))return e;return this._notExistParameterId.isExist(t)?this._notExistParameterId.getValue(t):(e=this._model.parameters.count+this._notExistParameterId.getSize(),this._notExistParameterId.setValue(t,e),this._notExistParameterValues.appendKey(e),e)}getParameterCount(){return this._model.parameters.count}getParameterType(t){return this._model.parameters.types[t]}getParameterMaximumValue(t){return this._model.parameters.maximumValues[t]}getParameterMinimumValue(t){return this._model.parameters.minimumValues[t]}getParameterDefaultValue(t){return this._model.parameters.defaultValues[t]}getParameterId(t){return ti.getIdManager().getId(this._model.parameters.ids[t])}getParameterValueByIndex(t){return this._notExistParameterValues.isExist(t)?this._notExistParameterValues.getValue(t):(ve(0<=t&&t<this.getParameterCount()),this._parameterValues[t])}getParameterValueById(t){const e=this.getParameterIndex(t);return this.getParameterValueByIndex(e)}setParameterValueByIndex(t,e,i=1){this._notExistParameterValues.isExist(t)?this._notExistParameterValues.setValue(t,1==i?e:this._notExistParameterValues.getValue(t)*(1-i)+e*i):(ve(0<=t&&t<this.getParameterCount()),e=this.isRepeat(t)?this.getParameterRepeatValue(t,e):this.getParameterClampValue(t,e),this._parameterValues[t]=1==i?e:this._parameterValues[t]=this._parameterValues[t]*(1-i)+e*i)}setParameterValueById(t,e,i=1){const s=this.getParameterIndex(t);this.setParameterValueByIndex(s,e,i)}addParameterValueByIndex(t,e,i=1){this.setParameterValueByIndex(t,this.getParameterValueByIndex(t)+e*i)}addParameterValueById(t,e,i=1){const s=this.getParameterIndex(t);this.addParameterValueByIndex(s,e,i)}isRepeat(t){if(this._notExistParameterValues.isExist(t))return!1;let e;return ve(0<=t&&t<this.getParameterCount()),e=this._isOverriddenParameterRepeat||this._userParameterRepeatDataList.at(t).isOverridden?this._userParameterRepeatDataList.at(t).isParameterRepeated:0!=this._model.parameters.repeats[t],e}getParameterRepeatValue(t,e){if(this._notExistParameterValues.isExist(t))return e;ve(0<=t&&t<this.getParameterCount());const i=this._model.parameters.maximumValues[t],s=this._model.parameters.minimumValues[t],r=i-s;if(i<e){const t=ni.mod(e-i,r);e=Number.isNaN(t)?i:s+t}if(e<s){const t=ni.mod(s-e,r);e=Number.isNaN(t)?s:i-t}return e}getParameterClampValue(t,e){if(this._notExistParameterValues.isExist(t))return e;ve(0<=t&&t<this.getParameterCount());const i=this._model.parameters.maximumValues[t],s=this._model.parameters.minimumValues[t];return ni.clamp(e,s,i)}getParameterRepeats(t){return 0!=this._model.parameters.repeats[t]}multiplyParameterValueById(t,e,i=1){const s=this.getParameterIndex(t);this.multiplyParameterValueByIndex(s,e,i)}multiplyParameterValueByIndex(t,e,i=1){this.setParameterValueByIndex(t,this.getParameterValueByIndex(t)*(1+(e-1)*i))}getDrawableIndex(t){const e=this._model.drawables.count;for(let i=0;i<e;++i)if(this._drawableIds.at(i)==t)return i;return-1}getDrawableCount(){return this._model.drawables.count}getDrawableId(t){const e=this._model.drawables.ids;return ti.getIdManager().getId(e[t])}getDrawableRenderOrders(){return this._model.drawables.renderOrders}getDrawableTextureIndices(t){return this.getDrawableTextureIndex(t)}getDrawableTextureIndex(t){return this._model.drawables.textureIndices[t]}getDrawableDynamicFlagVertexPositionsDidChange(t){const e=this._model.drawables.dynamicFlags;return Live2DCubismCore.Utils.hasVertexPositionsDidChangeBit(e[t])}getDrawableVertexIndexCount(t){return this._model.drawables.indexCounts[t]}getDrawableVertexCount(t){return this._model.drawables.vertexCounts[t]}getDrawableVertices(t){return this.getDrawableVertexPositions(t)}getDrawableVertexIndices(t){return this._model.drawables.indices[t]}getDrawableVertexPositions(t){return this._model.drawables.vertexPositions[t]}getDrawableVertexUvs(t){return this._model.drawables.vertexUvs[t]}getDrawableOpacity(t){return this._model.drawables.opacities[t]}getDrawableMultiplyColor(t){const e=this._model.drawables.multiplyColors,i=4*t,s=new Me;return s.r=e[i],s.g=e[i+1],s.b=e[i+2],s.a=e[i+3],s}getDrawableScreenColor(t){const e=this._model.drawables.screenColors,i=4*t,s=new Me;return s.r=e[i],s.g=e[i+1],s.b=e[i+2],s.a=e[i+3],s}getDrawableParentPartIndex(t){return this._model.drawables.parentPartIndices[t]}getDrawableBlendMode(t){const e=this._model.drawables.constantFlags;return Live2DCubismCore.Utils.hasBlendAdditiveBit(e[t])?xe.CubismBlendMode_Additive:Live2DCubismCore.Utils.hasBlendMultiplicativeBit(e[t])?xe.CubismBlendMode_Multiplicative:xe.CubismBlendMode_Normal}getDrawableInvertedMaskBit(t){const e=this._model.drawables.constantFlags;return Live2DCubismCore.Utils.hasIsInvertedMaskBit(e[t])}getDrawableMasks(){return this._model.drawables.masks}getDrawableMaskCounts(){return this._model.drawables.maskCounts}isUsingMasking(){for(let t=0;t<this._model.drawables.count;++t)if(!(this._model.drawables.maskCounts[t]<=0))return!0;return!1}getDrawableDynamicFlagIsVisible(t){const e=this._model.drawables.dynamicFlags;return Live2DCubismCore.Utils.hasIsVisibleBit(e[t])}getDrawableDynamicFlagVisibilityDidChange(t){const e=this._model.drawables.dynamicFlags;return Live2DCubismCore.Utils.hasVisibilityDidChangeBit(e[t])}getDrawableDynamicFlagOpacityDidChange(t){const e=this._model.drawables.dynamicFlags;return Live2DCubismCore.Utils.hasOpacityDidChangeBit(e[t])}getDrawableDynamicFlagRenderOrderDidChange(t){const e=this._model.drawables.dynamicFlags;return Live2DCubismCore.Utils.hasRenderOrderDidChangeBit(e[t])}getDrawableDynamicFlagBlendColorDidChange(t){const e=this._model.drawables.dynamicFlags;return Live2DCubismCore.Utils.hasBlendColorDidChangeBit(e[t])}loadParameters(){let t=this._model.parameters.count;const e=this._savedParameters.getSize();t>e&&(t=e);for(let i=0;i<t;++i)this._parameterValues[i]=this._savedParameters.at(i)}initialize(){ve(this._model),this._parameterValues=this._model.parameters.values,this._partOpacities=this._model.parts.opacities,this._parameterMaximumValues=this._model.parameters.maximumValues,this._parameterMinimumValues=this._model.parameters.minimumValues;{const t=this._model.parameters.ids,e=this._model.parameters.count;this._parameterIds.prepareCapacity(e),this._userParameterRepeatDataList.prepareCapacity(e);for(let i=0;i<e;++i)this._parameterIds.pushBack(ti.getIdManager().getId(t[i])),this._userParameterRepeatDataList.pushBack(new hr(!1,!1))}const t=this._model.parts.count;{const e=this._model.parts.ids;this._partIds.prepareCapacity(t);for(let i=0;i<t;++i)this._partIds.pushBack(ti.getIdManager().getId(e[i]));this._userPartMultiplyColors.prepareCapacity(t),this._userPartScreenColors.prepareCapacity(t),this._partChildDrawables.prepareCapacity(t)}{const e=this._model.drawables.ids,i=this._model.drawables.count;this._userMultiplyColors.prepareCapacity(i),this._userScreenColors.prepareCapacity(i),this._userCullings.prepareCapacity(i);const s=new cr(!1,!1);for(let r=0;r<t;++r){const t=new Me(1,1,1,1),e=new Me(0,0,0,1),s=new gr(!1,t),a=new gr(!1,e);this._userPartMultiplyColors.pushBack(s),this._userPartScreenColors.pushBack(a),this._partChildDrawables.pushBack(new se),this._partChildDrawables.at(r).prepareCapacity(i)}for(let t=0;t<i;++t){const i=new Me(1,1,1,1),r=new Me(0,0,0,1),a=new dr(!1,i),n=new dr(!1,r);this._drawableIds.pushBack(ti.getIdManager().getId(e[t])),this._userMultiplyColors.pushBack(a),this._userScreenColors.pushBack(n),this._userCullings.pushBack(s);const o=this.getDrawableParentPartIndex(t);o>=0&&this._partChildDrawables.at(o).pushBack(t)}}}constructor(t){this._model=t,this._parameterValues=null,this._parameterMaximumValues=null,this._parameterMinimumValues=null,this._partOpacities=null,this._savedParameters=new se,this._parameterIds=new se,this._drawableIds=new se,this._partIds=new se,this._isOverriddenParameterRepeat=!0,this._isOverriddenModelMultiplyColors=!1,this._isOverriddenModelScreenColors=!1,this._isOverriddenCullings=!1,this._modelOpacity=1,this._userParameterRepeatDataList=new se,this._userMultiplyColors=new se,this._userScreenColors=new se,this._userCullings=new se,this._userPartMultiplyColors=new se,this._userPartScreenColors=new se,this._partChildDrawables=new se,this._notExistPartId=new Ve,this._notExistParameterId=new Ve,this._notExistParameterValues=new Ve,this._notExistPartOpacities=new Ve}release(){this._model.release(),this._model=null}}(t=>{t.CubismModel=pr})(lr||(lr={}));class mr{static create(t,e){let i=null;if(e){if(!this.hasMocConsistency(t))return we("Inconsistent MOC3."),i}const s=Live2DCubismCore.Moc.fromArrayBuffer(t);return s&&(i=new mr(s),i._mocVersion=Live2DCubismCore.Version.csmGetMocVersion(s,t)),i}static delete(t){t._moc._release(),t._moc=null,t=null}createModel(){let t=null;const e=Live2DCubismCore.Model.fromMoc(this._moc);return e&&(t=new pr(e),t.initialize(),++this._modelCount),t}deleteModel(t){null!=t&&(t.release(),t=null,--this._modelCount)}constructor(t){this._moc=t,this._modelCount=0,this._mocVersion=0}release(){ve(0==this._modelCount),this._moc._release(),this._moc=null}getLatestMocVersion(){return Live2DCubismCore.Version.csmGetLatestMocVersion()}getMocVersion(){return this._mocVersion}static hasMocConsistency(t){return 1===Live2DCubismCore.Moc.prototype.hasMocConsistency(t)}}(t=>{t.CubismMoc=mr})(ur||(ur={}));var _r,fr=(t=>(t[t.CubismPhysicsTargetType_Parameter=0]="CubismPhysicsTargetType_Parameter",t))(fr||{}),yr=(t=>(t[t.CubismPhysicsSource_X=0]="CubismPhysicsSource_X",t[t.CubismPhysicsSource_Y=1]="CubismPhysicsSource_Y",t[t.CubismPhysicsSource_Angle=2]="CubismPhysicsSource_Angle",t))(yr||{});class xr{constructor(){this.gravity=new ri(0,0),this.wind=new ri(0,0)}}class Mr{}class Cr{}class Sr{constructor(){this.initialPosition=new ri(0,0),this.position=new ri(0,0),this.lastPosition=new ri(0,0),this.lastGravity=new ri(0,0),this.force=new ri(0,0),this.velocity=new ri(0,0)}}class vr{constructor(){this.normalizationPosition=new Cr,this.normalizationAngle=new Cr}}class br{constructor(){this.source=new Mr}}class Pr{constructor(){this.destination=new Mr,this.translationScale=new ri(0,0)}}class Br{constructor(){this.settings=new se,this.inputs=new se,this.outputs=new se,this.particles=new se,this.gravity=new ri(0,0),this.wind=new ri(0,0),this.fps=0}}(t=>{t.CubismPhysicsInput=br,t.CubismPhysicsNormalization=Cr,t.CubismPhysicsOutput=Pr,t.CubismPhysicsParameter=Mr,t.CubismPhysicsParticle=Sr,t.CubismPhysicsRig=Br,t.CubismPhysicsSource=yr,t.CubismPhysicsSubRig=vr,t.CubismPhysicsTargetType=fr,t.PhysicsJsonEffectiveForces=xr})(_r||(_r={}));const wr="Position",Ir="Angle",Fr="Type",Er="Meta",Lr="EffectiveForces",Vr="Gravity",Tr="Wind",Rr="PhysicsSettings",Dr="Normalization",Ar="Minimum",Or="Maximum",kr="Default",Nr="Reflect",Ur="Weight",zr="Input",jr="Output",Gr="Vertices";class Xr{constructor(t,e){this._json=ke.create(t,e)}release(){ke.delete(this._json)}getGravity(){const t=new ri(0,0);return t.x=this._json.getRoot().getValueByString(Er).getValueByString(Lr).getValueByString(Vr).getValueByString("X").toFloat(),t.y=this._json.getRoot().getValueByString(Er).getValueByString(Lr).getValueByString(Vr).getValueByString("Y").toFloat(),t}getWind(){const t=new ri(0,0);return t.x=this._json.getRoot().getValueByString(Er).getValueByString(Lr).getValueByString(Tr).getValueByString("X").toFloat(),t.y=this._json.getRoot().getValueByString(Er).getValueByString(Lr).getValueByString(Tr).getValueByString("Y").toFloat(),t}getFps(){return this._json.getRoot().getValueByString(Er).getValueByString("Fps").toFloat(0)}getSubRigCount(){return this._json.getRoot().getValueByString(Er).getValueByString("PhysicsSettingCount").toInt()}getTotalInputCount(){return this._json.getRoot().getValueByString(Er).getValueByString("TotalInputCount").toInt()}getTotalOutputCount(){return this._json.getRoot().getValueByString(Er).getValueByString("TotalOutputCount").toInt()}getVertexCount(){return this._json.getRoot().getValueByString(Er).getValueByString("VertexCount").toInt()}getNormalizationPositionMinimumValue(t){return this._json.getRoot().getValueByString(Rr).getValueByIndex(t).getValueByString(Dr).getValueByString(wr).getValueByString(Ar).toFloat()}getNormalizationPositionMaximumValue(t){return this._json.getRoot().getValueByString(Rr).getValueByIndex(t).getValueByString(Dr).getValueByString(wr).getValueByString(Or).toFloat()}getNormalizationPositionDefaultValue(t){return this._json.getRoot().getValueByString(Rr).getValueByIndex(t).getValueByString(Dr).getValueByString(wr).getValueByString(kr).toFloat()}getNormalizationAngleMinimumValue(t){return this._json.getRoot().getValueByString(Rr).getValueByIndex(t).getValueByString(Dr).getValueByString(Ir).getValueByString(Ar).toFloat()}getNormalizationAngleMaximumValue(t){return this._json.getRoot().getValueByString(Rr).getValueByIndex(t).getValueByString(Dr).getValueByString(Ir).getValueByString(Or).toFloat()}getNormalizationAngleDefaultValue(t){return this._json.getRoot().getValueByString(Rr).getValueByIndex(t).getValueByString(Dr).getValueByString(Ir).getValueByString(kr).toFloat()}getInputCount(t){return this._json.getRoot().getValueByString(Rr).getValueByIndex(t).getValueByString(zr).getVector().getSize()}getInputWeight(t,e){return this._json.getRoot().getValueByString(Rr).getValueByIndex(t).getValueByString(zr).getValueByIndex(e).getValueByString(Ur).toFloat()}getInputReflect(t,e){return this._json.getRoot().getValueByString(Rr).getValueByIndex(t).getValueByString(zr).getValueByIndex(e).getValueByString(Nr).toBoolean()}getInputType(t,e){return this._json.getRoot().getValueByString(Rr).getValueByIndex(t).getValueByString(zr).getValueByIndex(e).getValueByString(Fr).getRawString()}getInputSourceId(t,e){return ti.getIdManager().getId(this._json.getRoot().getValueByString(Rr).getValueByIndex(t).getValueByString(zr).getValueByIndex(e).getValueByString("Source").getValueByString("Id").getRawString())}getOutputCount(t){return this._json.getRoot().getValueByString(Rr).getValueByIndex(t).getValueByString(jr).getVector().getSize()}getOutputVertexIndex(t,e){return this._json.getRoot().getValueByString(Rr).getValueByIndex(t).getValueByString(jr).getValueByIndex(e).getValueByString("VertexIndex").toInt()}getOutputAngleScale(t,e){return this._json.getRoot().getValueByString(Rr).getValueByIndex(t).getValueByString(jr).getValueByIndex(e).getValueByString("Scale").toFloat()}getOutputWeight(t,e){return this._json.getRoot().getValueByString(Rr).getValueByIndex(t).getValueByString(jr).getValueByIndex(e).getValueByString(Ur).toFloat()}getOutputDestinationId(t,e){return ti.getIdManager().getId(this._json.getRoot().getValueByString(Rr).getValueByIndex(t).getValueByString(jr).getValueByIndex(e).getValueByString("Destination").getValueByString("Id").getRawString())}getOutputType(t,e){return this._json.getRoot().getValueByString(Rr).getValueByIndex(t).getValueByString(jr).getValueByIndex(e).getValueByString(Fr).getRawString()}getOutputReflect(t,e){return this._json.getRoot().getValueByString(Rr).getValueByIndex(t).getValueByString(jr).getValueByIndex(e).getValueByString(Nr).toBoolean()}getParticleCount(t){return this._json.getRoot().getValueByString(Rr).getValueByIndex(t).getValueByString(Gr).getVector().getSize()}getParticleMobility(t,e){return this._json.getRoot().getValueByString(Rr).getValueByIndex(t).getValueByString(Gr).getValueByIndex(e).getValueByString("Mobility").toFloat()}getParticleDelay(t,e){return this._json.getRoot().getValueByString(Rr).getValueByIndex(t).getValueByString(Gr).getValueByIndex(e).getValueByString("Delay").toFloat()}getParticleAcceleration(t,e){return this._json.getRoot().getValueByString(Rr).getValueByIndex(t).getValueByString(Gr).getValueByIndex(e).getValueByString("Acceleration").toFloat()}getParticleRadius(t,e){return this._json.getRoot().getValueByString(Rr).getValueByIndex(t).getValueByString(Gr).getValueByIndex(e).getValueByString("Radius").toFloat()}getParticlePosition(t,e){const i=new ri(0,0);return i.x=this._json.getRoot().getValueByString(Rr).getValueByIndex(t).getValueByString(Gr).getValueByIndex(e).getValueByString(wr).getValueByString("X").toFloat(),i.y=this._json.getRoot().getValueByString(Rr).getValueByIndex(t).getValueByString(Gr).getValueByIndex(e).getValueByString(wr).getValueByString("Y").toFloat(),i}}var Hr;(t=>{t.CubismPhysicsJson=Xr})(Hr||(Hr={}));const Yr="Angle";class qr{static create(t,e){const i=new qr;return i.parse(t,e),i._physicsRig.gravity.y=0,i}static delete(t){null!=t&&(t.release(),t=null)}parse(t,e){this._physicsRig=new Br;let i=new Xr(t,e);this._physicsRig.gravity=i.getGravity(),this._physicsRig.wind=i.getWind(),this._physicsRig.subRigCount=i.getSubRigCount(),this._physicsRig.fps=i.getFps(),this._physicsRig.settings.updateSize(this._physicsRig.subRigCount,vr,!0),this._physicsRig.inputs.updateSize(i.getTotalInputCount(),br,!0),this._physicsRig.outputs.updateSize(i.getTotalOutputCount(),Pr,!0),this._physicsRig.particles.updateSize(i.getVertexCount(),Sr,!0),this._currentRigOutputs.clear(),this._previousRigOutputs.clear();let s=0,r=0,a=0;for(let n=0;n<this._physicsRig.settings.getSize();++n){this._physicsRig.settings.at(n).normalizationPosition.minimum=i.getNormalizationPositionMinimumValue(n),this._physicsRig.settings.at(n).normalizationPosition.maximum=i.getNormalizationPositionMaximumValue(n),this._physicsRig.settings.at(n).normalizationPosition.defalut=i.getNormalizationPositionDefaultValue(n),this._physicsRig.settings.at(n).normalizationAngle.minimum=i.getNormalizationAngleMinimumValue(n),this._physicsRig.settings.at(n).normalizationAngle.maximum=i.getNormalizationAngleMaximumValue(n),this._physicsRig.settings.at(n).normalizationAngle.defalut=i.getNormalizationAngleDefaultValue(n),this._physicsRig.settings.at(n).inputCount=i.getInputCount(n),this._physicsRig.settings.at(n).baseInputIndex=s;for(let r=0;r<this._physicsRig.settings.at(n).inputCount;++r)this._physicsRig.inputs.at(s+r).sourceParameterIndex=-1,this._physicsRig.inputs.at(s+r).weight=i.getInputWeight(n,r),this._physicsRig.inputs.at(s+r).reflect=i.getInputReflect(n,r),"X"==i.getInputType(n,r)?(this._physicsRig.inputs.at(s+r).type=yr.CubismPhysicsSource_X,this._physicsRig.inputs.at(s+r).getNormalizedParameterValue=$r):"Y"==i.getInputType(n,r)?(this._physicsRig.inputs.at(s+r).type=yr.CubismPhysicsSource_Y,this._physicsRig.inputs.at(s+r).getNormalizedParameterValue=Zr):i.getInputType(n,r)==Yr&&(this._physicsRig.inputs.at(s+r).type=yr.CubismPhysicsSource_Angle,this._physicsRig.inputs.at(s+r).getNormalizedParameterValue=Kr),this._physicsRig.inputs.at(s+r).source.targetType=fr.CubismPhysicsTargetType_Parameter,this._physicsRig.inputs.at(s+r).source.id=i.getInputSourceId(n,r);s+=this._physicsRig.settings.at(n).inputCount,this._physicsRig.settings.at(n).outputCount=i.getOutputCount(n),this._physicsRig.settings.at(n).baseOutputIndex=r;const t=new Jr;t.outputs.resize(this._physicsRig.settings.at(n).outputCount);const e=new Jr;e.outputs.resize(this._physicsRig.settings.at(n).outputCount);for(let s=0;s<this._physicsRig.settings.at(n).outputCount;++s)t.outputs.set(s,0),e.outputs.set(s,0),this._physicsRig.outputs.at(r+s).destinationParameterIndex=-1,this._physicsRig.outputs.at(r+s).vertexIndex=i.getOutputVertexIndex(n,s),this._physicsRig.outputs.at(r+s).angleScale=i.getOutputAngleScale(n,s),this._physicsRig.outputs.at(r+s).weight=i.getOutputWeight(n,s),this._physicsRig.outputs.at(r+s).destination.targetType=fr.CubismPhysicsTargetType_Parameter,this._physicsRig.outputs.at(r+s).destination.id=i.getOutputDestinationId(n,s),"X"==i.getOutputType(n,s)?(this._physicsRig.outputs.at(r+s).type=yr.CubismPhysicsSource_X,this._physicsRig.outputs.at(r+s).getValue=Qr,this._physicsRig.outputs.at(r+s).getScale=sa):"Y"==i.getOutputType(n,s)?(this._physicsRig.outputs.at(r+s).type=yr.CubismPhysicsSource_Y,this._physicsRig.outputs.at(r+s).getValue=ta,this._physicsRig.outputs.at(r+s).getScale=ra):i.getOutputType(n,s)==Yr&&(this._physicsRig.outputs.at(r+s).type=yr.CubismPhysicsSource_Angle,this._physicsRig.outputs.at(r+s).getValue=ea,this._physicsRig.outputs.at(r+s).getScale=aa),this._physicsRig.outputs.at(r+s).reflect=i.getOutputReflect(n,s);this._currentRigOutputs.pushBack(t),this._previousRigOutputs.pushBack(e),r+=this._physicsRig.settings.at(n).outputCount,this._physicsRig.settings.at(n).particleCount=i.getParticleCount(n),this._physicsRig.settings.at(n).baseParticleIndex=a;for(let s=0;s<this._physicsRig.settings.at(n).particleCount;++s)this._physicsRig.particles.at(a+s).mobility=i.getParticleMobility(n,s),this._physicsRig.particles.at(a+s).delay=i.getParticleDelay(n,s),this._physicsRig.particles.at(a+s).acceleration=i.getParticleAcceleration(n,s),this._physicsRig.particles.at(a+s).radius=i.getParticleRadius(n,s),this._physicsRig.particles.at(a+s).position=i.getParticlePosition(n,s);a+=this._physicsRig.settings.at(n).particleCount}this.initialize(),i.release(),i=void 0,i=null}stabilization(t){var e,i,s,r;let a,n,o,l;const u=new ri;let h,d,g,c;const p=t.getModel().parameters.values,m=t.getModel().parameters.maximumValues,_=t.getModel().parameters.minimumValues,f=t.getModel().parameters.defaultValues;(null!=(i=null==(e=this._parameterCaches)?void 0:e.length)?i:0)<t.getParameterCount()&&(this._parameterCaches=new Float32Array(t.getParameterCount())),(null!=(r=null==(s=this._parameterInputCaches)?void 0:s.length)?r:0)<t.getParameterCount()&&(this._parameterInputCaches=new Float32Array(t.getParameterCount()));for(let y=0;y<t.getParameterCount();++y)this._parameterCaches[y]=p[y],this._parameterInputCaches[y]=p[y];for(let y=0;y<this._physicsRig.subRigCount;++y){a={angle:0},u.x=0,u.y=0,h=this._physicsRig.settings.at(y),d=this._physicsRig.inputs.get(h.baseInputIndex),g=this._physicsRig.outputs.get(h.baseOutputIndex),c=this._physicsRig.particles.get(h.baseParticleIndex);for(let e=0;e<h.inputCount;++e)n=d[e].weight/100,-1==d[e].sourceParameterIndex&&(d[e].sourceParameterIndex=t.getParameterIndex(d[e].source.id)),d[e].getNormalizedParameterValue(u,a,p[d[e].sourceParameterIndex],_[d[e].sourceParameterIndex],m[d[e].sourceParameterIndex],f[d[e].sourceParameterIndex],h.normalizationPosition,h.normalizationAngle,d[e].reflect,n),this._parameterCaches[d[e].sourceParameterIndex]=p[d[e].sourceParameterIndex];o=ni.degreesToRadian(-a.angle),u.x=u.x*ni.cos(o)-u.y*ni.sin(o),u.y=u.x*ni.sin(o)+u.y*ni.cos(o),oa(c,h.particleCount,u,a.angle,this._options.wind,.001*h.normalizationPosition.maximum);for(let e=0;e<h.outputCount;++e){const i=g[e].vertexIndex;if(-1==g[e].destinationParameterIndex&&(g[e].destinationParameterIndex=t.getParameterIndex(g[e].destination.id)),i<1||i>=h.particleCount)continue;let s=new ri;s=c[i].position.substract(c[i-1].position),l=g[e].getValue(s,c,i,g[e].reflect,this._options.gravity),this._currentRigOutputs.at(y).outputs.set(e,l),this._previousRigOutputs.at(y).outputs.set(e,l);const r=g[e].destinationParameterIndex,a=!Float32Array.prototype.slice&&"subarray"in Float32Array.prototype?JSON.parse(JSON.stringify(p.subarray(r))):p.slice(r);la(a,_[r],m[r],l,g[e]);for(let t=r,e=0;t<this._parameterCaches.length;t++,e++)p[t]=this._parameterCaches[t]=a[e]}}}evaluate(t,e){var i,s,r,a;let n,o,l,u;const h=new ri;let d,g,c,p;if(0>=e)return;const m=t.getModel().parameters.values,_=t.getModel().parameters.maximumValues,f=t.getModel().parameters.minimumValues,y=t.getModel().parameters.defaultValues;let x;if(this._currentRemainTime+=e,this._currentRemainTime>5&&(this._currentRemainTime=0),(null!=(s=null==(i=this._parameterCaches)?void 0:i.length)?s:0)<t.getParameterCount()&&(this._parameterCaches=new Float32Array(t.getParameterCount())),(null!=(a=null==(r=this._parameterInputCaches)?void 0:r.length)?a:0)<t.getParameterCount()){this._parameterInputCaches=new Float32Array(t.getParameterCount());for(let e=0;e<t.getParameterCount();++e)this._parameterInputCaches[e]=m[e]}for(x=this._physicsRig.fps>0?1/this._physicsRig.fps:e;this._currentRemainTime>=x;){for(let t=0;t<this._physicsRig.subRigCount;++t){d=this._physicsRig.settings.at(t),c=this._physicsRig.outputs.get(d.baseOutputIndex);for(let e=0;e<d.outputCount;++e)this._previousRigOutputs.at(t).outputs.set(e,this._currentRigOutputs.at(t).outputs.at(e))}const e=x/this._currentRemainTime;for(let i=0;i<t.getParameterCount();++i)this._parameterCaches[i]=this._parameterInputCaches[i]*(1-e)+m[i]*e,this._parameterInputCaches[i]=this._parameterCaches[i];for(let i=0;i<this._physicsRig.subRigCount;++i){n={angle:0},h.x=0,h.y=0,d=this._physicsRig.settings.at(i),g=this._physicsRig.inputs.get(d.baseInputIndex),c=this._physicsRig.outputs.get(d.baseOutputIndex),p=this._physicsRig.particles.get(d.baseParticleIndex);for(let e=0;e<d.inputCount;++e)o=g[e].weight/100,-1==g[e].sourceParameterIndex&&(g[e].sourceParameterIndex=t.getParameterIndex(g[e].source.id)),g[e].getNormalizedParameterValue(h,n,this._parameterCaches[g[e].sourceParameterIndex],f[g[e].sourceParameterIndex],_[g[e].sourceParameterIndex],y[g[e].sourceParameterIndex],d.normalizationPosition,d.normalizationAngle,g[e].reflect,o);l=ni.degreesToRadian(-n.angle),h.x=h.x*ni.cos(l)-h.y*ni.sin(l),h.y=h.x*ni.sin(l)+h.y*ni.cos(l),na(p,d.particleCount,h,n.angle,this._options.wind,.001*d.normalizationPosition.maximum,x,5);for(let e=0;e<d.outputCount;++e){const s=c[e].vertexIndex;if(-1==c[e].destinationParameterIndex&&(c[e].destinationParameterIndex=t.getParameterIndex(c[e].destination.id)),s<1||s>=d.particleCount)continue;const r=new ri;r.x=p[s].position.x-p[s-1].position.x,r.y=p[s].position.y-p[s-1].position.y,u=c[e].getValue(r,p,s,c[e].reflect,this._options.gravity),this._currentRigOutputs.at(i).outputs.set(e,u);const a=c[e].destinationParameterIndex,n=!Float32Array.prototype.slice&&"subarray"in Float32Array.prototype?JSON.parse(JSON.stringify(this._parameterCaches.subarray(a))):this._parameterCaches.slice(a);la(n,f[a],_[a],u,c[e]);for(let t=a,e=0;t<this._parameterCaches.length;t++,e++)this._parameterCaches[t]=n[e]}}this._currentRemainTime-=x}const M=this._currentRemainTime/x;this.interpolate(t,M)}interpolate(t,e){let i,s;const r=t.getModel().parameters.values,a=t.getModel().parameters.maximumValues,n=t.getModel().parameters.minimumValues;for(let o=0;o<this._physicsRig.subRigCount;++o){s=this._physicsRig.settings.at(o),i=this._physicsRig.outputs.get(s.baseOutputIndex);for(let t=0;t<s.outputCount;++t){if(-1==i[t].destinationParameterIndex)continue;const s=i[t].destinationParameterIndex,l=!Float32Array.prototype.slice&&"subarray"in Float32Array.prototype?JSON.parse(JSON.stringify(r.subarray(s))):r.slice(s);la(l,n[s],a[s],this._previousRigOutputs.at(o).outputs.at(t)*(1-e)+this._currentRigOutputs.at(o).outputs.at(t)*e,i[t]);for(let t=s,e=0;t<r.length;t++,e++)r[t]=l[e]}}}setOptions(t){this._options=t}getOption(){return this._options}constructor(){this._physicsRig=null,this._options=new Wr,this._options.gravity.y=-1,this._options.gravity.x=0,this._options.wind.x=0,this._options.wind.y=0,this._currentRigOutputs=new se,this._previousRigOutputs=new se,this._currentRemainTime=0,this._parameterCaches=null,this._parameterInputCaches=null}release(){this._physicsRig=void 0,this._physicsRig=null}initialize(){let t,e,i;for(let s=0;s<this._physicsRig.subRigCount;++s){e=this._physicsRig.settings.at(s),t=this._physicsRig.particles.get(e.baseParticleIndex),t[0].initialPosition=new ri(0,0),t[0].lastPosition=new ri(t[0].initialPosition.x,t[0].initialPosition.y),t[0].lastGravity=new ri(0,-1),t[0].lastGravity.y*=-1,t[0].velocity=new ri(0,0),t[0].force=new ri(0,0);for(let s=1;s<e.particleCount;++s)i=new ri(0,0),i.y=t[s].radius,t[s].initialPosition=new ri(t[s-1].initialPosition.x+i.x,t[s-1].initialPosition.y+i.y),t[s].position=new ri(t[s].initialPosition.x,t[s].initialPosition.y),t[s].lastPosition=new ri(t[s].initialPosition.x,t[s].initialPosition.y),t[s].lastGravity=new ri(0,-1),t[s].lastGravity.y*=-1,t[s].velocity=new ri(0,0),t[s].force=new ri(0,0)}}}class Wr{constructor(){this.gravity=new ri(0,0),this.wind=new ri(0,0)}}class Jr{constructor(){this.outputs=new se(0)}}function $r(t,e,i,s,r,a,n,o,l,u){t.x+=ua(i,s,r,a,n.minimum,n.maximum,n.defalut,l)*u}function Zr(t,e,i,s,r,a,n,o,l,u){t.y+=ua(i,s,r,a,n.minimum,n.maximum,n.defalut,l)*u}function Kr(t,e,i,s,r,a,n,o,l,u){e.angle+=ua(i,s,r,a,o.minimum,o.maximum,o.defalut,l)*u}function Qr(t,e,i,s,r){let a=t.x;return s&&(a*=-1),a}function ta(t,e,i,s,r){let a=t.y;return s&&(a*=-1),a}function ea(t,e,i,s,r){let a;return r=i>=2?e[i-1].position.substract(e[i-2].position):r.multiplyByScaler(-1),a=ni.directionToRadian(r,t),s&&(a*=-1),a}function ia(t,e){return ni.min(t,e)+function(t,e){const i=ni.max(t,e),s=ni.min(t,e);return ni.abs(i-s)}(t,e)/2}function sa(t,e){return JSON.parse(JSON.stringify(t.x))}function ra(t,e){return JSON.parse(JSON.stringify(t.y))}function aa(t,e){return JSON.parse(JSON.stringify(e))}function na(t,e,i,s,r,a,n,o){let l,u,h=new ri(0,0),d=new ri(0,0),g=new ri(0,0),c=new ri(0,0);t[0].position=new ri(i.x,i.y);const p=ni.degreesToRadian(s),m=ni.radianToDirection(p);m.normalize();for(let _=1;_<e;++_)t[_].force=m.multiplyByScaler(t[_].acceleration).add(r),t[_].lastPosition=new ri(t[_].position.x,t[_].position.y),l=t[_].delay*n*30,h=t[_].position.substract(t[_-1].position),u=ni.directionToRadian(t[_].lastGravity,m)/o,h.x=ni.cos(u)*h.x-h.y*ni.sin(u),h.y=ni.sin(u)*h.x+h.y*ni.cos(u),t[_].position=t[_-1].position.add(h),d=t[_].velocity.multiplyByScaler(l),g=t[_].force.multiplyByScaler(l).multiplyByScaler(l),t[_].position=t[_].position.add(d).add(g),c=t[_].position.substract(t[_-1].position),c.normalize(),t[_].position=t[_-1].position.add(c.multiplyByScaler(t[_].radius)),ni.abs(t[_].position.x)<a&&(t[_].position.x=0),0!=l&&(t[_].velocity=t[_].position.substract(t[_].lastPosition),t[_].velocity=t[_].velocity.divisionByScalar(l),t[_].velocity=t[_].velocity.multiplyByScaler(t[_].mobility)),t[_].force=new ri(0,0),t[_].lastGravity=new ri(m.x,m.y)}function oa(t,e,i,s,r,a){let n=new ri(0,0);t[0].position=new ri(i.x,i.y);const o=ni.degreesToRadian(s),l=ni.radianToDirection(o);l.normalize();for(let u=1;u<e;++u)t[u].force=l.multiplyByScaler(t[u].acceleration).add(r),t[u].lastPosition=new ri(t[u].position.x,t[u].position.y),t[u].velocity=new ri(0,0),n=t[u].force,n.normalize(),n=n.multiplyByScaler(t[u].radius),t[u].position=t[u-1].position.add(n),ni.abs(t[u].position.x)<a&&(t[u].position.x=0),t[u].force=new ri(0,0),t[u].lastGravity=new ri(l.x,l.y)}function la(t,e,i,s,r){let a;a=s*r.getScale(r.translationScale,r.angleScale),a<e?(a<r.valueBelowMinimum&&(r.valueBelowMinimum=a),a=e):a>i&&(a>r.valueExceededMaximum&&(r.valueExceededMaximum=a),a=i);const n=r.weight/100;n>=1||(a=t[0]*(1-n)+a*n),t[0]=a}function ua(t,e,i,s,r,a,n,o){let l=0;const u=ni.max(i,e);u<t&&(t=u);const h=ni.min(i,e);h>t&&(t=h);const d=ni.min(r,a),g=ni.max(r,a),c=n,p=ia(h,u),m=t-p;switch(function(t){let e=0;return t>0?e=1:t<0&&(e=-1),e}(m)){case 1:{const t=u-p;0!=t&&(l=m*((g-c)/t),l+=c);break}case-1:{const t=h-p;0!=t&&(l=m*((d-c)/t),l+=c);break}case 0:l=c}return o?l:-1*l}var ha;function da(){var t;null==(t=this.__moc)||t.release()}(t=>{t.CubismPhysics=qr,t.Options=Wr})(ha||(ha={})),Pt.registerRuntime({version:4,ready:er,test:t=>t instanceof $s||$s.isValidJSON(t),isValidMoc(t){if(t.byteLength<4)return!1;const e=new Int8Array(t,0,4);return"MOC3"===String.fromCharCode(...e)},createModelSettings:t=>new $s(t),createCoreModel(t,e){const i=mr.create(t,!!(null==e?void 0:e.checkMocConsistency));try{const t=i.createModel();return t.__moc=i,t}catch(s){try{i.release()}catch(r){p.warn("CubismFactory","Failed to release moc after core model creation failed.",r)}throw s}},createInternalModel(t,e,i){const s=new Gs(t,e,i),r=t;return r.__moc&&(s.__moc=r.__moc,delete r.__moc,s.once("destroy",da)),s},createPhysics(t,e){if(!(e instanceof ArrayBuffer))throw new TypeError("Cubism physics data must be an ArrayBuffer.");return qr.create(e,e.byteLength)},createPose(t,e){if(!(e instanceof ArrayBuffer))throw new TypeError("Cubism pose data must be an ArrayBuffer.");return ar.create(e,e.byteLength)}}),t.CubismExpressionManager=Si,t.CubismInternalModel=Gs,t.CubismLegacyExpressionManager=Gt,t.CubismLegacyInternalModel=$t,t.CubismLegacyModelSettings=ut,t.CubismLegacyMotionManager=Ht,t.CubismLegacyParallelMotionManager=qt,t.CubismModelSettings=$s,t.CubismMotionManager=Zi,t.CubismParallelMotionManager=ss,t.ExpressionManager=P,t.FileLoader=vt,t.FocusController=I,t.InternalModel=st,t.LOGICAL_HEIGHT=2,t.LOGICAL_WIDTH=2,t.Live2DExpression=jt,t.Live2DEyeBlink=Wt,t.Live2DFactory=Pt,t.Live2DLoader=lt,t.Live2DModel=Ut,t.Live2DPhysics=Qt,t.Live2DPlugin=Nt,t.Live2DPose=ee,t.Live2DTransform=Lt,t.MBToByte=f,t.ModelSettings=F,t.MotionManager=G,t.MotionPreloadStrategy=j,t.MotionPriority=E,t.MotionState=L,t.SoundManager=z,t.VERSION="1.3.2",t.VOLUME=T,t.XHRLoader=nt,t.applyMixins=M,t.clamp=m,t.config=c,t.configureCubismSDK=tr,t.copyArray=x,t.copyProperty=y,t.cubismReady=er,t.folderName=C,t.logger=p,t.normalizeHitAreaDefs=et,t.rand=_,t.reconfigureCubismSDK=function(t={}){tr(t),ti.isInitialized()&&ti.dispose(),ti.isStarted()&&ti.cleanUp(),ir(void 0,t.memorySizeMB)},t.remove=S,t.resolveURL=b,t.startUpCubism=ir,Object.defineProperty(t,Symbol.toStringTag,{value:"Module"})});
1
+ !function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports,require("pixi.js")):"function"==typeof define&&define.amd?define(["exports","pixi.js"],e):e(((t="undefined"!=typeof globalThis?globalThis:t||self).PIXI=t.PIXI||{},t.PIXI.live2d=t.PIXI.live2d||{}),t.PIXI)}(this,function(t,e){"use strict";var i=Object.defineProperty,s=Object.defineProperties,r=Object.getOwnPropertyDescriptors,a=Object.getOwnPropertySymbols,n=Object.prototype.hasOwnProperty,o=Object.prototype.propertyIsEnumerable,l=Math.pow,u=(t,e,s)=>e in t?i(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,h=(t,e)=>{for(var i in e||(e={}))n.call(e,i)&&u(t,i,e[i]);if(a)for(var i of a(e))o.call(e,i)&&u(t,i,e[i]);return t},d=(t,e,i)=>u(t,"symbol"!=typeof e?e+"":e,i),g=(t,e,i)=>new Promise((s,r)=>{var a=t=>{try{o(i.next(t))}catch(e){r(e)}},n=t=>{try{o(i.throw(t))}catch(e){r(e)}},o=t=>t.done?s(t.value):Promise.resolve(t.value).then(a,n);o((i=i.apply(t,e)).next())});const c={LOG_LEVEL_VERBOSE:0,LOG_LEVEL_WARNING:1,LOG_LEVEL_ERROR:2,LOG_LEVEL_NONE:999,logLevel:1,sound:!0,fftSize:512,motionSync:!0,motionFadingDuration:500,idleMotionFadingDuration:2e3,expressionFadingDuration:500,preserveExpressionOnMotion:!0,cubism:Object.freeze(Object.defineProperty({__proto__:null,CSM_LOG_LEVEL:0,CSM_LOG_LEVEL_DEBUG:1,CSM_LOG_LEVEL_ERROR:4,CSM_LOG_LEVEL_INFO:2,CSM_LOG_LEVEL_OFF:5,CSM_LOG_LEVEL_VERBOSE:0,CSM_LOG_LEVEL_WARNING:3},Symbol.toStringTag,{value:"Module"}))},p={log(t,...e){c.logLevel<=c.LOG_LEVEL_VERBOSE&&console.log(`[${t}]`,...e)},warn(t,...e){c.logLevel<=c.LOG_LEVEL_WARNING&&console.warn(`[${t}]`,...e)},error(t,...e){c.logLevel<=c.LOG_LEVEL_ERROR&&console.error(`[${t}]`,...e)}};function m(t,e,i){return t<e?e:t>i?i:t}function _(t,e){return Math.random()*(e-t)+t}function f(t){return 1024*t*1024}function y(t,e,i,s,r){const a=e[s];null!==a&&typeof a===t&&(i[r]=a)}function x(t,e,i,s,r){const a=e[s];Array.isArray(a)&&(i[r]=a.filter(e=>null!==e&&typeof e===t))}function M(t,e){e.forEach(e=>{Object.getOwnPropertyNames(e.prototype).forEach(i=>{"constructor"!==i&&Object.defineProperty(t.prototype,i,Object.getOwnPropertyDescriptor(e.prototype,i))})})}function C(t){let e=t.lastIndexOf("/");return-1!=e&&(t=t.slice(0,e)),e=t.lastIndexOf("/"),-1!==e&&(t=t.slice(e+1)),t}function S(t,e){const i=t.indexOf(e);-1!==i&&t.splice(i,1)}const v=/^[a-zA-Z][a-zA-Z0-9+.-]*:/;function b(t,e){if(!e)return t;if(v.test(e))return e;if(e.startsWith("/"))return v.test(t)?new URL(e,t).toString():e;if(v.test(t))return new URL(e,t).toString();const i="http://example.com",s=t.startsWith("/")?i+t:`${i}/${t}`,r=new URL(e,s);let a=r.pathname+r.search+r.hash;return!t.startsWith("/")&&a.startsWith("/")&&(a=a.slice(1)),a}class P extends e.EventEmitter{constructor(t,e){super(),d(this,"expressionDataType","json"),d(this,"tag"),d(this,"settings"),d(this,"expressions",[]),d(this,"defaultExpression"),d(this,"currentExpression"),d(this,"reserveExpressionIndex",-1),d(this,"destroyed",!1),this.settings=t,this.tag=`ExpressionManager(${t.name})`}init(){this.defaultExpression=this.createDefaultExpression(),this.currentExpression=this.defaultExpression,this.stopAllExpressions()}createDefaultExpression(){return this.createExpression({},void 0)}loadExpression(t){return g(this,null,function*(){if(!this.definitions[t])return void p.warn(this.tag,`Undefined expression at [${t}]`);if(null===this.expressions[t])return void p.warn(this.tag,`Cannot set expression at [${t}] because it's already failed in loading.`);if(this.expressions[t])return this.expressions[t];const e=yield this._loadExpression(t);return this.expressions[t]=e,e})}_loadExpression(t){throw new Error("Not implemented.")}setRandomExpression(){return g(this,null,function*(){if(this.definitions.length){const t=[];for(let e=0;e<this.definitions.length;e++)null!==this.expressions[e]&&this.expressions[e]!==this.currentExpression&&e!==this.reserveExpressionIndex&&t.push(e);if(t.length){const e=Math.floor(Math.random()*t.length);return this.setExpression(e)}}return!1})}resetExpression(){this._setExpression(this.defaultExpression)}restoreExpression(){this._setExpression(this.currentExpression)}setExpression(t){return g(this,null,function*(){if("number"!=typeof t&&(t=this.getExpressionIndex(t)),!(t>-1&&t<this.definitions.length))return!1;if(t===this.expressions.indexOf(this.currentExpression))return!1;this.reserveExpressionIndex=t;const e=yield this.loadExpression(t);return!(!e||this.reserveExpressionIndex!==t)&&(this.reserveExpressionIndex=-1,this.currentExpression=e,this._setExpression(e),!0)})}update(t,e){return!this.isFinished()&&this.updateParameters(t,e)}destroy(){this.destroyed=!0,this.emit("destroy");this.definitions=void 0,this.expressions=void 0}}const B=40/7.5,w=1/150;class I{constructor(){d(this,"targetX",0),d(this,"targetY",0),d(this,"x",0),d(this,"y",0),d(this,"vx",0),d(this,"vy",0)}focus(t,e,i=!1){this.targetX=m(t,-1,1),this.targetY=m(e,-1,1),i&&(this.x=this.targetX,this.y=this.targetY)}update(t){const e=this.targetX-this.x,i=this.targetY-this.y;if(Math.abs(e)<.01&&Math.abs(i)<.01)return;const s=Math.sqrt(l(e,2)+l(i,2)),r=B/(1e3/t);let a=r*(e/s)-this.vx,n=r*(i/s)-this.vy;const o=Math.sqrt(l(a,2)+l(n,2)),u=r*w*t;o>u&&(a*=u/o,n*=u/o),this.vx+=a,this.vy+=n;const h=Math.sqrt(l(this.vx,2)+l(this.vy,2)),d=.5*(Math.sqrt(l(u,2)+8*u*s)-u);h>d&&(this.vx*=d/h,this.vy*=d/h),this.x+=this.vx,this.y+=this.vy}}class F{constructor(t){d(this,"json"),d(this,"name"),d(this,"url"),d(this,"pose"),d(this,"physics"),this.json=t,this.url=t.url,this.name=C(this.url)}normalizeName(){this.name&&"name"!==this.name.toLowerCase()||(this.name=C(this.url))}setModelName(...t){for(const e of t){const t="string"==typeof e?e.trim():"";if(t&&"name"!==t.toLowerCase())return void(this.name=t)}this.normalizeName()}getFileStem(t){if(!t)return;const e=t.split(/[/\\]/).filter(Boolean).pop();return null==e?void 0:e.replace(/\.[^.]+$/,"")}resolveURL(t){return b(this.url,t)}replaceFiles(t){this.moc=t(this.moc,"moc"),void 0!==this.pose&&(this.pose=t(this.pose,"pose")),void 0!==this.physics&&(this.physics=t(this.physics,"physics"));for(let e=0;e<this.textures.length;e++)this.textures[e]=t(this.textures[e],`textures[${e}]`)}getDefinedFiles(){const t=[];return this.replaceFiles(e=>(t.push(e),e)),t}validateFiles(t){const e=(e,i)=>{const s=this.resolveURL(e);if(!t.includes(s)){if(i)throw new Error(`File "${e}" is defined in settings, but doesn't exist in given files`);return!1}return!0};[this.moc,...this.textures].forEach(t=>e(t,!0));return this.getDefinedFiles().filter(t=>e(t,!1))}}var E=(t=>(t[t.NONE=0]="NONE",t[t.IDLE=1]="IDLE",t[t.NORMAL=2]="NORMAL",t[t.FORCE=3]="FORCE",t))(E||{});class L{constructor(){d(this,"tag"),d(this,"debug",!1),d(this,"currentPriority",0),d(this,"reservePriority",0),d(this,"currentGroup"),d(this,"currentIndex"),d(this,"reservedGroup"),d(this,"reservedIndex"),d(this,"reservedIdleGroup"),d(this,"reservedIdleIndex")}reserve(t,e,i){if(i<=0)return p.log(this.tag,"Cannot start a motion with MotionPriority.NONE."),!1;if(t===this.currentGroup&&e===this.currentIndex)return p.log(this.tag,"Motion is already playing.",this.dump(t,e)),!1;if(t===this.reservedGroup&&e===this.reservedIndex||t===this.reservedIdleGroup&&e===this.reservedIdleIndex)return p.log(this.tag,"Motion is already reserved.",this.dump(t,e)),!1;if(1===i){if(0!==this.currentPriority)return p.log(this.tag,"Cannot start idle motion because another motion is playing.",this.dump(t,e)),!1;if(void 0!==this.reservedIdleGroup)return p.log(this.tag,"Cannot start idle motion because another idle motion has reserved.",this.dump(t,e)),!1;this.setReservedIdle(t,e)}else{if(i<3){if(i<=this.currentPriority)return p.log(this.tag,"Cannot start motion because another motion is playing as an equivalent or higher priority.",this.dump(t,e)),!1;if(i<=this.reservePriority)return p.log(this.tag,"Cannot start motion because another motion has reserved as an equivalent or higher priority.",this.dump(t,e)),!1}this.setReserved(t,e,i)}return!0}start(t,e,i,s){if(1===s){if(this.setReservedIdle(void 0,void 0),0!==this.currentPriority)return p.log(this.tag,"Cannot start idle motion because another motion is playing.",this.dump(e,i)),!1}else{if(e!==this.reservedGroup||i!==this.reservedIndex)return p.log(this.tag,"Cannot start motion because another motion has taken the place.",this.dump(e,i)),!1;this.setReserved(void 0,void 0,0)}return!!t&&(this.setCurrent(e,i,s),!0)}complete(){this.setCurrent(void 0,void 0,0)}setCurrent(t,e,i){this.currentPriority=i,this.currentGroup=t,this.currentIndex=e}setReserved(t,e,i){this.reservePriority=i,this.reservedGroup=t,this.reservedIndex=e}setReservedIdle(t,e){this.reservedIdleGroup=t,this.reservedIdleIndex=e}isActive(t,e){return t===this.currentGroup&&e===this.currentIndex||t===this.reservedGroup&&e===this.reservedIndex||t===this.reservedIdleGroup&&e===this.reservedIdleIndex}reset(){this.setCurrent(void 0,void 0,0),this.setReserved(void 0,void 0,0),this.setReservedIdle(void 0,void 0)}shouldRequestIdleMotion(){return void 0===this.currentGroup&&void 0===this.reservedIdleGroup}shouldOverrideExpression(){return!c.preserveExpressionOnMotion&&this.currentPriority>1}dump(t,e){if(this.debug){return`\n<Requested> group = "${t}", index = ${e}\n`+["currentPriority","reservePriority","currentGroup","currentIndex","reservedGroup","reservedIndex","reservedIdleGroup","reservedIdleIndex"].map(t=>"["+t+"] "+this[t]).join("\n")}return""}}const V="SoundManager",T=.5;let R,D=0;const A=new WeakSet;function O(t){if(!A.has(t)){try{t.disableAutoPause=!0}catch(e){p.warn(V,"Failed to disable @pixi/sound auto pause.",e)}A.add(t)}return t}function k(){return g(this,null,function*(){const t="undefined"!=typeof PIXI?null==PIXI?void 0:PIXI.sound:void 0;return t?O(t):(null!=R||(R=import("@pixi/sound").then(({sound:t})=>O(t)).catch(t=>(p.warn(V,"@pixi/sound is not available. Load pixi-sound.js before using motion sounds, speak(), or lip sync.",t),null))),R)})}function N(t,e){try{t.remove(e)}catch(i){p.warn(V,`Failed to remove sound "${e}".`,i)}}function U(t){const e=t.media.buffer;if(!e||"object"!=typeof e)return;return"function"==typeof e.getChannelData?e:void 0}class z{static get volume(){return this._volume}static set volume(t){this._volume=(t>1?1:t<0?0:t)||0,this.audios.forEach(t=>t.volume=this._volume)}static add(t,e){return g(this,null,function*(){let i,s=null;try{if(s=yield k(),!s)throw new Error("@pixi/sound is not available");i="live2d-sound-"+D++;const e=s,r=i,a=new Promise((i,s)=>{const a=e.add(r,{url:t,volume:this._volume,preload:!0,loaded:(e,r)=>{if(e)return void s(e);const n=null!=r?r:a;n?U(n)?i(n):s(new Error(`Error: ${t} is not WebAudioMedia`)):s(new Error(`Error: ${t} failed to load`))}})}),n=yield a;return this.aliases.set(n,{alias:r,library:e}),this.audios.push(n),n}catch(r){return s&&i&&N(s,i),p.warn(V,`Error occurred on "${t}"`,r),null==e||e(r),null}})}static play(t,e){t.play({singleInstance:!0,complete:()=>{null==e||e(),this.dispose(t)}})}static addAnalyzer(t,e){const i=U(t);if(!i)return void p.warn(V,"Cannot create audio analyzer because WebAudio media is unavailable.");const s=e.createBufferSource();s.buffer=i;const r=e.createAnalyser();return r.fftSize=c.fftSize,r.minDecibels=-90,r.maxDecibels=-10,r.smoothingTimeConstant=.85,s.connect(r),s.start(0),this.analysers.push(r),r}static analyze(t){if(!t)return parseFloat(Math.random().toFixed(1));const e=new Float32Array(t.fftSize);t.getFloatTimeDomainData(e);let i=0;for(let n=0;n<e.length;n++)i+=l(e[n],2);const s=Math.sqrt(i/e.length),r=20*Math.log10(s||l(10,-5)),a=Math.min(Math.max((r-t.minDecibels)/(t.maxDecibels-t.minDecibels),0),1);return parseFloat(a.toFixed(1))}static dispose(t){try{t.pause()}catch(i){p.warn(V,"Failed to pause audio.",i)}const e=this.aliases.get(t);e?(N(e.library,e.alias),this.aliases.delete(t)):function(t){try{t.destroy()}catch(i){p.warn(V,"Failed to destroy audio.",i)}}(t),S(this.audios,t)}static destroy(){for(let t=this.contexts.length-1;t>=0;t--){const e=this.contexts[t];null==e||e.close().catch(t=>{p.warn(V,"Failed to close AudioContext.",t)})}for(let t=this.audios.length-1;t>=0;t--)this.dispose(this.audios[t])}}d(z,"audios",[]),d(z,"analysers",[]),d(z,"contexts",[]),d(z,"aliases",new WeakMap),d(z,"_volume",T);var j=(t=>(t.ALL="ALL",t.IDLE="IDLE",t.NONE="NONE",t))(j||{});class G extends e.EventEmitter{constructor(t){super(),d(this,"tag"),d(this,"settings"),d(this,"motionGroups",{}),d(this,"state",new L),d(this,"currentAudio"),d(this,"currentAnalyzer"),d(this,"currentContext"),d(this,"playing",!1),d(this,"destroyed",!1),d(this,"parent"),this.settings=t.settings,this.tag=`MotionManager(${this.settings.name})`,this.state.tag=this.tag,this.parent=t}init(t){(null==t?void 0:t.idleMotionGroup)&&(this.groups.idle=t.idleMotionGroup),this.setupMotions(t),this.stopAllMotions()}setupMotions(t){if(!this.definitions)return void p.warn(this.tag,"Motion definitions are not initialized.");for(const i of Object.keys(this.definitions))this.motionGroups[i]=[];let e;switch(null==t?void 0:t.motionPreload){case"NONE":return;case"ALL":e=Object.keys(this.definitions);break;default:e=[this.groups.idle]}for(const i of e){const t=this.definitions[i];if(t)for(let e=0;e<t.length;e++)this.loadMotion(i,e)}}loadMotion(t,e){return g(this,null,function*(){var i,s;if(this.destroyed)return;if(!this.getMotionDefinition(t,e))return;const r=null!=(s=(i=this.motionGroups)[t])?s:i[t]=[];if(null===r[e])return void p.warn(this.tag,`Cannot start motion at "${t}"[${e}] because it's already failed in loading.`);if(r[e])return r[e];const a=yield this._loadMotion(t,e);return this.destroyed?void 0:(r[e]=null!=a?a:null,a)})}_loadMotion(t,e){throw new Error("Not implemented.")}initializeAudio(t,e){this.currentAudio=t,z.volume=e,this.currentContext=t.context.audioContext,this.currentAnalyzer=z.addAnalyzer(this.currentAudio,this.currentContext)}speak(t){return g(this,arguments,function*(t,{volume:e=.5,expression:i,resetExpression:s=!0,onFinish:r,onError:a}={}){if(!c.sound)return!1;let n,o;if(this.currentAudio&&this.currentAudio.isPlaying)return!1;const l=t&&t.startsWith("data:");if(t&&!l){const e=document.createElement("a");e.href=t,o=t=e.href}else o="data:audio/";const u=t;if(u)try{if(n=yield z.add(u,(t,e=this)=>{p.error(this.tag,"Error during audio playback:",t),null==a||a(t),s&&i&&e.expressionManager&&e.expressionManager.resetExpression(),e.currentAudio=void 0}),!n)return!1;this.initializeAudio(n,e)}catch(h){return p.warn(this.tag,"Failed to create audio",o,h),!1}if(n){let t=!0;try{c.motionSync&&z.play(n,()=>{null==r||r(),s&&i&&this.expressionManager&&this.expressionManager.resetExpression(),this.currentAudio=void 0})}catch(h){p.warn(this.tag,"Failed to play audio",n.url,h),t=!1}if(!t)return!1}return this.state.shouldOverrideExpression()&&this.expressionManager&&this.expressionManager.resetExpression(),i&&this.expressionManager&&(yield this.expressionManager.setExpression(i)),this.playing=!0,!0})}startMotion(t,e){return g(this,arguments,function*(t,e,i=E.NORMAL,{sound:s,volume:r=.5,expression:a,resetExpression:n=!0,onFinish:o,onError:l,ignoreParamIds:u=[],loop:h}={}){if(this.destroyed)return!1;if(!this.state.reserve(t,e,i))return!1;if(this.currentAudio&&this.currentAudio.isPlaying&&i!=E.FORCE)return!1;const d=this.getMotionDefinition(t,e);if(!d)return!1;let g,m;this.currentAudio&&z.dispose(this.currentAudio);const _=s&&s.startsWith("data:");if(s&&!_){const t=document.createElement("a");t.href=s,m=s=t.href}else m=this.getSoundFile(d),m&&(m=this.settings.resolveURL(m));const f=m;if(f)try{g=yield z.add(f,(t,e=this)=>{p.error(this.tag,"Error during audio playback:",t),null==l||l(t),n&&a&&e.expressionManager&&e.expressionManager.resetExpression(),e.currentAudio=void 0}),g&&this.initializeAudio(g,r)}catch(x){p.warn(this.tag,"Failed to create audio",m,x)}const y=yield this.loadMotion(t,e);if(g&&c.motionSync)try{z.play(g,(t=this)=>{null==o||o(),n&&a&&t.expressionManager&&t.expressionManager.resetExpression(),t.currentAudio=void 0})}catch(x){p.warn(this.tag,"Failed to play audio",g.url,x)}return this.state.start(y,t,e,i)?(this.state.shouldOverrideExpression()&&this.expressionManager&&this.expressionManager.resetExpression(),p.log(this.tag,"Start motion:",this.getMotionName(d)),this.emit("motionStart",t,e,g),a&&this.expressionManager&&this.state.shouldOverrideExpression()&&(yield this.expressionManager.setExpression(a)),this.playing=!0,y&&this._startMotion(y,void 0,u,h),!0):(g&&(z.dispose(g),this.currentAudio=void 0),!1)})}startRandomMotion(t,e){return g(this,arguments,function*(t,e,{sound:i,volume:s=.5,expression:r,resetExpression:a=!0,onFinish:n,onError:o,loop:l}={}){var u,h;if(this.destroyed)return!1;const d=null==(u=this.definitions)?void 0:u[t];if(null==d?void 0:d.length){const u=[],g=null!=(h=this.motionGroups[t])?h:[];for(let e=0;e<d.length;e++)null===g[e]||this.state.isActive(t,e)||u.push(e);if(u.length){const h=u[Math.floor(Math.random()*u.length)];return this.startMotion(t,h,e,{sound:i,volume:s,expression:r,resetExpression:a,onFinish:n,onError:o,loop:l})}}return!1})}stopSpeaking(){this.currentAudio&&(z.dispose(this.currentAudio),this.currentAudio=void 0)}stopAllMotions(){this._stopAllMotions(),this.state.reset(),this.stopSpeaking()}update(t,e){var i;return this.isFinished()&&(this.playing&&(this.playing=!1,this.emit("motionFinish")),this.state.shouldOverrideExpression()&&(null==(i=this.expressionManager)||i.restoreExpression()),this.state.complete(),this.state.shouldRequestIdleMotion()&&this.startRandomMotion(this.groups.idle,E.IDLE)),this.updateParameters(t,e)}mouthSync(){return this.currentAnalyzer?z.analyze(this.currentAnalyzer):0}destroy(){var t;this.destroyed=!0,this.emit("destroy"),this.stopAllMotions(),null==(t=this.expressionManager)||t.destroy();this.definitions=void 0,this.motionGroups=void 0}getMotionAndApplyExpression(t,e,i){return g(this,null,function*(){if(this.destroyed)return null;if(!this.state.reserve(t,e,E.FORCE))return null;const s=this.getMotionDefinition(t,e);if(!s)return null;this.currentAudio&&z.dispose(this.currentAudio);const r=yield this.loadMotion(t,e);return this.state.start(r,t,e,E.FORCE)?(this.state.shouldOverrideExpression()&&this.expressionManager&&this.expressionManager.resetExpression(),p.log(this.tag,"Start motion:",this.getMotionName(s)),this.emit("motionStart",t,e,void 0),i&&this.expressionManager&&this.state.shouldOverrideExpression()&&(yield this.expressionManager.setExpression(i)),r):null})}getMotionDefinition(t,e){var i,s;const r=null==(s=null==(i=this.definitions)?void 0:i[t])?void 0:s[e];return r||p.warn(this.tag,`Undefined motion at "${t}"[${e}]`),r}}function X(t,e){return 2*e*t.scale}function H(t){return 2*t.scale}function Y(t,e,i){t.scale=i/(2*e)}function q(t,e){t.scale=e/2}function W(t,e){t.x=e}function J(t,e){t.y=e}function $(t,e,i){W(t,i-X(t,e)/2)}function Z(t,e){J(t,e-H(t)/2)}function K(t,e,i){W(t,i-X(t,e))}function Q(t,e){J(t,e-H(t))}function tt(t,e,i,s){if(e<=0||i<=0)return t.identity(),{width:0,height:0};const r=function(t){const e=[];for(const[i,s]of Object.entries(t))"number"==typeof s&&e.push([i,s]);return e}(s),a=e/i,n={scale:1,x:0,y:0};for(const[u,h]of r)"width"===u?Y(n,a,h):"height"===u&&q(n,h);for(const[u,h]of r)"x"===u?W(n,h):"y"===u?J(n,h):"centerX"===u?$(n,a,h):"centerY"===u?Z(n,h):"top"===u?J(n,h):"bottom"===u?Q(n,h):"left"===u?W(n,h):"right"===u&&K(n,a,h);const o=i/2,l=2*a/2;return t.identity(),function(t,e){t.a=e,t.b=0,t.c=0,t.d=e}(t,n.scale),t.tx=o*(n.x+l)-e*n.scale/2,t.ty=o*(1-n.y)-i*n.scale/2,{width:e*n.scale,height:i*n.scale}}function et(t,e){if(!Array.isArray(t))return[];const i=[];for(const s of t){if(!s||"object"!=typeof s)continue;const t=s,r="string"==typeof t.id?t.id:"string"==typeof t.Id?t.Id:void 0,a="string"==typeof t.name?t.name:"string"==typeof t.Name?t.Name:void 0;r&&a&&i.push({id:r,name:a,index:e(r)})}return i}const it={x:0,y:0,width:0,height:0};class st extends e.EventEmitter{constructor(){super(...arguments),d(this,"focusController",new I),d(this,"pose"),d(this,"physics"),d(this,"originalWidth",0),d(this,"originalHeight",0),d(this,"width",0),d(this,"height",0),d(this,"localTransform",new e.Matrix),d(this,"drawingMatrix",new e.Matrix),d(this,"hitAreas",{}),d(this,"textureFlipY",!1),d(this,"viewport",[0,0,0,0]),d(this,"destroyed",!1)}init(){this.setupLayout(),this.setupHitAreas()}setupLayout(){const t=this,e=this.getSize();t.originalWidth=e[0],t.originalHeight=e[1];const i=function(t,e,i,s){var r,a;const n=h({width:2,height:2},s),o=null!=(r=n.width)?r:2,l=null!=(a=n.height)?a:2;t.identity(),t.scale(o/2,l/2);const u=e*t.a,d=i*t.d,g=void 0!==n.x&&n.x-o/2||void 0!==n.centerX&&n.centerX||void 0!==n.left&&n.left-o/2||void 0!==n.right&&n.right+o/2||0,c=void 0!==n.y&&n.y-l/2||void 0!==n.centerY&&n.centerY||void 0!==n.top&&n.top-l/2||void 0!==n.bottom&&n.bottom+l/2||0;return t.translate(u*g,-d*c),{width:u,height:d}}(this.localTransform,this.originalWidth,this.originalHeight,this.getLayout());t.width=i.width,t.height=i.height}setupHitAreas(){const t=this.getHitAreaDefs();this.hitAreas={};for(const e of t)e.name&&(this.hitAreas[e.name]=e)}hitTest(t,e){return Object.keys(this.hitAreas).filter(i=>this.isHit(i,t,e))}isHit(t,e,i){const s=this.hitAreas[t];if(!s)return!1;let r=s.index;if(r<0){if(!s.id)return!1;if(r=this.getDrawableIndex(s.id),r<0)return!1;s.index=r}const a=this.getDrawableBounds(r,it);return a.x<=e&&e<=a.x+a.width&&a.y<=i&&i<=a.y+a.height}getDrawableBounds(t,e){const i=this.getDrawableVertices(t);let s=i[0],r=i[0],a=i[1],n=i[1];for(let o=0;o<i.length;o+=2){const t=i[o],e=i[o+1];s=Math.min(t,s),r=Math.max(t,r),a=Math.min(e,a),n=Math.max(e,n)}return null!=e||(e={}),e.x=s,e.y=a,e.width=r-s,e.height=n-a,e}updateTransform(t){this.drawingMatrix.copyFrom(t).append(this.localTransform)}update(t,e){this.focusController.update(t)}destroy(){this.destroyed=!0,this.emit("destroy"),this.motionManager.destroy(),this.motionManager=void 0,this.parallelMotionManager.forEach(t=>t.destroy()),this.parallelMotionManager=[]}updateMotions(t,e){this.emit("beforeMotionUpdate");const i=this.motionManager.update(t,e),s=this.parallelMotionManager.map(i=>i.update(t,e)),r=i||s.reduce((t,e)=>t||e,!1);return this.emit("afterMotionUpdate"),r}}class rt extends Error{constructor(t,e,i,s=!1){super(t),this.url=e,this.status=i,this.aborted=s}}const at=class t{static createXHR(e,i,s,r,a){const n=new XMLHttpRequest;if(t.allXhrSet.add(n),e){let i=t.xhrMap.get(e);i?i.add(n):(i=new Set([n]),t.xhrMap.set(e,i))}return n.open("GET",i),n.responseType=s,n.onload=()=>{var t;200!==n.status&&0!==n.status||!n.response?null==(t=n.onerror)||t.call(n,new ProgressEvent("error")):r(n.response)},n.onerror=()=>{p.warn("XHRLoader",`Failed to load resource as ${n.responseType} (Status ${n.status}): ${i}`),a(new rt("Network error.",i,n.status))},n.onabort=()=>a(new rt("Aborted.",i,n.status,!0)),n.onloadend=()=>{var i;t.allXhrSet.delete(n),e&&(null==(i=t.xhrMap.get(e))||i.delete(n))},n}static cancelXHRs(){var e;null==(e=t.xhrMap.get(this))||e.forEach(e=>{e.abort(),t.allXhrSet.delete(e)}),t.xhrMap.delete(this)}static release(){t.allXhrSet.forEach(t=>t.abort()),t.allXhrSet.clear(),t.xhrMap=new WeakMap}};d(at,"xhrMap",new WeakMap),d(at,"allXhrSet",new Set),d(at,"loader",t=>new Promise((e,i)=>{const s=t.target,r=t.target&&"function"==typeof at.cancelXHRs?at.cancelXHRs.bind(t.target):void 0,a=at.createXHR(t.target,t.settings?t.settings.resolveURL(t.url):t.url,t.type,i=>{t.result=i,e()},i);if(t.target&&r&&"function"==typeof s.listeners&&"function"==typeof s.once){const t=s.listeners("destroy");Array.isArray(t)&&t.includes(r)||s.once("destroy",r)}a.send()}));let nt=at;function ot(t,e){let i=-1;return function s(r,a){if(a)return Promise.reject(a);if(r<=i)return Promise.reject(new Error("next() called multiple times"));i=r;const n=t[r];if(!n)return Promise.resolve();try{return Promise.resolve(n(e,s.bind(null,r+1)))}catch(o){const t=o instanceof Error?o:new Error(String(o));return Promise.reject(t)}}(0)}class lt{static load(t){return g(this,null,function*(){return yield ot(this.middlewares,t),t.result})}}d(lt,"middlewares",[nt.loader]);class ut extends F{constructor(t){if(super(t),d(this,"moc"),d(this,"textures"),d(this,"layout"),d(this,"hitAreas"),d(this,"initParams"),d(this,"initOpacities"),d(this,"expressions"),d(this,"motions",{}),!ut.isValidJSON(t))throw new TypeError("Invalid JSON.");this.moc=t.model,x("string",t,this,"textures","textures"),this.copy(t)}static isValidJSON(t){if(!t||"object"!=typeof t)return!1;const e=!!Array.isArray(t.textures)&&t.textures.every(t=>"string"==typeof t);return"string"==typeof t.model&&e}copy(t){y("string",t,this,"name","name"),y("string",t,this,"pose","pose"),y("string",t,this,"physics","physics"),y("object",t,this,"layout","layout"),y("object",t,this,"motions","motions"),x("object",t,this,"hit_areas","hitAreas"),x("object",t,this,"expressions","expressions"),x("object",t,this,"init_params","initParams"),x("object",t,this,"init_opacities","initOpacities");const e=this.getFileStem(this.moc);this.setModelName(this.name,e)}replaceFiles(t){super.replaceFiles(t);for(const[e,i]of Object.entries(this.motions))for(let s=0;s<i.length;s++)i[s].file=t(i[s].file,`motions.${e}[${s}].file`),void 0!==i[s].sound&&(i[s].sound=t(i[s].sound,`motions.${e}[${s}].sound`));if(this.expressions)for(let e=0;e<this.expressions.length;e++)this.expressions[e].file=t(this.expressions[e].file,`expressions[${e}].file`)}}function ht({lod:t,effectiveScale:e,textureWidth:i,textureHeight:s,lodScaleThreshold:r,lodTextureSizeThreshold:a,lodMaxLevel:n}){if("single-auto"!==dt(t))return;if(!Number.isFinite(e)||e<=0)return;const o=Math.floor(i),u=Math.floor(s);if(o<=1||u<=1)return;if(e>=ct(r,.5))return;const h=ct(a,4096);if(Math.max(o,u)<h)return;const d=Math.round(Math.log2(1/e)),g=Math.max(1,Math.floor(Math.log2(Math.max(o,u)))),c=Math.min(g,(m=g,void 0!==(p=n)&&Number.isFinite(p)&&p>=1?Math.floor(p):m));var p,m;const _=function(t,e,i){return Math.min(i,Math.max(e,t))}(Math.max(1,d),1,c),f=l(2,_);return{level:_,width:Math.max(1,Math.round(o/f)),height:Math.max(1,Math.round(u/f))}}function dt(t){return!1===t||"single-auto"===t?t:"full"}function gt(t){return"nearest"===t?"nearest":"linear"}function ct(t,e){return void 0!==t&&Number.isFinite(t)&&t>0?t:e}function pt(){}const mt="Live2DFactory",_t=(t,e)=>g(null,null,function*(){if("string"==typeof t.source){const e=yield lt.load({url:t.source,type:"json",target:t.live2dModel});e.url="string"==typeof e.url?e.url:t.source,t.source=e,t.live2dModel.emit("settingsJSONLoaded",e)}return e()}),ft=(t,e)=>g(null,null,function*(){if(t.source instanceof F)return t.settings=t.source,e();if("object"==typeof t.source){const i=Pt.findRuntime(t.source);if(i){const s=i.createModelSettings(t.source);return t.settings=s,t.live2dModel.emit("settingsLoaded",s),e()}}const i=t.source&&"string"==typeof t.source.url?t.source.url:void 0,s=Pt.runtimes.map(t=>t.version).join(", ");if(0===Pt.runtimes.length)throw new TypeError(["Unknown settings format: no Live2D runtimes registered.",'Import a published runtime entry before loading models (e.g. "<package>/cubism" for Cubism 3/4/5, "<package>/cubism-legacy" for Cubism 2).',i?`Settings URL: ${i}`:void 0].filter(Boolean).join("\n"));const r=(()=>{try{if(!t.source||"object"!=typeof t.source||Array.isArray(t.source))return;return Object.keys(t.source).slice(0,30).join(", ")}catch(e){return}})();throw new TypeError(["Unknown settings format: no matching runtime found for the loaded settings JSON.",s?`Registered runtimes (versions): ${s}`:void 0,r?`Settings JSON keys: ${r}`:void 0,i?`Settings URL: ${i}`:void 0].filter(Boolean).join("\n"))}),yt=(t,e)=>{if(t.settings){const i=Pt.findRuntime(t.settings);if(i)return i.ready().then(()=>e())}return e()},xt=(t,e)=>g(null,null,function*(){yield e();const i=t.internalModel;if(i){const e=t.settings,s=Pt.findRuntime(e);if(s){const r=[],a=e instanceof ut?"json":"arraybuffer";e.pose&&r.push(lt.load({settings:e,url:e.pose,type:a,target:i}).then(e=>{i.pose=s.createPose(i.coreModel,e),t.live2dModel.emit("poseLoaded",i.pose)}).catch(e=>{t.live2dModel.emit("poseLoadError",e),p.warn(mt,"Failed to load pose.",e)})),e.physics&&r.push(lt.load({settings:e,url:e.physics,type:a,target:i}).then(e=>{i.physics=s.createPhysics(i.coreModel,e),t.live2dModel.emit("physicsLoaded",i.physics)}).catch(e=>{t.live2dModel.emit("physicsLoadError",e),p.warn(mt,"Failed to load physics.",e)})),r.length&&(yield Promise.all(r))}}}),Mt=(t,i)=>g(null,null,function*(){if(!t.settings)throw new TypeError("Missing settings.");{const s=t.live2dModel,r=h({crossOrigin:t.options.crossOrigin},t.options.textureOptions);t.settings instanceof ut&&(r.preferCreateImageBitmap=!1);const a=Promise.all(t.settings.textures.map(i=>function(t,i={}){const s=e.loadTextures.config,r=null==s?void 0:s.crossOrigin,a=null==s?void 0:s.preferCreateImageBitmap,n=null==s?void 0:s.preferWorkers;return void 0!==i.crossOrigin&&s&&(s.crossOrigin=i.crossOrigin),!1===i.preferCreateImageBitmap&&s&&(s.preferCreateImageBitmap=!1,s.preferWorkers=!1),e.Assets.load({src:t,data:{autoGenerateMipmaps:"full"===dt(i.lod)}}).catch(t=>{if(t instanceof Error)throw t;throw new Error("Texture loading error",{cause:t})}).finally(()=>{s&&(s.crossOrigin=null!=r?r:s.crossOrigin,!1===i.preferCreateImageBitmap&&(s.preferCreateImageBitmap=null!=a?a:s.preferCreateImageBitmap,s.preferWorkers=null!=n?n:s.preferWorkers))})}(t.settings.resolveURL(i),r)));if(a.catch(pt),yield i(),!t.internalModel)throw new TypeError("Missing internal model.");s.internalModel=t.internalModel,s.emit("modelLoaded",t.internalModel),s.textures=yield a,s.emit("textureLoaded",s.textures)}}),Ct=(t,e)=>g(null,null,function*(){const i=t.settings;if(i instanceof F){const s=Pt.findRuntime(i);if(!s)throw new TypeError("Unknown model settings.");const r=yield lt.load({settings:i,url:i.moc,type:"arraybuffer",target:t.live2dModel});if(!s.isValidMoc(r))throw new Error("Invalid moc data");const a=s.createCoreModel(r);return t.internalModel=s.createInternalModel(a,i,t.options),e()}throw new TypeError("Missing settings.")}),St=class t{static resolveURL(e,i){var s;const r=null==(s=t.filesMap[e])?void 0:s[i];if(void 0===r)throw new Error("Cannot find this file from uploaded files: "+i);return r}static upload(e,i){const s={};for(const t of i.getDefinedFiles()){const r=decodeURI(b(i.url,t)),a=e.find(t=>t.webkitRelativePath===r);a&&(s[t]=URL.createObjectURL(a))}t.filesMap[i._objectURL]=s}static createSettings(e){return g(this,null,function*(){const i=e.find(t=>t.name.endsWith("model.json")||t.name.endsWith("model3.json"));if(!i)throw new TypeError("Settings file not found");const s=yield t.readText(i),r=JSON.parse(s);r.url=i.webkitRelativePath;const a=Pt.findRuntime(r);if(!a)throw new Error("Unknown settings JSON");const n=a.createModelSettings(r);return n._objectURL=URL.createObjectURL(i),n})}static readText(t){return g(this,null,function*(){return new Promise((e,i)=>{const s=new FileReader;s.onload=()=>e(s.result),s.onerror=i,s.readAsText(t,"utf8")})})}};d(St,"live2dFactory"),d(St,"filesMap",{}),d(St,"factory",(t,e)=>g(null,null,function*(){if(Array.isArray(t.source)&&t.source[0]instanceof File){const e=t.source;let i=e.settings;if(i){if(!i._objectURL)throw new Error('"_objectURL" must be specified in ModelSettings')}else i=yield St.createSettings(e);i.validateFiles(e.map(t=>encodeURI(t.webkitRelativePath))),St.upload(e,i),i.resolveURL=function(t){return St.resolveURL(this._objectURL,t)},t.source=i,t.live2dModel.once("modelLoaded",t=>{t.once("destroy",function(){const t=this.settings._objectURL;if(URL.revokeObjectURL(t),St.filesMap[t])for(const e of Object.values(St.filesMap[t]))URL.revokeObjectURL(e);delete St.filesMap[t]})})}return e()}));let vt=St;const bt=class t{static registerRuntime(e){t.runtimes.push(e),t.runtimes.sort((t,e)=>e.version-t.version)}static findRuntime(e){for(const i of t.runtimes)if(i.test(e))return i}static setupLive2DModel(e,i,s){return g(this,null,function*(){const r=new Promise(t=>e.once("textureLoaded",t)),a=new Promise(t=>e.once("modelLoaded",t)),n=Promise.all([r,a]).then(()=>e.emit("ready"));yield ot(t.live2DModelMiddlewares,{live2dModel:e,source:i,options:s||{}}),yield n,e.emit("load")})}static loadMotion(e,i,s){var r;const a=t=>e.emit("motionLoadError",i,s,t);try{const n=null==(r=e.definitions[i])?void 0:r[s];if(!n)return Promise.resolve(void 0);e.once("destroy",()=>t.releaseMotionTasks(e));let o=t.motionTasksMap.get(e);o||(o={},t.motionTasksMap.set(e,o));let l=o[i];l||(l=[],o[i]=l);const u=e.getMotionFile(n);return null!=l[s]||(l[s]=lt.load({url:u,settings:e.settings,type:e.motionDataType,target:e}).then(r=>{var a;const o=null==(a=t.motionTasksMap.get(e))?void 0:a[i];o&&(o[s]=void 0);const l=r,u=e.createMotion(l,i,n);return e.emit("motionLoaded",i,s,u),u}).catch(t=>{p.warn(e.tag,`Failed to load motion: ${u}\n`,t),a(t)})),l[s]}catch(n){p.warn(e.tag,`Failed to load motion at "${i}"[${s}]\n`,n),a(n)}return Promise.resolve(void 0)}static loadExpression(e,i){var s;const r=t=>e.emit("expressionLoadError",i,t);try{const a=e.definitions[i];if(!a)return Promise.resolve(void 0);e.once("destroy",()=>t.releaseExpressionTasks(e));let n=t.expressionTasksMap.get(e);n||(n=[],t.expressionTasksMap.set(e,n));const o=e.getExpressionFile(a),l=null!=(s=e.expressionDataType)?s:"json";return null!=n[i]||(n[i]=lt.load({url:o,settings:e.settings,type:l,target:e}).then(s=>{const r=t.expressionTasksMap.get(e);r&&(r[i]=void 0);const n=s,o=e.createExpression(n,a);return e.emit("expressionLoaded",i,o),o}).catch(t=>{p.warn(e.tag,`Failed to load expression: ${o}\n`,t),r(t)})),n[i]}catch(a){p.warn(e.tag,`Failed to load expression at [${i}]\n`,a),r(a)}return Promise.resolve(void 0)}static releaseMotionTasks(e){t.motionTasksMap.delete(e)}static releaseExpressionTasks(e){t.expressionTasksMap.delete(e)}};d(bt,"runtimes",[]),d(bt,"urlToJSON",_t),d(bt,"jsonToSettings",ft),d(bt,"waitUntilReady",yt),d(bt,"setupOptionals",xt),d(bt,"setupEssentials",Mt),d(bt,"createInternalModel",Ct),d(bt,"live2DModelMiddlewares",[vt.factory,_t,ft,yt,xt,Mt,Ct]),d(bt,"motionTasksMap",new WeakMap),d(bt,"expressionTasksMap",new WeakMap);let Pt=bt;G.prototype._loadMotion=function(t,e){return Pt.loadMotion(this,t,e)},P.prototype._loadExpression=function(t){return Pt.loadExpression(this,t)},vt.live2dFactory=Pt;const Bt=class t{constructor(i,{autoUpdate:s=!0,autoHitTest:r=!0,autoFocus:a=!0,autoInteract:n,ticker:o}={}){var l;d(this,"model"),d(this,"destroyed",!1),d(this,"_ticker"),d(this,"_autoUpdate",!1),d(this,"_autoHitTest",!1),d(this,"_autoFocus",!1),null!=o||(o=null!=(l=t.defaultTicker)?l:"undefined"!=typeof PIXI?PIXI.Ticker.shared:e.Ticker.shared),void 0!==n&&(r=n,a=n,p.warn(i.tag,"options.autoInteract is deprecated since v0.5.0, use autoHitTest and autoFocus instead.")),this.model=i,this.ticker=o,this.autoUpdate=s,this.autoHitTest=r,this.autoFocus=a,(r||a)&&(this.model.eventMode="static")}get ticker(){return this._ticker}set ticker(t){var e,i;this._ticker&&this._ticker.remove(It,this),this._ticker=t,this._autoUpdate&&(null==(e=this._ticker)||e.add(It,this),null==(i=this._ticker)||i.start())}get autoUpdate(){return this._autoUpdate}set autoUpdate(t){var e;this.destroyed||(t?this._ticker?(this._ticker.add(It,this),this._autoUpdate=!0):p.warn(this.model.tag,"No Ticker to be used for automatic updates. Either set option.ticker when creating Live2DModel, or expose PIXI to global scope (window.PIXI = PIXI)."):(null==(e=this._ticker)||e.remove(It,this),this._autoUpdate=!1))}get autoHitTest(){return this._autoHitTest}set autoHitTest(t){t!==this.autoHitTest&&(t?this.model.on("pointertap",Ft,this):this.model.off("pointertap",Ft,this),this._autoHitTest=t)}get autoFocus(){return this._autoFocus}set autoFocus(t){t!==this.autoFocus&&(t?(this.model.on("globalpointermove",Et,this),this.model.on("pointermove",Et,this)):(this.model.off("globalpointermove",Et,this),this.model.off("pointermove",Et,this)),this._autoFocus=t)}get autoInteract(){return this._autoHitTest&&this._autoFocus}set autoInteract(t){this.autoHitTest=t,this.autoFocus=t}onTickerUpdate(){const t=this.ticker.deltaMS;this.model.update(t)}onTap(t){this.model.tap(t.global.x,t.global.y)}onPointerMove(t){this.model.focus(t.global.x,t.global.y)}destroy(){this.autoFocus=!1,this.autoHitTest=!1,this.autoUpdate=!1,this.ticker=void 0,this.destroyed=!0}};d(Bt,"defaultTicker");let wt=Bt;function It(){this.onTickerUpdate()}function Ft(t){this.onTap(t)}function Et(t){this.onPointerMove(t)}class Lt extends e.Transform{}const Vt=new e.Point,Tt=new e.Matrix,Rt=new e.Matrix,Dt={x:0,y:0,width:0,height:0},At=new e.Bounds;let Ot=!1;class kt{constructor(t){this.renderer=t}addRenderable(t,e){var i,s;null==(s=null==(i=this.renderer.renderPipes.batch)?void 0:i.break)||s.call(i,e),e.add(t)}execute(t){!t.visible||t.alpha<=0||t.renderLive2D(this.renderer)}updateRenderable(){}destroyRenderable(){}validateRenderable(){return!1}destroy(){}}d(kt,"extension",{type:[e.ExtensionType.WebGLPipes],name:"live2d"});const Nt=kt;class Ut extends e.Container{constructor(t){var i;super(),d(this,"renderPipeId","live2d"),d(this,"tag","Live2DModel(uninitialized)"),d(this,"internalModel"),d(this,"textures",[]),d(this,"textureOptions"),d(this,"anchorMode"),d(this,"textureLODStates",[]),d(this,"textureLODFailures",[]),d(this,"transform",new Lt),d(this,"anchor"),d(this,"_bounds",new e.Bounds),d(this,"_boundsDirty",!0),d(this,"_boundsRetryAfterDraw",!1),d(this,"gl",null),d(this,"elapsedTime",0),d(this,"deltaTime",0),d(this,"automator"),d(this,"currentGlId",0),d(this,"renderLive2D",t=>{var i,s,r,a,n;if(!(t instanceof e.WebGLRenderer))throw new Error("Renderer is not supported");t.geometry.resetState(),t.shader.resetState(),t.texture.resetState();let o=!1;this.gl!==t.gl&&(this.gl=t.gl,this.internalModel.updateWebGLContext(t.gl,this.generateUID()),o=!0);const{projectionMatrix:l,offset:u,worldTransformMatrix:h}=t.globalUniforms.globalUniformData,d=Rt.copyFrom(h).append(this.groupTransform),g=(c=d,Math.max(Math.hypot(c.a,c.b),Math.hypot(c.c,c.d))*t.resolution);var c;for(let e=0;e<this.textures.length;e++){const i=this.textures[e];let s=this.resolveTextureForRender(e,i,g);try{this.uploadTextureForRender(t,s,o)}catch(C){if(s===i)throw new Error("Failed to upload Live2D texture.");const r=this.textureLODStates[e];(null==r?void 0:r.texture)===s&&(this.markTextureLODFailure(e,i,r.level),this.destroyTextureLODState(e)),s=i,this.uploadTextureForRender(t,s,o)}this.internalModel.bindTexture(e,t.texture.getGlSource(s.source).texture)}const p=t.renderTarget.viewport,m=t.renderTarget.renderTarget;let _=p.y;if(null==m?void 0:m.isRoot){_=m.colorTexture.source.pixelHeight-p.height-p.y}this.internalModel.viewport=[p.x,_,p.width,p.height];const f=this.deltaTime;this.deltaTime=0,f&&this.internalModel.update(f,this.elapsedTime),d.tx-=null!=(i=null==u?void 0:u.x)?i:0,d.ty-=null!=(s=null==u?void 0:u.y)?s:0;const y=Tt.copyFrom(l).append(d);this.internalModel.updateTransform(y),this.internalModel.draw(t.gl),this._boundsRetryAfterDraw&&this.updateDrawableBounds(),t.state.resetState(),t.texture.resetState();const x=null==(r=t.renderTarget)?void 0:r.defaultClearColor,M=null==(n=null==(a=t.renderTarget)?void 0:a.adaptor)?void 0:n._clearColorCache;x&&(t.gl.clearColor(x[0],x[1],x[2],x[3]),M&&(M[0]=x[0],M[1]=x[1],M[2]=x[2],M[3]=x[3]))}),this.textureOptions=null==t?void 0:t.textureOptions,this.anchorMode=null!=(i=null==t?void 0:t.anchorMode)?i:"canvas",this.anchor=new e.ObservablePoint({_onUpdate:()=>this.onAnchorChange()},0,0),this.automator=new wt(this,t),this.once("modelLoaded",()=>this.initializeOnModelLoad(t))}get isRenderable(){return!0}get canBundle(){return!1}static from(t,e){return g(this,null,function*(){const i=new this(e);return yield Pt.setupLive2DModel(i,t,e),i})}static fromSync(t,e){const i=new this(e);return Pt.setupLive2DModel(i,t,e).then(()=>{var t;return null==(t=null==e?void 0:e.onLoad)?void 0:t.call(e)}).catch(t=>{var i;return null==(i=null==e?void 0:e.onError)?void 0:i.call(e,t)}),i}static registerTicker(t){wt.defaultTicker=t.shared}get bounds(){return this.internalModel?(this._boundsDirty&&this.updateDrawableBounds(),this._bounds):(this._bounds.set(0,0,0,0),this._bounds)}updateDrawableBounds(){if(!this.internalModel)return this._bounds.set(0,0,0,0),void(this._boundsDirty=!1);const t=this.internalModel.getDrawableIDs();At.clear();for(let i=0;i<t.length;i++){const s=t[i],r=this.internalModel.getDrawableIndex(s);if(r<0)continue;const a=this.internalModel.getDrawableBounds(r,Dt);Number.isFinite(a.x)&&Number.isFinite(a.y)&&Number.isFinite(a.width)&&Number.isFinite(a.height)&&At.addFrame(a.x,a.y,a.x+a.width,a.y+a.height,e.Matrix.IDENTITY)}if(this._bounds.clear(),At.isValid&&At.isPositive)this._bounds.addFrame(At.minX,At.minY,At.maxX,At.maxY,this.internalModel.localTransform),this._boundsRetryAfterDraw=!1;else{const t=this.internalModel.originalWidth||this.internalModel.width,e=this.internalModel.originalHeight||this.internalModel.height;this._bounds.addFrame(0,0,t,e,this.internalModel.localTransform),this._boundsRetryAfterDraw=!0}this._boundsDirty=!1,this._didViewChangeTick++,"drawable"===this.anchorMode&&this.onAnchorChange()}generateUID(){return++this.currentGlId}collectRenderables(t,e,i){var s,r,a,n;if(this.parentRenderLayer&&this.parentRenderLayer!==i)return;if(this.globalDisplayStatus<7)return;if(!this.includeInBuild)return;this.sortableChildren&&this.sortChildren(),function(t){const e=t;e.renderPipes.live2d||(Ot||(Ot=!0,console.warn("[untitled-pixi-live2d-engine] Lazy Live2D render pipe registration is deprecated. Register Live2DPlugin explicitly with `extensions.add(Live2DPlugin)` before creating the Pixi renderer.")),e.renderPipes.live2d=new kt(t))}(e);const o=e.renderPipes,l=()=>{o.live2d.addRenderable(this,t)},u=()=>{const s=this.children,r=s.length;for(let a=0;a<r;a++)s[a].collectRenderables(t,e,i)},h=this.effects;if(h){for(let e=0;e<h.length;e++){const i=h[e],a=i.filters;if(a)for(const t of a)t&&"number"==typeof t.resolution&&1===t.resolution&&(t.resolution="inherit");null==(r=null==(s=o[i.pipe])?void 0:s.push)||r.call(s,i,this,t)}l(),u();for(let e=h.length-1;e>=0;e--){const i=h[e];null==(n=null==(a=o[i.pipe])?void 0:a.pop)||n.call(a,i,this,t)}}else l(),u()}initializeOnModelLoad(t){this.tag=`Live2DModel(${this.internalModel.settings.name})`,this.updateDrawableBounds(),"canvas"===this.anchorMode&&this.onAnchorChange()}onAnchorChange(){if(this.internalModel&&this.pivot)if("drawable"===this.anchorMode){const t=this.bounds;this.pivot.set(t.minX+this.anchor.x*t.width,t.minY+this.anchor.y*t.height)}else this.pivot.set(this.anchor.x*this.internalModel.width,this.anchor.y*this.internalModel.height)}motion(t,e,i){return g(this,arguments,function*(t,e,i,{sound:s,volume:r=.5,expression:a,resetExpression:n=!0,onFinish:o,onError:l,loop:u}={}){return void 0===e?this.internalModel.motionManager.startRandomMotion(t,i,{sound:s,volume:r,expression:a,resetExpression:n,onFinish:o,onError:l,loop:u}):this.internalModel.motionManager.startMotion(t,e,i,{sound:s,volume:r,expression:a,resetExpression:n,onFinish:o,onError:l,loop:u})})}motionLastFrame(t,e){return g(this,arguments,function*(t,e,{expression:i}={}){return this.internalModel.motionManager.motionLastFrame(t,e,{expression:i})})}parallelMotion(t){return g(this,null,function*(){this.internalModel.extendParallelMotionManager(t.length);const e=t.map((t,e)=>this.internalModel.parallelMotionManager[e].startMotion(t.group,t.index,t.priority,{ignoreParamIds:t.ignoreParamIds,loop:t.loop})),i=[];for(const t of e)i.push(yield t);return i})}parallelLastFrame(t){return g(this,null,function*(){this.internalModel.extendParallelMotionManager(t.length);const e=t.map((t,e)=>this.internalModel.parallelMotionManager[e].playMotionLastFrame(t.group,t.index)),i=[];for(const t of e)i.push(yield t);return i})}stopMotions(){return this.internalModel.motionManager.stopAllMotions()}speak(t,{volume:e=.5,expression:i,resetExpression:s=!0,onFinish:r,onError:a}={}){return this.internalModel.motionManager.speak(t,{volume:e,expression:i,resetExpression:s,onFinish:r,onError:a})}stopSpeaking(){return this.internalModel.motionManager.stopSpeaking()}expression(t){return this.internalModel.motionManager.expressionManager?void 0===t?this.internalModel.motionManager.expressionManager.setRandomExpression():this.internalModel.motionManager.expressionManager.setExpression(t):Promise.resolve(!1)}focus(t,e,i=!1){Vt.x=t,Vt.y=e,this.toModelPosition(Vt,Vt,!0);const s=Vt.x/this.internalModel.originalWidth*2-1,r=Vt.y/this.internalModel.originalHeight*2-1,a=Math.atan2(r,s);this.internalModel.focusController.focus(Math.cos(a),-Math.sin(a),i)}tap(t,e){const i=this.hitTest(t,e);i.length&&this.emit("hit",i)}hitTest(t,e){return Vt.x=t,Vt.y=e,this.toModelPosition(Vt,Vt),this.internalModel.hitTest(Vt.x,Vt.y)}toModelPosition(t,e=t.clone(),i){return i||this.updateLocalTransform(),this.toLocal(t,void 0,e,i),this.internalModel.localTransform.applyInverse(e,e),e}containsPoint(t){return this.bounds.containsPoint(t.x,t.y)}_calculateBounds(){if(!this.internalModel)return void this.getBounds().set(0,0,0,0);const t=this.bounds;this.getBounds().addFrame(t.minX,t.minY,t.maxX,t.maxY,this.transform.matrix)}update(t){this.deltaTime+=t,this.elapsedTime+=t}resolveTextureForRender(t,i,a){var n;const o=ht((l=h({},this.textureOptions),u={effectiveScale:a,textureWidth:i.source.pixelWidth,textureHeight:i.source.pixelHeight},s(l,r(u))));var l,u;if(!o)return i;const d=this.textureLODFailures[t];if((null==d?void 0:d.source)===i&&d.levels.has(o.level))return i;const g=this.textureLODStates[t];if((null==g?void 0:g.source)===i&&g.level===o.level&&!g.texture.destroyed)return g.texture;this.destroyTextureLODState(t);const c=function(t,i,s,r,a){var n,o;const l=t.source.resource;if(!function(t){if(!t||"object"!=typeof t)return!1;const{width:e,height:i}=t;return"number"==typeof e&&e>0&&"number"==typeof i&&i>0}(l))return;const u=e.DOMAdapter.get().createCanvas(s,r),h=u.getContext("2d");if(!h)return;try{h.clearRect(0,0,s,r),h.imageSmoothingEnabled="nearest"!==a,"imageSmoothingQuality"in h&&"nearest"!==a&&(h.imageSmoothingQuality="high"),h.drawImage(l,0,0,t.source.pixelWidth,t.source.pixelHeight,0,0,s,r)}catch(g){return}const d=`${null!=(o=null!=(n=t.label)?n:t.source.label)?o:"Live2DTexture"} LOD ${i}`;return new e.Texture({label:d,source:new e.CanvasSource({resource:u,width:s,height:r,resolution:1,scaleMode:gt(a),autoGenerateMipmaps:!1,label:d})})}(i,o.level,o.width,o.height,null==(n=this.textureOptions)?void 0:n.lodFilter);return c?(this.textureLODStates[t]={source:i,level:o.level,texture:c},c):(this.markTextureLODFailure(t,i,o.level),i)}markTextureLODFailure(t,e,i){let s=this.textureLODFailures[t];(null==s?void 0:s.source)!==e&&(s={source:e,levels:new Set},this.textureLODFailures[t]=s),s.levels.add(i)}destroyTextureLODState(t){const e=this.textureLODStates[t];e&&(e.texture.destroy(!0),this.textureLODStates[t]=void 0)}destroyTextureLODStates(){for(let t=0;t<this.textureLODStates.length;t++)this.destroyTextureLODState(t);this.textureLODFailures.length=0}uploadTextureForRender(t,e,i){const s=Boolean(e.source._gpuData[t.uid]);!i&&s||(t.gl.pixelStorei(WebGLRenderingContext.UNPACK_FLIP_Y_WEBGL,this.internalModel.textureFlipY),t.texture.bind(e,0))}destroy(t){this.emit("destroy"),this.destroyTextureLODStates(),(null==t?void 0:t.texture)&&this.textures.forEach(e=>e.destroy(t.baseTexture)),this.automator.destroy(),this.internalModel.destroy(),super.destroy(t)}}if(!("Live2D"in window))throw new Error("Could not find Cubism 2 runtime. This plugin requires live2d.min.js to be loaded.");const zt=Live2DMotion.prototype.updateParam;Live2DMotion.prototype.updateParam=function(t,e){zt.call(this,t,e),e.isFinished()&&this.onFinishHandler&&(this.onFinishHandler(this),delete this.onFinishHandler)};class jt extends AMotion{constructor(t){super(),d(this,"params",[]),this.setFadeIn(t.fade_in>0?t.fade_in:c.expressionFadingDuration),this.setFadeOut(t.fade_out>0?t.fade_out:c.expressionFadingDuration),Array.isArray(t.params)&&t.params.forEach(t=>{const e=t.calc||"add";if("add"===e){const e=t.def||0;t.val-=e}else if("mult"===e){const e=t.def||1;t.val/=e}this.params.push({calc:e,val:t.val,id:t.id})})}updateParamExe(t,e,i,s){this.params.forEach(e=>{t.setParamFloat(e.id,e.val*i)})}}class Gt extends P{constructor(t,e){var i;super(t,e),d(this,"queueManager",new MotionQueueManager),d(this,"definitions"),this.definitions=null!=(i=this.settings.expressions)?i:[],this.init()}isFinished(){return this.queueManager.isFinished()}getExpressionIndex(t){return this.definitions.findIndex(e=>e.name===t)}getExpressionFile(t){return t.file}createExpression(t,e){return new jt(t)}_setExpression(t){return this.queueManager.startMotion(t)}stopAllExpressions(){this.queueManager.stopAllMotions()}updateParameters(t,e){return this.queueManager.updateParam(t)}}function Xt(t,e,i){const s=i.getDurationMSec(),r=t.startMotion(i,!0),a=t.motions.find(t=>!!t&&t._$sr===r);return!!a&&(i.updateParamExe(e.coreModel,s,1,a),!0)}class Ht extends G{constructor(t){super(t),d(this,"definitions"),d(this,"groups",{idle:"idle"}),d(this,"motionDataType","arraybuffer"),d(this,"queueManager",new MotionQueueManager),d(this,"lipSyncIds"),d(this,"expressionManager"),this.definitions=this.settings.motions,this.init(t.options),this.lipSyncIds=["PARAM_MOUTH_OPEN_Y"]}init(t){super.init(t),this.settings.expressions&&(this.expressionManager=new Gt(this.settings,t))}isFinished(){return this.queueManager.isFinished()}createMotion(t,e,i){const s=Live2DMotion.loadMotion(t),r=e===this.groups.idle?c.idleMotionFadingDuration:c.motionFadingDuration;return s.setFadeIn(i.fade_in>0?i.fade_in:r),s.setFadeOut(i.fade_out>0?i.fade_out:r),s}getMotionFile(t){return t.file}getMotionName(t){return t.file}getSoundFile(t){return t.sound}_startMotion(t,e,i,s){return t.onFinishHandler=e,i&&i.length>0&&(t.motions=t.motions.filter(t=>!i.includes(t._$4P))),this.queueManager.stopAllMotions(),this.queueManager.startMotion(t)}_stopAllMotions(){this.queueManager.stopAllMotions()}updateParameters(t,e){return this.queueManager.updateParam(t)}destroy(){super.destroy(),this.queueManager=void 0}motionLastFrame(t,e){return g(this,arguments,function*(t,e,{expression:i}={}){const s=yield this.getMotionAndApplyExpression(t,e,i);return!!s&&(this.playing=!0,Xt(this.queueManager,this.parent,s),this.playing=!1,!0)})}}class Yt extends e.EventEmitter{constructor(t){super(),d(this,"tag"),d(this,"manager"),d(this,"settings"),d(this,"state",new L),d(this,"playing",!1),d(this,"destroyed",!1),d(this,"parent"),this.settings=t.settings,this.tag=`ParallelMotionManager(${this.settings.name})`,this.state.tag=this.tag,this.manager=t.motionManager,this.parent=t}startMotion(t,e){return g(this,arguments,function*(t,e,i=E.NORMAL,s={}){var r;const{ignoreParamIds:a=[],loop:n}=Array.isArray(s)?{ignoreParamIds:s,loop:void 0}:s;if(!this.state.reserve(t,e,i))return!1;const o=null==(r=this.manager.definitions[t])?void 0:r[e];if(!o)return!1;const l=yield this.manager.loadMotion(t,e);return!!this.state.start(l,t,e,i)&&(p.log(this.tag,"Start motion:",this.getMotionName(o)),this.emit("motionStart",t,e,void 0),this.playing=!0,this._startMotion(l,void 0,a,n),!0)})}startRandomMotion(t,e){return g(this,arguments,function*(t,e,{loop:i}={}){var s;const r=this.manager.definitions[t];if(null==r?void 0:r.length){const a=[],n=null!=(s=this.manager.motionGroups[t])?s:[];for(let e=0;e<r.length;e++)null===n[e]||this.state.isActive(t,e)||a.push(e);if(a.length){const s=a[Math.floor(Math.random()*a.length)];return this.startMotion(t,s,e,{loop:i})}}return!1})}stopAllMotions(){this._stopAllMotions(),this.state.reset()}update(t,e){return this.isFinished()&&(this.playing&&(this.playing=!1,this.emit("motionFinish")),this.state.complete()),this.updateParameters(t,e)}destroy(){this.destroyed=!0,this.emit("destroy"),this.stopAllMotions()}}class qt extends Yt{constructor(t){super(t),d(this,"queueManager",new MotionQueueManager)}isFinished(){return this.queueManager.isFinished()}getMotionName(t){return t.file}_startMotion(t,e,i,s){return t.onFinishHandler=e,i&&i.length>0&&(t.motions=t.motions.filter(t=>!i.includes(t._$4P))),this.queueManager.stopAllMotions(),this.queueManager.startMotion(t)}_stopAllMotions(){this.queueManager.stopAllMotions()}updateParameters(t,e){return this.queueManager.updateParam(t)}destroy(){super.destroy(),this.queueManager=void 0}playMotionLastFrame(t,e){return g(this,null,function*(){var i;if(!this.state.reserve(t,e,E.FORCE))return!1;const s=null==(i=this.manager.definitions[t])?void 0:i[e];if(!s)return!1;const r=yield this.manager.loadMotion(t,e);return!!this.state.start(r,t,e,E.FORCE)&&(p.log(this.tag,"Start motion:",this.getMotionName(s)),this.queueManager.stopAllMotions(),this.emit("motionStart",t,e,void 0),this.playing=!0,!!Xt(this.queueManager,this.parent,r)&&(this.playing=!1,!0))})}}class Wt{constructor(t){d(this,"leftParam"),d(this,"rightParam"),d(this,"blinkInterval",4e3),d(this,"closingDuration",100),d(this,"closedDuration",50),d(this,"openingDuration",150),d(this,"eyeState",0),d(this,"eyeParamValue",1),d(this,"closedTimer",0),d(this,"nextBlinkTimeLeft",this.blinkInterval),this.coreModel=t,this.leftParam=t.getParamIndex("PARAM_EYE_L_OPEN"),this.rightParam=t.getParamIndex("PARAM_EYE_R_OPEN")}setEyeParams(t){this.eyeParamValue=m(t,0,1),this.coreModel.setParamFloat(this.leftParam,this.eyeParamValue),this.coreModel.setParamFloat(this.rightParam,this.eyeParamValue)}update(t){switch(this.eyeState){case 0:this.nextBlinkTimeLeft-=t,this.nextBlinkTimeLeft<0&&(this.eyeState=1,this.nextBlinkTimeLeft=this.blinkInterval+this.closingDuration+this.closedDuration+this.openingDuration+_(0,2e3));break;case 1:this.setEyeParams(this.eyeParamValue+t/this.closingDuration),this.eyeParamValue<=0&&(this.eyeState=2,this.closedTimer=0);break;case 2:this.closedTimer+=t,this.closedTimer>=this.closedDuration&&(this.eyeState=3);break;case 3:this.setEyeParams(this.eyeParamValue+t/this.openingDuration),this.eyeParamValue>=1&&(this.eyeState=0)}}}const Jt=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);class $t extends st{constructor(t,e,i){super(),d(this,"settings"),d(this,"options"),d(this,"coreModel"),d(this,"motionManager"),d(this,"parallelMotionManager"),d(this,"eyeBlink"),d(this,"eyeballXParamIndex"),d(this,"eyeballYParamIndex"),d(this,"angleXParamIndex"),d(this,"angleYParamIndex"),d(this,"angleZParamIndex"),d(this,"bodyAngleXParamIndex"),d(this,"breathParamIndex"),d(this,"textureFlipY",!0),d(this,"lipSync",!0),d(this,"drawDataCount",0),d(this,"disableCulling",!1),d(this,"hasDrawn",!1),d(this,"customHitAreas"),this.coreModel=t,this.settings=e,this.options=Object.assign({},{breathDepth:1,lipSyncGain:1.5,lipSyncWeight:.4},i),void 0!==(null==i?void 0:i.useHighPrecisionMask)&&!1!==i.useHighPrecisionMask&&p.warn("CubismLegacyInternalModel","`useHighPrecisionMask` is only supported by Cubism 3/4/5 models and will be ignored for Cubism 2 models."),this.motionManager=new Ht(this),this.parallelMotionManager=[],!1!==this.options.eyeBlink&&(this.eyeBlink=new Wt(t)),this.eyeballXParamIndex=t.getParamIndex("PARAM_EYE_BALL_X"),this.eyeballYParamIndex=t.getParamIndex("PARAM_EYE_BALL_Y"),this.angleXParamIndex=t.getParamIndex("PARAM_ANGLE_X"),this.angleYParamIndex=t.getParamIndex("PARAM_ANGLE_Y"),this.angleZParamIndex=t.getParamIndex("PARAM_ANGLE_Z"),this.bodyAngleXParamIndex=t.getParamIndex("PARAM_BODY_ANGLE_X"),this.breathParamIndex=t.getParamIndex("PARAM_BREATH"),this.init()}init(){super.init(),this.settings.initParams&&this.settings.initParams.forEach(({id:t,value:e})=>this.coreModel.setParamFloat(t,e)),this.settings.initOpacities&&this.settings.initOpacities.forEach(({id:t,value:e})=>this.coreModel.setPartsOpacity(t,e)),this.coreModel.saveParam();const t=this.coreModel.getModelContext()._$aS;(null==t?void 0:t.length)&&(this.drawDataCount=t.length);let e=this.coreModel.drawParamWebGL.culling;Object.defineProperty(this.coreModel.drawParamWebGL,"culling",{set:t=>e=t,get:()=>!this.disableCulling&&e});const i=this.coreModel.getModelContext().clipManager,s=i.setupClip.bind(i);i.setupClip=(t,e)=>{s.call(i,t,e),e.gl.viewport(...this.viewport)}}getSize(){return[this.coreModel.getCanvasWidth(),this.coreModel.getCanvasHeight()]}getLayout(){const t={};if(this.settings.layout)for(const[e,i]of Object.entries(this.settings.layout)){let s=e;"center_x"===e?s="centerX":"center_y"===e&&(s="centerY"),"number"==typeof i&&(t[s]=i)}return t}updateWebGLContext(t,e){const i=this.coreModel.drawParamWebGL;i.firstDraw=!0,i.setGL(t),i.glno=e,i._$NT=null,i._$no=null,i._$vS=null;const s=this.coreModel.getModelContext().clipManager;s.curFrameNo=e;const r=t.getParameter(t.FRAMEBUFFER_BINDING);s.getMaskRenderTexture(),t.bindFramebuffer(t.FRAMEBUFFER,r)}bindTexture(t,e){this.coreModel.setTexture(t,e)}getHitAreaDefs(){var t,e,i;const s=this.settings.json;return et(null!=(i=null!=(e=null!=(t=this.settings.hitAreas)?t:s.hit_areas)?e:s.HitAreas)?i:s.hitAreas,t=>this.coreModel.getDrawDataIndex(t))}getDrawableIDs(){const t=this.coreModel.getModelContext(),e=[];for(let i=0;i<this.drawDataCount;i++){const s=t.getDrawData(i);s&&e.push(s.getDrawDataID().id)}return e}getDrawableIndex(t){return this.coreModel.getDrawDataIndex(t)}getDrawableVertices(t){if("string"==typeof t&&-1===(t=this.coreModel.getDrawDataIndex(t)))throw new TypeError("Unable to find drawable ID: "+t);return this.coreModel.getTransformedPoints(t).slice()}hitTest(t,e){this.hasDrawn||p.warn("Trying to hit-test a Cubism 2 model that has not been rendered yet. Drawable hit areas may be empty until the first draw.");const i=super.hitTest(t,e),s=this.hitTestCustom(t,e);return s.length?i.length?[...new Set([...i,...s])]:s:i}update(t,e){var i,s,r,a;super.update(t,e);const n=this.coreModel,o=this.updateMotions(n,e);if(n.saveParam(),null==(i=this.motionManager.expressionManager)||i.update(n,e),o||null==(s=this.eyeBlink)||s.update(t),this.updateFocus(),this.updateNaturalMovements(t,e),this.lipSync&&this.motionManager.currentAudio){let t=this.motionManager.mouthSync()*this.options.lipSyncGain;const e=1,i=t>0?.1:0;t=Math.pow(t,1.15),t=m(t,i,e);for(let s=0;s<this.motionManager.lipSyncIds.length;++s)this.coreModel.addToParamFloat(this.coreModel.getParamIndex(this.motionManager.lipSyncIds[s]),t,this.options.lipSyncWeight)}null==(r=this.physics)||r.update(e),null==(a=this.pose)||a.update(t),this.emit("beforeModelUpdate"),n.update(),n.loadParam()}updateFocus(){this.coreModel.addToParamFloat(this.eyeballXParamIndex,this.focusController.x),this.coreModel.addToParamFloat(this.eyeballYParamIndex,this.focusController.y),this.coreModel.addToParamFloat(this.angleXParamIndex,30*this.focusController.x),this.coreModel.addToParamFloat(this.angleYParamIndex,30*this.focusController.y),this.coreModel.addToParamFloat(this.angleZParamIndex,this.focusController.x*this.focusController.y*-30),this.coreModel.addToParamFloat(this.bodyAngleXParamIndex,10*this.focusController.x)}updateNaturalMovements(t,e){const i=e/1e3*2*Math.PI;this.coreModel.addToParamFloat(this.angleXParamIndex,15*this.options.breathDepth*Math.sin(i/6.5345)*.5),this.coreModel.addToParamFloat(this.angleYParamIndex,8*this.options.breathDepth*Math.sin(i/3.5345)*.5),this.coreModel.addToParamFloat(this.angleZParamIndex,10*this.options.breathDepth*Math.sin(i/5.5345)*.5),this.coreModel.addToParamFloat(this.bodyAngleXParamIndex,4*this.options.breathDepth*Math.sin(i/15.5345)*.5),this.coreModel.setParamFloat(this.breathParamIndex,.5+.5*Math.sin(i/3.2345))}draw(t){const e=this.disableCulling;t.getParameter(t.FRAMEBUFFER_BINDING)&&(this.disableCulling=!0);const i=this.drawingMatrix;Jt[0]=i.a,Jt[1]=i.b,Jt[4]=i.c,Jt[5]=i.d,Jt[12]=i.tx,Jt[13]=i.ty,this.coreModel.setMatrix(Jt),this.coreModel.draw(),this.hasDrawn=!0,this.disableCulling=e}extendParallelMotionManager(t){for(;this.parallelMotionManager.length<t;)this.parallelMotionManager.push(new qt(this))}destroy(){super.destroy(),this.coreModel=void 0}hitTestCustom(t,e){const i=this.getCustomHitAreas();if(!i)return[];const s=this.originalWidth||this.width,r=this.originalHeight||this.height;if(!s||!r)return[];const a=t/s*2-1,n=1-e/r*2,o=[];for(const[l,u]of Object.entries(i))a>=u.minX&&a<=u.maxX&&n>=u.minY&&n<=u.maxY&&o.push(l);return o}getCustomHitAreas(){var t,e,i,s,r;if(void 0!==this.customHitAreas)return this.customHitAreas;const a=this.settings.json,n=null!=(i=null!=(e=null!=(t=a.hit_areas_custom)?t:a.hitAreasCustom)?e:a.HitAreasCustom)?i:a.HitAreas_Custom;if(!n||"object"!=typeof n)return this.customHitAreas=null,null;const o=n,l={},u=(t,e,i)=>{if(!t||!Array.isArray(e)||!Array.isArray(i))return;if(e.length<2||i.length<2)return;const s=Number(e[0]),r=Number(e[1]),a=Number(i[0]),n=Number(i[1]);Number.isFinite(s)&&Number.isFinite(r)&&Number.isFinite(a)&&Number.isFinite(n)&&(l[t]={minX:Math.min(s,r),maxX:Math.max(s,r),minY:Math.min(a,n),maxY:Math.max(a,n)})};for(const[h,d]of Object.entries(o)){if(h.endsWith("_x")){const t=h.slice(0,-2);u(t,d,o[`${t}_y`]);continue}if(!h.endsWith("_y")&&(d&&"object"==typeof d)){const t=d;u(h,null!=(s=t.x)?s:t.X,null!=(r=t.y)?r:t.Y)}}return this.customHitAreas=Object.keys(l).length?l:null,this.customHitAreas}}const Zt={x:PhysicsHair.Src.SRC_TO_X,y:PhysicsHair.Src.SRC_TO_Y,angle:PhysicsHair.Src.SRC_TO_G_ANGLE},Kt={x:PhysicsHair.Src.SRC_TO_X,y:PhysicsHair.Src.SRC_TO_Y,angle:PhysicsHair.Src.SRC_TO_G_ANGLE};class Qt{constructor(t,e){d(this,"physicsHairs",[]),this.coreModel=t,e.physics_hair&&(this.physicsHairs=e.physics_hair.map(t=>{const e=new PhysicsHair;return e.setup(t.setup.length,t.setup.regist,t.setup.mass),t.src.forEach(({id:t,ptype:i,scale:s,weight:r})=>{const a=Zt[i];a&&e.addSrcParam(a,t,s,r)}),t.targets.forEach(({id:t,ptype:i,scale:s,weight:r})=>{const a=Kt[i];a&&e.addTargetParam(a,t,s,r)}),e}))}update(t){this.physicsHairs.forEach(e=>e.update(this.coreModel,t))}}class te{constructor(t){d(this,"paramIndex",-1),d(this,"partsIndex",-1),d(this,"link",[]),this.id=t}initIndex(t){this.paramIndex=t.getParamIndex("VISIBLE:"+this.id),this.partsIndex=t.getPartsDataIndex(PartsDataID.getID(this.id)),t.setParamFloat(this.paramIndex,1)}}class ee{constructor(t,e){d(this,"opacityAnimDuration",500),d(this,"partsGroups",[]),this.coreModel=t,e.parts_visible&&(this.partsGroups=e.parts_visible.map(({group:t})=>t.map(({id:t,link:e})=>{const i=new te(t);return e&&(i.link=e.map(t=>new te(t))),i})),this.init())}init(){this.partsGroups.forEach(t=>{t.forEach(t=>{if(t.initIndex(this.coreModel),t.paramIndex>=0){const e=0!==this.coreModel.getParamFloat(t.paramIndex);this.coreModel.setPartsOpacity(t.partsIndex,e?1:0),this.coreModel.setParamFloat(t.paramIndex,e?1:0),t.link.length>0&&t.link.forEach(t=>t.initIndex(this.coreModel))}})})}normalizePartsOpacityGroup(t,e){const i=this.coreModel,s=.5;let r=1,a=t.findIndex(({paramIndex:t,partsIndex:e})=>e>=0&&0!==i.getParamFloat(t));if(a>=0){const s=i.getPartsOpacity(t[a].partsIndex);r=m(s+e/this.opacityAnimDuration,0,1)}else a=0,r=1;t.forEach(({partsIndex:t},e)=>{if(t>=0)if(a==e)i.setPartsOpacity(t,r);else{let e,a=i.getPartsOpacity(t);e=r<s?-.5*r/s+1:(1-r)*s/.5;(1-e)*(1-r)>.15&&(e=1-.15/(1-r)),a>e&&(a=e),i.setPartsOpacity(t,a)}})}copyOpacity(t){const e=this.coreModel;t.forEach(({partsIndex:t,link:i})=>{if(t>=0&&i){const s=e.getPartsOpacity(t);i.forEach(({partsIndex:t})=>{t>=0&&e.setPartsOpacity(t,s)})}})}update(t){this.partsGroups.forEach(e=>{this.normalizePartsOpacityGroup(e,t),this.copyOpacity(e)})}}if(Pt.registerRuntime({version:2,test:t=>t instanceof ut||ut.isValidJSON(t),ready:()=>Promise.resolve(),isValidMoc(t){if(t.byteLength<3)return!1;const e=new Int8Array(t,0,3);return"moc"===String.fromCharCode(...e)},createModelSettings:t=>new ut(t),createCoreModel(t){const e=Live2DModelWebGL.loadModel(t),i=Live2D.getError();if(i){if(i instanceof Error)throw i;const t="string"==typeof i?i:`Live2D error: ${JSON.stringify(i)}`;throw new Error(t)}return e},createInternalModel:(t,e,i)=>new $t(t,e,i),createPose:(t,e)=>new ee(t,e),createPhysics:(t,e)=>new Qt(t,e)}),"undefined"==typeof window||void 0===window.Live2DCubismCore)throw new Error("Could not find Cubism runtime. This plugin requires live2dcubismcore.js to be loaded.");const ie=class t{constructor(t=0){t<1?(this._ptr=[],this._capacity=0,this._size=0):(this._ptr=new Array(t),this._capacity=t,this._size=0)}at(t){return this._ptr[t]}set(t,e){this._ptr[t]=e}get(t=0){const e=new Array;for(let i=t;i<this._size;i++)e.push(this._ptr[i]);return e}pushBack(e){this._size>=this._capacity&&this.prepareCapacity(0==this._capacity?t.DefaultSize:2*this._capacity),this._ptr[this._size++]=e}clear(){this._ptr.length=0,this._size=0}getSize(){return this._size}assign(t,e){this._size<t&&this.prepareCapacity(t);for(let i=0;i<t;i++)this._ptr[i]=e;this._size=t}resize(t,e=null){this.updateSize(t,e,!0)}updateSize(t,e=null,i=!0){if(this._size<t)if(this.prepareCapacity(t),i)for(let s=this._size;s<t;s++)this._ptr[s]="function"==typeof e?JSON.parse(JSON.stringify(new e)):e;else for(let s=this._size;s<t;s++)this._ptr[s]=e;else{const e=this._size-t;this._ptr.splice(this._size-e,e)}this._size=t}insert(t,e,i){let s=t._index;const r=e._index,a=i._index,n=a-r;this.prepareCapacity(this._size+n);const o=this._size-s;if(o>0)for(let l=0;l<o;l++)this._ptr.splice(s+l,0,null);for(let l=r;l<a;l++,s++)this._ptr[s]=e._vector._ptr[l];this._size=this._size+n}remove(t){return!(t<0||this._size<=t)&&(this._ptr.splice(t,1),--this._size,!0)}erase(t){const e=t._index;if(e<0||this._size<=e)return t;this._ptr.splice(e,1),--this._size;return new re(this,e)}prepareCapacity(t){t>this._capacity&&(0==this._capacity?(this._ptr=new Array(t),this._capacity=t):(this._ptr.length=t,this._capacity=t))}begin(){return 0==this._size?this.end():new re(this,0)}end(){return new re(this,this._size)}getOffset(e){const i=new t;return i._ptr=this.get(e),i._size=this.get(e).length,i._capacity=this.get(e).length,i}};ie.DefaultSize=10;let se=ie,re=class t{constructor(t,e){this._vector=null!=t?t:null,this._index=null!=e?e:0}set(t){return this._index=t._index,this._vector=t._vector,this}preIncrement(){return++this._index,this}preDecrement(){return--this._index,this}increment(){return new t(this._vector,this._index++)}decrement(){return new t(this._vector,this._index--)}ptr(){return this._vector._ptr[this._index]}substitution(t){return this._index=t._index,this._vector=t._vector,this}notEqual(t){return this._index!=t._index||this._vector!=t._vector}};var ae,ne,oe,le,ue,he,de;(ne=ae||(ae={})).csmVector=se,ne.iterator=re;class ge{append(t,e){return this.s+=void 0!==e?t.substr(0,e):t,this}expansion(t,e){for(let i=0;i<t;i++)this.append(e);return this}getBytes(){return encodeURIComponent(this.s).replace(/%../g,"x").length}getLength(){return this.s.length}isLess(t){return this.s<t.s}isGreat(t){return this.s>t.s}isEqual(t){return this.s==t}isEmpty(){return 0==this.s.length}constructor(t){this.s=t}}(t=>{t.csmString=ge})(oe||(oe={}));class ce{static createIdInternal(t){return new ce(t)}getString(){return this._id}isEqual(t){return"string"==typeof t?this._id.isEqual(t):t instanceof ge?this._id.isEqual(t.s):t instanceof ce&&this._id.isEqual(t._id.s)}isNotEqual(t){return"string"==typeof t?!this._id.isEqual(t):t instanceof ge?!this._id.isEqual(t.s):t instanceof ce&&!this._id.isEqual(t._id.s)}constructor(t){this._id="string"!=typeof t?t:new ge(t)}}(t=>{t.CubismId=ce})(le||(le={}));class pe{constructor(){this._ids=new se}release(){for(let t=0;t<this._ids.getSize();++t)this._ids.set(t,void 0);this._ids=null}registerIds(t){for(let e=0;e<t.length;e++)this.registerId(t[e])}registerId(t){let e=null;return"string"!=typeof t?this.registerId(t.s):(null!=(e=this.findId(t))||(e=ce.createIdInternal(t),this._ids.pushBack(e)),e)}getId(t){return this.registerId(t)}isExist(t){return"string"==typeof t?null!=this.findId(t):this.isExist(t.s)}findId(t){for(let e=0;e<this._ids.getSize();++e)if(this._ids.at(e).getString().isEqual(t))return this._ids.at(e);return null}}(t=>{t.CubismIdManager=pe})(ue||(ue={}));class me{constructor(){this._tr=new Float32Array(16),this.loadIdentity()}static multiply(t,e,i){const s=new Float32Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]);for(let r=0;r<4;++r)for(let i=0;i<4;++i)for(let a=0;a<4;++a)s[i+4*r]+=t[a+4*r]*e[i+4*a];for(let r=0;r<16;++r)i[r]=s[r]}loadIdentity(){const t=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);this.setMatrix(t)}setMatrix(t){for(let e=0;e<16;++e)this._tr[e]=t[e]}getArray(){return this._tr}getScaleX(){return this._tr[0]}getScaleY(){return this._tr[5]}getTranslateX(){return this._tr[12]}getTranslateY(){return this._tr[13]}transformX(t){return this._tr[0]*t+this._tr[12]}transformY(t){return this._tr[5]*t+this._tr[13]}invertTransformX(t){return(t-this._tr[12])/this._tr[0]}invertTransformY(t){return(t-this._tr[13])/this._tr[5]}translateRelative(t,e){const i=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,t,e,0,1]);me.multiply(i,this._tr,this._tr)}translate(t,e){this._tr[12]=t,this._tr[13]=e}translateX(t){this._tr[12]=t}translateY(t){this._tr[13]=t}scaleRelative(t,e){const i=new Float32Array([t,0,0,0,0,e,0,0,0,0,1,0,0,0,0,1]);me.multiply(i,this._tr,this._tr)}scale(t,e){this._tr[0]=t,this._tr[5]=e}multiplyByMatrix(t){me.multiply(t.getArray(),this._tr,this._tr)}clone(){const t=new me;for(let e=0;e<this._tr.length;e++)t._tr[e]=this._tr[e];return t}}(t=>{t.CubismMatrix44=me})(he||(he={}));class _e{constructor(t,e,i,s){this.x=t,this.y=e,this.width=i,this.height=s}getCenterX(){return this.x+.5*this.width}getCenterY(){return this.y+.5*this.height}getRight(){return this.x+this.width}getBottom(){return this.y+this.height}setRect(t){this.x=t.x,this.y=t.y,this.width=t.width,this.height=t.height}expand(t,e){this.x-=t,this.y-=e,this.width+=2*t,this.height+=2*e}}(t=>{t.csmRect=_e})(de||(de={}));class fe{static create(){return null}static delete(t){}initialize(t){this._model=t}drawModel(){null!=this.getModel()&&(this.saveProfile(),this.doDrawModel(),this.restoreProfile())}setMvpMatrix(t){this._mvpMatrix4x4.setMatrix(t.getArray())}getMvpMatrix(){return this._mvpMatrix4x4}setModelColor(t,e,i,s){t<0?t=0:t>1&&(t=1),e<0?e=0:e>1&&(e=1),i<0?i=0:i>1&&(i=1),s<0?s=0:s>1&&(s=1),this._modelColor.r=t,this._modelColor.g=e,this._modelColor.b=i,this._modelColor.a=s}getModelColor(){return JSON.parse(JSON.stringify(this._modelColor))}getModelColorWithOpacity(t){const e=this.getModelColor();return e.a*=t,this.isPremultipliedAlpha()&&(e.r*=e.a,e.g*=e.a,e.b*=e.a),e}setIsPremultipliedAlpha(t){this._isPremultipliedAlpha=t}isPremultipliedAlpha(){return this._isPremultipliedAlpha}setIsCulling(t){this._isCulling=t}isCulling(){return this._isCulling}setAnisotropy(t){this._anisotropy=t}getAnisotropy(){return this._anisotropy}getModel(){return this._model}useHighPrecisionMask(t){this._useHighPrecisionMask=t}isUsingHighPrecisionMask(){return this._useHighPrecisionMask}constructor(){this._isCulling=!1,this._isPremultipliedAlpha=!1,this._anisotropy=0,this._model=null,this._modelColor=new Me,this._useHighPrecisionMask=!1,this._mvpMatrix4x4=new me,this._mvpMatrix4x4.loadIdentity()}}var ye,xe=(t=>(t[t.CubismBlendMode_Normal=0]="CubismBlendMode_Normal",t[t.CubismBlendMode_Additive=1]="CubismBlendMode_Additive",t[t.CubismBlendMode_Multiplicative=2]="CubismBlendMode_Multiplicative",t))(xe||{});class Me{constructor(t=1,e=1,i=1,s=1){this.r=t,this.g=e,this.b=i,this.a=s}}class Ce{constructor(t,e){this._clippingIdList=t,this._clippingIdCount=e,this._allClippedDrawRect=new _e,this._layoutBounds=new _e,this._clippedDrawableIndexList=[],this._matrixForMask=new me,this._matrixForDraw=new me,this._bufferIndex=0}release(){null!=this._layoutBounds&&(this._layoutBounds=null),null!=this._allClippedDrawRect&&(this._allClippedDrawRect=null),null!=this._clippedDrawableIndexList&&(this._clippedDrawableIndexList=null)}addClippedDrawable(t){this._clippedDrawableIndexList.push(t)}}(t=>{t.CubismBlendMode=xe,t.CubismRenderer=fe,t.CubismTextureColor=Me})(ye||(ye={}));const Se=(t,e,i)=>{((t,e,i)=>{Ie.print(t,"[CSM]"+e,i)})(t,e+"\n",i)},ve=t=>{console.assert(t)};let be,Pe,Be,we;be=(t,...e)=>{Se(si.LogLevel_Debug,"[D]"+t,e)},Pe=(t,...e)=>{Se(si.LogLevel_Info,"[I]"+t,e)},Be=(t,...e)=>{Se(si.LogLevel_Warning,"[W]"+t,e)},we=(t,...e)=>{Se(si.LogLevel_Error,"[E]"+t,e)};class Ie{static print(t,e,i){if(t<ti.getLoggingLevel())return;const s=ti.coreLogFunction;if(!s)return;s(e.replace(/\{(\d+)\}/g,(t,e)=>i[e]))}static dumpBytes(t,e,i){for(let s=0;s<i;s++)s%16==0&&s>0?this.print(t,"\n"):s%8==0&&s>0&&this.print(t," "),this.print(t,"{0} ",[255&e[s]]);this.print(t,"\n")}constructor(){}}var Fe;(t=>{t.CubismDebug=Ie})(Fe||(Fe={}));class Ee{constructor(t,e){this.first=null==t?null:t,this.second=null==e?null:e}}const Le=class t{constructor(t){null!=t?t<1?(this._keyValues=[],this._dummyValue=null,this._size=0):(this._keyValues=new Array(t),this._size=t):(this._keyValues=[],this._dummyValue=null,this._size=0)}release(){this.clear()}appendKey(t){let e=-1;for(let i=0;i<this._size;i++)if(this._keyValues[i].first==t){e=i;break}-1==e?(this.prepareCapacity(this._size+1,!1),this._keyValues[this._size]=new Ee(t),this._size+=1):Be("The key `{0}` is already append.",t)}getValue(t){let e=-1;for(let i=0;i<this._size;i++)if(this._keyValues[i].first==t){e=i;break}return e>=0?this._keyValues[e].second:(this.appendKey(t),this._keyValues[this._size-1].second)}setValue(t,e){let i=-1;for(let s=0;s<this._size;s++)if(this._keyValues[s].first==t){i=s;break}i>=0?this._keyValues[i].second=e:(this.appendKey(t),this._keyValues[this._size-1].second=e)}isExist(t){for(let e=0;e<this._size;e++)if(this._keyValues[e].first==t)return!0;return!1}clear(){this._keyValues=void 0,this._keyValues=null,this._keyValues=[],this._size=0}getSize(){return this._size}prepareCapacity(e,i){e>this._keyValues.length&&(0==this._keyValues.length?(!i&&e<t.DefaultSize&&(e=t.DefaultSize),this._keyValues.length=e):(!i&&e<2*this._keyValues.length&&(e=2*this._keyValues.length),this._keyValues.length=e))}begin(){return new Te(this,0)}end(){return new Te(this,this._size)}erase(t){const e=t._index;if(e<0||this._size<=e)return t;this._keyValues.splice(e,1),--this._size;return new Te(this,e)}dumpAsInt(){for(let t=0;t<this._size;t++)be("{0} ,",this._keyValues[t]),be("\n")}};Le.DefaultSize=10;let Ve=Le;class Te{constructor(t,e){this._map=null!=t?t:new Ve,this._index=null!=e?e:0}set(t){return this._index=t._index,this._map=t._map,this}preIncrement(){return++this._index,this}preDecrement(){return--this._index,this}increment(){return new Te(this._map,this._index++)}decrement(){const t=new Te(this._map,this._index);return this._map=t._map,this._index=t._index,this}ptr(){return this._map._keyValues[this._index]}notEqual(t){return this._index!=t._index||this._map!=t._map}}var Re;(t=>{t.csmMap=Ve,t.csmPair=Ee,t.iterator=Te})(Re||(Re={}));class De{static parseJsonObject(t,e){return Object.keys(t).forEach(i=>{if("boolean"==typeof t[i]){const s=Boolean(t[i]);e.put(i,new Ue(s))}else if("string"==typeof t[i]){const s=String(t[i]);e.put(i,new ze(s))}else if("number"==typeof t[i]){const s=Number(t[i]);e.put(i,new Ne(s))}else t[i]instanceof Array?e.put(i,De.parseJsonArray(t[i])):t[i]instanceof Object?e.put(i,De.parseJsonObject(t[i],new He)):null==t[i]?e.put(i,new Ge):e.put(i,t[i])}),e}static parseJsonArray(t){const e=new Xe;return Object.keys(t).forEach(i=>{if("number"==typeof Number(i))if("boolean"==typeof t[i]){const s=Boolean(t[i]);e.add(new Ue(s))}else if("string"==typeof t[i]){const s=String(t[i]);e.add(new ze(s))}else if("number"==typeof t[i]){const s=Number(t[i]);e.add(new Ne(s))}else t[i]instanceof Array?e.add(this.parseJsonArray(t[i])):t[i]instanceof Object?e.add(this.parseJsonObject(t[i],new He)):null==t[i]?e.add(new Ge):e.add(t[i]);else if(t[i]instanceof Array)e.add(this.parseJsonArray(t[i]));else if(t[i]instanceof Object)e.add(this.parseJsonObject(t[i],new He));else if(null==t[i])e.add(new Ge);else{const s=Array(t[i]);for(let t=0;t<s.length;t++)e.add(s[t])}}),e}}const Ae="Error: type mismatch";let Oe=class t{constructor(){}getRawString(t,e){return this.getString(t,e)}toInt(t=0){return t}toFloat(t=0){return t}toBoolean(t=!1){return t}getSize(){return 0}getArray(t=null){return t}getVector(t=new se){return t}getMap(t){return t}getValueByIndex(e){return t.errorValue.setErrorNotForClientCall(Ae)}getValueByString(e){return t.nullValue.setErrorNotForClientCall(Ae)}getKeys(){return t.dummyKeys}isError(){return!1}isNull(){return!1}isBool(){return!1}isFloat(){return!1}isString(){return!1}isArray(){return!1}isMap(){return!1}equals(t){return!1}isStatic(){return!1}setErrorNotForClientCall(t){return je.errorValue}static staticInitializeNotForClientCall(){Ue.trueValue=new Ue(!0),Ue.falseValue=new Ue(!1),t.errorValue=new je("ERROR",!0),t.nullValue=new Ge,t.dummyKeys=new se}static staticReleaseNotForClientCall(){Ue.trueValue=null,Ue.falseValue=null,t.errorValue=null,t.nullValue=null,t.dummyKeys=null}};class ke{constructor(t,e){this._parseCallback=De.parseJsonObject,this._error=null,this._lineCount=0,this._root=null,null!=t&&this.parseBytes(t,e,this._parseCallback)}static create(t,e){const i=new ke;return i.parseBytes(t,e,i._parseCallback)?i:(ke.delete(i),null)}static delete(t){}getRoot(){return this._root}static arrayBufferToString(t){const e=new Uint8Array(t);let i="";for(let s=0,r=e.length;s<r;++s)i+="%"+this.pad(e[s].toString(16));return i=decodeURIComponent(i),i}static pad(t){return t.length<2?"0"+t:t}parseBytes(t,e,i){const s=new Array(1),r=ke.arrayBufferToString(t);if(this._root=null==i?this.parseValue(r,e,0,s):i(JSON.parse(r),new He),this._error){let t="\0";return t="Json parse error : @line "+(this._lineCount+1)+"\n",this._root=new ze(t),Pe("{0}",this._root.getRawString()),!1}return null!=this._root||(this._root=new je(new ge(this._error),!1),!1)}getParseError(){return this._error}checkEndOfFile(){return this._root.getArray()[1].equals("EOF")}parseValue(t,e,i,s){if(this._error)return null;let r,a=null,n=i;for(;n<e;n++){switch(t[n]){case"-":case".":case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{const e=new Array(1);return r=qe(t.slice(n),e),s[0]=t.indexOf(e[0]),new Ne(r)}case'"':return new ze(this.parseString(t,e,n+1,s));case"[":return a=this.parseArray(t,e,n+1,s),a;case"{":return a=this.parseObject(t,e,n+1,s),a;case"n":return n+3<e?(a=new Ge,s[0]=n+4):this._error="parse null",a;case"t":return n+3<e?(a=Ue.trueValue,s[0]=n+4):this._error="parse true",a;case"f":return n+4<e?(a=Ue.falseValue,s[0]=n+5):this._error="illegal ',' position",a;case",":return this._error="illegal ',' position",null;case"]":return s[0]=n,null;case"\n":this._lineCount++}}return this._error="illegal end of value",null}parseString(t,e,i,s){if(this._error)return null;if(!t)return this._error="string is null",null;let r,a,n=i;const o=new ge("");let l=i;for(;n<e;n++)switch(r=t[n],r){case'"':return s[0]=n+1,o.append(t.slice(l),n-l),o.s;case"//":if(n++,n-1>l&&o.append(t.slice(l),n-l),l=n+1,n<e)switch(a=t[n],a){case"\\":o.expansion(1,"\\");break;case'"':o.expansion(1,'"');break;case"/":o.expansion(1,"/");break;case"b":o.expansion(1,"\b");break;case"f":o.expansion(1,"\f");break;case"n":o.expansion(1,"\n");break;case"r":o.expansion(1,"\r");break;case"t":o.expansion(1,"\t");break;case"u":this._error="parse string/unicord escape not supported"}else this._error="parse string/escape error"}return this._error="parse string/illegal end",null}parseObject(t,e,i,s){if(this._error)return null;if(!t)return this._error="buffer is null",null;const r=new He;let a="",n=i,o="";const l=Array(1);let u=!1;for(;n<e;n++){t:for(;n<e;n++)switch(o=t[n],o){case'"':if(a=this.parseString(t,e,n+1,l),this._error)return null;n=l[0],u=!0;break t;case"}":return s[0]=n+1,r;case":":this._error="illegal ':' position";break;case"\n":this._lineCount++}if(!u)return this._error="key not found",null;u=!1;t:for(;n<e;n++)switch(o=t[n],o){case":":u=!0,n++;break t;case"}":this._error="illegal '}' position";break;case"\n":this._lineCount++}if(!u)return this._error="':' not found",null;const i=this.parseValue(t,e,n,l);if(this._error)return null;n=l[0],r.put(a,i);t:for(;n<e;n++)switch(o=t[n],o){case",":break t;case"}":return s[0]=n+1,r;case"\n":this._lineCount++}}return this._error="illegal end of perseObject",null}parseArray(t,e,i,s){if(this._error)return null;if(!t)return this._error="buffer is null",null;let r,a=new Xe,n=i;const o=new Array(1);for(;n<e;n++){const i=this.parseValue(t,e,n,o);if(this._error)return null;n=o[0],i&&a.add(i);t:for(;n<e;n++)switch(r=t[n],r){case",":break t;case"]":return s[0]=n+1,a;case"\n":++this._lineCount}}return a=void 0,this._error="illegal end of parseObject",null}}class Ne extends Oe{constructor(t){super(),this._value=t}isFloat(){return!0}getString(t,e){return this._value=parseFloat("\0"),this._stringBuffer="\0",this._stringBuffer}toInt(t=0){return parseInt(this._value.toString())}toFloat(t=0){return this._value}equals(t){return"number"==typeof t&&(!Math.round(t)&&t==this._value)}}class Ue extends Oe{isBool(){return!0}toBoolean(t=!1){return this._boolValue}getString(t,e){return this._stringBuffer=this._boolValue?"true":"false",this._stringBuffer}equals(t){return"boolean"==typeof t&&t==this._boolValue}isStatic(){return!0}constructor(t){super(),this._boolValue=t}}class ze extends Oe{constructor(t){super(),"string"==typeof t&&(this._stringBuffer=t),t instanceof ge&&(this._stringBuffer=t.s)}isString(){return!0}getString(t,e){return this._stringBuffer}equals(t){return"string"==typeof t?this._stringBuffer==t:t instanceof ge&&this._stringBuffer==t.s}}class je extends ze{isStatic(){return this._isStatic}setErrorNotForClientCall(t){return this._stringBuffer=t,this}constructor(t,e){super(t),this._isStatic=e}isError(){return!0}}class Ge extends Oe{isNull(){return!0}getString(t,e){return this._stringBuffer}isStatic(){return!0}setErrorNotForClientCall(t){return this._stringBuffer=t,je.nullValue}constructor(){super(),this._stringBuffer="NullValue"}}class Xe extends Oe{constructor(){super(),this._array=new se}release(){for(let t=this._array.begin();t.notEqual(this._array.end());t.preIncrement()){let e=t.ptr();e&&!e.isStatic()&&(e=void 0,e=null)}}isArray(){return!0}getValueByIndex(t){if(t<0||this._array.getSize()<=t)return Oe.errorValue.setErrorNotForClientCall("Error: index out of bounds");const e=this._array.at(t);return null==e?Oe.nullValue:e}getValueByString(t){return Oe.errorValue.setErrorNotForClientCall(Ae)}getString(t,e){const i=e+"[\n";for(let s=this._array.begin();s.notEqual(this._array.end());s.increment()){const t=s.ptr();this._stringBuffer+=e+""+t.getString(e+" ")+"\n"}return this._stringBuffer=i+e+"]\n",this._stringBuffer}add(t){this._array.pushBack(t)}getVector(t=null){return this._array}getSize(){return this._array.getSize()}}class He extends Oe{constructor(){super(),this._map=new Ve}release(){const t=this._map.begin();for(;t.notEqual(this._map.end());){let e=t.ptr().second;e&&!e.isStatic()&&(e=void 0,e=null),t.preIncrement()}}isMap(){return!0}getValueByString(t){if(t instanceof ge){const e=this._map.getValue(t.s);return null==e?Oe.nullValue:e}for(let e=this._map.begin();e.notEqual(this._map.end());e.preIncrement())if(e.ptr().first==t)return null==e.ptr().second?Oe.nullValue:e.ptr().second;return Oe.nullValue}getValueByIndex(t){return Oe.errorValue.setErrorNotForClientCall(Ae)}getString(t,e){this._stringBuffer=e+"{\n";const i=this._map.begin();for(;i.notEqual(this._map.end());){const t=i.ptr().first,s=i.ptr().second;this._stringBuffer+=e+" "+t+" : "+s.getString(e+" ")+" \n",i.preIncrement()}return this._stringBuffer+=e+"}\n",this._stringBuffer}getMap(t){return this._map}put(t,e){this._map.setValue(t,e)}getKeys(){if(!this._keys){this._keys=new se;const t=this._map.begin();for(;t.notEqual(this._map.end());){const e=t.ptr().first;this._keys.pushBack(e),t.preIncrement()}}return this._keys}getSize(){return this._keys.getSize()}}var Ye;function qe(t,e){let i=0;for(let r=1;;r++){const e=t.slice(r-1,r);if("e"==e||"-"==e||"E"==e)continue;const s=t.substring(0,r),a=Number(s);if(isNaN(a))break;i=r}let s=parseFloat(t);return isNaN(s)&&(s=NaN),e[0]=t.slice(i),s}(t=>{t.CubismJson=ke,t.JsonArray=Xe,t.JsonBoolean=Ue,t.JsonError=je,t.JsonFloat=Ne,t.JsonMap=He,t.JsonNullvalue=Ge,t.JsonString=ze,t.Value=Oe})(Ye||(Ye={}));let We=!1,Je=!1,$e=null,Ze=null;const Ke=Object.freeze({vertexOffset:0,vertexStep:2});function Qe(t){t&&(t=void 0)}class ti{static startUp(t=null){if(We)return Pe("CubismFramework.startUp() is already done."),We;if($e=t,null!=$e&&Live2DCubismCore.Logging.csmSetLogFunction($e.logFunction),We=!0,We){const t=Live2DCubismCore.Version.csmGetVersion(),e=(16711680&t)>>16,i=65535&t,s=t;Pe("Live2D Cubism Core version: {0}.{1}.{2} ({3})",("00"+((4278190080&t)>>24)).slice(-2),("00"+e).slice(-2),("0000"+i).slice(-4),s)}return Pe("CubismFramework.startUp() is complete."),We}static cleanUp(){We=!1,Je=!1,$e=null,Ze=null}static initialize(t=0){ve(We),We?Je?Be("CubismFramework.initialize() skipped, already initialized."):(Oe.staticInitializeNotForClientCall(),Ze=new pe,Live2DCubismCore.Memory.initializeAmountOfMemory(t),Je=!0,Pe("CubismFramework.initialize() is complete.")):Be("CubismFramework is not started.")}static dispose(){ve(We),We?Je?(Oe.staticReleaseNotForClientCall(),Ze.release(),Ze=null,fe.staticRelease(),Je=!1,Pe("CubismFramework.dispose() is complete.")):Be("CubismFramework.dispose() skipped, not initialized."):Be("CubismFramework is not started.")}static isStarted(){return We}static isInitialized(){return Je}static coreLogFunction(t){Live2DCubismCore.Logging.csmGetLogFunction()&&Live2DCubismCore.Logging.csmGetLogFunction()(t)}static getLoggingLevel(){return null!=$e?$e.loggingLevel:5}static getIdManager(){return Ze}constructor(){}}var ei,ii,si=(t=>(t[t.LogLevel_Verbose=0]="LogLevel_Verbose",t[t.LogLevel_Debug=1]="LogLevel_Debug",t[t.LogLevel_Info=2]="LogLevel_Info",t[t.LogLevel_Warning=3]="LogLevel_Warning",t[t.LogLevel_Error=4]="LogLevel_Error",t[t.LogLevel_Off=5]="LogLevel_Off",t))(si||{});(t=>{t.Constant=Ke,t.csmDelete=Qe,t.CubismFramework=ti})(ei||(ei={}));class ri{constructor(t,e){this.x=t,this.y=e,this.x=null==t?0:t,this.y=null==e?0:e}add(t){const e=new ri(0,0);return e.x=this.x+t.x,e.y=this.y+t.y,e}substract(t){const e=new ri(0,0);return e.x=this.x-t.x,e.y=this.y-t.y,e}multiply(t){const e=new ri(0,0);return e.x=this.x*t.x,e.y=this.y*t.y,e}multiplyByScaler(t){return this.multiply(new ri(t,t))}division(t){const e=new ri(0,0);return e.x=this.x/t.x,e.y=this.y/t.y,e}divisionByScalar(t){return this.division(new ri(t,t))}getLength(){return Math.sqrt(this.x*this.x+this.y*this.y)}getDistanceWith(t){return Math.sqrt((this.x-t.x)*(this.x-t.x)+(this.y-t.y)*(this.y-t.y))}dot(t){return this.x*t.x+this.y*t.y}normalize(){const t=Math.pow(this.x*this.x+this.y*this.y,.5);this.x=this.x/t,this.y=this.y/t}isEqual(t){return this.x==t.x&&this.y==t.y}isNotEqual(t){return!this.isEqual(t)}}(t=>{t.CubismVector2=ri})(ii||(ii={}));const ai=class t{static range(t,e,i){return t<e?t=e:t>i&&(t=i),t}static sin(t){return Math.sin(t)}static cos(t){return Math.cos(t)}static abs(t){return Math.abs(t)}static sqrt(t){return Math.sqrt(t)}static cbrt(t){if(0===t)return t;let e=t;const i=e<0;let s;return i&&(e=-e),e===1/0?s=1/0:(s=Math.exp(Math.log(e)/3),s=(e/(s*s)+2*s)/3),i?-s:s}static getEasingSine(t){return t<0?0:t>1?1:.5-.5*this.cos(t*Math.PI)}static max(t,e){return t>e?t:e}static min(t,e){return t>e?e:t}static clamp(t,e,i){return t<e?e:i<t?i:t}static degreesToRadian(t){return t/180*Math.PI}static radianToDegrees(t){return 180*t/Math.PI}static directionToRadian(t,e){let i=Math.atan2(e.y,e.x)-Math.atan2(t.y,t.x);for(;i<-Math.PI;)i+=2*Math.PI;for(;i>Math.PI;)i-=2*Math.PI;return i}static directionToDegrees(t,e){const i=this.directionToRadian(t,e);let s=this.radianToDegrees(i);return e.x-t.x>0&&(s=-s),s}static radianToDirection(t){const e=new ri;return e.x=this.sin(t),e.y=this.cos(t),e}static quadraticEquation(e,i,s){return this.abs(e)<t.Epsilon?this.abs(i)<t.Epsilon?-s:-s/i:-(i+this.sqrt(i*i-4*e*s))/(2*e)}static cardanoAlgorithmForBezier(e,i,s,r){if(this.abs(e)<t.Epsilon)return this.range(this.quadraticEquation(i,s,r),0,1);const a=i/e,n=s/e,o=(3*n-a*a)/3,l=o/3,u=(2*a*a*a-9*a*n+27*(r/e))/27,h=u/2,d=h*h+l*l*l,g=.5,c=.51;if(d<0){const t=-o/3,e=t*t*t,i=this.sqrt(e),s=-u/(2*i),r=this.range(s,-1,1),n=Math.acos(r),l=2*this.cbrt(i),h=l*this.cos(n/3)-a/3;if(this.abs(h-g)<c)return this.range(h,0,1);const d=l*this.cos((n+2*Math.PI)/3)-a/3;if(this.abs(d-g)<c)return this.range(d,0,1);const p=l*this.cos((n+4*Math.PI)/3)-a/3;return this.range(p,0,1)}if(0==d){let t;t=h<0?this.cbrt(-h):-this.cbrt(h);const e=2*t-a/3;if(this.abs(e-g)<c)return this.range(e,0,1);const i=-t-a/3;return this.range(i,0,1)}const p=this.sqrt(d),m=this.cbrt(p-h)-this.cbrt(p+h)-a/3;return this.range(m,0,1)}static mod(t,e){if(!isFinite(t)||0===e||isNaN(t)||isNaN(e))return console.warn(`divided: ${t}, divisor: ${e} mod() returns 'NaN'.`),NaN;const i=Math.abs(t),s=Math.abs(e);let r=i-Math.floor(i/s)*s;return r*=Math.sign(t),r}constructor(){}};ai.Epsilon=1e-5;let ni=ai;var oi,li;(t=>{t.CubismMath=ni})(oi||(oi={}));class ui{constructor(){this.setBeganMotionHandler=t=>this._onBeganMotion=t,this.getBeganMotionHandler=()=>this._onBeganMotion,this.setFinishedMotionHandler=t=>this._onFinishedMotion=t,this.getFinishedMotionHandler=()=>this._onFinishedMotion,this._fadeInSeconds=-1,this._fadeOutSeconds=-1,this._weight=1,this._offsetSeconds=0,this._isLoop=!1,this._isLoopFadeIn=!0,this._previousLoopState=this._isLoop,this._firedEventValues=new se}static delete(t){t.release(),t=null}release(){this._weight=0}updateParameters(t,e,i){if(!e.isAvailable()||e.isFinished())return;this.setupMotionQueueEntry(e,i);const s=this.updateFadeWeight(e,i);this.doUpdateParameters(t,i,s,e),e.getEndTime()>0&&e.getEndTime()<i&&e.setIsFinished(!0)}setupMotionQueueEntry(t,e){null==t||t.isStarted()||t.isAvailable()&&(t.setIsStarted(!0),t.setStartTime(e-this._offsetSeconds),t.setFadeInStartTime(e),t.getEndTime()<0&&this.adjustEndTime(t),t._motion._onBeganMotion&&t._motion._onBeganMotion(t._motion))}updateFadeWeight(t,e){null==t&&Ie.print(si.LogLevel_Error,"motionQueueEntry is null.");let i=this._weight;return i=i*(0==this._fadeInSeconds?1:ni.getEasingSine((e-t.getFadeInStartTime())/this._fadeInSeconds))*(0==this._fadeOutSeconds||t.getEndTime()<0?1:ni.getEasingSine((t.getEndTime()-e)/this._fadeOutSeconds)),t.setState(e,i),ve(0<=i&&i<=1),i}setFadeInTime(t){this._fadeInSeconds=t}setFadeOutTime(t){this._fadeOutSeconds=t}getFadeOutTime(){return this._fadeOutSeconds}getFadeInTime(){return this._fadeInSeconds}setWeight(t){this._weight=t}getWeight(){return this._weight}getDuration(){return-1}getLoopDuration(){return-1}setOffsetTime(t){this._offsetSeconds=t}setLoop(t){this._isLoop=t}getLoop(){return this._isLoop}setLoopFadeIn(t){this._isLoopFadeIn=t}getLoopFadeIn(){return this._isLoopFadeIn}getFiredEvent(t,e){return this._firedEventValues}isExistModelOpacity(){return!1}getModelOpacityIndex(){return-1}getModelOpacityId(t){return null}getModelOpacityValue(){return 1}adjustEndTime(t){const e=this.getDuration(),i=e<=0?-1:t.getStartTime()+e;t.setEndTime(i)}}(t=>{t.ACubismMotion=ui})(li||(li={}));const hi="Parameters",di="Blend",gi=class t extends ui{static create(e,i){const s=new t;return s.parse(e,i),s}doUpdateParameters(t,e,i,s){for(let r=0;r<this._parameters.getSize();++r){const e=this._parameters.at(r);switch(e.blendType){case 0:t.addParameterValueById(e.parameterId,e.value,i);break;case 1:t.multiplyParameterValueById(e.parameterId,e.value,i);break;case 2:t.setParameterValueById(e.parameterId,e.value,i)}}}calculateExpressionParameters(e,i,s,r,a,n){if(null!=s&&null!=r&&s.isAvailable()){this._fadeWeight=this.updateFadeWeight(s,i);for(let i=0;i<r.getSize();++i){const s=r.at(i);if(null==s.parameterId)continue;const o=s.overwriteValue=e.getParameterValueById(s.parameterId),l=this.getExpressionParameters();let u=-1;for(let t=0;t<l.getSize();++t)if(s.parameterId==l.at(t).parameterId){u=t;break}if(u<0){0==a?(s.additiveValue=t.DefaultAdditiveValue,s.multiplyValue=t.DefaultMultiplyValue,s.overwriteValue=o):(s.additiveValue=this.calculateValue(s.additiveValue,t.DefaultAdditiveValue,n),s.multiplyValue=this.calculateValue(s.multiplyValue,t.DefaultMultiplyValue,n),s.overwriteValue=this.calculateValue(s.overwriteValue,o,n));continue}const h=l.at(u).value;let d,g,c;switch(l.at(u).blendType){case 0:d=h,g=t.DefaultMultiplyValue,c=o;break;case 1:d=t.DefaultAdditiveValue,g=h,c=o;break;case 2:d=t.DefaultAdditiveValue,g=t.DefaultMultiplyValue,c=h;break;default:return}0==a?(s.additiveValue=d,s.multiplyValue=g,s.overwriteValue=c):(s.additiveValue=s.additiveValue*(1-n)+d*n,s.multiplyValue=s.multiplyValue*(1-n)+g*n,s.overwriteValue=s.overwriteValue*(1-n)+c*n)}}}getExpressionParameters(){return this._parameters}getFadeWeight(){return this._fadeWeight}parse(t,e){const i=ke.create(t,e);if(!i)return;const s=i.getRoot();this.setFadeInTime(s.getValueByString("FadeInTime").toFloat(1)),this.setFadeOutTime(s.getValueByString("FadeOutTime").toFloat(1));const r=s.getValueByString(hi).getSize();this._parameters.prepareCapacity(r);for(let a=0;a<r;++a){const t=s.getValueByString(hi).getValueByIndex(a),e=ti.getIdManager().getId(t.getValueByString("Id").getRawString()),i=t.getValueByString("Value").toFloat();let r;r=t.getValueByString(di).isNull()||"Add"==t.getValueByString(di).getString()?0:"Multiply"==t.getValueByString(di).getString()?1:"Overwrite"==t.getValueByString(di).getString()?2:0;const n=new fi;n.parameterId=e,n.blendType=r,n.value=i,this._parameters.pushBack(n)}ke.delete(i)}calculateValue(t,e,i){return t*(1-i)+e*i}constructor(){super(),this._parameters=new se,this._fadeWeight=0}};gi.DefaultAdditiveValue=0,gi.DefaultMultiplyValue=1;let ci=gi;var pi,mi,_i=(t=>(t[t.Additive=0]="Additive",t[t.Multiply=1]="Multiply",t[t.Overwrite=2]="Overwrite",t))(_i||{});class fi{}(t=>{t.CubismExpressionMotion=ci,t.ExpressionBlendType=_i,t.ExpressionParameter=fi})(pi||(pi={}));class yi{constructor(){this._autoDelete=!1,this._motion=null,this._available=!0,this._finished=!1,this._started=!1,this._startTimeSeconds=-1,this._fadeInStartTimeSeconds=0,this._endTimeSeconds=-1,this._stateTimeSeconds=0,this._stateWeight=0,this._lastEventCheckSeconds=0,this._motionQueueEntryHandle=this,this._fadeOutSeconds=0,this._isTriggeredFadeOut=!1}release(){this._autoDelete&&this._motion&&ui.delete(this._motion)}setFadeOut(t){this._fadeOutSeconds=t,this._isTriggeredFadeOut=!0}startFadeOut(t,e){const i=e+t;this._isTriggeredFadeOut=!0,(this._endTimeSeconds<0||i<this._endTimeSeconds)&&(this._endTimeSeconds=i)}isFinished(){return this._finished}isStarted(){return this._started}getStartTime(){return this._startTimeSeconds}getFadeInStartTime(){return this._fadeInStartTimeSeconds}getEndTime(){return this._endTimeSeconds}setStartTime(t){this._startTimeSeconds=t}setFadeInStartTime(t){this._fadeInStartTimeSeconds=t}setEndTime(t){this._endTimeSeconds=t}setIsFinished(t){this._finished=t}setIsStarted(t){this._started=t}isAvailable(){return this._available}setIsAvailable(t){this._available=t}setState(t,e){this._stateTimeSeconds=t,this._stateWeight=e}getStateTime(){return this._stateTimeSeconds}getStateWeight(){return this._stateWeight}getLastCheckEventSeconds(){return this._lastEventCheckSeconds}setLastCheckEventSeconds(t){this._lastEventCheckSeconds=t}isTriggeredFadeOut(){return this._isTriggeredFadeOut}getFadeOutSeconds(){return this._fadeOutSeconds}getCubismMotion(){return this._motion}}(t=>{t.CubismMotionQueueEntry=yi})(mi||(mi={}));class xi{constructor(){this._userTimeSeconds=0,this._eventCallBack=null,this._eventCustomData=null,this._motions=new se}release(){for(let t=0;t<this._motions.getSize();++t)this._motions.at(t)&&(this._motions.at(t).release(),this._motions.set(t,null));this._motions=null}startMotion(t,e,i){if(null==t)return Mi;let s=null;for(let r=0;r<this._motions.getSize();++r)s=this._motions.at(r),null!=s&&s.setFadeOut(s._motion.getFadeOutTime());return s=new yi,s._autoDelete=e,s._motion=t,this._motions.pushBack(s),s._motionQueueEntryHandle}isFinished(){for(let t=this._motions.begin();t.notEqual(this._motions.end());){let e=t.ptr();if(null==e){t=this._motions.erase(t);continue}if(null!=e._motion){if(!e.isFinished())return!1;t.preIncrement()}else e.release(),e=null,t=this._motions.erase(t)}return!0}isFinishedByHandle(t){for(let e=this._motions.begin();e.notEqual(this._motions.end());e.increment()){const i=e.ptr();if(null!=i&&(i._motionQueueEntryHandle==t&&!i.isFinished()))return!1}return!0}stopAllMotions(){for(let t=this._motions.begin();t.notEqual(this._motions.end());){let e=t.ptr();null!=e?(e.release(),e=null,t=this._motions.erase(t)):t=this._motions.erase(t)}}getCubismMotionQueueEntries(){return this._motions}getCubismMotionQueueEntry(t){for(let e=this._motions.begin();e.notEqual(this._motions.end());e.preIncrement()){const i=e.ptr();if(null!=i&&i._motionQueueEntryHandle==t)return i}return null}setEventCallback(t,e=null){this._eventCallBack=t,this._eventCustomData=e}doUpdateMotion(t,e){let i=!1;for(let s=this._motions.begin();s.notEqual(this._motions.end());){let r=s.ptr();if(null==r){s=this._motions.erase(s);continue}const a=r._motion;if(null==a){r.release(),r=null,s=this._motions.erase(s);continue}a.updateParameters(t,r,e),i=!0;const n=a.getFiredEvent(r.getLastCheckEventSeconds()-r.getStartTime(),e-r.getStartTime());for(let t=0;t<n.getSize();++t)this._eventCallBack(this,n.at(t),this._eventCustomData);r.setLastCheckEventSeconds(e),r.isFinished()?(r.release(),r=null,s=this._motions.erase(s)):(r.isTriggeredFadeOut()&&r.startFadeOut(r.getFadeOutSeconds(),e),s.preIncrement())}return i}}const Mi=-1;var Ci;(t=>{t.CubismMotionQueueManager=xi,t.InvalidMotionQueueEntryHandleValue=Mi})(Ci||(Ci={}));class Si extends P{constructor(t,e){var i,s;super(t,e),d(this,"expressionDataType","arraybuffer"),d(this,"queueManager",new xi),d(this,"definitions"),this.definitions=null!=(s=null==(i=t.expressions)?void 0:i.filter(t=>!!t&&"string"==typeof t.File))?s:[],this.init()}isFinished(){return this.queueManager.isFinished()}getExpressionIndex(t){return this.definitions.findIndex(e=>e.Name===t)}getExpressionFile(t){return t.File}createExpression(t,e){return ci.create(t,t.byteLength)}_setExpression(t){return this.queueManager.startMotion(t,!1)}stopAllExpressions(){this.queueManager.stopAllMotions()}updateParameters(t,e){return this.queueManager.doUpdateMotion(t,e)}createDefaultExpression(){const t=(new TextEncoder).encode(JSON.stringify({FadeInTime:0,FadeOutTime:0,Parameters:[]})).buffer;return ci.create(t,t.byteLength)}}var vi,bi=(t=>(t[t.CubismMotionCurveTarget_Model=0]="CubismMotionCurveTarget_Model",t[t.CubismMotionCurveTarget_Parameter=1]="CubismMotionCurveTarget_Parameter",t[t.CubismMotionCurveTarget_PartOpacity=2]="CubismMotionCurveTarget_PartOpacity",t))(bi||{}),Pi=(t=>(t[t.CubismMotionSegmentType_Linear=0]="CubismMotionSegmentType_Linear",t[t.CubismMotionSegmentType_Bezier=1]="CubismMotionSegmentType_Bezier",t[t.CubismMotionSegmentType_Stepped=2]="CubismMotionSegmentType_Stepped",t[t.CubismMotionSegmentType_InverseStepped=3]="CubismMotionSegmentType_InverseStepped",t))(Pi||{});class Bi{constructor(){this.time=0,this.value=0}}class wi{constructor(){this.evaluate=null,this.basePointIndex=0,this.segmentType=0}}class Ii{constructor(){this.type=0,this.segmentCount=0,this.baseSegmentIndex=0,this.fadeInTime=0,this.fadeOutTime=0}}class Fi{constructor(){this.fireTime=0}}class Ei{constructor(){this.duration=0,this.loop=!1,this.curveCount=0,this.eventCount=0,this.fps=0,this.curves=new se,this.segments=new se,this.points=new se,this.events=new se}}(t=>{t.CubismMotionCurve=Ii,t.CubismMotionCurveTarget=bi,t.CubismMotionData=Ei,t.CubismMotionEvent=Fi,t.CubismMotionPoint=Bi,t.CubismMotionSegment=wi,t.CubismMotionSegmentType=Pi})(vi||(vi={}));const Li="Meta",Vi="Curves",Ti="FadeInTime",Ri="FadeOutTime",Di="Segments",Ai="UserData";class Oi{constructor(t,e){this._json=ke.create(t,e)}release(){ke.delete(this._json)}getMotionDuration(){return this._json.getRoot().getValueByString(Li).getValueByString("Duration").toFloat()}isMotionLoop(){return this._json.getRoot().getValueByString(Li).getValueByString("Loop").toBoolean()}hasConsistency(){let t=!0;if(!this._json||!this._json.getRoot())return!1;const e=this._json.getRoot().getValueByString(Vi).getVector().getSize();let i=0,s=0;for(let r=0;r<e;++r)for(let t=0;t<this.getMotionCurveSegmentCount(r);){0==t&&(s+=1,t+=2);switch(this.getMotionCurveSegment(r,t)){case Pi.CubismMotionSegmentType_Linear:s+=1,t+=3;break;case Pi.CubismMotionSegmentType_Bezier:s+=3,t+=7;break;case Pi.CubismMotionSegmentType_Stepped:case Pi.CubismMotionSegmentType_InverseStepped:s+=1,t+=3;break;default:ve(0)}++i}return e!=this.getMotionCurveCount()&&(Be("The number of curves does not match the metadata."),t=!1),i!=this.getMotionTotalSegmentCount()&&(Be("The number of segment does not match the metadata."),t=!1),s!=this.getMotionTotalPointCount()&&(Be("The number of point does not match the metadata."),t=!1),t}getEvaluationOptionFlag(t){return 0==t&&this._json.getRoot().getValueByString(Li).getValueByString("AreBeziersRestricted").toBoolean()}getMotionCurveCount(){return this._json.getRoot().getValueByString(Li).getValueByString("CurveCount").toInt()}getMotionFps(){return this._json.getRoot().getValueByString(Li).getValueByString("Fps").toFloat()}getMotionTotalSegmentCount(){return this._json.getRoot().getValueByString(Li).getValueByString("TotalSegmentCount").toInt()}getMotionTotalPointCount(){return this._json.getRoot().getValueByString(Li).getValueByString("TotalPointCount").toInt()}isExistMotionFadeInTime(){return!this._json.getRoot().getValueByString(Li).getValueByString(Ti).isNull()}isExistMotionFadeOutTime(){return!this._json.getRoot().getValueByString(Li).getValueByString(Ri).isNull()}getMotionFadeInTime(){return this._json.getRoot().getValueByString(Li).getValueByString(Ti).toFloat()}getMotionFadeOutTime(){return this._json.getRoot().getValueByString(Li).getValueByString(Ri).toFloat()}getMotionCurveTarget(t){return this._json.getRoot().getValueByString(Vi).getValueByIndex(t).getValueByString("Target").getRawString()}getMotionCurveId(t){return ti.getIdManager().getId(this._json.getRoot().getValueByString(Vi).getValueByIndex(t).getValueByString("Id").getRawString())}isExistMotionCurveFadeInTime(t){return!this._json.getRoot().getValueByString(Vi).getValueByIndex(t).getValueByString(Ti).isNull()}isExistMotionCurveFadeOutTime(t){return!this._json.getRoot().getValueByString(Vi).getValueByIndex(t).getValueByString(Ri).isNull()}getMotionCurveFadeInTime(t){return this._json.getRoot().getValueByString(Vi).getValueByIndex(t).getValueByString(Ti).toFloat()}getMotionCurveFadeOutTime(t){return this._json.getRoot().getValueByString(Vi).getValueByIndex(t).getValueByString(Ri).toFloat()}getMotionCurveSegmentCount(t){return this._json.getRoot().getValueByString(Vi).getValueByIndex(t).getValueByString(Di).getVector().getSize()}getMotionCurveSegment(t,e){return this._json.getRoot().getValueByString(Vi).getValueByIndex(t).getValueByString(Di).getValueByIndex(e).toFloat()}getEventCount(){return this._json.getRoot().getValueByString(Li).getValueByString("UserDataCount").toInt()}getTotalEventValueSize(){return this._json.getRoot().getValueByString(Li).getValueByString("TotalUserDataSize").toInt()}getEventTime(t){return this._json.getRoot().getValueByString(Ai).getValueByIndex(t).getValueByString("Time").toFloat()}getEventValue(t){return new ge(this._json.getRoot().getValueByString(Ai).getValueByIndex(t).getValueByString("Value").getRawString())}}var ki,Ni=(t=>(t[t.EvaluationOptionFlag_AreBeziersRistricted=0]="EvaluationOptionFlag_AreBeziersRistricted",t))(Ni||{});(t=>{t.CubismMotionJson=Oi})(ki||(ki={}));const Ui="Opacity";function zi(t,e,i){const s=new Bi;return s.time=t.time+(e.time-t.time)*i,s.value=t.value+(e.value-t.value)*i,s}function ji(t,e){let i=(e-t[0].time)/(t[1].time-t[0].time);return i<0&&(i=0),t[0].value+(t[1].value-t[0].value)*i}function Gi(t,e){let i=(e-t[0].time)/(t[3].time-t[0].time);i<0&&(i=0);const s=zi(t[0],t[1],i),r=zi(t[1],t[2],i),a=zi(t[2],t[3],i),n=zi(s,r,i),o=zi(r,a,i);return zi(n,o,i).value}function Xi(t,e){const i=e,s=t[0].time,r=t[3].time,a=t[1].time,n=t[2].time,o=r-3*n+3*a-s,l=3*n-6*a+3*s,u=3*a-3*s,h=s-i,d=ni.cardanoAlgorithmForBezier(o,l,u,h),g=zi(t[0],t[1],d),c=zi(t[1],t[2],d),p=zi(t[2],t[3],d),m=zi(g,c,d),_=zi(c,p,d);return zi(m,_,d).value}function Hi(t,e){return t[0].value}function Yi(t,e){return t[1].value}function qi(t,e,i,s,r){const a=t.curves.at(e);let n=-1;const o=a.baseSegmentIndex+a.segmentCount;let l=0;for(let h=a.baseSegmentIndex;h<o;++h)if(l=t.segments.at(h).basePointIndex+(t.segments.at(h).segmentType==Pi.CubismMotionSegmentType_Bezier?3:1),t.points.at(l).time>i){n=h;break}if(-1==n)return s&&i<r?function(t,e,i,s,r,a){const n=[new Bi,new Bi];{const e=t.points.at(s);n[0].time=e.time,n[0].value=e.value}{const e=t.points.at(i);n[1].time=a,n[1].value=e.value}switch(t.segments.at(e).segmentType){case Pi.CubismMotionSegmentType_Linear:case Pi.CubismMotionSegmentType_Bezier:default:return ji(n,r);case Pi.CubismMotionSegmentType_Stepped:return Hi(n);case Pi.CubismMotionSegmentType_InverseStepped:return Yi(n)}}(t,o-1,t.segments.at(a.baseSegmentIndex).basePointIndex,l,i,r):t.points.at(l).value;const u=t.segments.at(n);return u.evaluate(t.points.get(u.basePointIndex),i)}class Wi extends ui{constructor(){super(),this._motionBehavior=1,this._sourceFrameRate=30,this._loopDurationSeconds=-1,this._isLoop=!1,this._isLoopFadeIn=!0,this._lastWeight=0,this._motionData=null,this._modelCurveIdEyeBlink=null,this._modelCurveIdLipSync=null,this._modelCurveIdOpacity=null,this._eyeBlinkParameterIds=null,this._lipSyncParameterIds=null,this._modelOpacity=1,this._debugMode=!1}static create(t,e,i,s,r=!1){const a=new Wi;return a.parse(t,e,r),a._motionData?(a._sourceFrameRate=a._motionData.fps,a._loopDurationSeconds=a._motionData.duration,a._onFinishedMotion=i,a._onBeganMotion=s,a):(Qe(a),null)}doUpdateParameters(t,e,i,s){null==this._modelCurveIdEyeBlink&&(this._modelCurveIdEyeBlink=ti.getIdManager().getId("EyeBlink")),null==this._modelCurveIdLipSync&&(this._modelCurveIdLipSync=ti.getIdManager().getId("LipSync")),null==this._modelCurveIdOpacity&&(this._modelCurveIdOpacity=ti.getIdManager().getId(Ui)),1===this._motionBehavior&&this._previousLoopState!==this._isLoop&&(this.adjustEndTime(s),this._previousLoopState=this._isLoop);let r=e-s.getStartTime();r<0&&(r=0);let a=Number.MAX_VALUE,n=Number.MAX_VALUE;const o=64;let l=0,u=0;this._eyeBlinkParameterIds.getSize()>o&&be("too many eye blink targets : {0}",this._eyeBlinkParameterIds.getSize()),this._lipSyncParameterIds.getSize()>o&&be("too many lip sync targets : {0}",this._lipSyncParameterIds.getSize());const h=this._fadeInSeconds<=0?1:ni.getEasingSine((e-s.getFadeInStartTime())/this._fadeInSeconds),d=this._fadeOutSeconds<=0||s.getEndTime()<0?1:ni.getEasingSine((s.getEndTime()-e)/this._fadeOutSeconds);let g,c,p,m=r,_=this._motionData.duration;const f=1===this._motionBehavior&&this._isLoop;if(this._isLoop)for(1===this._motionBehavior&&(_+=1/this._motionData.fps);m>_;)m-=_;const y=this._motionData.curves;for(c=0;c<this._motionData.curveCount&&y.at(c).type==bi.CubismMotionCurveTarget_Model;++c)g=qi(this._motionData,c,m,f,_),y.at(c).id==this._modelCurveIdEyeBlink?n=g:y.at(c).id==this._modelCurveIdLipSync?a=g:y.at(c).id==this._modelCurveIdOpacity&&(this._modelOpacity=g,t.setModelOapcity(this.getModelOpacityValue()));for(;c<this._motionData.curveCount&&y.at(c).type==bi.CubismMotionCurveTarget_Parameter;++c){if(p=t.getParameterIndex(y.at(c).id),-1==p)continue;const r=t.getParameterValueByIndex(p);if(g=qi(this._motionData,c,m,f,_),n!=Number.MAX_VALUE)for(let t=0;t<this._eyeBlinkParameterIds.getSize()&&t<o;++t)if(this._eyeBlinkParameterIds.at(t)==y.at(c).id){g*=n,u|=1<<t;break}if(a!=Number.MAX_VALUE)for(let t=0;t<this._lipSyncParameterIds.getSize()&&t<o;++t)if(this._lipSyncParameterIds.at(t)==y.at(c).id){g+=a,l|=1<<t;break}let x;if(t.isRepeat(p)&&(g=t.getParameterRepeatValue(p,g)),y.at(c).fadeInTime<0&&y.at(c).fadeOutTime<0)x=r+(g-r)*i;else{let t,i;t=y.at(c).fadeInTime<0?h:0==y.at(c).fadeInTime?1:ni.getEasingSine((e-s.getFadeInStartTime())/y.at(c).fadeInTime),i=y.at(c).fadeOutTime<0?d:0==y.at(c).fadeOutTime||s.getEndTime()<0?1:ni.getEasingSine((s.getEndTime()-e)/y.at(c).fadeOutTime);x=r+(g-r)*(this._weight*t*i)}t.setParameterValueByIndex(p,x,1)}if(n!=Number.MAX_VALUE)for(let x=0;x<this._eyeBlinkParameterIds.getSize()&&x<o;++x){const e=t.getParameterValueById(this._eyeBlinkParameterIds.at(x));if(u>>x&1)continue;const s=e+(n-e)*i;t.setParameterValueById(this._eyeBlinkParameterIds.at(x),s)}if(a!=Number.MAX_VALUE)for(let x=0;x<this._lipSyncParameterIds.getSize()&&x<o;++x){const e=t.getParameterValueById(this._lipSyncParameterIds.at(x));if(l>>x&1)continue;const s=e+(a-e)*i;t.setParameterValueById(this._lipSyncParameterIds.at(x),s)}for(;c<this._motionData.curveCount&&y.at(c).type==bi.CubismMotionCurveTarget_PartOpacity;++c)p=t.getParameterIndex(y.at(c).id),-1!=p&&(g=qi(this._motionData,c,m,f,_),t.setParameterValueByIndex(p,g));r>=_&&(this._isLoop?this.updateForNextLoop(s,e,m):(this._onFinishedMotion&&this._onFinishedMotion(this),s.setIsFinished(!0))),this._lastWeight=i}setIsLoop(t){Be("setIsLoop() is a deprecated function. Please use setLoop()."),this._isLoop=t}isLoop(){return Be("isLoop() is a deprecated function. Please use getLoop()."),this._isLoop}setIsLoopFadeIn(t){Be("setIsLoopFadeIn() is a deprecated function. Please use setLoopFadeIn()."),this._isLoopFadeIn=t}isLoopFadeIn(){return Be("isLoopFadeIn() is a deprecated function. Please use getLoopFadeIn()."),this._isLoopFadeIn}setMotionBehavior(t){this._motionBehavior=t}getMotionBehavior(){return this._motionBehavior}getDuration(){return this._isLoop?-1:this._loopDurationSeconds}getLoopDuration(){return this._loopDurationSeconds}setParameterFadeInTime(t,e){const i=this._motionData.curves;for(let s=0;s<this._motionData.curveCount;++s)if(t==i.at(s).id)return void(i.at(s).fadeInTime=e)}setParameterFadeOutTime(t,e){const i=this._motionData.curves;for(let s=0;s<this._motionData.curveCount;++s)if(t==i.at(s).id)return void(i.at(s).fadeOutTime=e)}getParameterFadeInTime(t){const e=this._motionData.curves;for(let i=0;i<this._motionData.curveCount;++i)if(t==e.at(i).id)return e.at(i).fadeInTime;return-1}getParameterFadeOutTime(t){const e=this._motionData.curves;for(let i=0;i<this._motionData.curveCount;++i)if(t==e.at(i).id)return e.at(i).fadeOutTime;return-1}setEffectIds(t,e){this._eyeBlinkParameterIds=t,this._lipSyncParameterIds=e}release(){this._motionData=void 0,this._motionData=null}updateForNextLoop(t,e,i){switch(this._motionBehavior){case 1:default:t.setStartTime(e-i),this._isLoopFadeIn&&t.setFadeInStartTime(e-i),null!=this._onFinishedMotion&&this._onFinishedMotion(this);break;case 0:t.setStartTime(e),this._isLoopFadeIn&&t.setFadeInStartTime(e)}}parse(t,e,i=!1){let s=new Oi(t,e);if(!s)return s.release(),void(s=void 0);if(i){if(!s.hasConsistency())return s.release(),void we("Inconsistent motion3.json.")}this._motionData=new Ei,this._motionData.duration=s.getMotionDuration(),this._motionData.loop=s.isMotionLoop(),this._motionData.curveCount=s.getMotionCurveCount(),this._motionData.fps=s.getMotionFps(),this._motionData.eventCount=s.getEventCount();const r=s.getEvaluationOptionFlag(Ni.EvaluationOptionFlag_AreBeziersRistricted);s.isExistMotionFadeInTime()?this._fadeInSeconds=s.getMotionFadeInTime()<0?1:s.getMotionFadeInTime():this._fadeInSeconds=1,s.isExistMotionFadeOutTime()?this._fadeOutSeconds=s.getMotionFadeOutTime()<0?1:s.getMotionFadeOutTime():this._fadeOutSeconds=1,this._motionData.curves.updateSize(this._motionData.curveCount,Ii,!0),this._motionData.segments.updateSize(s.getMotionTotalSegmentCount(),wi,!0),this._motionData.points.updateSize(s.getMotionTotalPointCount(),Bi,!0),this._motionData.events.updateSize(this._motionData.eventCount,Fi,!0);let a=0,n=0;for(let o=0;o<this._motionData.curveCount;++o){"Model"==s.getMotionCurveTarget(o)?this._motionData.curves.at(o).type=bi.CubismMotionCurveTarget_Model:"Parameter"==s.getMotionCurveTarget(o)?this._motionData.curves.at(o).type=bi.CubismMotionCurveTarget_Parameter:"PartOpacity"==s.getMotionCurveTarget(o)?this._motionData.curves.at(o).type=bi.CubismMotionCurveTarget_PartOpacity:Be('Warning : Unable to get segment type from Curve! The number of "CurveCount" may be incorrect!'),this._motionData.curves.at(o).id=s.getMotionCurveId(o),this._motionData.curves.at(o).baseSegmentIndex=n,this._motionData.curves.at(o).fadeInTime=s.isExistMotionCurveFadeInTime(o)?s.getMotionCurveFadeInTime(o):-1,this._motionData.curves.at(o).fadeOutTime=s.isExistMotionCurveFadeOutTime(o)?s.getMotionCurveFadeOutTime(o):-1;for(let t=0;t<s.getMotionCurveSegmentCount(o);){0==t?(this._motionData.segments.at(n).basePointIndex=a,this._motionData.points.at(a).time=s.getMotionCurveSegment(o,t),this._motionData.points.at(a).value=s.getMotionCurveSegment(o,t+1),a+=1,t+=2):this._motionData.segments.at(n).basePointIndex=a-1;switch(s.getMotionCurveSegment(o,t)){case Pi.CubismMotionSegmentType_Linear:this._motionData.segments.at(n).segmentType=Pi.CubismMotionSegmentType_Linear,this._motionData.segments.at(n).evaluate=ji,this._motionData.points.at(a).time=s.getMotionCurveSegment(o,t+1),this._motionData.points.at(a).value=s.getMotionCurveSegment(o,t+2),a+=1,t+=3;break;case Pi.CubismMotionSegmentType_Bezier:this._motionData.segments.at(n).segmentType=Pi.CubismMotionSegmentType_Bezier,this._motionData.segments.at(n).evaluate=r?Gi:Xi,this._motionData.points.at(a).time=s.getMotionCurveSegment(o,t+1),this._motionData.points.at(a).value=s.getMotionCurveSegment(o,t+2),this._motionData.points.at(a+1).time=s.getMotionCurveSegment(o,t+3),this._motionData.points.at(a+1).value=s.getMotionCurveSegment(o,t+4),this._motionData.points.at(a+2).time=s.getMotionCurveSegment(o,t+5),this._motionData.points.at(a+2).value=s.getMotionCurveSegment(o,t+6),a+=3,t+=7;break;case Pi.CubismMotionSegmentType_Stepped:this._motionData.segments.at(n).segmentType=Pi.CubismMotionSegmentType_Stepped,this._motionData.segments.at(n).evaluate=Hi,this._motionData.points.at(a).time=s.getMotionCurveSegment(o,t+1),this._motionData.points.at(a).value=s.getMotionCurveSegment(o,t+2),a+=1,t+=3;break;case Pi.CubismMotionSegmentType_InverseStepped:this._motionData.segments.at(n).segmentType=Pi.CubismMotionSegmentType_InverseStepped,this._motionData.segments.at(n).evaluate=Yi,this._motionData.points.at(a).time=s.getMotionCurveSegment(o,t+1),this._motionData.points.at(a).value=s.getMotionCurveSegment(o,t+2),a+=1,t+=3;break;default:ve(0)}++this._motionData.curves.at(o).segmentCount,++n}}for(let o=0;o<s.getEventCount();++o)this._motionData.events.at(o).fireTime=s.getEventTime(o),this._motionData.events.at(o).value=s.getEventValue(o);s.release(),s=void 0,s=null}getFiredEvent(t,e){this._firedEventValues.updateSize(0);for(let i=0;i<this._motionData.eventCount;++i)this._motionData.events.at(i).fireTime>t&&this._motionData.events.at(i).fireTime<=e&&this._firedEventValues.pushBack(new ge(this._motionData.events.at(i).value.s));return this._firedEventValues}isExistModelOpacity(){for(let t=0;t<this._motionData.curveCount;t++){const e=this._motionData.curves.at(t);if(e.type==bi.CubismMotionCurveTarget_Model&&0==e.id.getString().s.localeCompare(Ui))return!0}return!1}getModelOpacityIndex(){if(this.isExistModelOpacity())for(let t=0;t<this._motionData.curveCount;t++){const e=this._motionData.curves.at(t);if(e.type==bi.CubismMotionCurveTarget_Model&&0==e.id.getString().s.localeCompare(Ui))return t}return-1}getModelOpacityId(t){if(-1!=t){const e=this._motionData.curves.at(t);if(e.type==bi.CubismMotionCurveTarget_Model&&0==e.id.getString().s.localeCompare(Ui))return ti.getIdManager().getId(e.id.getString().s)}return null}getModelOpacityValue(){return this._modelOpacity}setDebugMode(t){this._debugMode=t}}var Ji;function $i(t,e,i){const s=t.startMotion(i,!1),r=t.getCubismMotionQueueEntry(s);if(!r)return!1;r.setStartTime(0),r.setFadeInStartTime(0);const a=i.getDuration(),n=r.getStartTime()+a;return i.doUpdateParameters(e.coreModel,n,1,r),r.setIsFinished(!0),!0}(t=>{t.CubismMotion=Wi})(Ji||(Ji={}));class Zi extends G{constructor(t){var e;super(t),d(this,"definitions"),d(this,"groups",{idle:"Idle"}),d(this,"motionDataType","arraybuffer"),d(this,"queueManager",new xi),d(this,"expressionManager"),d(this,"eyeBlinkIds"),d(this,"lipSyncIds",["ParamMouthOpenY"]),this.definitions=null!=(e=t.settings.motions)?e:{},this.eyeBlinkIds=t.settings.getEyeBlinkParameters()||[];const i=t.settings.getLipSyncParameters();(null==i?void 0:i.length)&&(this.lipSyncIds=i),this.init(t.options)}init(t){super.init(t),this.settings.expressions&&(this.expressionManager=new Si(this.settings,t)),this.queueManager.setEventCallback((t,e)=>{const i="string"==typeof e?e:"number"==typeof e?String(e):e&&"object"==typeof e?e.s:"undefined";this.emit("motion:"+i)})}isFinished(){return this.queueManager.isFinished()}_startMotion(t,e,i,s){if(t.setFinishedMotionHandler(e),t.setLoop(null!=s?s:t._motionData.loop),i&&i.length>0){const e=t._motionData.curves,s=function(t){if(Ki(t))return new se;return[]}(e),r=Qi(e);for(let t=0;t<r;t++){const r=ts(e,t);if(!r)continue;const a=es(r);a&&i.includes(a)||is(s,r)}t._motionData.curves=s,t._motionData.curveCount=Qi(s)}return this.queueManager.stopAllMotions(),this.queueManager.startMotion(t,!1)}_stopAllMotions(){this.queueManager.stopAllMotions()}createMotion(t,e,i){const s=!!this.parent.options.checkMotionConsistency,r=Wi.create(t,t.byteLength,void 0,void 0,s),a=new Oi(t,t.byteLength);r.setLoop(a.isMotionLoop());const n=(e===this.groups.idle?c.idleMotionFadingDuration:c.motionFadingDuration)/1e3;return void 0===a.getMotionFadeInTime()&&r.setFadeInTime(i.FadeInTime>0?i.FadeInTime:n),void 0===a.getMotionFadeOutTime()&&r.setFadeOutTime(i.FadeOutTime>0?i.FadeOutTime:n),r.setEffectIds(this.createIdVector(this.eyeBlinkIds),this.createIdVector(this.lipSyncIds)),r}getMotionFile(t){return t.File}getMotionName(t){return t.File}getSoundFile(t){return t.Sound}updateParameters(t,e){return this.queueManager.doUpdateMotion(t,e)}destroy(){super.destroy(),this.queueManager.release(),this.queueManager=void 0}motionLastFrame(t,e){return g(this,arguments,function*(t,e,{expression:i}={}){const s=yield this.getMotionAndApplyExpression(t,e,i);return!!s&&(this.playing=!0,$i(this.queueManager,this.parent,s),this.playing=!1,!0)})}createIdVector(t){const e=new se,i=ti.getIdManager();for(const s of t)e.pushBack(i.getId(s));return e}}function Ki(t){return"function"==typeof t.pushBack}function Qi(t){return Ki(t)?t.getSize():t.length}function ts(t,e){return Ki(t)?t.at(e):t[e]}function es(t){if(!t||"object"!=typeof t)return;const e=t.id;return"string"==typeof e?e:e&&"function"==typeof e.getString?e.getString().s:void 0}function is(t,e){Ki(t)?t.pushBack(e):t.push(e)}class ss extends Yt{constructor(t){super(t),d(this,"queueManager",new xi),this.init()}init(){this.queueManager.setEventCallback((t,e)=>{const i="string"==typeof e?e:"number"==typeof e?String(e):e&&"object"==typeof e?e.s:"undefined";this.emit("motion:"+i)})}isFinished(){return this.queueManager.isFinished()}_startMotion(t,e,i,s){if(t.setFinishedMotionHandler(e),t.setLoop(null!=s?s:t._motionData.loop),i&&i.length>0){const e=t._motionData.curves,s=function(t){if(rs(t))return new se;return[]}(e),r=as(e);for(let t=0;t<r;t++){const r=ns(e,t);if(!r)continue;const a=os(r);a&&i.includes(a)||ls(s,r)}t._motionData.curves=s,t._motionData.curveCount=as(s)}return this.queueManager.stopAllMotions(),this.queueManager.startMotion(t,!1)}_stopAllMotions(){this.queueManager.stopAllMotions()}updateParameters(t,e){return this.queueManager.doUpdateMotion(t,e)}getMotionName(t){return t.File}destroy(){super.destroy(),this.queueManager.release(),this.queueManager=void 0}playMotionLastFrame(t,e){return g(this,null,function*(){var i;if(!this.state.reserve(t,e,E.FORCE))return!1;const s=null==(i=this.manager.definitions[t])?void 0:i[e];if(!s)return!1;const r=yield this.manager.loadMotion(t,e);return!!this.state.start(r,t,e,E.FORCE)&&(p.log(this.tag,"Start motion:",this.getMotionName(s)),this.emit("motionStart",t,e,void 0),this.playing=!0,this.queueManager.stopAllMotions(),$i(this.queueManager,this.parent,r)?(this.playing=!1,!0):(this.playing=!1,!1))})}}function rs(t){return"function"==typeof t.pushBack}function as(t){return rs(t)?t.getSize():t.length}function ns(t,e){return rs(t)?t.at(e):t[e]}function os(t){if(!t||"object"!=typeof t)return;const e=t.id;return"string"==typeof e?e:e&&"function"==typeof e.getString?e.getString().s:void 0}function ls(t,e){rs(t)?t.pushBack(e):t.push(e)}const us=Object.freeze({HitAreaPrefix:"HitArea",HitAreaHead:"Head",HitAreaBody:"Body",PartsIdCore:"Parts01Core",PartsArmPrefix:"Parts01Arm_",PartsArmLPrefix:"Parts01ArmL_",PartsArmRPrefix:"Parts01ArmR_",ParamAngleX:"ParamAngleX",ParamAngleY:"ParamAngleY",ParamAngleZ:"ParamAngleZ",ParamEyeLOpen:"ParamEyeLOpen",ParamEyeLSmile:"ParamEyeLSmile",ParamEyeROpen:"ParamEyeROpen",ParamEyeRSmile:"ParamEyeRSmile",ParamEyeBallX:"ParamEyeBallX",ParamEyeBallY:"ParamEyeBallY",ParamEyeBallForm:"ParamEyeBallForm",ParamBrowLY:"ParamBrowLY",ParamBrowRY:"ParamBrowRY",ParamBrowLX:"ParamBrowLX",ParamBrowRX:"ParamBrowRX",ParamBrowLAngle:"ParamBrowLAngle",ParamBrowRAngle:"ParamBrowRAngle",ParamBrowLForm:"ParamBrowLForm",ParamBrowRForm:"ParamBrowRForm",ParamMouthForm:"ParamMouthForm",ParamMouthOpenY:"ParamMouthOpenY",ParamCheek:"ParamCheek",ParamBodyAngleX:"ParamBodyAngleX",ParamBodyAngleY:"ParamBodyAngleY",ParamBodyAngleZ:"ParamBodyAngleZ",ParamBreath:"ParamBreath",ParamArmLA:"ParamArmLA",ParamArmRA:"ParamArmRA",ParamArmLB:"ParamArmLB",ParamArmRB:"ParamArmRB",ParamHandL:"ParamHandL",ParamHandR:"ParamHandR",ParamHairFront:"ParamHairFront",ParamHairSide:"ParamHairSide",ParamHairBack:"ParamHairBack",ParamHairFluffy:"ParamHairFluffy",ParamShoulderY:"ParamShoulderY",ParamBustX:"ParamBustX",ParamBustY:"ParamBustY",ParamBaseX:"ParamBaseX",ParamBaseY:"ParamBaseY",ParamNONE:"NONE:"});var hs,ds;(t=>{t.HitAreaBody=us.HitAreaBody,t.HitAreaHead=us.HitAreaHead,t.HitAreaPrefix=us.HitAreaPrefix,t.ParamAngleX=us.ParamAngleX,t.ParamAngleY=us.ParamAngleY,t.ParamAngleZ=us.ParamAngleZ,t.ParamArmLA=us.ParamArmLA,t.ParamArmLB=us.ParamArmLB,t.ParamArmRA=us.ParamArmRA,t.ParamArmRB=us.ParamArmRB,t.ParamBaseX=us.ParamBaseX,t.ParamBaseY=us.ParamBaseY,t.ParamBodyAngleX=us.ParamBodyAngleX,t.ParamBodyAngleY=us.ParamBodyAngleY,t.ParamBodyAngleZ=us.ParamBodyAngleZ,t.ParamBreath=us.ParamBreath,t.ParamBrowLAngle=us.ParamBrowLAngle,t.ParamBrowLForm=us.ParamBrowLForm,t.ParamBrowLX=us.ParamBrowLX,t.ParamBrowLY=us.ParamBrowLY,t.ParamBrowRAngle=us.ParamBrowRAngle,t.ParamBrowRForm=us.ParamBrowRForm,t.ParamBrowRX=us.ParamBrowRX,t.ParamBrowRY=us.ParamBrowRY,t.ParamBustX=us.ParamBustX,t.ParamBustY=us.ParamBustY,t.ParamCheek=us.ParamCheek,t.ParamEyeBallForm=us.ParamEyeBallForm,t.ParamEyeBallX=us.ParamEyeBallX,t.ParamEyeBallY=us.ParamEyeBallY,t.ParamEyeLOpen=us.ParamEyeLOpen,t.ParamEyeLSmile=us.ParamEyeLSmile,t.ParamEyeROpen=us.ParamEyeROpen,t.ParamEyeRSmile=us.ParamEyeRSmile,t.ParamHairBack=us.ParamHairBack,t.ParamHairFluffy=us.ParamHairFluffy,t.ParamHairFront=us.ParamHairFront,t.ParamHairSide=us.ParamHairSide,t.ParamHandL=us.ParamHandL,t.ParamHandR=us.ParamHandR,t.ParamMouthForm=us.ParamMouthForm,t.ParamMouthOpenY=us.ParamMouthOpenY,t.ParamNONE=us.ParamNONE,t.ParamShoulderY=us.ParamShoulderY,t.PartsArmLPrefix=us.PartsArmLPrefix,t.PartsArmPrefix=us.PartsArmPrefix,t.PartsArmRPrefix=us.PartsArmRPrefix,t.PartsIdCore=us.PartsIdCore})(hs||(hs={}));class gs{static create(){return new gs}static delete(t){}setParameters(t){this._breathParameters=t}getParameters(){return this._breathParameters}updateParameters(t,e){this._currentTime+=e;const i=2*this._currentTime*Math.PI;for(let s=0;s<this._breathParameters.getSize();++s){const e=this._breathParameters.at(s);t.addParameterValueById(e.parameterId,e.offset+e.peak*Math.sin(i/e.cycle),e.weight)}}constructor(){this._currentTime=0}}class cs{constructor(t,e,i,s,r){this.parameterId=null==t?null:t,this.offset=null==e?0:e,this.peak=null==i?0:i,this.cycle=null==s?0:s,this.weight=null==r?0:r}}(t=>{t.BreathParameterData=cs,t.CubismBreath=gs})(ds||(ds={}));const ps=class t{static create(e=null){return new t(e)}static delete(t){}setBlinkingInterval(t){this._blinkingIntervalSeconds=t}setBlinkingSetting(t,e,i){this._closingSeconds=t,this._closedSeconds=e,this._openingSeconds=i}setParameterIds(t){this._parameterIds=t}getParameterIds(){return this._parameterIds}updateParameters(e,i){let s;this._userTimeSeconds+=i;let r=0;switch(this._blinkingState){case 2:r=(this._userTimeSeconds-this._stateStartTimeSeconds)/this._closingSeconds,r>=1&&(r=1,this._blinkingState=3,this._stateStartTimeSeconds=this._userTimeSeconds),s=1-r;break;case 3:r=(this._userTimeSeconds-this._stateStartTimeSeconds)/this._closedSeconds,r>=1&&(this._blinkingState=4,this._stateStartTimeSeconds=this._userTimeSeconds),s=0;break;case 4:r=(this._userTimeSeconds-this._stateStartTimeSeconds)/this._openingSeconds,r>=1&&(r=1,this._blinkingState=1,this._nextBlinkingTime=this.determinNextBlinkingTiming()),s=r;break;case 1:this._nextBlinkingTime<this._userTimeSeconds&&(this._blinkingState=2,this._stateStartTimeSeconds=this._userTimeSeconds),s=1;break;default:this._blinkingState=1,this._nextBlinkingTime=this.determinNextBlinkingTiming(),s=1}t.CloseIfZero||(s=-s);for(let t=0;t<this._parameterIds.getSize();++t)e.setParameterValueById(this._parameterIds.at(t),s)}constructor(t){if(this._blinkingState=0,this._nextBlinkingTime=0,this._stateStartTimeSeconds=0,this._blinkingIntervalSeconds=4,this._closingSeconds=.1,this._closedSeconds=.05,this._openingSeconds=.15,this._userTimeSeconds=0,this._parameterIds=new se,null!=t)for(let e=0;e<t.getEyeBlinkParameterCount();++e)this._parameterIds.pushBack(t.getEyeBlinkParameterId(e))}determinNextBlinkingTiming(){const t=Math.random();return this._userTimeSeconds+t*(2*this._blinkingIntervalSeconds-1)}};ps.CloseIfZero=!0;let ms=ps;var _s,fs=(t=>(t[t.EyeState_First=0]="EyeState_First",t[t.EyeState_Interval=1]="EyeState_Interval",t[t.EyeState_Closing=2]="EyeState_Closing",t[t.EyeState_Closed=3]="EyeState_Closed",t[t.EyeState_Opening=4]="EyeState_Opening",t))(fs||{});(t=>{t.CubismEyeBlink=ms,t.EyeState=fs})(_s||(_s={}));class ys{constructor(t){this._renderTextureCount=0,this._clippingMaskBufferSize=256,this._clippingContextListForMask=new se,this._clippingContextListForDraw=new se,this._channelColors=new se,this._tmpBoundsOnModel=new _e,this._tmpMatrix=new me,this._tmpMatrixForMask=new me,this._tmpMatrixForDraw=new me,this._clippingContexttConstructor=t;let e=new Me;e.r=1,e.g=0,e.b=0,e.a=0,this._channelColors.pushBack(e),e=new Me,e.r=0,e.g=1,e.b=0,e.a=0,this._channelColors.pushBack(e),e=new Me,e.r=0,e.g=0,e.b=1,e.a=0,this._channelColors.pushBack(e),e=new Me,e.r=0,e.g=0,e.b=0,e.a=1,this._channelColors.pushBack(e)}release(){for(let t=0;t<this._clippingContextListForMask.getSize();t++)this._clippingContextListForMask.at(t)&&(this._clippingContextListForMask.at(t).release(),this._clippingContextListForMask.set(t,void 0)),this._clippingContextListForMask.set(t,null);this._clippingContextListForMask=null;for(let t=0;t<this._clippingContextListForDraw.getSize();t++)this._clippingContextListForDraw.set(t,null);this._clippingContextListForDraw=null;for(let t=0;t<this._channelColors.getSize();t++)this._channelColors.set(t,null);this._channelColors=null,null!=this._clearedFrameBufferFlags&&this._clearedFrameBufferFlags.clear(),this._clearedFrameBufferFlags=null}initialize(t,e){e%1!=0&&(Be("The number of render textures must be specified as an integer. The decimal point is rounded down and corrected to an integer."),e=~~e),e<1&&Be("The number of render textures must be an integer greater than or equal to 1. Set the number of render textures to 1."),this._renderTextureCount=e<1?1:e,this._clearedFrameBufferFlags=new se(this._renderTextureCount);for(let i=0;i<t.getDrawableCount();i++){if(t.getDrawableMaskCounts()[i]<=0){this._clippingContextListForDraw.pushBack(null);continue}let e=this.findSameClip(t.getDrawableMasks()[i],t.getDrawableMaskCounts()[i]);null==e&&(e=new this._clippingContexttConstructor(this,t.getDrawableMasks()[i],t.getDrawableMaskCounts()[i]),this._clippingContextListForMask.pushBack(e)),e.addClippedDrawable(i),this._clippingContextListForDraw.pushBack(e)}}findSameClip(t,e){for(let i=0;i<this._clippingContextListForMask.getSize();i++){const s=this._clippingContextListForMask.at(i),r=s._clippingIdCount;if(r!=e)continue;let a=0;for(let e=0;e<r;e++){const i=s._clippingIdList[e];for(let e=0;e<r;e++)if(t[e]==i){a++;break}}if(a==r)return s}return null}setupMatrixForHighPrecision(t,e){let i=0;for(let s=0;s<this._clippingContextListForMask.getSize();s++){const e=this._clippingContextListForMask.at(s);this.calcClippedDrawTotalBounds(t,e),e._isUsing&&i++}if(i>0){if(this.setupLayoutBounds(0),this._clearedFrameBufferFlags.getSize()!=this._renderTextureCount){this._clearedFrameBufferFlags.clear();for(let t=0;t<this._renderTextureCount;t++)this._clearedFrameBufferFlags.pushBack(!1)}else for(let t=0;t<this._renderTextureCount;t++)this._clearedFrameBufferFlags.set(t,!1);for(let i=0;i<this._clippingContextListForMask.getSize();i++){const s=this._clippingContextListForMask.at(i),r=s._allClippedDrawRect,a=s._layoutBounds,n=.05;let o=0,l=0;const u=t.getPixelsPerUnit(),h=s.getClippingManager().getClippingMaskBufferSize(),d=a.width*h,g=a.height*h;this._tmpBoundsOnModel.setRect(r),this._tmpBoundsOnModel.width*u>d?(this._tmpBoundsOnModel.expand(r.width*n,0),o=a.width/this._tmpBoundsOnModel.width):o=u/d,this._tmpBoundsOnModel.height*u>g?(this._tmpBoundsOnModel.expand(0,r.height*n),l=a.height/this._tmpBoundsOnModel.height):l=u/g,this.createMatrixForMask(e,a,o,l),s._matrixForMask.setMatrix(this._tmpMatrixForMask.getArray()),s._matrixForDraw.setMatrix(this._tmpMatrixForDraw.getArray())}}}createMatrixForMask(t,e,i,s){this._tmpMatrix.loadIdentity(),this._tmpMatrix.translateRelative(-1,-1),this._tmpMatrix.scaleRelative(2,2),this._tmpMatrix.translateRelative(e.x,e.y),this._tmpMatrix.scaleRelative(i,s),this._tmpMatrix.translateRelative(-this._tmpBoundsOnModel.x,-this._tmpBoundsOnModel.y),this._tmpMatrixForMask.setMatrix(this._tmpMatrix.getArray()),this._tmpMatrix.loadIdentity(),this._tmpMatrix.translateRelative(e.x,e.y*(t?-1:1)),this._tmpMatrix.scaleRelative(i,s*(t?-1:1)),this._tmpMatrix.translateRelative(-this._tmpBoundsOnModel.x,-this._tmpBoundsOnModel.y),this._tmpMatrixForDraw.setMatrix(this._tmpMatrix.getArray())}setupLayoutBounds(t){const e=this._renderTextureCount<=1?36:32*this._renderTextureCount;if(t<=0||t>e){t>e&&we("not supported mask count : {0}\n[Details] render texture count : {1}, mask count : {2}",t-e,this._renderTextureCount,t);for(let t=0;t<this._clippingContextListForMask.getSize();t++){const e=this._clippingContextListForMask.at(t);e._layoutChannelIndex=0,e._layoutBounds.x=0,e._layoutBounds.y=0,e._layoutBounds.width=1,e._layoutBounds.height=1,e._bufferIndex=0}return}const i=this._renderTextureCount<=1?9:8;let s=t/this._renderTextureCount;const r=t%this._renderTextureCount;s=Math.ceil(s);let a=s/4;const n=s%4;a=~~a;let o=0;for(let l=0;l<this._renderTextureCount;l++)for(let s=0;s<4;s++){let u=a+(s<n?1:0);if(s==n+(a<1?-1:0)&&r>0&&(u-=l<r?0:1),0==u);else if(1==u){const t=this._clippingContextListForMask.at(o++);t._layoutChannelIndex=s,t._layoutBounds.x=0,t._layoutBounds.y=0,t._layoutBounds.width=1,t._layoutBounds.height=1,t._bufferIndex=l}else if(2==u)for(let t=0;t<u;t++){let e=t%2;e=~~e;const i=this._clippingContextListForMask.at(o++);i._layoutChannelIndex=s,i._layoutBounds.x=.5*e,i._layoutBounds.y=0,i._layoutBounds.width=.5,i._layoutBounds.height=1,i._bufferIndex=l}else if(u<=4)for(let t=0;t<u;t++){let e=t%2,i=t/2;e=~~e,i=~~i;const r=this._clippingContextListForMask.at(o++);r._layoutChannelIndex=s,r._layoutBounds.x=.5*e,r._layoutBounds.y=.5*i,r._layoutBounds.width=.5,r._layoutBounds.height=.5,r._bufferIndex=l}else if(u<=i)for(let t=0;t<u;t++){let e=t%3,i=t/3;e=~~e,i=~~i;const r=this._clippingContextListForMask.at(o++);r._layoutChannelIndex=s,r._layoutBounds.x=e/3,r._layoutBounds.y=i/3,r._layoutBounds.width=1/3,r._layoutBounds.height=1/3,r._bufferIndex=l}else{we("not supported mask count : {0}\n[Details] render texture count : {1}, mask count : {2}",t-e,this._renderTextureCount,t);for(let t=0;t<u;t++){const t=this._clippingContextListForMask.at(o++);t._layoutChannelIndex=0,t._layoutBounds.x=0,t._layoutBounds.y=0,t._layoutBounds.width=1,t._layoutBounds.height=1,t._bufferIndex=0}}}}calcClippedDrawTotalBounds(t,e){let i=Number.MAX_VALUE,s=Number.MAX_VALUE,r=Number.MIN_VALUE,a=Number.MIN_VALUE;const n=e._clippedDrawableIndexList.length;for(let o=0;o<n;o++){const n=e._clippedDrawableIndexList[o],l=t.getDrawableVertexCount(n),u=t.getDrawableVertices(n);let h=Number.MAX_VALUE,d=Number.MAX_VALUE,g=-Number.MAX_VALUE,c=-Number.MAX_VALUE;const p=l*Ke.vertexStep;for(let t=Ke.vertexOffset;t<p;t+=Ke.vertexStep){const e=u[t],i=u[t+1];e<h&&(h=e),e>g&&(g=e),i<d&&(d=i),i>c&&(c=i)}if(h!=Number.MAX_VALUE)if(h<i&&(i=h),d<s&&(s=d),g>r&&(r=g),c>a&&(a=c),i==Number.MAX_VALUE)e._allClippedDrawRect.x=0,e._allClippedDrawRect.y=0,e._allClippedDrawRect.width=0,e._allClippedDrawRect.height=0,e._isUsing=!1;else{e._isUsing=!0;const t=r-i,n=a-s;e._allClippedDrawRect.x=i,e._allClippedDrawRect.y=s,e._allClippedDrawRect.width=t,e._allClippedDrawRect.height=n}}}getClippingContextListForDraw(){return this._clippingContextListForDraw}getClippingMaskBufferSize(){return this._clippingMaskBufferSize}getRenderTextureCount(){return this._renderTextureCount}getChannelFlagAsColor(t){return this._channelColors.at(t)}setClippingMaskBufferSize(t){this._clippingMaskBufferSize=t}}let xs;class Ms{constructor(){this._shaderSets=new se}release(){this.releaseShaderProgram()}setupShaderProgramForDraw(t,e,i){let s,r,a,n;t.isPremultipliedAlpha()||we("NoPremultipliedAlpha is not allowed"),0==this._shaderSets.getSize()&&this.generateShaders();const o=null!=t.getClippingContextBufferForDraw(),l=e.getDrawableInvertedMaskBit(i),u=o?l?2:1:0;let h;switch(e.getDrawableBlendMode(i)){case xe.CubismBlendMode_Normal:default:h=this._shaderSets.at(1+u),s=this.gl.ONE,r=this.gl.ONE_MINUS_SRC_ALPHA,a=this.gl.ONE,n=this.gl.ONE_MINUS_SRC_ALPHA;break;case xe.CubismBlendMode_Additive:h=this._shaderSets.at(4+u),s=this.gl.ONE,r=this.gl.ONE,a=this.gl.ZERO,n=this.gl.ONE;break;case xe.CubismBlendMode_Multiplicative:h=this._shaderSets.at(7+u),s=this.gl.DST_COLOR,r=this.gl.ONE_MINUS_SRC_ALPHA,a=this.gl.ZERO,n=this.gl.ONE}this.gl.useProgram(h.shaderProgram),null==t._bufferData.vertex&&(t._bufferData.vertex=this.gl.createBuffer()),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,t._bufferData.vertex);const d=e.getDrawableVertices(i);this.gl.bufferData(this.gl.ARRAY_BUFFER,d,this.gl.DYNAMIC_DRAW),this.gl.enableVertexAttribArray(h.attributePositionLocation),this.gl.vertexAttribPointer(h.attributePositionLocation,2,this.gl.FLOAT,!1,0,0),null==t._bufferData.uv&&(t._bufferData.uv=this.gl.createBuffer()),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,t._bufferData.uv);const g=e.getDrawableVertexUvs(i);if(this.gl.bufferData(this.gl.ARRAY_BUFFER,g,this.gl.DYNAMIC_DRAW),this.gl.enableVertexAttribArray(h.attributeTexCoordLocation),this.gl.vertexAttribPointer(h.attributeTexCoordLocation,2,this.gl.FLOAT,!1,0,0),o){this.gl.activeTexture(this.gl.TEXTURE1);const e=t.getClippingContextBufferForDraw().getClippingManager().getColorBuffer().at(t.getClippingContextBufferForDraw()._bufferIndex);this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.uniform1i(h.samplerTexture1Location,1),this.gl.uniformMatrix4fv(h.uniformClipMatrixLocation,!1,t.getClippingContextBufferForDraw()._matrixForDraw.getArray());const i=t.getClippingContextBufferForDraw()._layoutChannelIndex,s=t.getClippingContextBufferForDraw().getClippingManager().getChannelFlagAsColor(i);this.gl.uniform4f(h.uniformChannelFlagLocation,s.r,s.g,s.b,s.a)}const c=e.getDrawableTextureIndex(i),p=t.getBindedTextures().getValue(c);this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,p),this.gl.uniform1i(h.samplerTexture0Location,0);const m=t.getMvpMatrix();this.gl.uniformMatrix4fv(h.uniformMatrixLocation,!1,m.getArray());const _=t.getModelColorWithOpacity(e.getDrawableOpacity(i)),f=e.getMultiplyColor(i),y=e.getScreenColor(i);this.gl.uniform4f(h.uniformBaseColorLocation,_.r,_.g,_.b,_.a),this.gl.uniform4f(h.uniformMultiplyColorLocation,f.r,f.g,f.b,f.a),this.gl.uniform4f(h.uniformScreenColorLocation,y.r,y.g,y.b,y.a),null==t._bufferData.index&&(t._bufferData.index=this.gl.createBuffer());const x=e.getDrawableVertexIndices(i);this.gl.bindBuffer(this.gl.ELEMENT_ARRAY_BUFFER,t._bufferData.index),this.gl.bufferData(this.gl.ELEMENT_ARRAY_BUFFER,x,this.gl.DYNAMIC_DRAW),this.gl.blendFuncSeparate(s,r,a,n)}setupShaderProgramForMask(t,e,i){t.isPremultipliedAlpha()||we("NoPremultipliedAlpha is not allowed"),0==this._shaderSets.getSize()&&this.generateShaders();const s=this._shaderSets.at(0);this.gl.useProgram(s.shaderProgram),null==t._bufferData.vertex&&(t._bufferData.vertex=this.gl.createBuffer()),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,t._bufferData.vertex);const r=e.getDrawableVertices(i);this.gl.bufferData(this.gl.ARRAY_BUFFER,r,this.gl.DYNAMIC_DRAW),this.gl.enableVertexAttribArray(s.attributePositionLocation),this.gl.vertexAttribPointer(s.attributePositionLocation,2,this.gl.FLOAT,!1,0,0),null==t._bufferData.uv&&(t._bufferData.uv=this.gl.createBuffer()),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,t._bufferData.uv);const a=e.getDrawableTextureIndex(i),n=t.getBindedTextures().getValue(a);this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,n),this.gl.uniform1i(s.samplerTexture0Location,0),null==t._bufferData.uv&&(t._bufferData.uv=this.gl.createBuffer()),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,t._bufferData.uv);const o=e.getDrawableVertexUvs(i);this.gl.bufferData(this.gl.ARRAY_BUFFER,o,this.gl.DYNAMIC_DRAW),this.gl.enableVertexAttribArray(s.attributeTexCoordLocation),this.gl.vertexAttribPointer(s.attributeTexCoordLocation,2,this.gl.FLOAT,!1,0,0),t.getClippingContextBufferForMask();const l=t.getClippingContextBufferForMask()._layoutChannelIndex,u=t.getClippingContextBufferForMask().getClippingManager().getChannelFlagAsColor(l);this.gl.uniform4f(s.uniformChannelFlagLocation,u.r,u.g,u.b,u.a),this.gl.uniformMatrix4fv(s.uniformClipMatrixLocation,!1,t.getClippingContextBufferForMask()._matrixForMask.getArray());const h=t.getClippingContextBufferForMask()._layoutBounds;this.gl.uniform4f(s.uniformBaseColorLocation,2*h.x-1,2*h.y-1,2*h.getRight()-1,2*h.getBottom()-1);const d=e.getMultiplyColor(i),g=e.getScreenColor(i);this.gl.uniform4f(s.uniformMultiplyColorLocation,d.r,d.g,d.b,d.a),this.gl.uniform4f(s.uniformScreenColorLocation,g.r,g.g,g.b,g.a);const c=this.gl.ZERO,p=this.gl.ONE_MINUS_SRC_COLOR,m=this.gl.ZERO,_=this.gl.ONE_MINUS_SRC_ALPHA;null==t._bufferData.index&&(t._bufferData.index=this.gl.createBuffer());const f=e.getDrawableVertexIndices(i);this.gl.bindBuffer(this.gl.ELEMENT_ARRAY_BUFFER,t._bufferData.index),this.gl.bufferData(this.gl.ELEMENT_ARRAY_BUFFER,f,this.gl.DYNAMIC_DRAW),this.gl.blendFuncSeparate(c,p,m,_)}releaseShaderProgram(){for(let t=0;t<this._shaderSets.getSize();t++)this.gl.deleteProgram(this._shaderSets.at(t).shaderProgram),this._shaderSets.at(t).shaderProgram=0,this._shaderSets.set(t,void 0),this._shaderSets.set(t,null)}generateShaders(){for(let t=0;t<10;t++)this._shaderSets.pushBack(new Ss);this._shaderSets.at(0).shaderProgram=this.loadShaderProgram(bs,Ps),this._shaderSets.at(1).shaderProgram=this.loadShaderProgram(Bs,Is),this._shaderSets.at(2).shaderProgram=this.loadShaderProgram(ws,Fs),this._shaderSets.at(3).shaderProgram=this.loadShaderProgram(ws,Es),this._shaderSets.at(4).shaderProgram=this._shaderSets.at(1).shaderProgram,this._shaderSets.at(5).shaderProgram=this._shaderSets.at(2).shaderProgram,this._shaderSets.at(6).shaderProgram=this._shaderSets.at(3).shaderProgram,this._shaderSets.at(7).shaderProgram=this._shaderSets.at(1).shaderProgram,this._shaderSets.at(8).shaderProgram=this._shaderSets.at(2).shaderProgram,this._shaderSets.at(9).shaderProgram=this._shaderSets.at(3).shaderProgram,this._shaderSets.at(0).attributePositionLocation=this.gl.getAttribLocation(this._shaderSets.at(0).shaderProgram,"a_position"),this._shaderSets.at(0).attributeTexCoordLocation=this.gl.getAttribLocation(this._shaderSets.at(0).shaderProgram,"a_texCoord"),this._shaderSets.at(0).samplerTexture0Location=this.gl.getUniformLocation(this._shaderSets.at(0).shaderProgram,"s_texture0"),this._shaderSets.at(0).uniformClipMatrixLocation=this.gl.getUniformLocation(this._shaderSets.at(0).shaderProgram,"u_clipMatrix"),this._shaderSets.at(0).uniformChannelFlagLocation=this.gl.getUniformLocation(this._shaderSets.at(0).shaderProgram,"u_channelFlag"),this._shaderSets.at(0).uniformBaseColorLocation=this.gl.getUniformLocation(this._shaderSets.at(0).shaderProgram,"u_baseColor"),this._shaderSets.at(0).uniformMultiplyColorLocation=this.gl.getUniformLocation(this._shaderSets.at(0).shaderProgram,"u_multiplyColor"),this._shaderSets.at(0).uniformScreenColorLocation=this.gl.getUniformLocation(this._shaderSets.at(0).shaderProgram,"u_screenColor"),this._shaderSets.at(1).attributePositionLocation=this.gl.getAttribLocation(this._shaderSets.at(1).shaderProgram,"a_position"),this._shaderSets.at(1).attributeTexCoordLocation=this.gl.getAttribLocation(this._shaderSets.at(1).shaderProgram,"a_texCoord"),this._shaderSets.at(1).samplerTexture0Location=this.gl.getUniformLocation(this._shaderSets.at(1).shaderProgram,"s_texture0"),this._shaderSets.at(1).uniformMatrixLocation=this.gl.getUniformLocation(this._shaderSets.at(1).shaderProgram,"u_matrix"),this._shaderSets.at(1).uniformBaseColorLocation=this.gl.getUniformLocation(this._shaderSets.at(1).shaderProgram,"u_baseColor"),this._shaderSets.at(1).uniformMultiplyColorLocation=this.gl.getUniformLocation(this._shaderSets.at(1).shaderProgram,"u_multiplyColor"),this._shaderSets.at(1).uniformScreenColorLocation=this.gl.getUniformLocation(this._shaderSets.at(1).shaderProgram,"u_screenColor"),this._shaderSets.at(2).attributePositionLocation=this.gl.getAttribLocation(this._shaderSets.at(2).shaderProgram,"a_position"),this._shaderSets.at(2).attributeTexCoordLocation=this.gl.getAttribLocation(this._shaderSets.at(2).shaderProgram,"a_texCoord"),this._shaderSets.at(2).samplerTexture0Location=this.gl.getUniformLocation(this._shaderSets.at(2).shaderProgram,"s_texture0"),this._shaderSets.at(2).samplerTexture1Location=this.gl.getUniformLocation(this._shaderSets.at(2).shaderProgram,"s_texture1"),this._shaderSets.at(2).uniformMatrixLocation=this.gl.getUniformLocation(this._shaderSets.at(2).shaderProgram,"u_matrix"),this._shaderSets.at(2).uniformClipMatrixLocation=this.gl.getUniformLocation(this._shaderSets.at(2).shaderProgram,"u_clipMatrix"),this._shaderSets.at(2).uniformChannelFlagLocation=this.gl.getUniformLocation(this._shaderSets.at(2).shaderProgram,"u_channelFlag"),this._shaderSets.at(2).uniformBaseColorLocation=this.gl.getUniformLocation(this._shaderSets.at(2).shaderProgram,"u_baseColor"),this._shaderSets.at(2).uniformMultiplyColorLocation=this.gl.getUniformLocation(this._shaderSets.at(2).shaderProgram,"u_multiplyColor"),this._shaderSets.at(2).uniformScreenColorLocation=this.gl.getUniformLocation(this._shaderSets.at(2).shaderProgram,"u_screenColor"),this._shaderSets.at(3).attributePositionLocation=this.gl.getAttribLocation(this._shaderSets.at(3).shaderProgram,"a_position"),this._shaderSets.at(3).attributeTexCoordLocation=this.gl.getAttribLocation(this._shaderSets.at(3).shaderProgram,"a_texCoord"),this._shaderSets.at(3).samplerTexture0Location=this.gl.getUniformLocation(this._shaderSets.at(3).shaderProgram,"s_texture0"),this._shaderSets.at(3).samplerTexture1Location=this.gl.getUniformLocation(this._shaderSets.at(3).shaderProgram,"s_texture1"),this._shaderSets.at(3).uniformMatrixLocation=this.gl.getUniformLocation(this._shaderSets.at(3).shaderProgram,"u_matrix"),this._shaderSets.at(3).uniformClipMatrixLocation=this.gl.getUniformLocation(this._shaderSets.at(3).shaderProgram,"u_clipMatrix"),this._shaderSets.at(3).uniformChannelFlagLocation=this.gl.getUniformLocation(this._shaderSets.at(3).shaderProgram,"u_channelFlag"),this._shaderSets.at(3).uniformBaseColorLocation=this.gl.getUniformLocation(this._shaderSets.at(3).shaderProgram,"u_baseColor"),this._shaderSets.at(3).uniformMultiplyColorLocation=this.gl.getUniformLocation(this._shaderSets.at(3).shaderProgram,"u_multiplyColor"),this._shaderSets.at(3).uniformScreenColorLocation=this.gl.getUniformLocation(this._shaderSets.at(3).shaderProgram,"u_screenColor"),this._shaderSets.at(4).attributePositionLocation=this.gl.getAttribLocation(this._shaderSets.at(4).shaderProgram,"a_position"),this._shaderSets.at(4).attributeTexCoordLocation=this.gl.getAttribLocation(this._shaderSets.at(4).shaderProgram,"a_texCoord"),this._shaderSets.at(4).samplerTexture0Location=this.gl.getUniformLocation(this._shaderSets.at(4).shaderProgram,"s_texture0"),this._shaderSets.at(4).uniformMatrixLocation=this.gl.getUniformLocation(this._shaderSets.at(4).shaderProgram,"u_matrix"),this._shaderSets.at(4).uniformBaseColorLocation=this.gl.getUniformLocation(this._shaderSets.at(4).shaderProgram,"u_baseColor"),this._shaderSets.at(4).uniformMultiplyColorLocation=this.gl.getUniformLocation(this._shaderSets.at(4).shaderProgram,"u_multiplyColor"),this._shaderSets.at(4).uniformScreenColorLocation=this.gl.getUniformLocation(this._shaderSets.at(4).shaderProgram,"u_screenColor"),this._shaderSets.at(5).attributePositionLocation=this.gl.getAttribLocation(this._shaderSets.at(5).shaderProgram,"a_position"),this._shaderSets.at(5).attributeTexCoordLocation=this.gl.getAttribLocation(this._shaderSets.at(5).shaderProgram,"a_texCoord"),this._shaderSets.at(5).samplerTexture0Location=this.gl.getUniformLocation(this._shaderSets.at(5).shaderProgram,"s_texture0"),this._shaderSets.at(5).samplerTexture1Location=this.gl.getUniformLocation(this._shaderSets.at(5).shaderProgram,"s_texture1"),this._shaderSets.at(5).uniformMatrixLocation=this.gl.getUniformLocation(this._shaderSets.at(5).shaderProgram,"u_matrix"),this._shaderSets.at(5).uniformClipMatrixLocation=this.gl.getUniformLocation(this._shaderSets.at(5).shaderProgram,"u_clipMatrix"),this._shaderSets.at(5).uniformChannelFlagLocation=this.gl.getUniformLocation(this._shaderSets.at(5).shaderProgram,"u_channelFlag"),this._shaderSets.at(5).uniformBaseColorLocation=this.gl.getUniformLocation(this._shaderSets.at(5).shaderProgram,"u_baseColor"),this._shaderSets.at(5).uniformMultiplyColorLocation=this.gl.getUniformLocation(this._shaderSets.at(5).shaderProgram,"u_multiplyColor"),this._shaderSets.at(5).uniformScreenColorLocation=this.gl.getUniformLocation(this._shaderSets.at(5).shaderProgram,"u_screenColor"),this._shaderSets.at(6).attributePositionLocation=this.gl.getAttribLocation(this._shaderSets.at(6).shaderProgram,"a_position"),this._shaderSets.at(6).attributeTexCoordLocation=this.gl.getAttribLocation(this._shaderSets.at(6).shaderProgram,"a_texCoord"),this._shaderSets.at(6).samplerTexture0Location=this.gl.getUniformLocation(this._shaderSets.at(6).shaderProgram,"s_texture0"),this._shaderSets.at(6).samplerTexture1Location=this.gl.getUniformLocation(this._shaderSets.at(6).shaderProgram,"s_texture1"),this._shaderSets.at(6).uniformMatrixLocation=this.gl.getUniformLocation(this._shaderSets.at(6).shaderProgram,"u_matrix"),this._shaderSets.at(6).uniformClipMatrixLocation=this.gl.getUniformLocation(this._shaderSets.at(6).shaderProgram,"u_clipMatrix"),this._shaderSets.at(6).uniformChannelFlagLocation=this.gl.getUniformLocation(this._shaderSets.at(6).shaderProgram,"u_channelFlag"),this._shaderSets.at(6).uniformBaseColorLocation=this.gl.getUniformLocation(this._shaderSets.at(6).shaderProgram,"u_baseColor"),this._shaderSets.at(6).uniformMultiplyColorLocation=this.gl.getUniformLocation(this._shaderSets.at(6).shaderProgram,"u_multiplyColor"),this._shaderSets.at(6).uniformScreenColorLocation=this.gl.getUniformLocation(this._shaderSets.at(6).shaderProgram,"u_screenColor"),this._shaderSets.at(7).attributePositionLocation=this.gl.getAttribLocation(this._shaderSets.at(7).shaderProgram,"a_position"),this._shaderSets.at(7).attributeTexCoordLocation=this.gl.getAttribLocation(this._shaderSets.at(7).shaderProgram,"a_texCoord"),this._shaderSets.at(7).samplerTexture0Location=this.gl.getUniformLocation(this._shaderSets.at(7).shaderProgram,"s_texture0"),this._shaderSets.at(7).uniformMatrixLocation=this.gl.getUniformLocation(this._shaderSets.at(7).shaderProgram,"u_matrix"),this._shaderSets.at(7).uniformBaseColorLocation=this.gl.getUniformLocation(this._shaderSets.at(7).shaderProgram,"u_baseColor"),this._shaderSets.at(7).uniformMultiplyColorLocation=this.gl.getUniformLocation(this._shaderSets.at(7).shaderProgram,"u_multiplyColor"),this._shaderSets.at(7).uniformScreenColorLocation=this.gl.getUniformLocation(this._shaderSets.at(7).shaderProgram,"u_screenColor"),this._shaderSets.at(8).attributePositionLocation=this.gl.getAttribLocation(this._shaderSets.at(8).shaderProgram,"a_position"),this._shaderSets.at(8).attributeTexCoordLocation=this.gl.getAttribLocation(this._shaderSets.at(8).shaderProgram,"a_texCoord"),this._shaderSets.at(8).samplerTexture0Location=this.gl.getUniformLocation(this._shaderSets.at(8).shaderProgram,"s_texture0"),this._shaderSets.at(8).samplerTexture1Location=this.gl.getUniformLocation(this._shaderSets.at(8).shaderProgram,"s_texture1"),this._shaderSets.at(8).uniformMatrixLocation=this.gl.getUniformLocation(this._shaderSets.at(8).shaderProgram,"u_matrix"),this._shaderSets.at(8).uniformClipMatrixLocation=this.gl.getUniformLocation(this._shaderSets.at(8).shaderProgram,"u_clipMatrix"),this._shaderSets.at(8).uniformChannelFlagLocation=this.gl.getUniformLocation(this._shaderSets.at(8).shaderProgram,"u_channelFlag"),this._shaderSets.at(8).uniformBaseColorLocation=this.gl.getUniformLocation(this._shaderSets.at(8).shaderProgram,"u_baseColor"),this._shaderSets.at(8).uniformMultiplyColorLocation=this.gl.getUniformLocation(this._shaderSets.at(8).shaderProgram,"u_multiplyColor"),this._shaderSets.at(8).uniformScreenColorLocation=this.gl.getUniformLocation(this._shaderSets.at(8).shaderProgram,"u_screenColor"),this._shaderSets.at(9).attributePositionLocation=this.gl.getAttribLocation(this._shaderSets.at(9).shaderProgram,"a_position"),this._shaderSets.at(9).attributeTexCoordLocation=this.gl.getAttribLocation(this._shaderSets.at(9).shaderProgram,"a_texCoord"),this._shaderSets.at(9).samplerTexture0Location=this.gl.getUniformLocation(this._shaderSets.at(9).shaderProgram,"s_texture0"),this._shaderSets.at(9).samplerTexture1Location=this.gl.getUniformLocation(this._shaderSets.at(9).shaderProgram,"s_texture1"),this._shaderSets.at(9).uniformMatrixLocation=this.gl.getUniformLocation(this._shaderSets.at(9).shaderProgram,"u_matrix"),this._shaderSets.at(9).uniformClipMatrixLocation=this.gl.getUniformLocation(this._shaderSets.at(9).shaderProgram,"u_clipMatrix"),this._shaderSets.at(9).uniformChannelFlagLocation=this.gl.getUniformLocation(this._shaderSets.at(9).shaderProgram,"u_channelFlag"),this._shaderSets.at(9).uniformBaseColorLocation=this.gl.getUniformLocation(this._shaderSets.at(9).shaderProgram,"u_baseColor"),this._shaderSets.at(9).uniformMultiplyColorLocation=this.gl.getUniformLocation(this._shaderSets.at(9).shaderProgram,"u_multiplyColor"),this._shaderSets.at(9).uniformScreenColorLocation=this.gl.getUniformLocation(this._shaderSets.at(9).shaderProgram,"u_screenColor")}loadShaderProgram(t,e){let i=this.gl.createProgram(),s=this.compileShaderSource(this.gl.VERTEX_SHADER,t);if(!s)return we("Vertex shader compile error!"),0;let r=this.compileShaderSource(this.gl.FRAGMENT_SHADER,e);if(!r)return we("Vertex shader compile error!"),0;this.gl.attachShader(i,s),this.gl.attachShader(i,r),this.gl.linkProgram(i);return this.gl.getProgramParameter(i,this.gl.LINK_STATUS)?(this.gl.deleteShader(s),this.gl.deleteShader(r),i):(we("Failed to link program: {0}",i),this.gl.deleteShader(s),s=0,this.gl.deleteShader(r),r=0,i&&(this.gl.deleteProgram(i),i=0),0)}compileShaderSource(t,e){const i=e,s=this.gl.createShader(t);if(this.gl.shaderSource(s,i),this.gl.compileShader(s),!s){const t=this.gl.getShaderInfoLog(s);we("Shader compile log: {0} ",t)}return this.gl.getShaderParameter(s,this.gl.COMPILE_STATUS)?s:(this.gl.deleteShader(s),null)}setGl(t){this.gl=t}}class Cs{static getInstance(){return null==xs&&(xs=new Cs),xs}static deleteInstance(){xs&&(xs.release(),xs=null)}constructor(){this._shaderMap=new Ve}release(){for(const t=this._shaderMap.begin();t.notEqual(this._shaderMap.end());t.preIncrement())t.ptr().second.release();this._shaderMap.clear()}getShader(t){return this._shaderMap.getValue(t)}setGlContext(t){if(!this._shaderMap.isExist(t)){const e=new Ms;e.setGl(t),this._shaderMap.setValue(t,e)}}}class Ss{}var vs=(t=>(t[t.ShaderNames_SetupMask=0]="ShaderNames_SetupMask",t[t.ShaderNames_NormalPremultipliedAlpha=1]="ShaderNames_NormalPremultipliedAlpha",t[t.ShaderNames_NormalMaskedPremultipliedAlpha=2]="ShaderNames_NormalMaskedPremultipliedAlpha",t[t.ShaderNames_NomralMaskedInvertedPremultipliedAlpha=3]="ShaderNames_NomralMaskedInvertedPremultipliedAlpha",t[t.ShaderNames_AddPremultipliedAlpha=4]="ShaderNames_AddPremultipliedAlpha",t[t.ShaderNames_AddMaskedPremultipliedAlpha=5]="ShaderNames_AddMaskedPremultipliedAlpha",t[t.ShaderNames_AddMaskedPremultipliedAlphaInverted=6]="ShaderNames_AddMaskedPremultipliedAlphaInverted",t[t.ShaderNames_MultPremultipliedAlpha=7]="ShaderNames_MultPremultipliedAlpha",t[t.ShaderNames_MultMaskedPremultipliedAlpha=8]="ShaderNames_MultMaskedPremultipliedAlpha",t[t.ShaderNames_MultMaskedPremultipliedAlphaInverted=9]="ShaderNames_MultMaskedPremultipliedAlphaInverted",t))(vs||{});const bs="attribute vec4 a_position;attribute vec2 a_texCoord;varying vec2 v_texCoord;varying vec4 v_myPos;uniform mat4 u_clipMatrix;void main(){ gl_Position = u_clipMatrix * a_position; v_myPos = u_clipMatrix * a_position; v_texCoord = a_texCoord; v_texCoord.y = 1.0 - v_texCoord.y;}",Ps="precision mediump float;varying vec2 v_texCoord;varying vec4 v_myPos;uniform vec4 u_baseColor;uniform vec4 u_channelFlag;uniform sampler2D s_texture0;void main(){ float isInside = step(u_baseColor.x, v_myPos.x/v_myPos.w) * step(u_baseColor.y, v_myPos.y/v_myPos.w) * step(v_myPos.x/v_myPos.w, u_baseColor.z) * step(v_myPos.y/v_myPos.w, u_baseColor.w); gl_FragColor = u_channelFlag * texture2D(s_texture0, v_texCoord).a * isInside;}",Bs="attribute vec4 a_position;attribute vec2 a_texCoord;varying vec2 v_texCoord;uniform mat4 u_matrix;void main(){ gl_Position = u_matrix * a_position; v_texCoord = a_texCoord; v_texCoord.y = 1.0 - v_texCoord.y;}",ws="attribute vec4 a_position;attribute vec2 a_texCoord;varying vec2 v_texCoord;varying vec4 v_clipPos;uniform mat4 u_matrix;uniform mat4 u_clipMatrix;void main(){ gl_Position = u_matrix * a_position; v_clipPos = u_clipMatrix * a_position; v_texCoord = a_texCoord; v_texCoord.y = 1.0 - v_texCoord.y;}",Is="precision mediump float;varying vec2 v_texCoord;uniform vec4 u_baseColor;uniform sampler2D s_texture0;uniform vec4 u_multiplyColor;uniform vec4 u_screenColor;void main(){ vec4 texColor = texture2D(s_texture0, v_texCoord); texColor.rgb = texColor.rgb * u_multiplyColor.rgb; texColor.rgb = (texColor.rgb + u_screenColor.rgb * texColor.a) - (texColor.rgb * u_screenColor.rgb); vec4 color = texColor * u_baseColor; gl_FragColor = vec4(color.rgb, color.a);}",Fs="precision mediump float;varying vec2 v_texCoord;varying vec4 v_clipPos;uniform vec4 u_baseColor;uniform vec4 u_channelFlag;uniform sampler2D s_texture0;uniform sampler2D s_texture1;uniform vec4 u_multiplyColor;uniform vec4 u_screenColor;void main(){ vec4 texColor = texture2D(s_texture0, v_texCoord); texColor.rgb = texColor.rgb * u_multiplyColor.rgb; texColor.rgb = (texColor.rgb + u_screenColor.rgb * texColor.a) - (texColor.rgb * u_screenColor.rgb); vec4 col_formask = texColor * u_baseColor; vec4 clipMask = (1.0 - texture2D(s_texture1, v_clipPos.xy / v_clipPos.w)) * u_channelFlag; float maskVal = clipMask.r + clipMask.g + clipMask.b + clipMask.a; col_formask = col_formask * maskVal; gl_FragColor = col_formask;}",Es="precision mediump float;varying vec2 v_texCoord;varying vec4 v_clipPos;uniform sampler2D s_texture0;uniform sampler2D s_texture1;uniform vec4 u_channelFlag;uniform vec4 u_baseColor;uniform vec4 u_multiplyColor;uniform vec4 u_screenColor;void main(){ vec4 texColor = texture2D(s_texture0, v_texCoord); texColor.rgb = texColor.rgb * u_multiplyColor.rgb; texColor.rgb = (texColor.rgb + u_screenColor.rgb * texColor.a) - (texColor.rgb * u_screenColor.rgb); vec4 col_formask = texColor * u_baseColor; vec4 clipMask = (1.0 - texture2D(s_texture1, v_clipPos.xy / v_clipPos.w)) * u_channelFlag; float maskVal = clipMask.r + clipMask.g + clipMask.b + clipMask.a; col_formask = col_formask * (1.0 - maskVal); gl_FragColor = col_formask;}";var Ls;let Vs,Ts;(t=>{t.CubismShaderSet=Ss,t.CubismShader_WebGL=Ms,t.CubismShaderManager_WebGL=Cs,t.ShaderNames=vs})(Ls||(Ls={}));class Rs extends ys{getMaskRenderTexture(){if(this._maskTexture&&null!=this._maskTexture.textures)this._maskTexture.frameNo=this._currentFrameNo;else{null!=this._maskRenderTextures&&this._maskRenderTextures.clear(),this._maskRenderTextures=new se,null!=this._maskColorBuffers&&this._maskColorBuffers.clear(),this._maskColorBuffers=new se;const t=this._clippingMaskBufferSize;for(let e=0;e<this._renderTextureCount;e++)this._maskColorBuffers.pushBack(this.gl.createTexture()),this.gl.bindTexture(this.gl.TEXTURE_2D,this._maskColorBuffers.at(e)),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,t,t,0,this.gl.RGBA,this.gl.UNSIGNED_BYTE,null),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),this.gl.bindTexture(this.gl.TEXTURE_2D,null),this._maskRenderTextures.pushBack(this.gl.createFramebuffer()),this.gl.bindFramebuffer(this.gl.FRAMEBUFFER,this._maskRenderTextures.at(e)),this.gl.framebufferTexture2D(this.gl.FRAMEBUFFER,this.gl.COLOR_ATTACHMENT0,this.gl.TEXTURE_2D,this._maskColorBuffers.at(e),0);this.gl.bindFramebuffer(this.gl.FRAMEBUFFER,Ts),this._maskTexture=new Ds(this._currentFrameNo,this._maskRenderTextures)}return this._maskTexture.textures}setGL(t){this.gl=t}constructor(){super(As)}setupClippingContext(t,e){this._currentFrameNo++;let i=0;for(let s=0;s<this._clippingContextListForMask.getSize();s++){const e=this._clippingContextListForMask.at(s);this.calcClippedDrawTotalBounds(t,e),e._isUsing&&i++}if(i>0){this.gl.viewport(0,0,this._clippingMaskBufferSize,this._clippingMaskBufferSize),this._currentMaskRenderTexture=this.getMaskRenderTexture().at(0),e.preDraw(),this.setupLayoutBounds(i),this.gl.bindFramebuffer(this.gl.FRAMEBUFFER,this._currentMaskRenderTexture),this._clearedFrameBufferFlags.getSize()!=this._renderTextureCount&&(this._clearedFrameBufferFlags.clear(),this._clearedFrameBufferFlags=new se(this._renderTextureCount));for(let t=0;t<this._clearedFrameBufferFlags.getSize();t++)this._clearedFrameBufferFlags.set(t,!1);for(let i=0;i<this._clippingContextListForMask.getSize();i++){const s=this._clippingContextListForMask.at(i),r=s._allClippedDrawRect,a=s._layoutBounds,n=.05;let o=0,l=0;const u=this.getMaskRenderTexture().at(s._bufferIndex);this._currentMaskRenderTexture!=u&&(this._currentMaskRenderTexture=u,e.preDraw(),this.gl.bindFramebuffer(this.gl.FRAMEBUFFER,this._currentMaskRenderTexture)),this._tmpBoundsOnModel.setRect(r),this._tmpBoundsOnModel.expand(r.width*n,r.height*n),o=a.width/this._tmpBoundsOnModel.width,l=a.height/this._tmpBoundsOnModel.height,this._tmpMatrix.loadIdentity(),this._tmpMatrix.translateRelative(-1,-1),this._tmpMatrix.scaleRelative(2,2),this._tmpMatrix.translateRelative(a.x,a.y),this._tmpMatrix.scaleRelative(o,l),this._tmpMatrix.translateRelative(-this._tmpBoundsOnModel.x,-this._tmpBoundsOnModel.y),this._tmpMatrixForMask.setMatrix(this._tmpMatrix.getArray()),this._tmpMatrix.loadIdentity(),this._tmpMatrix.translateRelative(a.x,a.y),this._tmpMatrix.scaleRelative(o,l),this._tmpMatrix.translateRelative(-this._tmpBoundsOnModel.x,-this._tmpBoundsOnModel.y),this._tmpMatrixForDraw.setMatrix(this._tmpMatrix.getArray()),s._matrixForMask.setMatrix(this._tmpMatrixForMask.getArray()),s._matrixForDraw.setMatrix(this._tmpMatrixForDraw.getArray());const h=s._clippingIdCount;for(let i=0;i<h;i++){const r=s._clippingIdList[i];t.getDrawableDynamicFlagVertexPositionsDidChange(r)&&(e.setIsCulling(0!=t.getDrawableCulling(r)),this._clearedFrameBufferFlags.at(s._bufferIndex)||(this.gl.clearColor(1,1,1,1),this.gl.clear(this.gl.COLOR_BUFFER_BIT),this._clearedFrameBufferFlags.set(s._bufferIndex,!0)),e.setClippingContextBufferForMask(s),e.drawMeshWebGL(t,r))}}this.gl.bindFramebuffer(this.gl.FRAMEBUFFER,Ts),e.setClippingContextBufferForMask(null),this.gl.viewport(Vs[0],Vs[1],Vs[2],Vs[3])}}getColorBuffer(){return this._maskColorBuffers}getClippingMaskCount(){return this._clippingContextListForMask.getSize()}}class Ds{constructor(t,e){this.frameNo=t,this.textures=e}}class As extends Ce{constructor(t,e,i){super(e,i),this._owner=t}getClippingManager(){return this._owner}setGl(t){this._owner.setGL(t)}}class Os{setGlEnable(t,e){e?this.gl.enable(t):this.gl.disable(t)}setGlEnableVertexAttribArray(t,e){e?this.gl.enableVertexAttribArray(t):this.gl.disableVertexAttribArray(t)}save(){null!=this.gl?(this._lastArrayBufferBinding=this.gl.getParameter(this.gl.ARRAY_BUFFER_BINDING),this._lastElementArrayBufferBinding=this.gl.getParameter(this.gl.ELEMENT_ARRAY_BUFFER_BINDING),this._lastProgram=this.gl.getParameter(this.gl.CURRENT_PROGRAM),this._lastActiveTexture=this.gl.getParameter(this.gl.ACTIVE_TEXTURE),this.gl.activeTexture(this.gl.TEXTURE1),this._lastTexture1Binding2D=this.gl.getParameter(this.gl.TEXTURE_BINDING_2D),this.gl.activeTexture(this.gl.TEXTURE0),this._lastTexture0Binding2D=this.gl.getParameter(this.gl.TEXTURE_BINDING_2D),this._lastVertexAttribArrayEnabled[0]=this.gl.getVertexAttrib(0,this.gl.VERTEX_ATTRIB_ARRAY_ENABLED),this._lastVertexAttribArrayEnabled[1]=this.gl.getVertexAttrib(1,this.gl.VERTEX_ATTRIB_ARRAY_ENABLED),this._lastVertexAttribArrayEnabled[2]=this.gl.getVertexAttrib(2,this.gl.VERTEX_ATTRIB_ARRAY_ENABLED),this._lastVertexAttribArrayEnabled[3]=this.gl.getVertexAttrib(3,this.gl.VERTEX_ATTRIB_ARRAY_ENABLED),this._lastScissorTest=this.gl.isEnabled(this.gl.SCISSOR_TEST),this._lastStencilTest=this.gl.isEnabled(this.gl.STENCIL_TEST),this._lastDepthTest=this.gl.isEnabled(this.gl.DEPTH_TEST),this._lastCullFace=this.gl.isEnabled(this.gl.CULL_FACE),this._lastBlend=this.gl.isEnabled(this.gl.BLEND),this._lastFrontFace=this.gl.getParameter(this.gl.FRONT_FACE),this._lastColorMask=this.gl.getParameter(this.gl.COLOR_WRITEMASK),this._lastBlending[0]=this.gl.getParameter(this.gl.BLEND_SRC_RGB),this._lastBlending[1]=this.gl.getParameter(this.gl.BLEND_DST_RGB),this._lastBlending[2]=this.gl.getParameter(this.gl.BLEND_SRC_ALPHA),this._lastBlending[3]=this.gl.getParameter(this.gl.BLEND_DST_ALPHA),this._lastFBO=this.gl.getParameter(this.gl.FRAMEBUFFER_BINDING),this._lastViewport=this.gl.getParameter(this.gl.VIEWPORT)):we("'gl' is null. WebGLRenderingContext is required.\nPlease call 'CubimRenderer_WebGL.startUp' function.")}restore(){null!=this.gl?(this.gl.useProgram(this._lastProgram),this.setGlEnableVertexAttribArray(0,this._lastVertexAttribArrayEnabled[0]),this.setGlEnableVertexAttribArray(1,this._lastVertexAttribArrayEnabled[1]),this.setGlEnableVertexAttribArray(2,this._lastVertexAttribArrayEnabled[2]),this.setGlEnableVertexAttribArray(3,this._lastVertexAttribArrayEnabled[3]),this.setGlEnable(this.gl.SCISSOR_TEST,this._lastScissorTest),this.setGlEnable(this.gl.STENCIL_TEST,this._lastStencilTest),this.setGlEnable(this.gl.DEPTH_TEST,this._lastDepthTest),this.setGlEnable(this.gl.CULL_FACE,this._lastCullFace),this.setGlEnable(this.gl.BLEND,this._lastBlend),this.gl.frontFace(this._lastFrontFace),this.gl.colorMask(this._lastColorMask[0],this._lastColorMask[1],this._lastColorMask[2],this._lastColorMask[3]),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this._lastArrayBufferBinding),this.gl.bindBuffer(this.gl.ELEMENT_ARRAY_BUFFER,this._lastElementArrayBufferBinding),this.gl.activeTexture(this.gl.TEXTURE1),this.gl.bindTexture(this.gl.TEXTURE_2D,this._lastTexture1Binding2D),this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this._lastTexture0Binding2D),this.gl.activeTexture(this._lastActiveTexture),this.gl.blendFuncSeparate(this._lastBlending[0],this._lastBlending[1],this._lastBlending[2],this._lastBlending[3])):we("'gl' is null. WebGLRenderingContext is required.\nPlease call 'CubimRenderer_WebGL.startUp' function.")}setGl(t){this.gl=t}constructor(){this._lastVertexAttribArrayEnabled=new Array(4),this._lastColorMask=new Array(4),this._lastBlending=new Array(4),this._lastViewport=new Array(4)}}class ks extends fe{initialize(t,e=1){t.isUsingMasking()&&(this._clippingManager=new Rs,this._clippingManager.initialize(t,e)),this._sortedDrawableIndexList.resize(t.getDrawableCount(),0),super.initialize(t)}bindTexture(t,e){this._textures.setValue(t,e)}getBindedTextures(){return this._textures}setClippingMaskBufferSize(t){if(!this._model.isUsingMasking())return;const e=this._clippingManager.getRenderTextureCount();this._clippingManager.release(),this._clippingManager=void 0,this._clippingManager=null,this._clippingManager=new Rs,this._clippingManager.setClippingMaskBufferSize(t),this._clippingManager.initialize(this.getModel(),e)}getClippingMaskBufferSize(){return this._model.isUsingMasking()?this._clippingManager.getClippingMaskBufferSize():-1}getRenderTextureCount(){return this._model.isUsingMasking()?this._clippingManager.getRenderTextureCount():-1}constructor(){super(),this._clippingContextBufferForMask=null,this._clippingContextBufferForDraw=null,this._rendererProfile=new Os,this.firstDraw=!0,this._textures=new Ve,this._sortedDrawableIndexList=new se,this._bufferData={vertex:WebGLBuffer=null,uv:WebGLBuffer=null,index:WebGLBuffer=null},this._textures.prepareCapacity(32,!0)}release(){this._clippingManager&&(this._clippingManager.release(),this._clippingManager=void 0,this._clippingManager=null),null!=this.gl&&(this.gl.deleteBuffer(this._bufferData.vertex),this._bufferData.vertex=null,this.gl.deleteBuffer(this._bufferData.uv),this._bufferData.uv=null,this.gl.deleteBuffer(this._bufferData.index),this._bufferData.index=null,this._bufferData=null,this._textures=null)}doDrawModel(){if(null==this.gl)return void we("'gl' is null. WebGLRenderingContext is required.\nPlease call 'CubimRenderer_WebGL.startUp' function.");null!=this._clippingManager&&(this.preDraw(),this.isUsingHighPrecisionMask()?this._clippingManager.setupMatrixForHighPrecision(this.getModel(),!1):this._clippingManager.setupClippingContext(this.getModel(),this)),this.preDraw();const t=this.getModel().getDrawableCount(),e=this.getModel().getDrawableRenderOrders();for(let i=0;i<t;++i){const t=e[i];this._sortedDrawableIndexList.set(t,i)}for(let i=0;i<t;++i){const t=this._sortedDrawableIndexList.at(i);if(!this.getModel().getDrawableDynamicFlagIsVisible(t))continue;const e=null!=this._clippingManager?this._clippingManager.getClippingContextListForDraw().at(t):null;if(null!=e&&this.isUsingHighPrecisionMask()){e._isUsing&&(this.gl.viewport(0,0,this._clippingManager.getClippingMaskBufferSize(),this._clippingManager.getClippingMaskBufferSize()),this.preDraw(),this.gl.bindFramebuffer(this.gl.FRAMEBUFFER,e.getClippingManager().getMaskRenderTexture().at(e._bufferIndex)),this.gl.clearColor(1,1,1,1),this.gl.clear(this.gl.COLOR_BUFFER_BIT));{const t=e._clippingIdCount;for(let i=0;i<t;i++){const t=e._clippingIdList[i];this._model.getDrawableDynamicFlagVertexPositionsDidChange(t)&&(this.setIsCulling(0!=this._model.getDrawableCulling(t)),this.setClippingContextBufferForMask(e),this.drawMeshWebGL(this._model,t))}}this.gl.bindFramebuffer(this.gl.FRAMEBUFFER,Ts),this.setClippingContextBufferForMask(null),this.gl.viewport(Vs[0],Vs[1],Vs[2],Vs[3]),this.preDraw()}this.setClippingContextBufferForDraw(e),this.setIsCulling(this.getModel().getDrawableCulling(t)),this.drawMeshWebGL(this._model,t)}}drawMeshWebGL(t,e){this.isCulling()?this.gl.enable(this.gl.CULL_FACE):this.gl.disable(this.gl.CULL_FACE),this.gl.frontFace(this.gl.CCW),this.isGeneratingMask()?Cs.getInstance().getShader(this.gl).setupShaderProgramForMask(this,t,e):Cs.getInstance().getShader(this.gl).setupShaderProgramForDraw(this,t,e);{const i=t.getDrawableVertexIndexCount(e);this.gl.drawElements(this.gl.TRIANGLES,i,this.gl.UNSIGNED_SHORT,0)}this.gl.useProgram(null),this.setClippingContextBufferForDraw(null),this.setClippingContextBufferForMask(null)}saveProfile(){this._rendererProfile.save()}restoreProfile(){this._rendererProfile.restore()}static doStaticRelease(){Cs.deleteInstance()}setRenderState(t,e){Ts=t,Vs=e}preDraw(){if(this.firstDraw&&(this.firstDraw=!1),this.gl.disable(this.gl.SCISSOR_TEST),this.gl.disable(this.gl.STENCIL_TEST),this.gl.disable(this.gl.DEPTH_TEST),this.gl.frontFace(this.gl.CW),this.gl.enable(this.gl.BLEND),this.gl.colorMask(!0,!0,!0,!0),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),this.gl.bindBuffer(this.gl.ELEMENT_ARRAY_BUFFER,null),this.getAnisotropy()>0&&this._extension)for(let t=0;t<this._textures.getSize();++t)this.gl.bindTexture(this.gl.TEXTURE_2D,this._textures.getValue(t)),this.gl.texParameterf(this.gl.TEXTURE_2D,this._extension.TEXTURE_MAX_ANISOTROPY_EXT,this.getAnisotropy())}setClippingContextBufferForMask(t){this._clippingContextBufferForMask=t}getClippingContextBufferForMask(){return this._clippingContextBufferForMask}setClippingContextBufferForDraw(t){this._clippingContextBufferForDraw=t}getClippingContextBufferForDraw(){return this._clippingContextBufferForDraw}isGeneratingMask(){return null!=this.getClippingContextBufferForMask()}startUp(t){this.gl=t,this._clippingManager&&this._clippingManager.setGL(t),Cs.getInstance().setGlContext(t),this._rendererProfile.setGl(t),this._extension=this.gl.getExtension("EXT_texture_filter_anisotropic")||this.gl.getExtension("WEBKIT_EXT_texture_filter_anisotropic")||this.gl.getExtension("MOZ_EXT_texture_filter_anisotropic")}}var Ns;fe.staticRelease=()=>{ks.doStaticRelease()},(t=>{t.CubismClippingContext=As,t.CubismClippingManager_WebGL=Rs,t.CubismRenderTextureResource=Ds,t.CubismRenderer_WebGL=ks})(Ns||(Ns={}));const Us=new me,zs={CenterX:"centerX",centerX:"centerX",center_x:"centerX",CenterY:"centerY",centerY:"centerY",center_y:"centerY",X:"x",x:"x",Y:"y",y:"y",Width:"width",width:"width",Height:"height",height:"height",Top:"top",top:"top",Bottom:"bottom",bottom:"bottom",Left:"left",left:"left",Right:"right",right:"right"};function js(t){if(!t.isUsingMasking())return!1;const e=function(t){var e,i;const s=t.getDrawableMaskCounts(),r=t.getDrawableMasks(),a=new Set,n=t.getDrawableCount();let o=0,l=0,u=0,h=0;for(let d=0;d<n;d++){const n=t.getDrawableVertexCount(d),g=null!=(e=s[d])?e:0;if(h+=n,g<=0)continue;o++,u+=n,l=Math.max(l,g);const c=Array.from(null!=(i=r[d])?i:[]).slice(0,g).sort((t,e)=>t-e).join(",");a.add(c)}return{maskedDrawableCount:o,uniqueMaskSetCount:a.size,maxMasksPerDrawable:l,maskedVertexCount:u,totalVertexCount:h}}(t),i=e.totalVertexCount>0?e.maskedVertexCount/e.totalVertexCount:0;return e.uniqueMaskSetCount>16||e.maskedDrawableCount>64||e.maxMasksPerDrawable>=3||e.maskedVertexCount>4096||i>=.5&&e.maskedDrawableCount>24}class Gs extends st{constructor(t,i,s){super(),d(this,"settings"),d(this,"options"),d(this,"coreModel"),d(this,"motionManager"),d(this,"parallelMotionManager"),d(this,"lipSync",!0),d(this,"breath",gs.create()),d(this,"eyeBlink"),d(this,"renderer",new ks),d(this,"idManager"),d(this,"idParamAngleX"),d(this,"idParamAngleY"),d(this,"idParamAngleZ"),d(this,"idParamEyeBallX"),d(this,"idParamEyeBallY"),d(this,"idParamBodyAngleX"),d(this,"idParamBreath"),d(this,"idParamMouthForm"),d(this,"pixelsPerUnit",1),d(this,"modelTransform",new e.Matrix),this.coreModel=t,this.settings=i,this.options=Object.assign({},{breathDepth:1,lipSyncGain:1.5,lipSyncWeight:.4},s),this.idManager=ti.getIdManager(),this.idParamAngleX=this.getIdSafe(us.ParamAngleX),this.idParamAngleY=this.getIdSafe(us.ParamAngleY),this.idParamAngleZ=this.getIdSafe(us.ParamAngleZ),this.idParamEyeBallX=this.getIdSafe(us.ParamEyeBallX),this.idParamEyeBallY=this.getIdSafe(us.ParamEyeBallY),this.idParamBodyAngleX=this.getIdSafe(us.ParamBodyAngleX),this.idParamBreath=this.getIdSafe(us.ParamBreath),this.idParamMouthForm=this.getIdSafe(us.ParamMouthForm),this.motionManager=new Zi(this),this.parallelMotionManager=[],this.init()}init(){var t;super.init();const e=this.settings.getEyeBlinkParameters();if(!1!==this.options.eyeBlink&&e.length){const i=new se;for(const t of e)i.pushBack(this.idManager.getId(t));const s=ms.create();null==(t=s.setParameterIds)||t.call(s,i),this.eyeBlink=s}const i=new se;var s,r;i.pushBack(new cs(this.idParamAngleX,0,15*this.options.breathDepth,6.5345,.5)),i.pushBack(new cs(this.idParamAngleY,0,8*this.options.breathDepth,3.5345,.5)),i.pushBack(new cs(this.idParamAngleZ,0,10*this.options.breathDepth,5.5345,.5)),i.pushBack(new cs(this.idParamBodyAngleX,0,4*this.options.breathDepth,15.5345,.5)),i.pushBack(new cs(this.idParamBreath,0,.5,3.2345,.5)),this.breath.setParameters(i),this.renderer.initialize(this.coreModel,function(t){var e;if(!t.isUsingMasking())return 1;const i=t.getDrawableMaskCounts(),s=t.getDrawableMasks(),r=new Set;for(let n=0;n<t.getDrawableCount();n++){const t=i[n];if(!t||t<=0)continue;const a=Array.from(null!=(e=s[n])?e:[]).slice(0,t).sort((t,e)=>t-e).join(",");r.add(a)}const a=r.size;return a<=36?1:Math.ceil(a/32)}(this.coreModel)),this.renderer.useHighPrecisionMask((s=this.coreModel,"boolean"==typeof(r=this.options.useHighPrecisionMask)?r:js(s))),this.renderer.setIsPremultipliedAlpha(!0)}getIdSafe(t){return this.idManager.getId(null!=t?t:"")}getSize(){return[this.coreModel.getModel().canvasinfo.CanvasWidth,this.coreModel.getModel().canvasinfo.CanvasHeight]}getLayout(){const t={},e=this.settings.layout;if(e)for(const[i,s]of Object.entries(e)){const e=zs[i];e&&"number"==typeof s&&(t[e]=s)}return t}setupLayout(){const t=this,e=this.getSize();t.originalWidth=e[0],t.originalHeight=e[1],t.pixelsPerUnit=this.coreModel.getModel().canvasinfo.PixelsPerUnit;const i=tt(this.localTransform,this.originalWidth,this.originalHeight,this.getLayout());t.width=i.width,t.height=i.height,this.modelTransform.identity().scale(this.pixelsPerUnit,this.pixelsPerUnit).translate(this.originalWidth/2,this.originalHeight/2)}updateWebGLContext(t,e){this.renderer.firstDraw=!0,this.renderer._bufferData={vertex:null,uv:null,index:null},this.renderer.startUp(t),this.renderer._clippingManager&&(this.renderer._clippingManager._currentFrameNo=e),Cs.getInstance().setGlContext(t)}bindTexture(t,e){this.renderer.bindTexture(t,e)}getHitAreaDefs(){var t,e,i;const s=this.settings.json;return et(null!=(i=null!=(e=null!=(t=this.settings.hitAreas)?t:s.HitAreas)?e:s.hitAreas)?i:s.hit_areas,t=>this.coreModel.getDrawableIndex(this.idManager.getId(t)))}getDrawableIDs(){const t=this.coreModel.getDrawableCount(),e=[];for(let i=0;i<t;i++)e.push(this.coreModel.getDrawableId(i).getString().s);return e}getDrawableIndex(t){return this.coreModel.getDrawableIndex(this.idManager.getId(t))}getDrawableVertices(t){if("string"==typeof t){const e=t;if(-1===(t=this.getDrawableIndex(e)))throw new TypeError("Unable to find drawable ID: "+e)}const e=this.coreModel.getDrawableVertices(t).slice();for(let i=0;i<e.length;i+=2)e[i]=e[i]*this.pixelsPerUnit+this.originalWidth/2,e[i+1]=-e[i+1]*this.pixelsPerUnit+this.originalHeight/2;return e}updateTransform(t){this.drawingMatrix.copyFrom(this.modelTransform).prepend(this.localTransform).prepend(t)}update(t,e){var i,s,r,a,n;super.update(t,e),t/=1e3,e/=1e3;const o=this.coreModel,l=this.updateMotions(o,e);if(o.saveParameters(),null==(i=this.motionManager.expressionManager)||i.update(o,e),l||null==(r=null==(s=this.eyeBlink)?void 0:s.updateParameters)||r.call(s,o,t),this.updateFocus(),this.updateNaturalMovements(1e3*t,1e3*e),this.lipSync&&this.motionManager.currentAudio){let t=this.motionManager.mouthSync()*this.options.lipSyncGain;t=Math.pow(t,1.15);t=m(t,t>0?.1:0,1),this.motionManager.lipSyncIds.forEach(e=>{o.addParameterValueById(this.getIdSafe(e),t,this.options.lipSyncWeight)})}null==(a=this.physics)||a.evaluate(o,t),null==(n=this.pose)||n.updateParameters(o,t),this.emit("beforeModelUpdate"),o.update(),o.loadParameters()}updateFocus(){this.coreModel.addParameterValueById(this.idParamEyeBallX,this.focusController.x),this.coreModel.addParameterValueById(this.idParamEyeBallY,this.focusController.y),this.coreModel.addParameterValueById(this.idParamAngleX,30*this.focusController.x),this.coreModel.addParameterValueById(this.idParamAngleY,30*this.focusController.y),this.coreModel.addParameterValueById(this.idParamAngleZ,this.focusController.x*this.focusController.y*-30),this.coreModel.addParameterValueById(this.idParamBodyAngleX,10*this.focusController.x)}updateFacialEmotion(t){this.coreModel.addParameterValueById(this.idParamMouthForm,t)}updateNaturalMovements(t,e){var i;null==(i=this.breath)||i.updateParameters(this.coreModel,t/1e3)}draw(t){const e=this.drawingMatrix,i=Us.getArray();i[0]=e.a,i[1]=e.b,i[4]=-e.c,i[5]=-e.d,i[12]=e.tx,i[13]=e.ty,this.renderer.setMvpMatrix(Us);const s=t.getParameter(t.FRAMEBUFFER_BINDING),r=t.getParameter(t.CULL_FACE_MODE),a=i[0]*i[5]-i[1]*i[4];t.cullFace(a<0?t.FRONT:t.BACK),this.renderer.setRenderState(s,this.viewport);try{this.renderer.drawModel()}finally{t.cullFace(r)}}extendParallelMotionManager(t){for(;this.parallelMotionManager.length<t;)this.parallelMotionManager.push(new ss(this))}destroy(){super.destroy(),this.renderer.release(),this.coreModel.release(),this.renderer=void 0,this.coreModel=void 0}}class Xs{}var Hs;(t=>{t.ICubismModelSetting=Xs})(Hs||(Hs={}));var Ys,qs=(t=>(t[t.FrequestNode_Groups=0]="FrequestNode_Groups",t[t.FrequestNode_Moc=1]="FrequestNode_Moc",t[t.FrequestNode_Motions=2]="FrequestNode_Motions",t[t.FrequestNode_Expressions=3]="FrequestNode_Expressions",t[t.FrequestNode_Textures=4]="FrequestNode_Textures",t[t.FrequestNode_Physics=5]="FrequestNode_Physics",t[t.FrequestNode_Pose=6]="FrequestNode_Pose",t[t.FrequestNode_HitAreas=7]="FrequestNode_HitAreas",t))(qs||{});class Ws extends Xs{constructor(t,e){super(),this.version="Version",this.fileReferences="FileReferences",this.groups="Groups",this.layout="Layout",this.hitAreas="HitAreas",this.moc="Moc",this.textures="Textures",this.physics="Physics",this.pose="Pose",this.expressions="Expressions",this.motions="Motions",this.userData="UserData",this.name="Name",this.filePath="File",this.id="Id",this.ids="Ids",this.target="Target",this.idle="Idle",this.tapBody="TapBody",this.pinchIn="PinchIn",this.pinchOut="PinchOut",this.shake="Shake",this.flickHead="FlickHead",this.parameter="Parameter",this.soundPath="Sound",this.fadeInTime="FadeInTime",this.fadeOutTime="FadeOutTime",this.centerX="CenterX",this.centerY="CenterY",this.x="X",this.y="Y",this.width="Width",this.height="Height",this.lipSync="LipSync",this.eyeBlink="EyeBlink",this.initParameter="init_param",this.initPartsVisible="init_parts_visible",this.val="val",this._json=ke.create(t,e),this.getJson()&&(this._jsonValue=new se,this._jsonValue.pushBack(this.getJson().getRoot().getValueByString(this.groups)),this._jsonValue.pushBack(this.getJson().getRoot().getValueByString(this.fileReferences).getValueByString(this.moc)),this._jsonValue.pushBack(this.getJson().getRoot().getValueByString(this.fileReferences).getValueByString(this.motions)),this._jsonValue.pushBack(this.getJson().getRoot().getValueByString(this.fileReferences).getValueByString(this.expressions)),this._jsonValue.pushBack(this.getJson().getRoot().getValueByString(this.fileReferences).getValueByString(this.textures)),this._jsonValue.pushBack(this.getJson().getRoot().getValueByString(this.fileReferences).getValueByString(this.physics)),this._jsonValue.pushBack(this.getJson().getRoot().getValueByString(this.fileReferences).getValueByString(this.pose)),this._jsonValue.pushBack(this.getJson().getRoot().getValueByString(this.hitAreas)))}release(){ke.delete(this._json),this._jsonValue=null}getJson(){return this._json}getModelFileName(){return this.isExistModelFile()?this._jsonValue.at(1).getRawString():""}getTextureCount(){return this.isExistTextureFiles()?this._jsonValue.at(4).getSize():0}getTextureDirectory(){const t=this._jsonValue.at(4).getValueByIndex(0).getRawString().split("/"),e=t.length-1;let i="";for(let s=0;s<e;s++)i+=t[s],s<e-1&&(i+="/");return i}getTextureFileName(t){return this._jsonValue.at(4).getValueByIndex(t).getRawString()}getHitAreasCount(){return this.isExistHitAreas()?this._jsonValue.at(7).getSize():0}getHitAreaId(t){return ti.getIdManager().getId(this._jsonValue.at(7).getValueByIndex(t).getValueByString(this.id).getRawString())}getHitAreaName(t){return this._jsonValue.at(7).getValueByIndex(t).getValueByString(this.name).getRawString()}getPhysicsFileName(){return this.isExistPhysicsFile()?this._jsonValue.at(5).getRawString():""}getPoseFileName(){return this.isExistPoseFile()?this._jsonValue.at(6).getRawString():""}getExpressionCount(){return this.isExistExpressionFile()?this._jsonValue.at(3).getSize():0}getExpressionName(t){return this._jsonValue.at(3).getValueByIndex(t).getValueByString(this.name).getRawString()}getExpressionFileName(t){return this._jsonValue.at(3).getValueByIndex(t).getValueByString(this.filePath).getRawString()}getMotionGroupCount(){return this.isExistMotionGroups()?this._jsonValue.at(2).getKeys().getSize():0}getMotionGroupName(t){return this.isExistMotionGroups()?this._jsonValue.at(2).getKeys().at(t):null}getMotionCount(t){return this.isExistMotionGroupName(t)?this._jsonValue.at(2).getValueByString(t).getSize():0}getMotionFileName(t,e){return this.isExistMotionGroupName(t)?this._jsonValue.at(2).getValueByString(t).getValueByIndex(e).getValueByString(this.filePath).getRawString():""}getMotionSoundFileName(t,e){return this.isExistMotionSoundFile(t,e)?this._jsonValue.at(2).getValueByString(t).getValueByIndex(e).getValueByString(this.soundPath).getRawString():""}getMotionFadeInTimeValue(t,e){return this.isExistMotionFadeIn(t,e)?this._jsonValue.at(2).getValueByString(t).getValueByIndex(e).getValueByString(this.fadeInTime).toFloat():-1}getMotionFadeOutTimeValue(t,e){return this.isExistMotionFadeOut(t,e)?this._jsonValue.at(2).getValueByString(t).getValueByIndex(e).getValueByString(this.fadeOutTime).toFloat():-1}getUserDataFile(){return this.isExistUserDataFile()?this.getJson().getRoot().getValueByString(this.fileReferences).getValueByString(this.userData).getRawString():""}getLayoutMap(t){const e=this.getJson().getRoot().getValueByString(this.layout).getMap();if(null==e)return!1;let i=!1;for(const s=e.begin();s.notEqual(e.end());s.preIncrement())t.setValue(s.ptr().first,s.ptr().second.toFloat()),i=!0;return i}getEyeBlinkParameterCount(){if(!this.isExistEyeBlinkParameters())return 0;let t=0;for(let e=0;e<this._jsonValue.at(0).getSize();e++){const i=this._jsonValue.at(0).getValueByIndex(e);if(!i.isNull()&&!i.isError()&&i.getValueByString(this.name).getRawString()==this.eyeBlink){t=i.getValueByString(this.ids).getVector().getSize();break}}return t}getEyeBlinkParameterId(t){if(!this.isExistEyeBlinkParameters())return null;for(let e=0;e<this._jsonValue.at(0).getSize();e++){const i=this._jsonValue.at(0).getValueByIndex(e);if(!i.isNull()&&!i.isError()&&i.getValueByString(this.name).getRawString()==this.eyeBlink)return ti.getIdManager().getId(i.getValueByString(this.ids).getValueByIndex(t).getRawString())}return null}getLipSyncParameterCount(){if(!this.isExistLipSyncParameters())return 0;let t=0;for(let e=0;e<this._jsonValue.at(0).getSize();e++){const i=this._jsonValue.at(0).getValueByIndex(e);if(!i.isNull()&&!i.isError()&&i.getValueByString(this.name).getRawString()==this.lipSync){t=i.getValueByString(this.ids).getVector().getSize();break}}return t}getLipSyncParameterId(t){if(!this.isExistLipSyncParameters())return null;for(let e=0;e<this._jsonValue.at(0).getSize();e++){const i=this._jsonValue.at(0).getValueByIndex(e);if(!i.isNull()&&!i.isError()&&i.getValueByString(this.name).getRawString()==this.lipSync)return ti.getIdManager().getId(i.getValueByString(this.ids).getValueByIndex(t).getRawString())}return null}isExistModelFile(){const t=this._jsonValue.at(1);return!t.isNull()&&!t.isError()}isExistTextureFiles(){const t=this._jsonValue.at(4);return!t.isNull()&&!t.isError()}isExistHitAreas(){const t=this._jsonValue.at(7);return!t.isNull()&&!t.isError()}isExistPhysicsFile(){const t=this._jsonValue.at(5);return!t.isNull()&&!t.isError()}isExistPoseFile(){const t=this._jsonValue.at(6);return!t.isNull()&&!t.isError()}isExistExpressionFile(){const t=this._jsonValue.at(3);return!t.isNull()&&!t.isError()}isExistMotionGroups(){const t=this._jsonValue.at(2);return!t.isNull()&&!t.isError()}isExistMotionGroupName(t){const e=this._jsonValue.at(2).getValueByString(t);return!e.isNull()&&!e.isError()}isExistMotionSoundFile(t,e){const i=this._jsonValue.at(2).getValueByString(t).getValueByIndex(e).getValueByString(this.soundPath);return!i.isNull()&&!i.isError()}isExistMotionFadeIn(t,e){const i=this._jsonValue.at(2).getValueByString(t).getValueByIndex(e).getValueByString(this.fadeInTime);return!i.isNull()&&!i.isError()}isExistMotionFadeOut(t,e){const i=this._jsonValue.at(2).getValueByString(t).getValueByIndex(e).getValueByString(this.fadeOutTime);return!i.isNull()&&!i.isError()}isExistUserDataFile(){const t=this.getJson().getRoot().getValueByString(this.fileReferences).getValueByString(this.userData);return!t.isNull()&&!t.isError()}isExistEyeBlinkParameters(){if(this._jsonValue.at(0).isNull()||this._jsonValue.at(0).isError())return!1;for(let t=0;t<this._jsonValue.at(0).getSize();++t)if(this._jsonValue.at(0).getValueByIndex(t).getValueByString(this.name).getRawString()==this.eyeBlink)return!0;return!1}isExistLipSyncParameters(){if(this._jsonValue.at(0).isNull()||this._jsonValue.at(0).isError())return!1;for(let t=0;t<this._jsonValue.at(0).getSize();++t)if(this._jsonValue.at(0).getValueByIndex(t).getValueByString(this.name).getRawString()==this.lipSync)return!0;return!1}}(t=>{t.CubismModelSettingJson=Ws,t.FrequestNode=qs})(Ys||(Ys={}));const Js=[us.ParamEyeLOpen,us.ParamEyeROpen];class $s extends F{constructor(t){var e,i;if(super(t),d(this,"moc"),d(this,"textures"),d(this,"layout"),d(this,"hitAreas"),d(this,"expressions"),d(this,"motions"),!$s.isValidJSON(t))throw new TypeError("Invalid JSON.");const s=(new TextEncoder).encode(JSON.stringify(t)).buffer;Object.assign(this,new Ws(s,s.byteLength)),this.moc=t.FileReferences.Moc,this.textures=[...t.FileReferences.Textures],this.pose=t.FileReferences.Pose,this.physics=t.FileReferences.Physics,this.expressions=null==(e=t.FileReferences.Expressions)?void 0:e.filter(t=>!!t&&"string"==typeof t.File),this.motions=null!=(i=t.FileReferences.Motions)?i:t.Motions,this.layout=t.Layout,this.hitAreas=t.HitAreas;const r=this.getFileStem(this.moc);this.setModelName(r,this.name)}static isValidJSON(t){if(!t||"object"!=typeof t)return!1;const e=t.FileReferences;if(!e||"object"!=typeof e||"string"!=typeof e.Moc)return!1;const i=e.Textures;if(!Array.isArray(i)||0===i.length)return!1;if(!i.every(t=>"string"==typeof t))return!1;const s=e.Expressions;return!(void 0!==s&&(!Array.isArray(s)||s.some(t=>!(t=>!!t&&"string"==typeof t.File)(t))))}replaceFiles(t){if(super.replaceFiles(t),this.motions)for(const[e,i]of Object.entries(this.motions))for(let s=0;s<i.length;s++){const r=i[s];(null==r?void 0:r.File)&&(r.File=t(r.File,`motions.${e}[${s}].File`),r.Sound&&(r.Sound=t(r.Sound,`motions.${e}[${s}].Sound`)))}if(this.expressions)for(let e=0;e<this.expressions.length;e++){const i=this.expressions[e];(null==i?void 0:i.File)&&(i.File=t(i.File,`expressions[${e}].File`))}}getEyeBlinkParameters(){var t,e,i;const s=[],r=null!=(e=null==(t=this.getEyeBlinkParameterCount)?void 0:t.call(this))?e:0;if(r>0)for(let a=0;a<r;a++){const t=null==(i=this.getEyeBlinkParameterId)?void 0:i.call(this,a);(null==t?void 0:t.getString)&&s.push(t.getString().s)}else{let t=!1;const e=this.json.Groups;if(Array.isArray(e))for(const i of e)if("EyeBlink"===(null==i?void 0:i.Name)&&(t=!0,Array.isArray(i.Ids)))for(const t of i.Ids)"string"==typeof t?s.push(t):(null==t?void 0:t.Id)&&s.push(t.Id);if(t)return s}return s.length?s:[...Js]}getLipSyncParameters(){var t,e,i;const s=[],r=null!=(e=null==(t=this.getLipSyncParameterCount)?void 0:t.call(this))?e:0;if(r>0)for(let a=0;a<r;a++){const t=null==(i=this.getLipSyncParameterId)?void 0:i.call(this,a);(null==t?void 0:t.getString)&&s.push(t.getString().s)}else if(Array.isArray(this.json.Groups)){const t=this.json.Groups;for(const e of t)if("LipSync"===(null==e?void 0:e.Name)&&Array.isArray(e.Ids))for(const t of e.Ids)"string"==typeof t?s.push(t):(null==t?void 0:t.Id)&&s.push(t.Id)}return s}}let Zs;M($s,[Ws]);let Ks=20,Qs=16;function tr(t={}){null!=t.memorySizeMB&&(Qs=t.memorySizeMB)}function er(){return ti.isStarted()?Promise.resolve():(null!=Zs||(Zs=new Promise((t,e)=>{!function i(){try{ir(),t()}catch(s){if(Ks--,Ks<0)return void e(new Error("Failed to start up Cubism framework.",{cause:s}));p.log("Cubism","Startup failed, retrying 10ms later..."),setTimeout(i,10)}}()})),Zs)}function ir(t,e){const i=h({logFunction:console.log,loggingLevel:si.LogLevel_Verbose},t),s=null!=e?e:Qs;ti.startUp(i),ti.initialize(f(s))}const sr="FadeInTime",rr="Link";class ar{static create(t,e){const i=ke.create(t,e);if(!i)return null;const s=new ar,r=i.getRoot();r.getValueByString(sr).isNull()||(s._fadeTimeSeconds=r.getValueByString(sr).toFloat(.5),s._fadeTimeSeconds<0&&(s._fadeTimeSeconds=.5));const a=r.getValueByString("Groups"),n=a.getSize();for(let o=0;o<n;++o){const t=a.getValueByIndex(o),e=t.getSize();let i=0;for(let r=0;r<e;++r){const e=t.getValueByIndex(r),a=new nr,n=ti.getIdManager().getId(e.getValueByString("Id").getRawString());if(a.partId=n,!e.getValueByString(rr).isNull()){const t=e.getValueByString(rr),i=t.getSize();for(let e=0;e<i;++e){const i=new nr,s=ti.getIdManager().getId(t.getValueByIndex(e).getString());i.partId=s,a.link.pushBack(i)}}s._partGroups.pushBack(a.clone()),++i}s._partGroupCounts.pushBack(i)}return ke.delete(i),s}static delete(t){}updateParameters(t,e){t!=this._lastModel&&this.reset(t),this._lastModel=t,e<0&&(e=0);let i=0;for(let s=0;s<this._partGroupCounts.getSize();s++){const r=this._partGroupCounts.at(s);this.doFade(t,e,i,r),i+=r}this.copyPartOpacities(t)}reset(t){let e=0;for(let i=0;i<this._partGroupCounts.getSize();++i){const s=this._partGroupCounts.at(i);for(let i=e;i<e+s;++i){this._partGroups.at(i).initialize(t);const s=this._partGroups.at(i).partIndex,r=this._partGroups.at(i).parameterIndex;if(!(s<0)){t.setPartOpacityByIndex(s,i==e?1:0),t.setParameterValueByIndex(r,i==e?1:0);for(let e=0;e<this._partGroups.at(i).link.getSize();++e)this._partGroups.at(i).link.at(e).initialize(t)}}e+=s}}copyPartOpacities(t){for(let e=0;e<this._partGroups.getSize();++e){const i=this._partGroups.at(e);if(0==i.link.getSize())continue;const s=this._partGroups.at(e).partIndex,r=t.getPartOpacityByIndex(s);for(let e=0;e<i.link.getSize();++e){const s=i.link.at(e).partIndex;s<0||t.setPartOpacityByIndex(s,r)}}}doFade(t,e,i,s){let r=-1,a=1;const n=.5;for(let o=i;o<i+s;++o){const i=this._partGroups.at(o).partIndex,s=this._partGroups.at(o).parameterIndex;if(t.getParameterValueByIndex(s)>.001){if(r>=0)break;if(r=o,0==this._fadeTimeSeconds){a=1;continue}a=t.getPartOpacityByIndex(i),a+=e/this._fadeTimeSeconds,a>1&&(a=1)}}r<0&&(r=0,a=1);for(let o=i;o<i+s;++o){const e=this._partGroups.at(o).partIndex;if(r==o)t.setPartOpacityByIndex(e,a);else{let i,s=t.getPartOpacityByIndex(e);i=a<n?-.5*a/n+1:(1-a)*n/.5;(1-i)*(1-a)>.15&&(i=1-.15/(1-a)),s>i&&(s=i),t.setPartOpacityByIndex(e,s)}}}constructor(){this._fadeTimeSeconds=.5,this._lastModel=null,this._partGroups=new se,this._partGroupCounts=new se}}class nr{constructor(t){if(this.parameterIndex=0,this.partIndex=0,this.link=new se,null!=t){this.partId=t.partId;for(const e=t.link.begin();e.notEqual(t.link.end());e.preIncrement())this.link.pushBack(e.ptr().clone())}}assignment(t){this.partId=t.partId;for(const e=t.link.begin();e.notEqual(t.link.end());e.preIncrement())this.link.pushBack(e.ptr().clone());return this}initialize(t){this.parameterIndex=t.getParameterIndex(this.partId),this.partIndex=t.getPartIndex(this.partId),t.setParameterValueByIndex(this.parameterIndex,1)}clone(){const t=new nr;t.partId=this.partId,t.parameterIndex=this.parameterIndex,t.partIndex=this.partIndex,t.link=new se;for(let e=this.link.begin();e.notEqual(this.link.end());e.increment())t.link.pushBack(e.ptr().clone());return t}}var or,lr,ur;(t=>{t.CubismPose=ar,t.PartData=nr})(or||(or={}));class hr{constructor(t=!1,e=!1){this.isOverridden=t,this.isParameterRepeated=e}}class dr{constructor(t=!1,e=new Me){this.isOverridden=t,this.color=e}get isOverwritten(){return this.isOverridden}}class gr{constructor(t=!1,e=new Me){this.isOverridden=t,this.color=e}get isOverwritten(){return this.isOverridden}}class cr{constructor(t=!1,e=!1){this.isOverridden=t,this.isCulling=e}get isOverwritten(){return this.isOverridden}}class pr{update(){this._model.update(),this._model.drawables.resetDynamicFlags()}getPixelsPerUnit(){return null==this._model?0:this._model.canvasinfo.PixelsPerUnit}getCanvasWidth(){return null==this._model?0:this._model.canvasinfo.CanvasWidth/this._model.canvasinfo.PixelsPerUnit}getCanvasHeight(){return null==this._model?0:this._model.canvasinfo.CanvasHeight/this._model.canvasinfo.PixelsPerUnit}saveParameters(){const t=this._model.parameters.count,e=this._savedParameters.getSize();for(let i=0;i<t;++i)i<e?this._savedParameters.set(i,this._parameterValues[i]):this._savedParameters.pushBack(this._parameterValues[i])}getMultiplyColor(t){if(this.getOverrideFlagForModelMultiplyColors()||this.getOverrideFlagForDrawableMultiplyColors(t))return this._userMultiplyColors.at(t).color;return this.getDrawableMultiplyColor(t)}getScreenColor(t){if(this.getOverrideFlagForModelScreenColors()||this.getOverrideFlagForDrawableScreenColors(t))return this._userScreenColors.at(t).color;return this.getDrawableScreenColor(t)}setMultiplyColorByTextureColor(t,e){this.setMultiplyColorByRGBA(t,e.r,e.g,e.b,e.a)}setMultiplyColorByRGBA(t,e,i,s,r=1){this._userMultiplyColors.at(t).color.r=e,this._userMultiplyColors.at(t).color.g=i,this._userMultiplyColors.at(t).color.b=s,this._userMultiplyColors.at(t).color.a=r}setScreenColorByTextureColor(t,e){this.setScreenColorByRGBA(t,e.r,e.g,e.b,e.a)}setScreenColorByRGBA(t,e,i,s,r=1){this._userScreenColors.at(t).color.r=e,this._userScreenColors.at(t).color.g=i,this._userScreenColors.at(t).color.b=s,this._userScreenColors.at(t).color.a=r}getPartMultiplyColor(t){return this._userPartMultiplyColors.at(t).color}getPartScreenColor(t){return this._userPartScreenColors.at(t).color}setPartColor(t,e,i,s,r,a,n){if(a.at(t).color.r=e,a.at(t).color.g=i,a.at(t).color.b=s,a.at(t).color.a=r,a.at(t).isOverridden)for(let o=0;o<this._partChildDrawables.at(t).getSize();++o){const a=this._partChildDrawables.at(t).at(o);n.at(a).color.r=e,n.at(a).color.g=i,n.at(a).color.b=s,n.at(a).color.a=r}}setPartMultiplyColorByTextureColor(t,e){this.setPartMultiplyColorByRGBA(t,e.r,e.g,e.b,e.a)}setPartMultiplyColorByRGBA(t,e,i,s,r){this.setPartColor(t,e,i,s,r,this._userPartMultiplyColors,this._userMultiplyColors)}setPartScreenColorByTextureColor(t,e){this.setPartScreenColorByRGBA(t,e.r,e.g,e.b,e.a)}setPartScreenColorByRGBA(t,e,i,s,r){this.setPartColor(t,e,i,s,r,this._userPartScreenColors,this._userScreenColors)}getOverrideFlagForModelParameterRepeat(){return this._isOverriddenParameterRepeat}setOverrideFlagForModelParameterRepeat(t){this._isOverriddenParameterRepeat=t}getOverrideFlagForParameterRepeat(t){return this._userParameterRepeatDataList.at(t).isOverridden}setOverrideFlagForParameterRepeat(t,e){this._userParameterRepeatDataList.at(t).isOverridden=e}getRepeatFlagForParameterRepeat(t){return this._userParameterRepeatDataList.at(t).isParameterRepeated}setRepeatFlagForParameterRepeat(t,e){this._userParameterRepeatDataList.at(t).isParameterRepeated=e}getOverwriteFlagForModelMultiplyColors(){return Be("getOverwriteFlagForModelMultiplyColors() is a deprecated function. Please use getOverrideFlagForModelMultiplyColors()."),this.getOverrideFlagForModelMultiplyColors()}getOverrideFlagForModelMultiplyColors(){return this._isOverriddenModelMultiplyColors}getOverwriteFlagForModelScreenColors(){return Be("getOverwriteFlagForModelScreenColors() is a deprecated function. Please use getOverrideFlagForModelScreenColors()."),this.getOverrideFlagForModelScreenColors()}getOverrideFlagForModelScreenColors(){return this._isOverriddenModelScreenColors}setOverwriteFlagForModelMultiplyColors(t){Be("setOverwriteFlagForModelMultiplyColors(value: boolean) is a deprecated function. Please use setOverrideFlagForModelMultiplyColors(value: boolean)."),this.setOverrideFlagForModelMultiplyColors(t)}setOverrideFlagForModelMultiplyColors(t){this._isOverriddenModelMultiplyColors=t}setOverwriteFlagForModelScreenColors(t){Be("setOverwriteFlagForModelScreenColors(value: boolean) is a deprecated function. Please use setOverrideFlagForModelScreenColors(value: boolean)."),this.setOverrideFlagForModelScreenColors(t)}setOverrideFlagForModelScreenColors(t){this._isOverriddenModelScreenColors=t}getOverwriteFlagForDrawableMultiplyColors(t){return Be("getOverwriteFlagForDrawableMultiplyColors(drawableindex: number) is a deprecated function. Please use getOverrideFlagForDrawableMultiplyColors(drawableindex: number)."),this.getOverrideFlagForDrawableMultiplyColors(t)}getOverrideFlagForDrawableMultiplyColors(t){return this._userMultiplyColors.at(t).isOverridden}getOverwriteFlagForDrawableScreenColors(t){return Be("getOverwriteFlagForDrawableScreenColors(drawableindex: number) is a deprecated function. Please use getOverrideFlagForDrawableScreenColors(drawableindex: number)."),this.getOverrideFlagForDrawableScreenColors(t)}getOverrideFlagForDrawableScreenColors(t){return this._userScreenColors.at(t).isOverridden}setOverwriteFlagForDrawableMultiplyColors(t,e){Be("setOverwriteFlagForDrawableMultiplyColors(drawableindex: number, value: boolean) is a deprecated function. Please use setOverrideFlagForDrawableMultiplyColors(drawableindex: number, value: boolean)."),this.setOverrideFlagForDrawableMultiplyColors(t,e)}setOverrideFlagForDrawableMultiplyColors(t,e){this._userMultiplyColors.at(t).isOverridden=e}setOverwriteFlagForDrawableScreenColors(t,e){Be("setOverwriteFlagForDrawableScreenColors(drawableindex: number, value: boolean) is a deprecated function. Please use setOverrideFlagForDrawableScreenColors(drawableindex: number, value: boolean)."),this.setOverrideFlagForDrawableScreenColors(t,e)}setOverrideFlagForDrawableScreenColors(t,e){this._userScreenColors.at(t).isOverridden=e}getOverwriteColorForPartMultiplyColors(t){return Be("getOverwriteColorForPartMultiplyColors(partIndex: number) is a deprecated function. Please use getOverrideColorForPartMultiplyColors(partIndex: number)."),this.getOverrideColorForPartMultiplyColors(t)}getOverrideColorForPartMultiplyColors(t){return this._userPartMultiplyColors.at(t).isOverridden}getOverwriteColorForPartScreenColors(t){return Be("getOverwriteColorForPartScreenColors(partIndex: number) is a deprecated function. Please use getOverrideColorForPartScreenColors(partIndex: number)."),this.getOverrideColorForPartScreenColors(t)}getOverrideColorForPartScreenColors(t){return this._userPartScreenColors.at(t).isOverridden}setOverwriteColorForPartColors(t,e,i,s){Be("setOverwriteColorForPartColors(partIndex: number, value: boolean, partColors: csmVector<PartColorData>, drawableColors: csmVector<DrawableColorData>) is a deprecated function. Please use setOverrideColorForPartColors(partIndex: number, value: boolean, partColors: csmVector<PartColorData>, drawableColors: csmVector<DrawableColorData>)."),this.setOverrideColorForPartColors(t,e,i,s)}setOverrideColorForPartColors(t,e,i,s){i.at(t).isOverridden=e;for(let r=0;r<this._partChildDrawables.at(t).getSize();++r){const a=this._partChildDrawables.at(t).at(r);s.at(a).isOverridden=e,e&&(s.at(a).color.r=i.at(t).color.r,s.at(a).color.g=i.at(t).color.g,s.at(a).color.b=i.at(t).color.b,s.at(a).color.a=i.at(t).color.a)}}setOverwriteColorForPartMultiplyColors(t,e){Be("setOverwriteColorForPartMultiplyColors(partIndex: number, value: boolean) is a deprecated function. Please use setOverrideColorForPartMultiplyColors(partIndex: number, value: boolean)."),this.setOverrideColorForPartMultiplyColors(t,e)}setOverrideColorForPartMultiplyColors(t,e){this._userPartMultiplyColors.at(t).isOverridden=e,this.setOverrideColorForPartColors(t,e,this._userPartMultiplyColors,this._userMultiplyColors)}setOverwriteColorForPartScreenColors(t,e){Be("setOverwriteColorForPartScreenColors(partIndex: number, value: boolean) is a deprecated function. Please use setOverrideColorForPartScreenColors(partIndex: number, value: boolean)."),this.setOverrideColorForPartScreenColors(t,e)}setOverrideColorForPartScreenColors(t,e){this._userPartScreenColors.at(t).isOverridden=e,this.setOverrideColorForPartColors(t,e,this._userPartScreenColors,this._userScreenColors)}getDrawableCulling(t){if(this.getOverrideFlagForModelCullings()||this.getOverrideFlagForDrawableCullings(t))return this._userCullings.at(t).isCulling;const e=this._model.drawables.constantFlags;return!Live2DCubismCore.Utils.hasIsDoubleSidedBit(e[t])}setDrawableCulling(t,e){this._userCullings.at(t).isCulling=e}getOverwriteFlagForModelCullings(){return Be("getOverwriteFlagForModelCullings() is a deprecated function. Please use getOverrideFlagForModelCullings()."),this.getOverrideFlagForModelCullings()}getOverrideFlagForModelCullings(){return this._isOverriddenCullings}setOverwriteFlagForModelCullings(t){Be("setOverwriteFlagForModelCullings(isOverriddenCullings: boolean) is a deprecated function. Please use setOverrideFlagForModelCullings(isOverriddenCullings: boolean)."),this.setOverrideFlagForModelCullings(t)}setOverrideFlagForModelCullings(t){this._isOverriddenCullings=t}getOverwriteFlagForDrawableCullings(t){return Be("getOverwriteFlagForDrawableCullings(drawableIndex: number) is a deprecated function. Please use getOverrideFlagForDrawableCullings(drawableIndex: number)."),this.getOverrideFlagForDrawableCullings(t)}getOverrideFlagForDrawableCullings(t){return this._userCullings.at(t).isOverridden}setOverwriteFlagForDrawableCullings(t,e){Be("setOverwriteFlagForDrawableCullings(drawableIndex: number, isOverriddenCullings: boolean) is a deprecated function. Please use setOverrideFlagForDrawableCullings(drawableIndex: number, isOverriddenCullings: boolean)."),this.setOverrideFlagForDrawableCullings(t,e)}setOverrideFlagForDrawableCullings(t,e){this._userCullings.at(t).isOverridden=e}getModelOapcity(){return this._modelOpacity}setModelOapcity(t){this._modelOpacity=t}getModel(){return this._model}getPartIndex(t){let e;const i=this._model.parts.count;for(e=0;e<i;++e)if(t==this._partIds.at(e))return e;return this._notExistPartId.isExist(t)?this._notExistPartId.getValue(t):(e=i+this._notExistPartId.getSize(),this._notExistPartId.setValue(t,e),this._notExistPartOpacities.appendKey(e),e)}getPartId(t){const e=this._model.parts.ids[t];return ti.getIdManager().getId(e)}getPartCount(){return this._model.parts.count}getPartParentPartIndices(){return this._model.parts.parentIndices}setPartOpacityByIndex(t,e){this._notExistPartOpacities.isExist(t)?this._notExistPartOpacities.setValue(t,e):(ve(0<=t&&t<this.getPartCount()),this._partOpacities[t]=e)}setPartOpacityById(t,e){const i=this.getPartIndex(t);i<0||this.setPartOpacityByIndex(i,e)}getPartOpacityByIndex(t){return this._notExistPartOpacities.isExist(t)?this._notExistPartOpacities.getValue(t):(ve(0<=t&&t<this.getPartCount()),this._partOpacities[t])}getPartOpacityById(t){const e=this.getPartIndex(t);return e<0?0:this.getPartOpacityByIndex(e)}getParameterIndex(t){let e;const i=this._model.parameters.count;for(e=0;e<i;++e)if(t==this._parameterIds.at(e))return e;return this._notExistParameterId.isExist(t)?this._notExistParameterId.getValue(t):(e=this._model.parameters.count+this._notExistParameterId.getSize(),this._notExistParameterId.setValue(t,e),this._notExistParameterValues.appendKey(e),e)}getParameterCount(){return this._model.parameters.count}getParameterType(t){return this._model.parameters.types[t]}getParameterMaximumValue(t){return this._model.parameters.maximumValues[t]}getParameterMinimumValue(t){return this._model.parameters.minimumValues[t]}getParameterDefaultValue(t){return this._model.parameters.defaultValues[t]}getParameterId(t){return ti.getIdManager().getId(this._model.parameters.ids[t])}getParameterValueByIndex(t){return this._notExistParameterValues.isExist(t)?this._notExistParameterValues.getValue(t):(ve(0<=t&&t<this.getParameterCount()),this._parameterValues[t])}getParameterValueById(t){const e=this.getParameterIndex(t);return this.getParameterValueByIndex(e)}setParameterValueByIndex(t,e,i=1){this._notExistParameterValues.isExist(t)?this._notExistParameterValues.setValue(t,1==i?e:this._notExistParameterValues.getValue(t)*(1-i)+e*i):(ve(0<=t&&t<this.getParameterCount()),e=this.isRepeat(t)?this.getParameterRepeatValue(t,e):this.getParameterClampValue(t,e),this._parameterValues[t]=1==i?e:this._parameterValues[t]=this._parameterValues[t]*(1-i)+e*i)}setParameterValueById(t,e,i=1){const s=this.getParameterIndex(t);this.setParameterValueByIndex(s,e,i)}addParameterValueByIndex(t,e,i=1){this.setParameterValueByIndex(t,this.getParameterValueByIndex(t)+e*i)}addParameterValueById(t,e,i=1){const s=this.getParameterIndex(t);this.addParameterValueByIndex(s,e,i)}isRepeat(t){if(this._notExistParameterValues.isExist(t))return!1;let e;return ve(0<=t&&t<this.getParameterCount()),e=this._isOverriddenParameterRepeat||this._userParameterRepeatDataList.at(t).isOverridden?this._userParameterRepeatDataList.at(t).isParameterRepeated:0!=this._model.parameters.repeats[t],e}getParameterRepeatValue(t,e){if(this._notExistParameterValues.isExist(t))return e;ve(0<=t&&t<this.getParameterCount());const i=this._model.parameters.maximumValues[t],s=this._model.parameters.minimumValues[t],r=i-s;if(i<e){const t=ni.mod(e-i,r);e=Number.isNaN(t)?i:s+t}if(e<s){const t=ni.mod(s-e,r);e=Number.isNaN(t)?s:i-t}return e}getParameterClampValue(t,e){if(this._notExistParameterValues.isExist(t))return e;ve(0<=t&&t<this.getParameterCount());const i=this._model.parameters.maximumValues[t],s=this._model.parameters.minimumValues[t];return ni.clamp(e,s,i)}getParameterRepeats(t){return 0!=this._model.parameters.repeats[t]}multiplyParameterValueById(t,e,i=1){const s=this.getParameterIndex(t);this.multiplyParameterValueByIndex(s,e,i)}multiplyParameterValueByIndex(t,e,i=1){this.setParameterValueByIndex(t,this.getParameterValueByIndex(t)*(1+(e-1)*i))}getDrawableIndex(t){const e=this._model.drawables.count;for(let i=0;i<e;++i)if(this._drawableIds.at(i)==t)return i;return-1}getDrawableCount(){return this._model.drawables.count}getDrawableId(t){const e=this._model.drawables.ids;return ti.getIdManager().getId(e[t])}getDrawableRenderOrders(){return this._model.drawables.renderOrders}getDrawableTextureIndices(t){return this.getDrawableTextureIndex(t)}getDrawableTextureIndex(t){return this._model.drawables.textureIndices[t]}getDrawableDynamicFlagVertexPositionsDidChange(t){const e=this._model.drawables.dynamicFlags;return Live2DCubismCore.Utils.hasVertexPositionsDidChangeBit(e[t])}getDrawableVertexIndexCount(t){return this._model.drawables.indexCounts[t]}getDrawableVertexCount(t){return this._model.drawables.vertexCounts[t]}getDrawableVertices(t){return this.getDrawableVertexPositions(t)}getDrawableVertexIndices(t){return this._model.drawables.indices[t]}getDrawableVertexPositions(t){return this._model.drawables.vertexPositions[t]}getDrawableVertexUvs(t){return this._model.drawables.vertexUvs[t]}getDrawableOpacity(t){return this._model.drawables.opacities[t]}getDrawableMultiplyColor(t){const e=this._model.drawables.multiplyColors,i=4*t,s=new Me;return s.r=e[i],s.g=e[i+1],s.b=e[i+2],s.a=e[i+3],s}getDrawableScreenColor(t){const e=this._model.drawables.screenColors,i=4*t,s=new Me;return s.r=e[i],s.g=e[i+1],s.b=e[i+2],s.a=e[i+3],s}getDrawableParentPartIndex(t){return this._model.drawables.parentPartIndices[t]}getDrawableBlendMode(t){const e=this._model.drawables.constantFlags;return Live2DCubismCore.Utils.hasBlendAdditiveBit(e[t])?xe.CubismBlendMode_Additive:Live2DCubismCore.Utils.hasBlendMultiplicativeBit(e[t])?xe.CubismBlendMode_Multiplicative:xe.CubismBlendMode_Normal}getDrawableInvertedMaskBit(t){const e=this._model.drawables.constantFlags;return Live2DCubismCore.Utils.hasIsInvertedMaskBit(e[t])}getDrawableMasks(){return this._model.drawables.masks}getDrawableMaskCounts(){return this._model.drawables.maskCounts}isUsingMasking(){for(let t=0;t<this._model.drawables.count;++t)if(!(this._model.drawables.maskCounts[t]<=0))return!0;return!1}getDrawableDynamicFlagIsVisible(t){const e=this._model.drawables.dynamicFlags;return Live2DCubismCore.Utils.hasIsVisibleBit(e[t])}getDrawableDynamicFlagVisibilityDidChange(t){const e=this._model.drawables.dynamicFlags;return Live2DCubismCore.Utils.hasVisibilityDidChangeBit(e[t])}getDrawableDynamicFlagOpacityDidChange(t){const e=this._model.drawables.dynamicFlags;return Live2DCubismCore.Utils.hasOpacityDidChangeBit(e[t])}getDrawableDynamicFlagRenderOrderDidChange(t){const e=this._model.drawables.dynamicFlags;return Live2DCubismCore.Utils.hasRenderOrderDidChangeBit(e[t])}getDrawableDynamicFlagBlendColorDidChange(t){const e=this._model.drawables.dynamicFlags;return Live2DCubismCore.Utils.hasBlendColorDidChangeBit(e[t])}loadParameters(){let t=this._model.parameters.count;const e=this._savedParameters.getSize();t>e&&(t=e);for(let i=0;i<t;++i)this._parameterValues[i]=this._savedParameters.at(i)}initialize(){ve(this._model),this._parameterValues=this._model.parameters.values,this._partOpacities=this._model.parts.opacities,this._parameterMaximumValues=this._model.parameters.maximumValues,this._parameterMinimumValues=this._model.parameters.minimumValues;{const t=this._model.parameters.ids,e=this._model.parameters.count;this._parameterIds.prepareCapacity(e),this._userParameterRepeatDataList.prepareCapacity(e);for(let i=0;i<e;++i)this._parameterIds.pushBack(ti.getIdManager().getId(t[i])),this._userParameterRepeatDataList.pushBack(new hr(!1,!1))}const t=this._model.parts.count;{const e=this._model.parts.ids;this._partIds.prepareCapacity(t);for(let i=0;i<t;++i)this._partIds.pushBack(ti.getIdManager().getId(e[i]));this._userPartMultiplyColors.prepareCapacity(t),this._userPartScreenColors.prepareCapacity(t),this._partChildDrawables.prepareCapacity(t)}{const e=this._model.drawables.ids,i=this._model.drawables.count;this._userMultiplyColors.prepareCapacity(i),this._userScreenColors.prepareCapacity(i),this._userCullings.prepareCapacity(i);const s=new cr(!1,!1);for(let r=0;r<t;++r){const t=new Me(1,1,1,1),e=new Me(0,0,0,1),s=new gr(!1,t),a=new gr(!1,e);this._userPartMultiplyColors.pushBack(s),this._userPartScreenColors.pushBack(a),this._partChildDrawables.pushBack(new se),this._partChildDrawables.at(r).prepareCapacity(i)}for(let t=0;t<i;++t){const i=new Me(1,1,1,1),r=new Me(0,0,0,1),a=new dr(!1,i),n=new dr(!1,r);this._drawableIds.pushBack(ti.getIdManager().getId(e[t])),this._userMultiplyColors.pushBack(a),this._userScreenColors.pushBack(n),this._userCullings.pushBack(s);const o=this.getDrawableParentPartIndex(t);o>=0&&this._partChildDrawables.at(o).pushBack(t)}}}constructor(t){this._model=t,this._parameterValues=null,this._parameterMaximumValues=null,this._parameterMinimumValues=null,this._partOpacities=null,this._savedParameters=new se,this._parameterIds=new se,this._drawableIds=new se,this._partIds=new se,this._isOverriddenParameterRepeat=!0,this._isOverriddenModelMultiplyColors=!1,this._isOverriddenModelScreenColors=!1,this._isOverriddenCullings=!1,this._modelOpacity=1,this._userParameterRepeatDataList=new se,this._userMultiplyColors=new se,this._userScreenColors=new se,this._userCullings=new se,this._userPartMultiplyColors=new se,this._userPartScreenColors=new se,this._partChildDrawables=new se,this._notExistPartId=new Ve,this._notExistParameterId=new Ve,this._notExistParameterValues=new Ve,this._notExistPartOpacities=new Ve}release(){this._model.release(),this._model=null}}(t=>{t.CubismModel=pr})(lr||(lr={}));class mr{static create(t,e){let i=null;if(e){if(!this.hasMocConsistency(t))return we("Inconsistent MOC3."),i}const s=Live2DCubismCore.Moc.fromArrayBuffer(t);return s&&(i=new mr(s),i._mocVersion=Live2DCubismCore.Version.csmGetMocVersion(s,t)),i}static delete(t){t._moc._release(),t._moc=null,t=null}createModel(){let t=null;const e=Live2DCubismCore.Model.fromMoc(this._moc);return e&&(t=new pr(e),t.initialize(),++this._modelCount),t}deleteModel(t){null!=t&&(t.release(),t=null,--this._modelCount)}constructor(t){this._moc=t,this._modelCount=0,this._mocVersion=0}release(){ve(0==this._modelCount),this._moc._release(),this._moc=null}getLatestMocVersion(){return Live2DCubismCore.Version.csmGetLatestMocVersion()}getMocVersion(){return this._mocVersion}static hasMocConsistency(t){return 1===Live2DCubismCore.Moc.prototype.hasMocConsistency(t)}}(t=>{t.CubismMoc=mr})(ur||(ur={}));var _r,fr=(t=>(t[t.CubismPhysicsTargetType_Parameter=0]="CubismPhysicsTargetType_Parameter",t))(fr||{}),yr=(t=>(t[t.CubismPhysicsSource_X=0]="CubismPhysicsSource_X",t[t.CubismPhysicsSource_Y=1]="CubismPhysicsSource_Y",t[t.CubismPhysicsSource_Angle=2]="CubismPhysicsSource_Angle",t))(yr||{});class xr{constructor(){this.gravity=new ri(0,0),this.wind=new ri(0,0)}}class Mr{}class Cr{}class Sr{constructor(){this.initialPosition=new ri(0,0),this.position=new ri(0,0),this.lastPosition=new ri(0,0),this.lastGravity=new ri(0,0),this.force=new ri(0,0),this.velocity=new ri(0,0)}}class vr{constructor(){this.normalizationPosition=new Cr,this.normalizationAngle=new Cr}}class br{constructor(){this.source=new Mr}}class Pr{constructor(){this.destination=new Mr,this.translationScale=new ri(0,0)}}class Br{constructor(){this.settings=new se,this.inputs=new se,this.outputs=new se,this.particles=new se,this.gravity=new ri(0,0),this.wind=new ri(0,0),this.fps=0}}(t=>{t.CubismPhysicsInput=br,t.CubismPhysicsNormalization=Cr,t.CubismPhysicsOutput=Pr,t.CubismPhysicsParameter=Mr,t.CubismPhysicsParticle=Sr,t.CubismPhysicsRig=Br,t.CubismPhysicsSource=yr,t.CubismPhysicsSubRig=vr,t.CubismPhysicsTargetType=fr,t.PhysicsJsonEffectiveForces=xr})(_r||(_r={}));const wr="Position",Ir="Angle",Fr="Type",Er="Meta",Lr="EffectiveForces",Vr="Gravity",Tr="Wind",Rr="PhysicsSettings",Dr="Normalization",Ar="Minimum",Or="Maximum",kr="Default",Nr="Reflect",Ur="Weight",zr="Input",jr="Output",Gr="Vertices";class Xr{constructor(t,e){this._json=ke.create(t,e)}release(){ke.delete(this._json)}getGravity(){const t=new ri(0,0);return t.x=this._json.getRoot().getValueByString(Er).getValueByString(Lr).getValueByString(Vr).getValueByString("X").toFloat(),t.y=this._json.getRoot().getValueByString(Er).getValueByString(Lr).getValueByString(Vr).getValueByString("Y").toFloat(),t}getWind(){const t=new ri(0,0);return t.x=this._json.getRoot().getValueByString(Er).getValueByString(Lr).getValueByString(Tr).getValueByString("X").toFloat(),t.y=this._json.getRoot().getValueByString(Er).getValueByString(Lr).getValueByString(Tr).getValueByString("Y").toFloat(),t}getFps(){return this._json.getRoot().getValueByString(Er).getValueByString("Fps").toFloat(0)}getSubRigCount(){return this._json.getRoot().getValueByString(Er).getValueByString("PhysicsSettingCount").toInt()}getTotalInputCount(){return this._json.getRoot().getValueByString(Er).getValueByString("TotalInputCount").toInt()}getTotalOutputCount(){return this._json.getRoot().getValueByString(Er).getValueByString("TotalOutputCount").toInt()}getVertexCount(){return this._json.getRoot().getValueByString(Er).getValueByString("VertexCount").toInt()}getNormalizationPositionMinimumValue(t){return this._json.getRoot().getValueByString(Rr).getValueByIndex(t).getValueByString(Dr).getValueByString(wr).getValueByString(Ar).toFloat()}getNormalizationPositionMaximumValue(t){return this._json.getRoot().getValueByString(Rr).getValueByIndex(t).getValueByString(Dr).getValueByString(wr).getValueByString(Or).toFloat()}getNormalizationPositionDefaultValue(t){return this._json.getRoot().getValueByString(Rr).getValueByIndex(t).getValueByString(Dr).getValueByString(wr).getValueByString(kr).toFloat()}getNormalizationAngleMinimumValue(t){return this._json.getRoot().getValueByString(Rr).getValueByIndex(t).getValueByString(Dr).getValueByString(Ir).getValueByString(Ar).toFloat()}getNormalizationAngleMaximumValue(t){return this._json.getRoot().getValueByString(Rr).getValueByIndex(t).getValueByString(Dr).getValueByString(Ir).getValueByString(Or).toFloat()}getNormalizationAngleDefaultValue(t){return this._json.getRoot().getValueByString(Rr).getValueByIndex(t).getValueByString(Dr).getValueByString(Ir).getValueByString(kr).toFloat()}getInputCount(t){return this._json.getRoot().getValueByString(Rr).getValueByIndex(t).getValueByString(zr).getVector().getSize()}getInputWeight(t,e){return this._json.getRoot().getValueByString(Rr).getValueByIndex(t).getValueByString(zr).getValueByIndex(e).getValueByString(Ur).toFloat()}getInputReflect(t,e){return this._json.getRoot().getValueByString(Rr).getValueByIndex(t).getValueByString(zr).getValueByIndex(e).getValueByString(Nr).toBoolean()}getInputType(t,e){return this._json.getRoot().getValueByString(Rr).getValueByIndex(t).getValueByString(zr).getValueByIndex(e).getValueByString(Fr).getRawString()}getInputSourceId(t,e){return ti.getIdManager().getId(this._json.getRoot().getValueByString(Rr).getValueByIndex(t).getValueByString(zr).getValueByIndex(e).getValueByString("Source").getValueByString("Id").getRawString())}getOutputCount(t){return this._json.getRoot().getValueByString(Rr).getValueByIndex(t).getValueByString(jr).getVector().getSize()}getOutputVertexIndex(t,e){return this._json.getRoot().getValueByString(Rr).getValueByIndex(t).getValueByString(jr).getValueByIndex(e).getValueByString("VertexIndex").toInt()}getOutputAngleScale(t,e){return this._json.getRoot().getValueByString(Rr).getValueByIndex(t).getValueByString(jr).getValueByIndex(e).getValueByString("Scale").toFloat()}getOutputWeight(t,e){return this._json.getRoot().getValueByString(Rr).getValueByIndex(t).getValueByString(jr).getValueByIndex(e).getValueByString(Ur).toFloat()}getOutputDestinationId(t,e){return ti.getIdManager().getId(this._json.getRoot().getValueByString(Rr).getValueByIndex(t).getValueByString(jr).getValueByIndex(e).getValueByString("Destination").getValueByString("Id").getRawString())}getOutputType(t,e){return this._json.getRoot().getValueByString(Rr).getValueByIndex(t).getValueByString(jr).getValueByIndex(e).getValueByString(Fr).getRawString()}getOutputReflect(t,e){return this._json.getRoot().getValueByString(Rr).getValueByIndex(t).getValueByString(jr).getValueByIndex(e).getValueByString(Nr).toBoolean()}getParticleCount(t){return this._json.getRoot().getValueByString(Rr).getValueByIndex(t).getValueByString(Gr).getVector().getSize()}getParticleMobility(t,e){return this._json.getRoot().getValueByString(Rr).getValueByIndex(t).getValueByString(Gr).getValueByIndex(e).getValueByString("Mobility").toFloat()}getParticleDelay(t,e){return this._json.getRoot().getValueByString(Rr).getValueByIndex(t).getValueByString(Gr).getValueByIndex(e).getValueByString("Delay").toFloat()}getParticleAcceleration(t,e){return this._json.getRoot().getValueByString(Rr).getValueByIndex(t).getValueByString(Gr).getValueByIndex(e).getValueByString("Acceleration").toFloat()}getParticleRadius(t,e){return this._json.getRoot().getValueByString(Rr).getValueByIndex(t).getValueByString(Gr).getValueByIndex(e).getValueByString("Radius").toFloat()}getParticlePosition(t,e){const i=new ri(0,0);return i.x=this._json.getRoot().getValueByString(Rr).getValueByIndex(t).getValueByString(Gr).getValueByIndex(e).getValueByString(wr).getValueByString("X").toFloat(),i.y=this._json.getRoot().getValueByString(Rr).getValueByIndex(t).getValueByString(Gr).getValueByIndex(e).getValueByString(wr).getValueByString("Y").toFloat(),i}}var Hr;(t=>{t.CubismPhysicsJson=Xr})(Hr||(Hr={}));const Yr="Angle";class qr{static create(t,e){const i=new qr;return i.parse(t,e),i._physicsRig.gravity.y=0,i}static delete(t){null!=t&&(t.release(),t=null)}parse(t,e){this._physicsRig=new Br;let i=new Xr(t,e);this._physicsRig.gravity=i.getGravity(),this._physicsRig.wind=i.getWind(),this._physicsRig.subRigCount=i.getSubRigCount(),this._physicsRig.fps=i.getFps(),this._physicsRig.settings.updateSize(this._physicsRig.subRigCount,vr,!0),this._physicsRig.inputs.updateSize(i.getTotalInputCount(),br,!0),this._physicsRig.outputs.updateSize(i.getTotalOutputCount(),Pr,!0),this._physicsRig.particles.updateSize(i.getVertexCount(),Sr,!0),this._currentRigOutputs.clear(),this._previousRigOutputs.clear();let s=0,r=0,a=0;for(let n=0;n<this._physicsRig.settings.getSize();++n){this._physicsRig.settings.at(n).normalizationPosition.minimum=i.getNormalizationPositionMinimumValue(n),this._physicsRig.settings.at(n).normalizationPosition.maximum=i.getNormalizationPositionMaximumValue(n),this._physicsRig.settings.at(n).normalizationPosition.defalut=i.getNormalizationPositionDefaultValue(n),this._physicsRig.settings.at(n).normalizationAngle.minimum=i.getNormalizationAngleMinimumValue(n),this._physicsRig.settings.at(n).normalizationAngle.maximum=i.getNormalizationAngleMaximumValue(n),this._physicsRig.settings.at(n).normalizationAngle.defalut=i.getNormalizationAngleDefaultValue(n),this._physicsRig.settings.at(n).inputCount=i.getInputCount(n),this._physicsRig.settings.at(n).baseInputIndex=s;for(let r=0;r<this._physicsRig.settings.at(n).inputCount;++r)this._physicsRig.inputs.at(s+r).sourceParameterIndex=-1,this._physicsRig.inputs.at(s+r).weight=i.getInputWeight(n,r),this._physicsRig.inputs.at(s+r).reflect=i.getInputReflect(n,r),"X"==i.getInputType(n,r)?(this._physicsRig.inputs.at(s+r).type=yr.CubismPhysicsSource_X,this._physicsRig.inputs.at(s+r).getNormalizedParameterValue=$r):"Y"==i.getInputType(n,r)?(this._physicsRig.inputs.at(s+r).type=yr.CubismPhysicsSource_Y,this._physicsRig.inputs.at(s+r).getNormalizedParameterValue=Zr):i.getInputType(n,r)==Yr&&(this._physicsRig.inputs.at(s+r).type=yr.CubismPhysicsSource_Angle,this._physicsRig.inputs.at(s+r).getNormalizedParameterValue=Kr),this._physicsRig.inputs.at(s+r).source.targetType=fr.CubismPhysicsTargetType_Parameter,this._physicsRig.inputs.at(s+r).source.id=i.getInputSourceId(n,r);s+=this._physicsRig.settings.at(n).inputCount,this._physicsRig.settings.at(n).outputCount=i.getOutputCount(n),this._physicsRig.settings.at(n).baseOutputIndex=r;const t=new Jr;t.outputs.resize(this._physicsRig.settings.at(n).outputCount);const e=new Jr;e.outputs.resize(this._physicsRig.settings.at(n).outputCount);for(let s=0;s<this._physicsRig.settings.at(n).outputCount;++s)t.outputs.set(s,0),e.outputs.set(s,0),this._physicsRig.outputs.at(r+s).destinationParameterIndex=-1,this._physicsRig.outputs.at(r+s).vertexIndex=i.getOutputVertexIndex(n,s),this._physicsRig.outputs.at(r+s).angleScale=i.getOutputAngleScale(n,s),this._physicsRig.outputs.at(r+s).weight=i.getOutputWeight(n,s),this._physicsRig.outputs.at(r+s).destination.targetType=fr.CubismPhysicsTargetType_Parameter,this._physicsRig.outputs.at(r+s).destination.id=i.getOutputDestinationId(n,s),"X"==i.getOutputType(n,s)?(this._physicsRig.outputs.at(r+s).type=yr.CubismPhysicsSource_X,this._physicsRig.outputs.at(r+s).getValue=Qr,this._physicsRig.outputs.at(r+s).getScale=sa):"Y"==i.getOutputType(n,s)?(this._physicsRig.outputs.at(r+s).type=yr.CubismPhysicsSource_Y,this._physicsRig.outputs.at(r+s).getValue=ta,this._physicsRig.outputs.at(r+s).getScale=ra):i.getOutputType(n,s)==Yr&&(this._physicsRig.outputs.at(r+s).type=yr.CubismPhysicsSource_Angle,this._physicsRig.outputs.at(r+s).getValue=ea,this._physicsRig.outputs.at(r+s).getScale=aa),this._physicsRig.outputs.at(r+s).reflect=i.getOutputReflect(n,s);this._currentRigOutputs.pushBack(t),this._previousRigOutputs.pushBack(e),r+=this._physicsRig.settings.at(n).outputCount,this._physicsRig.settings.at(n).particleCount=i.getParticleCount(n),this._physicsRig.settings.at(n).baseParticleIndex=a;for(let s=0;s<this._physicsRig.settings.at(n).particleCount;++s)this._physicsRig.particles.at(a+s).mobility=i.getParticleMobility(n,s),this._physicsRig.particles.at(a+s).delay=i.getParticleDelay(n,s),this._physicsRig.particles.at(a+s).acceleration=i.getParticleAcceleration(n,s),this._physicsRig.particles.at(a+s).radius=i.getParticleRadius(n,s),this._physicsRig.particles.at(a+s).position=i.getParticlePosition(n,s);a+=this._physicsRig.settings.at(n).particleCount}this.initialize(),i.release(),i=void 0,i=null}stabilization(t){var e,i,s,r;let a,n,o,l;const u=new ri;let h,d,g,c;const p=t.getModel().parameters.values,m=t.getModel().parameters.maximumValues,_=t.getModel().parameters.minimumValues,f=t.getModel().parameters.defaultValues;(null!=(i=null==(e=this._parameterCaches)?void 0:e.length)?i:0)<t.getParameterCount()&&(this._parameterCaches=new Float32Array(t.getParameterCount())),(null!=(r=null==(s=this._parameterInputCaches)?void 0:s.length)?r:0)<t.getParameterCount()&&(this._parameterInputCaches=new Float32Array(t.getParameterCount()));for(let y=0;y<t.getParameterCount();++y)this._parameterCaches[y]=p[y],this._parameterInputCaches[y]=p[y];for(let y=0;y<this._physicsRig.subRigCount;++y){a={angle:0},u.x=0,u.y=0,h=this._physicsRig.settings.at(y),d=this._physicsRig.inputs.get(h.baseInputIndex),g=this._physicsRig.outputs.get(h.baseOutputIndex),c=this._physicsRig.particles.get(h.baseParticleIndex);for(let e=0;e<h.inputCount;++e)n=d[e].weight/100,-1==d[e].sourceParameterIndex&&(d[e].sourceParameterIndex=t.getParameterIndex(d[e].source.id)),d[e].getNormalizedParameterValue(u,a,p[d[e].sourceParameterIndex],_[d[e].sourceParameterIndex],m[d[e].sourceParameterIndex],f[d[e].sourceParameterIndex],h.normalizationPosition,h.normalizationAngle,d[e].reflect,n),this._parameterCaches[d[e].sourceParameterIndex]=p[d[e].sourceParameterIndex];o=ni.degreesToRadian(-a.angle),u.x=u.x*ni.cos(o)-u.y*ni.sin(o),u.y=u.x*ni.sin(o)+u.y*ni.cos(o),oa(c,h.particleCount,u,a.angle,this._options.wind,.001*h.normalizationPosition.maximum);for(let e=0;e<h.outputCount;++e){const i=g[e].vertexIndex;if(-1==g[e].destinationParameterIndex&&(g[e].destinationParameterIndex=t.getParameterIndex(g[e].destination.id)),i<1||i>=h.particleCount)continue;let s=new ri;s=c[i].position.substract(c[i-1].position),l=g[e].getValue(s,c,i,g[e].reflect,this._options.gravity),this._currentRigOutputs.at(y).outputs.set(e,l),this._previousRigOutputs.at(y).outputs.set(e,l);const r=g[e].destinationParameterIndex,a=!Float32Array.prototype.slice&&"subarray"in Float32Array.prototype?JSON.parse(JSON.stringify(p.subarray(r))):p.slice(r);la(a,_[r],m[r],l,g[e]);for(let t=r,e=0;t<this._parameterCaches.length;t++,e++)p[t]=this._parameterCaches[t]=a[e]}}}evaluate(t,e){var i,s,r,a;let n,o,l,u;const h=new ri;let d,g,c,p;if(0>=e)return;const m=t.getModel().parameters.values,_=t.getModel().parameters.maximumValues,f=t.getModel().parameters.minimumValues,y=t.getModel().parameters.defaultValues;let x;if(this._currentRemainTime+=e,this._currentRemainTime>5&&(this._currentRemainTime=0),(null!=(s=null==(i=this._parameterCaches)?void 0:i.length)?s:0)<t.getParameterCount()&&(this._parameterCaches=new Float32Array(t.getParameterCount())),(null!=(a=null==(r=this._parameterInputCaches)?void 0:r.length)?a:0)<t.getParameterCount()){this._parameterInputCaches=new Float32Array(t.getParameterCount());for(let e=0;e<t.getParameterCount();++e)this._parameterInputCaches[e]=m[e]}for(x=this._physicsRig.fps>0?1/this._physicsRig.fps:e;this._currentRemainTime>=x;){for(let t=0;t<this._physicsRig.subRigCount;++t){d=this._physicsRig.settings.at(t),c=this._physicsRig.outputs.get(d.baseOutputIndex);for(let e=0;e<d.outputCount;++e)this._previousRigOutputs.at(t).outputs.set(e,this._currentRigOutputs.at(t).outputs.at(e))}const e=x/this._currentRemainTime;for(let i=0;i<t.getParameterCount();++i)this._parameterCaches[i]=this._parameterInputCaches[i]*(1-e)+m[i]*e,this._parameterInputCaches[i]=this._parameterCaches[i];for(let i=0;i<this._physicsRig.subRigCount;++i){n={angle:0},h.x=0,h.y=0,d=this._physicsRig.settings.at(i),g=this._physicsRig.inputs.get(d.baseInputIndex),c=this._physicsRig.outputs.get(d.baseOutputIndex),p=this._physicsRig.particles.get(d.baseParticleIndex);for(let e=0;e<d.inputCount;++e)o=g[e].weight/100,-1==g[e].sourceParameterIndex&&(g[e].sourceParameterIndex=t.getParameterIndex(g[e].source.id)),g[e].getNormalizedParameterValue(h,n,this._parameterCaches[g[e].sourceParameterIndex],f[g[e].sourceParameterIndex],_[g[e].sourceParameterIndex],y[g[e].sourceParameterIndex],d.normalizationPosition,d.normalizationAngle,g[e].reflect,o);l=ni.degreesToRadian(-n.angle),h.x=h.x*ni.cos(l)-h.y*ni.sin(l),h.y=h.x*ni.sin(l)+h.y*ni.cos(l),na(p,d.particleCount,h,n.angle,this._options.wind,.001*d.normalizationPosition.maximum,x,5);for(let e=0;e<d.outputCount;++e){const s=c[e].vertexIndex;if(-1==c[e].destinationParameterIndex&&(c[e].destinationParameterIndex=t.getParameterIndex(c[e].destination.id)),s<1||s>=d.particleCount)continue;const r=new ri;r.x=p[s].position.x-p[s-1].position.x,r.y=p[s].position.y-p[s-1].position.y,u=c[e].getValue(r,p,s,c[e].reflect,this._options.gravity),this._currentRigOutputs.at(i).outputs.set(e,u);const a=c[e].destinationParameterIndex,n=!Float32Array.prototype.slice&&"subarray"in Float32Array.prototype?JSON.parse(JSON.stringify(this._parameterCaches.subarray(a))):this._parameterCaches.slice(a);la(n,f[a],_[a],u,c[e]);for(let t=a,e=0;t<this._parameterCaches.length;t++,e++)this._parameterCaches[t]=n[e]}}this._currentRemainTime-=x}const M=this._currentRemainTime/x;this.interpolate(t,M)}interpolate(t,e){let i,s;const r=t.getModel().parameters.values,a=t.getModel().parameters.maximumValues,n=t.getModel().parameters.minimumValues;for(let o=0;o<this._physicsRig.subRigCount;++o){s=this._physicsRig.settings.at(o),i=this._physicsRig.outputs.get(s.baseOutputIndex);for(let t=0;t<s.outputCount;++t){if(-1==i[t].destinationParameterIndex)continue;const s=i[t].destinationParameterIndex,l=!Float32Array.prototype.slice&&"subarray"in Float32Array.prototype?JSON.parse(JSON.stringify(r.subarray(s))):r.slice(s);la(l,n[s],a[s],this._previousRigOutputs.at(o).outputs.at(t)*(1-e)+this._currentRigOutputs.at(o).outputs.at(t)*e,i[t]);for(let t=s,e=0;t<r.length;t++,e++)r[t]=l[e]}}}setOptions(t){this._options=t}getOption(){return this._options}constructor(){this._physicsRig=null,this._options=new Wr,this._options.gravity.y=-1,this._options.gravity.x=0,this._options.wind.x=0,this._options.wind.y=0,this._currentRigOutputs=new se,this._previousRigOutputs=new se,this._currentRemainTime=0,this._parameterCaches=null,this._parameterInputCaches=null}release(){this._physicsRig=void 0,this._physicsRig=null}initialize(){let t,e,i;for(let s=0;s<this._physicsRig.subRigCount;++s){e=this._physicsRig.settings.at(s),t=this._physicsRig.particles.get(e.baseParticleIndex),t[0].initialPosition=new ri(0,0),t[0].lastPosition=new ri(t[0].initialPosition.x,t[0].initialPosition.y),t[0].lastGravity=new ri(0,-1),t[0].lastGravity.y*=-1,t[0].velocity=new ri(0,0),t[0].force=new ri(0,0);for(let s=1;s<e.particleCount;++s)i=new ri(0,0),i.y=t[s].radius,t[s].initialPosition=new ri(t[s-1].initialPosition.x+i.x,t[s-1].initialPosition.y+i.y),t[s].position=new ri(t[s].initialPosition.x,t[s].initialPosition.y),t[s].lastPosition=new ri(t[s].initialPosition.x,t[s].initialPosition.y),t[s].lastGravity=new ri(0,-1),t[s].lastGravity.y*=-1,t[s].velocity=new ri(0,0),t[s].force=new ri(0,0)}}}class Wr{constructor(){this.gravity=new ri(0,0),this.wind=new ri(0,0)}}class Jr{constructor(){this.outputs=new se(0)}}function $r(t,e,i,s,r,a,n,o,l,u){t.x+=ua(i,s,r,a,n.minimum,n.maximum,n.defalut,l)*u}function Zr(t,e,i,s,r,a,n,o,l,u){t.y+=ua(i,s,r,a,n.minimum,n.maximum,n.defalut,l)*u}function Kr(t,e,i,s,r,a,n,o,l,u){e.angle+=ua(i,s,r,a,o.minimum,o.maximum,o.defalut,l)*u}function Qr(t,e,i,s,r){let a=t.x;return s&&(a*=-1),a}function ta(t,e,i,s,r){let a=t.y;return s&&(a*=-1),a}function ea(t,e,i,s,r){let a;return r=i>=2?e[i-1].position.substract(e[i-2].position):r.multiplyByScaler(-1),a=ni.directionToRadian(r,t),s&&(a*=-1),a}function ia(t,e){return ni.min(t,e)+function(t,e){const i=ni.max(t,e),s=ni.min(t,e);return ni.abs(i-s)}(t,e)/2}function sa(t,e){return JSON.parse(JSON.stringify(t.x))}function ra(t,e){return JSON.parse(JSON.stringify(t.y))}function aa(t,e){return JSON.parse(JSON.stringify(e))}function na(t,e,i,s,r,a,n,o){let l,u,h=new ri(0,0),d=new ri(0,0),g=new ri(0,0),c=new ri(0,0);t[0].position=new ri(i.x,i.y);const p=ni.degreesToRadian(s),m=ni.radianToDirection(p);m.normalize();for(let _=1;_<e;++_)t[_].force=m.multiplyByScaler(t[_].acceleration).add(r),t[_].lastPosition=new ri(t[_].position.x,t[_].position.y),l=t[_].delay*n*30,h=t[_].position.substract(t[_-1].position),u=ni.directionToRadian(t[_].lastGravity,m)/o,h.x=ni.cos(u)*h.x-h.y*ni.sin(u),h.y=ni.sin(u)*h.x+h.y*ni.cos(u),t[_].position=t[_-1].position.add(h),d=t[_].velocity.multiplyByScaler(l),g=t[_].force.multiplyByScaler(l).multiplyByScaler(l),t[_].position=t[_].position.add(d).add(g),c=t[_].position.substract(t[_-1].position),c.normalize(),t[_].position=t[_-1].position.add(c.multiplyByScaler(t[_].radius)),ni.abs(t[_].position.x)<a&&(t[_].position.x=0),0!=l&&(t[_].velocity=t[_].position.substract(t[_].lastPosition),t[_].velocity=t[_].velocity.divisionByScalar(l),t[_].velocity=t[_].velocity.multiplyByScaler(t[_].mobility)),t[_].force=new ri(0,0),t[_].lastGravity=new ri(m.x,m.y)}function oa(t,e,i,s,r,a){let n=new ri(0,0);t[0].position=new ri(i.x,i.y);const o=ni.degreesToRadian(s),l=ni.radianToDirection(o);l.normalize();for(let u=1;u<e;++u)t[u].force=l.multiplyByScaler(t[u].acceleration).add(r),t[u].lastPosition=new ri(t[u].position.x,t[u].position.y),t[u].velocity=new ri(0,0),n=t[u].force,n.normalize(),n=n.multiplyByScaler(t[u].radius),t[u].position=t[u-1].position.add(n),ni.abs(t[u].position.x)<a&&(t[u].position.x=0),t[u].force=new ri(0,0),t[u].lastGravity=new ri(l.x,l.y)}function la(t,e,i,s,r){let a;a=s*r.getScale(r.translationScale,r.angleScale),a<e?(a<r.valueBelowMinimum&&(r.valueBelowMinimum=a),a=e):a>i&&(a>r.valueExceededMaximum&&(r.valueExceededMaximum=a),a=i);const n=r.weight/100;n>=1||(a=t[0]*(1-n)+a*n),t[0]=a}function ua(t,e,i,s,r,a,n,o){let l=0;const u=ni.max(i,e);u<t&&(t=u);const h=ni.min(i,e);h>t&&(t=h);const d=ni.min(r,a),g=ni.max(r,a),c=n,p=ia(h,u),m=t-p;switch(function(t){let e=0;return t>0?e=1:t<0&&(e=-1),e}(m)){case 1:{const t=u-p;0!=t&&(l=m*((g-c)/t),l+=c);break}case-1:{const t=h-p;0!=t&&(l=m*((d-c)/t),l+=c);break}case 0:l=c}return o?l:-1*l}var ha;function da(){var t;null==(t=this.__moc)||t.release()}(t=>{t.CubismPhysics=qr,t.Options=Wr})(ha||(ha={})),Pt.registerRuntime({version:4,ready:er,test:t=>t instanceof $s||$s.isValidJSON(t),isValidMoc(t){if(t.byteLength<4)return!1;const e=new Int8Array(t,0,4);return"MOC3"===String.fromCharCode(...e)},createModelSettings:t=>new $s(t),createCoreModel(t,e){const i=mr.create(t,!!(null==e?void 0:e.checkMocConsistency));try{const t=i.createModel();return t.__moc=i,t}catch(s){try{i.release()}catch(r){p.warn("CubismFactory","Failed to release moc after core model creation failed.",r)}throw s}},createInternalModel(t,e,i){const s=new Gs(t,e,i),r=t;return r.__moc&&(s.__moc=r.__moc,delete r.__moc,s.once("destroy",da)),s},createPhysics(t,e){if(!(e instanceof ArrayBuffer))throw new TypeError("Cubism physics data must be an ArrayBuffer.");return qr.create(e,e.byteLength)},createPose(t,e){if(!(e instanceof ArrayBuffer))throw new TypeError("Cubism pose data must be an ArrayBuffer.");return ar.create(e,e.byteLength)}}),t.CubismExpressionManager=Si,t.CubismInternalModel=Gs,t.CubismLegacyExpressionManager=Gt,t.CubismLegacyInternalModel=$t,t.CubismLegacyModelSettings=ut,t.CubismLegacyMotionManager=Ht,t.CubismLegacyParallelMotionManager=qt,t.CubismModelSettings=$s,t.CubismMotionManager=Zi,t.CubismParallelMotionManager=ss,t.ExpressionManager=P,t.FileLoader=vt,t.FocusController=I,t.InternalModel=st,t.LOGICAL_HEIGHT=2,t.LOGICAL_WIDTH=2,t.Live2DExpression=jt,t.Live2DEyeBlink=Wt,t.Live2DFactory=Pt,t.Live2DLoader=lt,t.Live2DModel=Ut,t.Live2DPhysics=Qt,t.Live2DPlugin=Nt,t.Live2DPose=ee,t.Live2DTransform=Lt,t.MBToByte=f,t.ModelSettings=F,t.MotionManager=G,t.MotionPreloadStrategy=j,t.MotionPriority=E,t.MotionState=L,t.SoundManager=z,t.VERSION="1.3.3",t.VOLUME=T,t.XHRLoader=nt,t.applyMixins=M,t.clamp=m,t.config=c,t.configureCubismSDK=tr,t.copyArray=x,t.copyProperty=y,t.cubismReady=er,t.folderName=C,t.logger=p,t.normalizeHitAreaDefs=et,t.rand=_,t.reconfigureCubismSDK=function(t={}){tr(t),ti.isInitialized()&&ti.dispose(),ti.isStarted()&&ti.cleanUp(),ir(void 0,t.memorySizeMB)},t.remove=S,t.resolveURL=b,t.startUpCubism=ir,Object.defineProperty(t,Symbol.toStringTag,{value:"Module"})});