untitled-pixi-live2d-engine 1.3.3 → 1.3.5

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.
@@ -105,7 +105,7 @@ const config = {
105
105
  preserveExpressionOnMotion: true,
106
106
  cubism: CubismFrameworkConfig
107
107
  };
108
- const VERSION = "1.3.3";
108
+ const VERSION = "1.3.5";
109
109
  const logger = {
110
110
  log(tag, ...messages) {
111
111
  if (config.logLevel <= config.LOG_LEVEL_VERBOSE) {
@@ -2762,13 +2762,29 @@ class Live2DPipe {
2762
2762
  constructor(renderer) {
2763
2763
  this.renderer = renderer;
2764
2764
  }
2765
+ addPrepare(prepare, instructionSet) {
2766
+ var _a, _b;
2767
+ const renderPipes = this.renderer.renderPipes;
2768
+ (_b = (_a = renderPipes.batch) == null ? void 0 : _a.break) == null ? void 0 : _b.call(_a, instructionSet);
2769
+ instructionSet.add({
2770
+ renderPipeId: "live2d",
2771
+ action: "prepare",
2772
+ canBundle: false,
2773
+ prepare
2774
+ });
2775
+ }
2765
2776
  addRenderable(model, instructionSet) {
2766
2777
  var _a, _b;
2767
2778
  const renderPipes = this.renderer.renderPipes;
2768
2779
  (_b = (_a = renderPipes.batch) == null ? void 0 : _a.break) == null ? void 0 : _b.call(_a, instructionSet);
2769
2780
  instructionSet.add(model);
2770
2781
  }
2771
- execute(model) {
2782
+ execute(instruction) {
2783
+ if (!(instruction instanceof Live2DModel)) {
2784
+ instruction.prepare();
2785
+ return;
2786
+ }
2787
+ const model = instruction;
2772
2788
  if (!model.visible || model.alpha <= 0) {
2773
2789
  return;
2774
2790
  }
@@ -2981,7 +2997,7 @@ class Live2DModel extends Container {
2981
2997
  this.internalModel.updateTransform(internalTransform);
2982
2998
  this.internalModel.draw(renderer.gl);
2983
2999
  if (this._boundsRetryAfterDraw) {
2984
- this.updateDrawableBounds();
3000
+ this.updateDrawableBounds(true);
2985
3001
  }
2986
3002
  renderer.state.resetState();
2987
3003
  renderer.texture.resetState();
@@ -3083,7 +3099,7 @@ class Live2DModel extends Container {
3083
3099
  }
3084
3100
  return this._bounds;
3085
3101
  }
3086
- updateDrawableBounds() {
3102
+ updateDrawableBounds(applyAnchor = false) {
3087
3103
  if (!this.internalModel) {
3088
3104
  this._bounds.set(0, 0, 0, 0);
3089
3105
  this._boundsDirty = false;
@@ -3127,10 +3143,26 @@ class Live2DModel extends Container {
3127
3143
  }
3128
3144
  this._boundsDirty = false;
3129
3145
  this._didViewChangeTick++;
3130
- if (this.anchorMode === "drawable") {
3146
+ if (applyAnchor && this.anchorMode === "drawable") {
3131
3147
  this.onAnchorChange();
3132
3148
  }
3133
3149
  }
3150
+ /**
3151
+ * Updates the model and its drawable bounds before Pixi calculates filter areas.
3152
+ * Filter pipes collect their framebuffer bounds before the Live2D render pipe runs,
3153
+ * so waiting until `renderLive2D()` is too late for animated vertices.
3154
+ */
3155
+ prepareForRender() {
3156
+ if (!this.internalModel) {
3157
+ return;
3158
+ }
3159
+ const frameDelta = this.deltaTime;
3160
+ this.deltaTime = 0;
3161
+ if (frameDelta) {
3162
+ this.internalModel.update(frameDelta, this.elapsedTime);
3163
+ }
3164
+ this.updateDrawableBounds();
3165
+ }
3134
3166
  generateUID() {
3135
3167
  return ++this.currentGlId;
3136
3168
  }
@@ -3165,6 +3197,9 @@ class Live2DModel extends Container {
3165
3197
  };
3166
3198
  const effects = this.effects;
3167
3199
  if (effects) {
3200
+ if (effects.length) {
3201
+ renderPipes.live2d.addPrepare(() => this.prepareForRender(), instructionSet);
3202
+ }
3168
3203
  for (let i = 0; i < effects.length; i++) {
3169
3204
  const effect = effects[i];
3170
3205
  const filters = effect.filters;
@@ -3195,7 +3230,7 @@ class Live2DModel extends Container {
3195
3230
  */
3196
3231
  initializeOnModelLoad(_options) {
3197
3232
  this.tag = `Live2DModel(${this.internalModel.settings.name})`;
3198
- this.updateDrawableBounds();
3233
+ this.updateDrawableBounds(true);
3199
3234
  if (this.anchorMode === "canvas") {
3200
3235
  this.onAnchorChange();
3201
3236
  }
@@ -108,7 +108,7 @@ var __async = (__this, __arguments, generator) => {
108
108
  preserveExpressionOnMotion: true,
109
109
  cubism: CubismFrameworkConfig
110
110
  };
111
- const VERSION = "1.3.3";
111
+ const VERSION = "1.3.5";
112
112
  const logger = {
113
113
  log(tag, ...messages) {
114
114
  if (config.logLevel <= config.LOG_LEVEL_VERBOSE) {
@@ -2765,13 +2765,29 @@ var __async = (__this, __arguments, generator) => {
2765
2765
  constructor(renderer) {
2766
2766
  this.renderer = renderer;
2767
2767
  }
2768
+ addPrepare(prepare, instructionSet) {
2769
+ var _a, _b;
2770
+ const renderPipes = this.renderer.renderPipes;
2771
+ (_b = (_a = renderPipes.batch) == null ? void 0 : _a.break) == null ? void 0 : _b.call(_a, instructionSet);
2772
+ instructionSet.add({
2773
+ renderPipeId: "live2d",
2774
+ action: "prepare",
2775
+ canBundle: false,
2776
+ prepare
2777
+ });
2778
+ }
2768
2779
  addRenderable(model, instructionSet) {
2769
2780
  var _a, _b;
2770
2781
  const renderPipes = this.renderer.renderPipes;
2771
2782
  (_b = (_a = renderPipes.batch) == null ? void 0 : _a.break) == null ? void 0 : _b.call(_a, instructionSet);
2772
2783
  instructionSet.add(model);
2773
2784
  }
2774
- execute(model) {
2785
+ execute(instruction) {
2786
+ if (!(instruction instanceof Live2DModel)) {
2787
+ instruction.prepare();
2788
+ return;
2789
+ }
2790
+ const model = instruction;
2775
2791
  if (!model.visible || model.alpha <= 0) {
2776
2792
  return;
2777
2793
  }
@@ -2984,7 +3000,7 @@ var __async = (__this, __arguments, generator) => {
2984
3000
  this.internalModel.updateTransform(internalTransform);
2985
3001
  this.internalModel.draw(renderer.gl);
2986
3002
  if (this._boundsRetryAfterDraw) {
2987
- this.updateDrawableBounds();
3003
+ this.updateDrawableBounds(true);
2988
3004
  }
2989
3005
  renderer.state.resetState();
2990
3006
  renderer.texture.resetState();
@@ -3086,7 +3102,7 @@ var __async = (__this, __arguments, generator) => {
3086
3102
  }
3087
3103
  return this._bounds;
3088
3104
  }
3089
- updateDrawableBounds() {
3105
+ updateDrawableBounds(applyAnchor = false) {
3090
3106
  if (!this.internalModel) {
3091
3107
  this._bounds.set(0, 0, 0, 0);
3092
3108
  this._boundsDirty = false;
@@ -3130,10 +3146,26 @@ var __async = (__this, __arguments, generator) => {
3130
3146
  }
3131
3147
  this._boundsDirty = false;
3132
3148
  this._didViewChangeTick++;
3133
- if (this.anchorMode === "drawable") {
3149
+ if (applyAnchor && this.anchorMode === "drawable") {
3134
3150
  this.onAnchorChange();
3135
3151
  }
3136
3152
  }
3153
+ /**
3154
+ * Updates the model and its drawable bounds before Pixi calculates filter areas.
3155
+ * Filter pipes collect their framebuffer bounds before the Live2D render pipe runs,
3156
+ * so waiting until `renderLive2D()` is too late for animated vertices.
3157
+ */
3158
+ prepareForRender() {
3159
+ if (!this.internalModel) {
3160
+ return;
3161
+ }
3162
+ const frameDelta = this.deltaTime;
3163
+ this.deltaTime = 0;
3164
+ if (frameDelta) {
3165
+ this.internalModel.update(frameDelta, this.elapsedTime);
3166
+ }
3167
+ this.updateDrawableBounds();
3168
+ }
3137
3169
  generateUID() {
3138
3170
  return ++this.currentGlId;
3139
3171
  }
@@ -3168,6 +3200,9 @@ var __async = (__this, __arguments, generator) => {
3168
3200
  };
3169
3201
  const effects = this.effects;
3170
3202
  if (effects) {
3203
+ if (effects.length) {
3204
+ renderPipes.live2d.addPrepare(() => this.prepareForRender(), instructionSet);
3205
+ }
3171
3206
  for (let i = 0; i < effects.length; i++) {
3172
3207
  const effect = effects[i];
3173
3208
  const filters = effect.filters;
@@ -3198,7 +3233,7 @@ var __async = (__this, __arguments, generator) => {
3198
3233
  */
3199
3234
  initializeOnModelLoad(_options) {
3200
3235
  this.tag = `Live2DModel(${this.internalModel.settings.name})`;
3201
- this.updateDrawableBounds();
3236
+ this.updateDrawableBounds(true);
3202
3237
  if (this.anchorMode === "canvas") {
3203
3238
  this.onAnchorChange();
3204
3239
  }
@@ -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,o=Object.getOwnPropertySymbols,n=Object.prototype.hasOwnProperty,a=Object.prototype.propertyIsEnumerable,l=Math.pow,h=(t,e,s)=>e in t?i(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,d=(t,e)=>{for(var i in e||(e={}))n.call(e,i)&&h(t,i,e[i]);if(o)for(var i of o(e))a.call(e,i)&&h(t,i,e[i]);return t},u=(t,e,i)=>h(t,"symbol"!=typeof e?e+"":e,i),c=(t,e,i)=>new Promise((s,r)=>{var o=t=>{try{a(i.next(t))}catch(e){r(e)}},n=t=>{try{a(i.throw(t))}catch(e){r(e)}},a=t=>t.done?s(t.value):Promise.resolve(t.value).then(o,n);a((i=i.apply(t,e)).next())});const p={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"}))},g={log(t,...e){p.logLevel<=p.LOG_LEVEL_VERBOSE&&console.log(`[${t}]`,...e)},warn(t,...e){p.logLevel<=p.LOG_LEVEL_WARNING&&console.warn(`[${t}]`,...e)},error(t,...e){p.logLevel<=p.LOG_LEVEL_ERROR&&console.error(`[${t}]`,...e)}};function m(t,e,i){return t<e?e:t>i?i:t}function f(t,e){return Math.random()*(e-t)+t}function M(t,e,i,s,r){const o=e[s];null!==o&&typeof o===t&&(i[r]=o)}function y(t,e,i,s,r){const o=e[s];Array.isArray(o)&&(i[r]=o.filter(e=>null!==e&&typeof e===t))}function x(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 v(t,e){const i=t.indexOf(e);-1!==i&&t.splice(i,1)}const b=/^[a-zA-Z][a-zA-Z0-9+.-]*:/;function E(t,e){if(!e)return t;if(b.test(e))return e;if(e.startsWith("/"))return b.test(t)?new URL(e,t).toString():e;if(b.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 o=r.pathname+r.search+r.hash;return!t.startsWith("/")&&o.startsWith("/")&&(o=o.slice(1)),o}class w extends e.EventEmitter{constructor(t,e){super(),u(this,"expressionDataType","json"),u(this,"tag"),u(this,"settings"),u(this,"expressions",[]),u(this,"defaultExpression"),u(this,"currentExpression"),u(this,"reserveExpressionIndex",-1),u(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 c(this,null,function*(){if(!this.definitions[t])return void g.warn(this.tag,`Undefined expression at [${t}]`);if(null===this.expressions[t])return void g.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 c(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 c(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 P=40/7.5,L=1/150;class I{constructor(){u(this,"targetX",0),u(this,"targetY",0),u(this,"x",0),u(this,"y",0),u(this,"vx",0),u(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=P/(1e3/t);let o=r*(e/s)-this.vx,n=r*(i/s)-this.vy;const a=Math.sqrt(l(o,2)+l(n,2)),h=r*L*t;a>h&&(o*=h/a,n*=h/a),this.vx+=o,this.vy+=n;const d=Math.sqrt(l(this.vx,2)+l(this.vy,2)),u=.5*(Math.sqrt(l(h,2)+8*h*s)-h);d>u&&(this.vx*=u/d,this.vy*=u/d),this.x+=this.vx,this.y+=this.vy}}class _{constructor(t){u(this,"json"),u(this,"name"),u(this,"url"),u(this,"pose"),u(this,"physics"),this.json=t,this.url=t.url,this.name=x(this.url)}normalizeName(){this.name&&"name"!==this.name.toLowerCase()||(this.name=x(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 E(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 F=(t=>(t[t.NONE=0]="NONE",t[t.IDLE=1]="IDLE",t[t.NORMAL=2]="NORMAL",t[t.FORCE=3]="FORCE",t))(F||{});class A{constructor(){u(this,"tag"),u(this,"debug",!1),u(this,"currentPriority",0),u(this,"reservePriority",0),u(this,"currentGroup"),u(this,"currentIndex"),u(this,"reservedGroup"),u(this,"reservedIndex"),u(this,"reservedIdleGroup"),u(this,"reservedIdleIndex")}reserve(t,e,i){if(i<=0)return g.log(this.tag,"Cannot start a motion with MotionPriority.NONE."),!1;if(t===this.currentGroup&&e===this.currentIndex)return g.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 g.log(this.tag,"Motion is already reserved.",this.dump(t,e)),!1;if(1===i){if(0!==this.currentPriority)return g.log(this.tag,"Cannot start idle motion because another motion is playing.",this.dump(t,e)),!1;if(void 0!==this.reservedIdleGroup)return g.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 g.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 g.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 g.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 g.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!p.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 O="SoundManager",D=.5;let T,S=0;const R=new WeakSet;function C(t){if(!R.has(t)){try{t.disableAutoPause=!0}catch(e){g.warn(O,"Failed to disable @pixi/sound auto pause.",e)}R.add(t)}return t}function k(){return c(this,null,function*(){const t="undefined"!=typeof PIXI?null==PIXI?void 0:PIXI.sound:void 0;return t?C(t):(null!=T||(T=import("@pixi/sound").then(({sound:t})=>C(t)).catch(t=>(g.warn(O,"@pixi/sound is not available. Load pixi-sound.js before using motion sounds, speak(), or lip sync.",t),null))),T)})}function N(t,e){try{t.remove(e)}catch(i){g.warn(O,`Failed to remove sound "${e}".`,i)}}function G(t){const e=t.media.buffer;if(!e||"object"!=typeof e)return;return"function"==typeof e.getChannelData?e:void 0}class j{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 c(this,null,function*(){let i,s=null;try{if(s=yield k(),!s)throw new Error("@pixi/sound is not available");i="live2d-sound-"+S++;const e=s,r=i,o=new Promise((i,s)=>{const o=e.add(r,{url:t,volume:this._volume,preload:!0,loaded:(e,r)=>{if(e)return void s(e);const n=null!=r?r:o;n?G(n)?i(n):s(new Error(`Error: ${t} is not WebAudioMedia`)):s(new Error(`Error: ${t} failed to load`))}})}),n=yield o;return this.aliases.set(n,{alias:r,library:e}),this.audios.push(n),n}catch(r){return s&&i&&N(s,i),g.warn(O,`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=G(t);if(!i)return void g.warn(O,"Cannot create audio analyzer because WebAudio media is unavailable.");const s=e.createBufferSource();s.buffer=i;const r=e.createAnalyser();return r.fftSize=p.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)),o=Math.min(Math.max((r-t.minDecibels)/(t.maxDecibels-t.minDecibels),0),1);return parseFloat(o.toFixed(1))}static dispose(t){try{t.pause()}catch(i){g.warn(O,"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){g.warn(O,"Failed to destroy audio.",i)}}(t),v(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=>{g.warn(O,"Failed to close AudioContext.",t)})}for(let t=this.audios.length-1;t>=0;t--)this.dispose(this.audios[t])}}u(j,"audios",[]),u(j,"analysers",[]),u(j,"contexts",[]),u(j,"aliases",new WeakMap),u(j,"_volume",D);var H=(t=>(t.ALL="ALL",t.IDLE="IDLE",t.NONE="NONE",t))(H||{});class U extends e.EventEmitter{constructor(t){super(),u(this,"tag"),u(this,"settings"),u(this,"motionGroups",{}),u(this,"state",new A),u(this,"currentAudio"),u(this,"currentAnalyzer"),u(this,"currentContext"),u(this,"playing",!1),u(this,"destroyed",!1),u(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 g.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 c(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 g.warn(this.tag,`Cannot start motion at "${t}"[${e}] because it's already failed in loading.`);if(r[e])return r[e];const o=yield this._loadMotion(t,e);return this.destroyed?void 0:(r[e]=null!=o?o:null,o)})}_loadMotion(t,e){throw new Error("Not implemented.")}initializeAudio(t,e){this.currentAudio=t,j.volume=e,this.currentContext=t.context.audioContext,this.currentAnalyzer=j.addAnalyzer(this.currentAudio,this.currentContext)}speak(t){return c(this,arguments,function*(t,{volume:e=.5,expression:i,resetExpression:s=!0,onFinish:r,onError:o}={}){if(!p.sound)return!1;let n,a;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,a=t=e.href}else a="data:audio/";const h=t;if(h)try{if(n=yield j.add(h,(t,e=this)=>{g.error(this.tag,"Error during audio playback:",t),null==o||o(t),s&&i&&e.expressionManager&&e.expressionManager.resetExpression(),e.currentAudio=void 0}),!n)return!1;this.initializeAudio(n,e)}catch(d){return g.warn(this.tag,"Failed to create audio",a,d),!1}if(n){let t=!0;try{p.motionSync&&j.play(n,()=>{null==r||r(),s&&i&&this.expressionManager&&this.expressionManager.resetExpression(),this.currentAudio=void 0})}catch(d){g.warn(this.tag,"Failed to play audio",n.url,d),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 c(this,arguments,function*(t,e,i=F.NORMAL,{sound:s,volume:r=.5,expression:o,resetExpression:n=!0,onFinish:a,onError:l,ignoreParamIds:h=[],loop:d}={}){if(this.destroyed)return!1;if(!this.state.reserve(t,e,i))return!1;if(this.currentAudio&&this.currentAudio.isPlaying&&i!=F.FORCE)return!1;const u=this.getMotionDefinition(t,e);if(!u)return!1;let c,m;this.currentAudio&&j.dispose(this.currentAudio);const f=s&&s.startsWith("data:");if(s&&!f){const t=document.createElement("a");t.href=s,m=s=t.href}else m=this.getSoundFile(u),m&&(m=this.settings.resolveURL(m));const M=m;if(M)try{c=yield j.add(M,(t,e=this)=>{g.error(this.tag,"Error during audio playback:",t),null==l||l(t),n&&o&&e.expressionManager&&e.expressionManager.resetExpression(),e.currentAudio=void 0}),c&&this.initializeAudio(c,r)}catch(x){g.warn(this.tag,"Failed to create audio",m,x)}const y=yield this.loadMotion(t,e);if(c&&p.motionSync)try{j.play(c,(t=this)=>{null==a||a(),n&&o&&t.expressionManager&&t.expressionManager.resetExpression(),t.currentAudio=void 0})}catch(x){g.warn(this.tag,"Failed to play audio",c.url,x)}return this.state.start(y,t,e,i)?(this.state.shouldOverrideExpression()&&this.expressionManager&&this.expressionManager.resetExpression(),g.log(this.tag,"Start motion:",this.getMotionName(u)),this.emit("motionStart",t,e,c),o&&this.expressionManager&&this.state.shouldOverrideExpression()&&(yield this.expressionManager.setExpression(o)),this.playing=!0,y&&this._startMotion(y,void 0,h,d),!0):(c&&(j.dispose(c),this.currentAudio=void 0),!1)})}startRandomMotion(t,e){return c(this,arguments,function*(t,e,{sound:i,volume:s=.5,expression:r,resetExpression:o=!0,onFinish:n,onError:a,loop:l}={}){var h,d;if(this.destroyed)return!1;const u=null==(h=this.definitions)?void 0:h[t];if(null==u?void 0:u.length){const h=[],c=null!=(d=this.motionGroups[t])?d:[];for(let e=0;e<u.length;e++)null===c[e]||this.state.isActive(t,e)||h.push(e);if(h.length){const d=h[Math.floor(Math.random()*h.length)];return this.startMotion(t,d,e,{sound:i,volume:s,expression:r,resetExpression:o,onFinish:n,onError:a,loop:l})}}return!1})}stopSpeaking(){this.currentAudio&&(j.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,F.IDLE)),this.updateParameters(t,e)}mouthSync(){return this.currentAnalyzer?j.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 c(this,null,function*(){if(this.destroyed)return null;if(!this.state.reserve(t,e,F.FORCE))return null;const s=this.getMotionDefinition(t,e);if(!s)return null;this.currentAudio&&j.dispose(this.currentAudio);const r=yield this.loadMotion(t,e);return this.state.start(r,t,e,F.FORCE)?(this.state.shouldOverrideExpression()&&this.expressionManager&&this.expressionManager.resetExpression(),g.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||g.warn(this.tag,`Undefined motion at "${t}"[${e}]`),r}}function X(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,o="string"==typeof t.name?t.name:"string"==typeof t.Name?t.Name:void 0;r&&o&&i.push({id:r,name:o,index:e(r)})}return i}const B={x:0,y:0,width:0,height:0};class $ extends e.EventEmitter{constructor(){super(...arguments),u(this,"focusController",new I),u(this,"pose"),u(this,"physics"),u(this,"originalWidth",0),u(this,"originalHeight",0),u(this,"width",0),u(this,"height",0),u(this,"localTransform",new e.Matrix),u(this,"drawingMatrix",new e.Matrix),u(this,"hitAreas",{}),u(this,"textureFlipY",!1),u(this,"viewport",[0,0,0,0]),u(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,o;const n=d({width:2,height:2},s),a=null!=(r=n.width)?r:2,l=null!=(o=n.height)?o:2;t.identity(),t.scale(a/2,l/2);const h=e*t.a,u=i*t.d,c=void 0!==n.x&&n.x-a/2||void 0!==n.centerX&&n.centerX||void 0!==n.left&&n.left-a/2||void 0!==n.right&&n.right+a/2||0,p=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(h*c,-u*p),{width:h,height:u}}(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 o=this.getDrawableBounds(r,B);return o.x<=e&&e<=o.x+o.width&&o.y<=i&&i<=o.y+o.height}getDrawableBounds(t,e){const i=this.getDrawableVertices(t);let s=i[0],r=i[0],o=i[1],n=i[1];for(let a=0;a<i.length;a+=2){const t=i[a],e=i[a+1];s=Math.min(t,s),r=Math.max(t,r),o=Math.min(e,o),n=Math.max(e,n)}return null!=e||(e={}),e.x=s,e.y=o,e.width=r-s,e.height=n-o,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 W extends Error{constructor(t,e,i,s=!1){super(t),this.url=e,this.status=i,this.aborted=s}}const Y=class t{static createXHR(e,i,s,r,o){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=()=>{g.warn("XHRLoader",`Failed to load resource as ${n.responseType} (Status ${n.status}): ${i}`),o(new W("Network error.",i,n.status))},n.onabort=()=>o(new W("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}};u(Y,"xhrMap",new WeakMap),u(Y,"allXhrSet",new Set),u(Y,"loader",t=>new Promise((e,i)=>{const s=t.target,r=t.target&&"function"==typeof Y.cancelXHRs?Y.cancelXHRs.bind(t.target):void 0,o=Y.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)}o.send()}));let V=Y;function q(t,e){let i=-1;return function s(r,o){if(o)return Promise.reject(o);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(a){const t=a instanceof Error?a:new Error(String(a));return Promise.reject(t)}}(0)}class z{static load(t){return c(this,null,function*(){return yield q(this.middlewares,t),t.result})}}u(z,"middlewares",[V.loader]);class J extends _{constructor(t){if(super(t),u(this,"moc"),u(this,"textures"),u(this,"layout"),u(this,"hitAreas"),u(this,"initParams"),u(this,"initOpacities"),u(this,"expressions"),u(this,"motions",{}),!J.isValidJSON(t))throw new TypeError("Invalid JSON.");this.moc=t.model,y("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){M("string",t,this,"name","name"),M("string",t,this,"pose","pose"),M("string",t,this,"physics","physics"),M("object",t,this,"layout","layout"),M("object",t,this,"motions","motions"),y("object",t,this,"hit_areas","hitAreas"),y("object",t,this,"expressions","expressions"),y("object",t,this,"init_params","initParams"),y("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 Z({lod:t,effectiveScale:e,textureWidth:i,textureHeight:s,lodScaleThreshold:r,lodTextureSizeThreshold:o,lodMaxLevel:n}){if("single-auto"!==Q(t))return;if(!Number.isFinite(e)||e<=0)return;const a=Math.floor(i),h=Math.floor(s);if(a<=1||h<=1)return;if(e>=tt(r,.5))return;const d=tt(o,4096);if(Math.max(a,h)<d)return;const u=Math.round(Math.log2(1/e)),c=Math.max(1,Math.floor(Math.log2(Math.max(a,h)))),p=Math.min(c,(m=c,void 0!==(g=n)&&Number.isFinite(g)&&g>=1?Math.floor(g):m));var g,m;const f=function(t,e,i){return Math.min(i,Math.max(e,t))}(Math.max(1,u),1,p),M=l(2,f);return{level:f,width:Math.max(1,Math.round(a/M)),height:Math.max(1,Math.round(h/M))}}function Q(t){return!1===t||"single-auto"===t?t:"full"}function K(t){return"nearest"===t?"nearest":"linear"}function tt(t,e){return void 0!==t&&Number.isFinite(t)&&t>0?t:e}function et(){}const it="Live2DFactory",st=(t,e)=>c(null,null,function*(){if("string"==typeof t.source){const e=yield z.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()}),rt=(t,e)=>c(null,null,function*(){if(t.source instanceof _)return t.settings=t.source,e();if("object"==typeof t.source){const i=ct.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=ct.runtimes.map(t=>t.version).join(", ");if(0===ct.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"))}),ot=(t,e)=>{if(t.settings){const i=ct.findRuntime(t.settings);if(i)return i.ready().then(()=>e())}return e()},nt=(t,e)=>c(null,null,function*(){yield e();const i=t.internalModel;if(i){const e=t.settings,s=ct.findRuntime(e);if(s){const r=[],o=e instanceof J?"json":"arraybuffer";e.pose&&r.push(z.load({settings:e,url:e.pose,type:o,target:i}).then(e=>{i.pose=s.createPose(i.coreModel,e),t.live2dModel.emit("poseLoaded",i.pose)}).catch(e=>{t.live2dModel.emit("poseLoadError",e),g.warn(it,"Failed to load pose.",e)})),e.physics&&r.push(z.load({settings:e,url:e.physics,type:o,target:i}).then(e=>{i.physics=s.createPhysics(i.coreModel,e),t.live2dModel.emit("physicsLoaded",i.physics)}).catch(e=>{t.live2dModel.emit("physicsLoadError",e),g.warn(it,"Failed to load physics.",e)})),r.length&&(yield Promise.all(r))}}}),at=(t,i)=>c(null,null,function*(){if(!t.settings)throw new TypeError("Missing settings.");{const s=t.live2dModel,r=d({crossOrigin:t.options.crossOrigin},t.options.textureOptions);t.settings instanceof J&&(r.preferCreateImageBitmap=!1);const o=Promise.all(t.settings.textures.map(i=>function(t,i={}){const s=e.loadTextures.config,r=null==s?void 0:s.crossOrigin,o=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"===Q(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!=o?o:s.preferCreateImageBitmap,s.preferWorkers=null!=n?n:s.preferWorkers))})}(t.settings.resolveURL(i),r)));if(o.catch(et),yield i(),!t.internalModel)throw new TypeError("Missing internal model.");s.internalModel=t.internalModel,s.emit("modelLoaded",t.internalModel),s.textures=yield o,s.emit("textureLoaded",s.textures)}}),lt=(t,e)=>c(null,null,function*(){const i=t.settings;if(i instanceof _){const s=ct.findRuntime(i);if(!s)throw new TypeError("Unknown model settings.");const r=yield z.load({settings:i,url:i.moc,type:"arraybuffer",target:t.live2dModel});if(!s.isValidMoc(r))throw new Error("Invalid moc data");const o=s.createCoreModel(r);return t.internalModel=s.createInternalModel(o,i,t.options),e()}throw new TypeError("Missing settings.")}),ht=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(E(i.url,t)),o=e.find(t=>t.webkitRelativePath===r);o&&(s[t]=URL.createObjectURL(o))}t.filesMap[i._objectURL]=s}static createSettings(e){return c(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 o=ct.findRuntime(r);if(!o)throw new Error("Unknown settings JSON");const n=o.createModelSettings(r);return n._objectURL=URL.createObjectURL(i),n})}static readText(t){return c(this,null,function*(){return new Promise((e,i)=>{const s=new FileReader;s.onload=()=>e(s.result),s.onerror=i,s.readAsText(t,"utf8")})})}};u(ht,"live2dFactory"),u(ht,"filesMap",{}),u(ht,"factory",(t,e)=>c(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 ht.createSettings(e);i.validateFiles(e.map(t=>encodeURI(t.webkitRelativePath))),ht.upload(e,i),i.resolveURL=function(t){return ht.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),ht.filesMap[t])for(const e of Object.values(ht.filesMap[t]))URL.revokeObjectURL(e);delete ht.filesMap[t]})})}return e()}));let dt=ht;const ut=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 c(this,null,function*(){const r=new Promise(t=>e.once("textureLoaded",t)),o=new Promise(t=>e.once("modelLoaded",t)),n=Promise.all([r,o]).then(()=>e.emit("ready"));yield q(t.live2DModelMiddlewares,{live2dModel:e,source:i,options:s||{}}),yield n,e.emit("load")})}static loadMotion(e,i,s){var r;const o=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 a=t.motionTasksMap.get(e);a||(a={},t.motionTasksMap.set(e,a));let l=a[i];l||(l=[],a[i]=l);const h=e.getMotionFile(n);return null!=l[s]||(l[s]=z.load({url:h,settings:e.settings,type:e.motionDataType,target:e}).then(r=>{var o;const a=null==(o=t.motionTasksMap.get(e))?void 0:o[i];a&&(a[s]=void 0);const l=r,h=e.createMotion(l,i,n);return e.emit("motionLoaded",i,s,h),h}).catch(t=>{g.warn(e.tag,`Failed to load motion: ${h}\n`,t),o(t)})),l[s]}catch(n){g.warn(e.tag,`Failed to load motion at "${i}"[${s}]\n`,n),o(n)}return Promise.resolve(void 0)}static loadExpression(e,i){var s;const r=t=>e.emit("expressionLoadError",i,t);try{const o=e.definitions[i];if(!o)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 a=e.getExpressionFile(o),l=null!=(s=e.expressionDataType)?s:"json";return null!=n[i]||(n[i]=z.load({url:a,settings:e.settings,type:l,target:e}).then(s=>{const r=t.expressionTasksMap.get(e);r&&(r[i]=void 0);const n=s,a=e.createExpression(n,o);return e.emit("expressionLoaded",i,a),a}).catch(t=>{g.warn(e.tag,`Failed to load expression: ${a}\n`,t),r(t)})),n[i]}catch(o){g.warn(e.tag,`Failed to load expression at [${i}]\n`,o),r(o)}return Promise.resolve(void 0)}static releaseMotionTasks(e){t.motionTasksMap.delete(e)}static releaseExpressionTasks(e){t.expressionTasksMap.delete(e)}};u(ut,"runtimes",[]),u(ut,"urlToJSON",st),u(ut,"jsonToSettings",rt),u(ut,"waitUntilReady",ot),u(ut,"setupOptionals",nt),u(ut,"setupEssentials",at),u(ut,"createInternalModel",lt),u(ut,"live2DModelMiddlewares",[dt.factory,st,rt,ot,nt,at,lt]),u(ut,"motionTasksMap",new WeakMap),u(ut,"expressionTasksMap",new WeakMap);let ct=ut;U.prototype._loadMotion=function(t,e){return ct.loadMotion(this,t,e)},w.prototype._loadExpression=function(t){return ct.loadExpression(this,t)},dt.live2dFactory=ct;const pt=class t{constructor(i,{autoUpdate:s=!0,autoHitTest:r=!0,autoFocus:o=!0,autoInteract:n,ticker:a}={}){var l;u(this,"model"),u(this,"destroyed",!1),u(this,"_ticker"),u(this,"_autoUpdate",!1),u(this,"_autoHitTest",!1),u(this,"_autoFocus",!1),null!=a||(a=null!=(l=t.defaultTicker)?l:"undefined"!=typeof PIXI?PIXI.Ticker.shared:e.Ticker.shared),void 0!==n&&(r=n,o=n,g.warn(i.tag,"options.autoInteract is deprecated since v0.5.0, use autoHitTest and autoFocus instead.")),this.model=i,this.ticker=a,this.autoUpdate=s,this.autoHitTest=r,this.autoFocus=o,(r||o)&&(this.model.eventMode="static")}get ticker(){return this._ticker}set ticker(t){var e,i;this._ticker&&this._ticker.remove(mt,this),this._ticker=t,this._autoUpdate&&(null==(e=this._ticker)||e.add(mt,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(mt,this),this._autoUpdate=!0):g.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(mt,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",Mt,this),this.model.on("pointermove",Mt,this)):(this.model.off("globalpointermove",Mt,this),this.model.off("pointermove",Mt,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}};u(pt,"defaultTicker");let gt=pt;function mt(){this.onTickerUpdate()}function ft(t){this.onTap(t)}function Mt(t){this.onPointerMove(t)}class yt extends e.Transform{}const xt=new e.Point,vt=new e.Matrix,bt=new e.Matrix,Et={x:0,y:0,width:0,height:0},wt=new e.Bounds;let Pt=!1;class Lt{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(){}}u(Lt,"extension",{type:[e.ExtensionType.WebGLPipes],name:"live2d"});const It=Lt;class _t extends e.Container{constructor(t){var i;super(),u(this,"renderPipeId","live2d"),u(this,"tag","Live2DModel(uninitialized)"),u(this,"internalModel"),u(this,"textures",[]),u(this,"textureOptions"),u(this,"anchorMode"),u(this,"textureLODStates",[]),u(this,"textureLODFailures",[]),u(this,"transform",new yt),u(this,"anchor"),u(this,"_bounds",new e.Bounds),u(this,"_boundsDirty",!0),u(this,"_boundsRetryAfterDraw",!1),u(this,"gl",null),u(this,"elapsedTime",0),u(this,"deltaTime",0),u(this,"automator"),u(this,"currentGlId",0),u(this,"renderLive2D",t=>{var i,s,r,o,n;if(!(t instanceof e.WebGLRenderer))throw new Error("Renderer is not supported");t.geometry.resetState(),t.shader.resetState(),t.texture.resetState();let a=!1;this.gl!==t.gl&&(this.gl=t.gl,this.internalModel.updateWebGLContext(t.gl,this.generateUID()),a=!0);const{projectionMatrix:l,offset:h,worldTransformMatrix:d}=t.globalUniforms.globalUniformData,u=bt.copyFrom(d).append(this.groupTransform),c=(p=u,Math.max(Math.hypot(p.a,p.b),Math.hypot(p.c,p.d))*t.resolution);var p;for(let e=0;e<this.textures.length;e++){const i=this.textures[e];let s=this.resolveTextureForRender(e,i,c);try{this.uploadTextureForRender(t,s,a)}catch(b){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,a)}this.internalModel.bindTexture(e,t.texture.getGlSource(s.source).texture)}const g=t.renderTarget.viewport,m=t.renderTarget.renderTarget;let f=g.y;if(null==m?void 0:m.isRoot){f=m.colorTexture.source.pixelHeight-g.height-g.y}this.internalModel.viewport=[g.x,f,g.width,g.height];const M=this.deltaTime;this.deltaTime=0,M&&this.internalModel.update(M,this.elapsedTime),u.tx-=null!=(i=null==h?void 0:h.x)?i:0,u.ty-=null!=(s=null==h?void 0:h.y)?s:0;const y=vt.copyFrom(l).append(u);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,v=null==(n=null==(o=t.renderTarget)?void 0:o.adaptor)?void 0:n._clearColorCache;x&&(t.gl.clearColor(x[0],x[1],x[2],x[3]),v&&(v[0]=x[0],v[1]=x[1],v[2]=x[2],v[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 gt(this,t),this.once("modelLoaded",()=>this.initializeOnModelLoad(t))}get isRenderable(){return!0}get canBundle(){return!1}static from(t,e){return c(this,null,function*(){const i=new this(e);return yield ct.setupLive2DModel(i,t,e),i})}static fromSync(t,e){const i=new this(e);return ct.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){gt.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();wt.clear();for(let i=0;i<t.length;i++){const s=t[i],r=this.internalModel.getDrawableIndex(s);if(r<0)continue;const o=this.internalModel.getDrawableBounds(r,Et);Number.isFinite(o.x)&&Number.isFinite(o.y)&&Number.isFinite(o.width)&&Number.isFinite(o.height)&&wt.addFrame(o.x,o.y,o.x+o.width,o.y+o.height,e.Matrix.IDENTITY)}if(this._bounds.clear(),wt.isValid&&wt.isPositive)this._bounds.addFrame(wt.minX,wt.minY,wt.maxX,wt.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,o,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||(Pt||(Pt=!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 Lt(t))}(e);const a=e.renderPipes,l=()=>{a.live2d.addRenderable(this,t)},h=()=>{const s=this.children,r=s.length;for(let o=0;o<r;o++)s[o].collectRenderables(t,e,i)},d=this.effects;if(d){for(let e=0;e<d.length;e++){const i=d[e],o=i.filters;if(o)for(const t of o)t&&"number"==typeof t.resolution&&1===t.resolution&&(t.resolution="inherit");null==(r=null==(s=a[i.pipe])?void 0:s.push)||r.call(s,i,this,t)}l(),h();for(let e=d.length-1;e>=0;e--){const i=d[e];null==(n=null==(o=a[i.pipe])?void 0:o.pop)||n.call(o,i,this,t)}}else l(),h()}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 c(this,arguments,function*(t,e,i,{sound:s,volume:r=.5,expression:o,resetExpression:n=!0,onFinish:a,onError:l,loop:h}={}){return void 0===e?this.internalModel.motionManager.startRandomMotion(t,i,{sound:s,volume:r,expression:o,resetExpression:n,onFinish:a,onError:l,loop:h}):this.internalModel.motionManager.startMotion(t,e,i,{sound:s,volume:r,expression:o,resetExpression:n,onFinish:a,onError:l,loop:h})})}motionLastFrame(t,e){return c(this,arguments,function*(t,e,{expression:i}={}){return this.internalModel.motionManager.motionLastFrame(t,e,{expression:i})})}parallelMotion(t){return c(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 c(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:o}={}){return this.internalModel.motionManager.speak(t,{volume:e,expression:i,resetExpression:s,onFinish:r,onError:o})}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){xt.x=t,xt.y=e,this.toModelPosition(xt,xt,!0);const s=xt.x/this.internalModel.originalWidth*2-1,r=xt.y/this.internalModel.originalHeight*2-1,o=Math.atan2(r,s);this.internalModel.focusController.focus(Math.cos(o),-Math.sin(o),i)}tap(t,e){const i=this.hitTest(t,e);i.length&&this.emit("hit",i)}hitTest(t,e){return xt.x=t,xt.y=e,this.toModelPosition(xt,xt),this.internalModel.hitTest(xt.x,xt.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,o){var n;const a=Z((l=d({},this.textureOptions),h={effectiveScale:o,textureWidth:i.source.pixelWidth,textureHeight:i.source.pixelHeight},s(l,r(h))));var l,h;if(!a)return i;const u=this.textureLODFailures[t];if((null==u?void 0:u.source)===i&&u.levels.has(a.level))return i;const c=this.textureLODStates[t];if((null==c?void 0:c.source)===i&&c.level===a.level&&!c.texture.destroyed)return c.texture;this.destroyTextureLODState(t);const p=function(t,i,s,r,o){var n,a;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 h=e.DOMAdapter.get().createCanvas(s,r),d=h.getContext("2d");if(!d)return;try{d.clearRect(0,0,s,r),d.imageSmoothingEnabled="nearest"!==o,"imageSmoothingQuality"in d&&"nearest"!==o&&(d.imageSmoothingQuality="high"),d.drawImage(l,0,0,t.source.pixelWidth,t.source.pixelHeight,0,0,s,r)}catch(c){return}const u=`${null!=(a=null!=(n=t.label)?n:t.source.label)?a:"Live2DTexture"} LOD ${i}`;return new e.Texture({label:u,source:new e.CanvasSource({resource:h,width:s,height:r,resolution:1,scaleMode:K(o),autoGenerateMipmaps:!1,label:u})})}(i,a.level,a.width,a.height,null==(n=this.textureOptions)?void 0:n.lodFilter);return p?(this.textureLODStates[t]={source:i,level:a.level,texture:p},p):(this.markTextureLODFailure(t,i,a.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 Ft=Live2DMotion.prototype.updateParam;Live2DMotion.prototype.updateParam=function(t,e){Ft.call(this,t,e),e.isFinished()&&this.onFinishHandler&&(this.onFinishHandler(this),delete this.onFinishHandler)};class At extends AMotion{constructor(t){super(),u(this,"params",[]),this.setFadeIn(t.fade_in>0?t.fade_in:p.expressionFadingDuration),this.setFadeOut(t.fade_out>0?t.fade_out:p.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 Ot extends w{constructor(t,e){var i;super(t,e),u(this,"queueManager",new MotionQueueManager),u(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 At(t)}_setExpression(t){return this.queueManager.startMotion(t)}stopAllExpressions(){this.queueManager.stopAllMotions()}updateParameters(t,e){return this.queueManager.updateParam(t)}}function Dt(t,e,i){const s=i.getDurationMSec(),r=t.startMotion(i,!0),o=t.motions.find(t=>!!t&&t._$sr===r);return!!o&&(i.updateParamExe(e.coreModel,s,1,o),!0)}class Tt extends U{constructor(t){super(t),u(this,"definitions"),u(this,"groups",{idle:"idle"}),u(this,"motionDataType","arraybuffer"),u(this,"queueManager",new MotionQueueManager),u(this,"lipSyncIds"),u(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 Ot(this.settings,t))}isFinished(){return this.queueManager.isFinished()}createMotion(t,e,i){const s=Live2DMotion.loadMotion(t),r=e===this.groups.idle?p.idleMotionFadingDuration:p.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 c(this,arguments,function*(t,e,{expression:i}={}){const s=yield this.getMotionAndApplyExpression(t,e,i);return!!s&&(this.playing=!0,Dt(this.queueManager,this.parent,s),this.playing=!1,!0)})}}class St extends e.EventEmitter{constructor(t){super(),u(this,"tag"),u(this,"manager"),u(this,"settings"),u(this,"state",new A),u(this,"playing",!1),u(this,"destroyed",!1),u(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 c(this,arguments,function*(t,e,i=F.NORMAL,s={}){var r;const{ignoreParamIds:o=[],loop:n}=Array.isArray(s)?{ignoreParamIds:s,loop:void 0}:s;if(!this.state.reserve(t,e,i))return!1;const a=null==(r=this.manager.definitions[t])?void 0:r[e];if(!a)return!1;const l=yield this.manager.loadMotion(t,e);return!!this.state.start(l,t,e,i)&&(g.log(this.tag,"Start motion:",this.getMotionName(a)),this.emit("motionStart",t,e,void 0),this.playing=!0,this._startMotion(l,void 0,o,n),!0)})}startRandomMotion(t,e){return c(this,arguments,function*(t,e,{loop:i}={}){var s;const r=this.manager.definitions[t];if(null==r?void 0:r.length){const o=[],n=null!=(s=this.manager.motionGroups[t])?s:[];for(let e=0;e<r.length;e++)null===n[e]||this.state.isActive(t,e)||o.push(e);if(o.length){const s=o[Math.floor(Math.random()*o.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 Rt extends St{constructor(t){super(t),u(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 c(this,null,function*(){var i;if(!this.state.reserve(t,e,F.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,F.FORCE)&&(g.log(this.tag,"Start motion:",this.getMotionName(s)),this.queueManager.stopAllMotions(),this.emit("motionStart",t,e,void 0),this.playing=!0,!!Dt(this.queueManager,this.parent,r)&&(this.playing=!1,!0))})}}class Ct{constructor(t){u(this,"leftParam"),u(this,"rightParam"),u(this,"blinkInterval",4e3),u(this,"closingDuration",100),u(this,"closedDuration",50),u(this,"openingDuration",150),u(this,"eyeState",0),u(this,"eyeParamValue",1),u(this,"closedTimer",0),u(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+f(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 kt=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);class Nt extends ${constructor(t,e,i){super(),u(this,"settings"),u(this,"options"),u(this,"coreModel"),u(this,"motionManager"),u(this,"parallelMotionManager"),u(this,"eyeBlink"),u(this,"eyeballXParamIndex"),u(this,"eyeballYParamIndex"),u(this,"angleXParamIndex"),u(this,"angleYParamIndex"),u(this,"angleZParamIndex"),u(this,"bodyAngleXParamIndex"),u(this,"breathParamIndex"),u(this,"textureFlipY",!0),u(this,"lipSync",!0),u(this,"drawDataCount",0),u(this,"disableCulling",!1),u(this,"hasDrawn",!1),u(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&&g.warn("CubismLegacyInternalModel","`useHighPrecisionMask` is only supported by Cubism 3/4/5 models and will be ignored for Cubism 2 models."),this.motionManager=new Tt(this),this.parallelMotionManager=[],!1!==this.options.eyeBlink&&(this.eyeBlink=new Ct(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 X(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||g.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,o;super.update(t,e);const n=this.coreModel,a=this.updateMotions(n,e);if(n.saveParam(),null==(i=this.motionManager.expressionManager)||i.update(n,e),a||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==(o=this.pose)||o.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;kt[0]=i.a,kt[1]=i.b,kt[4]=i.c,kt[5]=i.d,kt[12]=i.tx,kt[13]=i.ty,this.coreModel.setMatrix(kt),this.coreModel.draw(),this.hasDrawn=!0,this.disableCulling=e}extendParallelMotionManager(t){for(;this.parallelMotionManager.length<t;)this.parallelMotionManager.push(new Rt(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 o=t/s*2-1,n=1-e/r*2,a=[];for(const[l,h]of Object.entries(i))o>=h.minX&&o<=h.maxX&&n>=h.minY&&n<=h.maxY&&a.push(l);return a}getCustomHitAreas(){var t,e,i,s,r;if(void 0!==this.customHitAreas)return this.customHitAreas;const o=this.settings.json,n=null!=(i=null!=(e=null!=(t=o.hit_areas_custom)?t:o.hitAreasCustom)?e:o.HitAreasCustom)?i:o.HitAreas_Custom;if(!n||"object"!=typeof n)return this.customHitAreas=null,null;const a=n,l={},h=(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]),o=Number(i[0]),n=Number(i[1]);Number.isFinite(s)&&Number.isFinite(r)&&Number.isFinite(o)&&Number.isFinite(n)&&(l[t]={minX:Math.min(s,r),maxX:Math.max(s,r),minY:Math.min(o,n),maxY:Math.max(o,n)})};for(const[d,u]of Object.entries(a)){if(d.endsWith("_x")){const t=d.slice(0,-2);h(t,u,a[`${t}_y`]);continue}if(!d.endsWith("_y")&&(u&&"object"==typeof u)){const t=u;h(d,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 Gt={x:PhysicsHair.Src.SRC_TO_X,y:PhysicsHair.Src.SRC_TO_Y,angle:PhysicsHair.Src.SRC_TO_G_ANGLE},jt={x:PhysicsHair.Src.SRC_TO_X,y:PhysicsHair.Src.SRC_TO_Y,angle:PhysicsHair.Src.SRC_TO_G_ANGLE};class Ht{constructor(t,e){u(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 o=Gt[i];o&&e.addSrcParam(o,t,s,r)}),t.targets.forEach(({id:t,ptype:i,scale:s,weight:r})=>{const o=jt[i];o&&e.addTargetParam(o,t,s,r)}),e}))}update(t){this.physicsHairs.forEach(e=>e.update(this.coreModel,t))}}class Ut{constructor(t){u(this,"paramIndex",-1),u(this,"partsIndex",-1),u(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 Xt{constructor(t,e){u(this,"opacityAnimDuration",500),u(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 Ut(t);return e&&(i.link=e.map(t=>new Ut(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,o=t.findIndex(({paramIndex:t,partsIndex:e})=>e>=0&&0!==i.getParamFloat(t));if(o>=0){const s=i.getPartsOpacity(t[o].partsIndex);r=m(s+e/this.opacityAnimDuration,0,1)}else o=0,r=1;t.forEach(({partsIndex:t},e)=>{if(t>=0)if(o==e)i.setPartsOpacity(t,r);else{let e,o=i.getPartsOpacity(t);e=r<s?-.5*r/s+1:(1-r)*s/.5;(1-e)*(1-r)>.15&&(e=1-.15/(1-r)),o>e&&(o=e),i.setPartsOpacity(t,o)}})}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)})}}ct.registerRuntime({version:2,test:t=>t instanceof J||J.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 J(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 Nt(t,e,i),createPose:(t,e)=>new Xt(t,e),createPhysics:(t,e)=>new Ht(t,e)}),t.CubismLegacyExpressionManager=Ot,t.CubismLegacyInternalModel=Nt,t.CubismLegacyModelSettings=J,t.CubismLegacyMotionManager=Tt,t.CubismLegacyParallelMotionManager=Rt,t.ExpressionManager=w,t.FileLoader=dt,t.FocusController=I,t.InternalModel=$,t.LOGICAL_HEIGHT=2,t.LOGICAL_WIDTH=2,t.Live2DExpression=At,t.Live2DEyeBlink=Ct,t.Live2DFactory=ct,t.Live2DLoader=z,t.Live2DModel=_t,t.Live2DPhysics=Ht,t.Live2DPlugin=It,t.Live2DPose=Xt,t.Live2DTransform=yt,t.MBToByte=function(t){return 1024*t*1024},t.ModelSettings=_,t.MotionManager=U,t.MotionPreloadStrategy=H,t.MotionPriority=F,t.MotionState=A,t.SoundManager=j,t.VERSION="1.3.3",t.VOLUME=D,t.XHRLoader=V,t.applyMixins=function(t,e){e.forEach(e=>{Object.getOwnPropertyNames(e.prototype).forEach(i=>{"constructor"!==i&&Object.defineProperty(t.prototype,i,Object.getOwnPropertyDescriptor(e.prototype,i))})})},t.clamp=m,t.config=p,t.copyArray=y,t.copyProperty=M,t.folderName=x,t.logger=g,t.normalizeHitAreaDefs=X,t.rand=f,t.remove=v,t.resolveURL=E,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,n=Object.getOwnPropertySymbols,o=Object.prototype.hasOwnProperty,a=Object.prototype.propertyIsEnumerable,l=Math.pow,h=(t,e,s)=>e in t?i(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s,d=(t,e)=>{for(var i in e||(e={}))o.call(e,i)&&h(t,i,e[i]);if(n)for(var i of n(e))a.call(e,i)&&h(t,i,e[i]);return t},u=(t,e,i)=>h(t,"symbol"!=typeof e?e+"":e,i),c=(t,e,i)=>new Promise((s,r)=>{var n=t=>{try{a(i.next(t))}catch(e){r(e)}},o=t=>{try{a(i.throw(t))}catch(e){r(e)}},a=t=>t.done?s(t.value):Promise.resolve(t.value).then(n,o);a((i=i.apply(t,e)).next())});const p={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"}))},g={log(t,...e){p.logLevel<=p.LOG_LEVEL_VERBOSE&&console.log(`[${t}]`,...e)},warn(t,...e){p.logLevel<=p.LOG_LEVEL_WARNING&&console.warn(`[${t}]`,...e)},error(t,...e){p.logLevel<=p.LOG_LEVEL_ERROR&&console.error(`[${t}]`,...e)}};function m(t,e,i){return t<e?e:t>i?i:t}function f(t,e){return Math.random()*(e-t)+t}function M(t,e,i,s,r){const n=e[s];null!==n&&typeof n===t&&(i[r]=n)}function y(t,e,i,s,r){const n=e[s];Array.isArray(n)&&(i[r]=n.filter(e=>null!==e&&typeof e===t))}function x(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 v(t,e){const i=t.indexOf(e);-1!==i&&t.splice(i,1)}const b=/^[a-zA-Z][a-zA-Z0-9+.-]*:/;function E(t,e){if(!e)return t;if(b.test(e))return e;if(e.startsWith("/"))return b.test(t)?new URL(e,t).toString():e;if(b.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 n=r.pathname+r.search+r.hash;return!t.startsWith("/")&&n.startsWith("/")&&(n=n.slice(1)),n}class w extends e.EventEmitter{constructor(t,e){super(),u(this,"expressionDataType","json"),u(this,"tag"),u(this,"settings"),u(this,"expressions",[]),u(this,"defaultExpression"),u(this,"currentExpression"),u(this,"reserveExpressionIndex",-1),u(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 c(this,null,function*(){if(!this.definitions[t])return void g.warn(this.tag,`Undefined expression at [${t}]`);if(null===this.expressions[t])return void g.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 c(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 c(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 P=40/7.5,L=1/150;class I{constructor(){u(this,"targetX",0),u(this,"targetY",0),u(this,"x",0),u(this,"y",0),u(this,"vx",0),u(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=P/(1e3/t);let n=r*(e/s)-this.vx,o=r*(i/s)-this.vy;const a=Math.sqrt(l(n,2)+l(o,2)),h=r*L*t;a>h&&(n*=h/a,o*=h/a),this.vx+=n,this.vy+=o;const d=Math.sqrt(l(this.vx,2)+l(this.vy,2)),u=.5*(Math.sqrt(l(h,2)+8*h*s)-h);d>u&&(this.vx*=u/d,this.vy*=u/d),this.x+=this.vx,this.y+=this.vy}}class _{constructor(t){u(this,"json"),u(this,"name"),u(this,"url"),u(this,"pose"),u(this,"physics"),this.json=t,this.url=t.url,this.name=x(this.url)}normalizeName(){this.name&&"name"!==this.name.toLowerCase()||(this.name=x(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 E(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 F=(t=>(t[t.NONE=0]="NONE",t[t.IDLE=1]="IDLE",t[t.NORMAL=2]="NORMAL",t[t.FORCE=3]="FORCE",t))(F||{});class A{constructor(){u(this,"tag"),u(this,"debug",!1),u(this,"currentPriority",0),u(this,"reservePriority",0),u(this,"currentGroup"),u(this,"currentIndex"),u(this,"reservedGroup"),u(this,"reservedIndex"),u(this,"reservedIdleGroup"),u(this,"reservedIdleIndex")}reserve(t,e,i){if(i<=0)return g.log(this.tag,"Cannot start a motion with MotionPriority.NONE."),!1;if(t===this.currentGroup&&e===this.currentIndex)return g.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 g.log(this.tag,"Motion is already reserved.",this.dump(t,e)),!1;if(1===i){if(0!==this.currentPriority)return g.log(this.tag,"Cannot start idle motion because another motion is playing.",this.dump(t,e)),!1;if(void 0!==this.reservedIdleGroup)return g.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 g.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 g.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 g.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 g.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!p.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 D="SoundManager",O=.5;let T,S=0;const R=new WeakSet;function C(t){if(!R.has(t)){try{t.disableAutoPause=!0}catch(e){g.warn(D,"Failed to disable @pixi/sound auto pause.",e)}R.add(t)}return t}function k(){return c(this,null,function*(){const t="undefined"!=typeof PIXI?null==PIXI?void 0:PIXI.sound:void 0;return t?C(t):(null!=T||(T=import("@pixi/sound").then(({sound:t})=>C(t)).catch(t=>(g.warn(D,"@pixi/sound is not available. Load pixi-sound.js before using motion sounds, speak(), or lip sync.",t),null))),T)})}function N(t,e){try{t.remove(e)}catch(i){g.warn(D,`Failed to remove sound "${e}".`,i)}}function G(t){const e=t.media.buffer;if(!e||"object"!=typeof e)return;return"function"==typeof e.getChannelData?e:void 0}class j{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 c(this,null,function*(){let i,s=null;try{if(s=yield k(),!s)throw new Error("@pixi/sound is not available");i="live2d-sound-"+S++;const e=s,r=i,n=new Promise((i,s)=>{const n=e.add(r,{url:t,volume:this._volume,preload:!0,loaded:(e,r)=>{if(e)return void s(e);const o=null!=r?r:n;o?G(o)?i(o):s(new Error(`Error: ${t} is not WebAudioMedia`)):s(new Error(`Error: ${t} failed to load`))}})}),o=yield n;return this.aliases.set(o,{alias:r,library:e}),this.audios.push(o),o}catch(r){return s&&i&&N(s,i),g.warn(D,`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=G(t);if(!i)return void g.warn(D,"Cannot create audio analyzer because WebAudio media is unavailable.");const s=e.createBufferSource();s.buffer=i;const r=e.createAnalyser();return r.fftSize=p.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 o=0;o<e.length;o++)i+=l(e[o],2);const s=Math.sqrt(i/e.length),r=20*Math.log10(s||l(10,-5)),n=Math.min(Math.max((r-t.minDecibels)/(t.maxDecibels-t.minDecibels),0),1);return parseFloat(n.toFixed(1))}static dispose(t){try{t.pause()}catch(i){g.warn(D,"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){g.warn(D,"Failed to destroy audio.",i)}}(t),v(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=>{g.warn(D,"Failed to close AudioContext.",t)})}for(let t=this.audios.length-1;t>=0;t--)this.dispose(this.audios[t])}}u(j,"audios",[]),u(j,"analysers",[]),u(j,"contexts",[]),u(j,"aliases",new WeakMap),u(j,"_volume",O);var H=(t=>(t.ALL="ALL",t.IDLE="IDLE",t.NONE="NONE",t))(H||{});class U extends e.EventEmitter{constructor(t){super(),u(this,"tag"),u(this,"settings"),u(this,"motionGroups",{}),u(this,"state",new A),u(this,"currentAudio"),u(this,"currentAnalyzer"),u(this,"currentContext"),u(this,"playing",!1),u(this,"destroyed",!1),u(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 g.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 c(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 g.warn(this.tag,`Cannot start motion at "${t}"[${e}] because it's already failed in loading.`);if(r[e])return r[e];const n=yield this._loadMotion(t,e);return this.destroyed?void 0:(r[e]=null!=n?n:null,n)})}_loadMotion(t,e){throw new Error("Not implemented.")}initializeAudio(t,e){this.currentAudio=t,j.volume=e,this.currentContext=t.context.audioContext,this.currentAnalyzer=j.addAnalyzer(this.currentAudio,this.currentContext)}speak(t){return c(this,arguments,function*(t,{volume:e=.5,expression:i,resetExpression:s=!0,onFinish:r,onError:n}={}){if(!p.sound)return!1;let o,a;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,a=t=e.href}else a="data:audio/";const h=t;if(h)try{if(o=yield j.add(h,(t,e=this)=>{g.error(this.tag,"Error during audio playback:",t),null==n||n(t),s&&i&&e.expressionManager&&e.expressionManager.resetExpression(),e.currentAudio=void 0}),!o)return!1;this.initializeAudio(o,e)}catch(d){return g.warn(this.tag,"Failed to create audio",a,d),!1}if(o){let t=!0;try{p.motionSync&&j.play(o,()=>{null==r||r(),s&&i&&this.expressionManager&&this.expressionManager.resetExpression(),this.currentAudio=void 0})}catch(d){g.warn(this.tag,"Failed to play audio",o.url,d),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 c(this,arguments,function*(t,e,i=F.NORMAL,{sound:s,volume:r=.5,expression:n,resetExpression:o=!0,onFinish:a,onError:l,ignoreParamIds:h=[],loop:d}={}){if(this.destroyed)return!1;if(!this.state.reserve(t,e,i))return!1;if(this.currentAudio&&this.currentAudio.isPlaying&&i!=F.FORCE)return!1;const u=this.getMotionDefinition(t,e);if(!u)return!1;let c,m;this.currentAudio&&j.dispose(this.currentAudio);const f=s&&s.startsWith("data:");if(s&&!f){const t=document.createElement("a");t.href=s,m=s=t.href}else m=this.getSoundFile(u),m&&(m=this.settings.resolveURL(m));const M=m;if(M)try{c=yield j.add(M,(t,e=this)=>{g.error(this.tag,"Error during audio playback:",t),null==l||l(t),o&&n&&e.expressionManager&&e.expressionManager.resetExpression(),e.currentAudio=void 0}),c&&this.initializeAudio(c,r)}catch(x){g.warn(this.tag,"Failed to create audio",m,x)}const y=yield this.loadMotion(t,e);if(c&&p.motionSync)try{j.play(c,(t=this)=>{null==a||a(),o&&n&&t.expressionManager&&t.expressionManager.resetExpression(),t.currentAudio=void 0})}catch(x){g.warn(this.tag,"Failed to play audio",c.url,x)}return this.state.start(y,t,e,i)?(this.state.shouldOverrideExpression()&&this.expressionManager&&this.expressionManager.resetExpression(),g.log(this.tag,"Start motion:",this.getMotionName(u)),this.emit("motionStart",t,e,c),n&&this.expressionManager&&this.state.shouldOverrideExpression()&&(yield this.expressionManager.setExpression(n)),this.playing=!0,y&&this._startMotion(y,void 0,h,d),!0):(c&&(j.dispose(c),this.currentAudio=void 0),!1)})}startRandomMotion(t,e){return c(this,arguments,function*(t,e,{sound:i,volume:s=.5,expression:r,resetExpression:n=!0,onFinish:o,onError:a,loop:l}={}){var h,d;if(this.destroyed)return!1;const u=null==(h=this.definitions)?void 0:h[t];if(null==u?void 0:u.length){const h=[],c=null!=(d=this.motionGroups[t])?d:[];for(let e=0;e<u.length;e++)null===c[e]||this.state.isActive(t,e)||h.push(e);if(h.length){const d=h[Math.floor(Math.random()*h.length)];return this.startMotion(t,d,e,{sound:i,volume:s,expression:r,resetExpression:n,onFinish:o,onError:a,loop:l})}}return!1})}stopSpeaking(){this.currentAudio&&(j.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,F.IDLE)),this.updateParameters(t,e)}mouthSync(){return this.currentAnalyzer?j.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 c(this,null,function*(){if(this.destroyed)return null;if(!this.state.reserve(t,e,F.FORCE))return null;const s=this.getMotionDefinition(t,e);if(!s)return null;this.currentAudio&&j.dispose(this.currentAudio);const r=yield this.loadMotion(t,e);return this.state.start(r,t,e,F.FORCE)?(this.state.shouldOverrideExpression()&&this.expressionManager&&this.expressionManager.resetExpression(),g.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||g.warn(this.tag,`Undefined motion at "${t}"[${e}]`),r}}function X(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,n="string"==typeof t.name?t.name:"string"==typeof t.Name?t.Name:void 0;r&&n&&i.push({id:r,name:n,index:e(r)})}return i}const B={x:0,y:0,width:0,height:0};class $ extends e.EventEmitter{constructor(){super(...arguments),u(this,"focusController",new I),u(this,"pose"),u(this,"physics"),u(this,"originalWidth",0),u(this,"originalHeight",0),u(this,"width",0),u(this,"height",0),u(this,"localTransform",new e.Matrix),u(this,"drawingMatrix",new e.Matrix),u(this,"hitAreas",{}),u(this,"textureFlipY",!1),u(this,"viewport",[0,0,0,0]),u(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,n;const o=d({width:2,height:2},s),a=null!=(r=o.width)?r:2,l=null!=(n=o.height)?n:2;t.identity(),t.scale(a/2,l/2);const h=e*t.a,u=i*t.d,c=void 0!==o.x&&o.x-a/2||void 0!==o.centerX&&o.centerX||void 0!==o.left&&o.left-a/2||void 0!==o.right&&o.right+a/2||0,p=void 0!==o.y&&o.y-l/2||void 0!==o.centerY&&o.centerY||void 0!==o.top&&o.top-l/2||void 0!==o.bottom&&o.bottom+l/2||0;return t.translate(h*c,-u*p),{width:h,height:u}}(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 n=this.getDrawableBounds(r,B);return n.x<=e&&e<=n.x+n.width&&n.y<=i&&i<=n.y+n.height}getDrawableBounds(t,e){const i=this.getDrawableVertices(t);let s=i[0],r=i[0],n=i[1],o=i[1];for(let a=0;a<i.length;a+=2){const t=i[a],e=i[a+1];s=Math.min(t,s),r=Math.max(t,r),n=Math.min(e,n),o=Math.max(e,o)}return null!=e||(e={}),e.x=s,e.y=n,e.width=r-s,e.height=o-n,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 W extends Error{constructor(t,e,i,s=!1){super(t),this.url=e,this.status=i,this.aborted=s}}const Y=class t{static createXHR(e,i,s,r,n){const o=new XMLHttpRequest;if(t.allXhrSet.add(o),e){let i=t.xhrMap.get(e);i?i.add(o):(i=new Set([o]),t.xhrMap.set(e,i))}return o.open("GET",i),o.responseType=s,o.onload=()=>{var t;200!==o.status&&0!==o.status||!o.response?null==(t=o.onerror)||t.call(o,new ProgressEvent("error")):r(o.response)},o.onerror=()=>{g.warn("XHRLoader",`Failed to load resource as ${o.responseType} (Status ${o.status}): ${i}`),n(new W("Network error.",i,o.status))},o.onabort=()=>n(new W("Aborted.",i,o.status,!0)),o.onloadend=()=>{var i;t.allXhrSet.delete(o),e&&(null==(i=t.xhrMap.get(e))||i.delete(o))},o}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}};u(Y,"xhrMap",new WeakMap),u(Y,"allXhrSet",new Set),u(Y,"loader",t=>new Promise((e,i)=>{const s=t.target,r=t.target&&"function"==typeof Y.cancelXHRs?Y.cancelXHRs.bind(t.target):void 0,n=Y.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)}n.send()}));let V=Y;function q(t,e){let i=-1;return function s(r,n){if(n)return Promise.reject(n);if(r<=i)return Promise.reject(new Error("next() called multiple times"));i=r;const o=t[r];if(!o)return Promise.resolve();try{return Promise.resolve(o(e,s.bind(null,r+1)))}catch(a){const t=a instanceof Error?a:new Error(String(a));return Promise.reject(t)}}(0)}class z{static load(t){return c(this,null,function*(){return yield q(this.middlewares,t),t.result})}}u(z,"middlewares",[V.loader]);class J extends _{constructor(t){if(super(t),u(this,"moc"),u(this,"textures"),u(this,"layout"),u(this,"hitAreas"),u(this,"initParams"),u(this,"initOpacities"),u(this,"expressions"),u(this,"motions",{}),!J.isValidJSON(t))throw new TypeError("Invalid JSON.");this.moc=t.model,y("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){M("string",t,this,"name","name"),M("string",t,this,"pose","pose"),M("string",t,this,"physics","physics"),M("object",t,this,"layout","layout"),M("object",t,this,"motions","motions"),y("object",t,this,"hit_areas","hitAreas"),y("object",t,this,"expressions","expressions"),y("object",t,this,"init_params","initParams"),y("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 Z({lod:t,effectiveScale:e,textureWidth:i,textureHeight:s,lodScaleThreshold:r,lodTextureSizeThreshold:n,lodMaxLevel:o}){if("single-auto"!==Q(t))return;if(!Number.isFinite(e)||e<=0)return;const a=Math.floor(i),h=Math.floor(s);if(a<=1||h<=1)return;if(e>=tt(r,.5))return;const d=tt(n,4096);if(Math.max(a,h)<d)return;const u=Math.round(Math.log2(1/e)),c=Math.max(1,Math.floor(Math.log2(Math.max(a,h)))),p=Math.min(c,(m=c,void 0!==(g=o)&&Number.isFinite(g)&&g>=1?Math.floor(g):m));var g,m;const f=function(t,e,i){return Math.min(i,Math.max(e,t))}(Math.max(1,u),1,p),M=l(2,f);return{level:f,width:Math.max(1,Math.round(a/M)),height:Math.max(1,Math.round(h/M))}}function Q(t){return!1===t||"single-auto"===t?t:"full"}function K(t){return"nearest"===t?"nearest":"linear"}function tt(t,e){return void 0!==t&&Number.isFinite(t)&&t>0?t:e}function et(){}const it="Live2DFactory",st=(t,e)=>c(null,null,function*(){if("string"==typeof t.source){const e=yield z.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()}),rt=(t,e)=>c(null,null,function*(){if(t.source instanceof _)return t.settings=t.source,e();if("object"==typeof t.source){const i=ct.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=ct.runtimes.map(t=>t.version).join(", ");if(0===ct.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"))}),nt=(t,e)=>{if(t.settings){const i=ct.findRuntime(t.settings);if(i)return i.ready().then(()=>e())}return e()},ot=(t,e)=>c(null,null,function*(){yield e();const i=t.internalModel;if(i){const e=t.settings,s=ct.findRuntime(e);if(s){const r=[],n=e instanceof J?"json":"arraybuffer";e.pose&&r.push(z.load({settings:e,url:e.pose,type:n,target:i}).then(e=>{i.pose=s.createPose(i.coreModel,e),t.live2dModel.emit("poseLoaded",i.pose)}).catch(e=>{t.live2dModel.emit("poseLoadError",e),g.warn(it,"Failed to load pose.",e)})),e.physics&&r.push(z.load({settings:e,url:e.physics,type:n,target:i}).then(e=>{i.physics=s.createPhysics(i.coreModel,e),t.live2dModel.emit("physicsLoaded",i.physics)}).catch(e=>{t.live2dModel.emit("physicsLoadError",e),g.warn(it,"Failed to load physics.",e)})),r.length&&(yield Promise.all(r))}}}),at=(t,i)=>c(null,null,function*(){if(!t.settings)throw new TypeError("Missing settings.");{const s=t.live2dModel,r=d({crossOrigin:t.options.crossOrigin},t.options.textureOptions);t.settings instanceof J&&(r.preferCreateImageBitmap=!1);const n=Promise.all(t.settings.textures.map(i=>function(t,i={}){const s=e.loadTextures.config,r=null==s?void 0:s.crossOrigin,n=null==s?void 0:s.preferCreateImageBitmap,o=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"===Q(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!=n?n:s.preferCreateImageBitmap,s.preferWorkers=null!=o?o:s.preferWorkers))})}(t.settings.resolveURL(i),r)));if(n.catch(et),yield i(),!t.internalModel)throw new TypeError("Missing internal model.");s.internalModel=t.internalModel,s.emit("modelLoaded",t.internalModel),s.textures=yield n,s.emit("textureLoaded",s.textures)}}),lt=(t,e)=>c(null,null,function*(){const i=t.settings;if(i instanceof _){const s=ct.findRuntime(i);if(!s)throw new TypeError("Unknown model settings.");const r=yield z.load({settings:i,url:i.moc,type:"arraybuffer",target:t.live2dModel});if(!s.isValidMoc(r))throw new Error("Invalid moc data");const n=s.createCoreModel(r);return t.internalModel=s.createInternalModel(n,i,t.options),e()}throw new TypeError("Missing settings.")}),ht=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(E(i.url,t)),n=e.find(t=>t.webkitRelativePath===r);n&&(s[t]=URL.createObjectURL(n))}t.filesMap[i._objectURL]=s}static createSettings(e){return c(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 n=ct.findRuntime(r);if(!n)throw new Error("Unknown settings JSON");const o=n.createModelSettings(r);return o._objectURL=URL.createObjectURL(i),o})}static readText(t){return c(this,null,function*(){return new Promise((e,i)=>{const s=new FileReader;s.onload=()=>e(s.result),s.onerror=i,s.readAsText(t,"utf8")})})}};u(ht,"live2dFactory"),u(ht,"filesMap",{}),u(ht,"factory",(t,e)=>c(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 ht.createSettings(e);i.validateFiles(e.map(t=>encodeURI(t.webkitRelativePath))),ht.upload(e,i),i.resolveURL=function(t){return ht.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),ht.filesMap[t])for(const e of Object.values(ht.filesMap[t]))URL.revokeObjectURL(e);delete ht.filesMap[t]})})}return e()}));let dt=ht;const ut=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 c(this,null,function*(){const r=new Promise(t=>e.once("textureLoaded",t)),n=new Promise(t=>e.once("modelLoaded",t)),o=Promise.all([r,n]).then(()=>e.emit("ready"));yield q(t.live2DModelMiddlewares,{live2dModel:e,source:i,options:s||{}}),yield o,e.emit("load")})}static loadMotion(e,i,s){var r;const n=t=>e.emit("motionLoadError",i,s,t);try{const o=null==(r=e.definitions[i])?void 0:r[s];if(!o)return Promise.resolve(void 0);e.once("destroy",()=>t.releaseMotionTasks(e));let a=t.motionTasksMap.get(e);a||(a={},t.motionTasksMap.set(e,a));let l=a[i];l||(l=[],a[i]=l);const h=e.getMotionFile(o);return null!=l[s]||(l[s]=z.load({url:h,settings:e.settings,type:e.motionDataType,target:e}).then(r=>{var n;const a=null==(n=t.motionTasksMap.get(e))?void 0:n[i];a&&(a[s]=void 0);const l=r,h=e.createMotion(l,i,o);return e.emit("motionLoaded",i,s,h),h}).catch(t=>{g.warn(e.tag,`Failed to load motion: ${h}\n`,t),n(t)})),l[s]}catch(o){g.warn(e.tag,`Failed to load motion at "${i}"[${s}]\n`,o),n(o)}return Promise.resolve(void 0)}static loadExpression(e,i){var s;const r=t=>e.emit("expressionLoadError",i,t);try{const n=e.definitions[i];if(!n)return Promise.resolve(void 0);e.once("destroy",()=>t.releaseExpressionTasks(e));let o=t.expressionTasksMap.get(e);o||(o=[],t.expressionTasksMap.set(e,o));const a=e.getExpressionFile(n),l=null!=(s=e.expressionDataType)?s:"json";return null!=o[i]||(o[i]=z.load({url:a,settings:e.settings,type:l,target:e}).then(s=>{const r=t.expressionTasksMap.get(e);r&&(r[i]=void 0);const o=s,a=e.createExpression(o,n);return e.emit("expressionLoaded",i,a),a}).catch(t=>{g.warn(e.tag,`Failed to load expression: ${a}\n`,t),r(t)})),o[i]}catch(n){g.warn(e.tag,`Failed to load expression at [${i}]\n`,n),r(n)}return Promise.resolve(void 0)}static releaseMotionTasks(e){t.motionTasksMap.delete(e)}static releaseExpressionTasks(e){t.expressionTasksMap.delete(e)}};u(ut,"runtimes",[]),u(ut,"urlToJSON",st),u(ut,"jsonToSettings",rt),u(ut,"waitUntilReady",nt),u(ut,"setupOptionals",ot),u(ut,"setupEssentials",at),u(ut,"createInternalModel",lt),u(ut,"live2DModelMiddlewares",[dt.factory,st,rt,nt,ot,at,lt]),u(ut,"motionTasksMap",new WeakMap),u(ut,"expressionTasksMap",new WeakMap);let ct=ut;U.prototype._loadMotion=function(t,e){return ct.loadMotion(this,t,e)},w.prototype._loadExpression=function(t){return ct.loadExpression(this,t)},dt.live2dFactory=ct;const pt=class t{constructor(i,{autoUpdate:s=!0,autoHitTest:r=!0,autoFocus:n=!0,autoInteract:o,ticker:a}={}){var l;u(this,"model"),u(this,"destroyed",!1),u(this,"_ticker"),u(this,"_autoUpdate",!1),u(this,"_autoHitTest",!1),u(this,"_autoFocus",!1),null!=a||(a=null!=(l=t.defaultTicker)?l:"undefined"!=typeof PIXI?PIXI.Ticker.shared:e.Ticker.shared),void 0!==o&&(r=o,n=o,g.warn(i.tag,"options.autoInteract is deprecated since v0.5.0, use autoHitTest and autoFocus instead.")),this.model=i,this.ticker=a,this.autoUpdate=s,this.autoHitTest=r,this.autoFocus=n,(r||n)&&(this.model.eventMode="static")}get ticker(){return this._ticker}set ticker(t){var e,i;this._ticker&&this._ticker.remove(mt,this),this._ticker=t,this._autoUpdate&&(null==(e=this._ticker)||e.add(mt,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(mt,this),this._autoUpdate=!0):g.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(mt,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",Mt,this),this.model.on("pointermove",Mt,this)):(this.model.off("globalpointermove",Mt,this),this.model.off("pointermove",Mt,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}};u(pt,"defaultTicker");let gt=pt;function mt(){this.onTickerUpdate()}function ft(t){this.onTap(t)}function Mt(t){this.onPointerMove(t)}class yt extends e.Transform{}const xt=new e.Point,vt=new e.Matrix,bt=new e.Matrix,Et={x:0,y:0,width:0,height:0},wt=new e.Bounds;let Pt=!1;class Lt{constructor(t){this.renderer=t}addPrepare(t,e){var i,s;null==(s=null==(i=this.renderer.renderPipes.batch)?void 0:i.break)||s.call(i,e),e.add({renderPipeId:"live2d",action:"prepare",canBundle:!1,prepare: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){if(!(t instanceof _t))return void t.prepare();const e=t;!e.visible||e.alpha<=0||e.renderLive2D(this.renderer)}updateRenderable(){}destroyRenderable(){}validateRenderable(){return!1}destroy(){}}u(Lt,"extension",{type:[e.ExtensionType.WebGLPipes],name:"live2d"});const It=Lt;class _t extends e.Container{constructor(t){var i;super(),u(this,"renderPipeId","live2d"),u(this,"tag","Live2DModel(uninitialized)"),u(this,"internalModel"),u(this,"textures",[]),u(this,"textureOptions"),u(this,"anchorMode"),u(this,"textureLODStates",[]),u(this,"textureLODFailures",[]),u(this,"transform",new yt),u(this,"anchor"),u(this,"_bounds",new e.Bounds),u(this,"_boundsDirty",!0),u(this,"_boundsRetryAfterDraw",!1),u(this,"gl",null),u(this,"elapsedTime",0),u(this,"deltaTime",0),u(this,"automator"),u(this,"currentGlId",0),u(this,"renderLive2D",t=>{var i,s,r,n,o;if(!(t instanceof e.WebGLRenderer))throw new Error("Renderer is not supported");t.geometry.resetState(),t.shader.resetState(),t.texture.resetState();let a=!1;this.gl!==t.gl&&(this.gl=t.gl,this.internalModel.updateWebGLContext(t.gl,this.generateUID()),a=!0);const{projectionMatrix:l,offset:h,worldTransformMatrix:d}=t.globalUniforms.globalUniformData,u=bt.copyFrom(d).append(this.groupTransform),c=(p=u,Math.max(Math.hypot(p.a,p.b),Math.hypot(p.c,p.d))*t.resolution);var p;for(let e=0;e<this.textures.length;e++){const i=this.textures[e];let s=this.resolveTextureForRender(e,i,c);try{this.uploadTextureForRender(t,s,a)}catch(b){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,a)}this.internalModel.bindTexture(e,t.texture.getGlSource(s.source).texture)}const g=t.renderTarget.viewport,m=t.renderTarget.renderTarget;let f=g.y;if(null==m?void 0:m.isRoot){f=m.colorTexture.source.pixelHeight-g.height-g.y}this.internalModel.viewport=[g.x,f,g.width,g.height];const M=this.deltaTime;this.deltaTime=0,M&&this.internalModel.update(M,this.elapsedTime),u.tx-=null!=(i=null==h?void 0:h.x)?i:0,u.ty-=null!=(s=null==h?void 0:h.y)?s:0;const y=vt.copyFrom(l).append(u);this.internalModel.updateTransform(y),this.internalModel.draw(t.gl),this._boundsRetryAfterDraw&&this.updateDrawableBounds(!0),t.state.resetState(),t.texture.resetState();const x=null==(r=t.renderTarget)?void 0:r.defaultClearColor,v=null==(o=null==(n=t.renderTarget)?void 0:n.adaptor)?void 0:o._clearColorCache;x&&(t.gl.clearColor(x[0],x[1],x[2],x[3]),v&&(v[0]=x[0],v[1]=x[1],v[2]=x[2],v[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 gt(this,t),this.once("modelLoaded",()=>this.initializeOnModelLoad(t))}get isRenderable(){return!0}get canBundle(){return!1}static from(t,e){return c(this,null,function*(){const i=new this(e);return yield ct.setupLive2DModel(i,t,e),i})}static fromSync(t,e){const i=new this(e);return ct.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){gt.defaultTicker=t.shared}get bounds(){return this.internalModel?(this._boundsDirty&&this.updateDrawableBounds(),this._bounds):(this._bounds.set(0,0,0,0),this._bounds)}updateDrawableBounds(t=!1){if(!this.internalModel)return this._bounds.set(0,0,0,0),void(this._boundsDirty=!1);const i=this.internalModel.getDrawableIDs();wt.clear();for(let s=0;s<i.length;s++){const t=i[s],r=this.internalModel.getDrawableIndex(t);if(r<0)continue;const n=this.internalModel.getDrawableBounds(r,Et);Number.isFinite(n.x)&&Number.isFinite(n.y)&&Number.isFinite(n.width)&&Number.isFinite(n.height)&&wt.addFrame(n.x,n.y,n.x+n.width,n.y+n.height,e.Matrix.IDENTITY)}if(this._bounds.clear(),wt.isValid&&wt.isPositive)this._bounds.addFrame(wt.minX,wt.minY,wt.maxX,wt.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++,t&&"drawable"===this.anchorMode&&this.onAnchorChange()}prepareForRender(){if(!this.internalModel)return;const t=this.deltaTime;this.deltaTime=0,t&&this.internalModel.update(t,this.elapsedTime),this.updateDrawableBounds()}generateUID(){return++this.currentGlId}collectRenderables(t,e,i){var s,r,n,o;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||(Pt||(Pt=!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 Lt(t))}(e);const a=e.renderPipes,l=()=>{a.live2d.addRenderable(this,t)},h=()=>{const s=this.children,r=s.length;for(let n=0;n<r;n++)s[n].collectRenderables(t,e,i)},d=this.effects;if(d){d.length&&a.live2d.addPrepare(()=>this.prepareForRender(),t);for(let e=0;e<d.length;e++){const i=d[e],n=i.filters;if(n)for(const t of n)t&&"number"==typeof t.resolution&&1===t.resolution&&(t.resolution="inherit");null==(r=null==(s=a[i.pipe])?void 0:s.push)||r.call(s,i,this,t)}l(),h();for(let e=d.length-1;e>=0;e--){const i=d[e];null==(o=null==(n=a[i.pipe])?void 0:n.pop)||o.call(n,i,this,t)}}else l(),h()}initializeOnModelLoad(t){this.tag=`Live2DModel(${this.internalModel.settings.name})`,this.updateDrawableBounds(!0),"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 c(this,arguments,function*(t,e,i,{sound:s,volume:r=.5,expression:n,resetExpression:o=!0,onFinish:a,onError:l,loop:h}={}){return void 0===e?this.internalModel.motionManager.startRandomMotion(t,i,{sound:s,volume:r,expression:n,resetExpression:o,onFinish:a,onError:l,loop:h}):this.internalModel.motionManager.startMotion(t,e,i,{sound:s,volume:r,expression:n,resetExpression:o,onFinish:a,onError:l,loop:h})})}motionLastFrame(t,e){return c(this,arguments,function*(t,e,{expression:i}={}){return this.internalModel.motionManager.motionLastFrame(t,e,{expression:i})})}parallelMotion(t){return c(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 c(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:n}={}){return this.internalModel.motionManager.speak(t,{volume:e,expression:i,resetExpression:s,onFinish:r,onError:n})}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){xt.x=t,xt.y=e,this.toModelPosition(xt,xt,!0);const s=xt.x/this.internalModel.originalWidth*2-1,r=xt.y/this.internalModel.originalHeight*2-1,n=Math.atan2(r,s);this.internalModel.focusController.focus(Math.cos(n),-Math.sin(n),i)}tap(t,e){const i=this.hitTest(t,e);i.length&&this.emit("hit",i)}hitTest(t,e){return xt.x=t,xt.y=e,this.toModelPosition(xt,xt),this.internalModel.hitTest(xt.x,xt.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,n){var o;const a=Z((l=d({},this.textureOptions),h={effectiveScale:n,textureWidth:i.source.pixelWidth,textureHeight:i.source.pixelHeight},s(l,r(h))));var l,h;if(!a)return i;const u=this.textureLODFailures[t];if((null==u?void 0:u.source)===i&&u.levels.has(a.level))return i;const c=this.textureLODStates[t];if((null==c?void 0:c.source)===i&&c.level===a.level&&!c.texture.destroyed)return c.texture;this.destroyTextureLODState(t);const p=function(t,i,s,r,n){var o,a;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 h=e.DOMAdapter.get().createCanvas(s,r),d=h.getContext("2d");if(!d)return;try{d.clearRect(0,0,s,r),d.imageSmoothingEnabled="nearest"!==n,"imageSmoothingQuality"in d&&"nearest"!==n&&(d.imageSmoothingQuality="high"),d.drawImage(l,0,0,t.source.pixelWidth,t.source.pixelHeight,0,0,s,r)}catch(c){return}const u=`${null!=(a=null!=(o=t.label)?o:t.source.label)?a:"Live2DTexture"} LOD ${i}`;return new e.Texture({label:u,source:new e.CanvasSource({resource:h,width:s,height:r,resolution:1,scaleMode:K(n),autoGenerateMipmaps:!1,label:u})})}(i,a.level,a.width,a.height,null==(o=this.textureOptions)?void 0:o.lodFilter);return p?(this.textureLODStates[t]={source:i,level:a.level,texture:p},p):(this.markTextureLODFailure(t,i,a.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 Ft=Live2DMotion.prototype.updateParam;Live2DMotion.prototype.updateParam=function(t,e){Ft.call(this,t,e),e.isFinished()&&this.onFinishHandler&&(this.onFinishHandler(this),delete this.onFinishHandler)};class At extends AMotion{constructor(t){super(),u(this,"params",[]),this.setFadeIn(t.fade_in>0?t.fade_in:p.expressionFadingDuration),this.setFadeOut(t.fade_out>0?t.fade_out:p.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 Dt extends w{constructor(t,e){var i;super(t,e),u(this,"queueManager",new MotionQueueManager),u(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 At(t)}_setExpression(t){return this.queueManager.startMotion(t)}stopAllExpressions(){this.queueManager.stopAllMotions()}updateParameters(t,e){return this.queueManager.updateParam(t)}}function Ot(t,e,i){const s=i.getDurationMSec(),r=t.startMotion(i,!0),n=t.motions.find(t=>!!t&&t._$sr===r);return!!n&&(i.updateParamExe(e.coreModel,s,1,n),!0)}class Tt extends U{constructor(t){super(t),u(this,"definitions"),u(this,"groups",{idle:"idle"}),u(this,"motionDataType","arraybuffer"),u(this,"queueManager",new MotionQueueManager),u(this,"lipSyncIds"),u(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 Dt(this.settings,t))}isFinished(){return this.queueManager.isFinished()}createMotion(t,e,i){const s=Live2DMotion.loadMotion(t),r=e===this.groups.idle?p.idleMotionFadingDuration:p.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 c(this,arguments,function*(t,e,{expression:i}={}){const s=yield this.getMotionAndApplyExpression(t,e,i);return!!s&&(this.playing=!0,Ot(this.queueManager,this.parent,s),this.playing=!1,!0)})}}class St extends e.EventEmitter{constructor(t){super(),u(this,"tag"),u(this,"manager"),u(this,"settings"),u(this,"state",new A),u(this,"playing",!1),u(this,"destroyed",!1),u(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 c(this,arguments,function*(t,e,i=F.NORMAL,s={}){var r;const{ignoreParamIds:n=[],loop:o}=Array.isArray(s)?{ignoreParamIds:s,loop:void 0}:s;if(!this.state.reserve(t,e,i))return!1;const a=null==(r=this.manager.definitions[t])?void 0:r[e];if(!a)return!1;const l=yield this.manager.loadMotion(t,e);return!!this.state.start(l,t,e,i)&&(g.log(this.tag,"Start motion:",this.getMotionName(a)),this.emit("motionStart",t,e,void 0),this.playing=!0,this._startMotion(l,void 0,n,o),!0)})}startRandomMotion(t,e){return c(this,arguments,function*(t,e,{loop:i}={}){var s;const r=this.manager.definitions[t];if(null==r?void 0:r.length){const n=[],o=null!=(s=this.manager.motionGroups[t])?s:[];for(let e=0;e<r.length;e++)null===o[e]||this.state.isActive(t,e)||n.push(e);if(n.length){const s=n[Math.floor(Math.random()*n.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 Rt extends St{constructor(t){super(t),u(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 c(this,null,function*(){var i;if(!this.state.reserve(t,e,F.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,F.FORCE)&&(g.log(this.tag,"Start motion:",this.getMotionName(s)),this.queueManager.stopAllMotions(),this.emit("motionStart",t,e,void 0),this.playing=!0,!!Ot(this.queueManager,this.parent,r)&&(this.playing=!1,!0))})}}class Ct{constructor(t){u(this,"leftParam"),u(this,"rightParam"),u(this,"blinkInterval",4e3),u(this,"closingDuration",100),u(this,"closedDuration",50),u(this,"openingDuration",150),u(this,"eyeState",0),u(this,"eyeParamValue",1),u(this,"closedTimer",0),u(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+f(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 kt=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);class Nt extends ${constructor(t,e,i){super(),u(this,"settings"),u(this,"options"),u(this,"coreModel"),u(this,"motionManager"),u(this,"parallelMotionManager"),u(this,"eyeBlink"),u(this,"eyeballXParamIndex"),u(this,"eyeballYParamIndex"),u(this,"angleXParamIndex"),u(this,"angleYParamIndex"),u(this,"angleZParamIndex"),u(this,"bodyAngleXParamIndex"),u(this,"breathParamIndex"),u(this,"textureFlipY",!0),u(this,"lipSync",!0),u(this,"drawDataCount",0),u(this,"disableCulling",!1),u(this,"hasDrawn",!1),u(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&&g.warn("CubismLegacyInternalModel","`useHighPrecisionMask` is only supported by Cubism 3/4/5 models and will be ignored for Cubism 2 models."),this.motionManager=new Tt(this),this.parallelMotionManager=[],!1!==this.options.eyeBlink&&(this.eyeBlink=new Ct(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 X(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||g.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,n;super.update(t,e);const o=this.coreModel,a=this.updateMotions(o,e);if(o.saveParam(),null==(i=this.motionManager.expressionManager)||i.update(o,e),a||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==(n=this.pose)||n.update(t),this.emit("beforeModelUpdate"),o.update(),o.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;kt[0]=i.a,kt[1]=i.b,kt[4]=i.c,kt[5]=i.d,kt[12]=i.tx,kt[13]=i.ty,this.coreModel.setMatrix(kt),this.coreModel.draw(),this.hasDrawn=!0,this.disableCulling=e}extendParallelMotionManager(t){for(;this.parallelMotionManager.length<t;)this.parallelMotionManager.push(new Rt(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 n=t/s*2-1,o=1-e/r*2,a=[];for(const[l,h]of Object.entries(i))n>=h.minX&&n<=h.maxX&&o>=h.minY&&o<=h.maxY&&a.push(l);return a}getCustomHitAreas(){var t,e,i,s,r;if(void 0!==this.customHitAreas)return this.customHitAreas;const n=this.settings.json,o=null!=(i=null!=(e=null!=(t=n.hit_areas_custom)?t:n.hitAreasCustom)?e:n.HitAreasCustom)?i:n.HitAreas_Custom;if(!o||"object"!=typeof o)return this.customHitAreas=null,null;const a=o,l={},h=(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]),n=Number(i[0]),o=Number(i[1]);Number.isFinite(s)&&Number.isFinite(r)&&Number.isFinite(n)&&Number.isFinite(o)&&(l[t]={minX:Math.min(s,r),maxX:Math.max(s,r),minY:Math.min(n,o),maxY:Math.max(n,o)})};for(const[d,u]of Object.entries(a)){if(d.endsWith("_x")){const t=d.slice(0,-2);h(t,u,a[`${t}_y`]);continue}if(!d.endsWith("_y")&&(u&&"object"==typeof u)){const t=u;h(d,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 Gt={x:PhysicsHair.Src.SRC_TO_X,y:PhysicsHair.Src.SRC_TO_Y,angle:PhysicsHair.Src.SRC_TO_G_ANGLE},jt={x:PhysicsHair.Src.SRC_TO_X,y:PhysicsHair.Src.SRC_TO_Y,angle:PhysicsHair.Src.SRC_TO_G_ANGLE};class Ht{constructor(t,e){u(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 n=Gt[i];n&&e.addSrcParam(n,t,s,r)}),t.targets.forEach(({id:t,ptype:i,scale:s,weight:r})=>{const n=jt[i];n&&e.addTargetParam(n,t,s,r)}),e}))}update(t){this.physicsHairs.forEach(e=>e.update(this.coreModel,t))}}class Ut{constructor(t){u(this,"paramIndex",-1),u(this,"partsIndex",-1),u(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 Xt{constructor(t,e){u(this,"opacityAnimDuration",500),u(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 Ut(t);return e&&(i.link=e.map(t=>new Ut(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,n=t.findIndex(({paramIndex:t,partsIndex:e})=>e>=0&&0!==i.getParamFloat(t));if(n>=0){const s=i.getPartsOpacity(t[n].partsIndex);r=m(s+e/this.opacityAnimDuration,0,1)}else n=0,r=1;t.forEach(({partsIndex:t},e)=>{if(t>=0)if(n==e)i.setPartsOpacity(t,r);else{let e,n=i.getPartsOpacity(t);e=r<s?-.5*r/s+1:(1-r)*s/.5;(1-e)*(1-r)>.15&&(e=1-.15/(1-r)),n>e&&(n=e),i.setPartsOpacity(t,n)}})}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)})}}ct.registerRuntime({version:2,test:t=>t instanceof J||J.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 J(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 Nt(t,e,i),createPose:(t,e)=>new Xt(t,e),createPhysics:(t,e)=>new Ht(t,e)}),t.CubismLegacyExpressionManager=Dt,t.CubismLegacyInternalModel=Nt,t.CubismLegacyModelSettings=J,t.CubismLegacyMotionManager=Tt,t.CubismLegacyParallelMotionManager=Rt,t.ExpressionManager=w,t.FileLoader=dt,t.FocusController=I,t.InternalModel=$,t.LOGICAL_HEIGHT=2,t.LOGICAL_WIDTH=2,t.Live2DExpression=At,t.Live2DEyeBlink=Ct,t.Live2DFactory=ct,t.Live2DLoader=z,t.Live2DModel=_t,t.Live2DPhysics=Ht,t.Live2DPlugin=It,t.Live2DPose=Xt,t.Live2DTransform=yt,t.MBToByte=function(t){return 1024*t*1024},t.ModelSettings=_,t.MotionManager=U,t.MotionPreloadStrategy=H,t.MotionPriority=F,t.MotionState=A,t.SoundManager=j,t.VERSION="1.3.5",t.VOLUME=O,t.XHRLoader=V,t.applyMixins=function(t,e){e.forEach(e=>{Object.getOwnPropertyNames(e.prototype).forEach(i=>{"constructor"!==i&&Object.defineProperty(t.prototype,i,Object.getOwnPropertyDescriptor(e.prototype,i))})})},t.clamp=m,t.config=p,t.copyArray=y,t.copyProperty=M,t.folderName=x,t.logger=g,t.normalizeHitAreaDefs=X,t.rand=f,t.remove=v,t.resolveURL=E,Object.defineProperty(t,Symbol.toStringTag,{value:"Module"})});
package/dist/cubism.es.js CHANGED
@@ -2759,7 +2759,7 @@ const config = {
2759
2759
  preserveExpressionOnMotion: true,
2760
2760
  cubism: CubismFrameworkConfig
2761
2761
  };
2762
- const VERSION = "1.3.3";
2762
+ const VERSION = "1.3.5";
2763
2763
  const logger = {
2764
2764
  log(tag, ...messages) {
2765
2765
  if (config.logLevel <= config.LOG_LEVEL_VERBOSE) {
@@ -5508,13 +5508,29 @@ class Live2DPipe {
5508
5508
  constructor(renderer) {
5509
5509
  this.renderer = renderer;
5510
5510
  }
5511
+ addPrepare(prepare, instructionSet) {
5512
+ var _a, _b;
5513
+ const renderPipes = this.renderer.renderPipes;
5514
+ (_b = (_a = renderPipes.batch) == null ? void 0 : _a.break) == null ? void 0 : _b.call(_a, instructionSet);
5515
+ instructionSet.add({
5516
+ renderPipeId: "live2d",
5517
+ action: "prepare",
5518
+ canBundle: false,
5519
+ prepare
5520
+ });
5521
+ }
5511
5522
  addRenderable(model, instructionSet) {
5512
5523
  var _a, _b;
5513
5524
  const renderPipes = this.renderer.renderPipes;
5514
5525
  (_b = (_a = renderPipes.batch) == null ? void 0 : _a.break) == null ? void 0 : _b.call(_a, instructionSet);
5515
5526
  instructionSet.add(model);
5516
5527
  }
5517
- execute(model) {
5528
+ execute(instruction) {
5529
+ if (!(instruction instanceof Live2DModel)) {
5530
+ instruction.prepare();
5531
+ return;
5532
+ }
5533
+ const model = instruction;
5518
5534
  if (!model.visible || model.alpha <= 0) {
5519
5535
  return;
5520
5536
  }
@@ -5727,7 +5743,7 @@ class Live2DModel extends Container {
5727
5743
  this.internalModel.updateTransform(internalTransform);
5728
5744
  this.internalModel.draw(renderer.gl);
5729
5745
  if (this._boundsRetryAfterDraw) {
5730
- this.updateDrawableBounds();
5746
+ this.updateDrawableBounds(true);
5731
5747
  }
5732
5748
  renderer.state.resetState();
5733
5749
  renderer.texture.resetState();
@@ -5829,7 +5845,7 @@ class Live2DModel extends Container {
5829
5845
  }
5830
5846
  return this._bounds;
5831
5847
  }
5832
- updateDrawableBounds() {
5848
+ updateDrawableBounds(applyAnchor = false) {
5833
5849
  if (!this.internalModel) {
5834
5850
  this._bounds.set(0, 0, 0, 0);
5835
5851
  this._boundsDirty = false;
@@ -5873,10 +5889,26 @@ class Live2DModel extends Container {
5873
5889
  }
5874
5890
  this._boundsDirty = false;
5875
5891
  this._didViewChangeTick++;
5876
- if (this.anchorMode === "drawable") {
5892
+ if (applyAnchor && this.anchorMode === "drawable") {
5877
5893
  this.onAnchorChange();
5878
5894
  }
5879
5895
  }
5896
+ /**
5897
+ * Updates the model and its drawable bounds before Pixi calculates filter areas.
5898
+ * Filter pipes collect their framebuffer bounds before the Live2D render pipe runs,
5899
+ * so waiting until `renderLive2D()` is too late for animated vertices.
5900
+ */
5901
+ prepareForRender() {
5902
+ if (!this.internalModel) {
5903
+ return;
5904
+ }
5905
+ const frameDelta = this.deltaTime;
5906
+ this.deltaTime = 0;
5907
+ if (frameDelta) {
5908
+ this.internalModel.update(frameDelta, this.elapsedTime);
5909
+ }
5910
+ this.updateDrawableBounds();
5911
+ }
5880
5912
  generateUID() {
5881
5913
  return ++this.currentGlId;
5882
5914
  }
@@ -5911,6 +5943,9 @@ class Live2DModel extends Container {
5911
5943
  };
5912
5944
  const effects = this.effects;
5913
5945
  if (effects) {
5946
+ if (effects.length) {
5947
+ renderPipes.live2d.addPrepare(() => this.prepareForRender(), instructionSet);
5948
+ }
5914
5949
  for (let i = 0; i < effects.length; i++) {
5915
5950
  const effect = effects[i];
5916
5951
  const filters = effect.filters;
@@ -5941,7 +5976,7 @@ class Live2DModel extends Container {
5941
5976
  */
5942
5977
  initializeOnModelLoad(_options) {
5943
5978
  this.tag = `Live2DModel(${this.internalModel.settings.name})`;
5944
- this.updateDrawableBounds();
5979
+ this.updateDrawableBounds(true);
5945
5980
  if (this.anchorMode === "canvas") {
5946
5981
  this.onAnchorChange();
5947
5982
  }